From bf8fc3ef6785fd41b25ab9095baac2f6cbf4d5a4 Mon Sep 17 00:00:00 2001 From: DOT_Bave Date: Sun, 15 Nov 2026 02:26:20 -0500 Subject: [PATCH 1/4] fix(provider): support combining Gemini built-in tools with function 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 #9937 --- .../core/provider/sources/gemini_source.py | 206 ++++-- pyproject.toml | 2 +- requirements.txt | 2 +- tests/test_gemini_source.py | 607 +++++++++++++++++- 4 files changed, 769 insertions(+), 48 deletions(-) diff --git a/astrbot/core/provider/sources/gemini_source.py b/astrbot/core/provider/sources/gemini_source.py index 135f37d81b3..df9ecb7bc41 100644 --- a/astrbot/core/provider/sources/gemini_source.py +++ b/astrbot/core/provider/sources/gemini_source.py @@ -264,21 +264,55 @@ async def _prepare_query_config( types.Tool(function_declarations=func_desc["function_declarations"]), ) + has_builtin_tool = bool(tool_list) and any( + getattr(t, "google_search", None) + or getattr(t, "code_execution", None) + or getattr(t, "url_context", None) + for t in tool_list + ) + if not tool_list: tool_list = None 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 can be combined with function calling only on + # Gemini 3+ models. The API requires opting into server-side tool + # invocations for that combination, and AUTO mode is not supported + # once the flag is enabled, so switch to VALIDATED mode. + # Match by substring (case-insensitively) because deployments may + # prefix model names, e.g. gateway aliases such as + # "gateway/gemini-3.8-flash-high". + combines_tools = has_builtin_tool and any( + marker in model_name.lower() for marker in ("gemini-3", "gemini-4") ) + 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 does not define this field and its SDK + # models reject unknown fields, so keep it off the request in + # that case and let the API report the unsupported combination + # instead of raising a confusing pydantic error. + 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) # oper thinking config thinking_config = None @@ -423,6 +457,9 @@ def append_or_extend( contents.append(content_cls(parts=part)) gemini_contents: list[types.Content] = [] + # Map custom tool call IDs to function names so tool result messages + # (which only carry the call ID) can be matched to the original call. + tool_id_to_name: dict[str, str] = {} for message in payloads["messages"]: role, content = message["role"], message.get("content") @@ -442,6 +479,41 @@ 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 (tool_call/tool_response) + # captured from a previous response. When server-side + # 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) + ) + 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): @@ -464,21 +536,20 @@ 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: + # Tool calls and replayed server-side tool parts already + # 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( types.Part( @@ -487,24 +558,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=" ")] @@ -512,7 +566,12 @@ 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"] + # Tool result messages only carry the call ID, so resolve the + # function name from the preceding assistant message. + 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={ @@ -670,8 +729,43 @@ def _process_content_parts( chain.append(Comp.Image.fromBytes(part.inline_data.data)) if ts := part.thought_signature: - # only keep the last thinking signature - llm_response.reasoning_signature = base64.b64encode(ts).decode("utf-8") + # Server-side tool parts are replayed through their own + # extra_content/server_parts. Copying their signature here would + # attach a tool-part signature to the narration text on the next + # turn, so only keep signatures from regular content parts. + is_server_side_part = bool( + getattr(part, "tool_call", None) + or getattr(part, "tool_response", None) + or getattr(part, "executable_code", None) + or getattr(part, "code_execution_result", None) + ) + if not is_server_side_part: + # only keep the last thinking signature + llm_response.reasoning_signature = base64.b64encode(ts).decode( + "utf-8" + ) + + # Keep server-side tool parts (tool_call/tool_response and code + # execution parts) so they can be replayed unchanged, with their thought + # signatures, in the next tool-loop request. The agent tool loop only + # keeps OpenAI-style tool call messages between steps, so the parts are + # stored on the first custom tool call's extra_content. + server_side_parts = [ + part.model_dump(exclude_none=True, mode="json") + for part in result_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) + ] + 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: @@ -846,6 +940,10 @@ async def _query_stream( accumulated_text = "" accumulated_reasoning = "" final_response = None + # Server-side tool parts (tool_call/tool_response) may stream in their own + # chunks before the custom tool call chunk. Keep them so they can be + # replayed to the API in the next tool-loop request. + pending_server_side_parts: list[dict] = [] async with self._conversation_header(conversation_id): async for chunk in result: @@ -858,9 +956,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( @@ -868,6 +966,16 @@ async def _query_stream( llm_response, validate_output=False, ) + # Server-side tool parts may arrive in earlier chunks; prepend + # them so the replayed parts keep their 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 @@ -890,6 +998,14 @@ 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 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 # 提取 reasoning content diff --git a/pyproject.toml b/pyproject.toml index 61b3c00223b..f5dad2570dc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,7 +26,7 @@ dependencies = [ "faiss-cpu>=1.14.3", "fastapi>=0.124.0", "filelock>=3.18.0", - "google-genai>=1.56.0", + "google-genai>=1.68.0", "httpx[socks]>=0.28.1", "lark-oapi>=1.4.15", "mcp>=1.8.0,<2", diff --git a/requirements.txt b/requirements.txt index 59930c1071b..acd7d7742d6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,7 +15,7 @@ docstring-parser>=0.16 faiss-cpu>=1.12.0 fastapi>=0.124.0 filelock>=3.18.0 -google-genai>=1.56.0 +google-genai>=1.68.0 httpx[socks]>=0.28.1 lark-oapi>=1.4.15 mcp>=1.8.0,<2 diff --git a/tests/test_gemini_source.py b/tests/test_gemini_source.py index 622e3bfe8f7..32900fb6c45 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,45 @@ 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. + + Args: + model: Model identifier to configure on the provider stub. + provider_config: Optional provider configuration dictionary. + + Returns: + Configured ProviderGoogleGenAI stub instance. + """ + 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: + """Build a minimal ToolSet stand-in exposing one function declaration. + + Returns: + SimpleNamespace implementing get_func_desc_google_genai_style. + """ + 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" @@ -51,6 +93,184 @@ async def test_gemini_37_minimal_thinking_level_falls_back_to_medium(): } +@pytest.mark.asyncio +@pytest.mark.parametrize( + "provider_config", + [ + {"gm_native_search": True}, + {"gm_url_context": True}, + {"gm_native_coderunner": True}, + ], +) +async def test_gemini_enables_server_side_tool_invocations_for_tool_combination( + provider_config, +): + # Built-in tools + function calling on Gemini 3+ must opt into server-side + # tool invocations to avoid 400 INVALID_ARGUMENT ("Please enable + # tool_config.include_server_side_tool_invocations to use Built-in tools + # with Function calling."). + model = "gemini-3.8-flash" + provider = _gemini_config_provider(model, provider_config) + + config = await provider._prepare_query_config( + {"model": model}, tools=_gemini_func_toolset() + ) + + assert config.tool_config is not None + assert config.tool_config.include_server_side_tool_invocations is True + assert config.tool_config.function_calling_config is not None + # AUTO mode is not supported together with the flag. + assert ( + config.tool_config.function_calling_config.mode + == types.FunctionCallingConfigMode.VALIDATED + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "model", + [ + "gateway/gemini-3.8-flash-high", + "Gateway/Gemini-3.8-Flash-High", + "gemini-4-flash-preview", + ], +) +async def test_gemini_enables_tool_combination_for_aliased_and_future_models(model): + # Model names can carry gateway prefixes; Gemini 4 is supported as well. + provider = _gemini_config_provider(model, {"gm_native_search": True}) + + config = await provider._prepare_query_config( + {"model": model}, tools=_gemini_func_toolset() + ) + + assert config.tool_config is not None + assert config.tool_config.include_server_side_tool_invocations is True + assert config.tool_config.function_calling_config is not None + assert ( + config.tool_config.function_calling_config.mode + == types.FunctionCallingConfigMode.VALIDATED + ) + + +@pytest.mark.asyncio +async def test_gemini_required_tool_choice_keeps_any_mode_for_tool_combination(): + model = "gemini-3.8-flash" + provider = _gemini_config_provider(model, {"gm_native_search": True}) + + config = await provider._prepare_query_config( + {"model": model}, + tools=_gemini_func_toolset(), + tool_choice="required", + ) + + assert config.tool_config is not None + assert config.tool_config.include_server_side_tool_invocations is True + assert config.tool_config.function_calling_config is not None + assert ( + config.tool_config.function_calling_config.mode + == types.FunctionCallingConfigMode.ANY + ) + + +@pytest.mark.asyncio +async def test_gemini_function_only_requests_keep_auto_mode(): + model = "gemini-3.8-flash" + provider = _gemini_config_provider(model) + + config = await provider._prepare_query_config( + {"model": model}, tools=_gemini_func_toolset() + ) + + assert config.tool_config is not None + assert config.tool_config.include_server_side_tool_invocations is None + assert config.tool_config.function_calling_config is not None + assert ( + config.tool_config.function_calling_config.mode + == types.FunctionCallingConfigMode.AUTO + ) + + +@pytest.mark.asyncio +async def test_gemini_function_only_config_omits_server_side_flag_kwarg(monkeypatch): + # google-genai<1.68.0 does not define + # ToolConfig.include_server_side_tool_invocations and rejects unknown + # constructor arguments, so plain function calling must not pass it. + captured_kwargs: dict = {} + original_tool_config = types.ToolConfig + + def _capturing_tool_config(**kwargs): + captured_kwargs.update(kwargs) + return original_tool_config(**kwargs) + + monkeypatch.setattr(gemini_source.types, "ToolConfig", _capturing_tool_config) + + model = "gemini-2.5-flash" + provider = _gemini_config_provider(model) + + await provider._prepare_query_config({"model": model}, tools=_gemini_func_toolset()) + + assert "include_server_side_tool_invocations" not in captured_kwargs + + +@pytest.mark.asyncio +async def test_gemini_tool_combination_warns_when_sdk_lacks_server_side_flag( + monkeypatch, caplog +): + # Simulate google-genai<1.68.0, where ToolConfig has no + # include_server_side_tool_invocations field and rejects the keyword. + class _LegacyToolConfig(types.ToolConfig): + pass + + _LegacyToolConfig.model_fields = { + name: field_info + for name, field_info in types.ToolConfig.model_fields.items() + if name != "include_server_side_tool_invocations" + } + monkeypatch.setattr(gemini_source.types, "ToolConfig", _LegacyToolConfig) + + model = "gemini-3.8-flash" + provider = _gemini_config_provider(model, {"gm_native_search": True}) + caplog.set_level(logging.WARNING, logger="astrbot") + + config = await provider._prepare_query_config( + {"model": model}, 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_builtin_only_requests_keep_tool_config_unset(): + model = "gemini-3.8-flash" + provider = _gemini_config_provider(model, {"gm_native_search": True}) + + config = await provider._prepare_query_config({"model": model}) + + assert config.tool_config is None + assert config.tools is not None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("model", ["gemini-2.5-flash", "gateway/gemini-2.5-flash"]) +async def test_gemini_legacy_models_do_not_opt_in_server_side_tool_invocations(model): + # Gemini 1.x/2.x must not receive the preview-only opt-in flag. + provider = _gemini_config_provider(model, {"gm_native_search": True}) + + config = await provider._prepare_query_config( + {"model": model}, tools=_gemini_func_toolset() + ) + + assert config.tool_config is not None + assert config.tool_config.include_server_side_tool_invocations is None + assert config.tool_config.function_calling_config is not None + assert ( + config.tool_config.function_calling_config.mode + == types.FunctionCallingConfigMode.AUTO + ) + + @pytest.mark.asyncio async def test_gemini_prepare_conversation_removes_leading_model_content(): provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) @@ -255,11 +475,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: @@ -414,3 +635,387 @@ 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]: + """Build the server-side tool parts returned by a combined tool turn. + + Returns: + List of google-genai Part objects representing a server-side search call + and its corresponding response. + """ + 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 part for part in stored] == [True, False] + assert ["tool_response" in part for part in stored] == [False, True] + assert stored[0]["thought_signature"] == base64.b64encode(b"\x01\x02").decode() + # The payload is persisted in conversation history and must stay JSON-safe. + json.dumps(stored) + # It must also survive the OpenAI-style tool call model used by the agent loop. + tool_call_model = llm_response.to_openai_tool_calls_model()[0] + assert ( + tool_call_model.model_dump()["extra_content"]["google"]["server_parts"] + == stored + ) + # The function-call signature still feeds the narration dedupe logic. + assert llm_response.reasoning_signature == base64.b64encode(b"\x03").decode() + + +def test_gemini_process_content_parts_ignores_server_side_signature_for_reasoning(): + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + candidate = SimpleNamespace( + content=types.Content( + role="model", + parts=[ + *_gemini_server_side_response_parts(), + types.Part(text="It is sunny in Shanghai."), + ], + ), + finish_reason=None, + ) + llm_response = LLMResponse(role="assistant") + + ProviderGoogleGenAI._process_content_parts( + provider, candidate, llm_response, validate_output=False + ) + + # The server-side parts themselves are not persisted for a turn without a + # custom function call, so replaying their signature as the narration + # signature would corrupt the next request. + assert llm_response.reasoning_signature is None + assert llm_response.tools_call_extra_content == {} + + +def test_gemini_process_content_parts_keeps_content_part_signature_for_reasoning(): + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + text_signature = b"\x09\x09" + 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 == base64.b64encode(text_signature).decode( + "utf-8" + ) + + +@pytest.mark.asyncio +async def test_gemini_prepare_conversation_replays_server_side_tool_parts(): + 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"}, + ], + } + }, + } + ], + }, + ] + } + ) + + model_content = contents[1] + assert model_content.parts is not None + parts = model_content.parts + assert len(parts) == 3 + assert parts[0].tool_call is not None + assert parts[0].tool_call.id == "search-1" + assert parts[0].tool_call.tool_type == types.ToolType.GOOGLE_SEARCH_WEB + assert parts[0].tool_call.args == {"queries": ["Shanghai weather"]} + assert parts[0].thought_signature == b"\x01\x02" + assert parts[1].tool_response is not None + assert parts[1].tool_response.id == "search-1" + assert parts[1].tool_response.tool_type == types.ToolType.GOOGLE_SEARCH_WEB + assert parts[1].tool_response.response == { + "search_suggestions": "Shanghai weather forecast" + } + 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].function_call.args == {"city": "Shanghai"} + assert parts[2].thought_signature == b"\x03" + + +@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 + ), + ], + ) + + final = responses[-1] + stored = final.tools_call_extra_content["call-1"]["google"]["server_parts"] + expected_signature = base64.b64encode(b"\x01\x02").decode() + # Earlier chunks are prepended so response order is preserved. + assert stored == [ + { + "tool_call": { + "id": "search-1", + "tool_type": "GOOGLE_SEARCH_WEB", + "args": {"queries": ["Shanghai weather"]}, + }, + "thought_signature": expected_signature, + }, + { + "tool_response": { + "id": "search-1", + "tool_type": "GOOGLE_SEARCH_WEB", + "response": {"search_suggestions": "Shanghai weather forecast"}, + }, + "thought_signature": expected_signature, + }, + ] + json.dumps(stored) + + +@pytest.mark.asyncio +async def test_gemini_prepare_conversation_maps_tool_result_to_function_name(): + # Tool results only carry tool_call_id, but Gemini needs the function name. + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + + 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"}', + }, + } + ], + }, + {"role": "tool", "tool_call_id": "call-1", "content": "sunny"}, + ] + } + ) + + assert [content.role for content in contents] == ["user", "model", "user"] + function_call = contents[1].parts[0].function_call + function_response = contents[2].parts[0].function_response + assert function_call is not None and function_call.name == "get_weather" + assert function_response is not None + # Regression: this used to echo the raw call ID ("call-1") as the name, + # which made the next Gemini request fail with INVALID_ARGUMENT. + assert function_response.name == "get_weather" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("narration", ["", "let me search first"]) +async def test_gemini_prepare_conversation_does_not_duplicate_server_side_signature( + narration, +): + # A signature already carried by a server-side part must not be reattached. + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + 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=signature, + ).model_dump(exclude_none=True, mode="json") + content = [ + { + "type": "think", + "think": "", + "encrypted": base64.b64encode(signature).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 + text_parts = [part for part in model_parts if part.text is not None] + if narration: + assert [part.text for part in text_parts] == [narration] + assert text_parts[0].thought_signature is None + else: + assert text_parts == [] + function_call = next(part for part in model_parts if part.function_call) + assert function_call.thought_signature is None + # The signature is only present on the replayed server-side tool part. + assert [part.thought_signature for part in model_parts if part.tool_call] == [ + signature + ] + + +@pytest.mark.asyncio +async def test_gemini_prepare_conversation_keeps_distinct_narration_signature(): + # When the narration part carries a different thought signature from the + # server-side or function-call parts, both signatures must be preserved. + provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) + narration_signature = b"\x09\x09" + 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") + + contents = await provider._prepare_conversation( + { + "messages": [ + {"role": "user", "content": "what's the weather?"}, + { + "role": "assistant", + "content": [ + { + "type": "think", + "think": "initial thought", + "encrypted": base64.b64encode(narration_signature).decode(), + }, + {"type": "text", "text": "let me search first"}, + ], + "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 + assert len(model_parts) == 3 + assert model_parts[0].text == "let me search first" + assert model_parts[0].thought_signature == narration_signature + assert model_parts[1].tool_call is not None + assert model_parts[1].thought_signature == tool_signature + assert model_parts[2].function_call is not None + assert model_parts[2].thought_signature is None From 1c397154698373e2ddbf65e8a162e79f4784d0d7 Mon Sep 17 00:00:00 2001 From: DOT Bave Date: Sun, 15 Nov 2026 12:00:49 -0500 Subject: [PATCH 2/4] refactor(provider): detect Gemini 3+ by parsing the model generation 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. --- astrbot/core/provider/sources/gemini_source.py | 14 +++++++++----- tests/test_gemini_source.py | 3 ++- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/astrbot/core/provider/sources/gemini_source.py b/astrbot/core/provider/sources/gemini_source.py index df9ecb7bc41..a5825c84213 100644 --- a/astrbot/core/provider/sources/gemini_source.py +++ b/astrbot/core/provider/sources/gemini_source.py @@ -3,6 +3,7 @@ import json import logging import random +import re from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from typing import Literal, cast @@ -281,11 +282,14 @@ async def _prepare_query_config( # Gemini 3+ models. The API requires opting into server-side tool # invocations for that combination, and AUTO mode is not supported # once the flag is enabled, so switch to VALIDATED mode. - # Match by substring (case-insensitively) because deployments may - # prefix model names, e.g. gateway aliases such as - # "gateway/gemini-3.8-flash-high". - combines_tools = has_builtin_tool and any( - marker in model_name.lower() for marker in ("gemini-3", "gemini-4") + # Parse the major generation anywhere in the model ID so gateway + # prefixes (e.g. "gateway/gemini-3.8-flash-high") and future + # generations are covered without maintaining a version list. + generation_match = re.search(r"gemini-(\d+)", model_name, re.IGNORECASE) + combines_tools = ( + has_builtin_tool + and generation_match is not None + and int(generation_match.group(1)) >= 3 ) if tool_choice == "required": mode = types.FunctionCallingConfigMode.ANY diff --git a/tests/test_gemini_source.py b/tests/test_gemini_source.py index 32900fb6c45..ac9acb3b64f 100644 --- a/tests/test_gemini_source.py +++ b/tests/test_gemini_source.py @@ -133,10 +133,11 @@ async def test_gemini_enables_server_side_tool_invocations_for_tool_combination( "gateway/gemini-3.8-flash-high", "Gateway/Gemini-3.8-Flash-High", "gemini-4-flash-preview", + "gemini-5-pro", ], ) async def test_gemini_enables_tool_combination_for_aliased_and_future_models(model): - # Model names can carry gateway prefixes; Gemini 4 is supported as well. + # Model names can carry gateway prefixes; Gemini 4+ generations are supported as well. provider = _gemini_config_provider(model, {"gm_native_search": True}) config = await provider._prepare_query_config( From ed4ebb4c4c4849be8e3e3da522f644574459f208 Mon Sep 17 00:00:00 2001 From: DOT_Bave Date: Wed, 18 Nov 2026 19:19:15 -0500 Subject: [PATCH 3/4] chore: keep google-genai minimum version at 1.56.0 --- pyproject.toml | 2 +- requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4eb1d4664da..e1377b7f5d9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,7 +26,7 @@ dependencies = [ "faiss-cpu>=1.14.3", "fastapi>=0.124.0", "filelock>=3.18.0", - "google-genai>=1.68.0", + "google-genai>=1.56.0", # bump to >=3.4.0 at some point "httpx[socks]>=0.28.1", "lark-oapi>=1.4.15", "mcp>=1.8.0,<2", diff --git a/requirements.txt b/requirements.txt index acd7d7742d6..59930c1071b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,7 +15,7 @@ docstring-parser>=0.16 faiss-cpu>=1.12.0 fastapi>=0.124.0 filelock>=3.18.0 -google-genai>=1.68.0 +google-genai>=1.56.0 httpx[socks]>=0.28.1 lark-oapi>=1.4.15 mcp>=1.8.0,<2 From 2e5afb8dec497a3f53b71b83cf4d9562e379241a Mon Sep 17 00:00:00 2001 From: DOT_Bave Date: Thu, 19 Nov 2026 07:28:43 -0500 Subject: [PATCH 4/4] refactor(provider): reuse Gemini 3/4 model check and tighten tests --- .../core/provider/sources/gemini_source.py | 103 ++-- tests/test_gemini_source.py | 474 +++++------------- 2 files changed, 159 insertions(+), 418 deletions(-) diff --git a/astrbot/core/provider/sources/gemini_source.py b/astrbot/core/provider/sources/gemini_source.py index 7adddb16929..519dc188c1f 100644 --- a/astrbot/core/provider/sources/gemini_source.py +++ b/astrbot/core/provider/sources/gemini_source.py @@ -3,7 +3,6 @@ import json import logging import random -import re from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from typing import Literal, cast @@ -41,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 中的非文本部分警告""" @@ -270,37 +276,23 @@ 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( types.Tool(function_declarations=func_desc["function_declarations"]), ) - has_builtin_tool = bool(tool_list) and any( - getattr(t, "google_search", None) - or getattr(t, "code_execution", None) - or getattr(t, "url_context", None) - for t in tool_list - ) - if not tool_list: tool_list = None tool_config = None has_func_decl = tool_list and any(t.function_declarations for t in tool_list) if has_func_decl: - # Built-in tools can be combined with function calling only on - # Gemini 3+ models. The API requires opting into server-side tool - # invocations for that combination, and AUTO mode is not supported - # once the flag is enabled, so switch to VALIDATED mode. - # Parse the major generation anywhere in the model ID so gateway - # prefixes (e.g. "gateway/gemini-3.8-flash-high") and future - # generations are covered without maintaining a version list. - generation_match = re.search(r"gemini-(\d+)", model_name, re.IGNORECASE) - combines_tools = ( - has_builtin_tool - and generation_match is not None - and int(generation_match.group(1)) >= 3 + # 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 @@ -312,10 +304,7 @@ async def _prepare_query_config( "function_calling_config": types.FunctionCallingConfig(mode=mode), } if combines_tools: - # google-genai<1.68.0 does not define this field and its SDK - # models reject unknown fields, so keep it off the request in - # that case and let the API report the unsupported combination - # instead of raising a confusing pydantic error. + # google-genai<1.68.0 lacks this field and rejects unknown kwargs. if ( "include_server_side_tool_invocations" in types.ToolConfig.model_fields @@ -499,8 +488,7 @@ def append_or_extend( contents.append(content_cls(parts=part)) gemini_contents: list[types.Content] = [] - # Map custom tool call IDs to function names so tool result messages - # (which only carry the call ID) can be matched to the original call. + # 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") @@ -529,10 +517,7 @@ def append_or_extend( function_name = tool["function"]["name"] if tool.get("id"): tool_id_to_name[tool["id"]] = function_name - # Replay server-side tool parts (tool_call/tool_response) - # captured from a previous response. When server-side - # invocations are enabled, the API requires them to be - # sent back unchanged, including their thought signatures. + # 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( @@ -586,10 +571,7 @@ def append_or_extend( ) ) if has_duplicate_thought_signature: - # Tool calls and replayed server-side tool parts already - # 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. + # Omit duplicate thought_signature already carried by a tool/server part. if text: parts.append(types.Part(text=text)) else: @@ -609,8 +591,7 @@ def append_or_extend( elif role == "tool": tool_call_id = message["tool_call_id"] - # Tool result messages only carry the call ID, so resolve the - # function name from the preceding assistant message. + # 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 ) @@ -736,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 @@ -770,36 +752,15 @@ def _process_content_parts( ): chain.append(Comp.Image.fromBytes(part.inline_data.data)) - if ts := part.thought_signature: - # Server-side tool parts are replayed through their own - # extra_content/server_parts. Copying their signature here would - # attach a tool-part signature to the narration text on the next - # turn, so only keep signatures from regular content parts. - is_server_side_part = bool( - getattr(part, "tool_call", None) - or getattr(part, "tool_response", None) - or getattr(part, "executable_code", None) - or getattr(part, "code_execution_result", None) + 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") ) - if not is_server_side_part: - # only keep the last thinking signature - llm_response.reasoning_signature = base64.b64encode(ts).decode( - "utf-8" - ) + 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") - # Keep server-side tool parts (tool_call/tool_response and code - # execution parts) so they can be replayed unchanged, with their thought - # signatures, in the next tool-loop request. The agent tool loop only - # keeps OpenAI-style tool call messages between steps, so the parts are - # stored on the first custom tool call's extra_content. - server_side_parts = [ - part.model_dump(exclude_none=True, mode="json") - for part in result_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) - ] + # 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], {} @@ -978,9 +939,7 @@ async def _query_stream( accumulated_text = "" accumulated_reasoning = "" final_response = None - # Server-side tool parts (tool_call/tool_response) may stream in their own - # chunks before the custom tool call chunk. Keep them so they can be - # replayed to the API in the next tool-loop request. + # 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): @@ -1004,8 +963,7 @@ async def _query_stream( llm_response, validate_output=False, ) - # Server-side tool parts may arrive in earlier chunks; prepend - # them so the replayed parts keep their response order. + # 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], {} @@ -1039,10 +997,9 @@ async def _query_stream( 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) + if any( + getattr(part, attr, None) for attr in _SERVER_SIDE_PART_ATTRS + ) ) _f = False diff --git a/tests/test_gemini_source.py b/tests/test_gemini_source.py index 8007ebd5c07..d84bf5831b3 100644 --- a/tests/test_gemini_source.py +++ b/tests/test_gemini_source.py @@ -18,15 +18,6 @@ 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. - - Args: - model: Model identifier to configure on the provider stub. - provider_config: Optional provider configuration dictionary. - - Returns: - Configured ProviderGoogleGenAI stub instance. - """ provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) provider.provider_config = provider_config or {} provider.provider_settings = {} @@ -36,11 +27,6 @@ def _gemini_config_provider( def _gemini_func_toolset() -> SimpleNamespace: - """Build a minimal ToolSet stand-in exposing one function declaration. - - Returns: - SimpleNamespace implementing get_func_desc_google_genai_style. - """ return SimpleNamespace( get_func_desc_google_genai_style=lambda: { "function_declarations": [ @@ -107,107 +93,89 @@ async def test_gemini_omits_unset_or_unsupported_thinking_config(model, provider @pytest.mark.asyncio @pytest.mark.parametrize( - "provider_config", + ("model", "cfg", "with_func", "choice", "expected_mode", "expected_flag"), [ - {"gm_native_search": True}, - {"gm_url_context": True}, - {"gm_native_coderunner": True}, + ( + "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_enables_server_side_tool_invocations_for_tool_combination( - provider_config, +async def test_gemini_tool_combination_config_matrix( + model, cfg, with_func, choice, expected_mode, expected_flag ): - # Built-in tools + function calling on Gemini 3+ must opt into server-side - # tool invocations to avoid 400 INVALID_ARGUMENT ("Please enable - # tool_config.include_server_side_tool_invocations to use Built-in tools - # with Function calling."). - model = "gemini-3.8-flash" - provider = _gemini_config_provider(model, provider_config) - - config = await provider._prepare_query_config( - {"model": model}, tools=_gemini_func_toolset() - ) - - assert config.tool_config is not None - assert config.tool_config.include_server_side_tool_invocations is True - assert config.tool_config.function_calling_config is not None - # AUTO mode is not supported together with the flag. - assert ( - config.tool_config.function_calling_config.mode - == types.FunctionCallingConfigMode.VALIDATED - ) - - -@pytest.mark.asyncio -@pytest.mark.parametrize( - "model", - [ - "gateway/gemini-3.8-flash-high", - "Gateway/Gemini-3.8-Flash-High", - "gemini-4-flash-preview", - "gemini-5-pro", - ], -) -async def test_gemini_enables_tool_combination_for_aliased_and_future_models(model): - # Model names can carry gateway prefixes; Gemini 4+ generations are supported as well. - provider = _gemini_config_provider(model, {"gm_native_search": True}) - - config = await provider._prepare_query_config( - {"model": model}, tools=_gemini_func_toolset() - ) - - assert config.tool_config is not None - assert config.tool_config.include_server_side_tool_invocations is True - assert config.tool_config.function_calling_config is not None - assert ( - config.tool_config.function_calling_config.mode - == types.FunctionCallingConfigMode.VALIDATED - ) - - -@pytest.mark.asyncio -async def test_gemini_required_tool_choice_keeps_any_mode_for_tool_combination(): - model = "gemini-3.8-flash" - provider = _gemini_config_provider(model, {"gm_native_search": True}) - + provider = _gemini_config_provider(model, cfg) config = await provider._prepare_query_config( {"model": model}, - tools=_gemini_func_toolset(), - tool_choice="required", - ) - - assert config.tool_config is not None - assert config.tool_config.include_server_side_tool_invocations is True - assert config.tool_config.function_calling_config is not None - assert ( - config.tool_config.function_calling_config.mode - == types.FunctionCallingConfigMode.ANY + tools=_gemini_func_toolset() if with_func else None, + tool_choice=choice, ) - -@pytest.mark.asyncio -async def test_gemini_function_only_requests_keep_auto_mode(): - model = "gemini-3.8-flash" - provider = _gemini_config_provider(model) - - config = await provider._prepare_query_config( - {"model": model}, tools=_gemini_func_toolset() - ) + 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 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 - == types.FunctionCallingConfigMode.AUTO + assert config.tool_config.function_calling_config.mode == getattr( + types.FunctionCallingConfigMode, expected_mode ) @pytest.mark.asyncio -async def test_gemini_function_only_config_omits_server_side_flag_kwarg(monkeypatch): - # google-genai<1.68.0 does not define - # ToolConfig.include_server_side_tool_invocations and rejects unknown - # constructor arguments, so plain function calling must not pass it. +async def test_gemini_tool_config_sdk_fallback_and_kwarg_omission(monkeypatch, caplog): captured_kwargs: dict = {} original_tool_config = types.ToolConfig @@ -215,75 +183,34 @@ def _capturing_tool_config(**kwargs): captured_kwargs.update(kwargs) return original_tool_config(**kwargs) - monkeypatch.setattr(gemini_source.types, "ToolConfig", _capturing_tool_config) - - model = "gemini-2.5-flash" - provider = _gemini_config_provider(model) - - await provider._prepare_query_config({"model": model}, tools=_gemini_func_toolset()) - + 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 - -@pytest.mark.asyncio -async def test_gemini_tool_combination_warns_when_sdk_lacks_server_side_flag( - monkeypatch, caplog -): - # 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. class _LegacyToolConfig(types.ToolConfig): pass _LegacyToolConfig.model_fields = { - name: field_info - for name, field_info in types.ToolConfig.model_fields.items() - if name != "include_server_side_tool_invocations" + 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) - - model = "gemini-3.8-flash" - provider = _gemini_config_provider(model, {"gm_native_search": True}) caplog.set_level(logging.WARNING, logger="astrbot") - config = await provider._prepare_query_config( - {"model": model}, tools=_gemini_func_toolset() - ) + 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_builtin_only_requests_keep_tool_config_unset(): - model = "gemini-3.8-flash" - provider = _gemini_config_provider(model, {"gm_native_search": True}) - - config = await provider._prepare_query_config({"model": model}) - - assert config.tool_config is None - assert config.tools is not None - - -@pytest.mark.asyncio -@pytest.mark.parametrize("model", ["gemini-2.5-flash", "gateway/gemini-2.5-flash"]) -async def test_gemini_legacy_models_do_not_opt_in_server_side_tool_invocations(model): - # Gemini 1.x/2.x must not receive the preview-only opt-in flag. - provider = _gemini_config_provider(model, {"gm_native_search": True}) - - config = await provider._prepare_query_config( - {"model": model}, tools=_gemini_func_toolset() - ) - - assert config.tool_config is not None - assert config.tool_config.include_server_side_tool_invocations is None - assert config.tool_config.function_calling_config is not None - assert ( - config.tool_config.function_calling_config.mode - == types.FunctionCallingConfigMode.AUTO - ) - - @pytest.mark.asyncio async def test_gemini_prepare_conversation_keeps_normal_user_first_history(): provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) @@ -671,12 +598,6 @@ async def test_gemini_stream_keeps_reasoning_from_tool_call_chunk(monkeypatch): def _gemini_server_side_response_parts() -> list[types.Part]: - """Build the server-side tool parts returned by a combined tool turn. - - Returns: - List of google-genai Part objects representing a server-side search call - and its corresponding response. - """ signature = b"\x01\x02" return [ types.Part( @@ -723,49 +644,29 @@ def test_gemini_process_content_parts_keeps_server_side_tool_parts(): 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 part for part in stored] == [True, False] - assert ["tool_response" in part for part in stored] == [False, True] + 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() - # The payload is persisted in conversation history and must stay JSON-safe. json.dumps(stored) - # It must also survive the OpenAI-style tool call model used by the agent loop. tool_call_model = llm_response.to_openai_tool_calls_model()[0] assert ( tool_call_model.model_dump()["extra_content"]["google"]["server_parts"] == stored ) - # The function-call signature still feeds the narration dedupe logic. assert llm_response.reasoning_signature == base64.b64encode(b"\x03").decode() -def test_gemini_process_content_parts_ignores_server_side_signature_for_reasoning(): - provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) - candidate = SimpleNamespace( - content=types.Content( - role="model", - parts=[ - *_gemini_server_side_response_parts(), - types.Part(text="It is sunny in Shanghai."), - ], - ), - finish_reason=None, - ) - llm_response = LLMResponse(role="assistant") - - ProviderGoogleGenAI._process_content_parts( - provider, candidate, llm_response, validate_output=False - ) - - # The server-side parts themselves are not persisted for a turn without a - # custom function call, so replaying their signature as the narration - # signature would corrupt the next request. - assert llm_response.reasoning_signature is None - assert llm_response.tools_call_extra_content == {} - - -def test_gemini_process_content_parts_keeps_content_part_signature_for_reasoning(): +@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) - text_signature = b"\x09\x09" candidate = SimpleNamespace( content=types.Content( role="model", @@ -782,13 +683,12 @@ def test_gemini_process_content_parts_keeps_content_part_signature_for_reasoning provider, candidate, llm_response, validate_output=False ) - assert llm_response.reasoning_signature == base64.b64encode(text_signature).decode( - "utf-8" - ) + assert llm_response.reasoning_signature == expected + assert llm_response.tools_call_extra_content == {} @pytest.mark.asyncio -async def test_gemini_prepare_conversation_replays_server_side_tool_parts(): +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") @@ -823,30 +723,25 @@ async def test_gemini_prepare_conversation_replays_server_side_tool_parts(): } ], }, + {"role": "tool", "tool_call_id": "call-1", "content": "sunny"}, ] } ) - model_content = contents[1] - assert model_content.parts is not None - parts = model_content.parts - assert len(parts) == 3 - assert parts[0].tool_call is not None - assert parts[0].tool_call.id == "search-1" - assert parts[0].tool_call.tool_type == types.ToolType.GOOGLE_SEARCH_WEB - assert parts[0].tool_call.args == {"queries": ["Shanghai weather"]} + 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 - assert parts[1].tool_response.id == "search-1" - assert parts[1].tool_response.tool_type == types.ToolType.GOOGLE_SEARCH_WEB - assert parts[1].tool_response.response == { - "search_suggestions": "Shanghai weather forecast" - } + 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].function_call.args == {"city": "Shanghai"} 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 @@ -871,87 +766,38 @@ async def test_gemini_stream_keeps_server_side_tool_parts_for_next_turn(monkeypa ], ) - final = responses[-1] - stored = final.tools_call_extra_content["call-1"]["google"]["server_parts"] - expected_signature = base64.b64encode(b"\x01\x02").decode() - # Earlier chunks are prepended so response order is preserved. + stored = responses[-1].tools_call_extra_content["call-1"]["google"]["server_parts"] assert stored == [ - { - "tool_call": { - "id": "search-1", - "tool_type": "GOOGLE_SEARCH_WEB", - "args": {"queries": ["Shanghai weather"]}, - }, - "thought_signature": expected_signature, - }, - { - "tool_response": { - "id": "search-1", - "tool_type": "GOOGLE_SEARCH_WEB", - "response": {"search_suggestions": "Shanghai weather forecast"}, - }, - "thought_signature": expected_signature, - }, + part.model_dump(exclude_none=True, mode="json") for part in server_side_parts ] json.dumps(stored) @pytest.mark.asyncio -async def test_gemini_prepare_conversation_maps_tool_result_to_function_name(): - # Tool results only carry tool_call_id, but Gemini needs the function name. - provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) - - 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"}', - }, - } - ], - }, - {"role": "tool", "tool_call_id": "call-1", "content": "sunny"}, - ] - } - ) - - assert [content.role for content in contents] == ["user", "model", "user"] - function_call = contents[1].parts[0].function_call - function_response = contents[2].parts[0].function_response - assert function_call is not None and function_call.name == "get_weather" - assert function_response is not None - # Regression: this used to echo the raw call ID ("call-1") as the name, - # which made the next Gemini request fail with INVALID_ARGUMENT. - assert function_response.name == "get_weather" - - -@pytest.mark.asyncio -@pytest.mark.parametrize("narration", ["", "let me search first"]) -async def test_gemini_prepare_conversation_does_not_duplicate_server_side_signature( - narration, +@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 ): - # A signature already carried by a server-side part must not be reattached. provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) - signature = b"\x01\x02" + 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=signature, + thought_signature=tool_signature, ).model_dump(exclude_none=True, mode="json") content = [ { "type": "think", "think": "", - "encrypted": base64.b64encode(signature).decode(), + "encrypted": base64.b64encode(narration_sig).decode(), } ] if narration: @@ -968,10 +814,7 @@ async def test_gemini_prepare_conversation_does_not_duplicate_server_side_signat { "id": "call-1", "type": "function", - "function": { - "name": "get_weather", - "arguments": "{}", - }, + "function": {"name": "get_weather", "arguments": "{}"}, "extra_content": { "google": {"server_parts": [server_side_part]} }, @@ -983,72 +826,13 @@ async def test_gemini_prepare_conversation_does_not_duplicate_server_side_signat ) model_parts = contents[1].parts - text_parts = [part for part in model_parts if part.text is not None] - if narration: - assert [part.text for part in text_parts] == [narration] - assert text_parts[0].thought_signature is None + 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 == [] - function_call = next(part for part in model_parts if part.function_call) - assert function_call.thought_signature is None - # The signature is only present on the replayed server-side tool part. - assert [part.thought_signature for part in model_parts if part.tool_call] == [ - signature - ] - - -@pytest.mark.asyncio -async def test_gemini_prepare_conversation_keeps_distinct_narration_signature(): - # When the narration part carries a different thought signature from the - # server-side or function-call parts, both signatures must be preserved. - provider = ProviderGoogleGenAI.__new__(ProviderGoogleGenAI) - narration_signature = b"\x09\x09" - 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") - - contents = await provider._prepare_conversation( - { - "messages": [ - {"role": "user", "content": "what's the weather?"}, - { - "role": "assistant", - "content": [ - { - "type": "think", - "think": "initial thought", - "encrypted": base64.b64encode(narration_signature).decode(), - }, - {"type": "text", "text": "let me search first"}, - ], - "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 - assert len(model_parts) == 3 - assert model_parts[0].text == "let me search first" - assert model_parts[0].thought_signature == narration_signature - assert model_parts[1].tool_call is not None - assert model_parts[1].thought_signature == tool_signature - assert model_parts[2].function_call is not None - assert model_parts[2].thought_signature is None + 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]