Skip to content

Add support for multiple function calling for Gemini - #1267

Merged
ystknsh merged 3 commits into
receptron:mainfrom
masap:fix-1266
Jan 25, 2026
Merged

ystknsh merged 3 commits into
receptron:mainfrom
masap:fix-1266

Conversation

@masap

@masap masap commented Jan 24, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #1266.

Summary by CodeRabbit

  • Improvements

    • Improved handling of tool invocations so streaming and non-stream responses reliably aggregate partial tool outputs, yielding more accurate and complete tool-call results and better mapping of tool-call metadata in final responses for multi-tool scenarios.
  • Tests

    • Added test coverage for multiple-tool scenarios, including streaming flows and validation of aggregated tool-call results.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 24, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Convert Gemini agent to collect and pass multiple function calls: converter signature updated to accept a functionCalls array; streaming path accumulates chunk-level functionCalls and supplies them to the converter; tests added for multi-tool streaming.

Changes

Cohort / File(s) Summary
Core runtime (JS)
llm_agents/gemini_agent/lib/gemini_agent.js
convertOpenAIChatCompletion signature changed to (response, functionCalls, messages, llmMetaData); streaming now collects chunk.functionCalls into an array and passes it to the converter; non-stream path supplies an empty array.
Core runtime (TS)
llm_agents/gemini_agent/src/gemini_agent.ts
Added FunctionCall import; updated convertOpenAIChatCompletion signature to accept functionCalls: FunctionCall[]; streaming accumulates functionCalls and passes them into conversion; final result maps tool_calls from provided functionCalls; exported geminiAgent type now AgentFunction<GeminiParams, GeminiResult, GeminiInputs, GeminiConfig>.
Tests
llm_agents/gemini_agent/tests/run_gemini.ts
Added "test gemini multiple tools" using multiple tool definitions with stream: true; existing test updated to print res.tool_calls.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Agent
    participant GeminiAPI
    participant Converter

    Client->>Agent: call geminiAgent(params, stream:true)
    Agent->>GeminiAPI: start streaming GenerateContent request
    GeminiAPI-->>Agent: stream chunks (content + optional chunk.functionCalls)
    Agent->>Agent: accumulate chunk.functionCalls into functionCalls[]
    Agent->>Converter: convertOpenAIChatCompletion(response, functionCalls, messages, llmMetaData)
    Converter-->>Agent: standardized result (includes tool_calls derived from functionCalls)
    Agent-->>Client: deliver final result (messages + tool_calls)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hop through streams and gather each call,
Chunks in my basket, I bring them to all.
Tools line up neatly, assembled with care,
Many small hops make one tidy hare. 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and concisely describes the main change: adding support for multiple function calling for the Gemini model, which aligns with the primary objective.
Linked Issues check ✅ Passed The PR implements the core requirement from issue #1266 to collect and handle multiple function/tool calls from Gemini, with signature updates and streaming aggregation logic.
Out of Scope Changes check ✅ Passed The PR contains changes scoped to Gemini agent implementation and related tests; no out-of-scope modifications to unrelated systems are evident.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
llm_agents/gemini_agent/lib/gemini_agent.js (1)

11-24: Add stable, unique IDs to tool_calls for proper response correlation.

Multiple tool calls receive hardcoded id: "dummy", preventing tools_agent from mapping tool responses to the correct calls. Additionally, message.tool_calls lacks id and type fields required for OpenAI-style tool response handling. During streaming, aggregated calls will all collide on the same ID, breaking multi-tool workflows.

Generate unique IDs per call using call.id ?? gemini_${idx}`` for both tool_calls and `message.tool_calls`, and add the `type: "function"` field to match OpenAI format.

🧹 Nitpick comments (3)
llm_agents/gemini_agent/lib/gemini_agent.js (1)

129-134: Streaming aggregation may duplicate partial functionCalls.

If @google/genai streams the full functionCalls array on each chunk (or sends partial updates for the same call), push(...chunk.functionCalls) can duplicate or fragment calls. Consider replacing with the latest snapshot or de-duping by id/name after confirming SDK semantics.

♻️ Possible adjustment (if chunks include full snapshots)
-            if (chunk.functionCalls) {
-                functionCalls.push(...chunk.functionCalls);
-            }
+            if (chunk.functionCalls) {
+                functionCalls = chunk.functionCalls;
+            }
llm_agents/gemini_agent/tests/run_gemini.ts (1)

56-104: Add a minimal assertion for multi-tool coverage.

The new test is a pure smoke test (always true). To guard the new feature, consider asserting at least that tool_calls is an array (or use a mocked/recorded response for deterministic expectations).

✅ Example minimal assertion
   if (res) {
     console.log(res);
     console.log(res.tool_calls);
+    assert.ok(Array.isArray(res.tool_calls), "tool_calls should be an array");
   }
llm_agents/gemini_agent/src/gemini_agent.ts (1)

181-187: Streaming aggregation may duplicate partial functionCalls.

If @google/genai emits the full functionCalls list per chunk (or partial updates for the same call), pushing into the array can create duplicates or fragmented calls. Consider replacing with the latest snapshot or de-duping after verifying SDK semantics.

♻️ Possible adjustment (if chunks include full snapshots)
-      if (chunk.functionCalls) {
-        functionCalls.push(...chunk.functionCalls);
-      }
+      if (chunk.functionCalls) {
+        functionCalls = chunk.functionCalls;
+      }

@ystknsh

ystknsh commented Jan 24, 2026

Copy link
Copy Markdown
Contributor

@masap

Thank you for the PR!!

To verify that the change (collecting multiple tool calls) works correctly, could you add a check for res.tool_calls.length === 2 in test gemini multiple tools?

@masap

masap commented Jan 24, 2026

Copy link
Copy Markdown
Contributor Author

@ystknsh Thank you for your comment. I'd like to confirm one thing. Looking at other directories, tests starting with test_ verify results using assert.deepStrictEqual. However, tests starting with run_ use assert.deepStrictEqual(true, true); and do not verify the test results. I modified run_gemini.ts this time. Do I need to add code to verify the test results?

@ystknsh

ystknsh commented Jan 24, 2026

Copy link
Copy Markdown
Contributor

In my environment, the test passed with only one tool call returned:

[
  {
    id: 'dummy',
    name: 'generalToolAgent--get_weather',
    arguments: { city: 'Tokyo' }
  }
]

It doesn't have to be an assert - just something that makes it clear when multiple tool calls aren't being returned (e.g., logging tool_calls.length).

@masap

masap commented Jan 25, 2026

Copy link
Copy Markdown
Contributor Author

Ah, ok I understand what you're trying to say. Gemini doesn't call the function 100% of the time, which is why the issue you mentioned occurs. I tried it ten times, and nine times it called it twice, but one time it only called it once. So, could you please try it a few times?

[
  {
    id: 'dummy',
    name: 'generalToolAgent--get_weather',
    arguments: { city: 'Tokyo' }
  },
  {
    id: 'dummy',
    name: 'generalToolAgent--get_fx_rate',
    arguments: { pair: 'USDJPY' }
  }
]

@masap

masap commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor Author

This is because Gemini defaults to function_calling_config = AUTO [1], which causes it to choose between using function calls or responding in natural language. It is also possible to correct Gemini to use function calls. Since this PR concerns multiple function calls, I can implement the function calling method in a separate PR.

[1] https://ai.google.dev/gemini-api/docs/function-calling?example=meeting#function_calling_modes

@ystknsh

ystknsh commented Jan 25, 2026

Copy link
Copy Markdown
Contributor

I understand that retrying the test may return 2 tool calls.
However, the problem is that the test result (pass/fail) is the same whether 1 or 2 tool calls are returned.

You don't need to change the pass/fail result - just add a log so we can tell from the output.

tool_calls.length: ${res.tool_calls.length} (expected: 2, may vary due to Gemini AUTO mode)

Also, looking forward to the separate PR for forcing function calling!!

Signed-off-by: Masashi Honma <[email protected]>
@masap

masap commented Jan 25, 2026

Copy link
Copy Markdown
Contributor Author

Sure, fixed.

@ystknsh

ystknsh commented Jan 25, 2026

Copy link
Copy Markdown
Contributor

Thank you for adding the log!
Now we can clearly see whether multiple tool calls are working or not.

[
  {
    id: 'dummy',
    name: 'generalToolAgent--get_weather',
    arguments: { city: 'Tokyo' }
  }
]
tool_calls.length: 1 (expected: 2, may vary due to Gemini AUTO mode)
[
  {
    id: 'dummy',
    name: 'generalToolAgent--get_weather',
    arguments: { city: 'Tokyo' }
  },
  {
    id: 'dummy',
    name: 'generalToolAgent--get_fx_rate',
    arguments: { pair: 'MYRJPY' }
  }
]
tool_calls.length: 2 (expected: 2, may vary due to Gemini AUTO mode)
[]
tool_calls.length: 0 (expected: 2, may vary due to Gemini AUTO mode)

@ystknsh
ystknsh merged commit fa329cc into receptron:main Jan 25, 2026
@masap
masap deleted the fix-1266 branch January 25, 2026 08:37
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.

Add support for multiple function calling for Gemini

2 participants