Skip to content

Tools palla - #1212

Merged
isamu merged 7 commits into
receptron:mainfrom
isamu:toolsPalla
Aug 17, 2025
Merged

isamu merged 7 commits into
receptron:mainfrom
isamu:toolsPalla

Conversation

@isamu

@isamu isamu commented Aug 16, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Tool-enabled workflows now support streaming responses and dynamic per-tool invocation; results are consolidated per tool and surfaced alongside messages.
    • Assistant responses aggregate multi-tool outputs into a single follow-up message.
  • Refactor

    • Orchestration reworked to a data-driven flow with streamlined message composition and merged tool results for clearer outputs.
  • Tests

    • Added end-to-end tests for OpenAI tool integration with shared mock tools and updated expectations for aggregated tool-result formats.

@coderabbitai

coderabbitai Bot commented Aug 16, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

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

⌛ How to resolve this issue?

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

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

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

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

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between a94d5f8 and 7ba60a1.

📒 Files selected for processing (2)
  • llm_agents/tools_agent/tests/run_openai.ts (1 hunks)
  • llm_agents/tools_agent/tests/test_tools.ts (6 hunks)

Walkthrough

Reworks the tools_agent workflow into a streaming-capable, data-driven per-tool invocation and aggregation pipeline; adds shared mock tools + wrapped test agent; introduces OpenAI-based tests (parallel tool call handling and a GraphAI end-to-end run); updates tests to use the shared agent and new result shapes.

Changes

Cohort / File(s) Summary
Core tools agent refactor
llm_agents/tools_agent/src/tools_agent.ts
Converts linear tool-call flow into a stream-enabled, data-driven map of per-tool invocations (llmToolCall/llmToolCalls), adds llmModel/stream state nodes, merges per-tool data into mergedData, and produces consolidated toolsResult for final output.
Shared test tooling
llm_agents/tools_agent/tests/common.ts
Adds exported tools spec (five function tools) and toolsTestAgent (agentInfoWrapper around a dummy agent) producing content+data for each tool.
OpenAI tools parallel test
llm_agents/openai_agent/tests/run_openai_tools_parallel.ts
New TypeScript test that calls openAIAgent with tools (tool_choice:auto), captures tool_calls, invokes a dummy tool runner (toolsTestDummyAgent), appends tool role messages, re-calls the agent, streams tokens via callback, and asserts completion. Exports a tools constant.
OpenAI workflow test via GraphAI
llm_agents/tools_agent/tests/run_openai.ts
New test constructing a GraphAI graph that runs toolsAgent with openAIAgent and the shared toolsTestAgent, executes the graph, and logs resulting tool messages.
Updated tools tests
llm_agents/tools_agent/tests/test_tools.ts
Replaces local dummy agent with import from ./common; updates LLM dummy to emit tool_calls, changes tool result handling to aggregate by tool_call_id into tools.data, and updates expected assistant content to reflect aggregated tool_call_id responses.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant toolsAgent
  participant LLM as openAIAgent
  participant ToolMap as Per-Tool Map
  participant Tools as toolsTestAgent

  User->>toolsAgent: messages, tools, llmAgent, stream
  toolsAgent->>LLM: initial messages + tools (tool_choice:auto)
  LLM-->>toolsAgent: assistant message with tool_calls
  toolsAgent->>ToolMap: create llmToolCalls for each tool_call
  loop per tool_call
    ToolMap->>Tools: invoke func(arg) (passthrough)
    Tools-->>ToolMap: tool role message {content, data}
  end
  ToolMap-->>toolsAgent: mergedData + tool role messages
  toolsAgent->>LLM: messages + tool role messages (stream enabled)
  LLM-->>toolsAgent: assistant final (streamed)
  toolsAgent-->>User: combined messages + toolsResult (mergedData)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Tools iterator #1207 — Overlaps on reworking per-tool invocation mapping and introducing llmToolCall/llmToolCalls and related orchestration.
  • fix response of tools agent #1209 — Related aggregation changes that merge per-tool call results into a merged structure (mergedData/toolsResult).
  • update test #1189 — Modifies tests and dummy LLM tool_calls emission, likely touching the same test behavior and expectations.

Suggested reviewers

  • snakajima

Poem

I twitched my ears at streaming breeze,
Tools hop in parallel—such ease!
Calls go out, results hop back,
We weave the threads into one track.
With whiskers, logs, and tidy data—thump! 🐇✨

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

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Status, Documentation and Community

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (14)
llm_agents/tools_agent/tests/run_openai.ts (2)

12-12: Skip the test when OPENAI_API_KEY is not set to avoid flaky CI runs.

Running this test without an API key will fail in CI or local environments. Node’s test runner supports an options object with skip.

Apply this diff:

-test("test openai tools", async () => {
+test("test openai tools", { skip: !process.env.OPENAI_API_KEY }, async () => {

31-34: Add a minimal assertion to validate result shape.

Currently the test only logs. Adding a basic assertion catches regressions and ensures the tool flow executed.

-  const res = (await graphai.run()) as any;
-  console.log(res.tools.messages);
+  const res = (await graphai.run()) as any;
+  assert.ok(res && res.tools && Array.isArray(res.tools.messages), "Expected tools.messages array in result");
+  console.log(res.tools.messages);
llm_agents/openai_agent/tests/run_openai_tools_parallel.ts (4)

89-132: Defensively handle OpenAI’s function call arguments, which may be JSON strings.

OpenAI returns function.arguments as a JSON string in some APIs. To avoid runtime errors, parse when necessary.

-const toolsTestDummyAgent = (func: string, arg: any) => {
+const toolsTestDummyAgent = (func: string, arg: any) => {
+  const parsedArg =
+    typeof arg === "string"
+      ? (() => {
+          try {
+            return JSON.parse(arg);
+          } catch {
+            return {};
+          }
+        })()
+      : arg ?? {};
   console.log(func, arg);
   if (func === "get_weather") {
     return {
-      content: `Weather for ${arg.city ?? "Unknown"}: fine.`,
-      data: { city: arg.city ?? null, temp: 22, unit: arg.unit ?? "C" },
+      content: `Weather for ${parsedArg.city ?? "Unknown"}: fine.`,
+      data: { city: parsedArg.city ?? null, temp: 22, unit: parsedArg.unit ?? "C" },
     };
   }
 
   if (func === "get_fx_rate") {
-    const pair = (arg.pair ?? "USDJPY").toUpperCase();
+    const pair = (parsedArg.pair ?? "USDJPY").toUpperCase();
     return {
       content: `FX ${pair}: 150.12`,
       data: { pair, rate: 150.12, ts: Date.now() },
     };
   }
 
   if (func === "lookup_stock_price") {
-    const ticker = String(arg.ticker ?? "AAPL").toUpperCase();
+    const ticker = String(parsedArg.ticker ?? "AAPL").toUpperCase();
     return {
       content: `Price ${ticker}: $123.45 (+0.78)`,
       data: { ticker, price: 123.45, change: 0.78, currency: "USD" },
     };
   }
 
   if (func === "translate_text") {
-    const text = arg.text ?? "";
-    const target = arg.target_lang ?? "en";
+    const text = parsedArg.text ?? "";
+    const target = parsedArg.target_lang ?? "en";
     return {
       content: `Translated to ${target}.`,
       data: { source_text: text, target_lang: target, translated_text: `[${target}] ${text}` },
     };
   }
 
   if (func === "geocode_address") {
-    const address = arg.address ?? "Unknown";
+    const address = parsedArg.address ?? "Unknown";
     return {
       content: `Geocoded "${address}".`,
       data: { address, location: { lat: 35.000001, lon: 135.000001 }, precision: "ROOFTOP" },
     };
   }
 
   return {};
 };

160-169: Avoid shadowing the outer res constant inside map callback.

Shadowing can confuse readers and tooling.

-  res.tool_calls.map((tool: any) => {
+  res.tool_calls.map((tool: any) => {
     const { name, arguments: arg, id } = tool;
     const func = name.split("--")[1];
-    const res = toolsTestDummyAgent(func, arg);
+    const toolResult = toolsTestDummyAgent(func, arg);
     messages.push({
       role: "tool",
       tool_call_id: id,
-      content: JSON.stringify(res) 
+      content: JSON.stringify(toolResult)
     });
   });

145-155: Guard for absent tool calls to make the test more robust.

OpenAI may return no tool calls. Add a basic guard to avoid runtime errors while keeping the test informative.

   const res = (await openAIAgent({
     ...defaultTestContext,
     namedInputs,
     params,
     filterParams: {
       streamTokenCallback: (data: any) => {
         console.log(JSON.stringify(data, null, 2));
       },
     },
   })) as any;
 
-  if (res) {
+  if (res) {
     console.log(res);
   }
+  if (!res?.tool_calls || res.tool_calls.length === 0) {
+    console.warn("No tool calls returned by the model.");
+  }

172-180: Add a minimal assertion on the second response to ensure a reply is generated.

Keeps this from being a pure smoke test and catches regressions.

   const res2 = (await openAIAgent({
     ...defaultTestContext,
     namedInputs: {messages},
     filterParams: {
       streamTokenCallback: (data: any) => {
         console.log(JSON.stringify(data, null, 2));
       },
     },
   })) as any;
 
   if (res2) {
     console.log(res2);
   }
+  assert.ok(res2?.message, "Expected a final assistant message after tool responses");
llm_agents/tools_agent/tests/common.ts (2)

84-86: Default namedInputs fields to avoid crashes when missing.

The agent assumes namedInputs.arg and namedInputs.func exist. Defaulting prevents accidental undefined access during future refactors.

-const toolsTestDummyAgent: AgentFunction = async ({ namedInputs }) => {
-  const { arg, func } = namedInputs;
+const toolsTestDummyAgent: AgentFunction = async ({ namedInputs }) => {
+  const { arg = {}, func = "" } = namedInputs ?? {};

94-101: Typo in "textSpeach" is intentional but consider documenting.

Keeping the misspelling aligns with legacy test cases, but a short comment helps future readers avoid “fixing” it inadvertently.

-  if (func === "textSpeach") {
+  // NOTE: "textSpeach" kept for backward-compatibility with legacy tests.
+  if (func === "textSpeach") {
llm_agents/tools_agent/tests/test_tools.ts (2)

52-54: Remove unused variable last.

This variable isn’t used and can be safely removed.

-  if (messages.length > 0 && messages[messages.length - 1].role === "tool") {
-    const last = messages[messages.length - 1];
+  if (messages.length > 0 && messages[messages.length - 1].role === "tool") {
     const toolIds = messages.filter((message: { role: string }) => message.role === "tool").map((message: { tool_call_id: string }) => message.tool_call_id);

84-86: Use an empty array for tools in these tests for clarity.

Since the dummy LLM ignores the tools schema, passing an empty array communicates intent better than [{}].

-          tools: [{}], // In fact, you set the tools schema here.
+          tools: [], // In fact, you set the tools schema here.

Also applies to: 122-126, 194-198

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

53-74: Optional: Coerce tool arguments to an object if they arrive as a JSON string.

Some LLM adapters return arguments as JSON strings. Safely parse before invoking tool agents.

         nodes: {
-          data: {
+          data: {
             agent: ({ passthrough, agentName }: { passthrough: Record<string, unknown>; agentName: string }) => {
               if (passthrough && passthrough[agentName]) {
                 return passthrough[agentName];
               }
               return {};
             },
             inputs: {
               passthrough: ":passthrough",
               agentName: ":llmToolCall.name.split(--).$0",
             },
           },
+          parsedArg: {
+            agent: ({ raw }: { raw: unknown }) => {
+              if (typeof raw === "string") {
+                try {
+                  return JSON.parse(raw);
+                } catch {
+                  return {};
+                }
+              }
+              return raw ?? {};
+            },
+            inputs: {
+              raw: ":llmToolCall.arguments",
+            },
+          },
           toolCallAgent: {
             isResult: true,
             agent: ":llmToolCall.name.split(--).$0",
             inputs: {
-              arg: ":llmToolCall.arguments",
+              arg: ":parsedArg",
               func: ":llmToolCall.name.split(--).$1",
               tool_call: ":llmToolCall",
               data: ":data",
             },
           },

9-16: llmModel is currently unused; either wire it or remove it.

If you intend to control the model, pass it through to the LLM calls. Otherwise, drop the node to avoid confusion.

Wire into both LLM calls:

     llmCallWithTools: {
       agent: ":llmAgent",
       isResult: true,
       params: {
         forWeb: true,
       },
       inputs: {
         messages: ":messages",
         prompt: ":userInput.text",
         tools: ":tools",
         params: {
           dataStream: ":stream",
+          model: ":llmModel",
         },
       },
     },

And:

     toolsResponseLLM: {
       agent: ":llmAgent",
       isResult: true,
       params: {
         forWeb: true,
       },
       inputs: {
         messages: ":toolsMessage.array",
         params: {
           dataStream: ":stream",
+          model: ":llmModel",
         },
       },
     },

100-112: Consider disabling tool-calls on the second LLM pass.

Once tool outputs are appended, the second LLM call usually should not trigger further tools. If supported by your LLM agent, set tool_choice: "none" (or equivalent) in params.

Would you like me to wire a flag (e.g., allowFollowupTools) to toggle this behavior?


121-135: Index-based merge assumes stable ordering; add a name-based fallback to be safe.

If any adapter reorders tool calls, mergedData could mismatch. A name-based map improves robustness.

-      agent: ({ llmToolCalls, data }: { llmToolCalls: { name: string }[]; data: unknown[] }) => {
-        const ret: Record<string, unknown> = {};
-        llmToolCalls.forEach((tool, index) => {
-          const { name } = tool;
-          ret[name] = data[index];
-        });
-        return ret;
-      },
+      agent: ({ llmToolCalls, data }: { llmToolCalls: { name: string }[]; data: unknown[] }) => {
+        const ret: Record<string, unknown> = {};
+        // Prefer index alignment, but guard by name if available
+        llmToolCalls.forEach((tool, index) => {
+          const key = tool?.name ?? `tool_${index}`;
+          ret[key] = data[index];
+        });
+        return ret;
+      },
📜 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 f257414 and d76a50e.

📒 Files selected for processing (5)
  • llm_agents/openai_agent/tests/run_openai_tools_parallel.ts (1 hunks)
  • llm_agents/tools_agent/src/tools_agent.ts (1 hunks)
  • llm_agents/tools_agent/tests/common.ts (1 hunks)
  • llm_agents/tools_agent/tests/run_openai.ts (1 hunks)
  • llm_agents/tools_agent/tests/test_tools.ts (6 hunks)
🔇 Additional comments (5)
llm_agents/tools_agent/tests/run_openai.ts (1)

15-29: Confirm that tools_agent actually enters the tools path with openAIAgent.

Given the tools_agent gating (currently checks :llmCallWithTools.tool.id), this test may inadvertently return just the text messages path even if the OpenAI response includes tool_calls. After fixing tools_agent (see my comment in src/tools_agent.ts), this test should exercise the full tool flow.

Would you like me to add an assertion for the tool responses (e.g., ensure tool messages are present) after we adjust the gating?

llm_agents/tools_agent/tests/common.ts (1)

3-82: Shared tools schema looks good and consistent with the new orchestration.

The tool names follow the agent--func convention and schemas are tight (additionalProperties: false). Solid foundation for tests.

llm_agents/tools_agent/tests/test_tools.ts (2)

131-181: Test expectations align with the new tools data merge and message aggregation.

The expected shape includes tools.data keyed by tool name and the final assistant message aggregating tool_call_ids. This matches the refactored tools agent behavior.


203-278: Parallel multi-tool test looks correct and asserts the aggregated success message.

Covers multiple tool calls and their merged data footprint adequately.

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

147-152: Result selection looks correct with the updated nodes.

arrayFindFirstExistsAgent prioritizing justTextMessagesResult then toolsResult is fine after the gating fix above.

Comment on lines 27 to 36
justTextMessagesResult: {
unless: ":llmCallWithTools.tool.id",
agent: "copyAgent",
agent: "pushAgent",
params: {
arrayKey: "messages",
},
inputs: {
messages: ":textMessagesResult.messages",
array: ":messages",
items: [{ role: "user", content: ":userInput.text" }, ":llmCallWithTools.message"],
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Bug: gating checks the wrong field (tool.id) and will skip tool flow for OpenAI responses.

OpenAI returns tool_calls (array), not tool. Using unless: :llmCallWithTools.tool.id triggers the “just text” path even when tools are requested.

Change gating to check tool_calls existence:

-    justTextMessagesResult: {
-      unless: ":llmCallWithTools.tool.id",
+    justTextMessagesResult: {
+      unless: ":llmCallWithTools.tool_calls",
       agent: "pushAgent",
       params: {
         arrayKey: "messages",
       },
       inputs: {
         array: ":messages",
         items: [{ role: "user", content: ":userInput.text" }, ":llmCallWithTools.message"],
       },
     },
📝 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
justTextMessagesResult: {
unless: ":llmCallWithTools.tool.id",
agent: "copyAgent",
agent: "pushAgent",
params: {
arrayKey: "messages",
},
inputs: {
messages: ":textMessagesResult.messages",
array: ":messages",
items: [{ role: "user", content: ":userInput.text" }, ":llmCallWithTools.message"],
},
justTextMessagesResult: {
unless: ":llmCallWithTools.tool_calls",
agent: "pushAgent",
params: {
arrayKey: "messages",
},
inputs: {
array: ":messages",
items: [{ role: "user", content: ":userInput.text" }, ":llmCallWithTools.message"],
},
🤖 Prompt for AI Agents
In llm_agents/tools_agent/src/tools_agent.ts around lines 27 to 36, the gating
currently checks :llmCallWithTools.tool.id which is wrong for OpenAI responses
(they use tool_calls), so replace that gating to check the presence of
tool_calls (e.g. use :llmCallWithTools.tool_calls or a check for its
length/first element) so the tool flow is exercised when tool_calls exist
instead of being skipped; update the unless expression accordingly to gate on
tool_calls existence.

Comment on lines +39 to 50
llmToolAgentCallMap: {
if: ":llmCallWithTools.tool.id",
agent: "mapAgent",
inputs: {
llmToolCalls: ":llmCallWithTools.tool_calls",
rows: ":llmCallWithTools.tool_calls",
passthrough: ":passthrough",
toolsResponseMessages: ":textMessagesResult.messages",
llmAgent: ":llmAgent",
},
params: {
compositeResult: true,
rowKey: "llmToolCall",
},
graph: {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Same gating issue in the tool-call map; use tool_calls.

Currently guarded by if: :llmCallWithTools.tool.id, which won’t be set for OpenAI paths.

-    llmToolAgentCallMap: {
-      if: ":llmCallWithTools.tool.id",
+    llmToolAgentCallMap: {
+      if: ":llmCallWithTools.tool_calls",
       agent: "mapAgent",
       inputs: {
         rows: ":llmCallWithTools.tool_calls",
         passthrough: ":passthrough",
       },
       params: {
         compositeResult: true,
         rowKey: "llmToolCall",
       },
📝 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
llmToolAgentCallMap: {
if: ":llmCallWithTools.tool.id",
agent: "mapAgent",
inputs: {
llmToolCalls: ":llmCallWithTools.tool_calls",
rows: ":llmCallWithTools.tool_calls",
passthrough: ":passthrough",
toolsResponseMessages: ":textMessagesResult.messages",
llmAgent: ":llmAgent",
},
params: {
compositeResult: true,
rowKey: "llmToolCall",
},
graph: {
llmToolAgentCallMap: {
if: ":llmCallWithTools.tool_calls",
agent: "mapAgent",
inputs: {
rows: ":llmCallWithTools.tool_calls",
passthrough: ":passthrough",
},
params: {
compositeResult: true,
rowKey: "llmToolCall",
},
graph: {
🤖 Prompt for AI Agents
In llm_agents/tools_agent/src/tools_agent.ts around lines 39 to 50, the map step
is gated with if: ":llmCallWithTools.tool.id" which fails for OpenAI paths;
change the guard to check for the presence of tool_calls (e.g. if
":llmCallWithTools.tool_calls" or if a non-empty list via length) so the map
runs when tool_calls exist, and ensure the inputs.rows continues to use
":llmCallWithTools.tool_calls".

@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/tools_agent/tests/test_tools.ts (1)

359-377: test 3 expectations are out of sync with the new message/result shape

This block still asserts the legacy shape:

  • Includes name on the "tool" role message (Line 361), which tests 1 and 2 removed.
  • Embeds extra.data in the "tool" message (Lines 368-371), which tests 1 and 2 removed.
  • Expects assistant content based on the tool message content ("success getWeather Tokyo"), but llmDummy now summarizes via tool_call_id (e.g., "success call_1").

Please align test 3 with the updated shape (consistent with tests 1 and 2). Example corrected expectation snippet:

const expect = {
  tools: {
    data: {
      "toolsTestAgent--getWeather": {
        content: "getWeather Tokyo",
        data: { weather: "fine" },
      },
    },
    messages: [
      {},
      {},
      { content: "test1", role: "user" },
      {
        role: "assistant",
        tool_calls: [
          {
            id: "call_1",
            name: "toolsTestAgent--getWeather",
            arguments: { location: "Tokyo" },
          },
        ],
      },
      {
        role: "tool",
        tool_call_id: "call_1",
        content: "getWeather Tokyo",
        extra: {
          agent: "toolsTestAgent",
          arg: { location: "Tokyo" },
          func: "getWeather",
        },
      },
      { role: "assistant", content: "success call_1" },
    ],
    toolsResults: [
      {
        agent: "toolsTestAgent",
        data: {
          content: "getWeather Tokyo",
          data: { weather: "fine" },
        },
        func: "getWeather",
      },
    ],
  },
};

This keeps name only on assistant.tool_calls, removes name and embedded data from the "tool" message, and updates the assistant’s final content to use tool_call_id.

🧹 Nitpick comments (2)
llm_agents/tools_agent/tests/test_tools.ts (2)

53-57: Deriving success text from tool_call_id is correct; add guards to avoid undefined and tighten types

If any tool message lacks tool_call_id, the join could include "undefined". Add a presence check and avoid implicit any.

Apply this diff:

-    const toolIds = messages.filter((message: { role: string }) => message.role === "tool").map((message: { tool_call_id: string }) => message.tool_call_id);
+    const toolIds = messages
+      .filter((m: { role?: string; tool_call_id?: string }) => m.role === "tool" && typeof m.tool_call_id === "string")
+      .map((m: { tool_call_id: string }) => m.tool_call_id as string);

Note: Line 52’s const last = ... is now unused; consider removing it.


52-52: Remove unused variable

const last = messages[messages.length - 1]; is no longer used; please remove to avoid lint warnings.

📜 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 d76a50e and 01afe55.

📒 Files selected for processing (1)
  • llm_agents/tools_agent/tests/test_tools.ts (6 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). (1)
  • GitHub Check: build (22.x)
🔇 Additional comments (8)
llm_agents/tools_agent/tests/test_tools.ts (8)

6-7: Good refactor: shared test agent import

Switching to the shared toolsTestAgent from ./common removes duplication and keeps tests consistent across files. LGTM.


136-143: New tools.data assertion looks right

Validating the data map keyed by "toolsTestAgent--getWeather" with content/data mirrors the new result shape. LGTM.


147-147: User message expectation aligned

Ensures the initial user input "test1" is captured in messages. Looks good.


175-175: Assistant summary now reflects tool_call_id

The success summary using the tool_call_id ("success call_1") aligns with the new aggregation logic in llmDummy. LGTM.


220-233: tools.data for multiple tool results is correct

Asserting both getWeather and textSpeach entries under tools.data matches the new per-tool aggregation. LGTM.


237-237: User message expectation aligned (test2)

Confirms "test2" prompt is captured as the user message. Looks good.


245-247: Tool call arguments shape is consistent

Arguments for getWeather are correctly specified under tool_calls. LGTM.


284-284: Assistant summary for multiple calls is correct

"success call_1, call_2" matches the new tool_call_id aggregation logic. LGTM.

@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

♻️ Duplicate comments (2)
llm_agents/tools_agent/src/tools_agent.ts (2)

27-36: Fix gating: check tool_calls presence instead of tool.id to avoid skipping tool flow

OpenAI-style responses provide tool_calls (array). Gating on tool.id causes the “just text” path to run even when tools were actually requested/returned. Tests pass because llmDummy injects a non-standard tool field; real agents won’t. Use tool_calls (preferably first element) for gating.

Apply this diff:

-    justTextMessagesResult: {
-      unless: ":llmCallWithTools.tool.id",
+    justTextMessagesResult: {
+      unless: ":llmCallWithTools.tool_calls.$0",
       agent: "pushAgent",
       params: {
         arrayKey: "messages",
       },
       inputs: {
         array: ":messages",
         items: [{ role: "user", content: ":userInput.text" }, ":llmCallWithTools.message"],
       },
     },

39-50: Same gating issue in the tool-call map; use tool_calls (preferably first element) for the condition

The map step is guarded by if: :llmCallWithTools.tool.id while rows already use :llmCallWithTools.tool_calls. This inconsistency will skip tool execution for OpenAI paths.

Apply this diff:

-    llmToolAgentCallMap: {
-      if: ":llmCallWithTools.tool.id",
+    llmToolAgentCallMap: {
+      if: ":llmCallWithTools.tool_calls.$0",
       agent: "mapAgent",
       inputs: {
         rows: ":llmCallWithTools.tool_calls",
         passthrough: ":passthrough",
       },
🧹 Nitpick comments (3)
llm_agents/tools_agent/src/tools_agent.ts (2)

9-10: Unused workflow state “llmModel”

llmModel isn’t referenced elsewhere. Remove it or wire it through to llm calls (e.g., as params.model).

Apply this diff to remove (if unused):

-    llmModel: { value: "" },
-    stream: { value: true },
+    stream: { value: true },

168-181: Nit: clarify sample function description

Minor wording improvement to make the sample clearer to readers.

-              description: "Switch of light",
+              description: "Toggle the light on or off",
llm_agents/tools_agent/tests/test_tools.ts (1)

208-221: Covers multi-tool data aggregation

Ensures both tools’ content and data are included. Suggest adding a future test with duplicate tool names to validate mergedData grouping logic (after refactor).

I can add a test variant that invokes the same tool twice to validate duplicate handling once mergedData is updated. Want me to open a follow-up?

📜 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 01afe55 and a94d5f8.

📒 Files selected for processing (5)
  • llm_agents/openai_agent/tests/run_openai_tools_parallel.ts (1 hunks)
  • llm_agents/tools_agent/src/tools_agent.ts (1 hunks)
  • llm_agents/tools_agent/tests/common.ts (1 hunks)
  • llm_agents/tools_agent/tests/run_openai.ts (1 hunks)
  • llm_agents/tools_agent/tests/test_tools.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • llm_agents/tools_agent/tests/run_openai.ts
  • llm_agents/tools_agent/tests/common.ts
  • llm_agents/openai_agent/tests/run_openai_tools_parallel.ts
⏰ 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 (7)
llm_agents/tools_agent/src/tools_agent.ts (3)

92-111: Streaming wiring looks good

Passing dataStream: :stream into both LLM calls enables toggling streaming centrally. This aligns with the PR objective of a streaming-capable flow.


147-152: Result selection via arrayFindFirstExistsAgent looks correct

Combining justTextMessagesResult and toolsResult and selecting the first existing is appropriate after fixing the gating conditions above.


27-50: No other references to llmCallWithTools.tool.id found

I ran a repo-wide search and only found those two occurrences in src/tools_agent.ts (lines 28 and 40) and their counterparts in lib/tools_agent.js. There are no remaining gates or references elsewhere.

llm_agents/tools_agent/tests/test_tools.ts (4)

6-7: Good move: centralize test tools via common.ts

Sharing toolsTestAgent across tests reduces duplication and improves maintainability.


53-58: Assistant reply aggregation based on tool messages is fine

Collecting tool_call_id from tool messages ensures the final assistant reply acknowledges all executed calls in order.


136-144: Expectation updated to include tools.data payloads

Validates the new merged data shape per tool. This aligns with the revamped tools path.


271-273: Final assistant message reflects all tool calls

Confirms correct aggregation of multiple tool results into the assistant response.

Comment on lines +127 to +135
agent: ({ llmToolCalls, data }: { llmToolCalls: { name: string }[]; data: unknown[] }) => {
const ret: Record<string, unknown> = {};
llmToolCalls.forEach((tool, index) => {
const { name } = tool;
ret[name] = data[index];
});
return ret;
},
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

mergedData overwrites duplicate tool names; group by name or key by id to avoid data loss

Using tool.name as the object key will drop earlier results when the same tool is called multiple times. This is a common scenario (e.g., multiple getWeather calls). Preserve all results by grouping duplicates into arrays.

Apply this diff:

-      agent: ({ llmToolCalls, data }: { llmToolCalls: { name: string }[]; data: unknown[] }) => {
-        const ret: Record<string, unknown> = {};
-        llmToolCalls.forEach((tool, index) => {
-          const { name } = tool;
-          ret[name] = data[index];
-        });
-        return ret;
-      },
+      agent: ({ llmToolCalls, data }: { llmToolCalls: { name: string; id?: string }[]; data: unknown[] }) => {
+        const ret: Record<string, unknown | unknown[]> = {};
+        llmToolCalls.forEach((tool, index) => {
+          const key = tool.name;
+          const value = data[index];
+          if (ret[key] === undefined) {
+            ret[key] = value;
+          } else if (Array.isArray(ret[key])) {
+            (ret[key] as unknown[]).push(value);
+          } else {
+            ret[key] = [ret[key] as unknown, value];
+          }
+        });
+        return ret;
+      },

If you prefer stable keys, consider additionally emitting an id-keyed map alongside the name-grouped object.

📝 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
agent: ({ llmToolCalls, data }: { llmToolCalls: { name: string }[]; data: unknown[] }) => {
const ret: Record<string, unknown> = {};
llmToolCalls.forEach((tool, index) => {
const { name } = tool;
ret[name] = data[index];
});
return ret;
},
},
agent: ({ llmToolCalls, data }: { llmToolCalls: { name: string; id?: string }[]; data: unknown[] }) => {
const ret: Record<string, unknown | unknown[]> = {};
llmToolCalls.forEach((tool, index) => {
const key = tool.name;
const value = data[index];
if (ret[key] === undefined) {
ret[key] = value;
} else if (Array.isArray(ret[key])) {
(ret[key] as unknown[]).push(value);
} else {
ret[key] = [ret[key] as unknown, value];
}
});
return ret;
},
🤖 Prompt for AI Agents
In llm_agents/tools_agent/src/tools_agent.ts around lines 127 to 135, the
current agent function keys merged results by tool.name which overwrites earlier
entries when the same tool is called multiple times; change the logic to
preserve all results by grouping values under each name into arrays (e.g., if a
name already exists push the new data into the array, otherwise create a new
array), and optionally also produce an id-keyed map (use call index or an
explicit id from llmToolCalls) if consumers need stable unique keys; ensure the
return type reflects grouped arrays (Record<string, unknown[]>) or include both
maps (name->array and id->value) as needed.

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