Skip to content

Commit

Permalink
feat(Anthropic Chat Model Node): Fetch models dynamically & support t…
Browse files Browse the repository at this point in the history
…hinking (#13543)
  • Loading branch information
OlegIvaniv authored Feb 27, 2025
1 parent 615a42a commit 461df37
Show file tree
Hide file tree
Showing 5 changed files with 316 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {

import { getConnectionHintNoticeField } from '@utils/sharedFields';

import { searchModels } from './methods/searchModels';
import { makeN8nLlmFailedAttemptHandler } from '../n8nLlmFailedAttemptHandler';
import { N8nLlmTracing } from '../N8nLlmTracing';

Expand Down Expand Up @@ -69,15 +70,23 @@ const modelField: INodeProperties = {
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',
// eslint-disable-next-line n8n-nodes-base/node-class-description-name-miscased
name: 'lmChatAnthropic',
icon: 'file:anthropic.svg',
group: ['transform'],
version: [1, 1.1, 1.2],
defaultVersion: 1.2,
version: [1, 1.1, 1.2, 1.3],
defaultVersion: 1.3,
description: 'Language Model Anthropic',
defaults: {
name: 'Anthropic Chat Model',
Expand Down Expand Up @@ -135,7 +144,43 @@ export class LmChatAnthropic implements INodeType {
),
displayOptions: {
show: {
'@version': [{ _cnd: { gte: 1.2 } }],
'@version': [{ _cnd: { lte: 1.2 } }],
},
},
},
{
displayName: 'Model',
name: 'model',
type: 'resourceLocator',
default: {
mode: 'list',
value: 'claude-3-7-sonnet-20250219',
cachedResultName: 'Claude 3.7 Sonnet',
},
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 } }],
},
},
},
Expand All @@ -150,7 +195,7 @@ export class LmChatAnthropic implements INodeType {
{
displayName: 'Maximum Number of Tokens',
name: 'maxTokensToSample',
default: 4096,
default: DEFAULT_MAX_TOKENS,
description: 'The maximum number of tokens to generate in the completion',
type: 'number',
},
Expand All @@ -162,6 +207,11 @@ export class LmChatAnthropic implements INodeType {
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',
Expand All @@ -171,6 +221,11 @@ export class LmChatAnthropic implements INodeType {
description:
'Used to remove "long tail" low probability responses. Defaults to -1, which disables it.',
type: 'number',
displayOptions: {
hide: {
thinking: [true],
},
},
},
{
displayName: 'Top P',
Expand All @@ -180,6 +235,30 @@ export class LmChatAnthropic implements INodeType {
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],
},
},
},
],
},
Expand All @@ -189,13 +268,21 @@ export class LmChatAnthropic implements INodeType {
async supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise<SupplyData> {
const credentials = await this.getCredentials('anthropicApi');

const modelName = this.getNodeParameter('model', itemIndex) as string;
const version = this.getNode().typeVersion;
const modelName =
version >= 1.3
? (this.getNodeParameter('model.value', itemIndex) as string)
: (this.getNodeParameter('model', itemIndex) as string);

const options = this.getNodeParameter('options', itemIndex, {}) as {
maxTokensToSample?: number;
temperature: number;
topK: number;
topP: number;
topK?: number;
topP?: number;
thinking?: boolean;
thinkingBudget?: number;
};
let invocationKwargs = {};

const tokensUsageParser = (llmOutput: LLMResult['llmOutput']) => {
const usage = (llmOutput?.usage as { input_tokens: number; output_tokens: number }) ?? {
Expand All @@ -208,6 +295,27 @@ export class LmChatAnthropic implements INodeType {
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 model = new ChatAnthropic({
anthropicApiKey: credentials.apiKey as string,
modelName,
Expand All @@ -217,6 +325,7 @@ export class LmChatAnthropic implements INodeType {
topP: options.topP,
callbacks: [new N8nLlmTracing(this, { tokensUsageParser })],
onFailedAttempt: makeN8nLlmFailedAttemptHandler(this),
invocationKwargs,
});

return {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
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 = {
helpers: {
httpRequestWithAuthentication: jest.fn().mockResolvedValue({
data: mockModels,
}),
},
} as unknown as jest.Mocked<ILoadOptionsFunctions>;
});

afterEach(() => {
jest.clearAllMocks();
});

it('should fetch models from Anthropic API', async () => {
const result = await searchModels.call(mockContext);

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);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
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 response = (await this.helpers.httpRequestWithAuthentication.call(this, 'anthropicApi', {
url: 'https://api.anthropic.com/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,
};
}
2 changes: 1 addition & 1 deletion packages/@n8n/nodes-langchain/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@
"@google-cloud/resource-manager": "5.3.0",
"@google/generative-ai": "0.21.0",
"@huggingface/inference": "2.8.0",
"@langchain/anthropic": "0.3.11",
"@langchain/anthropic": "0.3.14",
"@langchain/aws": "0.1.3",
"@langchain/cohere": "0.3.2",
"@langchain/community": "0.3.24",
Expand Down
Loading

0 comments on commit 461df37

Please sign in to comment.