-
Notifications
You must be signed in to change notification settings - Fork 75
fix(ai): coalesce adjacent user and toolResult turns for Anthropic #1126
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
code-yeongyu
merged 5 commits into
code-yeongyu:main
from
codeg-dev:fix/anthropic-adjacent-user-tool-result-coalesce
Aug 29, 2026
Merged
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
72f7386
fix(ai): coalesce adjacent user and toolResult turns for Anthropic
codeg-dev 662cc79
docs(changes): track Anthropic user-turn coalescing
codeg-dev 0c7ee98
fix(ai): preserve standalone Anthropic user strings
code-yeongyu a2e234e
test(ai): cover coalesced Anthropic user text
code-yeongyu be7371d
Merge upstream/main into fix/anthropic-adjacent-user-tool-result-coal…
codeg-dev 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
150 changes: 150 additions & 0 deletions
150
packages/ai/test/anthropic-adjacent-user-tool-result-coalesce.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,150 @@ | ||
| import type Anthropic from "@anthropic-ai/sdk"; | ||
| import { Type } from "typebox"; | ||
| import { describe, expect, it } from "vitest"; | ||
| import { getModel } from "../src/compat.ts"; | ||
| import { streamAnthropic } from "../src/providers/anthropic.ts"; | ||
| import { fauxAssistantMessage, fauxToolCall } from "../src/providers/faux.ts"; | ||
| import type { Context, Tool, ToolResultMessage, UserMessage } from "../src/types.ts"; | ||
|
|
||
| type WireBlock = { | ||
| type: string; | ||
| tool_use_id?: string; | ||
| content?: unknown; | ||
| is_error?: boolean; | ||
| text?: string; | ||
| }; | ||
|
|
||
| type WireMessage = { | ||
| role: string; | ||
| content: WireBlock[] | string; | ||
| }; | ||
|
|
||
| type WirePayload = { | ||
| messages: WireMessage[]; | ||
| }; | ||
|
|
||
| function createSseResponse(): Response { | ||
| const events = [ | ||
| [ | ||
| "message_start", | ||
| { type: "message_start", message: { id: "msg_test", usage: { input_tokens: 1, output_tokens: 0 } } }, | ||
| ], | ||
| ["content_block_start", { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }], | ||
| ["content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ok" } }], | ||
| ["content_block_stop", { type: "content_block_stop", index: 0 }], | ||
| ["message_delta", { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } }], | ||
| ["message_stop", { type: "message_stop" }], | ||
| ] as const; | ||
| return new Response(events.map(([event, data]) => `event: ${event}\ndata: ${JSON.stringify(data)}\n`).join("\n"), { | ||
| status: 200, | ||
| headers: { "content-type": "text/event-stream" }, | ||
| }); | ||
| } | ||
|
|
||
| function userMessage(content: string): UserMessage { | ||
| return { role: "user", content, timestamp: Date.now() }; | ||
| } | ||
|
|
||
| function toolResultMessage(toolCallId: string, toolName: string, text = "result"): ToolResultMessage { | ||
| return { | ||
| role: "toolResult", | ||
| toolCallId, | ||
| toolName, | ||
| content: [{ type: "text", text }], | ||
| isError: false, | ||
| timestamp: Date.now(), | ||
| }; | ||
| } | ||
|
|
||
| function makeTool(name: string): Tool { | ||
| return { name, description: name, parameters: Type.Object({}) }; | ||
| } | ||
|
|
||
| describe("Anthropic adjacent user and toolResult coalescence", () => { | ||
| it("coalesces a user message immediately following a toolResult into a single alternating user turn", async () => { | ||
| let captured: WirePayload | undefined; | ||
| const client = { | ||
| messages: { | ||
| create: (params: unknown) => { | ||
| captured = params as WirePayload; | ||
| return { asResponse: async () => createSseResponse() }; | ||
| }, | ||
| }, | ||
| } as Anthropic; | ||
|
|
||
| const context: Context = { | ||
| messages: [ | ||
| userMessage("first prompt"), | ||
| fauxAssistantMessage([fauxToolCall("bash", { command: "ls" }, { id: "toolu_1" })], { | ||
| stopReason: "toolUse", | ||
| }), | ||
| toolResultMessage("toolu_1", "bash", "file1.txt"), | ||
| userMessage("continue after interrupted turn"), | ||
| ], | ||
| tools: [makeTool("bash")], | ||
| }; | ||
|
|
||
| const stream = streamAnthropic(getModel("anthropic", "claude-haiku-4-5"), context, { | ||
| apiKey: "fake-key", | ||
| client, | ||
| }); | ||
| await stream.result(); | ||
|
|
||
| expect(captured).toBeDefined(); | ||
| const messages = captured!.messages; | ||
| expect(messages.map((m) => m.role)).toEqual(["user", "assistant", "user"]); | ||
|
|
||
| const lastUserMsg = messages[2]; | ||
| expect(Array.isArray(lastUserMsg.content)).toBe(true); | ||
| const contentBlocks = lastUserMsg.content as WireBlock[]; | ||
| expect(contentBlocks).toHaveLength(2); | ||
| expect(contentBlocks[0]).toMatchObject({ | ||
| type: "tool_result", | ||
| tool_use_id: "toolu_1", | ||
| }); | ||
| expect(contentBlocks[1]).toMatchObject({ | ||
| type: "text", | ||
| text: "continue after interrupted turn", | ||
| }); | ||
| }); | ||
|
|
||
| it("coalesces consecutive user text messages into a single user turn", async () => { | ||
| let captured: WirePayload | undefined; | ||
| const client = { | ||
| messages: { | ||
| create: (params: unknown) => { | ||
| captured = params as WirePayload; | ||
| return { asResponse: async () => createSseResponse() }; | ||
| }, | ||
| }, | ||
| } as Anthropic; | ||
|
|
||
| const context: Context = { | ||
| messages: [ | ||
| userMessage("hello"), | ||
| userMessage("world"), | ||
| fauxAssistantMessage([{ type: "text", text: "acknowledged" }], { stopReason: "stop" }), | ||
| userMessage("turn 2 part 1"), | ||
| userMessage("turn 2 part 2"), | ||
| ], | ||
| }; | ||
|
|
||
| const stream = streamAnthropic(getModel("anthropic", "claude-haiku-4-5"), context, { | ||
| apiKey: "fake-key", | ||
| client, | ||
| }); | ||
| await stream.result(); | ||
|
|
||
| expect(captured).toBeDefined(); | ||
| const messages = captured!.messages; | ||
| expect(messages.map((m) => m.role)).toEqual(["user", "assistant", "user"]); | ||
|
|
||
| const firstMsg = messages[0]; | ||
| expect(Array.isArray(firstMsg.content)).toBe(true); | ||
| expect((firstMsg.content as WireBlock[]).map((b) => b.text)).toEqual(["hello", "world"]); | ||
|
|
||
| const lastMsg = messages[2]; | ||
| expect(Array.isArray(lastMsg.content)).toBe(true); | ||
| expect((lastMsg.content as WireBlock[]).map((b) => b.text)).toEqual(["turn 2 part 1", "turn 2 part 2"]); | ||
| }); | ||
| }); |
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.