Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(model-runtime): handle Responses API tool pairing and context limit errors (#13078)

YuTengjing81becc3583e7
diff --git a/packages/model-runtime/src/core/contextBuilders/openai.test.ts b/packages/model-runtime/src/core/contextBuilders/openai.test.ts
index 27a2fbe86dc..cd2dfc06faa 100644
--- a/packages/model-runtime/src/core/contextBuilders/openai.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/openai.test.ts
@@ -592,6 +592,88 @@ describe('convertOpenAIResponseInputs', () => {
]);
});
+ it('should filter orphan tool calls when strictToolPairing is enabled', async () => {
+ const messages: OpenAIChatMessage[] = [
+ { role: 'user', content: 'Use tools carefully' },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ {
+ id: 'call_paired',
+ type: 'function',
+ function: {
+ name: 'get_weather',
+ arguments: '{"city":"Hangzhou"}',
+ },
+ },
+ {
+ id: 'call_orphan',
+ type: 'function',
+ function: {
+ name: 'get_news',
+ arguments: '{"topic":"AI"}',
+ },
+ },
+ ],
+ },
+ {
+ role: 'tool',
+ content: '{"temp":22}',
+ tool_call_id: 'call_paired',
+ },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages, { strictToolPairing: true });
+
+ expect(result).toEqual([
+ { role: 'user', content: 'Use tools carefully' },
+ {
+ arguments: '{"city":"Hangzhou"}',
+ call_id: 'call_paired',
+ name: 'get_weather',
+ type: 'function_call',
+ },
+ {
+ call_id: 'call_paired',
+ output: '{"temp":22}',
+ type: 'function_call_output',
+ },
+ ]);
+ });
+
+ it('should drop assistant message with all orphaned tool_calls in strict mode', async () => {
+ const messages: OpenAIChatMessage[] = [
+ { role: 'user', content: 'Do something' },
+ {
+ role: 'assistant',
+ content: '',
+ tool_calls: [
+ {
+ id: 'call_orphan_1',
+ type: 'function',
+ function: { name: 'fn_a', arguments: '{}' },
+ },
+ {
+ id: 'call_orphan_2',
+ type: 'function',
+ function: { name: 'fn_b', arguments: '{}' },
+ },
+ ],
+ },
+ { role: 'assistant', content: 'Final answer' },
+ ];
+
+ const result = await convertOpenAIResponseInputs(messages, { strictToolPairing: true });
+
+ // The assistant message with all-orphaned tool_calls should produce no items,
+ // NOT fall through to the default builder which would spread tool_calls back.
+ expect(result).toEqual([
+ { role: 'user', content: 'Do something' },
+ { role: 'assistant', content: 'Final answer' },
+ ]);
+ });
+
it('should extract reasoning.content into a separate reasoning item', async () => {
const messages: OpenAIChatMessage[] = [
{ content: 'system prompts', role: 'system' },
diff --git a/packages/model-runtime/src/core/contextBuilders/openai.ts b/packages/model-runtime/src/core/contextBuilders/openai.ts
index a11494ccddc..70452fdc040 100644
--- a/packages/model-runtime/src/core/contextBuilders/openai.ts
+++ b/packages/model-runtime/src/core/contextBuilders/openai.ts
@@ -16,6 +16,7 @@ export type ExtendedChatCompletionContentPart = {
type ConvertMessageContentOptions = {
forceImageBase64?: boolean;
forceVideoBase64?: boolean;
+ strictToolPairing?: boolean;
};
type OpenAICompatibleContentPart =
@@ -115,6 +116,31 @@ export const convertOpenAIResponseInputs = async (
messages: OpenAIChatMessage[],
options?: ConvertMessageContentOptions,
) => {
+ const strictToolPairing = options?.strictToolPairing === true;
+ // OpenAI Responses API rejects inputs that keep a function_call without its matching
+ // function_call_output. Example from production:
+ // "No tool output found for function call call_w5odMFjtXEYBBVyBUAQNMOh5."
+ const validToolCallIds = new Set<string>();
+ const pairedToolOutputIds = new Set<string>();
+
+ for (const message of messages) {
+ if (message.role === 'assistant' && message.tool_calls?.length) {
+ message.tool_calls.forEach((tool) => {
+ if (tool.id) validToolCallIds.add(tool.id);
+ });
+ }
+ }
+
+ for (const message of messages) {
+ if (
+ message.role === 'tool' &&
+ message.tool_call_id &&
+ validToolCallIds.has(message.tool_call_id)
+ ) {
+ pairedToolOutputIds.add(message.tool_call_id);
+ }
+ }
+
const inputGroups = await Promise.all(
messages.map(async (message) => {
const items: OpenAI.Responses.ResponseInputItem[] = [];
@@ -129,9 +155,13 @@ export const convertOpenAIResponseInputs = async (
// if message is assistant messages with tool calls , transform it to function type item
if (message.role === 'assistant' && message.tool_calls && message.tool_calls?.length > 0) {
- message.tool_calls?.forEach((tool) => {
+ const toolCalls = strictToolPairing
+ ? message.tool_calls.filter((tool) => !!tool.id && pairedToolOutputIds.has(tool.id))
+ : message.tool_calls;
+
+ toolCalls.forEach((tool) => {
items.push({
- arguments: tool.function.name,
+ arguments: strictToolPairing ? tool.function.arguments : tool.function.name,
call_id: tool.id,
name: tool.function.name,
type: 'function_call',
@@ -142,6 +172,12 @@ export const convertOpenAIResponseInputs = async (
}
if (message.role === 'tool') {
+ if (
+ strictToolPairing &&
+ (!message.tool_call_id || !pairedToolOutputIds.has(message.tool_call_id))
+ )
+ return items;
+
items.push({
call_id: message.tool_call_id,
output: message.content,
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index e8c91256517..32364580ea4 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -1123,6 +1123,49 @@ describe('LobeOpenAICompatibleFactory', () => {
{ timeout: 10000 },
);
+ it('should enable strictToolPairing when building Responses API input', async () => {
+ const LobeMockProviderUseResponses = createOpenAICompatibleRuntime({
+ baseURL: 'https://api.test.com/v1',
+ chatCompletion: {
+ useResponse: true,
+ },
+ provider: ModelProvider.OpenAI,
+ });
+
+ const inst = new LobeMockProviderUseResponses({ apiKey: 'test' });
+ const convertSpy = vi
+ .spyOn(openaiHelpers, 'convertOpenAIResponseInputs')
+ .mockResolvedValue([{ role: 'user', content: 'mocked input' }] as any);
+
+ vi.spyOn(inst['client'].responses, 'create').mockResolvedValue({
+ toReadableStream: () =>
+ new ReadableStream({
+ start(controller) {
+ controller.close();
+ },
+ }),
+ } as any);
+
+ try {
+ await inst.chat({
+ messages: [{ content: 'hi', role: 'user' }],
+ model: 'any-model',
+ temperature: 0,
+ });
+ } catch {
+ // Ignore stream mock limitations; we only care about input conversion options.
+ }
+
+ expect(convertSpy).toHaveBeenCalledWith(
+ [{ content: 'hi', role: 'user' }],
+ expect.objectContaining({
+ forceImageBase64: undefined,
+ forceVideoBase64: undefined,
+ strictToolPairing: true,
+ }),
+ );
+ });
+
it(
'should route to Responses API when model matches useResponseModels',
async () => {
@@ -1813,6 +1856,46 @@ describe('LobeOpenAICompatibleFactory', () => {
);
});
+ it('should detect ExceededContextWindow from responses API error message text', async () => {
+ const apiError = new OpenAI.APIError(
+ 400,
+ {
+ error: {
+ message:
+ '400 Input tokens exceed the configured limit of 272000 tokens. Your messages resulted in 479832 tokens. Please reduce the length of the messages.',
+ },
+ status: 400,
+ },
+ 'Error message',
+ {},
+ );
+
+ vi.spyOn(instance['client'].responses, 'create').mockRejectedValue(apiError);
+
+ const payload = {
+ messages: [{ content: 'Generate data', role: 'user' as const }],
+ model: 'gpt-5-mini',
+ responseApi: true,
+ schema: {
+ name: 'test_tool',
+ schema: { properties: {}, type: 'object' as const },
+ },
+ };
+
+ await expect(instance.generateObject(payload)).rejects.toEqual({
+ endpoint: defaultBaseURL,
+ error: {
+ error: {
+ message:
+ '400 Input tokens exceed the configured limit of 272000 tokens. Your messages resulted in 479832 tokens. Please reduce the length of the messages.',
+ },
+ status: 400,
+ },
+ errorType: AgentRuntimeErrorType.ExceededContextWindow,
+ provider,
+ });
+ });
+
describe('chat completions API path', () => {
it('should return parsed JSON object using chat completions API', async () => {
const mockResponse = {
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index 46d0a80dcb7..b1eb49e0a46 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -653,116 +653,146 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
}
async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {
- const { messages, schema, model, responseApi, tools } = payload;
+ try {
+ const { messages, schema, model, responseApi, tools } = payload;
- const log = debug(`${this.logPrefix}:generateObject`);
- log(
- 'generateObject called with model: %s, hasTools: %s, hasSchema: %s',
- model,
- !!tools,
- !!schema,
- );
+ const log = debug(`${this.logPrefix}:generateObject`);
+ log(
+ 'generateObject called with model: %s, hasTools: %s, hasSchema: %s',
+ model,
+ !!tools,
+ !!schema,
+ );
- const pricing = await getModelPricing(model, this.id);
- const usagePayload = { model, pricing, provider: this.id };
+ const pricing = await getModelPricing(model, this.id);
+ const usagePayload = { model, pricing, provider: this.id };
- if (tools) {
- log('using tools-based generation');
- return this.generateObjectWithTools(payload, options, usagePayload);
- }
+ if (tools) {
+ log('using tools-based generation');
+ return this.generateObjectWithTools(payload, options, usagePayload);
+ }
- if (!schema) throw new Error('tools or schema is required');
+ if (!schema) throw new Error('tools or schema is required');
- // Use tool calling fallback if configured
- if (generateObjectConfig?.useToolsCalling) {
- log('using tool calling fallback for structured output');
+ // Use tool calling fallback if configured
+ if (generateObjectConfig?.useToolsCalling) {
+ log('using tool calling fallback for structured output');
- // Apply schema transformation if configured
- const processedSchema = generateObjectConfig.handleSchema
- ? { ...schema, schema: generateObjectConfig.handleSchema(schema.schema) }
- : schema;
+ // Apply schema transformation if configured
+ const processedSchema = generateObjectConfig.handleSchema
+ ? { ...schema, schema: generateObjectConfig.handleSchema(schema.schema) }
+ : schema;
- const tool: ChatCompletionTool = {
- function: {
- description:
- processedSchema.description ||
- 'Generate structured output according to the provided schema',
- name: processedSchema.name || 'structured_output',
- parameters: processedSchema.schema,
- },
- type: 'function',
- };
+ const tool: ChatCompletionTool = {
+ function: {
+ description:
+ processedSchema.description ||
+ 'Generate structured output according to the provided schema',
+ name: processedSchema.name || 'structured_output',
+ parameters: processedSchema.schema,
+ },
+ type: 'function',
+ };
- const res = await this.client.chat.completions.create(
- {
- messages,
- model,
- tool_choice: { function: { name: tool.function.name }, type: 'function' },
- tools: [tool],
- user: options?.user,
- },
- { headers: options?.headers, signal: options?.signal },
- );
+ const res = await this.client.chat.completions.create(
+ {
+ messages,
+ model,
+ tool_choice: { function: { name: tool.function.name }, type: 'function' },
+ tools: [tool],
+ user: options?.user,
+ },
+ { headers: options?.headers, signal: options?.signal },
+ );
- if (res.usage) {
- await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
- }
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
+ }
- const toolCalls = res.choices[0].message.tool_calls!;
+ const toolCalls = res.choices[0].message.tool_calls!;
- try {
- return toolCalls.map((item) => ({
- arguments: JSON.parse(item.function.arguments),
- name: item.function.name,
- }));
- } catch {
- console.error('parse tool call arguments error:', toolCalls);
- return undefined;
+ try {
+ return toolCalls.map((item) => ({
+ arguments: JSON.parse(item.function.arguments),
+ name: item.function.name,
+ }));
+ } catch {
+ console.error('parse tool call arguments error:', toolCalls);
+ return undefined;
+ }
}
- }
- // Factory-level Responses API routing control (supports instance override)
- const instanceGenerateObject = ((this._options as any).generateObject || {}) as {
- useResponse?: boolean;
- useResponseModels?: Array<string | RegExp>;
- };
- const flagUseResponse =
- instanceGenerateObject.useResponse ??
- (generateObjectConfig ? generateObjectConfig.useResponse : undefined);
- const flagUseResponseModels =
- instanceGenerateObject.useResponseModels ?? generateObjectConfig?.useResponseModels;
+ // Factory-level Responses API routing control (supports instance override)
+ const instanceGenerateObject = ((this._options as any).generateObject || {}) as {
+ useResponse?: boolean;
+ useResponseModels?: Array<string | RegExp>;
+ };
+ const flagUseResponse =
+ instanceGenerateObject.useResponse ??
+ (generateObjectConfig ? generateObjectConfig.useResponse : undefined);
+ const flagUseResponseModels =
+ instanceGenerateObject.useResponseModels ?? generateObjectConfig?.useResponseModels;
- const shouldUseResponses = this.shouldUseResponsesAPI({
- context: 'generateObject',
- flagUseResponse,
- flagUseResponseModels,
- model,
- responseApi,
- });
+ const shouldUseResponses = this.shouldUseResponsesAPI({
+ context: 'generateObject',
+ flagUseResponse,
+ flagUseResponseModels,
+ model,
+ responseApi,
+ });
- // Apply schema transformation if configured
- const processedSchema = generateObjectConfig?.handleSchema
- ? { ...schema, schema: generateObjectConfig.handleSchema(schema.schema) }
- : schema;
+ // Apply schema transformation if configured
+ const processedSchema = generateObjectConfig?.handleSchema
+ ? { ...schema, schema: generateObjectConfig.handleSchema(schema.schema) }
+ : schema;
- if (shouldUseResponses) {
- log('calling responses.create for structured output');
- const res = await this.client!.responses.create(
+ if (shouldUseResponses) {
+ log('calling responses.create for structured output');
+ const res = await this.client!.responses.create(
+ {
+ input: messages,
+ model,
+ text: { format: { strict: true, type: 'json_schema', ...processedSchema } },
+ user: options?.user,
+ },
+ { headers: options?.headers, signal: options?.signal },
+ );
+
+ if (res.usage) {
+ await options?.onUsage?.(convertOpenAIResponseUsage(res.usage, usagePayload));
+ }
+
+ const text = res.output_text;
+ log('received structured output from Responses API, length: %d', text?.length || 0);
+ try {
+ const result = JSON.parse(text);
+ log('successfully parsed JSON output');
+ return result;
+ } catch (error) {
+ log('failed to parse JSON output: %O', error);
+ console.error('parse json error:', text);
+ return undefined;
+ }
+ }
+
+ log('calling chat.completions.create for structured output');
+ const res = await this.client.chat.completions.create(
{
- input: messages,
+ messages,
model,
- text: { format: { strict: true, type: 'json_schema', ...processedSchema } },
+ response_format: { json_schema: processedSchema, type: 'json_schema' },
user: options?.user,
},
{ headers: options?.headers, signal: options?.signal },
);
-
if (res.usage) {
- await options?.onUsage?.(convertOpenAIResponseUsage(res.usage, usagePayload));
+ await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
}
- const text = res.output_text;
- log('received structured output from Responses API, length: %d', text?.length || 0);
+ const text = res.choices[0].message.content!;
+
+ log('received structured output from Chat Completions API, length: %d', text?.length || 0);
+
try {
const result = JSON.parse(text);
log('successfully parsed JSON output');
@@ -772,34 +802,17 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
console.error('parse json error:', text);
return undefined;
}
- }
-
- log('calling chat.completions.create for structured output');
- const res = await this.client.chat.completions.create(
- {
- messages,
- model,
- response_format: { json_schema: processedSchema, type: 'json_schema' },
- user: options?.user,
- },
- { headers: options?.headers, signal: options?.signal },
- );
- if (res.usage) {
- await options?.onUsage?.(convertOpenAIUsage(res.usage, usagePayload));
- }
-
- const text = res.choices[0].message.content!;
+ } catch (error) {
+ const handledError = this.handleError(error);
- log('received structured output from Chat Completions API, length: %d', text?.length || 0);
+ if (
+ handledError.errorType === AgentRuntimeErrorType.AgentRuntimeError ||
+ handledError.errorType === ErrorType.bizError
+ ) {
+ throw error;
+ }
- try {
- const result = JSON.parse(text);
- log('successfully parsed JSON output');
- return result;
- } catch (error) {
- log('failed to parse JSON output: %O', error);
- console.error('parse json error:', text);
- return undefined;
+ throw handledError;
}
}
@@ -1004,6 +1017,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
const input = await convertOpenAIResponseInputs(messages as any, {
forceImageBase64: chatCompletion?.forceImageBase64,
forceVideoBase64: chatCompletion?.forceVideoBase64,
+ strictToolPairing: true,
});
const isStreaming = payload.stream !== false;
@@ -1145,6 +1159,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
const input = await convertOpenAIResponseInputs(messages as any, {
forceImageBase64: chatCompletion?.forceImageBase64,
forceVideoBase64: chatCompletion?.forceVideoBase64,
+ strictToolPairing: true,
});
const res = await this.client.responses.create(
diff --git a/packages/model-runtime/src/utils/isExceededContextWindowError.test.ts b/packages/model-runtime/src/utils/isExceededContextWindowError.test.ts
index 57673d92f43..52a62ffc959 100644
--- a/packages/model-runtime/src/utils/isExceededContextWindowError.test.ts
+++ b/packages/model-runtime/src/utils/isExceededContextWindowError.test.ts
@@ -50,6 +50,14 @@ describe('isExceededContextWindowError', () => {
expect(isExceededContextWindowError('too many input tokens')).toBe(true);
});
+ it('should detect configured input token limit errors', () => {
+ expect(
+ isExceededContextWindowError(
+ '400 Input tokens exceed the configured limit of 272000 tokens. Your messages resulted in 479832 tokens. Please reduce the length of the messages.',
+ ),
+ ).toBe(true);
+ });
+
it('should detect Google "exceeds the maximum number of tokens" errors', () => {
expect(
isExceededContextWindowError(
diff --git a/packages/model-runtime/src/utils/isExceededContextWindowError.ts b/packages/model-runtime/src/utils/isExceededContextWindowError.ts
index 72045914cb1..c63b76c1f4f 100644
--- a/packages/model-runtime/src/utils/isExceededContextWindowError.ts
+++ b/packages/model-runtime/src/utils/isExceededContextWindowError.ts
@@ -6,6 +6,7 @@ const CONTEXT_WINDOW_PATTERNS = [
'exceeds the context window', // Aihubmix / generic
'prompt is too long', // Anthropic
'input is too long', // Anthropic
+ 'input tokens exceed the configured limit', // OpenAI-compatible providers / wrapped upstream errors
'too many input tokens', // Bedrock
'exceeds the maximum number of tokens', // Google
'maximum allowed number of input tokens',