Skip to content

fix(gemini): preserve tool-call identities and stream complete batches - #11185

Open
JosephTian876 wants to merge 2 commits into
AstrBotDevs:masterfrom
JosephTian876:fix/gemini-tool-call-ids-current
Open

JosephTian876 wants to merge 2 commits into
AstrBotDevs:masterfrom
JosephTian876:fix/gemini-tool-call-ids-current

Conversation

@JosephTian876

@JosephTian876 JosephTian876 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Gemini 响应可能不提供函数调用编号。以函数名代替编号会让同名调用共用标识;流式路径在收到首个工具调用分片时提前返回,还可能遗漏后续调用和已累计内容。

本改动保留提供方返回的编号;缺失时为逻辑调用生成唯一编号,并在重试和明确回放时保持稳定。函数响应关联最近一批助手工具调用,并保留 Google 思考签名。流式响应聚合完整工具调用,同时继续提供文本和推理分片。

验证:最新上游适配的 Gemini 提供方定向测试 24 项通过,覆盖同名调用、提供方编号、重试与回放、多分片聚合、响应关联和思考签名;变更文件 Ruff、格式及 Python 编译检查通过。旧版兼容补丁曾部署,本次最新上游适配尚未进行实机 Gemini 端到端验证。

建议相关 PR 合并顺序:陪伴插件的工具失败结果修复与本 PR 分属不同仓库,可独立合并。

Summary by Sourcery

Fix Gemini tool-call identity handling and stream complete responses while preserving accumulated content and metadata.

Bug Fixes:

  • Preserve Gemini provider-supplied tool-call IDs and generate unique, stable identifiers when IDs are absent.
  • Associate tool responses with the correct recent assistant tool-call batch, including across intervening assistant messages.
  • Aggregate complete streamed tool-call batches without losing preceding text, reasoning, usage, or Google thought signatures.
  • Avoid retrying Gemini streams after partial output has already been emitted.

Enhancements:

  • Expand Gemini provider coverage for tool-call identity, replay and retry stability, streaming aggregation, response association, and thought-signature preservation.

Tests:

  • Add comprehensive Gemini tests for missing and provider-supplied tool-call IDs, retries, replay stability, multi-chunk streaming, response association, and mid-stream failures.

@codecov-commenter

codecov-commenter commented Nov 16, 2026 •

Copy link
Copy Markdown

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

Codecov Report

❌ Patch coverage is 68.18182% with 14 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
astrbot/core/provider/sources/gemini_source.py 68.18% 14 Missing ⚠️

📢 Thoughts on this report? Let us know!

@JosephTian876
JosephTian876 marked this pull request as ready for review November 16, 2026 18:12

@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 2 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="905" />
<code_context>
-                        llm_response.usage = self._extract_usage(chunk.usage_metadata)
-                    yield llm_response
-                    return
+                accumulated_parts.extend(candidate.content.parts or [])

                 _f = False
</code_context>
<issue_to_address>
**Retried streams duplicate partial text**

When gemini has already yielded one or more text or reasoning chunks, then raises an `APIError` before the stream completes, `text_chat_stream` catches the stream’s `APIError` and retries the full request after these parts have been exposed as text or reasoning chunks, so callers receive duplicated partial output before the retried response completes.

Do not retry a stream after exposing chunks, or buffer the output until the request has completed before making a retry decision.
</issue_to_address>

### Comment 2
<location path="astrbot/core/provider/sources/gemini_source.py" line_range="453-457" />
<code_context>

             elif role == "assistant":
+                # Tool responses belong to the most recent assistant tool-call batch.
+                tool_call_names = {
+                    tool["id"]: tool["function"]["name"]
+                    for tool in message.get("tool_calls") or []
+                    if tool.get("id")
+                }
                 parts = []
                 if isinstance(content, str):
</code_context>
<issue_to_address>
**Tool response loses function association**

When an assistant message without tool calls appears between a tool-call batch and its tool response, and that response's own name is absent or stale, an assistant message without `tool_calls` replaces `tool_call_names` with an empty dictionary, so a later tool response cannot recover the name from the most recent tool-call batch and uses its possibly stale name or call ID instead. Gemini then receives a response for the wrong or unknown function and rejects the conversation.

Only replace `tool_call_names` when an assistant message contains a new tool-call batch.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: astrbot/core/provider/sources/gemini_source.py:905, astrbot/core/provider/sources/gemini_source.py:457


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

@JosephTian876 JosephTian876 changed the title fix: 修复 Gemini 工具调用编号冲突与流式结果遗漏 fix(gemini): preserve tool-call identities and stream complete batches Nov 21, 2026
@JosephTian876
JosephTian876 force-pushed the fix/gemini-tool-call-ids-current branch from 42c8f06 to 8ff9934 Compare November 27, 2026 02:20

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.

2 participants