Skip to content

tools - #1213

Merged
isamu merged 4 commits into
receptron:mainfrom
isamu:anthropicTools
Aug 17, 2025
Merged

tools#1213
isamu merged 4 commits into
receptron:mainfrom
isamu:anthropicTools

Conversation

@isamu

@isamu isamu commented Aug 17, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Round-trip tool usage between Anthropic and OpenAI-style messages, enabling tool_calls to be preserved and merged into assistant messages.
  • Bug Fixes

    • Stops mutating input messages during conversion and improves reliability of tool output handling.
  • Refactor

    • Agent flow now converts and feeds only relevant messages to Anthropic; minor prompt formatting cleanup.
  • Tests

    • Added tool-driven and converter unit tests plus sample tool workflows to validate multi-turn tool interactions.

@coderabbitai

coderabbitai Bot commented Aug 17, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds 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

Cohort / File(s) Summary
Anthropic agent core
llm_agents/anthropic_agent/src/anthropic_agent.ts
Adds anthoropicTool2OpenAITool(response) to convert Anthropic content/tool_use blocks to OpenAI-style message objects (role, content, optional tool_calls); adds convOpenAIToolsToAnthropicToolMessage to map OpenAI messages (with tool_calls) into Anthropic-format content blocks; rewrites convertOpenAIChatCompletion to avoid mutating input messages and to use the new conversion functions; updates agent request assembly to feed converted non-system messages to Anthropic.
Unit tests for conversion
llm_agents/anthropic_agent/tests/test_conv.ts
New unit tests validating Anthropic→OpenAI conversion behavior: text block concatenation, extraction/expansion of tool_use → tool_calls, and cases without tool_use.
Integration/tool tests
llm_agents/anthropic_agent/tests/run_tools.ts
New integration-style test that defines five tool descriptors, a mock tools agent, and runs two sequential GraphAI runs using the Anthropic agent to exercise tool invocation and message/response flow (logs results; placeholder assertions). Exports tools constant.
Tools orchestration agent
llm_agents/anthropic_agent/tests/tools_agent.ts
New GraphAI nested workflow (toolsAgent) that orchestrates LLM calls with tools, maps tool_calls to per-tool executions, collects tool responses, reinvokes LLM with merged tool results, and exports toolsAgentInfo (default export) describing the agent and samples.

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)
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • update openai #1190 — Overlaps in converting/parsing tool_calls and changes to chat completion conversion logic.

Poem

I nibble code like clover leaves,
Turning blocks to calls beneath my eaves.
From Anthropic hops to OpenAI tunes,
I stitch the messages under the moons.
A rabbit maps each tool and thread —
Hooray! The conversation's fed. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 text

If 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.

📥 Commits

Reviewing files that changed from the base of the PR and between a62e0ab and c01a213.

📒 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 correct

Filtering out system messages for Anthropic and feeding the converted array is the right call and aligns with Anthropic’s API semantics.

@isamu
isamu merged commit f9f84fd into receptron:main Aug 17, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 teardown

A 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 content

Strengthen 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 name

Currently, 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 assertions

Uncomment 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 set

Prevents 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 behavior

Assert 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.

📥 Commits

Reviewing files that changed from the base of the PR and between c01a213 and 3ef730b.

📒 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 converter

Using 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 arrays

messages 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 conversion

This verifies role propagation and text extraction. Looks good.


18-33: Good coverage: tool_use → tool_calls mapping

This 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 clean

Threading 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant