Repository navigation
tools - #1213
tools#1213
Conversation
WalkthroughAdds bidirectional conversion between Anthropic content blocks and OpenAI-style messages (including tool_calls), updates Anthropic agent to use non-mutating response conversion, and integrates converted tool-aware messages into requests; also adds tests and a tools-oriented test agent/workflow. Changes
Sequence Diagram(s)sequenceDiagram
participant Caller as OpenAI-style Caller
participant AnthAgent as AnthropicAgent
participant Conv as Converter
participant Anthropic as Anthropic API
Caller->>AnthAgent: send messages (may include tool_calls)
AnthAgent->>Conv: convOpenAIToolsToAnthropicToolMessage(messages without system)
Conv-->>AnthAgent: Anthropic-formatted content blocks (text / tool_use)
AnthAgent->>Anthropic: send chat request (chatParams)
Anthropic-->>AnthAgent: response (content blocks, may include tool_use)
AnthAgent->>Conv: anthoropicTool2OpenAITool(response)
Conv-->>AnthAgent: OpenAI-style message (role, content, optional tool_calls)
AnthAgent-->>Caller: completion (original messages, choices[0] with converted message, metadata)
sequenceDiagram
participant LLM as Assistant (OpenAI-style)
participant Conv as Converter
participant Tool as Tool Runtime
LLM->>Conv: assistant message with tool_calls
Conv->>Tool: produce Anthropic tool_use blocks / tool executions
Tool-->>Conv: tool results
Conv-->>LLM: Anthropic-compatible content blocks containing tool results
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
llm_agents/anthropic_agent/src/anthropic_agent.ts (2)
86-93: Wrap JSON.parse to avoid hard failures on non-JSON textIf text isn’t valid JSON (or contains trailing commentary), JSON.parse will throw and fail the whole call. Safer to catch and return null.
- const responseFormat = (() => { - if (maybeResponseFormat && text) { - const parsed = JSON.parse(text); - if (typeof parsed === "object" && parsed !== null) { - return parsed; - } - } - return null; - })(); + const responseFormat = (() => { + if (maybeResponseFormat && text) { + try { + const parsed = JSON.parse(text); + if (typeof parsed === "object" && parsed !== null) { + return parsed; + } + } catch { + // ignore parse errors and fall back to null + } + } + return null; + })();
306-308: Fix typo in error message"Anthoropic" → "Anthropic".
- throw new Error("Anthoropic no response"); + throw new Error("Anthropic no response");
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
llm_agents/anthropic_agent/src/anthropic_agent.ts(3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
llm_agents/anthropic_agent/src/anthropic_agent.ts (2)
llm_agents/anthropic_agent/lib/anthropic_agent.js (5)
message(21-21)response(32-32)text(17-17)tool(20-20)messagesCopy(79-79)llm_agents/openai_agent/lib/openai_agent.js (5)
message(34-50)message(215-218)text(29-29)tool(33-33)messagesCopy(87-87)
🔇 Additional comments (1)
llm_agents/anthropic_agent/src/anthropic_agent.ts (1)
232-232: LGTM: Excluding system messages and converting tools before dispatch is correctFiltering out system messages for Anthropic and feeding the converted array is the right call and aligns with Anthropic’s API semantics.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
llm_agents/anthropic_agent/src/anthropic_agent.ts (1)
139-188: Crash risk and invalid Anthropic messages in OpenAI→Anthropic conversion
- Possible crash when handling a "tool" role as the first incoming message (last is undefined on Line 163).
- message.tool_calls can be an empty array; current truthy check emits an assistant message with an empty content array or a text block with undefined text (invalid for Anthropic).
- Unconditionally pushing a text block from message.content (Line 145) can send undefined/empty text.
This was flagged earlier and still applies; implement the hardened logic.
Apply this diff to harden the conversion:
-const convOpenAIToolsToAnthropicToolMessage = (messages: any[]) => { - return messages.reduce((tmp: any[], message: any) => { - if (message.role === "assistant" && message.tool_calls) { - const content: { type: string; text?: string; id?: string; name?: string; input?: unknown }[] = [ - { - type: "text", - text: message.content, - }, - ]; - message.tool_calls.forEach((tool: { id: string; name: string; arguments: unknown }) => { - const { id, name, arguments: args } = tool; - - content.push({ - type: "tool_use", - id, - name, - input: args, - }); - }); - tmp.push({ - role: "assistant", - content, - }); - } else if (message.role === "tool") { - const last = tmp[tmp.length - 1]; - if (last.role === "user" && last.content?.[0]?.type === "tool_result") { - tmp[tmp.length - 1].content.push({ - type: "tool_result", - tool_use_id: message.tool_call_id, - content: message.content, - }); - } else { - tmp.push({ - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: message.tool_call_id, - content: message.content, - }, - ], - }); - } - } else { - tmp.push(message); - } - return tmp; - }, []); -}; +const convOpenAIToolsToAnthropicToolMessage = (messages: any[]) => { + return messages.reduce((tmp: any[], message: any) => { + if (message.role === "assistant" && Array.isArray(message.tool_calls) && message.tool_calls.length > 0) { + const content: { type: string; text?: string; id?: string; name?: string; input?: unknown }[] = []; + + if (typeof message.content === "string" && message.content.length > 0) { + content.push({ type: "text", text: message.content }); + } else if (Array.isArray(message.content)) { + const textParts = message.content + .filter((p: any) => p?.type === "text" && typeof p.text === "string") + .map((p: any) => p.text) + .join(""); + if (textParts.length > 0) { + content.push({ type: "text", text: textParts }); + } + } + + message.tool_calls.forEach((tool: { id: string; name: string; arguments: unknown }) => { + const { id, name, arguments: args } = tool; + content.push({ type: "tool_use", id, name, input: args }); + }); + + if (content.length > 0) { + tmp.push({ role: "assistant", content }); + } + } else if (message.role === "tool") { + const last = tmp[tmp.length - 1]; + if (last && last.role === "user" && last.content?.[0]?.type === "tool_result") { + tmp[tmp.length - 1].content.push({ + type: "tool_result", + tool_use_id: message.tool_call_id, + content: message.content, + }); + } else { + tmp.push({ + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: message.tool_call_id, + content: message.content, + }, + ], + }); + } + } else { + // user/system passthrough (Anthropic accepts string or block array for user/system) + tmp.push(message); + } + return tmp; + }, []); +};
🧹 Nitpick comments (9)
llm_agents/anthropic_agent/src/anthropic_agent.ts (3)
51-75: Robust conversion; fix type guard and consider an alias for the misspelled export name
- The converter correctly concatenates text blocks and maps tool_use blocks to tool_calls. Good.
- Type guard inconsistency: you use Anthropic.ToolUseBlock in convToolCall (Line 44) but Anthropic.Messages.ToolUseBlock here (Line 58). Unify to the same type to avoid TS errors.
- The export name anthoropicTool2OpenAITool has a typo. To avoid churn, keep it, but add a correctly spelled alias export for ergonomics.
Apply this diff to fix the type guard:
- const tool_calls = response.content - .filter((c): c is Anthropic.Messages.ToolUseBlock => c.type === "tool_use") + const tool_calls = response.content + .filter((c): c is Anthropic.ToolUseBlock => c.type === "tool_use") .map((content) => {Outside this hunk, consider adding an alias export:
// Add alongside existing export export const anthropicTool2OpenAITool = anthoropicTool2OpenAITool;Please verify which type namespace is valid for your @anthropic-ai/sdk version and make both sites consistent.
309-311: Typo in error message"Anthoropic no response" → "Anthropic no response".
- throw new Error("Anthoropic no response"); + throw new Error("Anthropic no response");
316-318: Guard JSON.parse on tool_use partials to avoid stream teardownA malformed or partial JSON (edge case) will throw and drop the stream. Safer to try/catch.
- if (streamResponse.content[index].type === "tool_use") { - streamResponse.content[index].input = JSON.parse(partial); - } + if (streamResponse.content[index].type === "tool_use") { + try { + streamResponse.content[index].input = partial ? JSON.parse(partial) : {}; + } catch { + // Fallback to empty object to keep schema valid; optionally log when verbose + streamResponse.content[index].input = {}; + } + }llm_agents/anthropic_agent/tests/test_conv.ts (2)
35-35: Fix test title typo"eturns only text..." → "returns only text...".
-test("eturns only text when no tool_use is mixed in", () => { +test("returns only text when no tool_use is mixed in", () => {
45-49: Add edge-case tests: tool-only responses, non-text-first blocks, and empty contentStrengthen the converter’s guarantees with a few additional cases.
+test("handles tool-only assistant response (no text)", () => { + const response = { + role: "assistant", + content: [{ type: "tool_use", id: "t1", name: "do_it", input: { x: 1 } }], + }; + const result = anthoropicTool2OpenAITool(response as any); + assert.deepStrictEqual(result, { + role: "assistant", + content: "", + tool_calls: [{ id: "t1", name: "do_it", arguments: { x: 1 } }], + }); +}); + +test("concatenates text when first block is not text", () => { + const response = { + role: "assistant", + content: [ + { type: "tool_use", id: "t1", name: "noop", input: {} }, + { type: "text", text: "After tool" }, + ], + }; + const result = anthoropicTool2OpenAITool(response as any); + assert.deepStrictEqual(result, { + role: "assistant", + content: "After tool", + tool_calls: [{ id: "t1", name: "noop", arguments: {} }], + }); +}); + +test("defensively treats empty or undefined text as empty string", () => { + const response = { + role: "assistant", + content: [{ type: "text", text: undefined }], + }; + const result = anthoropicTool2OpenAITool(response as any); + assert.deepStrictEqual(result, { role: "assistant", content: "" }); +});I can also add tests for convOpenAIToolsToAnthropicToolMessage if you want parity across both directions.
llm_agents/anthropic_agent/tests/tools_agent.ts (1)
129-136: Optional: normalize mergedData keys to base agent or function nameCurrently, mergedData keys use the full tool name (e.g., "generalToolAgent--get_weather"). If consumers prefer grouping by agent or function, consider splitting on "--" and using either part as the key.
Example refinement:
- llmToolCalls.forEach((tool, index) => { - const { name } = tool; - ret[name] = data[index]; - }); + llmToolCalls.forEach((tool, index) => { + const [agent, func] = String(tool.name).split("--"); + // Choose your preferred key: agent, func, or `${agent}.${func}` + const key = `${agent}.${func}`; + ret[key] = data[index]; + });llm_agents/anthropic_agent/tests/run_tools.ts (3)
7-9: Enable basic assertionsUncomment the assert import to validate outputs rather than only logging.
-import test from "node:test"; -// import assert from "node:assert"; +import test from "node:test"; +import assert from "node:assert";
139-139: Skip the integration test when ANTHROPIC_API_KEY is not setPrevents CI flakiness and local failures.
-test("test tools 1", async () => { +test("test tools 1", { skip: !process.env.ANTHROPIC_API_KEY }, async () => {
167-175: Add minimal assertions to validate tool-flow behaviorAssert that messages accumulate and that the tool_calls path returns merged results.
- const res = (await graphai.run()) as any; - console.log(JSON.stringify(res, null, 2)); + const res = (await graphai.run()) as any; + assert.ok(res?.tools?.messages?.length >= 2, "should contain user and LLM messages"); + assert.ok(res?.tools?.data, "should include mergedData payload"); + // console.log(JSON.stringify(res, null, 2)); @@ - const res2 = (await graphai2.run()) as any; - console.log(JSON.stringify(res2, null, 2)); + const res2 = (await graphai2.run()) as any; + assert.ok(res2?.tools?.messages?.length > res.tools.messages.length, "follow-up should append messages"); + // console.log(JSON.stringify(res2, null, 2));
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
llm_agents/anthropic_agent/src/anthropic_agent.ts(4 hunks)llm_agents/anthropic_agent/tests/run_tools.ts(1 hunks)llm_agents/anthropic_agent/tests/test_conv.ts(1 hunks)llm_agents/anthropic_agent/tests/tools_agent.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
llm_agents/anthropic_agent/tests/test_conv.ts (1)
llm_agents/anthropic_agent/src/anthropic_agent.ts (1)
anthoropicTool2OpenAITool(51-75)
llm_agents/anthropic_agent/tests/tools_agent.ts (1)
llm_agents/tools_agent/lib/tools_agent.js (2)
toolWorkFlowStep(4-154)toolsAgentInfo(156-208)
llm_agents/anthropic_agent/src/anthropic_agent.ts (2)
llm_agents/anthropic_agent/lib/anthropic_agent.js (5)
response(32-32)tool_calls(19-19)message(21-21)tool(20-20)messagesCopy(79-79)llm_agents/openai_agent/lib/openai_agent.js (5)
tool_calls(32-32)message(34-50)message(215-218)tool(33-33)messagesCopy(87-87)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: build (22.x)
- GitHub Check: build (24.x)
🔇 Additional comments (6)
llm_agents/anthropic_agent/src/anthropic_agent.ts (2)
87-87: Nice: switched to a non-mutating, centralized converterUsing anthoropicTool2OpenAITool(response) to build choices[0].message keeps the code path consistent and avoids mutating input messages. LGTM.
235-235: Confirm message conversion outputs valid Anthropic MessageParam arraysmessages is now derived from convOpenAIToolsToAnthropicToolMessage. With the hardened conversion above, assistant entries will have non-empty content arrays and "tool" results will be embedded under a "user" message as tool_result, matching Anthropic’s schema.
Would you like me to add focused unit tests to validate:
- assistant with only tool_calls (no text),
- first incoming message is a tool_result (no prior messages),
- multiple consecutive tool_results merging,
- assistant content supplied as array parts (OpenAI-style) is normalized?
llm_agents/anthropic_agent/tests/test_conv.ts (2)
5-16: Good coverage: single text block conversionThis verifies role propagation and text extraction. Looks good.
18-33: Good coverage: tool_use → tool_calls mappingThis ensures tool_use blocks are translated correctly and text is preserved.
llm_agents/anthropic_agent/tests/tools_agent.ts (1)
21-26: Passing model and stream via nested params is cleanThreading model and dataStream into the nested LLM call keeps the workflow decoupled. Looks good.
llm_agents/anthropic_agent/tests/run_tools.ts (1)
157-157: Model slug likely invalid; align with known Anthropic model IDs"claude-opus-4-1-20250805" does not match public Anthropic slugs. Use a known-good default (e.g., "claude-3-7-sonnet-20250219") or omit llmModel to use agent default.
- llmModel: "claude-opus-4-1-20250805", + llmModel: "claude-3-7-sonnet-20250219",Alternatively, remove llmModel to test against the agent’s default.
Summary by CodeRabbit
New Features
Bug Fixes
Refactor
Tests