Skip to content

Play ground - #1216

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

isamu merged 9 commits into
receptron:mainfrom
isamu:playGround

Conversation

@isamu

@isamu isamu commented Aug 18, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features
    • Improved Anthropic tool-calling compatibility with safer JSON argument handling.
    • Streaming output logging enabled for in-progress responses.
    • New Playground tools demo showcasing multi-agent, multi-step flows.
    • Added common tool definitions and a mock agent for quick experimentation.
  • Tests
    • Updated test cases to the new function-calling format.
    • Added streaming test runs.
  • Documentation
    • Added README instructions for running Anthropic tools.
  • Chores
    • Introduced Playground package scaffolding (package.json, tsconfig, ESLint).
    • Updated Anthropic package test script to run real TypeScript tests.

@coderabbitai

coderabbitai Bot commented Aug 18, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Convert Anthropic tool-calls to a function-typed payload with JSON-stringified arguments and add guarded stringify/parse. Update conversion logic and tests to match. Add streaming logging and agent filters in tests. Introduce a new playground package with tools, demo scripts, ESLint/TS configs, README, and updated test scripts.

Changes

Cohort / File(s) Summary
Anthropic tool-call refactor
llm_agents/anthropic_agent/src/anthropic_agent.ts
Convert tool_calls to { type: "function", function: { name, arguments: "<json-string>" } }; guard JSON.stringify and JSON.parse (fallback to {}); update convOpenAIToolsToAnthropicToolMessage to use parsed args and message.content fallback.
Anthropic tests & streaming
llm_agents/anthropic_agent/tests/test_conv.ts, llm_agents/anthropic_agent/tests/test_conv_messages.ts, llm_agents/anthropic_agent/tests/run_tools.ts
Update test fixtures to use function-style tool_calls with JSON-string arguments; add and export consoleStreamAgentFilter; enable streaming and pass agentFilters to GraphAI in test harness.
Anthropic package script
llm_agents/anthropic_agent/package.json
Replace placeholder test script with: node --test --require ts-node/register ./tests/test_*.ts.
Playground package (new)
llm_agents/playground/package.json, llm_agents/playground/tsconfig.json, llm_agents/playground/eslint.config.mjs, llm_agents/playground/README.md, llm_agents/playground/src/tools/common.ts, llm_agents/playground/src/tools/run_tools.ts
Add playground package: package manifest and scripts, TS config, ESLint config, README snippet, tool catalog and mock agent (tools, generalToolAgent), demo runner with two multi-agent flows, and exported consoleStreamAgentFilter, main, main2.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant AnthropicAgent
  participant Converter
  participant AnthropicAPI

  Client->>AnthropicAgent: send messages (may include OpenAI-style tool_calls)
  AnthropicAgent->>Converter: convOpenAIToolsToAnthropicToolMessage
  Converter->>Converter: JSON.stringify(args) (try/catch -> "{}")
  Converter-->>AnthropicAgent: tool_calls as function-type with string args
  AnthropicAgent->>AnthropicAPI: tool_use with parsed input (try/catch -> {})
  AnthropicAPI-->>AnthropicAgent: response (streaming optional)
  AnthropicAgent-->>Client: messages and tool results
Loading
sequenceDiagram
  participant Runner
  participant GraphAI
  participant LLM
  participant ToolsAgent

  Runner->>GraphAI: run(graph, {messages, tools}, {agentFilters, stream:true})
  GraphAI->>LLM: prompt + tool schema
  LLM-->>GraphAI: tool_calls (type:function, arguments: JSON string)
  GraphAI->>ToolsAgent: execute tool with parsed arguments
  ToolsAgent-->>GraphAI: tool results
  GraphAI->>LLM: follow-up prompt with results
  LLM-->>GraphAI: final content (streamed in-progress events)
  GraphAI-->>Runner: result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

I hop through code with a curious grin,
I stringify carrots and tuck them in.
Functions now carry their JSONed seeds,
I watch streams whisper output deeds.
A playground of agents — hop, run, repeat! 🥕🐇

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

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Status, Documentation and Community

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

98-105: Guard JSON.parse(text) when inferring response_format.

JSON.parse(text) will throw if the model returns a plain string or non-JSON. Add try/catch to avoid crashing when maybeResponseFormat is true.

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 {}
+    }
+    return null;
+  })();

333-334: Streaming path: unguarded JSON.parse can crash on partial/incomplete tool_use inputs.

At the end of streaming, JSON.parse(partial) can throw if the stream yielded incomplete/invalid JSON. This will crash the whole request on malformed tool inputs.

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 {
+        streamResponse.content[index].input = {};
+      }
+    }

44-47: Align convToolCall with the function-type tool_calls format

The helper convToolCall in llm_agents/anthropic_agent/src/anthropic_agent.ts currently emits the legacy

{ id, name, arguments: input }

shape, whereas anthoropicTool2OpenAITool produces a function-style tool call:

{ 
  id, 
  type: "function", 
  function: { name, arguments: JSON.stringify(...) } 
}

Mixing two formats in the same response will lead to downstream confusion.

Refactor required:

• File: llm_agents/anthropic_agent/src/anthropic_agent.ts (lines 44–47)
Replace:

-const convToolCall = (tool_call: Anthropic.ToolUseBlock) => {
-  const { id, name, input } = tool_call;
-  return { id, name, arguments: input };
-};
+const convToolCall = (tool_call: Anthropic.ToolUseBlock) => {
+  const { id, name, input } = tool_call;
+  return {
+    id,
+    type: "function" as const,
+    function: {
+      name,
+      arguments: (() => {
+        try {
+          return JSON.stringify(input ?? {});
+        } catch {
+          return "{}";
+        }
+      })(),
+    },
+  };
+};

• File: llm_agents/anthropic_agent/lib/anthropic_agent.d.ts (lines 29–32)
Update the tool_calls declaration to match the new function-type signature:

// from
tool_calls: {
  id: string;
  name: string;
  arguments: unknown;
}[];
// to
tool_calls: {
  id: string;
  type: "function";
  function: {
    name: string;
    arguments: string;
  };
}[];

• Follow-up:

  • Audit any consumer of convertOpenAIChatCompletion or anthoropicTool2OpenAITool (e.g. downstream GraphAI agents or tests) for assumptions on the old { name, arguments } shape.
  • If needed, adjust tests or add a backward-compatibility shim to prevent breaking changes.
🧹 Nitpick comments (14)
llm_agents/anthropic_agent/tests/test_conv_messages.ts (1)

16-21: Add “type: 'function'” to tool_calls for consistency and future-proofing.

Your other tests use the { type: "function", function: { ... } } shape. Adding the type here keeps the structure consistent and avoids edge-case assumptions in converters.

Apply this diff to each tool_calls entry:

-        function: {
+        type: "function",
+        function: {
           name: "generalToolAgent--get_weather",
           arguments: JSON.stringify({
             city: "東京",
           }),
         },

Repeat the same insertion before each “function: { … }” block in this file (Osaka, 札幌, get_fx_rate, AAPL, MSFT).

Also applies to: 25-30, 35-40, 43-48, 52-57, 61-66

llm_agents/playground/eslint.config.mjs (1)

8-9: Avoid ignoring “*.ts” globally; it can mask top-level TS files unintentionally.

Given you already scope files to {src,test,samples}/**, the extra "*.ts" ignore is redundant and risky if you ever add top-level TS utilities.

   {
-    ignores: ["lib/**/*", "*.ts", "apiDoc/**/*"],
+    ignores: ["lib/**/*", "apiDoc/**/*"],
   },
llm_agents/playground/package.json (1)

1-19: Mark the playground package as private to prevent accidental publishing.

This is a playground; setting "private": true guards against accidental npm publish.

 {
   "name": "@graphai/playground",
   "version": "0.0.1",
+  "private": true,
   "description": "PlayGround",
llm_agents/anthropic_agent/tests/run_tools.ts (2)

151-156: Refine streaming logs to print only text chunks and guard for shape.

Logging the entire response object in-progress can be noisy. Consider logging only text blocks with null checks.

-export const consoleStreamAgentFilter = streamAgentFilterGenerator<GraphAILLMStreamData>((context, data) => {
-  if (data.type === "response.in_progress") {
-    console.log(data.response);
-  }
-});
+export const consoleStreamAgentFilter =
+  streamAgentFilterGenerator<GraphAILLMStreamData>((context, data) => {
+    if (data.type === "response.in_progress") {
+      const blocks = (data as any)?.response?.output ?? [];
+      for (const b of blocks) {
+        if (b?.type === "text" && typeof b.text === "string") {
+          console.log(b.text);
+        }
+      }
+    }
+  });

143-150: Remove stale commented code or convert to a named alternative.

The older consoleStreamDataAgentFilter block is commented out. Consider removing it or keeping a named variant if you plan to switch between “text-only” and “raw” modes.

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

325-327: Typo in error message.

"Anthoropic no response" → "Anthropic no response" (or a clearer message).

Apply this diff:

-    throw new Error("Anthoropic no response");
+    throw new Error("Anthropic: no response received from streaming API");
llm_agents/anthropic_agent/tests/test_conv.ts (1)

35-35: Spelling in test name.

"eturns only text..." → "returns only text...".

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/playground/README.md (1)

2-5: Specify code block language and clean spacing.

markdownlint MD040: code fences should specify a language. Also remove the double space before src.

Apply this diff:

-Anthropic tools
-```
-node --require ts-node/register  src/tools/run_tools.ts
-``` 
+## Anthropic tools
+```sh
+node --require ts-node/register src/tools/run_tools.ts
+```
llm_agents/playground/src/tools/run_tools.ts (3)

53-61: Minor: prefer importing agents from packages over src paths.

Using deep relative imports into src/index couples the playground to local source layout and build assumptions. Importing from published package names (as your commented lines suggest) makes the script more portable.

Apply this diff (if package resolution is available in this workspace):

-// import { anthropicAgent } from "@graphai/anthropic_agent";
-// import { openAIAgent } from "@graphai/openai_agent";
-// import { toolsAgent } from "@graphai/tools_agent";
-import { anthropicAgent } from "../../../anthropic_agent/src/index";
-import { openAIAgent } from "../../../openai_agent/src/index";
-import { toolsAgent } from "../../../tools_agent/src/index";
+import { anthropicAgent } from "@graphai/anthropic_agent";
+import { openAIAgent } from "@graphai/openai_agent";
+import { toolsAgent } from "@graphai/tools_agent";

70-81: Unused main() or intentional?

main is defined but never invoked, while main2() is called at the bottom. If main is kept for ad-hoc runs, consider adding a simple CLI switch or a comment to clarify intent; otherwise, remove it.

Apply this diff to gate which flow runs:

-const main2 = async () => {
+const main2 = async () => {
   // ...
-};
-
-main2();
+};
+
+// Run with: node --require ts-node/register src/tools/run_tools.ts [main|main2]
+const flow = process.argv[2] || "main2";
+if (flow === "main") {
+  // eslint-disable-next-line @typescript-eslint/no-floating-promises
+  main();
+} else {
+  // eslint-disable-next-line @typescript-eslint/no-floating-promises
+  main2();
+}

85-116: Duplication between main and main2.

Two nearly identical graphs and setup blocks increase maintenance cost. Consider extracting a small factory that builds the graph/filters and parameterizes the agent/model and prompt text.

If helpful, I can provide a refactor that parameterizes the run while keeping the playground simplicity.

llm_agents/playground/src/tools/common.ts (3)

3-3: Prefer runtime immutability for the tools registry

as const gives compile-time readonly, but the array can still be mutated at runtime. Wrapping with Object.freeze prevents accidental mutation in the playground.

Apply this diff:

-export const tools = [
+export const tools = Object.freeze([
@@
-] as const;
+] as const);

Also applies to: 82-82


86-86: Gate playground logging behind DEBUG to avoid noisy stdout

Keep logs opt-in to prevent cluttering test output.

Apply this diff:

-  console.log(`call ${func}`);
+  if (process.env.DEBUG?.includes("playground:tools")) {
+    console.log(`call ${func}`);
+  }

128-129: Return a structured message for unknown tools instead of an empty object

Returning {} can be hard to debug downstream. Surface a minimal, consistent payload.

Apply this diff:

-  return {};
+  return { content: `Unknown tool function: ${func ?? "(missing)"}` };
📜 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 e215a9b and cb047a2.

📒 Files selected for processing (11)
  • llm_agents/anthropic_agent/package.json (1 hunks)
  • llm_agents/anthropic_agent/src/anthropic_agent.ts (2 hunks)
  • llm_agents/anthropic_agent/tests/run_tools.ts (3 hunks)
  • llm_agents/anthropic_agent/tests/test_conv.ts (1 hunks)
  • llm_agents/anthropic_agent/tests/test_conv_messages.ts (1 hunks)
  • llm_agents/playground/README.md (1 hunks)
  • llm_agents/playground/eslint.config.mjs (1 hunks)
  • llm_agents/playground/package.json (1 hunks)
  • llm_agents/playground/src/tools/common.ts (1 hunks)
  • llm_agents/playground/src/tools/run_tools.ts (1 hunks)
  • llm_agents/playground/tsconfig.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
llm_agents/anthropic_agent/tests/run_tools.ts (1)
agent_filters/stream_agent_filter/lib/stream.js (1)
  • streamAgentFilter (6-15)
llm_agents/playground/src/tools/run_tools.ts (1)
agent_filters/stream_agent_filter/lib/stream.js (1)
  • streamAgentFilter (6-15)
🪛 markdownlint-cli2 (0.17.2)
llm_agents/playground/README.md

3-3: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ 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 (13)
llm_agents/anthropic_agent/package.json (1)

15-16: ts-node is already available via the root devDependencies

  • The root package.json (/package.json) lists ts-node@^10.9.2 under devDependencies.
  • Node’s module resolution will hoist and resolve ts-node from the workspace root, so the TS test runner in llm_agents/anthropic_agent will find it at runtime.

No changes to this package’s package.json are required.

llm_agents/playground/eslint.config.mjs (1)

1-1: ESLint base config import path is correct

The base config lives at config/eslint.config.base.mjs in the repo root, so from llm_agents/playground/eslint.config.mjs the relative path ../../config/eslint.config.base.mjs is accurate. No change needed.

llm_agents/anthropic_agent/tests/run_tools.ts (2)

182-189: LGTM: Agent filter wiring is correct.

Good use of streamAgentFilterGenerator and GraphAI’s agentFilters to tap streaming events.


175-177: Model ID Verified: “claude-opus-4-1-20250805” Is Valid
According to Anthropic’s public docs (Aug 18 2025), “claude-opus-4-1-20250805” is the correct snapshot ID for Claude Opus 4.1. No change is needed here.

Likely an incorrect or invalid review comment.

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

63-74: Good move: switch to function-type tool_calls with robust JSON stringify.

The new shape matches OpenAI-style function calls and guards against stringify failures with a sensible "{}" fallback.


151-156: Sane default for assistant text in tool-calling messages.

Using message.content || "run tools" is a reasonable default and avoids empty text blocks when tool_calls are present.


157-173: Robust parsing of function arguments from tool_calls.

JSON.parse is correctly guarded with a fallback to {}. This aligns with the new function-call format.


248-257: Model Identifiers Confirmed as Active

  • “claude-3-7-sonnet-20250219” (Claude Sonnet 3.7) is currently active.
  • “claude-opus-4-1-20250805” (Claude Opus 4.1) is currently active.

No updates needed to the default or Playground model IDs.

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

28-32: Test update matches function-type tool_calls format.

The expectation now correctly asserts type: "function" and a nested function object with stringified arguments.

llm_agents/playground/tsconfig.json (1)

1-11: LGTM.

Reasonable local overrides (baseUrl/rootDir/outDir) with inheritance from the monorepo base tsconfig.

llm_agents/playground/src/tools/run_tools.ts (2)

20-25: Console streaming logger looks good for playground usage.

The filter prints in-progress responses, which is appropriate for a demo environment.


26-51: Graph definition and streaming configuration are clear.

Good structure of nodes and passing stream: true through to the tools node with a dedicated stream filter. Suitable for demonstrating multi-step tool flows.

llm_agents/playground/src/tools/common.ts (1)

25-32: Schema for FX tool is well-scoped

Good use of a strict 6-letter pattern and additionalProperties: false to constrain inputs.

Comment on lines +84 to +85
const toolsTestDummyAgent: AgentFunction = async ({ namedInputs }) => {
const { arg = {}, func } = namedInputs ?? {};

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

Normalize tool function name to tolerate prefixed names (generalToolAgent--*)

Tool entries are named like generalToolAgent--get_weather, but the handler branches on unprefixed names (e.g., get_weather). Make the handler robust by normalizing func to its suffix.
[suggest_optional_refactor]

Apply this diff:

 const toolsTestDummyAgent: AgentFunction = async ({ namedInputs }) => {
   const { arg = {}, func } = namedInputs ?? {};
+  const fullName = String(func ?? "");
+  const name = fullName.includes("--") ? fullName.split("--").pop()! : fullName;
@@
-  if (func === "get_weather") {
+  if (name === "get_weather") {
@@
-  if (func === "get_fx_rate") {
+  if (name === "get_fx_rate") {
@@
-  if (func === "lookup_stock_price") {
+  if (name === "lookup_stock_price") {
@@
-  if (func === "translate_text") {
+  if (name === "translate_text") {
@@
-  if (func === "geocode_address") {
+  if (name === "geocode_address") {

To confirm whether callers pass prefixed or unprefixed names, run:

Also applies to: 88-88, 95-95, 103-103, 111-111, 120-120


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Look for prefixed func usage
rg -nP -C2 '\bfunc\s*:\s*["'\'']generalToolAgent--' --type=ts || true

# Look for unprefixed func usage
rg -nP -C2 '\bfunc\s*:\s*["'\''](get_weather|get_fx_rate|lookup_stock_price|translate_text|geocode_address)["'\'']' --type=ts || true

# Inspect agentInfoWrapper references to learn its naming behavior
rg -nP -C3 '\bagentInfoWrapper\s*\(' --type=ts || true

Length of output: 20043


To understand whether the func field can ever include the wrapper’s prefix, let’s inspect how agentInfoWrapper constructs the func name. We’ll locate its definition and review its logic. If it never prefixes the name, normalizing is unnecessary.


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find where agentInfoWrapper is defined
rg -nP --max-count 1 'export (?:const|function) agentInfoWrapper' -n .

# Show its implementation for context
rg -nP 'agentInfoWrapper' -C5 --type=ts

Length of output: 41607


Inspecting defaultAgentInfo to see if it includes an ID or prefix behavior:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# View defaultAgentInfo in utils.ts
sed -n '1,100p' packages/graphai/src/utils/utils.ts

Length of output: 2994


To confirm how func is derived from your tools definitions, let’s inspect the top of llm_agents/playground/src/tools/common.ts (where you declare tools and toolsTestDummyAgent), so we can see whether your graph nodes use the prefixed names.


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show the tools definitions and the dummy agent in playground common.ts
sed -n '1,150p' llm_agents/playground/src/tools/common.ts

Length of output: 3834


Normalize prefixed tool names in Playground dummy agent

To correctly handle tool names like generalToolAgent--get_weather, extract the suffix once and compare against that in each branch.

• llm_agents/playground/src/tools/common.ts
– Lines 84–85: insert fullName and name normalization
– Lines 88, 95, 103, 111, 120: replace func === … with name === …

--- a/llm_agents/playground/src/tools/common.ts
+++ b/llm_agents/playground/src/tools/common.ts
@@ -82,7 +82,10 @@
   const { arg = {}, func } = namedInputs ?? {};
-  // existing code continues...
+  // normalize prefixed tool name to its suffix
+  const fullName = String(func ?? "");
+  const name = fullName.includes("--")
+    ? fullName.split("--").pop()!
+    : fullName;

   console.log(`call ${func}`);
@@ -88c91
-  if (func === "get_weather") {
+  if (name === "get_weather") {
     return {
       content: `Weather for ${arg.city ?? "Unknown"}: fine.`,
@@ -95c98
-  if (func === "get_fx_rate") {
+  if (name === "get_fx_rate") {
     const pair = (arg.pair ?? "USDJPY").toUpperCase();
@@ -103c106
-  if (func === "lookup_stock_price") {
+  if (name === "lookup_stock_price") {
     const ticker = String(arg.ticker ?? "AAPL").toUpperCase();
@@ -111c114
-  if (func === "translate_text") {
+  if (name === "translate_text") {
     const text = arg.text ?? "";
     const target = arg.target_lang ?? "en";
@@ -120c123
-  if (func === "geocode_address") {
+  if (name === "geocode_address") {
     const address = arg.address ?? "Unknown";
     return {
       content: `Geocoded "${address}".`,
🤖 Prompt for AI Agents
In llm_agents/playground/src/tools/common.ts around lines 84–85, normalize the
incoming tool name by creating a fullName from func (e.g., const fullName =
(func ?? '').toString()) and derive the suffix-only name (e.g., const name =
fullName.includes('--') ? fullName.split('--').pop()! : fullName); then update
the conditional branches at lines 88, 95, 103, 111, and 120 to compare against
name instead of func (replace all occurrences of func === '...' with name ===
'...') so prefixed tool names like "generalToolAgent--get_weather" match by
their suffix.

Comment on lines +63 to +66
graphai.injectValue("text", "東京・大阪・札幌の天気、USDJPYのレート、AAPLとMSFTの株価を教えて");
graphai.injectValue("llmAgent", "anthropicAgent");
graphai.injectValue("llmModel", "claude-opus-4-1-20250805");

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

Verify Anthropic model ID used here.

claude-opus-4-1-20250805 may not be a valid model ID. Prefer aligning with the default used in the Anthropic agent or a known-good ID to avoid runtime errors.


🏁 Script executed:

#!/bin/bash
# Grep for Anthropic model IDs used across the repo to keep them consistent.
rg -nP -C2 'claude[-_a-zA-Z0-9]+' llm_agents | sed -n '1,200p'

Length of output: 2976


Align Anthropic model ID across the codebase

The Anthropic agent defaults to "claude-3-7-sonnet-20250219" (see llm_agents/anthropic_agent/src/anthropic_agent.ts:250), but in both the playground scripts and tests we’re injecting "claude-opus-4-1-20250805". If this ID isn’t supported you’ll get runtime errors. Please verify which model you intend to use and update the references accordingly:

• llm_agents/playground/src/tools/run_tools.ts (lines 65 & 133)
• llm_agents/anthropic_agent/tests/run_tools.ts (line 175)

Suggested change:

- graphai.injectValue("llmModel", "claude-opus-4-1-20250805");
+ graphai.injectValue("llmModel", "claude-3-7-sonnet-20250219");
📝 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
graphai.injectValue("text", "東京・大阪・札幌の天気、USDJPYのレート、AAPLとMSFTの株価を教えて");
graphai.injectValue("llmAgent", "anthropicAgent");
graphai.injectValue("llmModel", "claude-opus-4-1-20250805");
graphai.injectValue("text", "東京・大阪・札幌の天気、USDJPYのレート、AAPLとMSFTの株価を教えて");
graphai.injectValue("llmAgent", "anthropicAgent");
graphai.injectValue("llmModel", "claude-3-7-sonnet-20250219");

@isamu
isamu merged commit f2ef2ff into receptron:main Aug 18, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
llm_agents/playground/src/tools/run_tools.ts (2)

63-66: Anthropic model ID likely invalid/inconsistent with agent defaults. Update to a supported ID.

This was already flagged in a prior review; repeating here because it’s still present.

Apply this diff:

-  graphai.injectValue("llmModel", "claude-opus-4-1-20250805");
+  graphai.injectValue("llmModel", "claude-3-7-sonnet-20250219");

Run this script to locate and align model IDs across the repo:

#!/bin/bash
set -euo pipefail

# Anthropic model injections
rg -nP -C2 '\binjectValue\(\s*"llmModel"\s*,\s*"claude-[^"]+"' llm_agents | sed -n '1,200p'

# Check Anthropic agent defaults/hardcoded models
rg -nP -C3 --type=ts '(?i)default.*model|llmModel|model\s*:' llm_agents/anthropic_agent | sed -n '1,400p'

132-134: Anthropic model ID again — align with a supported ID.

Same issue as Line 65.

Apply this diff:

-  graphai2.injectValue("llmModel", "claude-opus-4-1-20250805");
+  graphai2.injectValue("llmModel", "claude-3-7-sonnet-20250219");
🧹 Nitpick comments (8)
llm_agents/playground/src/tools/run_tools.ts (8)

5-7: Prefer package imports for portability (keep relative only for local-only runs).

Using internal relative paths couples the playground to the monorepo layout. Favor the published package entrypoints so this script runs after packaging too.

Apply this diff if packages are available:

-import { anthropicAgent } from "../../../anthropic_agent/src/index";
-import { openAIAgent } from "../../../openai_agent/src/index";
-import { toolsAgent } from "../../../tools_agent/src/index";
+import { anthropicAgent } from "@graphai/anthropic_agent";
+import { openAIAgent } from "@graphai/openai_agent";
+import { toolsAgent } from "@graphai/tools_agent";

20-24: Widen stream logging to cover more provider event types.

Right now only Anthropic’s in-progress events are printed. OpenAI or future providers may emit different types; log them too.

Apply this diff:

-export const consoleStreamAgentFilter = streamAgentFilterGenerator<GraphAILLMStreamData>((context, data) => {
-  if (data.type === "response.in_progress") {
-    console.log(data.response);
-  }
-});
+export const consoleStreamAgentFilter = streamAgentFilterGenerator<GraphAILLMStreamData>((_context, data) => {
+  switch (data.type) {
+    case "response.in_progress":
+    case "response.delta":
+    case "message.delta":
+    case "message_start":
+    case "message_stop":
+      console.log(data.response ?? data.delta ?? data);
+      break;
+    default:
+      // no-op
+      break;
+  }
+});

58-58: Missing semicolons (style consistency).

The rest of the file uses semicolons; keep consistency.

Apply this diff:

-  const agentFilters = [streamAgentFilter]
+  const agentFilters = [streamAgentFilter];

Also applies to: 116-116


59-61: Rename aagents to a clearer name (readability).

aagents is cryptic; agentsMap/registeredAgents reads better.

Apply this diff:

-  const aagents = { ...agents, toolsAgent, generalToolAgent, openAIAgent, anthropicAgent };
-  
-  const graphai = new GraphAI(graph, aagents, { agentFilters });
+  const agentsMap = { ...agents, toolsAgent, generalToolAgent, openAIAgent, anthropicAgent };
+  
+  const graphai = new GraphAI(graph, agentsMap, { agentFilters });
@@
-  const graphai2 = new GraphAI(graph, aagents, { agentFilters });
+  const graphai2 = new GraphAI(graph, agentsMap, { agentFilters });
@@
-  const aagents = { ...agents, toolsAgent, generalToolAgent, openAIAgent, anthropicAgent };
-  
-  const graphai = new GraphAI(graph, aagents, { agentFilters });
+  const agentsMap = { ...agents, toolsAgent, generalToolAgent, openAIAgent, anthropicAgent };
+  
+  const graphai = new GraphAI(graph, agentsMap, { agentFilters });
@@
-  const graphai2 = new GraphAI(graph, aagents, { agentFilters });
+  const graphai2 = new GraphAI(graph, agentsMap, { agentFilters });

Also applies to: 70-70, 118-120, 129-129


67-69: Avoid as any; add a minimal result type to retain safety.

This improves DX without heavy typing.

Example adjustment:

type ToolsRunResult = { tools: { messages: unknown[] } };

const res = (await graphai.run()) as ToolsRunResult;
console.log(JSON.stringify(res, null, 2));

const graphai2 = new GraphAI(graph, agentsMap, { agentFilters });
// ...
const res2 = (await graphai2.run()) as ToolsRunResult;
console.log(JSON.stringify(res2, null, 2));

Also applies to: 79-81, 126-128, 135-136


26-51: DRY the duplicated graph definition.

Create a factory to keep one source of truth and avoid drift between main and main2.

Example:

const createGraph = () => ({
  version: 0.5,
  nodes: {
    messages: { value: [] },
    text: { value: "" },
    llmAgent: {},
    llmModel: {},
    tools: {
      isResult: true,
      agent: "toolsAgent",
      inputs: {
        messages: ":messages",
        userInput: { text: ":text" },
        tools,
        llmAgent: ":llmAgent",
        llmModel: ":llmModel",
        stream: true,
      },
    },
  },
});

// usage
const graph = createGraph();

Also applies to: 86-111


112-117: Repeat: missing semicolon (style consistency).

Apply this diff:

-  const agentFilters = [streamAgentFilter]
+  const agentFilters = [streamAgentFilter];

140-140: Handle top-level promise rejections.

Avoid unhandled rejections when the script is run directly.

Apply this diff:

-main2();
+void main2().catch((err) => {
+  console.error(err);
+  process.exitCode = 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 cb047a2 and 3b22460.

📒 Files selected for processing (1)
  • llm_agents/playground/src/tools/run_tools.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
llm_agents/playground/src/tools/run_tools.ts (1)
agent_filters/stream_agent_filter/lib/stream.js (1)
  • streamAgentFilter (6-15)
⏰ 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 (2)
llm_agents/playground/src/tools/run_tools.ts (2)

39-49: Streaming wiring LGTM.

  • isResult: true aligns with the stream filter’s guarded callback in stream.js.
  • The filter is correctly passed via agentFilters.

Also applies to: 53-56


74-75: No changes needed: plain “gpt-4o” is supported
The OpenAI agent’s default modelName is already set to "gpt-4o" (see openai_agent/src/openai_agent.ts:174) and existing tests pass using the plain "gpt-4o", so injecting "gpt-4o" in run_tools.ts is valid.

This was referenced 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