Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 46 additions & 9 deletions src/llm/anthropic/utils/message_inputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -645,13 +645,21 @@ const standardContentBlockConverter: StandardContentBlockConverter<{
};

function _formatContent(message: BaseMessage) {
const serverToolResultTypes = [
'web_search_tool_result',
'code_execution_tool_result',
'web_fetch_tool_result',
'bash_code_execution_tool_result',
'text_editor_code_execution_tool_result',
'tool_search_tool_result',
];
const toolTypes = [
'tool_use',
'tool_result',
'input_json_delta',
'server_tool_use',
'web_search_tool_result',
'web_search_result',
...serverToolResultTypes,
];
const textTypes = ['text', 'text_delta'];
/**
Expand Down Expand Up @@ -691,19 +699,24 @@ function _formatContent(message: BaseMessage) {
'name' in contentPart
) {
const rawPart = contentPart as Record<string, unknown>;
const corrected: AnthropicServerToolUseBlockParam = {
const corrected: Record<string, unknown> = {
type: 'server_tool_use',
id: rawPart.id as string,
name: (rawPart.name ?? 'web_search') as 'web_search',
name: (rawPart.name ?? 'web_search') as string,
input: coerceAnthropicToolUseInput(rawPart.input ?? rawPart.args),
};
return corrected;
if (rawPart.caller !== undefined) {
corrected.caller = rawPart.caller;
}
return corrected as unknown as AnthropicServerToolUseBlockParam;
}

/**
* Normalize web_search_tool_result blocks into a clean shape.
* Same rationale as above — the block may carry extra properties from
* streaming (input, index, etc.) that the API rejects. Rebuild cleanly.
* Normalize Anthropic server tool result blocks (`web_search_tool_result`,
* `code_execution_tool_result`, `web_fetch_tool_result`, etc.) into a clean
* shape. These blocks may carry extra properties from streaming (`index`,
* `input`, etc.) that the API rejects, while `caller` must be preserved
* for nested server tool calls (e.g. `web_search_20260209`).
*/
if (
'tool_use_id' in contentPart &&
Expand All @@ -715,7 +728,28 @@ function _formatContent(message: BaseMessage) {
'content' in contentPart
) {
const rawPart = contentPart as Record<string, unknown>;
const rawType = typeof rawPart.type === 'string' ? rawPart.type : undefined;
const content = rawPart.content;

if (
rawType !== undefined &&
rawType !== 'web_search_tool_result' &&
serverToolResultTypes.includes(rawType)
) {
if (content == null) {
return null;
}
const corrected: Record<string, unknown> = {
type: rawType,
tool_use_id: rawPart.tool_use_id as string,
content,
};
if (rawPart.caller !== undefined) {
corrected.caller = rawPart.caller;
}
return corrected as unknown as AnthropicWebSearchToolResultBlockParam;
}

const isValidContent =
Array.isArray(content) ||
(content != null &&
Expand All @@ -725,13 +759,16 @@ function _formatContent(message: BaseMessage) {
'web_search_tool_result_error');

if (isValidContent) {
const corrected: AnthropicWebSearchToolResultBlockParam = {
const corrected: Record<string, unknown> = {
type: 'web_search_tool_result',
tool_use_id: rawPart.tool_use_id as string,
content:
content as AnthropicWebSearchToolResultBlockParam['content'],
};
return corrected;
if (rawPart.caller !== undefined) {
corrected.caller = rawPart.caller;
}
return corrected as unknown as AnthropicWebSearchToolResultBlockParam;
}
return null;
}
Expand Down
5 changes: 5 additions & 0 deletions src/llm/anthropic/utils/message_outputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ export function _makeMessageChunkFromAnthropicEvent(
'document',
'server_tool_use',
'web_search_tool_result',
'code_execution_tool_result',
'web_fetch_tool_result',
'bash_code_execution_tool_result',
'text_editor_code_execution_tool_result',
'tool_search_tool_result',
].includes(data.content_block.type)
) {
const contentBlock = data.content_block;
Expand Down
136 changes: 136 additions & 0 deletions src/llm/anthropic/utils/server-tool-inputs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { AIMessage, HumanMessage, ToolMessage } from '@langchain/core/messages';
import type { BaseMessage } from '@langchain/core/messages';
import { _convertMessagesToAnthropicPayload } from './message_inputs';
import { _makeMessageChunkFromAnthropicEvent } from './message_outputs';

type AnthropicTestBlock = {
id?: unknown;
Expand Down Expand Up @@ -505,4 +506,139 @@ describe('_convertMessagesToAnthropicPayload — server tool use (web search) mu
expect(textBlocks[0].text).toBe('Here are the results.');
}
);

it('preserves code_execution_tool_result in stream chunks and replays caller/code_execution_tool_result for web_search_20260209', () => {
const codeExecResultEvent = {
type: 'content_block_start',
index: 3,
content_block: {
type: 'code_execution_tool_result',
tool_use_id: 'srvtoolu_code_1',
content: {
type: 'code_execution_result',
stdout: 'filtered results',
stderr: '',
return_code: 0,
},
},
} as any;

const streamed = _makeMessageChunkFromAnthropicEvent(codeExecResultEvent, {
streamUsage: false,
coerceContentToString: false,
});
expect(streamed).not.toBeNull();
const streamedBlocks = streamed!.chunk.content as any[];
expect(streamedBlocks).toHaveLength(1);
expect(streamedBlocks[0]).toMatchObject({
type: 'code_execution_tool_result',
tool_use_id: 'srvtoolu_code_1',
content: {
type: 'code_execution_result',
stdout: 'filtered results',
stderr: '',
return_code: 0,
},
});

const caller = {
type: 'code_execution_20260120',
tool_id: 'srvtoolu_code_1',
};
const messageHistory: BaseMessage[] = [
new HumanMessage('search with dynamic filtering'),
new AIMessage({
content: [
{
type: 'server_tool_use',
id: 'srvtoolu_code_1',
name: 'code_execution',
input: { code: 'print(1)' },
index: 0,
},
{
type: 'server_tool_use',
id: 'srvtoolu_search_1',
name: 'web_search',
input: { query: 'test' },
caller,
index: 1,
},
{
type: 'web_search_tool_result',
tool_use_id: 'srvtoolu_search_1',
caller,
index: 2,
input: undefined,
content: [
{
type: 'web_search_result',
url: 'https://example.com',
title: 'Example',
encrypted_content: 'enc',
page_age: '1d',
},
],
},
{
type: 'code_execution_tool_result',
tool_use_id: 'srvtoolu_code_1',
index: 3,
input: undefined,
content: {
type: 'code_execution_result',
stdout: 'filtered results',
stderr: '',
return_code: 0,
},
},
{ type: 'text', text: 'Done.' },
],
}),
new HumanMessage('next turn'),
];

const { messages } = _convertMessagesToAnthropicPayload(messageHistory);
const assistantContent = messages[1].content as any[];

expect(assistantContent).toHaveLength(5);
expect(assistantContent[0]).toEqual({
type: 'server_tool_use',
id: 'srvtoolu_code_1',
name: 'code_execution',
input: { code: 'print(1)' },
});
expect(assistantContent[1]).toEqual({
type: 'server_tool_use',
id: 'srvtoolu_search_1',
name: 'web_search',
input: { query: 'test' },
caller,
});
expect(assistantContent[2]).toEqual({
type: 'web_search_tool_result',
tool_use_id: 'srvtoolu_search_1',
caller,
content: [
{
type: 'web_search_result',
url: 'https://example.com',
title: 'Example',
encrypted_content: 'enc',
page_age: '1d',
},
],
});
expect(assistantContent[3]).toEqual({
type: 'code_execution_tool_result',
tool_use_id: 'srvtoolu_code_1',
content: {
type: 'code_execution_result',
stdout: 'filtered results',
stderr: '',
return_code: 0,
},
});
expect(assistantContent[4]).toEqual({ type: 'text', text: 'Done.' });
});
});