Skip to content

@graphai/anthropic [email protected] - #1215

Merged
isamu merged 3 commits into
receptron:mainfrom
isamu:@graphai/[email protected]
Aug 17, 2025
Merged

isamu merged 3 commits into
receptron:mainfrom
isamu:@graphai/[email protected]

Conversation

@isamu

@isamu isamu commented Aug 17, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • Chores
    • Incremented anthropic_agent package version to 2.0.8.
    • Incremented tools_agent package version to 1.0.4.
  • New Features
    • Made an internal message-conversion utility available as a public API for broader use.
  • Tests
    • Added end-to-end tests validating conversion of multi-turn conversations and tool call results to the target message format.

@coderabbitai

coderabbitai Bot commented Aug 17, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Exported a message-conversion function and added tests; bumped package versions for two llm_agents packages. No other API, dependency, or manifest changes.

Changes

Cohort / File(s) Summary of Edits
Version bumps
llm_agents/anthropic_agent/package.json, llm_agents/tools_agent/package.json
anthropic_agent: version 2.0.7 → 2.0.8; tools_agent: version 1.0.3 → 1.0.4. No other manifest changes.
Exported conversion function
llm_agents/anthropic_agent/src/anthropic_agent.ts
convOpenAIToolsToAnthropicToolMessage changed from an internal function to an exported constant (export const ...). Function body unchanged.
Tests added
llm_agents/anthropic_agent/tests/test_conv_messages.ts
New TypeScript test validating conversion of OpenAI-style messages to Anthropic tool-message sequence produced by convOpenAIToolsToAnthropicToolMessage. Asserts precise sequence and contents including tool_use/tool_result mapping.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Runner
    participant Conv as convOpenAIToolsToAnthropicToolMessage
    participant Input as OpenAI-style Messages
    participant Output as Anthropic-style Messages

    Test->>Conv: call convOpenAIToolsToAnthropicToolMessage(Input)
    Conv->>Input: parse messages (user, assistant with tool_calls, tool messages)
    Conv->>Output: emit user, assistant (with tool_use array), user (tool_results), assistant summary, next user query
    Test->>Output: assert expected sequence and contents
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • tools #1213 — touches the same converter in llm_agents/anthropic_agent/src/anthropic_agent.ts and earlier introduced related tool-conversion logic; likely related to export/tests added here.

Poem

I nibble on code and twirl my ears with glee,
A function freed, now hopping bold and free.
Versions nudged onward, tests clap in a row,
I drum my paws — the rabbit-runner show! 🐰✨

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

📜 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 8970aa2 and 07124b8.

📒 Files selected for processing (2)
  • llm_agents/anthropic_agent/package.json (1 hunks)
  • llm_agents/tools_agent/package.json (1 hunks)
⏰ 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 (24.x)
  • GitHub Check: build (22.x)
🔇 Additional comments (1)
llm_agents/anthropic_agent/package.json (1)

3-3: Version bump to 2.0.8 verified and good to go

  • llm_agents/anthropic_agent/package.json is now at @graphai/[email protected]
  • Downstream agents/llm_agents/package.json uses "@graphai/anthropic_agent": "^2.0.7", which includes 2.0.8 (no hard-pins)
  • No git tags found for this package—please create a [email protected] tag and draft release notes as needed

{
"name": "@graphai/tools_agent",
"version": "1.0.3",
"version": "1.0.4",

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

Version bump to 1.0.4 looks good.

Patch release aligns with the PR objective and no unintended manifest changes are present.

Run this script to double-check that the versions in both packages match the PR intent and to see if any other workspace packages pin @graphai/tools_agent and may need range updates:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Verifying package versions..."
jq -r '.name + "@" + .version' llm_agents/tools_agent/package.json llm_agents/anthropic_agent/package.json

echo
echo "Searching for workspace dependencies referencing @graphai/tools_agent..."
rg -nP -C2 '"@graphai/tools_agent"\s*:\s*"[^\"]+"' --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/lib/**' || echo "No dependents found or none pin a version."

Length of output: 871


Update workspace dependency for @graphai/tools_agent

Please update the version specifier in your workspace manifest to match the bumped release:

• File: agents/llm_agents/package.json
Change:

-    "@graphai/tools_agent": "^1.0.2"
+    "@graphai/tools_agent": "^1.0.4"

All other package versions are correct and no further pins were found.
Once that change is applied, this patch is good to merge.

📝 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
"version": "1.0.4",
"dependencies": {
"@graphai/tools_agent": "^1.0.4",
// …other dependencies…
}
🤖 Prompt for AI Agents
llm_agents/tools_agent/package.json around lines 3 to 3: the workspace
dependency version for @graphai/tools_agent is out of sync with the bumped
release; update the version specifier in your workspace manifest
(agents/llm_agents/package.json) to the new release version used across the repo
so the workspace entry matches the bumped release, and verify any workspace
dependency references to @graphai/tools_agent use that exact new version.

@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

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

139-187: Export looks good; tighten typing and support OpenAI’s function-shaped tool_calls (and stringified args).

Right now this utility is loosely typed (any) and assumes tool_calls have top-level name/arguments objects. To make it robust and future-proof:

  • Return Anthropic.MessageParam[].
  • Use Anthropic.ContentBlockParam[] for content construction.
  • Support both OpenAI shapes: tool.function.{name,arguments} and top-level {name,arguments}.
  • Safely JSON-parse string arguments; fall back gracefully.
  • Guard when appending tool_result to ensure last.content is an array.

Suggested diff:

-export const convOpenAIToolsToAnthropicToolMessage = (messages: any[]) => {
-  return messages.reduce((tmp: any[], message: any) => {
+export const convOpenAIToolsToAnthropicToolMessage = (messages: any[]): Anthropic.MessageParam[] => {
+  return messages.reduce((tmp: Anthropic.MessageParam[], message: any) => {
     if (message.role === "assistant" && message.tool_calls) {
-      const content: { type: string; text?: string; id?: string; name?: string; input?: unknown }[] = [
+      const content: Anthropic.ContentBlockParam[] = [
         {
           type: "text",
-          text: message.content,
+          text: String(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,
-      });
+      const safeParseJSON = (val: unknown) => {
+        if (typeof val === "string") {
+          try {
+            return JSON.parse(val);
+          } catch {
+            return val;
+          }
+        }
+        return val;
+      };
+      message.tool_calls.forEach((tool: any) => {
+        const id = tool.id;
+        const name = tool?.function?.name ?? tool?.name;
+        const rawArgs = tool?.function?.arguments ?? tool?.arguments;
+        const input = safeParseJSON(rawArgs);
+        content.push({
+          type: "tool_use",
+          id,
+          name,
+          input,
+        } as Anthropic.ContentBlockParam);
+      });
+      tmp.push({ role: "assistant", content } as Anthropic.MessageParam);
     } 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({
+      if (last?.role === "user" && Array.isArray(last?.content) && last?.content?.[0]?.type === "tool_result") {
+        (tmp[tmp.length - 1] as any).content.push({
           type: "tool_result",
           tool_use_id: message.tool_call_id,
           content: message.content,
         });
       } else {
-        tmp.push({
+        tmp.push({
           role: "user",
           content: [
             {
               type: "tool_result",
               tool_use_id: message.tool_call_id,
               content: message.content,
             },
           ],
-        });
+        } as Anthropic.MessageParam);
       }
     } else {
-      tmp.push(message);
+      tmp.push(message as Anthropic.MessageParam);
     }
     return tmp;
-  }, []);
+  }, [] as Anthropic.MessageParam[]);
 };
🧹 Nitpick comments (4)
llm_agents/anthropic_agent/src/anthropic_agent.ts (1)

139-187: Consider documenting the expected input/output message shapes.

A brief JSDoc helps prevent misuse (e.g., passing Anthropic-shaped messages in). Note we convert OpenAI-like tool_calls + tool messages into Anthropic’s tool_use/tool_result blocks.

I can add a concise JSDoc describing accepted OpenAI variants and the Anthropic output schema if you’d like.

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

5-6: Avoid exporting test fixtures from the test module.

No consumer needs this symbol; keeping it local reduces accidental coupling.

Apply this diff:

-export const messages = [
+const messages = [

141-141: Remove commented debug code.

Leftover console logs add noise; tests should be quiet by default.

Apply this diff:

-//console.log(JSON.stringify(convOpenAIToolsToAnthropicToolMessage(messages)));

145-176: Test scenario is solid; add compatibility cases to prevent regressions.

Consider adding tests for:

  • tool_calls using OpenAI’s function shape (tool.function.{name,arguments} with stringified arguments).
  • Mixed sequences where tool messages are interrupted or there are no tool_calls (ensure pass-through behavior).

I can author these additional tests to lock in behavior across both OpenAI variants.

📜 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 07124b8 and 050afde.

📒 Files selected for processing (2)
  • llm_agents/anthropic_agent/src/anthropic_agent.ts (1 hunks)
  • llm_agents/anthropic_agent/tests/test_conv_messages.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
llm_agents/anthropic_agent/src/anthropic_agent.ts (2)
llm_agents/anthropic_agent/lib/anthropic_agent.js (1)
  • convOpenAIToolsToAnthropicToolMessage (94-144)
llm_agents/anthropic_agent/tests/test_conv_messages.ts (1)
  • messages (5-139)
llm_agents/anthropic_agent/tests/test_conv_messages.ts (1)
llm_agents/anthropic_agent/src/anthropic_agent.ts (1)
  • convOpenAIToolsToAnthropicToolMessage (139-187)
⏰ 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/tests/test_conv_messages.ts (1)

1-1: Ensure TS loader is configured for anthropic_agent tests

We’ve confirmed:
• The root workspace has ts-node hoisted in devDependencies.
• llm_agents/anthropic_agent/package.json defines
– “test”: “echo hello”
– “test_run”: “node --test --require ts-node/register ./tests/run_.ts”
• Tests under tests/
.ts import directly from src/anthropic_agent.

Next steps:
• Confirm your CI/test pipeline invokes the loader-equipped command (e.g. yarn workspace anthropic_agent test_run or similar) so Node can import .ts files from src.
• Or unify the package’s test script to run TS tests directly:

 "scripts": {
-  "test": "echo hello",
+  "test": "node --test --require ts-node/register ./tests/run_*.ts",
   "test_run": "node --test --require ts-node/register ./tests/run_*.ts"
 }

• If you instead intend to test against compiled output, update imports in tests/ from ../src/anthropic_agent to ../lib/anthropic_agent and ensure a build step runs first.

@isamu
isamu merged commit c0ec9c3 into receptron:main Aug 17, 2025
@coderabbitai coderabbitai Bot mentioned this pull request 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