Repository navigation
Refactor anthropic - #1218
Refactor anthropic#1218
Conversation
|
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 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. 📒 Files selected for processing (8)
WalkthroughCentralizes 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 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: 1
🧹 Nitpick comments (9)
agents/agent_utils/lib/type.d.ts (1)
52-56: Consider narrowingtypeand clarifyingfunction.argumentsshapeRight now
typeis a plainstringandfunction.argumentsisunknown. Given our current usage, you can improve type-safety:
typeis always"function"for OpenAI-style tool calls.argumentsis 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 ofunknown:- arguments?: unknown; + arguments?: string | Record<string, unknown>;agents/agent_utils/src/type.ts (1)
55-55: Strengthen typing forGraphAIToolPayloadFor better safety and editor DX, consider aligning with a literal type for
typeand a clearerargumentsshape, 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.tsduring 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 fortypeto match our GraphAIToolPayload suggestion:- type: "function", + type: "function" as const,
70-70: Update call-site after renameKeep 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 renameSame rename should be applied here.
Apply this diff:
- const tool_calls = functionResponses.map(anthoropicToolCall2OpenAIToolCall); + const tool_calls = functionResponses.map(anthropicToolCall2OpenAIToolCall);
144-144: NarrowTOOLS_CONTENTto precise discriminated unionUsing 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 objectargumentswhen converting back to Anthropic
GraphAIToolPayload.function.argumentsis typed asunknownin agent_utils. If a producer passes an object (not a JSON string),JSON.parsewill 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 arrayStyle 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 recomputingtool_callsYou compute
tool_callstwice (once viaanthropicTool2OpenAITool, again inconvertOpenAIChatCompletion). 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.
📒 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 goodThis 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 consistentImporting
GraphAIToolPayloadalongside the other GraphAI types is consistent with the refactor and keeps the conversions typed.
| 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 "{}"; | ||
| } | ||
| })(), | ||
| }, | ||
| }; | ||
| }; |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 crashesWhen 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” namingImporting 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 clarityError 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 claritySame 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 inputsPartial 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 inputsMirror 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 shapeconvOpenAIToolsToAnthropicToolMessage 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 consumersExpose “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.
📒 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 contentTests correctly validate the conversion of a single text block to OpenAI-style content.
19-34: LGTM: tool_use → tool_calls conversion path verifiedGood assertion of nested shape with type: "function" and stringified arguments.
52-71: LGTM: Anthropic tool_use → OpenAI tool_call test is correctCovers 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 worksEnsures id/name continuity and correct JSON payload parsing.
113-130: LGTM: Robustness against invalid JSON argumentsFallback 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 utilityUsing anthoropicToolCall2OpenAIToolCall consolidates shape logic and reduces duplication.
llm_agents/anthropic_agent/lib/anthropic_agent.js (4)
16-17: LGTM: tool_calls conversion uses shared utilsCentralization reduces duplication and sync issues.
18-18: LGTM: message conversion delegated to utilsConsistent output shape with the new nested function payload.
100-100: LGTM: OpenAI→Anthropic message conversion is now unifiedUsing utils.convOpenAIToolsToAnthropicToolMessage ensures consistent tool_use and tool_result construction.
6-6: No external imports of removed exports detectedVerified that no internal or external code imports
anthoropicTool2OpenAIToolorconvOpenAIToolsToAnthropicToolMessagefrom the module root (@graphai/anthropic_agent). All existing references either importanthropicAgentfrom the package index or pull the utility functions directly fromsrc/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 stringifySolid conversion with a safe fallback to "{}" on stringify failures.
44-59: LGTM: Assistant response → OpenAI message with consolidated text and tool_callsCorrectly concatenates text blocks and maps tool_use blocks via the shared converter.
| 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 {}; | ||
| } | ||
| })(), | ||
| }; | ||
| }; |
There was a problem hiding this comment.
🛠️ 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.
| 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.
| ? calls.map((call) => { | ||
| return { | ||
| id: "dummy", | ||
| name: call.name, | ||
| arguments: call.args, | ||
| type: "function", | ||
| function: { | ||
| name: call.name, | ||
| arguments: call.args, | ||
| } |
There was a problem hiding this comment.
💡 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.
| ? 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.
e13516c to
5e2be5f
Compare
There was a problem hiding this comment.
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 crashesWhen
maybeResponseFormatis 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 messageSame 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 feedbackWhen
function.argumentsis already an object,JSON.parsethrows 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 typoImporting 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 blockIf the first content block is a tool_use,
.textis 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 anthoropicTool2OpenAIToolThe 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[]andtmp: 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.
📒 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 callGood consolidation of types and conversion logic into a single module. This reduces duplication and keeps the agent lean.
| type: "text", | ||
| text: message.content || "run tools", | ||
| }, |
There was a problem hiding this comment.
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.
| 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.
Summary by CodeRabbit