diff --git a/astrbot/core/provider/sources/gemini_source.py b/astrbot/core/provider/sources/gemini_source.py index ee4ed09249..519dc188c1 100644 --- a/astrbot/core/provider/sources/gemini_source.py +++ b/astrbot/core/provider/sources/gemini_source.py @@ -40,6 +40,13 @@ "gemini-4-hydrogen": ("LOW", "MEDIUM", "HIGH", "XHIGH"), } +_SERVER_SIDE_PART_ATTRS = ( + "tool_call", + "tool_response", + "executable_code", + "code_execution_result", +) + class SuppressNonTextPartsWarning(logging.Filter): """过滤 Gemini SDK 中的非文本部分警告""" @@ -269,6 +276,7 @@ async def _prepare_query_config( if url_context: tool_list.append(types.Tool(url_context=types.UrlContext())) + has_builtin_tool = bool(tool_list) if tools: func_desc = tools.get_func_desc_google_genai_style() tool_list.append( @@ -281,15 +289,34 @@ async def _prepare_query_config( tool_config = None has_func_decl = tool_list and any(t.function_declarations for t in tool_list) if has_func_decl: - tool_config = types.ToolConfig( - function_calling_config=types.FunctionCallingConfig( - mode=( - types.FunctionCallingConfigMode.ANY - if tool_choice == "required" - else types.FunctionCallingConfigMode.AUTO - ) - ) + # Built-in tools + function calling on Gemini 3/4 require server-side + # tool invocations and VALIDATED (or ANY) mode instead of AUTO. + combines_tools = has_builtin_tool and ( + is_gemini_4 or model_name.startswith(("gemini-3-", "gemini-3.")) ) + if tool_choice == "required": + mode = types.FunctionCallingConfigMode.ANY + elif combines_tools: + mode = types.FunctionCallingConfigMode.VALIDATED + else: + mode = types.FunctionCallingConfigMode.AUTO + tool_config_kwargs = { + "function_calling_config": types.FunctionCallingConfig(mode=mode), + } + if combines_tools: + # google-genai<1.68.0 lacks this field and rejects unknown kwargs. + if ( + "include_server_side_tool_invocations" + in types.ToolConfig.model_fields + ): + tool_config_kwargs["include_server_side_tool_invocations"] = True + else: + logger.warning( + "Gemini built-in tool combination with function calling " + "requires google-genai>=1.68.0; the installed SDK does not " + "support it." + ) + tool_config = types.ToolConfig(**tool_config_kwargs) extra_body = self.provider_config.get("custom_extra_body") if extra_body is None: @@ -461,6 +488,8 @@ def append_or_extend( contents.append(content_cls(parts=part)) gemini_contents: list[types.Content] = [] + # Map tool call IDs to function names for later tool result matching. + tool_id_to_name: dict[str, str] = {} for message in payloads["messages"]: role, content = message["role"], message.get("content") @@ -480,6 +509,38 @@ def append_or_extend( elif role == "assistant": parts = [] + tool_parts: list[types.Part] = [] + if "tool_calls" in message: + for tool in message["tool_calls"]: + extra_content = tool.get("extra_content") or {} + google_extra = extra_content.get("google") or {} + function_name = tool["function"]["name"] + if tool.get("id"): + tool_id_to_name[tool["id"]] = function_name + # Replay server-side tool parts unchanged (with 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) + ) + except Exception as e: + logger.warning( + "Failed to restore Gemini server-side tool part: %s", + e, + exc_info=True, + ) + part = types.Part.from_function_call( + name=function_name, + args=json.loads(tool["function"]["arguments"]), + ) + # we should set thought_signature back to part if exists + # for more info about thought_signature, see: + # https://ai.google.dev/gemini-api/docs/thought-signatures + ts_bs64 = google_extra.get("thought_signature") + if ts_bs64: + part.thought_signature = base64.b64decode(ts_bs64) + tool_parts.append(part) + if isinstance(content, str): parts.append(types.Part.from_text(text=content)) elif isinstance(content, list): @@ -502,21 +563,17 @@ def append_or_extend( ) thinking_signature = None - if ( - not text - and thinking_signature - and "tool_calls" in message + has_duplicate_thought_signature = bool( + thinking_signature and any( - isinstance(tool, dict) - and isinstance(tool.get("extra_content"), dict) - and isinstance(tool["extra_content"].get("google"), dict) - and tool["extra_content"]["google"].get("thought_signature") - for tool in message["tool_calls"] + tool_part.thought_signature == thinking_signature + for tool_part in tool_parts ) - ): - # If the main content is empty but tool calls have thought signatures, - # skip adding an empty text part to deduplicate the thinking signature in the main content and tool calls. - pass + ) + if has_duplicate_thought_signature: + # Omit duplicate thought_signature already carried by a tool/server part. + if text: + parts.append(types.Part(text=text)) else: parts.append( types.Part( @@ -525,24 +582,7 @@ def append_or_extend( ) ) - if "tool_calls" in message: - for tool in message["tool_calls"]: - part = types.Part.from_function_call( - name=tool["function"]["name"], - args=json.loads(tool["function"]["arguments"]), - ) - # we should set thought_signature back to part if exists - # for more info about thought_signature, see: - # https://ai.google.dev/gemini-api/docs/thought-signatures - if "extra_content" in tool and tool["extra_content"]: - ts_bs64 = ( - tool["extra_content"] - .get("google", {}) - .get("thought_signature") - ) - if ts_bs64: - part.thought_signature = base64.b64decode(ts_bs64) - parts.append(part) + parts.extend(tool_parts) if not parts: parts = [types.Part.from_text(text=" ")] @@ -550,7 +590,11 @@ def append_or_extend( append_or_extend(gemini_contents, parts, types.ModelContent) elif role == "tool": - func_name = message.get("name", message["tool_call_id"]) + tool_call_id = message["tool_call_id"] + # Resolve function name from preceding assistant tool calls via call ID. + func_name = message.get("name") or tool_id_to_name.get( + tool_call_id, tool_call_id + ) part = types.Part.from_function_response( name=func_name, response={ @@ -673,6 +717,7 @@ def _process_content_parts( for part in result_parts ): chain.append(Comp.Plain("这是图片")) + server_side_parts: list[dict] = [] for part in result_parts: # Skip thinking parts — their text is already captured via # _extract_reasoning_content above. Including them here would @@ -707,9 +752,23 @@ def _process_content_parts( ): chain.append(Comp.Image.fromBytes(part.inline_data.data)) - if ts := part.thought_signature: - # only keep the last thinking signature + if any(getattr(part, attr, None) for attr in _SERVER_SIDE_PART_ATTRS): + server_side_parts.append( + part.model_dump(exclude_none=True, mode="json") + ) + elif ts := part.thought_signature: + # Only keep the last thinking signature from non-server-side parts. llm_response.reasoning_signature = base64.b64encode(ts).decode("utf-8") + + # Store server-side parts on the first custom tool call for replay. + 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: @@ -880,6 +939,8 @@ async def _query_stream( accumulated_text = "" accumulated_reasoning = "" final_response = None + # Buffer server-side tool parts until a custom tool call is emitted. + pending_server_side_parts: list[dict] = [] async with self._conversation_header(conversation_id): async for chunk in result: @@ -892,9 +953,9 @@ async def _query_stream( logger.warning(f"Gemini stream chunk has empty content: {chunk}") continue - if chunk.candidates[0].content.parts and any( - part.function_call for part in chunk.candidates[0].content.parts - ): + 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( @@ -902,6 +963,15 @@ async def _query_stream( llm_response, validate_output=False, ) + # Prepend earlier server-side parts so replay keeps response order. + if pending_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"] = [ + *pending_server_side_parts, + *(google_extra.get("server_parts") or []), + ] # This response replaces the whole turn in conversation # history, so keep the narration and reasoning that were # already streamed before the tool call. Dropping them made @@ -924,6 +994,13 @@ async def _query_stream( yield llm_response return + pending_server_side_parts.extend( + part.model_dump(exclude_none=True, mode="json") + for part in chunk_parts + if any( + getattr(part, attr, None) for attr in _SERVER_SIDE_PART_ATTRS + ) + ) _f = False # 提取 reasoning content diff --git a/tests/test_gemini_source.py b/tests/test_gemini_source.py index c39aa7cace..d84bf5831b 100644 --- a/tests/test_gemini_source.py +++ b/tests/test_gemini_source.py @@ -1,3 +1,6 @@ +import base64 +import json +import logging from types import SimpleNamespace import httpx @@ -12,6 +15,31 @@ from astrbot.core.provider.sources.gemini_source import ProviderGoogleGenAI +def _gemini_config_provider( + model: str, provider_config: dict | None = None +) -> ProviderGoogleGenAI: + 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: + return SimpleNamespace( + get_func_desc_google_genai_style=lambda: { + "function_declarations": [ + { + "name": "get_weather", + "description": "Get weather", + "parameters": {"type": "object", "properties": {}}, + } + ] + } + ) + + @pytest.mark.asyncio async def test_gemini_thinking_level_is_serialized_on_every_request(): model = "gemini-3.7-flash" @@ -63,6 +91,126 @@ async def test_gemini_omits_unset_or_unsupported_thinking_config(model, provider assert "thinking_config" not in config.model_dump(exclude_none=True) +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("model", "cfg", "with_func", "choice", "expected_mode", "expected_flag"), + [ + ( + "gemini-3.8-flash", + {"gm_native_search": True}, + True, + "auto", + "VALIDATED", + True, + ), + ("gemini-3.8-flash", {"gm_url_context": True}, True, "auto", "VALIDATED", True), + ( + "gemini-3.8-flash", + {"gm_native_coderunner": True}, + True, + "auto", + "VALIDATED", + True, + ), + ( + "gemini-3.5-flash-lite", + {"gm_native_search": True}, + True, + "auto", + "VALIDATED", + True, + ), + ( + "gateway/gemini-3.8-flash-high", + {"gm_native_search": True}, + True, + "auto", + "VALIDATED", + True, + ), + ( + "Gateway/Gemini-3.8-Flash-High", + {"gm_native_search": True}, + True, + "auto", + "VALIDATED", + True, + ), + ("gemini-4-neon", {"gm_native_search": True}, True, "auto", "VALIDATED", True), + ("gemini-3.8-flash", {"gm_native_search": True}, True, "required", "ANY", True), + ("gemini-3.8-flash", {}, True, "auto", "AUTO", None), + ("gemini-3.8-flash", {"gm_native_search": True}, False, "auto", None, None), + ("gemini-2.5-flash", {"gm_native_search": True}, True, "auto", "AUTO", None), + ( + "gateway/gemini-2.5-flash", + {"gm_native_search": True}, + True, + "auto", + "AUTO", + None, + ), + ], +) +async def test_gemini_tool_combination_config_matrix( + model, cfg, with_func, choice, expected_mode, expected_flag +): + provider = _gemini_config_provider(model, cfg) + config = await provider._prepare_query_config( + {"model": model}, + tools=_gemini_func_toolset() if with_func else None, + tool_choice=choice, + ) + + if expected_mode is None: + assert config.tool_config is None + assert config.tools is not None + return + + assert config.tool_config is not None + assert config.tool_config.include_server_side_tool_invocations is expected_flag + assert config.tool_config.function_calling_config is not None + assert config.tool_config.function_calling_config.mode == getattr( + types.FunctionCallingConfigMode, expected_mode + ) + + +@pytest.mark.asyncio +async def test_gemini_tool_config_sdk_fallback_and_kwarg_omission(monkeypatch, caplog): + captured_kwargs: dict = {} + original_tool_config = types.ToolConfig + + def _capturing_tool_config(**kwargs): + captured_kwargs.update(kwargs) + return original_tool_config(**kwargs) + + with monkeypatch.context() as m: + m.setattr(gemini_source.types, "ToolConfig", _capturing_tool_config) + await _gemini_config_provider("gemini-2.5-flash")._prepare_query_config( + {"model": "gemini-2.5-flash"}, tools=_gemini_func_toolset() + ) + assert "include_server_side_tool_invocations" not in captured_kwargs + + # Simulate google-genai<1.68.0 where include_server_side_tool_invocations is absent. + class _LegacyToolConfig(types.ToolConfig): + pass + + _LegacyToolConfig.model_fields = { + k: v + for k, v in types.ToolConfig.model_fields.items() + if k != "include_server_side_tool_invocations" + } + monkeypatch.setattr(gemini_source.types, "ToolConfig", _LegacyToolConfig) + caplog.set_level(logging.WARNING, logger="astrbot") + + config = await _gemini_config_provider( + "gemini-3.8-flash", {"gm_native_search": True} + )._prepare_query_config({"model": "gemini-3.8-flash"}, tools=_gemini_func_toolset()) + + assert "google-genai>=1.68.0" in caplog.text + assert config.tool_config is not None + assert config.tool_config.include_server_side_tool_invocations is None + + @pytest.mark.asyncio async def test_gemini_prepare_conversation_keeps_normal_user_first_history(): provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) @@ -290,11 +438,12 @@ def _gemini_stream_chunk( text=None, thought=None, function_call=None, + server_side_parts=None, finish_reason=None, response_id="resp-1", ): """Build a minimal stand-in for a google-genai streaming chunk.""" - parts = [] + parts = list(server_side_parts or []) if text is not None: parts.append(_gemini_part(text=text)) if thought is not None: @@ -446,3 +595,244 @@ async def test_gemini_stream_keeps_reasoning_from_tool_call_chunk(monkeypatch): final = responses[-1] assert final.reasoning_content == "weighing optionsdeciding to call" + + +def _gemini_server_side_response_parts() -> list[types.Part]: + signature = b"\x01\x02" + return [ + types.Part( + tool_call=types.ToolCall( + tool_type="GOOGLE_SEARCH_WEB", + args={"queries": ["Shanghai weather"]}, + id="search-1", + ), + thought_signature=signature, + ), + types.Part( + tool_response=types.ToolResponse( + tool_type="GOOGLE_SEARCH_WEB", + response={"search_suggestions": "Shanghai weather forecast"}, + id="search-1", + ), + thought_signature=signature, + ), + ] + + +def test_gemini_process_content_parts_keeps_server_side_tool_parts(): + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + function_call_part = types.Part( + function_call=types.FunctionCall( + name="get_weather", args={"city": "Shanghai"}, id="call-1" + ), + thought_signature=b"\x03", + ) + candidate = SimpleNamespace( + content=types.Content( + role="model", + parts=[*_gemini_server_side_response_parts(), function_call_part], + ), + finish_reason=None, + ) + llm_response = LLMResponse(role="assistant") + + ProviderGoogleGenAI._process_content_parts( + provider, candidate, llm_response, validate_output=False + ) + + assert llm_response.tools_call_ids == ["call-1"] + google_extra = llm_response.tools_call_extra_content["call-1"]["google"] + assert google_extra["thought_signature"] == base64.b64encode(b"\x03").decode() + stored = google_extra["server_parts"] + assert ["tool_call" in p for p in stored] == [True, False] + assert ["tool_response" in p for p in stored] == [False, True] + assert stored[0]["thought_signature"] == base64.b64encode(b"\x01\x02").decode() + json.dumps(stored) + tool_call_model = llm_response.to_openai_tool_calls_model()[0] + assert ( + tool_call_model.model_dump()["extra_content"]["google"]["server_parts"] + == stored + ) + assert llm_response.reasoning_signature == base64.b64encode(b"\x03").decode() + + +@pytest.mark.parametrize( + ("text_signature", "expected"), + [ + (None, None), + (b"\x09\x09", base64.b64encode(b"\x09\x09").decode("utf-8")), + ], +) +def test_gemini_process_content_parts_reasoning_signature_isolation( + text_signature, expected +): + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + candidate = SimpleNamespace( + content=types.Content( + role="model", + parts=[ + *_gemini_server_side_response_parts(), + types.Part(text="answer", thought_signature=text_signature), + ], + ), + finish_reason=None, + ) + llm_response = LLMResponse(role="assistant") + + ProviderGoogleGenAI._process_content_parts( + provider, candidate, llm_response, validate_output=False + ) + + assert llm_response.reasoning_signature == expected + assert llm_response.tools_call_extra_content == {} + + +@pytest.mark.asyncio +async def test_gemini_prepare_conversation_replays_server_parts_and_maps_tool_name(): + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + server_side_parts = [ + part.model_dump(exclude_none=True, mode="json") + for part in _gemini_server_side_response_parts() + ] + + contents = await provider._prepare_conversation( + { + "messages": [ + {"role": "user", "content": "what's the weather?"}, + { + "role": "assistant", + "tool_calls": [ + { + "id": "call-1", + "type": "function", + "function": { + "name": "get_weather", + "arguments": '{"city": "Shanghai"}', + }, + "extra_content": { + "google": { + "thought_signature": base64.b64encode( + b"\x03" + ).decode(), + "server_parts": [ + *server_side_parts, + {"tool_call": "invalid"}, + ], + } + }, + } + ], + }, + {"role": "tool", "tool_call_id": "call-1", "content": "sunny"}, + ] + } + ) + + assert [c.role for c in contents] == ["user", "model", "user"] + parts = contents[1].parts + assert parts is not None and len(parts) == 3 + assert parts[0].tool_call is not None and parts[0].tool_call.id == "search-1" + assert parts[0].thought_signature == b"\x01\x02" + assert ( + parts[1].tool_response is not None and parts[1].tool_response.id == "search-1" + ) + assert parts[1].thought_signature == b"\x01\x02" + assert parts[2].function_call is not None + assert parts[2].function_call.name == "get_weather" + assert parts[2].thought_signature == b"\x03" + func_resp = contents[2].parts[0].function_response + assert func_resp is not None and func_resp.name == "get_weather" + + +@pytest.mark.asyncio +async def test_gemini_stream_keeps_server_side_tool_parts_for_next_turn(monkeypatch): + provider = _gemini_stream_provider() + server_side_parts = _gemini_server_side_response_parts() + tool_call = SimpleNamespace( + name="get_weather", + args={"city": "Shanghai"}, + id="call-1", + thought_signature=None, + ) + + responses = await _drain_gemini_stream( + provider, + monkeypatch, + [ + _gemini_stream_chunk(server_side_parts=server_side_parts[:1]), + _gemini_stream_chunk( + server_side_parts=server_side_parts[1:], function_call=tool_call + ), + ], + ) + + stored = responses[-1].tools_call_extra_content["call-1"]["google"]["server_parts"] + assert stored == [ + part.model_dump(exclude_none=True, mode="json") for part in server_side_parts + ] + json.dumps(stored) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("narration", "narration_sig", "expect_text", "expect_text_sig"), + [ + ("", b"\x01\x02", False, None), + ("let me search first", b"\x01\x02", True, None), + ("let me search first", b"\x09\x09", True, b"\x09\x09"), + ], +) +async def test_gemini_prepare_conversation_narration_signature_dedup( + narration, narration_sig, expect_text, expect_text_sig +): + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + tool_signature = b"\x01\x02" + server_side_part = types.Part( + tool_call=types.ToolCall( + tool_type="GOOGLE_SEARCH_WEB", args={"queries": ["x"]}, id="search-1" + ), + thought_signature=tool_signature, + ).model_dump(exclude_none=True, mode="json") + content = [ + { + "type": "think", + "think": "", + "encrypted": base64.b64encode(narration_sig).decode(), + } + ] + if narration: + content.append({"type": "text", "text": narration}) + + contents = await provider._prepare_conversation( + { + "messages": [ + {"role": "user", "content": "what's the weather?"}, + { + "role": "assistant", + "content": content, + "tool_calls": [ + { + "id": "call-1", + "type": "function", + "function": {"name": "get_weather", "arguments": "{}"}, + "extra_content": { + "google": {"server_parts": [server_side_part]} + }, + } + ], + }, + ] + } + ) + + model_parts = contents[1].parts + assert model_parts is not None + text_parts = [p for p in model_parts if p.text is not None] + if expect_text: + assert [p.text for p in text_parts] == [narration] + assert text_parts[0].thought_signature == expect_text_sig + else: + assert text_parts == [] + func_call = next(p for p in model_parts if p.function_call) + assert func_call.thought_signature is None + assert [p.thought_signature for p in model_parts if p.tool_call] == [tool_signature]