Repository navigation
fix(task): lead each request user message with its tool_result blocks #1839
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
Open
PierrunoYT
wants to merge
5
commits into
Zoo-Code-Org:main
Choose a base branch
from
PierrunoYT:fix/1774-repair-interleaved-tool-results
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
4935751
fix(task): lead each request user message with its tool_result blocks
PierrunoYT e5de8f1
test(task): assert the complete outgoing user content for reordered t…
PierrunoYT 2cfa4b3
fix(task): nest an image that follows a tool_result into that result'…
PierrunoYT ec7057c
Merge remote-tracking branch 'upstream/main' into fix/1774-repair-int…
PierrunoYT 04da4c6
fix(task): keep repaired tool_result images top-level so every provid…
PierrunoYT 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
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
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,184 @@ | ||
| // npx vitest run core/task/__tests__/orderToolResultsFirst.spec.ts | ||
|
|
||
| import type { Anthropic } from "@anthropic-ai/sdk" | ||
|
|
||
| import type { ApiHandler } from "../../../api" | ||
| import { OpenAiCodexHandler } from "../../../api/providers/openai-codex" | ||
| import { convertToAiSdkMessages } from "../../../api/transform/ai-sdk" | ||
| import { maybeRemoveImageBlocks } from "../../../api/transform/image-cleaning" | ||
| import { convertToOpenAiMessages } from "../../../api/transform/openai-format" | ||
| import type { ApiMessage } from "../../task-persistence" | ||
| import { mergeConsecutiveApiMessages } from "../mergeConsecutiveApiMessages" | ||
| import { orderToolResultsFirst } from "../orderToolResultsFirst" | ||
|
|
||
| const toolResult = (id: string, content = `result ${id}`): Anthropic.Messages.ToolResultBlockParam => ({ | ||
| type: "tool_result", | ||
| tool_use_id: id, | ||
| content, | ||
| }) | ||
| const image = (data: string): Anthropic.Messages.ImageBlockParam => ({ | ||
| type: "image", | ||
| source: { type: "base64", media_type: "image/jpeg", data }, | ||
| }) | ||
| const text = (value: string): Anthropic.Messages.TextBlockParam => ({ type: "text", text: value }) | ||
| const nested = (id: string, content: Anthropic.Messages.ToolResultBlockParam["content"]) => ({ | ||
| type: "tool_result" as const, | ||
| tool_use_id: id, | ||
| content, | ||
| }) | ||
|
|
||
| // [tool_result, image, tool_result, text] as saved when read_file on an image ran alongside | ||
| // another tool call in the same turn (#1774). | ||
| const stuckTurn = (): ApiMessage[] => [ | ||
| { | ||
| role: "assistant", | ||
| content: [ | ||
| { type: "tool_use", id: "read", name: "read_file", input: { path: "logo.jpg" } }, | ||
| { type: "tool_use", id: "cmd", name: "execute_command", input: { command: "ls" } }, | ||
| ], | ||
| }, | ||
| { | ||
| role: "user", | ||
| content: [toolResult("read"), image("jpeg"), toolResult("cmd"), text("<environment_details>")], | ||
| }, | ||
| ] | ||
|
|
||
| describe("orderToolResultsFirst", () => { | ||
| it("repairs the persisted #1774 shape so every tool_result leads the message", () => { | ||
| const stuck: ApiMessage = { | ||
| role: "user", | ||
| ts: 16, | ||
| content: [toolResult("read"), image("jpeg"), toolResult("cmd"), text("<environment_details>")], | ||
| } | ||
|
|
||
| const [repaired] = orderToolResultsFirst([stuck]) | ||
|
|
||
| // The results lead; the image stays a top-level block, as live turns store it (#1307). | ||
| expect(repaired.content).toEqual([ | ||
| toolResult("read"), | ||
| toolResult("cmd"), | ||
| image("jpeg"), | ||
| text("<environment_details>"), | ||
| ]) | ||
| expect(repaired.ts).toBe(16) | ||
| // Stored history is untouched. | ||
| expect(stuck.content).toEqual([ | ||
| toolResult("read"), | ||
| image("jpeg"), | ||
| toolResult("cmd"), | ||
| text("<environment_details>"), | ||
| ]) | ||
| }) | ||
|
|
||
| it("keeps the order of results and of other blocks with several interleaved images", () => { | ||
| const [repaired] = orderToolResultsFirst([ | ||
| { | ||
| role: "user", | ||
| content: [toolResult("a"), toolResult("b"), image("1"), toolResult("c"), image("2"), text("t")], | ||
| }, | ||
| ]) | ||
|
|
||
| expect(repaired.content).toEqual([ | ||
| toolResult("a"), | ||
| toolResult("b"), | ||
| toolResult("c"), | ||
| image("1"), | ||
| image("2"), | ||
| text("t"), | ||
| ]) | ||
| }) | ||
|
|
||
| it("leaves the content of every result block untouched", () => { | ||
| const withArray = nested("a", [text("first"), text("second")]) | ||
|
|
||
| const [repaired] = orderToolResultsFirst([{ role: "user", content: [withArray, image("1"), toolResult("b")] }]) | ||
|
|
||
| expect(repaired.content).toEqual([withArray, toolResult("b"), image("1")]) | ||
| expect(withArray.content).toEqual([text("first"), text("second")]) | ||
| }) | ||
|
|
||
| it("moves leading and mid-message blocks after the results in their original order", () => { | ||
| const [repaired] = orderToolResultsFirst([ | ||
| { | ||
| role: "user", | ||
| content: [image("lead"), toolResult("a"), text("note"), image("after-text"), toolResult("b")], | ||
| }, | ||
| ]) | ||
|
|
||
| expect(repaired.content).toEqual([ | ||
| toolResult("a"), | ||
| toolResult("b"), | ||
| image("lead"), | ||
| text("note"), | ||
| image("after-text"), | ||
| ]) | ||
| }) | ||
|
|
||
| it("repairs interleaving introduced by merging consecutive user messages", () => { | ||
| const merged = mergeConsecutiveApiMessages([ | ||
| { role: "user", content: [toolResult("a"), text("note")] }, | ||
| { role: "user", content: [toolResult("b")] }, | ||
| ]) | ||
|
|
||
| expect(orderToolResultsFirst(merged)[0].content).toEqual([toolResult("a"), toolResult("b"), text("note")]) | ||
| }) | ||
|
|
||
| it("returns already-ordered, string, and assistant messages unchanged", () => { | ||
| const ordered: ApiMessage = { role: "user", content: [toolResult("a"), image("1"), text("t")] } | ||
| const plain: ApiMessage = { role: "user", content: "hello" } | ||
| const noResults: ApiMessage = { role: "user", content: [text("a"), image("1")] } | ||
| const assistant: ApiMessage = { role: "assistant", content: [text("a")] } | ||
|
|
||
| const out = orderToolResultsFirst([ordered, plain, noResults, assistant]) | ||
|
|
||
| out.forEach((message, index) => expect(message).toBe([ordered, plain, noResults, assistant][index])) | ||
| }) | ||
|
|
||
| describe("repaired images reach the provider request", () => { | ||
| const dataUrl = "data:image/jpeg;base64,jpeg" | ||
|
|
||
| it("OpenAI chat format sends the image as an image_url part", () => { | ||
| const converted = convertToOpenAiMessages(orderToolResultsFirst(stuckTurn())) | ||
|
|
||
| expect(converted.map((message) => message.role)).toEqual(["assistant", "tool", "tool", "user"]) | ||
| expect(converted.at(-1)?.content).toContainEqual({ type: "image_url", image_url: { url: dataUrl } }) | ||
| }) | ||
|
|
||
| it("AI SDK format sends the image as an image part", () => { | ||
| const converted = convertToAiSdkMessages(orderToolResultsFirst(stuckTurn())) | ||
| const user = converted.find((message) => message.role === "user") | ||
|
|
||
| expect(user?.content).toContainEqual({ type: "image", image: dataUrl, mimeType: "image/jpeg" }) | ||
| }) | ||
|
|
||
| it("OpenAI Codex Responses input sends the image as an input_image part", () => { | ||
| const handler = new OpenAiCodexHandler({ apiModelId: "gpt-5.1-codex" }) | ||
| const input: unknown[] = handler["formatFullConversation"]("", orderToolResultsFirst(stuckTurn())) | ||
|
|
||
| expect(input).toContainEqual({ | ||
| role: "user", | ||
| content: [ | ||
| { type: "input_image", image_url: dataUrl }, | ||
| { type: "input_text", text: "<environment_details>" }, | ||
| ], | ||
| }) | ||
| }) | ||
|
|
||
| it("a model without image support gets no image block anywhere in the request", () => { | ||
| const textOnly: ApiHandler = { | ||
| getModel: vi.fn().mockReturnValue({ id: "text-only", info: { supportsImages: false } }), | ||
| createMessage: vi.fn(), | ||
| countTokens: vi.fn(), | ||
| getModelCacheScope: vi.fn(), | ||
| } | ||
| const [, user] = maybeRemoveImageBlocks(orderToolResultsFirst(stuckTurn()), textOnly) | ||
|
|
||
| expect(user.content).toEqual([ | ||
| toolResult("read"), | ||
| toolResult("cmd"), | ||
| text("[Referenced image in conversation]"), | ||
| text("<environment_details>"), | ||
| ]) | ||
| }) | ||
| }) | ||
| }) |
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,33 @@ | ||
| import type { ApiMessage } from "../task-persistence" | ||
|
|
||
| /** | ||
| * Moves `tool_result` blocks to the front of each user message, keeping the relative order of | ||
| * the results and of the remaining blocks (images, text). This is the same partition | ||
| * `Task.pushToolResultToUserContent` applies to live turns (#1307), so repaired history has the | ||
| * shape every provider converter already handles: images stay top-level blocks after the results, | ||
| * where image-capable converters forward them and `maybeRemoveImageBlocks` can strip them. | ||
| * | ||
| * Anthropic requires the results for the previous turn's `tool_use` blocks to lead the next user | ||
| * message. History saved with image blocks between results (#1307, #1774), or produced by merging | ||
| * consecutive user messages, is otherwise rejected with a 400 on every retry. | ||
| * | ||
| * Used for *API request shaping only* (do not use for storage). Messages already in order are | ||
| * returned unchanged. | ||
| */ | ||
| export function orderToolResultsFirst(messages: ApiMessage[]): ApiMessage[] { | ||
| return messages.map((message) => { | ||
| if (message.role !== "user" || !Array.isArray(message.content)) { | ||
|
Check warning on line 19 in src/core/task/orderToolResultsFirst.ts
|
||
| return message | ||
| } | ||
| const firstOther = message.content.findIndex((block) => block.type !== "tool_result") | ||
| const hasLaterResult = | ||
| firstOther !== -1 && message.content.slice(firstOther).some((block) => block.type === "tool_result") | ||
|
Check warning on line 24 in src/core/task/orderToolResultsFirst.ts
|
||
| if (!hasLaterResult) { | ||
| return message | ||
| } | ||
|
|
||
| const results = message.content.filter((block) => block.type === "tool_result") | ||
| const rest = message.content.filter((block) => block.type !== "tool_result") | ||
| return { ...message, content: [...results, ...rest] } | ||
| }) | ||
| } | ||
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.