Repository navigation
Tools palla - #1212
Tools palla#1212
Conversation
|
Warning Rate limit exceeded@isamu has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 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 We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (2)
WalkthroughReworks 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
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)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 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.argumentsas 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 outerresconstant 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: DefaultnamedInputsfields to avoid crashes when missing.The agent assumes
namedInputs.argandnamedInputs.funcexist. 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 variablelast.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
argumentsas 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:llmModelis 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,
mergedDatacould 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.
📒 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 includestool_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--funcconvention 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.datakeyed 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.
arrayFindFirstExistsAgentprioritizingjustTextMessagesResultthentoolsResultis fine after the gating fix above.
| 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"], | ||
| }, |
There was a problem hiding this comment.
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.
| 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.
| 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: { |
There was a problem hiding this comment.
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.
| 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".
There was a problem hiding this comment.
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 shapeThis 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 typesIf 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.
📒 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 importSwitching to the shared toolsTestAgent from ./common removes duplication and keeps tests consistent across files. LGTM.
136-143: New tools.data assertion looks rightValidating the data map keyed by "toolsTestAgent--getWeather" with content/data mirrors the new result shape. LGTM.
147-147: User message expectation alignedEnsures the initial user input "test1" is captured in messages. Looks good.
175-175: Assistant summary now reflects tool_call_idThe 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 correctAsserting 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 consistentArguments 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.
There was a problem hiding this comment.
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 flowOpenAI-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 conditionThe 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 descriptionMinor 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 aggregationEnsures 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.
📒 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 goodPassing 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 correctCombining justTextMessagesResult and toolsResult and selecting the first existing is appropriate after fixing the gating conditions above.
27-50: No other references tollmCallWithTools.tool.idfoundI ran a repo-wide search and only found those two occurrences in
src/tools_agent.ts(lines 28 and 40) and their counterparts inlib/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.tsSharing toolsTestAgent across tests reduces duplication and improves maintainability.
53-58: Assistant reply aggregation based on tool messages is fineCollecting 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 payloadsValidates the new merged data shape per tool. This aligns with the revamped tools path.
271-273: Final assistant message reflects all tool callsConfirms correct aggregation of multiple tool results into the assistant response.
| 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; | ||
| }, | ||
| }, |
There was a problem hiding this comment.
🛠️ Refactor suggestion
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.
| 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.
Summary by CodeRabbit
New Features
Refactor
Tests