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,327 @@
import { ChatOpenAI, type ClientOptions } from '@langchain/openai';
import {
getProxyAgent,
makeN8nLlmFailedAttemptHandler,
N8nLlmTracing,
getConnectionHintNoticeField,
} from '@n8n/ai-utilities';
import {
NodeConnectionTypes,
type INodeType,
type INodeTypeDescription,
type ISupplyDataFunctions,
type SupplyData,
} from 'n8n-workflow';
import type { OpenAICompatibleCredential } from '../../../types/types';
import { openAiFailedAttemptHandler } from '../../vendors/OpenAi/helpers/error-handling';
interface OpenAIToolCall {
function?: { arguments?: unknown };
}
interface OpenAIChoice {
message?: { tool_calls?: OpenAIToolCall[] };
}
function isOpenAIResponseWithChoices(json: unknown): json is { choices: OpenAIChoice[] } {
return (
typeof json === 'object' &&
json !== null &&
'choices' in json &&
Array.isArray((json as { choices: unknown }).choices)
);
}
/**
* Wraps fetch to fix empty tool call arguments in API responses.
*
* When Anthropic models are accessed through OpenRouter, tool calls for tools
* with no parameters return empty string arguments ("") instead of "{}".
* LangChain's parseToolCall does JSON.parse("") which throws, breaking the agent.
* This wrapper normalizes empty arguments to "{}" before LangChain sees them.
*/
function createOpenRouterFetch(baseFetch: typeof globalThis.fetch): typeof globalThis.fetch {
return async (input, init) => {
const response = await baseFetch(input, init);
const contentType = response.headers.get('content-type') ?? '';
if (!contentType.includes('json')) return response;
// Clone before reading, since .json() consumes the body. If no
// modification is needed we return the clone with the original body intact.
const clone = response.clone();
const json: unknown = await response.json();
if (!isOpenAIResponseWithChoices(json)) return clone;
const isInvalidArgs = (args: unknown): boolean => typeof args !== 'string' || !args.trim();
const toolCallsToFix = json.choices
.flatMap((choice) => choice.message?.tool_calls ?? [])
.filter((tc) => tc.function && isInvalidArgs(tc.function.arguments));
if (toolCallsToFix.length === 0) return clone;
for (const tc of toolCallsToFix) {
if (!tc.function) continue;
const { arguments: args } = tc.function;
// Preserve already-parsed plain objects by stringifying them.
// Arrays and other non-object types are not valid tool args, so default to '{}'.
const isPlainObject = typeof args === 'object' && args !== null && !Array.isArray(args);
tc.function.arguments = isPlainObject ? JSON.stringify(args) : '{}';
}
const body = JSON.stringify(json);
return new Response(body, {
status: response.status,
statusText: response.statusText,
headers: { 'content-type': contentType },
});
};
}
export class LmChatOpenRouter implements INodeType {
description: INodeTypeDescription = {
displayName: 'OpenRouter Chat Model',
name: 'lmChatOpenRouter',
icon: { light: 'file:openrouter.svg', dark: 'file:openrouter.dark.svg' },
group: ['transform'],
version: [1],
description: 'For advanced usage with an AI chain',
defaults: {
name: 'OpenRouter 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.lmchatopenrouter/',
},
],
},
},
inputs: [],
outputs: [NodeConnectionTypes.AiLanguageModel],
outputNames: ['Model'],
credentials: [
{
name: 'openRouterApi',
required: true,
},
],
requestDefaults: {
ignoreHttpStatusErrors: true,
baseURL: '={{ $credentials?.url }}',
},
properties: [
getConnectionHintNoticeField([NodeConnectionTypes.AiChain, NodeConnectionTypes.AiAgent]),
{
displayName:
'If using JSON response format, you must include word "json" in the prompt in your chain or agent. Also, make sure to select latest models released post November 2023.',
name: 'notice',
type: 'notice',
default: '',
displayOptions: {
show: {
'/options.responseFormat': ['json_object'],
},
},
},
{
displayName: 'Model',
name: 'model',
type: 'options',
description:
'The model which will generate the completion. <a href="https://openrouter.ai/docs/models">Learn more</a>.',
typeOptions: {
loadOptions: {
routing: {
request: {
method: 'GET',
url: '/models',
},
output: {
postReceive: [
{
type: 'rootProperty',
properties: {
property: 'data',
},
},
{
type: 'setKeyValue',
properties: {
name: '={{$responseItem.id}}',
value: '={{$responseItem.id}}',
},
},
{
type: 'sort',
properties: {
key: 'name',
},
},
],
},
},
},
},
routing: {
send: {
type: 'body',
property: 'model',
},
},
default: 'openai/gpt-4.1-mini',
},
{
displayName: 'Options',
name: 'options',
placeholder: 'Add Option',
description: 'Additional options to add',
type: 'collection',
default: {},
options: [
{
displayName: 'Frequency Penalty',
name: 'frequencyPenalty',
default: 0,
typeOptions: { maxValue: 2, minValue: -2, numberPrecision: 1 },
description:
"Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim",
type: 'number',
},
{
displayName: 'Maximum Number of Tokens',
name: 'maxTokens',
default: -1,
description:
'The maximum number of tokens to generate in the completion. Most models have a context length of 2048 tokens (except for the newest models, which support 32,768).',
type: 'number',
typeOptions: {
maxValue: 32768,
},
},
{
displayName: 'Response Format',
name: 'responseFormat',
default: 'text',
type: 'options',
options: [
{
name: 'Text',
value: 'text',
description: 'Regular text response',
},
{
name: 'JSON',
value: 'json_object',
description:
'Enables JSON mode, which should guarantee the message the model generates is valid JSON',
},
],
},
{
displayName: 'Presence Penalty',
name: 'presencePenalty',
default: 0,
typeOptions: { maxValue: 2, minValue: -2, numberPrecision: 1 },
description:
"Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics",
type: 'number',
},
{
displayName: 'Sampling Temperature',
name: 'temperature',
default: 0.7,
typeOptions: { maxValue: 2, 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',
},
{
displayName: 'Timeout',
name: 'timeout',
default: 360000,
description: 'Maximum amount of time a request is allowed to take in milliseconds',
type: 'number',
},
{
displayName: 'Max Retries',
name: 'maxRetries',
default: 2,
description: 'Maximum number of retries to attempt',
type: 'number',
},
{
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',
},
],
},
],
};
async supplyData(this: ISupplyDataFunctions, itemIndex: number): Promise<SupplyData> {
const credentials = await this.getCredentials<OpenAICompatibleCredential>('openRouterApi');
const modelName = this.getNodeParameter('model', itemIndex) as string;
const options = this.getNodeParameter('options', itemIndex, {}) as {
frequencyPenalty?: number;
maxTokens?: number;
maxRetries: number;
timeout: number;
presencePenalty?: number;
temperature?: number;
topP?: number;
responseFormat?: 'text' | 'json_object';
};
const timeout = options.timeout;
const configuration: ClientOptions = {
baseURL: credentials.url,
fetch: createOpenRouterFetch(globalThis.fetch),
fetchOptions: {
dispatcher: getProxyAgent(credentials.url, {
headersTimeout: timeout,
bodyTimeout: timeout,
}),
},
};
const model = new ChatOpenAI({
apiKey: credentials.apiKey,
model: modelName,
...options,
timeout,
maxRetries: options.maxRetries ?? 2,
configuration,
callbacks: [new N8nLlmTracing(this)],
modelKwargs: options.responseFormat
? {
response_format: { type: options.responseFormat },
}
: undefined,
onFailedAttempt: makeN8nLlmFailedAttemptHandler(this, openAiFailedAttemptHandler),
});
return {
response: model,
};
}
}
@@ -0,0 +1 @@
<svg fill="white" fill-rule="evenodd" width="40" height="40" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>OpenRouter</title><path d="M16.804 1.957l7.22 4.105v.087L16.73 10.21l.017-2.117-.821-.03c-1.059-.028-1.611.002-2.268.11-1.064.175-2.038.577-3.147 1.352L8.345 11.03c-.284.195-.495.336-.68.455l-.515.322-.397.234.385.23.53.338c.476.314 1.17.796 2.701 1.866 1.11.775 2.083 1.177 3.147 1.352l.3.045c.694.091 1.375.094 2.825.033l.022-2.159 7.22 4.105v.087L16.589 22l.014-1.862-.635.022c-1.386.042-2.137.002-3.138-.162-1.694-.28-3.26-.926-4.881-2.059l-2.158-1.5a21.997 21.997 0 00-.755-.498l-.467-.28a55.927 55.927 0 00-.76-.43C2.908 14.73.563 14.116 0 14.116V9.888l.14.004c.564-.007 2.91-.622 3.809-1.124l1.016-.58.438-.274c.428-.28 1.072-.726 2.686-1.853 1.621-1.133 3.186-1.78 4.881-2.059 1.152-.19 1.974-.213 3.814-.138l.02-1.907z"></path></svg>

After

Width:  |  Height:  |  Size: 866 B

@@ -0,0 +1 @@
<svg fill="#94A3B8" fill-rule="evenodd" width="40" height="40" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>OpenRouter</title><path d="M16.804 1.957l7.22 4.105v.087L16.73 10.21l.017-2.117-.821-.03c-1.059-.028-1.611.002-2.268.11-1.064.175-2.038.577-3.147 1.352L8.345 11.03c-.284.195-.495.336-.68.455l-.515.322-.397.234.385.23.53.338c.476.314 1.17.796 2.701 1.866 1.11.775 2.083 1.177 3.147 1.352l.3.045c.694.091 1.375.094 2.825.033l.022-2.159 7.22 4.105v.087L16.589 22l.014-1.862-.635.022c-1.386.042-2.137.002-3.138-.162-1.694-.28-3.26-.926-4.881-2.059l-2.158-1.5a21.997 21.997 0 00-.755-.498l-.467-.28a55.927 55.927 0 00-.76-.43C2.908 14.73.563 14.116 0 14.116V9.888l.14.004c.564-.007 2.91-.622 3.809-1.124l1.016-.58.438-.274c.428-.28 1.072-.726 2.686-1.853 1.621-1.133 3.186-1.78 4.881-2.059 1.152-.19 1.974-.213 3.814-.138l.02-1.907z"></path></svg>

After

Width:  |  Height:  |  Size: 868 B

@@ -0,0 +1,327 @@
/* eslint-disable n8n-nodes-base/node-filename-against-convention */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/unbound-method */
import { ChatOpenAI } from '@langchain/openai';
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 { LmChatOpenRouter } from '../LmChatOpenRouter.node';
jest.mock('@langchain/openai');
jest.mock('@n8n/ai-utilities');
const MockedChatOpenAI = jest.mocked(ChatOpenAI);
const MockedN8nLlmTracing = jest.mocked(N8nLlmTracing);
const mockedMakeN8nLlmFailedAttemptHandler = jest.mocked(makeN8nLlmFailedAttemptHandler);
const mockedGetProxyAgent = jest.mocked(getProxyAgent);
describe('LmChatOpenRouter', () => {
let node: LmChatOpenRouter;
const mockNodeDef: INode = {
id: '1',
name: 'OpenRouter Chat Model',
typeVersion: 1,
type: 'n8n-nodes-langchain.lmChatOpenRouter',
position: [0, 0],
parameters: {},
};
const setupMockContext = (nodeOverrides: Partial<INode> = {}) => {
const nodeDef = { ...mockNodeDef, ...nodeOverrides };
const ctx = createMockExecuteFunction<ISupplyDataFunctions>(
{},
nodeDef,
) as jest.Mocked<ISupplyDataFunctions>;
ctx.getCredentials = jest.fn().mockResolvedValue({
apiKey: 'test-key',
url: 'https://openrouter.ai/api/v1',
});
ctx.getNode = jest.fn().mockReturnValue(nodeDef);
ctx.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model') return 'anthropic/claude-sonnet-4-20250514';
if (paramName === 'options') return {};
return undefined;
});
MockedN8nLlmTracing.mockImplementation(() => ({}) as unknown as N8nLlmTracing);
mockedMakeN8nLlmFailedAttemptHandler.mockReturnValue(jest.fn());
mockedGetProxyAgent.mockReturnValue({} as any);
return ctx;
};
beforeEach(() => {
node = new LmChatOpenRouter();
jest.clearAllMocks();
});
describe('node description', () => {
it('should have correct node properties', () => {
expect(node.description).toMatchObject({
displayName: 'OpenRouter Chat Model',
name: 'lmChatOpenRouter',
group: ['transform'],
version: [1],
});
});
it('should require openRouterApi credentials', () => {
expect(node.description.credentials).toEqual([{ name: 'openRouterApi', required: true }]);
});
it('should output ai_languageModel', () => {
expect(node.description.outputs).toEqual(['ai_languageModel']);
expect(node.description.outputNames).toEqual(['Model']);
});
});
describe('supplyData', () => {
it('should create ChatOpenAI with basic configuration', async () => {
const ctx = setupMockContext();
const result = await node.supplyData.call(ctx, 0);
expect(ctx.getCredentials).toHaveBeenCalledWith('openRouterApi');
expect(MockedChatOpenAI).toHaveBeenCalledWith(
expect.objectContaining({
apiKey: 'test-key',
model: 'anthropic/claude-sonnet-4-20250514',
maxRetries: 2,
callbacks: expect.arrayContaining([expect.any(Object)]),
onFailedAttempt: expect.any(Function),
}),
);
expect(result).toEqual({ response: expect.any(Object) });
});
it('should pass options to ChatOpenAI', async () => {
const ctx = setupMockContext();
ctx.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model') return 'anthropic/claude-sonnet-4-20250514';
if (paramName === 'options')
return {
temperature: 0.5,
maxTokens: 2000,
topP: 0.9,
frequencyPenalty: 0.3,
presencePenalty: 0.2,
timeout: 60000,
maxRetries: 5,
};
return undefined;
});
await node.supplyData.call(ctx, 0);
expect(MockedChatOpenAI).toHaveBeenCalledWith(
expect.objectContaining({
temperature: 0.5,
maxTokens: 2000,
topP: 0.9,
frequencyPenalty: 0.3,
presencePenalty: 0.2,
timeout: 60000,
maxRetries: 5,
}),
);
});
it('should set response_format in modelKwargs when responseFormat is provided', async () => {
const ctx = setupMockContext();
ctx.getNodeParameter = jest.fn().mockImplementation((paramName: string) => {
if (paramName === 'model') return 'anthropic/claude-sonnet-4-20250514';
if (paramName === 'options') return { responseFormat: 'json_object' };
return undefined;
});
await node.supplyData.call(ctx, 0);
expect(MockedChatOpenAI).toHaveBeenCalledWith(
expect.objectContaining({
modelKwargs: { response_format: { type: 'json_object' } },
}),
);
});
it('should not set modelKwargs when no responseFormat', async () => {
const ctx = setupMockContext();
await node.supplyData.call(ctx, 0);
expect(MockedChatOpenAI).toHaveBeenCalledWith(
expect.objectContaining({
modelKwargs: undefined,
}),
);
});
it('should pass a custom fetch wrapper in configuration', async () => {
const ctx = setupMockContext();
await node.supplyData.call(ctx, 0);
const callArgs = MockedChatOpenAI.mock.calls[0][0];
expect(callArgs?.configuration?.fetch).toEqual(expect.any(Function));
});
});
describe('fetch wrapper (empty tool call arguments fix)', () => {
const origFetch = globalThis.fetch;
afterEach(() => {
globalThis.fetch = origFetch;
});
function jsonResponse(body: unknown): Response {
const json = JSON.stringify(body);
return new Response(json, {
status: 200,
headers: { 'content-type': 'application/json' },
});
}
/**
* Sets up a mock fetch, calls supplyData to capture it in the wrapper,
* and returns the wrapper function from the ChatOpenAI constructor args.
*/
async function setupFetchWrapper(mockFetch: jest.Mock): Promise<typeof globalThis.fetch> {
globalThis.fetch = mockFetch;
const ctx = setupMockContext();
await node.supplyData.call(ctx, 0);
return MockedChatOpenAI.mock.calls[0][0]?.configuration?.fetch as typeof fetch;
}
it.each<{ input: unknown; expected: string; label: string }>([
{ input: '', expected: '{}', label: 'empty string' },
{ input: ' ', expected: '{}', label: 'whitespace-only string' },
{ input: null, expected: '{}', label: 'null' },
{ input: [], expected: '{}', label: 'empty array' },
{ input: [1, 2], expected: '{}', label: 'non-empty array' },
{ input: {}, expected: '{}', label: 'empty object (stringified)' },
{
input: { location: 'NYC' },
expected: '{"location":"NYC"}',
label: 'plain object (stringified)',
},
{
input: '{"location":"NYC"}',
expected: '{"location":"NYC"}',
label: 'valid JSON string (unchanged)',
},
{ input: '{}', expected: '{}', label: 'empty JSON object string (unchanged)' },
])('should normalize arguments: $label → $expected', async ({ input, expected }) => {
const mockFetch = jest.fn().mockResolvedValue(
jsonResponse({
choices: [
{
message: {
tool_calls: [{ id: 'call_1', function: { name: 'tool', arguments: input } }],
},
},
],
}),
);
const wrappedFetch = await setupFetchWrapper(mockFetch);
const response = await wrappedFetch('https://openrouter.ai/api/v1/chat/completions');
const result = await response.json();
expect(result.choices[0].message.tool_calls[0].function.arguments).toBe(expected);
});
it('should pass through non-JSON responses untouched', async () => {
const textBody = 'plain text response';
const mockFetch = jest.fn().mockResolvedValue(
new Response(textBody, {
status: 200,
headers: { 'content-type': 'text/plain' },
}),
);
const wrappedFetch = await setupFetchWrapper(mockFetch);
const response = await wrappedFetch('https://openrouter.ai/api/v1/chat/completions');
expect(await response.text()).toBe(textBody);
});
it('should pass through JSON responses without choices', async () => {
const body = { models: ['a', 'b'] };
const mockFetch = jest.fn().mockResolvedValue(jsonResponse(body));
const wrappedFetch = await setupFetchWrapper(mockFetch);
const response = await wrappedFetch('https://openrouter.ai/api/v1/models');
expect(await response.json()).toEqual(body);
});
it('should pass through responses without tool_calls', async () => {
const body = {
choices: [{ message: { role: 'assistant', content: 'Hello!' } }],
};
const mockFetch = jest.fn().mockResolvedValue(jsonResponse(body));
const wrappedFetch = await setupFetchWrapper(mockFetch);
const response = await wrappedFetch('https://openrouter.ai/api/v1/chat/completions');
expect(await response.json()).toEqual(body);
});
it('should fix only empty arguments in a mixed set of tool calls', async () => {
const mockFetch = jest.fn().mockResolvedValue(
jsonResponse({
choices: [
{
message: {
tool_calls: [
{
id: 'call_1',
function: { name: 'get_weather', arguments: '{"city":"NYC"}' },
},
{ id: 'call_2', function: { name: 'get_time', arguments: '' } },
{
id: 'call_3',
function: { name: 'get_date', arguments: '{"format":"iso"}' },
},
],
},
},
],
}),
);
const wrappedFetch = await setupFetchWrapper(mockFetch);
const response = await wrappedFetch('https://openrouter.ai/api/v1/chat/completions');
const result = await response.json();
const toolCalls = result.choices[0].message.tool_calls;
expect(toolCalls[0].function.arguments).toBe('{"city":"NYC"}');
expect(toolCalls[1].function.arguments).toBe('{}');
expect(toolCalls[2].function.arguments).toBe('{"format":"iso"}');
});
it('should only carry content-type header on modified responses', async () => {
const mockFetch = jest.fn().mockResolvedValue(
jsonResponse({
choices: [
{
message: {
tool_calls: [{ id: 'call_1', function: { name: 'get_time', arguments: '' } }],
},
},
],
}),
);
const wrappedFetch = await setupFetchWrapper(mockFetch);
const response = await wrappedFetch('https://openrouter.ai/api/v1/chat/completions');
expect(response.headers.get('content-type')).toBe('application/json');
// Stale metadata headers (content-length, etag, etc.) are not carried over
expect(response.headers.get('content-length')).toBeNull();
});
});
});