Skip to content

fix(provider): support combining Gemini built-in tools with function calling - #11078

Open
DOTBave wants to merge 6 commits into
AstrBotDevs:masterfrom
DOTBave:fix/gemini-tool-combination
Open

DOTBave wants to merge 6 commits into
AstrBotDevs:masterfrom
DOTBave:fix/gemini-tool-combination

Conversation

@DOTBave

@DOTBave DOTBave commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #9937.

Motivation

Since #8833 allowed Gemini built-in tools (gm_native_search, gm_native_coderunner, gm_url_context) and custom function declarations (function_declarations) to coexist in one generateContent request, any such combination on Gemini 3+ models fails with cascading 400 INVALID_ARGUMENT errors:

  1. Turn 1: Please enable tool_config.include_server_side_tool_invocations to use Built-in tools with Function calling. The combination requires include_server_side_tool_invocations=True and FunctionCallingConfigMode.VALIDATED (AUTO is rejected once the flag is enabled). It only works on Gemini 3+ with google-genai>=1.68.0; older SDKs now log a warning and omit the flag instead of failing with a pydantic error.
  2. Turn 2: functionResponse.name "<call_id>" does not match functionCall.name "<name>" — tool results only carry tool_call_id, so the function name was lost — and the server-side toolCall / toolResponse parts from turn 1 were dropped instead of replayed.
  3. _prepare_conversation could also copy a tool part's thought_signature onto narration text, duplicating signatures in the replayed history.

Related: #9978 (early flag-only PR, superseded by this one), #10174 (name mapping; the functionResponse.id half stays with #9760 / #9761), #10961 (touches thinking config in the same function, non-overlapping hunks), #11219 (keeps the google-genai>=1.56.0 dependency floor unchanged).

Modifications / 改动点

  • astrbot/core/provider/sources/gemini_source.py
    • _prepare_query_config: detect built-in tools combined with function_declarations on Gemini 3/4 (reusing is_gemini_4 or model_name.startswith(("gemini-3-", "gemini-3.")) after gateway prefix stripping, consistent with thinking_config), switch to VALIDATED / ANY (tool_choice="required"), and add include_server_side_tool_invocations=True. The flag is only sent when the installed SDK defines the field; otherwise a warning is logged and the flag is omitted.
    • _prepare_conversation: persist tool_call_id -> function name while iterating assistant tool calls and use it for FunctionResponse.name; replay saved server-side parts (extra_content.google.server_parts) in response order with their signatures; suppress a narration signature only when it duplicates a tool part's signature (compare by value, not by presence).
    • _process_content_parts / _query_stream: capture server-side tool_call / tool_response / executable_code / code_execution_result parts (accumulating across stream chunks) and attach them to the first custom tool call's extra_content.google.server_parts; keep server-part signatures out of reasoning_signature.
  • tests/test_gemini_source.py: 7 new test functions covering the full config matrix (opt-in, model aliases, required, function-only, built-in-only, legacy models, old-SDK fallback), server-part capture/replay (streaming + non-streaming), name resolution, and signature deduplication/isolation.

Behavior Matrix

Scenario function_calling_config.mode include_server_side_tool_invocations Changed?
Function tools only AUTO (or ANY if required) None No
Built-in tools only tool_config = None None No
Gemini 1.x / 2.x + built-in + function tools AUTO / ANY None No (combination not supported by the API)
Gemini 3/4 + built-in + function tools VALIDATED / ANY True Yes (previously 400)
google-genai<1.68.0 + Gemini 3/4 + built-in + function tools VALIDATED / ANY omitted (warning logged) Fallback (flag omitted; avoids pydantic error)

Known limitations

  • Completed built-in-tool-only turns are not persisted. A turn that used a built-in tool but emitted no custom function_call has no history slot for toolCall/toolResponse in AstrBot's provider-agnostic message model. The same-turn tool loop is covered; cross-turn persistence would need a provider-specific history field and would re-bill those parts on every later request, so it is out of scope here.

  • skills_like tool-schema mode (runner-level, pre-existing). tool_schema_mode defaults to full. In skills_like, ToolLoopAgentRunner._step copies only tool names/args/IDs after the re-query, so tools_call_extra_content remains keyed by the original IDs and thought_signature / server_parts are dropped during serialization. This predates this PR and needs a runner-level decision about which response is authoritative; out of scope for this provider fix.

  • functionResponse.id round-tripping is tracked in [Bug] Gemini functionResponse 未正确保留 name/id,导致 cpa-Antigravity 工具调用失败 #9760 / fix: keep Gemini functionResponse name/id paired #9761; strict relay/proxy backends are not covered by the e2e runs below.

  • Runtime SDK requirement (google-genai>=1.68.0, dependency floor intentionally unchanged). include_server_side_tool_invocations and Part.tool_call/Part.tool_response require google-genai>=1.68.0. Consistent with feat: gemini 4 model series reasoning effort support without bumping google-genai #11219 (which avoids bumping google-genai due to the WebUI upgrade issue on AstrBot <=4.29.2), pyproject.toml and requirements.txt remain at >=1.56.0. Fresh installs resolve to a current release automatically; existing environments stuck on <1.68.0 will log a warning instead of failing with a pydantic error and need to upgrade google-genai manually to use combined tools.

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

$ uv run pytest tests/test_gemini_source.py -q
39 passed, 1 warning in 10.12s

$ uv run pytest tests/ -k gemini -q
43 passed, 5849 deselected, 7 warnings in 31.99s

$ uv run ruff format --check .
599 files already formatted

$ uv run ruff check .
All checks passed!

End-to-end (official Gemini API, gemini-3.8-flash, gm_native_search + a generate_image plugin tool)

Before: turn 1 fails with

400 INVALID_ARGUMENT: Please enable tool_config.include_server_side_tool_invocations to use Built-in tools with Function calling.

After (run on gemini-3.8-flash before simplifying the test suite and switching model detection to reuse is_gemini_4 or model_name.startswith(("gemini-3-", "gemini-3.")); behavior for gemini-3.8-flash is unchanged):

[15:05:09] <user>: 搜索崩坏三的角色,希儿·芙乐艾,并画出她。
[15:05:17] [runners.tool_loop_agent_runner:1416]: Agent 使用工具: ['generate_image']
[15:05:31] [runners.tool_loop_agent_runner:1681]: Tool `generate_image` Result: 系统提示:已成功下发 1 张图。
[15:05:34] [respond.stage:237]: Prepare to send - <user>: **角色信息检索**:... 已生成其经典形态 ... 的立绘。

Not covered by this run: built-in-tool-only turns (unit tested; the rejection is not reproducible on demand), Gemini 2.5 shapes (the flag is only enabled for Gemini 3/4), strict relay endpoints (#9937 / #9760), and tool_choice="required" (config-level tests only).


Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc. / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。
  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above. / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。
  • 📚 I checked the affected WebUI instructions and screenshots in docs/zh and docs/en against the changed navigation, page structure, and labels, and updated them in this PR (or explained why no documentation update is needed). / 我已对照变化后的 WebUI 入口、页面结构和术语,核对并在本 PR 中更新 docs/zh 和 docs/en 的相关操作说明与截图(或说明无需更新文档的原因)。
  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml. / 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到 requirements.txt 和 pyproject.toml 文件相应位置。
  • 😮 My changes do not introduce malicious code. / 我的更改没有引入恶意代码。

@sourcery-ai

sourcery-ai Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit bf8fc3e

#9937 [Bug] gemini API格式工具调用必定报错 · 2 of 2 met

# Requirement Status Notes
1 Allow Gemini 3.8 built-in tools and function calling to work together without the reported 400 error. ✅ Met The request config opts into server-side tool invocations for Gemini 3/4 combinations and uses VALIDATED mode; the change also preserves and replays server-side tool parts for subsequent tool-loop turns.
2 Match a tool result to the original function name rather than the tool-call ID. ✅ Met _prepare_conversation records tool-call IDs and function names, then uses that mapping for FunctionResponse.name.

@sourcery-ai sourcery-ai 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.

Hey - I've found 8 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="506-507" />
<code_context>
+                        # carry their own thought signatures. Attaching the same
+                        # signature to the narration part would send it twice, so
+                        # leave the narration part unsigned and skip it when empty.
+                        if text:
+                            parts.append(types.Part(text=text))
                     else:
                         parts.append(
</code_context>
<issue_to_address>
**Gemini history loses part order**

When a Gemini response interleaves narration, server-side parts, and custom function calls, including across stream chunks, `_process_content_parts` stores server-side parts separately, and `_prepare_conversation` replays them before function calls; `_query_stream` also returns at a function-call chunk without collecting later chunks. The next request therefore sends reordered or incomplete tool history, which Gemini can reject or mis-handle.

Preserve the original order of narration, server-side parts, and function calls, and collect all relevant parts before returning a streamed response.

Also at `astrbot/core/provider/sources/gemini_source.py:527-538`, `astrbot/core/provider/sources/gemini_source.py:722-743`, `astrbot/core/provider/sources/gemini_source.py:931`, `astrbot/core/provider/sources/gemini_source.py:971`.
</issue_to_address>

### Comment 2
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="735" />
<code_context>
+            or getattr(part, "executable_code", None)
+            or getattr(part, "code_execution_result", None)
+        ]
+        if server_side_parts and llm_response.tools_call_ids:
+            google_extra = llm_response.tools_call_extra_content.setdefault(
+                llm_response.tools_call_ids[0], {}
</code_context>
<issue_to_address>
**Built-in tool history disappears**

When gemini returns server-side tool parts without a custom function call and the conversation continues, `_process_content_parts` and the streaming path attach server-side parts only to custom tool calls, while the runner stores only assistant text when there is no custom call. The next Gemini request omits the built-in tool history and can fail validation or lose tool context.

Persist server-side parts in the response history even when Gemini returns no custom function call.

Also at `astrbot/core/provider/sources/gemini_source.py:940-941`, `astrbot/core/provider/sources/gemini_source.py:971-978`.
</issue_to_address>

### Comment 3
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="501" />
<code_context>
-                        pass
+                        for tool in message.get("tool_calls") or []
+                    )
+                    if thinking_signature and has_tool_thought_signature:
+                        # Tool calls and replayed server-side tool parts already
+                        # carry their own thought signatures. Attaching the same
</code_context>
<issue_to_address>
**Narration signature is omitted**

When the narration signature differs from a signature on a tool or server-side part, `_prepare_conversation` treats any tool or server-side signature as a duplicate without comparing values, so it omits the narration signature. Gemini receives incomplete signed history on the next request.

Suppress the narration signature only when a tool or server-side part carries the same signature.
</issue_to_address>

### Comment 4
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="736-740" />
<code_context>
+            or getattr(part, "code_execution_result", None)
+        ]
+        if server_side_parts and llm_response.tools_call_ids:
+            google_extra = llm_response.tools_call_extra_content.setdefault(
+                llm_response.tools_call_ids[0], {}
+            ).setdefault("google", {})
+            google_extra["server_parts"] = [
+                *server_side_parts,
+                *(google_extra.get("server_parts") or []),
+            ]
</code_context>
<issue_to_address>
**Requery loses server-side context**

When the `skills_like` path re-queries and returns different tool-call IDs, `ToolLoopAgentRunner._step` replaces the tool-call IDs without transferring `tools_call_extra_content`, leaving the saved server-side parts under the original IDs. The next Gemini request omits that context.

Transfer the saved `tools_call_extra_content` to the re-query's tool-call IDs.

Also at `astrbot/core/provider/sources/gemini_source.py:735`.
</issue_to_address>

### Comment 5
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="735-743" />
<code_context>
+            or getattr(part, "executable_code", None)
+            or getattr(part, "code_execution_result", None)
+        ]
+        if server_side_parts and llm_response.tools_call_ids:
+            google_extra = llm_response.tools_call_extra_content.setdefault(
+                llm_response.tools_call_ids[0], {}
+            ).setdefault("google", {})
+            google_extra["server_parts"] = [
+                *server_side_parts,
+                *(google_extra.get("server_parts") or []),
+            ]
         chain_result = MessageChain(chain=chain)
         llm_response.result_chain = chain_result
         if validate_output:
</code_context>
<issue_to_address>
**Skills requery drops server context**

When skills-like tool schema mode is enabled and Gemini returns server-side parts with a custom tool call, `_resolve_tool_exec` builds its parameter requery from `run_context.messages`, which does not yet contain the current response, then replaces or rewrites that response’s tool calls. The requery therefore omits the captured server-side parts, and the later tool-loop request loses them too.

Include the current response’s server-side parts in the parameter requery context and preserve them under the resulting tool-call ID.
</issue_to_address>

### Comment 6
<location path="tests/test_gemini_source.py" line_range="677" />
<code_context>
+    assert parts[0].tool_call.id == "search-1"
+    assert parts[0].thought_signature == b"\x01\x02"
+    assert parts[1].tool_response is not None
+    assert parts[2].function_call is not None
+    assert parts[2].function_call.name == "generate_image"
+    assert parts[2].thought_signature == b"\x03"
</code_context>
<issue_to_address>
**Lost tool payloads go unnoticed**

When replayed server-side parts retain their wrapper but lose payload fields, when replay serialization drops a server-side part’s fields but leaves its wrapper present, `test_gemini_prepare_conversation_replays_server_side_tool_parts` passes because it checks only that `tool_response` is non-`None`; the streaming test checks only key presence and order, so lost IDs or response data go unnoticed.

Assert that replayed and streamed server-side parts preserve their IDs, tool types, arguments, responses, and thought signatures.

Also at `tests/test_gemini_source.py:708`.
</issue_to_address>

### Comment 7
<location path="tests/test_gemini_source.py" line_range="20" />
<code_context>
+def _gemini_config_provider(
+    model: str, provider_config: dict | None = None
+) -> ProviderGoogleGenAI:
+    """Build a provider stub that can build request configs without network I/O."""
+    provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI)
+    provider.provider_config = provider_config or {}
</code_context>
<issue_to_address>
**New docstrings omit required sections**

When an added docstring documents a function with parameters or a return value, the added docstrings for helpers and parameterized tests describe functions with parameters or return values without Google-format `Args:` or `Returns:` sections, contrary to the repository's docstring rule.

Add the appropriate Google-format `Args:` and `Returns:` sections to the affected docstrings.

Also at `tests/test_gemini_source.py:31`, `tests/test_gemini_source.py:95`, `tests/test_gemini_source.py:128`, `tests/test_gemini_source.py:197`, `tests/test_gemini_source.py:572`, `tests/test_gemini_source.py:754`.
</issue_to_address>

### Comment 8
<location path="tests/test_gemini_source.py" line_range="17-46" />
<code_context>
 from astrbot.core.provider.sources.gemini_source import ProviderGoogleGenAI


+def _gemini_config_provider(
+    model: str, provider_config: dict | None = None
+) -> ProviderGoogleGenAI:
+    """Build a provider stub that can build request configs without network I/O."""
+    provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI)
+    provider.provider_config = provider_config or {}
+    provider.provider_settings = {}
+    provider.model_name = model
+    provider.safety_settings = []
+    return provider
+
+
+def _gemini_func_toolset() -> SimpleNamespace:
</code_context>
<issue_to_address>
**Tests added against repository rule**

When the PR adds new test code to `tests/test_gemini_source.py`, the added test helpers and regression tests expand the test suite despite the repository instruction to avoid generating test files.

Remove the added test code to comply with the repository instruction.

Also at `tests/test_gemini_source.py:570-810`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and the change stores Gemini server-side tool parts and signatures in tool-call conversation history so later requests can replay them. If that data is recorded incorrectly, follow-up requests for affected conversations may fail; reverting stops new entries but does not remove existing ones, which can be repaired by clearing those conversations.

Blocking findings: astrbot/core/provider/sources/gemini_source.py:507, astrbot/core/provider/sources/gemini_source.py:735, astrbot/core/provider/sources/gemini_source.py:501, astrbot/core/provider/sources/gemini_source.py:740, astrbot/core/provider/sources/gemini_source.py:743, and 1 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread tests/test_gemini_source.py Resolved
Comment thread tests/test_gemini_source.py Resolved
Comment thread tests/test_gemini_source.py Resolved
@codecov-commenter

codecov-commenter commented Nov 11, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@DOTBave

DOTBave commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@sourcery-ai review please

@sourcery-ai sourcery-ai 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.

Hey - I've found 5 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="728" />
<code_context>
+            or getattr(part, "executable_code", None)
+            or getattr(part, "code_execution_result", None)
+        ]
+        if server_side_parts and llm_response.tools_call_ids:
+            google_extra = llm_response.tools_call_extra_content.setdefault(
+                llm_response.tools_call_ids[0], {}
</code_context>
<issue_to_address>
**Built-in tool history disappears**

When gemini uses a built-in tool but returns no custom function call, and the conversation continues, `_process_content_parts` does not save `server_side_parts` without a tool-call ID, and the streaming path likewise leaves `pending_server_side_parts` unattached. The agent records only the assistant text and reasoning, so a later request omits the built-in tool history and Gemini rejects or mishandles the conversation.

Persist and replay server-side tool parts even when Gemini returns no custom function call.

Also at `astrbot/core/provider/sources/gemini_source.py:463`, `astrbot/core/provider/sources/gemini_source.py:934`, `astrbot/core/provider/sources/gemini_source.py:964-971`.
</issue_to_address>

### Comment 2
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="475-499" />
<code_context>
+                        # invocations are enabled, the API requires them to be
+                        # sent back unchanged, including their thought signatures.
+                        for server_side_part in google_extra.get("server_parts") or []:
+                            try:
+                                tool_parts.append(
+                                    types.Part.model_validate(server_side_part)
</code_context>
<issue_to_address>
**Tool history order changes**

When gemini returns server-side parts before or interleaved with narration or custom function calls, `_process_content_parts` separates server-side parts from their original positions, and `_prepare_conversation` replays them before the associated function calls. Gemini receives tool history in a different order and can reject or incorrectly process the follow-up request.

Preserve the original positions of server-side parts and replay them in that order.
</issue_to_address>

### Comment 3
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="925" />
<code_context>
+                chunk_parts = chunk.candidates[0].content.parts or []
+
+                if chunk_parts and any(part.function_call for part in chunk_parts):
                     llm_response = LLMResponse("assistant", is_chunk=False)
                     llm_response.raw_completion = chunk
                     llm_response.result_chain = self._process_content_parts(
</code_context>
<issue_to_address>
**Later tool context is dropped**

When gemini emits a server-side tool part in a stream chunk after the first custom function-call chunk, `_query_stream` returns as soon as it sees a custom function call, so server-side tool parts arriving in subsequent chunks are never added to `pending_server_side_parts` or attached to the tool call. `_prepare_conversation` then replays incomplete history, and the next combined-tool request can fail.

Continue consuming the stream and accumulate server-side parts before yielding the completed tool-call response.
</issue_to_address>

### Comment 4
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="728" />
<code_context>
+            or getattr(part, "executable_code", None)
+            or getattr(part, "code_execution_result", None)
+        ]
+        if server_side_parts and llm_response.tools_call_ids:
+            google_extra = llm_response.tools_call_extra_content.setdefault(
+                llm_response.tools_call_ids[0], {}
</code_context>
<issue_to_address>
**Re-query loses server-side history**

When the agent uses `skills_like` mode and the initial Gemini response includes server-side parts alongside a custom function call, `ToolLoopAgentRunner._resolve_tool_exec` rebuilds the re-query context from pre-call messages and replaces the original response, so the re-query response and later tool-loop history omit the original `server_parts`. Gemini receives a follow-up request without the required tool history and rejects or misprocesses it.

Carry the original response's server-side parts into the `skills_like` re-query context and its replacement response.

Also at `astrbot/core/provider/sources/gemini_source.py:729-735`.
</issue_to_address>

### Comment 5
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="732-734" />
<code_context>
+            google_extra = llm_response.tools_call_extra_content.setdefault(
+                llm_response.tools_call_ids[0], {}
+            ).setdefault("google", {})
+            google_extra["server_parts"] = [
+                *server_side_parts,
+                *(google_extra.get("server_parts") or []),
+            ]
         chain_result = MessageChain(chain=chain)
</code_context>
<issue_to_address>
**Server context disappears after re-query**

When a Gemini request with combined built-in and function tools runs with `tool_schema_mode="skills_like"` and takes the re-query branch, `ToolLoopAgentRunner._step` replaces the tool-call IDs after a `skills_like` re-query without transferring `tools_call_extra_content`. `to_openai_tool_calls_model` then looks up metadata using the new IDs, so `_prepare_conversation` omits the stored server-side parts and the next Gemini request loses required tool context.

Preserve or merge the original and re-query `tools_call_extra_content` under the IDs that will be serialized into history.
</issue_to_address>

Sourcery assessment

Approval pending. 5 findings to address first.

Blocking findings: astrbot/core/provider/sources/gemini_source.py:728, astrbot/core/provider/sources/gemini_source.py:499, astrbot/core/provider/sources/gemini_source.py:925, astrbot/core/provider/sources/gemini_source.py:728, astrbot/core/provider/sources/gemini_source.py:734


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

@DOTBave

DOTBave commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

@sourcery-ai reivew please

@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Sure! I'm generating a new review now.

@sourcery-ai sourcery-ai 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.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="993-1000" />
<code_context>
                     yield llm_response
                     return

+                pending_server_side_parts.extend(
+                    part.model_dump(exclude_none=True, mode="json")
+                    for part in chunk_parts
+                    if getattr(part, "tool_call", None)
+                    or getattr(part, "tool_response", None)
+                    or getattr(part, "executable_code", None)
+                    or getattr(part, "code_execution_result", None)
+                )
                 _f = False

</code_context>
<issue_to_address>
**Streaming code execution aborts**

When streaming Gemini 3/4 with code execution emits an executable-code or code-execution-result chunk before a custom function call, `_query_stream` reaches `chunk.text` for chunks containing only captured `executable_code` or `code_execution_result` parts; the Google GenAI response text accessor raises on non-text parts, so streaming the newly supported built-in-tool combination aborts before the custom function call is handled.

Read text from text-bearing parts only, or safely handle the SDK accessor’s non-text-part error before yielding the chunk.
</issue_to_address>

### Comment 2
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="490-512" />
<code_context>
+                        for server_side_part in google_extra.get("server_parts") or []:
</code_context>
<issue_to_address>
**Gemini tool history is reordered**

When a Gemini response interleaves narration or a custom function call with server-side tool parts, `_prepare_conversation` reconstructs narration, custom function-call parts, and saved server-side parts in separate batches instead of their original order. The next tool-loop request sends a reordered model turn, invalidating the tool history and causing Gemini to reject the request.

Preserve the original sequence when collecting and replaying narration, custom function-call parts, and server-side parts.

Also at `astrbot/core/provider/sources/gemini_source.py:557`.
</issue_to_address>

### Comment 3
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="757" />
<code_context>
+            or getattr(part, "executable_code", None)
+            or getattr(part, "code_execution_result", None)
+        ]
+        if server_side_parts and llm_response.tools_call_ids:
+            google_extra = llm_response.tools_call_extra_content.setdefault(
+                llm_response.tools_call_ids[0], {}
</code_context>
<issue_to_address>
**Tool context lost in skills mode**

When the agent uses `tool_schema_mode="skills_like"` and the re-query returns a function call, `_resolve_tool_exec` replaces `llm_resp`, and `_step` copies only tool names, arguments, and IDs from the re-query response. The `tools_call_extra_content` holding `server_parts` is lost, so the next Gemini request omits required server-side parts and the tool turn fails.

Preserve the original response's `tools_call_extra_content` for the matching calls when replacing its tool-call fields with the re-query result.
</issue_to_address>

### Comment 4
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="757" />
<code_context>
+            or getattr(part, "executable_code", None)
+            or getattr(part, "code_execution_result", None)
+        ]
+        if server_side_parts and llm_response.tools_call_ids:
+            google_extra = llm_response.tools_call_extra_content.setdefault(
+                llm_response.tools_call_ids[0], {}
</code_context>
<issue_to_address>
**Built-in-only tool context is lost**

When gemini returns server-side tool parts but no custom function call in a turn, `_process_content_parts` attaches captured server-side parts only when `tools_call_ids` is nonempty; the streaming path likewise saves pending parts only alongside a custom tool call. The runner then stores a built-in-only turn as ordinary assistant text, so the next request sends incomplete Gemini history and loses the built-in tool context.

Persist server-side parts on assistant history independently of custom tool calls and replay them in later Gemini requests.

Also at `astrbot/core/provider/sources/gemini_source.py:963`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and if tool-part serialization or replay is wrong, Gemini requests or tool loops may fail, and malformed replay data can remain in the affected conversation history after a revert. That impact is limited to those conversations and can be repaired by starting a fresh one.

Blocking findings: astrbot/core/provider/sources/gemini_source.py:1000, astrbot/core/provider/sources/gemini_source.py:512, astrbot/core/provider/sources/gemini_source.py:757, astrbot/core/provider/sources/gemini_source.py:757


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Hey @DOTBave, I've posted a new review for you!

@DOTBave
DOTBave force-pushed the fix/gemini-tool-combination branch from 75ab439 to 30664dd Compare November 15, 2026 07:28
…calling

- Opt into include_server_side_tool_invocations and VALIDATED function
  calling mode when combining built-in tools with function declarations
  on Gemini 3+ models, degrading gracefully if the installed
  google-genai SDK lacks the field.
- Persist and replay server-side tool parts (tool_call/tool_response and
  code execution parts) and their thought signatures across tool-loop
  turns without duplicating signatures onto narration text.
- Resolve tool result messages to their original function names by
  tool_call_id when rebuilding conversation history.
- Bump google-genai to >=1.68.0.

Refs AstrBotDevs#9937
@DOTBave
DOTBave force-pushed the fix/gemini-tool-combination branch from 30664dd to bf8fc3e Compare November 15, 2026 11:34
Parse the major generation from the model ID with a regex instead of matching hardcoded gemini-3/gemini-4 substrings, so future generations and gateway-prefixed aliases are covered without maintaining a version list.
…ombination

# Conflicts:
#	tests/test_gemini_source.py

@Sha1rholder Sha1rholder 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.

正则检查过于脆弱

由于Gemini 3.x系统模型已不再更新,建议仅显式适配Gemini-3.8-flash和3.5-flash-lite。这个diff量对于这样的fix太变态了

@DOTBave

DOTBave commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

正则检查过于脆弱

由于Gemini 3.x系统模型已不再更新,建议仅显式适配Gemini-3.8-flash和3.5-flash-lite。这个diff量对于这样的fix太变态了

diff大部分来源于单测文件,是为了之前codecov bot提的覆盖率写的。本身的逻辑和注释diff只有 +165 -45,因为只加 include_server_side_tool_invocations=True 的话第 2 轮会直接 400,必须同时完成 tool_call_id -> name 映射以及 server_parts 的捕获重放与去重。

关于模型判断,我可以去掉 re.search 正则,直接复用 master 上提取好的 model_name 和 is_gemini_4。不过同样不用正则的话,用 is_gemini_4 or model_name.startswith(("gemini-3-", "gemini-3.")) 相比写死 ("gemini-3.8-flash", "gemini-3.5-flash-lite") 维护成本几乎一样,而且后者会导致还依赖官方自动路由的用户报错。综上所述我就复用和 master 的 thinking_config 一样的逻辑了。

@Sha1rholder Sha1rholder 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.

我觉得这个PR尚缺self-review

看去一堆红的绿的和本次PR目的要改的内容一点关系也没有啊

Comment thread tests/test_gemini_source.py Resolved
"auto",
"AUTO",
None,
),

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.

  • 不用给gemini 2系列加测试,马上就drop support了
  • gemini 3系列只用留两个测试用例,第一个和"gateway/"开头的

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

这里每一行 tuple 各自对应不同的模型前缀分支、内置工具或参数组合,没有重复用例;2.x 那两行也是验证旧模型不触发新字段的负向边界。如果删掉这些分支就漏测了。

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.

没有测试能覆盖所有分支的。行为正确性的根本保证还是实现代码自身写得严谨

gm_native_search、gm_url_context和gm_native_coderunner三个工具没有什么明显值得测试的行为区别,本质上确实是重复的,推荐减掉

Gateway/gemini-3xxx开头的用例本质上仅是测试model_name = model.rsplit("/", 1)[-1].lower()有没有在什么时候被移除,而这行代码并不是本次PR加入的。与其加个只为了测试模型名称normalizer不如在那行代码边上补个注释说明一下目的,要求动的时候多想一下

这里其实就算只有一个fixture也完全够用

):
# Simulate google-genai<1.68.0, where ToolConfig has no
# include_server_side_tool_invocations field and rejects the keyword.
# Simulate google-genai<1.68.0 where include_server_side_tool_invocations is absent.

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.

这个有点变态的,但凡是带lockfile的正常项目里都不该有这种东西的,确实是个workaround。留着吧

Comment thread tests/test_gemini_source.py Resolved
@DOTBave
DOTBave requested a review from Sha1rholder November 19, 2026 15:32
@DOTBave

DOTBave commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

@Sha1rholder 你好,请看Files Changed,而不是单个commit diff,谢谢。这几处“删 docstring / 改变量名”是相对于上一个 PR 提交的增量变化,并不是在改 master 原有代码。

@Sha1rholder

Copy link
Copy Markdown
Contributor

@Sha1rholder 你好,请看Files Changed,而不是单个commit diff,谢谢

我的问题。我眼瞎点进单个commit了。应该看整个的

This branch has not been deployed

No deployments
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.

[Bug] gemini API格式工具调用必定报错

3 participants