-
Notifications
You must be signed in to change notification settings - Fork 16
fix(agent): do not execute tool calls from a max_output_tokens-truncated response #125
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
LukasParke
merged 6 commits into
main
from
fix/skip-tool-calls-on-max-output-tokens-truncation
Sep 22, 2026
+274
−1
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
69aae63
fix(agent): do not execute tool calls from a max_output_tokens-trunca…
w0nche0l b212546
fix(agent): filter truncated calls per item, keep calls completed bef…
w0nche0l 10236d9
Revert "fix(agent): filter truncated calls per item, keep calls compl…
w0nche0l 703e236
fix(agent): pin the batch rule for max_output_tokens truncation
w0nche0l e7de1a0
docs(agent): note the streaming tool-call surface is outside the trun…
w0nche0l ddd60df
chore(agent): add changeset for the truncation tool-call guard
LukasParke File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| --- | ||
| '@openrouter/agent': patch | ||
| --- | ||
|
|
||
| Do not execute tool calls from a response truncated at `max_output_tokens`. A turn that hits the token budget mid-tool-call now finalizes with `status: 'incomplete'` instead of running the cut-off call (and re-requesting on the same exhausted budget). | ||
|
|
||
| ```ts | ||
| import { callModel } from '@openrouter/agent'; | ||
|
|
||
| const result = callModel(client, { | ||
| model: 'anthropic/claude-sonnet-4.5', | ||
| maxOutputTokens: 512, // budget exhausted mid tool call | ||
| tools: [myTool], | ||
| }); | ||
| const response = await result.getResponse(); | ||
| // response.status === 'incomplete' | ||
| // response.incompleteDetails.reason === 'max_output_tokens' | ||
| // The cut-off call is NOT executed; raise the budget and re-request. | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
220 changes: 220 additions & 0 deletions
220
packages/agent/tests/unit/max-output-tokens-truncation.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,220 @@ | ||
| import type { OpenRouterCore } from '@openrouter/sdk/core'; | ||
| import type * as models from '@openrouter/sdk/models'; | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
| import { z } from 'zod/v4'; | ||
|
|
||
| const mockBetaResponsesSend = vi.hoisted(() => vi.fn()); | ||
|
|
||
| vi.mock('@openrouter/sdk/funcs/betaResponsesSend', () => ({ | ||
| betaResponsesSend: mockBetaResponsesSend, | ||
| })); | ||
|
|
||
| import { callModel } from '../../src/inner-loop/call-model.js'; | ||
| import { stepCountIs } from '../../src/lib/stop-conditions.js'; | ||
| import { | ||
| extractToolCallsFromResponse, | ||
| responseHasToolCalls, | ||
| } from '../../src/lib/stream-transformers.js'; | ||
| import { ToolType } from '../../src/lib/tool-types.js'; | ||
|
|
||
| /** | ||
| * A turn the provider stopped at `max_output_tokens` two tokens into the tool | ||
| * call: a reasoning model spent the whole budget thinking. The `function_call` | ||
| * item is present but its arguments are a fragment. The loop must treat this | ||
| * as the end of the run, not as a call to execute or a reason to request again. | ||
| */ | ||
| function truncatedToolCallResponse( | ||
| output: models.OpenResponsesResult['output'] = [ | ||
| { | ||
| type: 'function_call', | ||
| id: 'fc_1', | ||
| callId: 'call_1', | ||
| name: 'run_shell', | ||
| arguments: '{"commands":', | ||
| status: 'incomplete', | ||
| }, | ||
| ], | ||
| ): models.OpenResponsesResult { | ||
| return { | ||
| id: 'resp_truncated', | ||
| object: 'response', | ||
| createdAt: 1_783_462_506, | ||
| completedAt: 1_783_462_520, | ||
| model: 'test-model', | ||
| status: 'incomplete', | ||
| incompleteDetails: { | ||
| reason: 'max_output_tokens', | ||
| }, | ||
| error: null, | ||
| output, | ||
| usage: { | ||
| inputTokens: 4529, | ||
| inputTokensDetails: { | ||
| cachedTokens: 0, | ||
| }, | ||
| outputTokens: 3002, | ||
| totalTokens: 7531, | ||
| outputTokensDetails: { | ||
| reasoningTokens: 3000, | ||
| }, | ||
| }, | ||
| temperature: null, | ||
| topP: null, | ||
| presencePenalty: null, | ||
| frequencyPenalty: null, | ||
| metadata: null, | ||
| instructions: null, | ||
| tools: [], | ||
| toolChoice: 'auto', | ||
| parallelToolCalls: false, | ||
| } as models.OpenResponsesResult; | ||
| } | ||
|
|
||
| /** | ||
| * The same cut-off after a parallel batch: three weather calls completed | ||
| * before the budget ran out inside the fourth call. The batch is one plan; | ||
| * running the three would leave the model a result set with a silent hole. | ||
| */ | ||
| function truncatedBatchResponse(): models.OpenResponsesResult { | ||
| return truncatedToolCallResponse([ | ||
| ...[ | ||
| 'Paris', | ||
| 'London', | ||
| 'Tokyo', | ||
| ].map((city, index) => ({ | ||
| type: 'function_call' as const, | ||
| id: `fc_weather_${index}`, | ||
| callId: `call_weather_${index}`, | ||
| name: 'get_weather', | ||
| arguments: JSON.stringify({ | ||
| city, | ||
| }), | ||
| status: 'completed' as const, | ||
| })), | ||
| { | ||
| type: 'function_call', | ||
| id: 'fc_shell', | ||
| callId: 'call_shell', | ||
| name: 'run_shell', | ||
| arguments: '{"commands":', | ||
| status: 'incomplete', | ||
| }, | ||
| ]); | ||
| } | ||
|
|
||
| const client = {} as OpenRouterCore; | ||
|
|
||
| describe('max_output_tokens truncation', () => { | ||
| beforeEach(() => { | ||
| mockBetaResponsesSend.mockReset(); | ||
| }); | ||
|
|
||
| it('extracts no tool calls from a response truncated at max_output_tokens', () => { | ||
| const response = truncatedToolCallResponse(); | ||
|
|
||
| expect(responseHasToolCalls(response)).toBe(false); | ||
| expect(extractToolCallsFromResponse(response)).toEqual([]); | ||
| }); | ||
|
|
||
| it('finalizes on the truncated turn without executing the partial call or requesting again', async () => { | ||
| const executed: unknown[] = []; | ||
| mockBetaResponsesSend.mockResolvedValue({ | ||
| ok: true, | ||
| value: truncatedToolCallResponse(), | ||
| }); | ||
|
|
||
| const result = callModel(client, { | ||
| model: 'test-model', | ||
| input: 'Run echo hello.', | ||
| // Bounds the run so a regression (re-requesting on the exhausted budget) | ||
| // fails on the request count rather than looping until the worker dies. | ||
| stopWhen: stepCountIs(3), | ||
| tools: [ | ||
| { | ||
| type: ToolType.Function, | ||
| function: { | ||
| name: 'run_shell', | ||
| description: 'Run shell commands.', | ||
| inputSchema: z.object({ | ||
| commands: z.array(z.string()), | ||
| }), | ||
| execute: async (params: { commands: string[] }) => { | ||
| executed.push(params); | ||
| return { | ||
| ok: true, | ||
| }; | ||
| }, | ||
| }, | ||
| }, | ||
| ] as const, | ||
| }); | ||
|
|
||
| const response = await result.getResponse(); | ||
|
|
||
| expect(executed).toEqual([]); | ||
| expect(mockBetaResponsesSend).toHaveBeenCalledTimes(1); | ||
| expect(response.id).toBe('resp_truncated'); | ||
| expect(response.status).toBe('incomplete'); | ||
| }); | ||
|
|
||
| it('does not execute the calls that completed before the cut-off either', async () => { | ||
| const executed: unknown[] = []; | ||
| mockBetaResponsesSend.mockResolvedValue({ | ||
| ok: true, | ||
| value: truncatedBatchResponse(), | ||
| }); | ||
|
|
||
| const result = callModel(client, { | ||
| model: 'test-model', | ||
| input: 'Weather in three cities, then run echo hello.', | ||
| stopWhen: stepCountIs(3), | ||
| tools: [ | ||
| { | ||
| type: ToolType.Function, | ||
| function: { | ||
| name: 'get_weather', | ||
| description: 'Get the weather.', | ||
| inputSchema: z.object({ | ||
| city: z.string(), | ||
| }), | ||
| execute: async (params: { city: string }) => { | ||
| executed.push(params); | ||
| return { | ||
| temperature: 22, | ||
| }; | ||
| }, | ||
| }, | ||
| }, | ||
| { | ||
| type: ToolType.Function, | ||
| function: { | ||
| name: 'run_shell', | ||
| description: 'Run shell commands.', | ||
| inputSchema: z.object({ | ||
| commands: z.array(z.string()), | ||
| }), | ||
| execute: async (params: { commands: string[] }) => { | ||
| executed.push(params); | ||
| return { | ||
| ok: true, | ||
| }; | ||
| }, | ||
| }, | ||
| }, | ||
| ] as const, | ||
| }); | ||
|
|
||
| const response = await result.getResponse(); | ||
|
|
||
| expect(executed).toEqual([]); | ||
| expect(mockBetaResponsesSend).toHaveBeenCalledTimes(1); | ||
| expect(response.status).toBe('incomplete'); | ||
| // The caller gets the whole turn, cut-off item included, to resume from. | ||
| expect(response.output.map((item) => ('callId' in item ? item.callId : item.type))).toEqual([ | ||
| 'call_weather_0', | ||
| 'call_weather_1', | ||
| 'call_weather_2', | ||
| 'call_shell', | ||
| ]); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.