Skip to content

Refactor anthropic - #1218

Merged
isamu merged 18 commits into
receptron:mainfrom
isamu:refactorAnthropic
Aug 18, 2025
Merged

isamu merged 18 commits into
receptron:mainfrom
isamu:refactorAnthropic

Conversation

@isamu

@isamu isamu commented Aug 18, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features
    • No user-visible feature changes.
  • Refactor
    • Centralized tool/message conversion into shared utilities and simplified the public API surface without altering core behavior.
  • Tests
    • Expanded coverage for bidirectional tool-call conversions, including handling of missing input and invalid JSON.
  • Chores
    • Bumped package versions across multiple modules and updated related dependencies.

@coderabbitai

coderabbitai Bot commented Aug 18, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@isamu has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 8 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 5e2be5f and 6ffeed5.

📒 Files selected for processing (8)
  • agents/agent_utils/package.json (1 hunks)
  • agents/llm_agents/package.json (2 hunks)
  • agents/vanilla_agents/package.json (2 hunks)
  • agents/vanilla_node_agents/package.json (2 hunks)
  • llm_agents/anthropic_agent/package.json (1 hunks)
  • packages/agents/package.json (2 hunks)
  • packages/cli/package.json (2 hunks)
  • packages/test_utils/package.json (2 hunks)

Walkthrough

Centralizes Anthropic↔OpenAI tool/message conversion into a new utils module, updates the Anthropic agent source to consume these utilities, removes prior exports from the agent module, adjusts type declarations and compiled JS accordingly, updates tests to import from utils, and bumps versions in several package.json files.

Changes

Cohort / File(s) Summary of changes
Anthropic agent source refactor
llm_agents/anthropic_agent/src/anthropic_agent.ts
Replaced in-file conversion logic with imports from ./utils; removed local Response and converter exports; continued local convToolCall helper usage.
New conversion utilities
llm_agents/anthropic_agent/src/utils.ts
Added utilities and types for Anthropic↔OpenAI conversion: Response type, anthoropicToolCall2OpenAIToolCall, openAIToolCall2AnthropicToolCall, anthoropicTool2OpenAITool, convOpenAIToolsToAnthropicToolMessage.
Built artifacts (JS + d.ts)
llm_agents/anthropic_agent/lib/anthropic_agent.js, llm_agents/anthropic_agent/lib/anthropic_agent.d.ts
JS now imports and uses ./utils; removed exports for former converters. d.ts drops corresponding declarations.
Tests updated
llm_agents/anthropic_agent/tests/test_conv.ts, llm_agents/anthropic_agent/tests/test_conv_messages.ts
Tests now import conversion utilities from ../src/utils; added tests for bidirectional tool-call conversion and edge cases.
Version bumps: agent utils
agents/agent_utils/package.json
Version 2.0.2 → 2.0.3.
Version/deps: vanilla agents
agents/vanilla_agents/package.json
Version 2.0.10 → 2.0.11; dependency @graphai/agent_utils ^2.0.2 → ^2.0.3.
Version/deps: vanilla node agents
agents/vanilla_node_agents/package.json
Version 2.0.1 → 2.0.2; devDependency @graphai/agent_utils ^2.0.2 → ^2.0.3.
Version/deps: test utils
packages/test_utils/package.json
Version 2.0.1 → 2.0.2; devDeps @graphai/vanilla ^2.0.10 → ^2.0.11, graphai ^2.0.13 → ^2.0.14.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant anthropicAgent
  participant Utils as Utils (./utils)
  participant AnthropicAPI as Anthropic API

  Client->>anthropicAgent: messages (OpenAI format)
  anthropicAgent->>Utils: convOpenAIToolsToAnthropicToolMessage(messages)
  Utils-->>anthropicAgent: messages (Anthropic format)
  anthropicAgent->>AnthropicAPI: createMessage(params)
  AnthropicAPI-->>anthropicAgent: response (Anthropic)
  anthropicAgent->>Utils: anthoropicTool2OpenAITool(response)
  Utils-->>anthropicAgent: assistant message (OpenAI style)
  anthropicAgent-->>Client: result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • llmModel #1214 — Touches the same convOpenAIToolsToAnthropicToolMessage logic, adding safety checks that intersect with this refactor.
  • @graphai/anthropic [email protected] #1215 — Modifies Anthropic↔OpenAI conversion utilities, overlapping with the utilities introduced here.
  • Play ground #1216 — Adjusts tool-call conversions to function-style with robust JSON handling, aligning with the new utils’ behavior.

Poem

A whisk of code, a hop to utils’ glen,
We moved the gears, then bound them up again.
Tools now converse across the forest line,
JSON blossoms, arguments align.
I twitch my nose—refactor neat—
Fewer exports, cleaner feet. 🐇✨

✨ Finishing Touches
🧪 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: 1

🧹 Nitpick comments (9)
agents/agent_utils/lib/type.d.ts (1)

52-56: Consider narrowing type and clarifying function.arguments shape

Right now type is a plain string and function.arguments is unknown. Given our current usage, you can improve type-safety:

  • type is always "function" for OpenAI-style tool calls.
  • arguments is serialized JSON (string) in our produced payloads.

This helps catch accidental misuse at compile time.

Apply this diff:

-export type GraphAIToolPayload = {
-    id: string;
-    type: string;
-    function: {
-        name: string;
-        arguments?: unknown;
-    };
-};
+export type GraphAIToolPayload = {
+    id: string;
+    type: "function";
+    function: {
+        name: string;
+        arguments?: string;
+    };
+};

If you need to support both string and object for arguments, consider a union instead of unknown:

-        arguments?: unknown;
+        arguments?: string | Record<string, unknown>;
agents/agent_utils/src/type.ts (1)

55-55: Strengthen typing for GraphAIToolPayload

For better safety and editor DX, consider aligning with a literal type for type and a clearer arguments shape, mirroring the lib suggestion. This will prevent accidental non-function tool types slipping in.

Apply this diff:

-export type GraphAIToolPayload = { id: string; type: string; function: { name: string; arguments?: unknown } };
+export type GraphAIToolPayload = {
+  id: string;
+  type: "function";
+  function: {
+    name: string;
+    arguments?: string; // or: string | Record<string, unknown>
+  };
+};

Optionally, export this type from a single source-of-truth (src) and generate lib/type.d.ts during build to avoid drift.

llm_agents/anthropic_agent/src/anthropic_agent.ts (7)

46-62: Good conversion helper; fix naming typo (“anthoropic” → “anthropic”)

The conversion logic is solid. The function name has a typo which propagates to call sites.

Apply this diff:

-const anthoropicToolCall2OpenAIToolCall = (toolCall: Anthropic.Messages.ToolUseBlock): GraphAIToolPayload => {
+const anthropicToolCall2OpenAIToolCall = (toolCall: Anthropic.Messages.ToolUseBlock): GraphAIToolPayload => {

And update references (see lines 70 and 89).
Additionally, consider returning a literal type for type to match our GraphAIToolPayload suggestion:

-    type: "function",
+    type: "function" as const,

70-70: Update call-site after rename

Keep the call-site aligned with the corrected helper name.

Apply this diff:

-  const tool_calls = response.content.filter((c): c is Anthropic.Messages.ToolUseBlock => c.type === "tool_use").map(anthoropicToolCall2OpenAIToolCall);
+  const tool_calls = response.content
+    .filter((c): c is Anthropic.Messages.ToolUseBlock => c.type === "tool_use")
+    .map(anthropicToolCall2OpenAIToolCall);

89-89: Update call-site after rename

Same rename should be applied here.

Apply this diff:

-  const tool_calls = functionResponses.map(anthoropicToolCall2OpenAIToolCall);
+  const tool_calls = functionResponses.map(anthropicToolCall2OpenAIToolCall);

144-144: Narrow TOOLS_CONTENT to precise discriminated union

Using a discriminated union tightens types and improves autocomplete and exhaustiveness checks.

Apply this diff:

-type TOOLS_CONTENT = { type: string; text?: string; id?: string; name?: string; input?: unknown };
+type TOOLS_CONTENT =
+  | { type: "text"; text: string }
+  | { type: "tool_use"; id: string; name: string; input: unknown };

146-162: Support both string and object arguments when converting back to Anthropic

GraphAIToolPayload.function.arguments is typed as unknown in agent_utils. If a producer passes an object (not a JSON string), JSON.parse will throw and you’ll silently return {}. Handle both shapes to avoid losing tool inputs.

Apply this diff:

-const openAIToolCall2AnthropicToolCall = (tool: { id: string; function: { name: string; arguments: string } }) => {
-  const { id, function: func } = tool;
-  const { name, arguments: args } = func ?? {};
+const openAIToolCall2AnthropicToolCall = (tool: { id: string; function: { name: string; arguments?: unknown } }) => {
+  const { id, function: func } = tool;
+  const { name, arguments: args } = func ?? {};
   return {
     type: "tool_use",
     id,
     name,
-    input: (() => {
-      try {
-        return JSON.parse(args ?? "{}");
-      } catch (__e) {
-        return {};
-      }
-    })(),
+    input: (() => {
+      if (typeof args === "string") {
+        try {
+          return JSON.parse(args);
+        } catch {
+          return {};
+        }
+      }
+      if (args && typeof args === "object") {
+        return args;
+      }
+      return {};
+    })(),
   };
};

If you adopt the earlier type narrowing (arguments?: string | Record<string, unknown>), update the parameter type accordingly.


167-175: Minor: simplify push by spreading mapped array

Style nit only. You can avoid the intermediate forEach.

Apply this diff:

-      message.tool_calls.map(openAIToolCall2AnthropicToolCall).forEach((data: TOOLS_CONTENT) => {
-        content.push(data);
-      });
+      content.push(...message.tool_calls.map(openAIToolCall2AnthropicToolCall));

64-79: Avoid recomputing tool_calls

You compute tool_calls twice (once via anthropicTool2OpenAITool, again in convertOpenAIChatCompletion). You can reuse the earlier result.

One approach:

-  const functionResponses = response.content.filter((content) => content.type === "tool_use") ?? [];
-  const tool_calls = functionResponses.map(anthropicToolCall2OpenAIToolCall);
+  const tool_calls = (Array.isArray((message as any).tool_calls) ? (message as any).tool_calls : []) as GraphAIToolPayload[];

Also applies to: 89-91

📜 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 b9fabd8 and 283c0f5.

📒 Files selected for processing (3)
  • agents/agent_utils/lib/type.d.ts (1 hunks)
  • agents/agent_utils/src/type.ts (1 hunks)
  • llm_agents/anthropic_agent/src/anthropic_agent.ts (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
agents/agent_utils/src/type.ts (1)
agents/agent_utils/lib/type.d.ts (1)
  • GraphAIToolPayload (50-57)
llm_agents/anthropic_agent/src/anthropic_agent.ts (2)
agents/agent_utils/src/type.ts (1)
  • GraphAIToolPayload (55-55)
llm_agents/anthropic_agent/lib/anthropic_agent.js (8)
  • anthoropicTool2OpenAITool (13-46)
  • response (66-66)
  • contentText (14-17)
  • tool_calls (18-37)
  • tool_calls (54-54)
  • tool (55-55)
  • convOpenAIToolsToAnthropicToolMessage (104-162)
  • message (56-56)
🔇 Additional comments (2)
agents/agent_utils/lib/type.d.ts (1)

52-56: Lib/src alignment check looks good

This declaration matches the updated shape used in agents/agent_utils/src/type.ts. Thanks for keeping lib and src consistent.

llm_agents/anthropic_agent/src/anthropic_agent.ts (1)

14-14: Type re-exports are correct and consistent

Importing GraphAIToolPayload alongside the other GraphAI types is consistent with the refactor and keeps the conversions typed.

Comment on lines +46 to +62
const anthoropicToolCall2OpenAIToolCall = (toolCall: Anthropic.Messages.ToolUseBlock): GraphAIToolPayload => {
const { id, name, input } = toolCall;
return {
id,
type: "function",
function: {
name,
arguments: (() => {
try {
return JSON.stringify(input ?? {});
} catch (__e) {
return "{}";
}
})(),
},
};
};

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.

⚠️ Potential issue

Also fix the “Anthoropic” typo in the thrown error message

The error string surfaced to users has the same typo.

Change outside the selected lines:

-    throw new Error("Anthoropic no response");
+    throw new Error("Anthropic stream returned no response");

Optionally, rename the other helper as well for consistency:

-export const anthoropicTool2OpenAITool = (response: Response) => {
+export const anthropicTool2OpenAITool = (response: Response) => {

And its usages:

-  const message = anthoropicTool2OpenAITool(response);
+  const message = anthropicTool2OpenAITool(response);

Also applies to: 70-70, 89-89

@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

🔭 Outside diff range comments (2)
llm_agents/gemini_agent/lib/gemini_agent.js (1)

17-28: Generate stable, unique tool_call IDs and normalize arguments shape

  • id: "dummy" will duplicate across multiple function calls and break correlation with tool results. Generate a stable unique id per call (e.g., call_0, call_1).
  • Consider normalizing function.arguments to a JSON string for consistency with OpenAI-style payloads and with the Anthropic conversion utilities elsewhere in the repo.

Apply this diff:

-    ? calls.map((call) => {
-            return {
-                id: "dummy",
-                type: "function",
-                function: {
-                    name: call.name,
-                    arguments: call.args,
-                }
-            };
-        })
+    ? calls.map((call, idx) => {
+            return {
+                id: `call_${idx}`,
+                type: "function",
+                function: {
+                    name: call.name,
+                    arguments: JSON.stringify(call.args ?? {}),
+                }
+            };
+        })
         : [];

Additionally, for downstream compatibility, consider aligning message.tool_calls to include id and type as well (outside this hunk), since many OpenAI-compatible consumers expect { id, type: "function", function: {...} } in choices[0].message.tool_calls.

llm_agents/anthropic_agent/src/anthropic_agent.ts (1)

59-66: Wrap JSON.parse in try/catch to avoid runtime crashes

When response_format is requested, model outputs may still be non-JSON or partially valid. Uncaught JSON.parse will throw and break the request.

Apply this diff:

-  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 (_e) {
+        // fall through
+      }
+    }
+    return null;
+  })();
♻️ Duplicate comments (4)
llm_agents/anthropic_agent/tests/test_conv.ts (1)

1-1: Rename “anthoropic” to “anthropic” (consistent naming)

Function names and imports are misspelled. Prefer “anthropic” consistently across the codebase. Consider keeping a deprecated alias for backward compatibility if these are public exports.

Possible follow-up (rename + alias to avoid breakage):

-import { anthoropicTool2OpenAITool, anthoropicToolCall2OpenAIToolCall, openAIToolCall2AnthropicToolCall } from "../src/utils";
+import {
+  anthropicTool2OpenAITool,
+  anthropicToolCall2OpenAIToolCall,
+  openAIToolCall2AnthropicToolCall,
+  // Backward-compat aliases if still exported
+  // anthoropicTool2OpenAITool,
+  // anthoropicToolCall2OpenAIToolCall,
+} from "../src/utils";
llm_agents/anthropic_agent/src/anthropic_agent.ts (2)

16-17: Good centralization to utils; consider correcting “anthoropic” naming

Importing conversions from utils is the right direction. Please fix the “anthoropic” typo in exported helper names for consistency, ideally by introducing correctly spelled exports with backward-compat aliases.

Example change (in utils.ts):

// Keep existing anthoropic* exports, but also add:
export const anthropicTool2OpenAITool = anthoropicTool2OpenAITool;
export const anthropicToolCall2OpenAIToolCall = anthoropicToolCall2OpenAIToolCall;

229-231: Fix typo and improve error clarity

Error message contains “Anthoropic” typo and is vague.

[ suggest_nitpick ]

Apply this diff:

-    throw new Error("Anthoropic no response");
+    throw new Error("Anthropic stream returned no response");
llm_agents/anthropic_agent/lib/anthropic_agent.js (1)

174-175: Fix typo and improve error clarity

Same typo as in the TS source.

Apply this diff:

-        throw new Error("Anthoropic no response");
+        throw new Error("Anthropic stream returned no response");
🧹 Nitpick comments (9)
llm_agents/anthropic_agent/tests/test_conv_messages.ts (1)

153-191: Add a test case for the nested tool_calls shape with type discriminator.

Current fixture covers legacy OpenAI-style tool_calls (no type, JSON-stringified arguments). Add another test where tool_calls entries use the new nested shape: { id, type: "function", function: { name, arguments: object } }. This ensures convOpenAIToolsToAnthropicToolMessage handles both inputs.

If helpful, I can draft the additional test case.

llm_agents/gemini_agent/src/gemini_agent.ts (2)

41-46: Prefer stronger typing for message and unify shapes.

message is typed as any. Consider typing as a GraphAILlmMessage-compatible shape to surface type errors early. Also consider including type: "function" in message.tool_calls for parity with OpenAI’s response shape (optional).

Example:

type OpenAIToolCall = { id?: string; type?: "function"; function: { name: string; arguments: string } };
const message: { role: "assistant"; content: string; tool_calls?: OpenAIToolCall[] } = { role: "assistant", content: text };

243-244: npms metadata lists Anthropic SDK in a Gemini agent.

The npms field shows @anthropic-ai/sdk, which is likely a copy/paste artifact. Consider switching to @google/generative-ai or removing if not used in your doc tooling.

llm_agents/anthropic_agent/tests/test_conv.ts (1)

36-50: Fix small typo in test name

“eturns” → “returns”.

Apply this diff:

-test("eturns only text when no tool_use is mixed in", () => {
+test("returns only text when no tool_use is mixed in", () => {
llm_agents/anthropic_agent/src/anthropic_agent.ts (1)

233-239: Guard JSON.parse for streamed tool_use inputs

Partial or malformed JSON can still occur; parsing without a try/catch can crash the stream handling.

Apply this diff:

-    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 = JSON.parse(partial || "{}");
+      } catch (_e) {
+        streamResponse.content[index].input = {};
+      }
+    }
llm_agents/anthropic_agent/lib/anthropic_agent.js (1)

181-181: Guard JSON.parse for streamed tool_use inputs

Mirror the TS fix: avoid crashing on malformed partials.

Apply this diff:

-            streamResponse.content[index].input = JSON.parse(partial);
+            try {
+                streamResponse.content[index].input = JSON.parse(partial || "{}");
+            } catch (_e) {
+                streamResponse.content[index].input = {};
+            }
llm_agents/anthropic_agent/src/utils.ts (3)

5-6: Broaden TOOLS_CONTENT to include tool_result shape

convOpenAIToolsToAnthropicToolMessage pushes objects with tool_use_id and content, which aren’t represented in TOOLS_CONTENT. Expand the type (or use Anthropic’s SDK types) to avoid type gaps.

Apply this diff:

-type TOOLS_CONTENT = { type: string; text?: string; id?: string; name?: string; input?: unknown };
+type TOOLS_CONTENT = {
+  type: string;
+  // text block
+  text?: string;
+  // tool_use block
+  id?: string;
+  name?: string;
+  input?: unknown;
+  // tool_result block
+  tool_use_id?: string;
+  content?: unknown;
+};

Alternatively, prefer the SDK types directly:

// e.g., use Anthropic.ContentBlockParam for content arrays

61-102: Prefer stronger typings for message transformation and minor resilience

  • Input parameter and return value can be typed using Anthropic.MessageParam and related types.
  • Current merging logic is fine. Keeping a single “user” message with multiple tool_result blocks aligns with Anthropic’s expectations.

Example type improvement:

-export const convOpenAIToolsToAnthropicToolMessage = (messages: any[]) => {
-  return messages.reduce((tmp: any[], message: any) => {
+export const convOpenAIToolsToAnthropicToolMessage = (messages: any[]): Anthropic.Messages.MessageParam[] => {
+  return messages.reduce<Anthropic.Messages.MessageParam[]>((tmp, message: any) => {
     // ...
   }, []);
};

8-8: Add correctly spelled alias for external consumers

Expose “anthropic*” aliases alongside existing “anthoropic*” exports to allow a gradual rename without breakage.

Apply this addition (outside functional logic):

 export const anthoropicToolCall2OpenAIToolCall = (toolCall: Anthropic.Messages.ToolUseBlock): GraphAIToolPayload => {
   // ...
 };
+
+// New, correctly spelled alias (keep old name for compatibility)
+export const anthropicToolCall2OpenAIToolCall = anthoropicToolCall2OpenAIToolCall;

And similarly at the bottom of the file:

 export const anthoropicTool2OpenAITool = (response: Response) => {
   // ...
 };
+
+// New, correctly spelled alias
+export const anthropicTool2OpenAITool = anthoropicTool2OpenAITool;
📜 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 283c0f5 and e13516c.

📒 Files selected for processing (12)
  • agents/agent_utils/package.json (1 hunks)
  • agents/vanilla_agents/package.json (2 hunks)
  • agents/vanilla_node_agents/package.json (2 hunks)
  • llm_agents/anthropic_agent/lib/anthropic_agent.d.ts (0 hunks)
  • llm_agents/anthropic_agent/lib/anthropic_agent.js (2 hunks)
  • llm_agents/anthropic_agent/src/anthropic_agent.ts (2 hunks)
  • llm_agents/anthropic_agent/src/utils.ts (1 hunks)
  • llm_agents/anthropic_agent/tests/test_conv.ts (2 hunks)
  • llm_agents/anthropic_agent/tests/test_conv_messages.ts (1 hunks)
  • llm_agents/gemini_agent/lib/gemini_agent.js (1 hunks)
  • llm_agents/gemini_agent/src/gemini_agent.ts (1 hunks)
  • packages/test_utils/package.json (2 hunks)
💤 Files with no reviewable changes (1)
  • llm_agents/anthropic_agent/lib/anthropic_agent.d.ts
✅ Files skipped from review due to trivial changes (1)
  • agents/agent_utils/package.json
🧰 Additional context used
🧬 Code Graph Analysis (3)
llm_agents/anthropic_agent/src/utils.ts (1)
llm_agents/anthropic_agent/tests/test_conv_messages.ts (1)
  • messages (5-151)
llm_agents/anthropic_agent/tests/test_conv.ts (1)
llm_agents/anthropic_agent/src/utils.ts (2)
  • anthoropicToolCall2OpenAIToolCall (8-24)
  • openAIToolCall2AnthropicToolCall (26-42)
llm_agents/anthropic_agent/src/anthropic_agent.ts (3)
llm_agents/anthropic_agent/lib/anthropic_agent.js (2)
  • tool_calls (16-16)
  • functionResponses (15-15)
llm_agents/openai_agent/lib/openai_agent.js (2)
  • tool_calls (32-32)
  • functionResponses (30-30)
llm_agents/anthropic_agent/src/utils.ts (1)
  • anthoropicToolCall2OpenAIToolCall (8-24)
🔇 Additional comments (17)
agents/vanilla_node_agents/package.json (1)

3-3: Version/devDependency bumps align with agent_utils 2.0.3 API shift.

The package version bump and devDependency update look consistent with the nested GraphAIToolPayload changes in @graphai/agent_utils 2.0.3. No issues spotted.

Also applies to: 29-29

agents/vanilla_agents/package.json (1)

3-3: Dependency alignment with agent_utils 2.0.3 looks good.

The version bump and dependency update to @graphai/agent_utils ^2.0.3 correctly track the new tool payload shape. Looks good.

Also applies to: 30-30

packages/test_utils/package.json (1)

3-3: Version and devDependency bumps are consistent across the monorepo.

The updates to @graphai/vanilla and graphai versions align with related package bumps in this PR. No concerns.

Also applies to: 32-34

llm_agents/anthropic_agent/tests/test_conv_messages.ts (1)

1-1: Import path change to utils is correct post-refactor.

Switching to ../src/utils matches the new central utilities module. Good move to reduce duplication.

llm_agents/anthropic_agent/tests/test_conv.ts (6)

5-17: LGTM: solid coverage for text-only assistant content

Tests correctly validate the conversion of a single text block to OpenAI-style content.


19-34: LGTM: tool_use → tool_calls conversion path verified

Good assertion of nested shape with type: "function" and stringified arguments.


52-71: LGTM: Anthropic tool_use → OpenAI tool_call test is correct

Covers id, type discriminator, function name, and stringified arguments.


73-91: LGTM: Handles missing input by defaulting to “{}”

Graceful fallback is validated.


93-111: LGTM: OpenAI tool_call → Anthropic tool_use path works

Ensures id/name continuity and correct JSON payload parsing.


113-130: LGTM: Robustness against invalid JSON arguments

Fallback to empty object is exercised and correct.

llm_agents/anthropic_agent/src/anthropic_agent.ts (1)

54-55: LGTM: Tool-call conversion now uses the shared utility

Using anthoropicToolCall2OpenAIToolCall consolidates shape logic and reduces duplication.

llm_agents/anthropic_agent/lib/anthropic_agent.js (4)

16-17: LGTM: tool_calls conversion uses shared utils

Centralization reduces duplication and sync issues.


18-18: LGTM: message conversion delegated to utils

Consistent output shape with the new nested function payload.


100-100: LGTM: OpenAI→Anthropic message conversion is now unified

Using utils.convOpenAIToolsToAnthropicToolMessage ensures consistent tool_use and tool_result construction.


6-6: No external imports of removed exports detected

Verified that no internal or external code imports anthoropicTool2OpenAITool or convOpenAIToolsToAnthropicToolMessage from the module root (@graphai/anthropic_agent). All existing references either import anthropicAgent from the package index or pull the utility functions directly from src/utils (e.g., in tests). It’s safe to remove these exports from the public API.

llm_agents/anthropic_agent/src/utils.ts (2)

8-24: LGTM: Anthropic tool_use → OpenAI tool_call conversion with safe JSON stringify

Solid conversion with a safe fallback to "{}" on stringify failures.


44-59: LGTM: Assistant response → OpenAI message with consolidated text and tool_calls

Correctly concatenates text blocks and maps tool_use blocks via the shared converter.

Comment on lines +26 to +40
export const openAIToolCall2AnthropicToolCall = (tool: { id: string; function: { name: string; arguments: string } }) => {
const { id, function: func } = tool;
const { name, arguments: args } = func ?? {};

return {
type: "tool_use",
id,
name,
input: (() => {
try {
return JSON.parse(args ?? "{}");
} catch (__e) {
return {};
}
})(),
};
};

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.

🛠️ Refactor suggestion

Handle non-string arguments and add an explicit return type

When GraphAIToolPayload.function.arguments is already an object (some agents provide raw objects), JSON.parse will throw and you currently fall back to {} losing data. Handle both string and object.

Apply this diff:

-export const openAIToolCall2AnthropicToolCall = (tool: { id: string; function: { name: string; arguments: string } }) => {
+export const openAIToolCall2AnthropicToolCall = (
+  tool: { id: string; function: { name: string; arguments: unknown } }
+): Anthropic.Messages.ToolUseBlockParam => {
   const { id, function: func } = tool;
-  const { name, arguments: args } = func ?? {};
+  const { name, arguments: args } = func ?? {};
 
   return {
     type: "tool_use",
     id,
     name,
     input: (() => {
       try {
-        return JSON.parse(args ?? "{}");
+        if (typeof args === "string") {
+          return JSON.parse(args || "{}");
+        }
+        if (args && typeof args === "object") {
+          return args as object;
+        }
+        return {};
       } catch (__e) {
         return {};
       }
     })(),
   };
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const openAIToolCall2AnthropicToolCall = (tool: { id: string; function: { name: string; arguments: string } }) => {
const { id, function: func } = tool;
const { name, arguments: args } = func ?? {};
return {
type: "tool_use",
id,
name,
input: (() => {
try {
return JSON.parse(args ?? "{}");
} catch (__e) {
return {};
}
})(),
};
};
export const openAIToolCall2AnthropicToolCall = (
tool: { id: string; function: { name: string; arguments: unknown } }
): Anthropic.Messages.ToolUseBlockParam => {
const { id, function: func } = tool;
const { name, arguments: args } = func ?? {};
return {
type: "tool_use",
id,
name,
input: (() => {
try {
if (typeof args === "string") {
return JSON.parse(args || "{}");
}
if (args && typeof args === "object") {
return args as object;
}
return {};
} catch (__e) {
return {};
}
})(),
};
};
🤖 Prompt for AI Agents
In llm_agents/anthropic_agent/src/utils.ts around lines 26 to 42, the function
assumes GraphAIToolPayload.function.arguments is a JSON string and JSON.parse
will throw for non-strings, causing data loss; change the implementation to
accept both string and object by: add an explicit return type for
openAIToolCall2AnthropicToolCall, then when building input check typeof args ===
"string" and attempt JSON.parse with a try/catch fallback to {} on parse error,
else if args is a non-null object return args as-is, otherwise return {}; keep
existing id/name mapping and error-safe behavior.

Comment on lines +49 to +56
? calls.map((call) => {
return {
id: "dummy",
name: call.name,
arguments: call.args,
type: "function",
function: {
name: call.name,
arguments: call.args,
}

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.

💡 Verification agent

🧩 Analysis chain

Generate stable, unique tool_call IDs and reuse them in message.tool_calls. Avoid "dummy".

Using id: "dummy" prevents correlating tool_use/tool_result pairs and can break downstream flows expecting stable IDs. Generate unique IDs and propagate the same IDs to both message.tool_calls and tool_calls.

Apply this diff to the tool_calls construction:

-  const tool_calls = calls
-    ? calls.map((call) => {
-        return {
-          id: "dummy",
-          type: "function",
-          function: {
-            name: call.name,
-            arguments: call.args,
-          }
-        };
-      })
-    : [];
+  const tool_calls = calls
+    ? calls.map((call, i) => {
+        const id =
+          typeof globalThis.crypto?.randomUUID === "function"
+            ? globalThis.crypto.randomUUID()
+            : `tool_${Date.now()}_${i}`;
+        return {
+          id,
+          type: "function",
+          function: {
+            name: call.name,
+            arguments: call.args,
+          },
+        };
+      })
+    : [];

And update message.tool_calls to reuse the same IDs (outside this hunk), for example:

// Replace the existing message.tool_calls mapping:
const calls = response.functionCalls();
if (calls) {
  // after computing tool_calls above (or compute ids first), reuse IDs here
  message.tool_calls = tool_calls.map((tc) => ({
    id: tc.id,
    // optional: type: "function",
    function: { name: tc.function.name, arguments: JSON.stringify(tc.function.arguments) },
  }));
}

Optionally, add type: "function" to message.tool_calls entries for consistency with OpenAI shape.



Run this to locate any remaining placeholder IDs:

---

🏁 Script executed:

```shell
#!/bin/bash
# Find any lingering "dummy" tool_call IDs across the repo
rg -nP -C2 'id:\s*["'\'']dummy["'\'']' --type=ts --type=js

Length of output: 795


Refactor tool_call IDs to be unique and reusable

The placeholder id: "dummy" still exists in both your source and compiled output. Update only the TS source so that builds regenerate the JS, and ensure you propagate the same IDs into message.tool_calls.

Files to update:

  • llm_agents/gemini_agent/src/gemini_agent.ts

Apply this diff to generate stable IDs and reuse them:

--- a/llm_agents/gemini_agent/src/gemini_agent.ts
+++ b/llm_agents/gemini_agent/src/gemini_agent.ts
@@ 49,56c49,64
-  const tool_calls = calls
-    ? calls.map((call) => {
-        return {
-          id: "dummy",
-          type: "function",
-          function: {
-            name: call.name,
-            arguments: call.args,
-          }
-        };
-      })
-    : [];
+  const tool_calls = calls
+    ? calls.map((call, i) => {
+        const id =
+          typeof globalThis.crypto?.randomUUID === "function"
+            ? globalThis.crypto.randomUUID()
+            : `tool_${Date.now()}_${i}`;
+        return {
+          id,
+          type: "function",
+          function: {
+            name: call.name,
+            arguments: call.args,
+          },
+        };
+      })
+    : [];
 
   // …later, when building the message
   const calls = response.functionCalls();
   if (calls) {
-    message.tool_calls = calls.map((c) => ({
-      name: c.name,
-      arguments: JSON.stringify(c.args),
-    }));
+    // reuse the same IDs and include type for clarity
+    message.tool_calls = tool_calls.map((tc) => ({
+      id: tc.id,
+      type: tc.type,
+      function: {
+        name: tc.function.name,
+        arguments: JSON.stringify(tc.function.arguments),
+      },
+    }));
   }

• After updating the TS file, rebuild so lib/gemini_agent.js drops the "dummy" entries.
• This ensures downstream flows can correlate tool_use/tool_result by stable IDs.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
? calls.map((call) => {
return {
id: "dummy",
name: call.name,
arguments: call.args,
type: "function",
function: {
name: call.name,
arguments: call.args,
}
const tool_calls = calls
? calls.map((call, i) => {
const id =
typeof globalThis.crypto?.randomUUID === "function"
? globalThis.crypto.randomUUID()
: `tool_${Date.now()}_${i}`;
return {
id,
type: "function",
function: {
name: call.name,
arguments: call.args,
},
};
})
: [];
// …later, when building the message
const calls = response.functionCalls();
if (calls) {
// reuse the same IDs and include type for clarity
message.tool_calls = tool_calls.map((tc) => ({
id: tc.id,
type: tc.type,
function: {
name: tc.function.name,
arguments: JSON.stringify(tc.function.arguments),
},
}));
}
🤖 Prompt for AI Agents
In llm_agents/gemini_agent/src/gemini_agent.ts around lines 49–56 the tool_call
objects are created with a hardcoded id: "dummy"; replace this with a stable
unique id per call (for example derive an id from the call name plus a sequence
or deterministic hash) and ensure that same generated id is assigned into the
corresponding message.tool_calls entries so callers can correlate
tool_use/tool_result; update only the TS file and then rebuild so
lib/gemini_agent.js no longer contains "dummy" and the generated IDs propagate
into the compiled output.

@isamu
isamu force-pushed the refactorAnthropic branch from e13516c to 5e2be5f Compare August 18, 2025 02:36

@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: 1

🔭 Outside diff range comments (2)
llm_agents/anthropic_agent/src/anthropic_agent.ts (2)

64-71: Guard JSON.parse when building responseFormat to avoid runtime crashes

When maybeResponseFormat is true and the model returns non-JSON or malformed JSON, JSON.parse(text) will throw and crash the agent.

Apply this diff:

-  const responseFormat = (() => {
-    if (maybeResponseFormat && text) {
-      const parsed = JSON.parse(text);
-      if (typeof parsed === "object" && parsed !== null) {
-        return parsed;
-      }
-    }
-    return null;
-  })();
+  const responseFormat = (() => {
+    if (maybeResponseFormat && typeof text === "string") {
+      try {
+        const parsed = JSON.parse(text);
+        if (parsed && typeof parsed === "object") {
+          return parsed;
+        }
+      } catch {
+        // ignore non-JSON responses
+      }
+    }
+    return null;
+  })();

241-243: Harden streaming input JSON parsing to avoid stream termination on malformed partials

JSON.parse(partial) will throw if the stream delivers unexpected data or an empty string; fail-safe to {} instead of crashing.

Apply this diff:

-    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 {
+        streamResponse.content[index].input = {};
+      }
+    }
♻️ Duplicate comments (2)
llm_agents/anthropic_agent/src/anthropic_agent.ts (1)

235-235: Fix the “Anthoropic” typo in the thrown error message

Same nit as the previous review; the message has the typo and is user-facing.

Apply this diff:

-    throw new Error("Anthoropic no response");
+    throw new Error("Anthropic stream returned no response");
llm_agents/anthropic_agent/src/utils.ts (1)

24-40: Support non-string arguments in openAIToolCall2AnthropicToolCall (avoid data loss) — same as earlier feedback

When function.arguments is already an object, JSON.parse throws and you currently fall back to {}, losing the payload. Handle both string and object.

Apply this diff:

-export const openAIToolCall2AnthropicToolCall = (tool: { id: string; function: { name: string; arguments: string } }) => {
+export const openAIToolCall2AnthropicToolCall = (
+  tool: { id: string; function: { name: string; arguments: unknown } }
+): Anthropic.Messages.ToolUseBlockParam => {
   const { id, function: func } = tool;
   const { name, arguments: args } = func ?? {};
 
   return {
     type: "tool_use",
     id,
     name,
     input: (() => {
       try {
-        return JSON.parse(args ?? "{}");
+        if (typeof args === "string") {
+          return JSON.parse(args || "{}");
+        }
+        if (args && typeof args === "object") {
+          return args as object;
+        }
+        return {};
       } catch (__e) {
         return {};
       }
     })(),
   };
 };
🧹 Nitpick comments (4)
llm_agents/anthropic_agent/src/anthropic_agent.ts (2)

16-16: Good extraction to shared utils; consider adding a correctly spelled alias to avoid propagating the typo

Importing the conversion helpers from a central utils module is the right direction. To reduce tech debt on the public surface, consider adding a correctly spelled alias (anthropicTool2OpenAITool) next to the existing misspelled export in utils, while keeping the old name for backward compatibility. See suggested diff in utils.ts.


57-57: Make text extraction robust to non-text first content block

If the first content block is a tool_use, .text is undefined. Prefer finding the first text block.

Apply this diff:

-  const text = (response.content[0] as Anthropic.TextBlock).text;
+  const firstText = response.content.find((c): c is Anthropic.TextBlock => c.type === "text");
+  const text = firstText?.text;
llm_agents/anthropic_agent/src/utils.ts (2)

42-57: Optionally export a correctly spelled alias for anthoropicTool2OpenAITool

The misspelling leaks into consumers. Add a correctly spelled alias while keeping the original for backward compatibility.

Apply this diff:

 export const anthoropicTool2OpenAITool = (response: Response) => {
   const contentText = response.content
     .filter((c): c is Anthropic.TextBlock => c.type === "text")
     .map((b) => b.text ?? "")
     .join(" ");
 
   const tool_calls = response.content.filter((c): c is Anthropic.Messages.ToolUseBlock => c.type === "tool_use").map(anthoropicToolCall2OpenAIToolCall);
   if (tool_calls.length > 0) {
     return {
       role: response.role,
       content: contentText,
       tool_calls,
     };
   }
   return { role: response.role, content: contentText };
 };
+
+// Temporary alias to fix the typo while maintaining backward compatibility
+export const anthropicTool2OpenAITool = anthoropicTool2OpenAITool;

59-100: Consider tightening types for messages and content to reduce any-casting

messages: any[] and tmp: any[] erode type safety and could mask structural issues (e.g., tool_result blocks). If feasible, introduce precise types for the Anthropic message shapes.

I can provide a follow-up typed version if you want to raise the bar here.

📜 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 e13516c and 5e2be5f.

📒 Files selected for processing (4)
  • llm_agents/anthropic_agent/lib/anthropic_agent.d.ts (0 hunks)
  • llm_agents/anthropic_agent/lib/anthropic_agent.js (3 hunks)
  • llm_agents/anthropic_agent/src/anthropic_agent.ts (1 hunks)
  • llm_agents/anthropic_agent/src/utils.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • llm_agents/anthropic_agent/lib/anthropic_agent.d.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • llm_agents/anthropic_agent/lib/anthropic_agent.js
🧰 Additional context used
🧬 Code Graph Analysis (1)
llm_agents/anthropic_agent/src/utils.ts (2)
llm_agents/anthropic_agent/lib/anthropic_agent.js (4)
  • tool (21-21)
  • response (32-32)
  • tool_calls (20-20)
  • message (22-22)
llm_agents/anthropic_agent/tests/test_conv_messages.ts (1)
  • messages (5-151)
⏰ 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 (1)
llm_agents/anthropic_agent/src/utils.ts (1)

1-4: Centralizing conversion helpers is the right call

Good consolidation of types and conversion logic into a single module. This reduces duplication and keeps the agent lean.

Comment on lines +64 to +66
type: "text",
text: message.content || "run tools",
},

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.

⚠️ Potential issue

Ensure assistant content text is a string (prevent schema mismatch for Anthropic)

message.content can be non-string (e.g., an array). Passing it directly into { type: "text", text: ... } breaks the Anthropic schema.

Apply this diff:

-          text: message.content || "run tools",
+          text: typeof message.content === "string" ? message.content : "run tools",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
type: "text",
text: message.content || "run tools",
},
type: "text",
text: typeof message.content === "string" ? message.content : "run tools",
},
🤖 Prompt for AI Agents
In llm_agents/anthropic_agent/src/utils.ts around lines 64 to 66, the object
passed to Anthropic can receive a non-string message.content (e.g., an array)
which breaks the schema; coerce message.content to a string before assigning to
text by using the original string if typeof message.content === "string",
otherwise fall back to JSON.stringify(message.content) (or
String(message.content)) and still use "run tools" as the final default if
content is null/undefined, ensuring the text field is always a string.

@isamu
isamu merged commit 4aa4e3c into receptron:main Aug 18, 2025
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