first commit
Security: Sync from Public / sync-from-public (push) Has been cancelled
Test: Benchmark Nightly / build (push) Has been cancelled
Test: Benchmark Nightly / Notify Cats on failure (push) Has been cancelled
CI: Python / Checks (push) Has been cancelled
Test: Evals Python / Workflow Comparison Python (push) Has been cancelled
Util: Check Docs URLs / check-docs-urls (push) Has been cancelled
Test: Visual Storybook / Cloudflare Pages (push) Has been cancelled
Test: E2E Performance / build-and-test-performance (push) Has been cancelled
Test: Workflows Nightly / Run Workflow Tests (push) Has been cancelled
Util: Cleanup CI Docker Images / Delete stale CI images (push) Has been cancelled
Test: Benchmark Destroy Env / build (push) Has been cancelled
Util: Update Node Popularity / update-popularity (push) Has been cancelled
Test: E2E Coverage Weekly / Coverage Tests (push) Has been cancelled

This commit is contained in:
2026-03-17 16:22:57 +03:30
commit 3d5eaf9445
15349 changed files with 2847338 additions and 0 deletions
@@ -0,0 +1,399 @@
import { ChatAnthropic } from '@langchain/anthropic';
import type { LLMResult } from '@langchain/core/outputs';
import {
getProxyAgent,
makeN8nLlmFailedAttemptHandler,
N8nLlmTracing,
getConnectionHintNoticeField,
} from '@n8n/ai-utilities';
import {
NodeConnectionTypes,
NodeOperationError,
type INodeProperties,
type INodePropertyOptions,
type INodeType,
type INodeTypeDescription,
type ISupplyDataFunctions,
type SupplyData,
} from 'n8n-workflow';
import { searchModels } from './methods/searchModels';
const modelField: INodeProperties = {
displayName: 'Model',
name: 'model',
type: 'options',
// eslint-disable-next-line n8n-nodes-base/node-param-options-type-unsorted-items
options: [
{
name: 'Claude 3.5 Sonnet(20241022)',
value: 'claude-3-5-sonnet-20241022',
},
{
name: 'Claude 3 Opus(20240229)',
value: 'claude-3-opus-20240229',
},
{
name: 'Claude 3.5 Sonnet(20240620)',
value: 'claude-3-5-sonnet-20240620',
},
{
name: 'Claude 3 Sonnet(20240229)',
value: 'claude-3-sonnet-20240229',
},
{
name: 'Claude 3.5 Haiku(20241022)',
value: 'claude-3-5-haiku-20241022',
},
{
name: 'Claude 3 Haiku(20240307)',
value: 'claude-3-haiku-20240307',
},
{
name: 'LEGACY: Claude 2',
value: 'claude-2',
},
{
name: 'LEGACY: Claude 2.1',
value: 'claude-2.1',
},
{
name: 'LEGACY: Claude Instant 1.2',
value: 'claude-instant-1.2',
},
{
name: 'LEGACY: Claude Instant 1',
value: 'claude-instant-1',
},
],
description:
'The model which will generate the completion. <a href="https://docs.anthropic.com/claude/docs/models-overview">Learn more</a>.',
default: 'claude-2',
};
const MIN_THINKING_BUDGET = 1024;
const DEFAULT_MAX_TOKENS = 4096;
export class LmChatAnthropic implements INodeType {
methods = {
listSearch: {
searchModels,
},
};
description: INodeTypeDescription = {
displayName: 'Anthropic Chat Model',
name: 'lmChatAnthropic',
icon: 'file:anthropic.svg',
group: ['transform'],
version: [1, 1.1, 1.2, 1.3],
defaultVersion: 1.3,
description: 'Language Model Anthropic',
defaults: {
name: 'Anthropic Chat Model',
},
codex: {
categories: ['AI'],
subcategories: {
AI: ['Language Models', 'Root Nodes'],
'Language Models': ['Chat Models (Recommended)'],
},
resources: {
primaryDocumentation: [
{
url: 'https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.lmchatanthropic/',
},
],
},
alias: ['claude', 'sonnet', 'opus'],
},
inputs: [],
outputs: [NodeConnectionTypes.AiLanguageModel],
outputNames: ['Model'],
credentials: [
{
name: 'anthropicApi',
required: true,
},
],
properties: [
getConnectionHintNoticeField([NodeConnectionTypes.AiChain, NodeConnectionTypes.AiChain]),
{
...modelField,
displayOptions: {
show: {
'@version': [1],
},
},
},
{
...modelField,
default: 'claude-3-sonnet-20240229',
displayOptions: {
show: {
'@version': [1.1],
},
},
},
{
...modelField,
default: 'claude-3-5-sonnet-20240620',
options: (modelField.options ?? []).filter(
(o): o is INodePropertyOptions => 'name' in o && !o.name.toString().startsWith('LEGACY'),
),
displayOptions: {
show: {
'@version': [{ _cnd: { lte: 1.2 } }],
},
},
},
{
displayName: 'Model',
name: 'model',
type: 'resourceLocator',
default: {
mode: 'list',
value: 'claude-sonnet-4-5-20250929',
cachedResultName: 'Claude Sonnet 4.5',
},
required: true,
modes: [
{
displayName: 'From List',
name: 'list',
type: 'list',
placeholder: 'Select a model...',
typeOptions: {
searchListMethod: 'searchModels',
searchable: true,
},
},
{
displayName: 'ID',
name: 'id',
type: 'string',
placeholder: 'Claude Sonnet',
},
],
description:
'The model. Choose from the list, or specify an ID. <a href="https://docs.anthropic.com/claude/docs/models-overview">Learn more</a>.',
displayOptions: {
show: {
'@version': [{ _cnd: { gte: 1.3 } }],
},
},
},
{
displayName: 'Options',
name: 'options',
placeholder: 'Add Option',
description: 'Additional options to add',
type: 'collection',
default: {},
options: [
{
displayName: 'Maximum Number of Tokens',
name: 'maxTokensToSample',
default: DEFAULT_MAX_TOKENS,
description: 'The maximum number of tokens to generate in the completion',
type: 'number',
},
{
displayName: 'Sampling Temperature',
name: 'temperature',
default: 0.7,
typeOptions: { maxValue: 1, minValue: 0, numberPrecision: 1 },
description:
'Controls randomness: Lowering results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive.',
type: 'number',
displayOptions: {
hide: {
thinking: [true],
},
},
},
{
displayName: 'Top K',
name: 'topK',
default: -1,
typeOptions: { maxValue: 1, minValue: -1, numberPrecision: 1 },
description:
'Used to remove "long tail" low probability responses. Defaults to -1, which disables it.',
type: 'number',
displayOptions: {
hide: {
thinking: [true],
},
},
},
{
displayName: 'Top P',
name: 'topP',
default: 1,
typeOptions: { maxValue: 1, minValue: 0, numberPrecision: 1 },
description:
'Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options are considered. We generally recommend altering this or temperature but not both.',
type: 'number',
displayOptions: {
hide: {
thinking: [true],
},
},
},
{
displayName: 'Enable Thinking',
name: 'thinking',
type: 'boolean',
default: false,
description: 'Whether to enable thinking mode for the model',
},
{
displayName: 'Thinking Budget (Tokens)',
name: 'thinkingBudget',
type: 'number',
default: MIN_THINKING_BUDGET,
description: 'The maximum number of tokens to use for thinking',
displayOptions: {
show: {
thinking: [true],
},
},
},
],
},
],
};
async supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise<SupplyData> {
const credentials = await this.getCredentials<{
url?: string;
apiKey?: string;
header?: boolean;
headerName?: string;
headerValue?: string;
}>('anthropicApi');
const baseURL = credentials.url ?? 'https://api.anthropic.com';
const version = this.getNode().typeVersion;
const modelName =
version >= 1.3
? (this.getNodeParameter('model.value', itemIndex) as string)
: (this.getNodeParameter('model', itemIndex) as string);
if (!modelName) {
throw new NodeOperationError(this.getNode(), 'No model selected. Please choose a model.', {
itemIndex,
});
}
const options = this.getNodeParameter('options', itemIndex, {}) as {
maxTokensToSample?: number;
temperature: number;
topK?: number;
topP?: number;
thinking?: boolean;
thinkingBudget?: number;
};
let invocationKwargs = {};
const tokensUsageParser = (result: LLMResult) => {
const usage = (result?.llmOutput?.usage as {
input_tokens: number;
output_tokens: number;
}) ?? {
input_tokens: 0,
output_tokens: 0,
};
return {
completionTokens: usage.output_tokens,
promptTokens: usage.input_tokens,
totalTokens: usage.input_tokens + usage.output_tokens,
};
};
if (options.thinking) {
invocationKwargs = {
thinking: {
type: 'enabled',
// If thinking is enabled, we need to set a budget.
// We fallback to 1024 as that is the minimum
budget_tokens: options.thinkingBudget ?? MIN_THINKING_BUDGET,
},
// The default Langchain max_tokens is -1 (no limit) but Anthropic requires a number
// higher than budget_tokens
max_tokens: options.maxTokensToSample ?? DEFAULT_MAX_TOKENS,
// These need to be unset when thinking is enabled.
// Because the invocationKwargs will override the model options
// we can pass options to the model and then override them here
top_k: undefined,
top_p: undefined,
temperature: undefined,
};
}
const clientOptions: {
fetchOptions?: { dispatcher: ReturnType<typeof getProxyAgent> };
defaultHeaders?: Record<string, string>;
} = {
fetchOptions: {
dispatcher: getProxyAgent(baseURL),
},
};
if (
credentials.header &&
typeof credentials.headerName === 'string' &&
credentials.headerName &&
typeof credentials.headerValue === 'string'
) {
clientOptions.defaultHeaders = {
[credentials.headerName]: credentials.headerValue,
};
}
const isUsingGateway = baseURL !== 'https://api.anthropic.com';
const gatewayErrorHandler = isUsingGateway
? (error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
const isModelError =
/model.*not found|not found.*model|invalid model|does not exist/i.test(message);
if (isModelError) {
throw new NodeOperationError(
this.getNode(),
`The model "${modelName}" was not found at ${baseURL}. If you're using an AI gateway, select a model that your gateway supports.`,
{ itemIndex },
);
}
}
: undefined;
const model = new ChatAnthropic({
anthropicApiKey: credentials.apiKey,
model: modelName,
anthropicApiUrl: baseURL,
maxTokens: options.maxTokensToSample,
temperature: options.temperature,
topK: options.topK,
topP: options.topP,
callbacks: [new N8nLlmTracing(this, { tokensUsageParser })],
onFailedAttempt: makeN8nLlmFailedAttemptHandler(this, gatewayErrorHandler),
invocationKwargs,
clientOptions,
});
// Some Anthropic models do not support Langchain default of -1 for topP so we need to unset it
if (options.topP === undefined) {
delete model.topP;
}
// If topP is set to a value and temperature is not, unset default Langchain temperature
if (options.topP !== undefined && options.temperature === undefined) {
delete model.temperature;
}
return {
response: model,
};
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="46" height="32" fill="none"><path fill="#7D7D87" d="M32.73 0h-6.945L38.45 32h6.945zM12.665 0 0 32h7.082l2.59-6.72h13.25l2.59 6.72h7.082L19.929 0zm-.702 19.337 4.334-11.246 4.334 11.246z"/></svg>

After

Width:  |  Height:  |  Size: 241 B

@@ -0,0 +1,142 @@
import type { ILoadOptionsFunctions } from 'n8n-workflow';
import { searchModels, type AnthropicModel } from '../searchModels';
describe('searchModels', () => {
let mockContext: jest.Mocked<ILoadOptionsFunctions>;
const mockModels: AnthropicModel[] = [
{
id: 'claude-3-opus-20240229',
display_name: 'Claude 3 Opus',
type: 'model',
created_at: '2024-02-29T00:00:00Z',
},
{
id: 'claude-3-sonnet-20240229',
display_name: 'Claude 3 Sonnet',
type: 'model',
created_at: '2024-02-29T00:00:00Z',
},
{
id: 'claude-3-haiku-20240307',
display_name: 'Claude 3 Haiku',
type: 'model',
created_at: '2024-03-07T00:00:00Z',
},
{
id: 'claude-2.1',
display_name: 'Claude 2.1',
type: 'model',
created_at: '2023-11-21T00:00:00Z',
},
{
id: 'claude-2.0',
display_name: 'Claude 2.0',
type: 'model',
created_at: '2023-07-11T00:00:00Z',
},
];
beforeEach(() => {
mockContext = {
getCredentials: jest.fn().mockResolvedValue({}),
helpers: {
httpRequestWithAuthentication: jest.fn().mockResolvedValue({
data: mockModels,
}),
},
} as unknown as jest.Mocked<ILoadOptionsFunctions>;
});
afterEach(() => {
jest.clearAllMocks();
// Reset the getCredentials mock to its default value
mockContext.getCredentials = jest.fn().mockResolvedValue({});
});
it('should fetch models from default Anthropic API URL when no custom URL is provided', async () => {
const result = await searchModels.call(mockContext);
expect(mockContext.getCredentials).toHaveBeenCalledWith('anthropicApi');
expect(mockContext.helpers.httpRequestWithAuthentication).toHaveBeenCalledWith('anthropicApi', {
url: 'https://api.anthropic.com/v1/models',
headers: {
'anthropic-version': '2023-06-01',
},
});
expect(result.results).toHaveLength(5);
});
it('should fetch models from custom Anthropic API URL when provided in credentials', async () => {
const customUrl = 'https://custom-anthropic-api.example.com';
// Override the default mock to return credentials with a custom URL
mockContext.getCredentials = jest.fn().mockResolvedValue({ url: customUrl });
const result = await searchModels.call(mockContext);
expect(mockContext.getCredentials).toHaveBeenCalledWith('anthropicApi');
expect(mockContext.helpers.httpRequestWithAuthentication).toHaveBeenCalledWith('anthropicApi', {
url: `${customUrl}/v1/models`,
headers: {
'anthropic-version': '2023-06-01',
},
});
expect(result.results).toHaveLength(5);
});
it('should use default URL when empty URL is provided in credentials', async () => {
// Override the default mock to return credentials with an empty URL
mockContext.getCredentials = jest.fn().mockResolvedValue({ url: null });
const result = await searchModels.call(mockContext);
expect(mockContext.getCredentials).toHaveBeenCalledWith('anthropicApi');
expect(mockContext.helpers.httpRequestWithAuthentication).toHaveBeenCalledWith('anthropicApi', {
url: 'https://api.anthropic.com/v1/models',
headers: {
'anthropic-version': '2023-06-01',
},
});
expect(result.results).toHaveLength(5);
});
it('should sort models by created_at date, most recent first', async () => {
const result = await searchModels.call(mockContext);
const sortedResults = result.results;
expect(sortedResults[0].value).toBe('claude-3-haiku-20240307');
expect(sortedResults[1].value).toBe('claude-3-opus-20240229');
expect(sortedResults[2].value).toBe('claude-3-sonnet-20240229');
expect(sortedResults[3].value).toBe('claude-2.1');
expect(sortedResults[4].value).toBe('claude-2.0');
});
it('should filter models based on search term', async () => {
const result = await searchModels.call(mockContext, 'claude-3');
expect(result.results).toHaveLength(3);
expect(result.results).toEqual([
{ name: 'Claude 3 Haiku', value: 'claude-3-haiku-20240307' },
{ name: 'Claude 3 Opus', value: 'claude-3-opus-20240229' },
{ name: 'Claude 3 Sonnet', value: 'claude-3-sonnet-20240229' },
]);
});
it('should handle case-insensitive search', async () => {
const result = await searchModels.call(mockContext, 'CLAUDE-3');
expect(result.results).toHaveLength(3);
expect(result.results).toEqual([
{ name: 'Claude 3 Haiku', value: 'claude-3-haiku-20240307' },
{ name: 'Claude 3 Opus', value: 'claude-3-opus-20240229' },
{ name: 'Claude 3 Sonnet', value: 'claude-3-sonnet-20240229' },
]);
});
it('should handle when no models match the filter', async () => {
const result = await searchModels.call(mockContext, 'nonexistent-model');
expect(result.results).toHaveLength(0);
});
});
@@ -0,0 +1,63 @@
import type {
ILoadOptionsFunctions,
INodeListSearchItems,
INodeListSearchResult,
} from 'n8n-workflow';
export interface AnthropicModel {
id: string;
display_name: string;
type: string;
created_at: string;
}
export async function searchModels(
this: ILoadOptionsFunctions,
filter?: string,
): Promise<INodeListSearchResult> {
const credentials = await this.getCredentials<{ url?: string }>('anthropicApi');
const baseURL = credentials.url ?? 'https://api.anthropic.com';
const response = (await this.helpers.httpRequestWithAuthentication.call(this, 'anthropicApi', {
url: `${baseURL}/v1/models`,
headers: {
'anthropic-version': '2023-06-01',
},
})) as { data: AnthropicModel[] };
const models = response.data || [];
let results: INodeListSearchItems[] = [];
if (filter) {
for (const model of models) {
if (model.id.toLowerCase().includes(filter.toLowerCase())) {
results.push({
name: model.display_name,
value: model.id,
});
}
}
} else {
results = models.map((model) => ({
name: model.display_name,
value: model.id,
}));
}
// Sort models with more recent ones first (claude-3 before claude-2)
results = results.sort((a, b) => {
const modelA = models.find((m) => m.id === a.value);
const modelB = models.find((m) => m.id === b.value);
if (!modelA || !modelB) return 0;
// Sort by created_at date, most recent first
const dateA = new Date(modelA.created_at);
const dateB = new Date(modelB.created_at);
return dateB.getTime() - dateA.getTime();
});
return {
results,
};
}
@@ -0,0 +1,583 @@
/* eslint-disable n8n-nodes-base/node-filename-against-convention */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { ChatAnthropic } from '@langchain/anthropic';
import { makeN8nLlmFailedAttemptHandler, N8nLlmTracing, getProxyAgent } from '@n8n/ai-utilities';
import { createMockExecuteFunction } from 'n8n-nodes-base/test/nodes/Helpers';
import type { INode, ISupplyDataFunctions } from 'n8n-workflow';
import { NodeOperationError } from 'n8n-workflow';
import { LmChatAnthropic } from '../LmChatAnthropic.node';
jest.mock('@langchain/anthropic');
jest.mock('@n8n/ai-utilities', () => ({
getConnectionHintNoticeField: jest
.fn()
.mockReturnValue({ displayName: '', name: 'notice', type: 'notice', default: '' }),
makeN8nLlmFailedAttemptHandler: jest.fn(),
N8nLlmTracing: jest.fn(),
getProxyAgent: jest.fn(),
}));
const MockedChatAnthropic = jest.mocked(ChatAnthropic);
const MockedN8nLlmTracing = jest.mocked(N8nLlmTracing);
const mockedMakeN8nLlmFailedAttemptHandler = jest.mocked(makeN8nLlmFailedAttemptHandler);
const mockedGetProxyAgent = jest.mocked(getProxyAgent);
describe('LmChatAnthropic', () => {
let lmChatAnthropic: LmChatAnthropic;
let mockContext: jest.Mocked<ISupplyDataFunctions>;
const mockNode: INode = {
id: '1',
name: 'Anthropic Chat Model',
typeVersion: 1.3,
type: 'n8n-nodes-langchain.lmChatAnthropic',
position: [0, 0],
parameters: {},
};
const setupMockContext = (nodeOverrides: Partial<INode> = {}) => {
const node = { ...mockNode, ...nodeOverrides };
mockContext = createMockExecuteFunction<ISupplyDataFunctions>(
{},
node,
) as jest.Mocked<ISupplyDataFunctions>;
// Setup default mocks
mockContext.getCredentials = jest.fn().mockResolvedValue({
apiKey: 'test-api-key',
});
mockContext.getNode = jest.fn().mockReturnValue(node);
mockContext.getNodeParameter = jest.fn();
// Mock the constructors/functions properly
MockedN8nLlmTracing.mockImplementation(() => ({}) as N8nLlmTracing);
mockedMakeN8nLlmFailedAttemptHandler.mockReturnValue(jest.fn());
mockedGetProxyAgent.mockReturnValue({} as any);
return mockContext;
};
const createMockModel = (properties: Partial<ChatAnthropic>): ChatAnthropic => {
const mockModel = properties as ChatAnthropic;
MockedChatAnthropic.mockImplementation(() => mockModel);
return mockModel;
};
beforeEach(() => {
lmChatAnthropic = new LmChatAnthropic();
jest.clearAllMocks();
});
afterEach(() => {
jest.clearAllMocks();
});
describe('node description', () => {
it('should have correct node properties', () => {
expect(lmChatAnthropic.description).toMatchObject({
displayName: 'Anthropic Chat Model',
name: 'lmChatAnthropic',
group: ['transform'],
version: [1, 1.1, 1.2, 1.3],
description: 'Language Model Anthropic',
});
});
it('should have correct credentials configuration', () => {
expect(lmChatAnthropic.description.credentials).toEqual([
{
name: 'anthropicApi',
required: true,
},
]);
});
it('should have correct output configuration', () => {
expect(lmChatAnthropic.description.outputs).toEqual(['ai_languageModel']);
expect(lmChatAnthropic.description.outputNames).toEqual(['Model']);
});
});
describe('supplyData', () => {
it('should create ChatAnthropic instance with basic configuration (version >= 1.3)', async () => {
const mockContext = setupMockContext({ typeVersion: 1.3 });
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return {};
return undefined;
});
const result = await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(mockContext.getCredentials).toHaveBeenCalledWith('anthropicApi');
expect(mockContext.getNodeParameter).toHaveBeenCalledWith('model.value', 0);
expect(mockContext.getNodeParameter).toHaveBeenCalledWith('options', 0, {});
expect(MockedChatAnthropic).toHaveBeenCalledWith(
expect.objectContaining({
anthropicApiKey: 'test-api-key',
model: 'claude-sonnet-4-20250514',
anthropicApiUrl: 'https://api.anthropic.com',
maxTokens: undefined,
temperature: undefined,
topK: undefined,
topP: undefined,
callbacks: expect.arrayContaining([expect.any(Object)]),
onFailedAttempt: expect.any(Function),
invocationKwargs: {},
clientOptions: {
fetchOptions: {
dispatcher: {},
},
},
}),
);
expect(result).toEqual({
response: expect.any(Object),
});
});
it('should create ChatAnthropic instance with basic configuration (version < 1.3)', async () => {
const mockContext = setupMockContext({ typeVersion: 1.2 });
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model') return 'claude-3-5-sonnet-20241022';
if (paramName === 'options') return {};
return undefined;
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(mockContext.getNodeParameter).toHaveBeenCalledWith('model', 0);
expect(mockContext.getNodeParameter).toHaveBeenCalledWith('options', 0, {});
expect(MockedChatAnthropic).toHaveBeenCalledWith(
expect.objectContaining({
anthropicApiKey: 'test-api-key',
model: 'claude-3-5-sonnet-20241022',
anthropicApiUrl: 'https://api.anthropic.com',
}),
);
});
it('should handle custom baseURL from credentials', async () => {
const customURL = 'https://custom-anthropic.example.com';
const mockContext = setupMockContext();
mockContext.getCredentials.mockResolvedValue({
apiKey: 'test-api-key',
url: customURL,
});
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return {};
return undefined;
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(MockedChatAnthropic).toHaveBeenCalledWith(
expect.objectContaining({
anthropicApiKey: 'test-api-key',
model: 'claude-sonnet-4-20250514',
anthropicApiUrl: customURL,
}),
);
});
it('should handle all available options', async () => {
const mockContext = setupMockContext();
const options = {
maxTokensToSample: 2048,
temperature: 0.8,
topK: 40,
topP: 0.9,
};
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return options;
return undefined;
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(MockedChatAnthropic).toHaveBeenCalledWith(
expect.objectContaining({
anthropicApiKey: 'test-api-key',
model: 'claude-sonnet-4-20250514',
anthropicApiUrl: 'https://api.anthropic.com',
maxTokens: 2048,
temperature: 0.8,
topK: 40,
topP: 0.9,
callbacks: expect.arrayContaining([expect.any(Object)]),
onFailedAttempt: expect.any(Function),
invocationKwargs: {},
}),
);
});
it('should remove topP from model when not explicitly set', async () => {
const mockContext = setupMockContext();
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return { temperature: 0.7 };
return undefined;
});
const mockModel = createMockModel({
topP: -1,
temperature: 0.7,
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
// Verify topP was deleted from the model instance
expect(mockModel).not.toHaveProperty('topP');
});
it('should keep topP on model when explicitly set', async () => {
const mockContext = setupMockContext();
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return { topP: 0.9 };
return undefined;
});
const mockModel = createMockModel({
topP: 0.9,
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
// Verify topP was not deleted from the model instance
expect(mockModel).toHaveProperty('topP', 0.9);
});
it('should remove temperature when topP is set but temperature is not', async () => {
const mockContext = setupMockContext();
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return { topP: 0.9 };
return undefined;
});
const mockModel = createMockModel({
topP: 0.9,
temperature: 0.7,
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
// Verify temperature was deleted from the model instance
expect(mockModel).not.toHaveProperty('temperature');
expect(mockModel).toHaveProperty('topP', 0.9);
});
it('should keep temperature when both topP and temperature are set', async () => {
const mockContext = setupMockContext();
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return { topP: 0.9, temperature: 0.8 };
return undefined;
});
const mockModel = createMockModel({
topP: 0.9,
temperature: 0.8,
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
// Verify both properties remain
expect(mockModel).toHaveProperty('topP', 0.9);
expect(mockModel).toHaveProperty('temperature', 0.8);
});
it('should configure thinking mode correctly when enabled', async () => {
const mockContext = setupMockContext();
const options = {
thinking: true,
thinkingBudget: 2048,
maxTokensToSample: 4096,
};
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return options;
return undefined;
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(MockedChatAnthropic).toHaveBeenCalledWith(
expect.objectContaining({
anthropicApiKey: 'test-api-key',
model: 'claude-sonnet-4-20250514',
maxTokens: 4096,
invocationKwargs: {
thinking: {
type: 'enabled',
budget_tokens: 2048,
},
max_tokens: 4096,
top_k: undefined,
top_p: undefined,
temperature: undefined,
},
}),
);
});
it('should use default thinking budget when not specified', async () => {
const mockContext = setupMockContext();
const options = {
thinking: true,
};
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return options;
return undefined;
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(MockedChatAnthropic).toHaveBeenCalledWith(
expect.objectContaining({
invocationKwargs: {
thinking: {
type: 'enabled',
budget_tokens: 1024, // MIN_THINKING_BUDGET
},
max_tokens: 4096, // DEFAULT_MAX_TOKENS
top_k: undefined,
top_p: undefined,
temperature: undefined,
},
}),
);
});
it('should unset sampling parameters when thinking mode is enabled', async () => {
const mockContext = setupMockContext();
const options = {
thinking: true,
thinkingBudget: 2048,
maxTokensToSample: 4096,
temperature: 0.8,
topK: 40,
topP: 0.9,
};
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return options;
return undefined;
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(MockedChatAnthropic).toHaveBeenCalledWith(
expect.objectContaining({
// These are set initially but will be overridden by invocationKwargs
temperature: 0.8,
topK: 40,
topP: 0.9,
invocationKwargs: {
thinking: {
type: 'enabled',
budget_tokens: 2048,
},
max_tokens: 4096,
// These override the model options
top_k: undefined,
top_p: undefined,
temperature: undefined,
},
}),
);
});
it('should create N8nLlmTracing callback with tokens usage parser', async () => {
const mockContext = setupMockContext();
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return {};
return undefined;
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(MockedN8nLlmTracing).toHaveBeenCalledWith(
mockContext,
expect.objectContaining({
tokensUsageParser: expect.any(Function),
}),
);
});
it('should create failed attempt handler without gateway handler for direct API', async () => {
const mockContext = setupMockContext();
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return {};
return undefined;
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(mockedMakeN8nLlmFailedAttemptHandler).toHaveBeenCalledWith(mockContext, undefined);
});
it('should create failed attempt handler with gateway handler for custom URL', async () => {
const mockContext = setupMockContext();
mockContext.getCredentials.mockResolvedValue({
apiKey: 'test-api-key',
url: 'https://ai-gateway.example.com',
});
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return {};
return undefined;
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(mockedMakeN8nLlmFailedAttemptHandler).toHaveBeenCalledWith(
mockContext,
expect.any(Function),
);
});
it('should enrich model-not-found errors with gateway hint when using custom URL', async () => {
const gatewayURL = 'https://ai-gateway.example.com';
const mockContext = setupMockContext();
mockContext.getCredentials.mockResolvedValue({
apiKey: 'test-api-key',
url: gatewayURL,
});
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return 'claude-sonnet-4-20250514';
if (paramName === 'options') return {};
return undefined;
});
// Capture the gateway handler passed to makeN8nLlmFailedAttemptHandler
let capturedHandler: ((error: unknown) => void) | undefined;
mockedMakeN8nLlmFailedAttemptHandler.mockImplementation((_ctx, handler) => {
capturedHandler = handler as (error: unknown) => void;
return jest.fn();
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(capturedHandler).toBeDefined();
// Model-not-found error should be enriched
expect(() => capturedHandler!(new Error('model not found'))).toThrow(NodeOperationError);
expect(() => capturedHandler!(new Error('model not found'))).toThrow(
/ai-gateway\.example\.com/,
);
// Non-model errors should pass through without throwing
expect(() => capturedHandler!(new Error('rate limit exceeded'))).not.toThrow();
});
it('should throw when model is empty (v1.3)', async () => {
const mockContext = setupMockContext({ typeVersion: 1.3 });
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return '';
if (paramName === 'options') return {};
return undefined;
});
await expect(lmChatAnthropic.supplyData.call(mockContext, 0)).rejects.toThrow(
NodeOperationError,
);
expect(MockedChatAnthropic).not.toHaveBeenCalled();
});
it('should throw when model is empty (v1.2)', async () => {
const mockContext = setupMockContext({ typeVersion: 1.2 });
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model') return '';
if (paramName === 'options') return {};
return undefined;
});
await expect(lmChatAnthropic.supplyData.call(mockContext, 0)).rejects.toThrow(
NodeOperationError,
);
expect(MockedChatAnthropic).not.toHaveBeenCalled();
});
it('should use gateway-provided model name via custom base URL without hardcoded defaults', async () => {
const gatewayURL = 'https://ai-gateway.example.com';
const gatewayModel = 'my-org/claude-3-sonnet';
const mockContext = setupMockContext({ typeVersion: 1.3 });
mockContext.getCredentials.mockResolvedValue({
apiKey: 'gateway-api-key',
url: gatewayURL,
});
mockContext.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model.value') return gatewayModel;
if (paramName === 'options') return {};
return undefined;
});
await lmChatAnthropic.supplyData.call(mockContext, 0);
expect(MockedChatAnthropic).toHaveBeenCalledWith(
expect.objectContaining({
anthropicApiKey: 'gateway-api-key',
model: gatewayModel,
anthropicApiUrl: gatewayURL,
}),
);
});
it('should have a default model in v1.3 resource locator', () => {
const v13ModelField = lmChatAnthropic.description.properties.find(
(p) =>
p.name === 'model' &&
p.type === 'resourceLocator' &&
p.displayOptions?.show?.['@version']?.[0] !== undefined,
);
expect(v13ModelField).toBeDefined();
expect(v13ModelField!.default).toEqual({
mode: 'list',
value: 'claude-sonnet-4-5-20250929',
cachedResultName: 'Claude Sonnet 4.5',
});
});
});
describe('methods', () => {
it('should have searchModels method', () => {
expect(lmChatAnthropic.methods).toEqual({
listSearch: {
searchModels: expect.any(Function),
},
});
});
});
});