From c82a9148082d061cfa91ca51e3c8ba7e7baf0000 Mon Sep 17 00:00:00 2001 From: Lorenze Jay Date: Fri, 27 Nov 2026 11:58:44 -0800 Subject: [PATCH 1/3] Gemini 3 and 4: sign handed-back tool calls on the engines LangGraph's fix did not reach Gemini 3 and later refuse a function call in the current turn without the thought signature the model gave it ("Function call is missing a thought_signature in functionCall parts"). OpenBot runs each tool between two runs and an AG-UI tool call has no field for a signature. 1.2.2 carries the real signature through the thread on both LangGraph engines (#2334, #2335); every other engine still sent the handed-back call unsigned, so a Bot on Gemini 3.x or 4 failed after its first tool. - shared/gemini_signatures.py: ADK, AG2, CrewAI, Langroid, LlamaIndex and Strands install it beside run_model_key. It wraps httpx/httpx2 sends and aiohttp requests and gives each unsigned call Google's documented placeholder, `skip_thought_signature_validator`: on Gemini's own API (`functionCall` parts, any host) and on Google's OpenAI-compatible endpoint or OpenBot's gateway for a Gemini model (`extra_content.google.thought_signature`). A real signature is kept; any other provider's or model's request is sent byte for byte. - shared/gemini-signatures.ts: the same rules as a fetch wrapper, for Mastra's OpenAI-compatible client. - LiteLLM engines (ADK, Strands, Langroid, CrewAI, LlamaIndex) address Gemini as `gemini/`, not `google/` ("LLM Provider NOT provided"), through `litellm_model` in model_providers.py. - AG2 answers `BOT_PROVIDER=google` with its GeminiConfig on the Google key, instead of the OpenAI config that asked for OPENAI_API_KEY. - scripts/model-compat.ts: the one run per model now hands back an unsigned tool call and its result (`handBackRun`), so the lock no longer verifies a model a Bot cannot finish a tool call on. - Tests: a hand-back test per engine against the shared fake provider (now also serving Gemini's generateContent), signing-rule tests for both modules, model-compat's run body. --- CHANGELOG.md | 15 ++ agent-adk/Dockerfile | 2 +- agent-adk/src/main.py | 21 +- agent-adk/tests/test_gemini_handback.py | 50 ++++ agent-adk/tests/test_gemini_signatures.py | 157 +++++++++++++ agent-ag2/Dockerfile | 2 +- agent-ag2/requirements.txt | 8 +- agent-ag2/src/main.py | 39 +++- agent-ag2/tests/test_gemini_handback.py | 51 ++++ agent-crewai/Dockerfile | 2 +- agent-crewai/src/main.py | 20 +- agent-crewai/tests/test_gemini_handback.py | 55 +++++ agent-langroid/Dockerfile | 2 +- agent-langroid/src/main.py | 8 +- agent-langroid/tests/test_gemini_handback.py | 66 ++++++ agent-llamaindex/Dockerfile | 2 +- agent-llamaindex/src/main.py | 21 +- .../tests/test_gemini_handback.py | 58 +++++ agent-mastra/Dockerfile | 1 + agent-mastra/src/mastra/index.test.ts | 104 +++++++++ agent-mastra/src/mastra/index.ts | 4 + agent-strands/Dockerfile | 2 +- agent-strands/src/main.py | 21 +- agent-strands/tests/test_gemini_handback.py | 49 ++++ docs/releasing.md | 5 +- scripts/model-compat.test.ts | 54 +++++ scripts/model-compat.ts | 114 +++++++-- shared/gemini-signatures.test.ts | 157 +++++++++++++ shared/gemini-signatures.ts | 145 ++++++++++++ shared/gemini_signatures.py | 221 ++++++++++++++++++ shared/harness_contract.py | 168 ++++++++++++- shared/model_providers.py | 20 ++ 32 files changed, 1548 insertions(+), 96 deletions(-) create mode 100644 agent-adk/tests/test_gemini_handback.py create mode 100644 agent-adk/tests/test_gemini_signatures.py create mode 100644 agent-ag2/tests/test_gemini_handback.py create mode 100644 agent-crewai/tests/test_gemini_handback.py create mode 100644 agent-langroid/tests/test_gemini_handback.py create mode 100644 agent-llamaindex/tests/test_gemini_handback.py create mode 100644 agent-strands/tests/test_gemini_handback.py create mode 100644 shared/gemini-signatures.test.ts create mode 100644 shared/gemini-signatures.ts create mode 100644 shared/gemini_signatures.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 06e35d78dd..5dddce23e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,21 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **A Bot on Gemini 3 or Gemini 4 finishes what it started with a tool, on every engine.** 1.2.2 + fixed this on the LangGraph engines. On the others, a Bot that used a tool on Gemini 3.x or + Gemini 4 still got an error from Google once the tool's result came back ("Function call is + missing a thought_signature"), with a key saved as Google's OpenAI-compatible endpoint, as + OpenBot Desktop and Settings save it. Google ADK, AG2, CrewAI, Langroid, LlamaIndex, Mastra and + Strands now send each handed-back tool call to a Gemini model with Google's documented + placeholder, and keep a real signature when there is one. Requests to every other provider are + sent as before. Antigravity was not affected. +- **`BOT_PROVIDER=google` works on Google ADK, Strands, Langroid, CrewAI, LlamaIndex and AG2.** + The first five stopped before reaching Google ("LLM Provider NOT provided"), and AG2 asked for an + OpenAI key. AG2 now answers on Google's own Gemini API with the Google key. +- **The model check tries each model on a tool call handed back.** The scheduled check of which + models each engine can run sends every model a run that ends in a tool call and its result, as a + Bot's runs do, so a model that cannot finish a tool call is no longer listed as working. + ## 1.2.2 **Before upgrading.** diff --git a/agent-adk/Dockerfile b/agent-adk/Dockerfile index 65266eee30..9abc0a8cb3 100644 --- a/agent-adk/Dockerfile +++ b/agent-adk/Dockerfile @@ -9,7 +9,7 @@ COPY agent-adk/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY agent-adk/src ./src -COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py /shared/ ENV PORT=4208 EXPOSE 4208 diff --git a/agent-adk/src/main.py b/agent-adk/src/main.py index 8d5224be9d..07d2d0cb83 100644 --- a/agent-adk/src/main.py +++ b/agent-adk/src/main.py @@ -14,8 +14,12 @@ # The spec file every language in the box reads: one level above this Bot in the repository, and # one level above /app/src in the image the Dockerfile builds. sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) -from model_providers import bot_settings +from model_providers import bot_settings, litellm_model from run_model_key import RunModelKey +import gemini_signatures + +# Every Gemini tool call this Bot sends back is signed. See gemini_signatures.py. +gemini_signatures.install() from ag_ui.core import ( AssistantMessage, @@ -334,20 +338,9 @@ async def run(self, input: RunAgentInput): def _model_id() -> str: - """`provider/model`, which is how litellm addresses one. - - The model half is whatever the endpoint publishes, slashes included. litellm takes the first - path component as the provider and sends the rest as the model name, so a name that already - contains a slash still needs the chosen provider in front: `qwen/qwen3-8b` on an - OpenAI-compatible endpoint is `openai/qwen/qwen3-8b`, and `openai/gpt-5.6-terra` is - `openai/openai/gpt-5.6-terra`. Treating a slash as "already a provider" dropped the prefix, - and litellm then either routed to a provider nobody configured (`LLM Provider NOT provided`) - or sent only the second half to the endpoint. - """ + """`provider/model`, which is how LiteLLM addresses one. See `litellm_model`.""" settings = bot_settings("agent-adk") - provider = settings.provider - model = settings.model - return f"{provider}/{model}" + return litellm_model(settings.provider, settings.model) app = FastAPI() diff --git a/agent-adk/tests/test_gemini_handback.py b/agent-adk/tests/test_gemini_handback.py new file mode 100644 index 0000000000..c86f198efd --- /dev/null +++ b/agent-adk/tests/test_gemini_handback.py @@ -0,0 +1,50 @@ +"""A tool call handed back on Gemini reaches it signed; on any other model, as it was. + +See `shared/gemini_signatures.py`. Checked at the model's door, on both ways a Bot reaches Gemini: +its own API (`BOT_PROVIDER=google`) and an OpenAI-compatible address. +""" + +import importlib +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from harness_contract import ( + check_handback_signed, + gemini_environment, + gemini_gateway_environment, + handback_bodies, + openai_environment, + tool_calls_sent, +) + +TOKEN = "contract-token" + + +@pytest.fixture +def app_for(monkeypatch): + def app_for(environment): + monkeypatch.delenv("OPENAI_API_BASE", raising=False) + monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) + monkeypatch.setenv("OTEL_SDK_DISABLED", "true") + for key, value in environment.items(): + monkeypatch.setenv(key, value) + from src import main + + return importlib.reload(main).app + + return app_for + + +@pytest.mark.parametrize("environment", [gemini_environment, gemini_gateway_environment]) +def test_a_handed_back_gemini_call_is_signed(app_for, environment): + check_handback_signed(handback_bodies(app_for, environment, token=TOKEN)) + + +def test_a_handed_back_call_to_another_model_is_sent_as_it_was(app_for): + calls = tool_calls_sent(handback_bodies(app_for, openai_environment, token=TOKEN)[-1]) + assert calls, "the handed-back call never reached the model as a call" + assert not any(call["signature"] for call in calls), calls diff --git a/agent-adk/tests/test_gemini_signatures.py b/agent-adk/tests/test_gemini_signatures.py new file mode 100644 index 0000000000..0eb0228e71 --- /dev/null +++ b/agent-adk/tests/test_gemini_signatures.py @@ -0,0 +1,157 @@ +"""Which requests `shared/gemini_signatures.py` signs, and which it leaves byte for byte. + +The module is shared by every Python harness; its rules are checked once, here. Each harness's +`test_gemini_handback.py` checks that the harness actually installs it. +""" + +import json +import sys +from pathlib import Path + +import httpx +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +import gemini_signatures +from gemini_signatures import GEMINI_UNSIGNED_CALL, is_gemini_model, signed_body + +GOOGLE = "https://generativelanguage.googleapis.com" +COMPAT = f"{GOOGLE}/v1beta/openai/chat/completions" + + +def _chat(model="gemini-3.8-flash", extra=None): + call = {"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{}"}} + if extra is not None: + call["extra_content"] = extra + return json.dumps( + { + "model": model, + "messages": [ + {"role": "user", "content": "hi"}, + {"role": "assistant", "content": None, "tool_calls": [call]}, + {"role": "tool", "tool_call_id": "c1", "content": "{}"}, + ], + } + ).encode() + + +def _contents(signature=None): + part = {"functionCall": {"name": "f", "args": {}}} + if signature is not None: + part["thoughtSignature"] = signature + return json.dumps( + { + "contents": [ + {"role": "user", "parts": [{"text": "hi"}]}, + {"role": "model", "parts": [part, {"function_call": {"name": "g", "args": {}}}]}, + {"role": "user", "parts": [{"functionResponse": {"name": "f", "response": {}}}]}, + ] + } + ).encode() + + +def _signatures(body): + parsed = json.loads(body) + if "messages" in parsed: + return [ + ((call.get("extra_content") or {}).get("google") or {}).get("thought_signature") + for message in parsed["messages"] + for call in message.get("tool_calls") or [] + ] + return [ + part.get("thoughtSignature") + for content in parsed["contents"] + for part in content["parts"] + if "functionCall" in part or "function_call" in part + ] + + +@pytest.mark.parametrize( + "model", + ["gemini-4-hydrogen", "gemini-3.8-flash", "models/gemini-4-neon", "google/gemini-4-carbon"], +) +def test_gemini_models_are_gemini(model): + assert is_gemini_model(model) + + +@pytest.mark.parametrize("model", ["gpt-5.5", "claude-sonnet-5-5", "gemma-4-31b-it", None, ""]) +def test_other_models_are_not(model): + assert not is_gemini_model(model) + + +@pytest.mark.parametrize( + "path", [":generateContent", ":streamGenerateContent"] +) +def test_gemini_native_calls_are_signed_on_any_host(path): + for base in (f"{GOOGLE}/v1beta", "http://127.0.0.1:9/gateway/v1beta"): + body = signed_body("POST", f"{base}/models/gemini-4-hydrogen{path}?alt=sse", _contents()) + assert _signatures(body) == [GEMINI_UNSIGNED_CALL, GEMINI_UNSIGNED_CALL] + + +def test_a_signature_already_there_is_kept(): + body = signed_body( + "POST", f"{GOOGLE}/v1beta/models/gemini-3.8-flash:generateContent", _contents("real") + ) + assert _signatures(body) == ["real", GEMINI_UNSIGNED_CALL] + assert ( + signed_body("POST", COMPAT, _chat(extra={"google": {"thought_signature": "real"}})) is None + ) + + +def test_a_native_request_for_another_model_is_left_alone(): + assert signed_body("POST", f"{GOOGLE}/v1beta/models/gemma-4-31b-it:generateContent", _contents()) is None + + +def test_googles_compatible_endpoint_is_signed_in_extra_content(): + body = signed_body("POST", COMPAT, _chat(extra={"other": 1})) + call = json.loads(body)["messages"][1]["tool_calls"][0] + assert call["extra_content"] == { + "other": 1, + "google": {"thought_signature": GEMINI_UNSIGNED_CALL}, + } + + +def test_openbots_gateway_is_signed_for_a_gemini_model(): + url = "http://openbot:3010/api/model-provider/v1/chat/completions" + assert _signatures(signed_body("POST", url, _chat())) == [GEMINI_UNSIGNED_CALL] + assert signed_body("POST", url, _chat(model="gpt-5.5")) is None + + +@pytest.mark.parametrize( + "url", + [ + "https://api.openai.com/v1/chat/completions", + "https://openrouter.ai/api/v1/chat/completions", + "http://localhost:11434/v1/chat/completions", + ], +) +def test_another_provider_is_never_touched_even_for_a_gemini_name(url): + assert signed_body("POST", url, _chat()) is None + + +def test_a_non_gemini_model_on_googles_endpoint_is_left_alone(): + assert signed_body("POST", COMPAT, _chat(model="gemma-4-31b-it")) is None + + +def test_nothing_to_sign_and_not_json_are_left_alone(): + assert signed_body("GET", COMPAT, _chat()) is None + assert signed_body("POST", COMPAT, b"not json") is None + assert signed_body("POST", COMPAT, None) is None + plain = json.dumps({"model": "gemini-3.8-flash", "messages": [{"role": "user", "content": "hi"}]}) + assert signed_body("POST", COMPAT, plain.encode()) is None + + +def test_an_httpx_request_is_sent_signed(): + gemini_signatures.install() + seen = [] + + def handler(request): + seen.append(json.loads(request.content)) + assert int(request.headers["content-length"]) == len(request.content) + return httpx.Response(200, json={}) + + with httpx.Client(transport=httpx.MockTransport(handler)) as client: + client.post(COMPAT, content=_chat(), headers={"content-type": "application/json"}) + client.post("https://api.openai.com/v1/chat/completions", content=_chat()) + assert _signatures(json.dumps(seen[0]).encode()) == [GEMINI_UNSIGNED_CALL] + assert _signatures(json.dumps(seen[1]).encode()) == [None] diff --git a/agent-ag2/Dockerfile b/agent-ag2/Dockerfile index fbce0838fa..304403b26d 100644 --- a/agent-ag2/Dockerfile +++ b/agent-ag2/Dockerfile @@ -9,7 +9,7 @@ COPY agent-ag2/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY agent-ag2/src ./src -COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py /shared/ ENV PORT=4210 EXPOSE 4210 diff --git a/agent-ag2/requirements.txt b/agent-ag2/requirements.txt index 38e0aab92e..3607eeaed9 100644 --- a/agent-ag2/requirements.txt +++ b/agent-ag2/requirements.txt @@ -1,6 +1,10 @@ # 1.3.2 is the first release this harness is checked on with both OpenAICompletionsConfig and -# OpenAIResponsesConfig, which src/main.py names explicitly. -ag2[ag-ui,anthropic,openai]>=1.3.2 +# OpenAIResponsesConfig, which src/main.py names explicitly. `gemini` installs google-genai, which +# GeminiConfig needs for a Bot on a Gemini key. +ag2[ag-ui,anthropic,gemini,openai]>=1.3.2 +# google-genai 3.0.0 (2026-11-06) moved generateContent from /v1beta to /v1, and ag2[gemini] asks +# for any google-genai, so a fresh install picks it up. Held with the other harnesses. +google-genai>=2.34,<3 fastapi python-multipart uvicorn[standard] diff --git a/agent-ag2/src/main.py b/agent-ag2/src/main.py index 0d705c2560..c5653a288a 100644 --- a/agent-ag2/src/main.py +++ b/agent-ag2/src/main.py @@ -2,29 +2,47 @@ import hmac import os +import re import sys from pathlib import Path # The spec file every language in the box reads: one level above this Bot in the repository, and # one level above /app/src in the image the Dockerfile builds. sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) -from model_providers import bot_settings, openai_api +from model_providers import SPEC, bot_settings, openai_api from run_model_key import RunModelKey +import gemini_signatures + +# Every Gemini tool call this Bot sends back is signed. See gemini_signatures.py. +gemini_signatures.install() from ag2 import Agent from ag2.ag_ui import AGUIStream -from ag2.config import AnthropicConfig, OpenAICompletionsConfig, OpenAIResponsesConfig +from ag2.config import ( + AnthropicConfig, + GeminiConfig, + OpenAICompletionsConfig, + OpenAIResponsesConfig, +) from fastapi import FastAPI, Request from fastapi.responses import JSONResponse TOKEN_HEADER = "x-openbot-agent-token" -def _config() -> AnthropicConfig | OpenAICompletionsConfig | OpenAIResponsesConfig: +def _config() -> ( + AnthropicConfig | GeminiConfig | OpenAICompletionsConfig | OpenAIResponsesConfig +): """The provider the model screen chose, which AG2 reaches through a config of its own. - `BOT_PROVIDER` is `anthropic` for an Anthropic key and `openai` otherwise, an OpenAI-compatible - endpoint included. Each SDK reads its own key from the environment. + `BOT_PROVIDER` is `anthropic` for an Anthropic key, `google` for a Gemini key, and `openai` + otherwise, an OpenAI-compatible endpoint included. Each SDK reads its own key from the + environment. + + A Gemini key takes AG2's Gemini config, on Google's own API. Before, `google` fell through to + the OpenAI config, which asked for `OPENAI_API_KEY` and sent the Gemini model to OpenAI. The + Gemini config also hands a call's thought signature to AG-UI and takes it back on a + handed-back call, where the server keeps it. An OpenAI model takes AG2's Responses config when it takes function tools only there (`gpt-5.6` and later, `gpt-5.4` and `gpt-5.5` once a run carries an effort, the `-pro` models: @@ -36,6 +54,17 @@ def _config() -> AnthropicConfig | OpenAICompletionsConfig | OpenAIResponsesConf settings = bot_settings("agent-ag2") provider = settings.provider model = settings.model + if provider == "google": + google = SPEC["providers"]["google"] + base_url = (os.environ.get(google["base_url_variable"]) or "").strip() + if base_url: + # google-genai's own name for the address, which it reads when it builds its client. + # It adds the API version itself, so one the address ends in (`.../v1beta`, as the AI + # SDK takes it) is left off. + version = r"/v\d+(?:alpha|beta)?\d*/?$" + os.environ["GOOGLE_GEMINI_BASE_URL"] = re.sub(version, "", base_url) + api_key = (os.environ.get(google["key_variable"]) or "").strip() or None + return GeminiConfig(model=model, api_key=api_key) if provider == "anthropic": # Compose exports missing overrides as ""; the SDK only defaults an absent URL. base_url = (os.environ.get("ANTHROPIC_BASE_URL") or "").strip() or "https://api.anthropic.com" diff --git a/agent-ag2/tests/test_gemini_handback.py b/agent-ag2/tests/test_gemini_handback.py new file mode 100644 index 0000000000..5397ec1be6 --- /dev/null +++ b/agent-ag2/tests/test_gemini_handback.py @@ -0,0 +1,51 @@ +"""A tool call handed back on Gemini reaches it signed; on any other model, as it was. + +See `shared/gemini_signatures.py`. Checked at the model's door, on both ways a Bot reaches Gemini: +its own API (`BOT_PROVIDER=google`) and an OpenAI-compatible address. +""" + +import importlib +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from harness_contract import ( + check_handback_signed, + gemini_environment, + gemini_gateway_environment, + handback_bodies, + openai_environment, + tool_calls_sent, +) + +TOKEN = "contract-token" + + +@pytest.fixture +def app_for(monkeypatch): + def app_for(environment): + monkeypatch.delenv("OPENAI_API_BASE", raising=False) + monkeypatch.delenv("ANTHROPIC_AUTH_TOKEN", raising=False) + monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) + for key, value in environment.items(): + monkeypatch.setenv(key, value) + from src import main + + return importlib.reload(main).app + + return app_for + + +@pytest.mark.parametrize("environment", [gemini_environment, gemini_gateway_environment]) +def test_a_handed_back_gemini_call_is_signed(app_for, environment): + check_handback_signed(handback_bodies(app_for, environment, token=TOKEN)) + + +def test_a_handed_back_call_to_another_model_is_sent_as_it_was(app_for): + calls = tool_calls_sent(handback_bodies(app_for, openai_environment, token=TOKEN)[-1]) + assert calls, "the handed-back call never reached the model as a call" + assert not any(call["signature"] for call in calls), calls + diff --git a/agent-crewai/Dockerfile b/agent-crewai/Dockerfile index ed67960f20..279ee62bb0 100644 --- a/agent-crewai/Dockerfile +++ b/agent-crewai/Dockerfile @@ -9,7 +9,7 @@ COPY agent-crewai/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY agent-crewai/src ./src -COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py /shared/ ENV PORT=4202 EXPOSE 4202 diff --git a/agent-crewai/src/main.py b/agent-crewai/src/main.py index 943970295b..2c5e7e8673 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -19,8 +19,12 @@ # The spec file every language in the box reads: one level above this Bot in the repository, and # one level above /app/src in the image the Dockerfile builds. sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) -from model_providers import bot_settings +from model_providers import bot_settings, litellm_model from run_model_key import RunModelKey +import gemini_signatures + +# Every Gemini tool call this Bot sends back is signed. See gemini_signatures.py. +gemini_signatures.install() import ag_ui_crewai.endpoint as crewai_endpoint from ag_ui.core import Message, Tool @@ -44,20 +48,10 @@ def _model() -> str: `BOT_PROVIDER` and `BOT_MODEL` are set by the shell from the model screen. litellm addresses a model as `provider/model`, and it reads that provider's key from the environment itself, which - is why nothing here touches a key. - - The model half is whatever the endpoint publishes, slashes included. litellm takes the first - path component as the provider and sends the rest as the model name, so a name that already - contains a slash still needs the chosen provider in front: `qwen/qwen3-8b` on an - OpenAI-compatible endpoint is `openai/qwen/qwen3-8b`, and `openai/gpt-5.6-terra` is - `openai/openai/gpt-5.6-terra`. Treating a slash as "already a provider" dropped the prefix, - and litellm then either routed to a provider nobody configured (`LLM Provider NOT provided`) - or sent only the second half to the endpoint. + is why nothing here touches a key. See `litellm_model` for the spelling. """ settings = bot_settings("agent-crewai") - provider = settings.provider - model = settings.model - return f"{provider}/{model}" + return litellm_model(settings.provider, settings.model) _PROVIDER_MESSAGE_FIELDS = { diff --git a/agent-crewai/tests/test_gemini_handback.py b/agent-crewai/tests/test_gemini_handback.py new file mode 100644 index 0000000000..dd9a0a5770 --- /dev/null +++ b/agent-crewai/tests/test_gemini_handback.py @@ -0,0 +1,55 @@ +"""A tool call handed back on Gemini reaches it signed; on any other model, as it was. + +See `shared/gemini_signatures.py`. Checked at the model's door, on both ways a Bot reaches Gemini: +its own API (`BOT_PROVIDER=google`) and an OpenAI-compatible address. +""" + +import importlib +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from harness_contract import ( + check_handback_signed, + gemini_environment, + gemini_gateway_environment, + handback_bodies, + openai_environment, + tool_calls_sent, +) + +TOKEN = "contract-token" + + +@pytest.fixture +def app_for(monkeypatch): + def app_for(environment): + monkeypatch.delenv("OPENAI_API_BASE", raising=False) + monkeypatch.delenv("ANTHROPIC_AUTH_TOKEN", raising=False) + monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) + for key, value in environment.items(): + monkeypatch.setenv(key, value) + # `main` wraps `crewai_prepare_inputs` in the library's module when it is imported; restoring + # the library first, then importing `main` anew, is what a fresh process sees. See + # test_conversation_contract.py. + import ag_ui_crewai.endpoint + + importlib.reload(ag_ui_crewai.endpoint) + sys.modules.pop("src.main", None) + return importlib.import_module("src.main").app + + return app_for + + +@pytest.mark.parametrize("environment", [gemini_environment, gemini_gateway_environment]) +def test_a_handed_back_gemini_call_is_signed(app_for, environment): + check_handback_signed(handback_bodies(app_for, environment, token=TOKEN)) + + +def test_a_handed_back_call_to_another_model_is_sent_as_it_was(app_for): + calls = tool_calls_sent(handback_bodies(app_for, openai_environment, token=TOKEN)[-1]) + assert calls, "the handed-back call never reached the model as a call" + assert not any(call["signature"] for call in calls), calls diff --git a/agent-langroid/Dockerfile b/agent-langroid/Dockerfile index c6d82df2bc..515d1a53da 100644 --- a/agent-langroid/Dockerfile +++ b/agent-langroid/Dockerfile @@ -9,7 +9,7 @@ COPY agent-langroid/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY agent-langroid/src ./src -COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py /shared/ ENV PORT=4209 EXPOSE 4209 diff --git a/agent-langroid/src/main.py b/agent-langroid/src/main.py index 3655b6a883..9a48d9f1ee 100644 --- a/agent-langroid/src/main.py +++ b/agent-langroid/src/main.py @@ -8,8 +8,12 @@ # The spec file every language in the box reads: one level above this Bot in the repository, and # one level above /app/src in the image the Dockerfile builds. sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) -from model_providers import bot_settings, openai_api +from model_providers import bot_settings, litellm_model, openai_api from run_model_key import RunModelKey +import gemini_signatures + +# Every Gemini tool call this Bot sends back is signed. See gemini_signatures.py. +gemini_signatures.install() import litellm from ag_ui_langroid import create_langroid_app @@ -56,7 +60,7 @@ def _model_id() -> str: provider = settings.provider model = settings.model if provider != "openai": - return model if "/" in model else f"litellm/{provider}/{model}" + return model if "/" in model else f"litellm/{litellm_model(provider, model)}" if model.startswith("litellm/"): return model if openai_api(model) == "responses": diff --git a/agent-langroid/tests/test_gemini_handback.py b/agent-langroid/tests/test_gemini_handback.py new file mode 100644 index 0000000000..414ee4e012 --- /dev/null +++ b/agent-langroid/tests/test_gemini_handback.py @@ -0,0 +1,66 @@ +"""A tool call handed back on Gemini reaches it signed; on any other model, as it was. + +See `shared/gemini_signatures.py`. Checked at the model's door, on both ways a Bot reaches Gemini: +its own API (`BOT_PROVIDER=google`) and an OpenAI-compatible address. +""" + +import importlib +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from harness_contract import ( + check_handback_signed, + gemini_environment, + gemini_gateway_environment, + handback_bodies, + openai_environment, + tool_calls_sent, +) + +TOKEN = "contract-token" + + + +@pytest.fixture(autouse=True) +def _no_cached_clients(): + """A fresh process has no cached clients either. + + Langroid keeps one OpenAI client per key and settings for the life of the process, and the + address an SDK reads from `OPENAI_BASE_URL` is not part of that key, so a client made for one + test's fake provider would be handed to the next. + """ + from langroid.language_models import client_cache + + client_cache._client_cache.clear() + yield + client_cache._client_cache.clear() + + +@pytest.fixture +def app_for(monkeypatch): + def app_for(environment): + monkeypatch.delenv("OPENAI_API_BASE", raising=False) + monkeypatch.delenv("ANTHROPIC_AUTH_TOKEN", raising=False) + monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) + for key, value in environment.items(): + monkeypatch.setenv(key, value) + from src import main + + return importlib.reload(main).app + + return app_for + + +@pytest.mark.parametrize("environment", [gemini_environment, gemini_gateway_environment]) +def test_a_handed_back_gemini_call_is_signed(app_for, environment): + check_handback_signed(handback_bodies(app_for, environment, token=TOKEN)) + + +def test_a_handed_back_call_to_another_model_is_sent_as_it_was(app_for): + calls = tool_calls_sent(handback_bodies(app_for, openai_environment, token=TOKEN)[-1]) + assert calls, "the handed-back call never reached the model as a call" + assert not any(call["signature"] for call in calls), calls diff --git a/agent-llamaindex/Dockerfile b/agent-llamaindex/Dockerfile index 7e94d0976f..6c3cc23a38 100644 --- a/agent-llamaindex/Dockerfile +++ b/agent-llamaindex/Dockerfile @@ -9,7 +9,7 @@ COPY agent-llamaindex/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY agent-llamaindex/src ./src -COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py /shared/ ENV PORT=4204 EXPOSE 4204 diff --git a/agent-llamaindex/src/main.py b/agent-llamaindex/src/main.py index 8b618f5419..8a4f5144f0 100644 --- a/agent-llamaindex/src/main.py +++ b/agent-llamaindex/src/main.py @@ -12,8 +12,12 @@ # The spec file every language in the box reads: one level above this Bot in the repository, and # one level above /app/src in the image the Dockerfile builds. sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) -from model_providers import bot_settings +from model_providers import bot_settings, litellm_model from run_model_key import RunModelKey +import gemini_signatures + +# Every Gemini tool call this Bot sends back is signed. See gemini_signatures.py. +gemini_signatures.install() import litellm from fastapi import FastAPI, Request @@ -25,20 +29,9 @@ def _model_id() -> str: - """`provider/model`, which is how litellm addresses one. - - The model half is whatever the endpoint publishes, slashes included. litellm takes the first - path component as the provider and sends the rest as the model name, so a name that already - contains a slash still needs the chosen provider in front: `qwen/qwen3-8b` on an - OpenAI-compatible endpoint is `openai/qwen/qwen3-8b`, and `openai/gpt-5.6-terra` is - `openai/openai/gpt-5.6-terra`. Treating a slash as "already a provider" dropped the prefix, - and litellm then either routed to a provider nobody configured (`LLM Provider NOT provided`) - or sent only the second half to the endpoint. - """ + """`provider/model`, which is how LiteLLM addresses one. See `litellm_model`.""" settings = bot_settings("agent-llamaindex") - provider = settings.provider - model = settings.model - return f"{provider}/{model}" + return litellm_model(settings.provider, settings.model) def _llm() -> LiteLLM: diff --git a/agent-llamaindex/tests/test_gemini_handback.py b/agent-llamaindex/tests/test_gemini_handback.py new file mode 100644 index 0000000000..d382180919 --- /dev/null +++ b/agent-llamaindex/tests/test_gemini_handback.py @@ -0,0 +1,58 @@ +"""A tool call handed back on Gemini never reaches it unsigned. + +See `shared/gemini_signatures.py`. Checked at the model's door, on both ways a Bot reaches Gemini: +its own API (`BOT_PROVIDER=google`) and an OpenAI-compatible address. + +LlamaIndex's AG-UI router replays a handed-back call to the model as text, not as a function call, +so today there is no call to sign. The signer is installed all the same, and this holds the line +if the router ever starts sending real calls: whatever call it sends is signed. +""" + +import importlib +import json +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from harness_contract import ( + gemini_environment, + gemini_gateway_environment, + handback_bodies, + openai_environment, + tool_calls_sent, +) + +TOKEN = "contract-token" +PATH = "/run" + + +@pytest.fixture +def app_for(monkeypatch): + def app_for(environment): + monkeypatch.delenv("OPENAI_API_BASE", raising=False) + monkeypatch.delenv("ANTHROPIC_AUTH_TOKEN", raising=False) + monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) + for key, value in environment.items(): + monkeypatch.setenv(key, value) + from src import main + + return importlib.reload(main).app + + return app_for + + +@pytest.mark.parametrize("environment", [gemini_environment, gemini_gateway_environment]) +def test_a_handed_back_gemini_call_is_never_sent_unsigned(app_for, environment): + bodies = handback_bodies(app_for, environment, path=PATH, token=TOKEN) + assert bodies, "the model was never called" + calls = tool_calls_sent(bodies[-1]) + assert all(call["signature"] for call in calls), calls + assert "look_up_order" in json.dumps(bodies[-1]), "the handed-back call was dropped" + + +def test_a_handed_back_call_to_another_model_is_sent_as_it_was(app_for): + calls = tool_calls_sent(handback_bodies(app_for, openai_environment, path=PATH, token=TOKEN)[-1]) + assert not any(call["signature"] for call in calls), calls diff --git a/agent-mastra/Dockerfile b/agent-mastra/Dockerfile index 6acac4a27a..37442c7726 100644 --- a/agent-mastra/Dockerfile +++ b/agent-mastra/Dockerfile @@ -6,6 +6,7 @@ WORKDIR /app COPY agent-mastra/package.json agent-mastra/bun.lock ./ RUN bun install --frozen-lockfile +COPY shared/gemini-signatures.ts /shared/gemini-signatures.ts COPY shared/listen-port.ts /shared/listen-port.ts COPY shared/model-providers.ts /shared/model-providers.ts COPY shared/model-providers.json /shared/model-providers.json diff --git a/agent-mastra/src/mastra/index.test.ts b/agent-mastra/src/mastra/index.test.ts index e7ac469e3f..ec94ab3272 100644 --- a/agent-mastra/src/mastra/index.test.ts +++ b/agent-mastra/src/mastra/index.test.ts @@ -796,3 +796,107 @@ describe("OpenBot Mastra on OpenBot's model gateway", () => { }, 15_000); } }); + +/** + * Gemini 3 and later refuse a function call handed back without the thought signature the model + * gave it, and an AG-UI tool call has no field for one. On a Gemini model at Google's compatible + * endpoint, or OpenBot's gateway in front of it, each handed-back call goes with Google's + * documented placeholder; any other model's request is sent as it was. See + * shared/gemini-signatures.ts. + */ +describe("OpenBot Mastra hands a tool call back to Gemini signed", () => { + for (const [model, signed] of [ + ["gemini-3.8-flash", true], + ["gpt-5.2", false], + ] as const) { + test(`${model}: ${signed ? "the placeholder goes with the call" : "the call is sent as it was"}`, async () => { + const calls: unknown[] = []; + const gateway = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + async fetch(request) { + const body = await request.json(); + for (const message of body.messages ?? []) + for (const call of message.tool_calls ?? []) calls.push(call); + return Response.json({ + id: "chat", + object: "chat.completion", + created: 0, + model: body.model, + choices: [ + { + index: 0, + finish_reason: "stop", + message: { role: "assistant", content: "It shipped." }, + }, + ], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, + }); + }, + }); + const base = `${gateway.url.toString().replace(/\/+$/, "")}/api/model-provider/v1`; + const handedBack = [ + { role: "user", content: "What is the status of order 42?" }, + { + role: "assistant", + content: [ + { + type: "tool-call", + toolCallId: "call_order", + toolName: "look_up_order", + input: { order: "42" }, + }, + ], + }, + { + role: "tool", + content: [ + { + type: "tool-result", + toolCallId: "call_order", + toolName: "look_up_order", + output: { type: "json", value: { status: "shipped" } }, + }, + ], + }, + ]; + try { + const { stdout, stderr, exitCode } = await runProbe( + [ + Bun.argv[0], + "--no-env-file", + "-e", + [ + 'const { mastra } = await import("./agent-mastra/src/mastra/index.ts");', + `const result = await mastra.getAgent("openbot").generate(${JSON.stringify(handedBack)});`, + "console.log(JSON.stringify({ text: result.text }));", + ].join("\n"), + ], + { + PATH: process.env.PATH ?? "/opt/homebrew/bin:/usr/bin:/bin", + MASTRA_TELEMETRY_DISABLED: "true", + DO_NOT_TRACK: "1", + NODE_ENV: "test", + BOT_PROVIDER: "openai", + BOT_MODEL: model, + OPENAI_API_KEY: "deployment-gateway-token", + OPENAI_BASE_URL: base, + ANTHROPIC_API_KEY: "", + ANTHROPIC_BASE_URL: "", + }, + 10_000, + ); + if (exitCode !== 0) + throw new Error(`probe exited ${exitCode}\n${stdout}\n${stderr}`); + expect(stdout).toContain('"text":"It shipped."'); + expect(calls).toHaveLength(1); + expect( + (calls[0] as { extra_content?: { google?: Record } }) + .extra_content?.google?.thought_signature, + ).toBe(signed ? "skip_thought_signature_validator" : undefined); + } finally { + await gateway.stop(true); + } + }, 15_000); + } +}); diff --git a/agent-mastra/src/mastra/index.ts b/agent-mastra/src/mastra/index.ts index 0d6df2d481..ad6ca0212e 100644 --- a/agent-mastra/src/mastra/index.ts +++ b/agent-mastra/src/mastra/index.ts @@ -15,6 +15,7 @@ import { Agent } from "@mastra/core/agent"; import { Mastra } from "@mastra/core/mastra"; import { registerApiRoute } from "@mastra/core/server"; +import { signingFetch } from "../../../shared/gemini-signatures"; import { listenPort } from "../../../shared/listen-port"; import { apiKeyOrPlaceholder, @@ -74,6 +75,9 @@ async function buildModel(runKey?: string) { baseURL?.replace(/\/+$/, "") !== "https://api.openai.com/v1"; const openai = createOpenAI({ baseURL: baseURL || "https://api.openai.com/v1", + // A compatible address may be Gemini's (Google's endpoint, or the gateway in front of it), + // which refuses a handed-back call without its thought signature. + ...(compatible ? { fetch: signingFetch() } : {}), apiKey: key ?? (compatible diff --git a/agent-strands/Dockerfile b/agent-strands/Dockerfile index ab9c308d7d..4a7695fc62 100644 --- a/agent-strands/Dockerfile +++ b/agent-strands/Dockerfile @@ -9,7 +9,7 @@ COPY agent-strands/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY agent-strands/src ./src -COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py /shared/ ENV PORT=4207 EXPOSE 4207 diff --git a/agent-strands/src/main.py b/agent-strands/src/main.py index 2c12411e46..870e595f89 100644 --- a/agent-strands/src/main.py +++ b/agent-strands/src/main.py @@ -9,8 +9,12 @@ # The spec file every language in the box reads: one level above this Bot in the repository, and # one level above /app/src in the image the Dockerfile builds. sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) -from model_providers import bot_settings +from model_providers import bot_settings, litellm_model from run_model_key import RunModelKey +import gemini_signatures + +# Every Gemini tool call this Bot sends back is signed. See gemini_signatures.py. +gemini_signatures.install() from ag_ui_strands import StrandsAgent, add_strands_fastapi_endpoint from fastapi import FastAPI, Request @@ -22,20 +26,9 @@ def _model_id() -> str: - """`provider/model`, which is how litellm addresses one. - - The model half is whatever the endpoint publishes, slashes included. litellm takes the first - path component as the provider and sends the rest as the model name, so a name that already - contains a slash still needs the chosen provider in front: `qwen/qwen3-8b` on an - OpenAI-compatible endpoint is `openai/qwen/qwen3-8b`, and `openai/gpt-5.6-terra` is - `openai/openai/gpt-5.6-terra`. Treating a slash as "already a provider" dropped the prefix, - and litellm then either routed to a provider nobody configured (`LLM Provider NOT provided`) - or sent only the second half to the endpoint. - """ + """`provider/model`, which is how LiteLLM addresses one. See `litellm_model`.""" settings = bot_settings("agent-strands") - provider = settings.provider - model = settings.model - return f"{provider}/{model}" + return litellm_model(settings.provider, settings.model) app = FastAPI() diff --git a/agent-strands/tests/test_gemini_handback.py b/agent-strands/tests/test_gemini_handback.py new file mode 100644 index 0000000000..e4c2e933e6 --- /dev/null +++ b/agent-strands/tests/test_gemini_handback.py @@ -0,0 +1,49 @@ +"""A tool call handed back on Gemini reaches it signed; on any other model, as it was. + +See `shared/gemini_signatures.py`. Checked at the model's door, on both ways a Bot reaches Gemini: +its own API (`BOT_PROVIDER=google`) and an OpenAI-compatible address. +""" + +import importlib +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from harness_contract import ( + check_handback_signed, + gemini_environment, + gemini_gateway_environment, + handback_bodies, + openai_environment, + tool_calls_sent, +) + +TOKEN = "contract-token" + + +@pytest.fixture +def app_for(monkeypatch): + def app_for(environment): + monkeypatch.delenv("OPENAI_API_BASE", raising=False) + monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) + for key, value in environment.items(): + monkeypatch.setenv(key, value) + from src import main + + return importlib.reload(main).app + + return app_for + + +@pytest.mark.parametrize("environment", [gemini_environment, gemini_gateway_environment]) +def test_a_handed_back_gemini_call_is_signed(app_for, environment): + check_handback_signed(handback_bodies(app_for, environment, token=TOKEN)) + + +def test_a_handed_back_call_to_another_model_is_sent_as_it_was(app_for): + calls = tool_calls_sent(handback_bodies(app_for, openai_environment, token=TOKEN)[-1]) + assert calls, "the handed-back call never reached the model as a call" + assert not any(call["signature"] for call in calls), calls diff --git a/docs/releasing.md b/docs/releasing.md index 493f5bf6f8..edafd0bde3 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1172,7 +1172,10 @@ from the Actions tab. One job per harness in `.github/published-images.json` run [The model list](configuration.md#the-model-list)); - starts the harness image on each provider the way the Desktop configures it, and sends one AG-UI run per model, so the harness's own client makes the call. It checks `latest`, the published - image people run, and `source`, the image built from this commit; + image people run, and `source`, the image built from this commit. The run hands back a tool call + the model made earlier, with its result and nothing the provider gave the call (Gemini's thought + signature), as the server does after running a tool between two runs, so a model a Bot cannot + finish a tool call on fails here; - compares the LangGraph harness's Codex client version with the minimum each ChatGPT plan model needs, from openai/codex's published model catalogue. A plan sign-in cannot run in CI. A Claude plan runs through the same Claude Code CLI as an Anthropic key, so the key's rows cover it. diff --git a/scripts/model-compat.test.ts b/scripts/model-compat.test.ts index 60f36982c2..1ce083c51a 100644 --- a/scripts/model-compat.test.ts +++ b/scripts/model-compat.test.ts @@ -6,6 +6,7 @@ import { classifyMastra, classifyRun, codexGate, + handBackRun, type Harness, type MatrixRow, NOT_CHECKED, @@ -407,3 +408,56 @@ test("every published harness is one the matrix can run", () => { expect(providersFor(harness!).length, image).toBeGreaterThan(0); } }); + +// FOUND ON THE REAL GEMINI API: the lock verified gemini-3.8-flash and gemini-4-hydrogen on a run +// with only a prompt, while every Bot that handed a tool call back to them was refused ("Function +// call is missing a thought_signature"). The probe's run is that hand-back. +test("the probe hands back an unsigned tool call and its result, as the server sends it", () => { + const run = handBackRun("abc", "gemini-4-hydrogen", false) as { + messages: { + role: string; + toolCalls?: Record[]; + toolCallId?: string; + }[]; + tools: { name: string }[]; + forwardedProps: unknown; + }; + expect(run.messages.map((message) => message.role)).toEqual([ + "user", + "assistant", + "tool", + ]); + const [call] = run.messages[1]!.toolCalls!; + expect(call).toEqual({ + id: "call_abc", + type: "function", + function: { name: "look_up_order", arguments: '{"order": "42"}' }, + }); + expect(run.messages[2]!.toolCallId).toBe("call_abc"); + expect(run.tools.map((tool) => tool.name)).toEqual(["look_up_order"]); + expect(run.forwardedProps).toEqual({ + openbotModel: { model: "gemini-4-hydrogen" }, + }); + + const mastra = handBackRun("abc", "gemini-4-hydrogen", true) as { + messages: { role: string; content: unknown }[]; + }; + expect(mastra.messages.map((message) => message.role)).toEqual([ + "user", + "assistant", + "tool", + ]); + expect(JSON.stringify(mastra)).not.toContain("signature"); +}); + +test("a model that calls the handed-back tool again has not replied", () => { + const again = [ + 'data: {"type":"RUN_STARTED","threadId":"t","runId":"r"}', + 'data: {"type":"TOOL_CALL_START","toolCallId":"c2","toolCallName":"look_up_order"}', + 'data: {"type":"RUN_FINISHED","threadId":"t","runId":"r"}', + ].join("\n\n"); + expect(classifyRun({ status: 200, body: again })).toEqual({ + status: "fail", + detail: "the model called the probe's tool again instead of replying", + }); +}); diff --git a/scripts/model-compat.ts b/scripts/model-compat.ts index a2c5f32cb0..1a79999aa1 100644 --- a/scripts/model-compat.ts +++ b/scripts/model-compat.ts @@ -13,7 +13,10 @@ * (docs/configuration.md, "The model list"). * 2. Starts each harness image on that provider, as the Desktop's settings would, and sends it * one AG-UI run per model. The harness's own client makes the call, at the version that image - * ships. `latest` is the published image people run (ghcr.io/copilotkit/openbot-); + * ships. The run is the one every Bot's tool path ends in: it hands back a tool call the + * model made in an earlier run, with its result and without the provider's own artefacts on + * it (Gemini's thought signature, which an AG-UI tool call has no field for), as the server + * sends it after running the tool between two runs (`handBackRun`). `latest` is the published image people run (ghcr.io/copilotkit/openbot-); * `source` is the image built from this checkout, which shows whether a bumped pin fixed it. * 3. Checks the ChatGPT plan's Codex client version in each image against the minimum each * listed Codex model needs, from openai/codex's published model catalogue. A plan sign-in @@ -62,8 +65,9 @@ const SOURCE = "source"; const MODELS_DEV = "https://models.dev/api.json"; const CODEX_CATALOGUE = "https://raw.githubusercontent.com/openai/codex/main/codex-rs/models-manager/models.json"; -const PROMPT = "Reply with the single word OK."; -/** One tool the prompt has no use for, so the request takes the client's tool path. */ +const PROMPT = + "Look up order 42. Once you have its status, reply with the single word OK."; +/** The tool the handed-back call was made to, offered again so the request takes the tool path. */ const PROBE_TOOL = { name: "look_up_order", description: "Look up the status of an order by its number.", @@ -509,7 +513,7 @@ export function classifyRun(response: { return judgeReply( streamed || snapshot, calledTool - ? "the model called the probe's tool instead of replying" + ? "the model called the probe's tool again instead of replying" : finished ? "the run finished without a reply" : "the stream ended without finishing the run", @@ -973,6 +977,88 @@ async function clientsIn(image: string): Promise> { let serial = 0; /** Starts the harness on one provider and model, sends one run, and stops it. */ +/** The order status the handed-back call answers with. */ +const PROBE_RESULT = '{"order": "42", "status": "shipped"}'; + +/** + * The run sent to a harness for one model: a tool call the model made in the previous run, then + * its result, as the server sends a Bot's thread after running the tool between two runs. The call + * carries nothing the provider gave it: an AG-UI tool call has no field for Gemini's thought + * signature, which Gemini 3 and later refuse a call in the current turn without ("Function call is + * missing a thought_signature"). A model that answers only a fresh prompt, and not this, cannot + * finish any tool call a Bot makes. + * + * Mastra is reached through its own agent API, in the AI SDK's message shape. + */ +export function handBackRun( + id: string, + model: string, + mastra: boolean, +): Record { + const call = `call_${id}`; + if (mastra) + return { + messages: [ + { role: "user", content: PROMPT }, + { + role: "assistant", + content: [ + { + type: "tool-call", + toolCallId: call, + toolName: PROBE_TOOL.name, + input: { order: "42" }, + }, + ], + }, + { + role: "tool", + content: [ + { + type: "tool-result", + toolCallId: call, + toolName: PROBE_TOOL.name, + output: { type: "json", value: JSON.parse(PROBE_RESULT) }, + }, + ], + }, + ], + }; + return { + threadId: `model-compat-${id}`, + runId: `run-${id}`, + state: {}, + messages: [ + { id: `message-${id}`, role: "user", content: PROMPT }, + { + id: `call-${id}`, + role: "assistant", + content: "", + toolCalls: [ + { + id: call, + type: "function", + function: { name: PROBE_TOOL.name, arguments: '{"order": "42"}' }, + }, + ], + }, + { + id: `result-${id}`, + role: "tool", + toolCallId: call, + content: PROBE_RESULT, + }, + ], + // A Bot's run always carries tools, and a client's tool path is where models part ways + // (Responses-only models, parallel tool calls, signed calls), so this one does too. + tools: [PROBE_TOOL], + context: [], + // What the server tells the LangGraph and Claude Agent SDK harnesses; the others read + // BOT_MODEL, set by the caller. + forwardedProps: { openbotModel: { model } }, + }; +} + async function runOne( row: Extract, key: string, @@ -1062,25 +1148,7 @@ async function runOne( accept: mastra ? "application/json" : "text/event-stream", "x-openbot-agent-token": token, }, - body: JSON.stringify( - mastra - ? { messages: [{ role: "user", content: PROMPT }] } - : { - threadId: `model-compat-${id}`, - runId: `run-${id}`, - state: {}, - messages: [ - { id: `message-${id}`, role: "user", content: PROMPT }, - ], - // A Bot's run always carries tools, and a client's tool path is where models - // part ways (Responses-only models, parallel tool calls), so this one does too. - tools: [PROBE_TOOL], - context: [], - // What the server tells the LangGraph and Claude Agent SDK harnesses; the others - // read BOT_MODEL, set above. - forwardedProps: { openbotModel: { model: row.model } }, - }, - ), + body: JSON.stringify(handBackRun(id, row.model, mastra)), signal: AbortSignal.timeout(RUN_TIMEOUT_MS), }, ); diff --git a/shared/gemini-signatures.test.ts b/shared/gemini-signatures.test.ts new file mode 100644 index 0000000000..ab3cdec40f --- /dev/null +++ b/shared/gemini-signatures.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, test } from "bun:test"; +import { + GEMINI_UNSIGNED_CALL, + isGeminiModel, + signedBody, + signingFetch, +} from "./gemini-signatures"; + +const COMPAT = + "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"; + +const chat = (model = "gemini-3.8-flash", extra?: unknown) => + JSON.stringify({ + model, + messages: [ + { role: "user", content: "hi" }, + { + role: "assistant", + content: null, + tool_calls: [ + { + id: "c1", + type: "function", + function: { name: "f", arguments: "{}" }, + ...(extra ? { extra_content: extra } : {}), + }, + ], + }, + { role: "tool", tool_call_id: "c1", content: "{}" }, + ], + }); + +const contents = (signature?: string) => + JSON.stringify({ + contents: [ + { role: "user", parts: [{ text: "hi" }] }, + { + role: "model", + parts: [ + { + functionCall: { name: "f", args: {} }, + ...(signature ? { thoughtSignature: signature } : {}), + }, + { functionCall: { name: "g", args: {} } }, + ], + }, + ], + }); + +const chatSignatures = (body: string | undefined) => + JSON.parse(body ?? "{}").messages.flatMap( + (m: { + tool_calls?: { + extra_content?: { google?: { thought_signature?: string } }; + }[]; + }) => + (m.tool_calls ?? []).map( + (c) => c.extra_content?.google?.thought_signature, + ), + ); + +describe("which requests a handed-back Gemini call is signed in", () => { + test("Gemini models, by name", () => { + for (const model of [ + "gemini-4-hydrogen", + "models/gemini-4-neon", + "google/gemini-4-carbon", + ]) + expect(isGeminiModel(model)).toBe(true); + for (const model of [ + "gpt-5.5", + "claude-sonnet-5-5", + "gemma-4-31b-it", + "", + undefined, + ]) + expect(isGeminiModel(model)).toBe(false); + }); + + test("Gemini's own API, on any host, keeping a signature already there", () => { + for (const base of [ + "https://generativelanguage.googleapis.com/v1beta", + "http://127.0.0.1:9/v1beta", + ]) { + const body = signedBody( + "POST", + `${base}/models/gemini-4-hydrogen:streamGenerateContent?alt=sse`, + contents("real"), + ); + const parts = JSON.parse(body ?? "{}").contents[1].parts; + expect( + parts.map((p: { thoughtSignature?: string }) => p.thoughtSignature), + ).toEqual(["real", GEMINI_UNSIGNED_CALL]); + } + expect( + signedBody( + "POST", + "http://x/v1beta/models/gemma-4-31b-it:generateContent", + contents(), + ), + ).toBeUndefined(); + }); + + test("Google's compatible endpoint and OpenBot's gateway, for a Gemini model only", () => { + expect(chatSignatures(signedBody("POST", COMPAT, chat()))).toEqual([ + GEMINI_UNSIGNED_CALL, + ]); + const gateway = + "http://openbot:3010/api/model-provider/v1/chat/completions"; + expect(chatSignatures(signedBody("POST", gateway, chat()))).toEqual([ + GEMINI_UNSIGNED_CALL, + ]); + expect(signedBody("POST", gateway, chat("gpt-5.5"))).toBeUndefined(); + expect( + signedBody( + "POST", + COMPAT, + chat("gemini-3.8-flash", { google: { thought_signature: "real" } }), + ), + ).toBeUndefined(); + }); + + test("never another provider, even for a Gemini name", () => { + for (const url of [ + "https://api.openai.com/v1/chat/completions", + "https://openrouter.ai/api/v1/chat/completions", + ]) + expect(signedBody("POST", url, chat())).toBeUndefined(); + expect(signedBody("GET", COMPAT, chat())).toBeUndefined(); + expect(signedBody("POST", COMPAT, "not json")).toBeUndefined(); + }); + + test("the wrapped fetch sends the signed body, a Request included", async () => { + const sent: string[] = []; + const inner = (async ( + input: string | URL | Request, + init?: RequestInit, + ) => { + sent.push( + input instanceof Request ? await input.text() : String(init?.body), + ); + return new Response("{}"); + }) as typeof fetch; + const signed = signingFetch(inner); + await signed(COMPAT, { method: "POST", body: chat() }); + await signed(new Request(COMPAT, { method: "POST", body: chat() })); + await signed("https://api.openai.com/v1/chat/completions", { + method: "POST", + body: chat(), + }); + expect(sent.map(chatSignatures)).toEqual([ + [GEMINI_UNSIGNED_CALL], + [GEMINI_UNSIGNED_CALL], + [undefined], + ]); + }); +}); diff --git a/shared/gemini-signatures.ts b/shared/gemini-signatures.ts new file mode 100644 index 0000000000..d57e99ebf0 --- /dev/null +++ b/shared/gemini-signatures.ts @@ -0,0 +1,145 @@ +/** + * A handed-back tool call signed for Gemini, for the TypeScript engines. The rules are those of + * `shared/gemini_signatures.py`, which every Python engine uses. + * + * Gemini 3 and later refuse a function call in the current turn that does not carry the thought + * signature the model gave it: "Function call is missing a thought_signature in functionCall + * parts". OpenBot runs each tool between two runs, and an AG-UI tool call has no field for a + * signature, so a call can come back without its own. Google documents a value for a history whose + * signatures are not available, `skip_thought_signature_validator`. + * + * `signingFetch` wraps the `fetch` a model client is given, and rewrites a request body only when + * it is a Gemini request: + * - Gemini's own API: a POST to `.../models/gemini-...:generateContent` or + * `:streamGenerateContent`, whatever the host. Each `functionCall` part with no + * `thoughtSignature` is given the placeholder. + * - Google's OpenAI-compatible endpoint (`generativelanguage.googleapis.com/.../openai/`), or + * OpenBot's model gateway asked for a Gemini model: each assistant `tool_calls` entry with no + * `extra_content.google.thought_signature` is given the placeholder there. + * A signature already there is kept, and every other request is sent exactly as it was built. + */ + +/** Google's documented stand-in for a signature that is not available. */ +export const GEMINI_UNSIGNED_CALL = "skip_thought_signature_validator"; + +const GOOGLE_HOST = "generativelanguage.googleapis.com"; +const GATEWAY_PATH = "/api/model-provider/"; +const NATIVE_PATH = /\/models\/([^/:]+):(?:stream)?[gG]enerateContent$/; + +type Json = Record; +const isObject = (value: unknown): value is Json => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** Whether a model name names a Gemini model; a gateway's `google/gemini-...` counts. */ +export function isGeminiModel(model: unknown): boolean { + return ( + typeof model === "string" && + (model.trim().toLowerCase().split("/").at(-1) ?? "").startsWith("gemini-") + ); +} + +/** Every unsigned `functionCall` part in a generateContent body, signed. Whether any was. */ +export function signContents(body: unknown): boolean { + if (!isObject(body) || !Array.isArray(body.contents)) return false; + let signed = false; + for (const content of body.contents) { + if (!isObject(content) || !Array.isArray(content.parts)) continue; + for (const part of content.parts) { + if ( + !isObject(part) || + !("functionCall" in part || "function_call" in part) + ) + continue; + if (part.thoughtSignature || part.thought_signature) continue; + part.thoughtSignature = GEMINI_UNSIGNED_CALL; + signed = true; + } + } + return signed; +} + +/** Every unsigned assistant tool call in a Chat Completions body, signed. Whether any was. */ +export function signMessages(body: unknown): boolean { + if (!isObject(body) || !Array.isArray(body.messages)) return false; + let signed = false; + for (const message of body.messages) { + if (!isObject(message) || message.role !== "assistant") continue; + const calls = Array.isArray(message.tool_calls) ? message.tool_calls : []; + for (const call of calls) { + if (!isObject(call)) continue; + const extra = isObject(call.extra_content) ? call.extra_content : {}; + const google = isObject(extra.google) ? extra.google : {}; + if (google.thought_signature) continue; + call.extra_content = { + ...extra, + google: { ...google, thought_signature: GEMINI_UNSIGNED_CALL }, + }; + signed = true; + } + } + return signed; +} + +/** The request body with its Gemini tool calls signed, or undefined to send it as it was. */ +export function signedBody( + method: string, + url: string, + body: string | undefined, +): string | undefined { + if (!body || method.toUpperCase() !== "POST") return undefined; + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return undefined; + } + const native = NATIVE_PATH.exec(parsed.pathname); + const chat = parsed.pathname.endsWith("/chat/completions"); + if (native ? !isGeminiModel(native[1]) : !chat) return undefined; + let json: unknown; + try { + json = JSON.parse(body); + } catch { + return undefined; + } + if (!native) { + if (!isObject(json) || !isGeminiModel(json.model)) return undefined; + if ( + parsed.hostname.toLowerCase() !== GOOGLE_HOST && + !parsed.pathname.includes(GATEWAY_PATH) + ) + return undefined; + } + const changed = native ? signContents(json) : signMessages(json); + return changed ? JSON.stringify(json) : undefined; +} + +/** `inner`, with every Gemini request's tool calls signed on the way out. */ +export function signingFetch(inner: typeof fetch = fetch): typeof fetch { + const signed = async ( + input: string | URL | Request, + init?: RequestInit, + ): Promise => { + if (input instanceof Request) { + if (init?.body === undefined && input.body) { + const body = signedBody( + input.method, + input.url, + await input.clone().text(), + ); + if (body !== undefined) + return inner(new Request(input, { ...init, body })); + } + return inner(input, init); + } + const body = + typeof init?.body === "string" + ? signedBody(init.method ?? "GET", String(input), init.body) + : undefined; + if (body === undefined) return inner(input, init); + const headers = new Headers(init?.headers); + headers.delete("content-length"); + return inner(input, { ...init, headers, body }); + }; + return signed as typeof fetch; +} diff --git a/shared/gemini_signatures.py b/shared/gemini_signatures.py new file mode 100644 index 0000000000..c043717f0c --- /dev/null +++ b/shared/gemini_signatures.py @@ -0,0 +1,221 @@ +"""A handed-back tool call signed for Gemini, for every Python harness OpenBot runs. + +Gemini 3 and later refuse a function call in the current turn that does not carry the thought +signature the model gave it: "Function call is missing a thought_signature in functionCall parts". +OpenBot runs each tool between two runs, and an AG-UI tool call has no field for a signature, so a +call always comes back to the harness without its own. Holding the real one between runs would +mean holding it on whichever replica answered the first. Google documents a value for a history +whose signatures are not available, `skip_thought_signature_validator`, and this module puts it on +every call that has none. + +THE FRAMEWORKS BUILD THE REQUEST, each its own way (LiteLLM, google-genai, the OpenAI SDK under +AG2 or LangChain). So the signature goes in where every one of them ends up, as `run_model_key.py` +puts a run's key in: the HTTP request. `install()` wraps `httpx` and `httpx2` sends and `aiohttp` +requests (google-genai sends through `aiohttp` when it is installed), and rewrites a request body +only when it is a Gemini request: + +- Gemini's own API: a POST to `.../models/gemini-...:generateContent` or `:streamGenerateContent`, + whatever the host (a base url may name a gateway or a mock in front of Gemini). Each + `functionCall` part in `contents` with no `thoughtSignature` is given the placeholder. +- Google's OpenAI-compatible endpoint (`generativelanguage.googleapis.com/.../openai/`), or + OpenBot's model gateway asked for a Gemini model: each assistant `tool_calls` entry in + `messages` with no `extra_content.google.thought_signature` is given the placeholder there. + +A signature the request already carries is kept: a framework that held the real one (inside one +run's tool loop, or brought back by the server) sends it as it was. Every other request, to any +other provider or for any other model, is sent byte for byte as it was built. +""" + +from __future__ import annotations + +import json +import re +from typing import Any +from urllib.parse import urlsplit + +#: Google's documented stand-in for a signature that is not available. +GEMINI_UNSIGNED_CALL = "skip_thought_signature_validator" + +GOOGLE_HOST = "generativelanguage.googleapis.com" +GATEWAY_PATH = "/api/model-provider/" + +_NATIVE_PATH = re.compile(r"/models/([^/:]+):(?:stream)?[gG]enerateContent$") + + +def is_gemini_model(model: Any) -> bool: + """Whether a model name names a Gemini model: `gemini-4-hydrogen`, `models/gemini-3.8-flash`. + + A gateway's namespaced name (`google/gemini-3.8-flash`, `gemini/gemini-3.8-flash`) is the + model it names. + """ + if not isinstance(model, str): + return False + return model.strip().lower().rsplit("/", 1)[-1].startswith("gemini-") + + +def sign_contents(body: Any) -> bool: + """Every unsigned `functionCall` part in a generateContent body, signed. Whether any was.""" + if not isinstance(body, dict) or not isinstance(body.get("contents"), list): + return False + signed = False + for content in body["contents"]: + if not isinstance(content, dict) or not isinstance(content.get("parts"), list): + continue + for part in content["parts"]: + if not isinstance(part, dict): + continue + if "functionCall" not in part and "function_call" not in part: + continue + if part.get("thoughtSignature") or part.get("thought_signature"): + continue + part["thoughtSignature"] = GEMINI_UNSIGNED_CALL + signed = True + return signed + + +def sign_messages(body: Any) -> bool: + """Every unsigned assistant tool call in a Chat Completions body, signed. Whether any was.""" + if not isinstance(body, dict) or not isinstance(body.get("messages"), list): + return False + signed = False + for message in body["messages"]: + if not isinstance(message, dict) or message.get("role") != "assistant": + continue + for call in message.get("tool_calls") or []: + if not isinstance(call, dict): + continue + extra = call.get("extra_content") + extra = extra if isinstance(extra, dict) else {} + google = extra.get("google") + google = google if isinstance(google, dict) else {} + if google.get("thought_signature"): + continue + call["extra_content"] = { + **extra, + "google": {**google, "thought_signature": GEMINI_UNSIGNED_CALL}, + } + signed = True + return signed + + +def signed_body(method: str, url: str, content: bytes | None) -> bytes | None: + """The request body with its Gemini tool calls signed, or None to send it as it was.""" + if not content or (method or "").upper() != "POST": + return None + parts = urlsplit(url) + path = parts.path or "" + native = _NATIVE_PATH.search(path) + chat = path.endswith("/chat/completions") + if native: + if not is_gemini_model(native.group(1)): + return None + elif not chat: + return None + try: + body = json.loads(content) + except (ValueError, UnicodeDecodeError): + return None + if native: + changed = sign_contents(body) + else: + host = (parts.hostname or "").lower() + if not is_gemini_model(body.get("model") if isinstance(body, dict) else None): + return None + if host != GOOGLE_HOST and GATEWAY_PATH not in path: + return None + changed = sign_messages(body) + if not changed: + return None + return json.dumps(body).encode("utf-8") + + +_installed = False + + +def install() -> None: + """Every Gemini request this process sends carries a signature on each tool call. Idempotent.""" + global _installed + if _installed: + return + import importlib + + for name in ("httpx", "httpx2"): + try: + module = importlib.import_module(name) + except ImportError: + continue + _patch_httpx(module) + try: + import aiohttp + except ImportError: + pass + else: + _patch_aiohttp(aiohttp.ClientSession) + _installed = True + + +def _resigned(module, request): + """An httpx request with its Gemini tool calls signed, or the request itself.""" + try: + content = request.content + except Exception: # a streaming body: not one a framework builds for a model call + return request + body = signed_body(request.method, str(request.url), content) + if body is None: + return request + headers = [ + (key, value) + for key, value in request.headers.multi_items() + if key.lower() not in ("content-length", "transfer-encoding") + ] + return module.Request( + request.method, + request.url, + headers=headers, + content=body, + extensions=request.extensions, + ) + + +def _patch_httpx(module) -> None: + client, async_client = module.Client, module.AsyncClient + sync_send = client.send + async_send = async_client.send + + def send(self, request, *args, **kwargs): + return sync_send(self, _resigned(module, request), *args, **kwargs) + + async def asend(self, request, *args, **kwargs): + return await async_send(self, _resigned(module, request), *args, **kwargs) + + client.send = send + async_client.send = asend + + +def _patch_aiohttp(session_class) -> None: + request = session_class._request + + async def _request(self, method, str_or_url, *args, **kwargs): + data = kwargs.get("data") + if isinstance(data, str): + data = data.encode("utf-8") + if isinstance(data, (bytes, bytearray)): + body = signed_body(method, str(str_or_url), bytes(data)) + if body is not None: + kwargs["data"] = body + elif kwargs.get("json") is not None: + body = signed_body(method, str(str_or_url), json.dumps(kwargs["json"]).encode("utf-8")) + if body is not None: + kwargs["json"] = json.loads(body) + else: + body = None + if body is not None and isinstance(kwargs.get("headers"), dict): + # The body grew: a length the caller worked out is no longer its length. + kwargs["headers"] = { + key: value + for key, value in kwargs["headers"].items() + if key.lower() != "content-length" + } + return await request(self, method, str_or_url, *args, **kwargs) + + session_class._request = _request diff --git a/shared/harness_contract.py b/shared/harness_contract.py index d000fe0107..808bf96241 100644 --- a/shared/harness_contract.py +++ b/shared/harness_contract.py @@ -84,6 +84,126 @@ def missing_from(body: dict) -> list[str]: return [name for name, marker in MARKERS.items() if marker not in text] +# A tool call the model made in the previous run, which the server ran between the two runs and +# now hands back with its result. AG-UI's tool call has no field for Gemini's thought signature, so +# it arrives unsigned, and Gemini 3 and later refuse an unsigned call in the current turn. See +# `shared/gemini_signatures.py`. +HANDED_BACK_TOOL = { + "name": "look_up_order", + "description": "Look up the status of an order by its number.", + "parameters": { + "type": "object", + "properties": {"order": {"type": "string", "description": "The order number."}}, + "required": ["order"], + }, +} +GEMINI_MODEL = "gemini-3.8-flash" + + +def handback(thread_id: str = "handback-thread", run_id: str = "handback-run") -> dict: + """A run carrying a tool call made in the previous run and its result, as the server sends it.""" + return { + "threadId": thread_id, + "runId": run_id, + "state": {}, + "messages": [ + {"id": "u1", "role": "user", "content": "What is the status of order 42?"}, + { + "id": "a1", + "role": "assistant", + "content": "", + "toolCalls": [ + { + "id": "call_handback", + "type": "function", + "function": {"name": "look_up_order", "arguments": '{"order": "42"}'}, + } + ], + }, + { + "id": "t1", + "role": "tool", + "toolCallId": "call_handback", + "content": '{"status": "shipped"}', + }, + ], + "tools": [HANDED_BACK_TOOL], + "context": [], + "forwardedProps": {}, + } + + +def tool_calls_sent(body: dict) -> list[dict]: + """Every tool call in a model request: Chat Completions `tool_calls` and Gemini `functionCall` + parts, each as `{"name": ..., "signature": ...}` with the thought signature it carries, if any. + """ + calls = [] + for message in body.get("messages") or []: + for call in (message.get("tool_calls") or []) if isinstance(message, dict) else []: + google = ((call.get("extra_content") or {}).get("google") or {}) + calls.append( + { + "name": (call.get("function") or {}).get("name"), + "signature": google.get("thought_signature"), + } + ) + for content in body.get("contents") or []: + for part in content.get("parts") or [] if isinstance(content, dict) else []: + call = part.get("functionCall") or part.get("function_call") + if call: + calls.append( + { + "name": call.get("name"), + "signature": part.get("thoughtSignature") or part.get("thought_signature"), + } + ) + return calls + + +def check_handback_signed(bodies: list[dict]) -> None: + """The model was sent the handed-back call as a call, and the call carries a signature.""" + assert bodies, "the model was never called" + calls = [call for call in tool_calls_sent(bodies[-1]) if call["name"] == "look_up_order"] + assert calls, f"the handed-back call never reached the model as a call: {bodies[-1]}" + assert all(call["signature"] for call in calls), f"an unsigned call reached Gemini: {calls}" + + +def gemini_environment(base: str, model: str = GEMINI_MODEL) -> dict[str, str]: + """Gemini's own API at `base`, the way `BOT_PROVIDER=google` configures one. + + `GOOGLE_GENERATIVE_AI_BASE_URL` is the `google` row's variable; `GEMINI_API_BASE` and + `GOOGLE_GEMINI_BASE_URL` are LiteLLM's and google-genai's own names for the same address, set + here so whichever client a framework builds is pointed at the fake. + """ + return { + "BOT_PROVIDER": "google", + "BOT_MODEL": model, + "GOOGLE_API_KEY": "contract-key", + "GOOGLE_GENERATIVE_AI_BASE_URL": base, + "GEMINI_API_BASE": base, + "GOOGLE_GEMINI_BASE_URL": base, + "OPENAI_API_KEY": "", + "OPENAI_BASE_URL": "", + "ANTHROPIC_API_KEY": "", + } + + +def gemini_gateway_environment(base: str, model: str = GEMINI_MODEL) -> dict[str, str]: + """A Gemini model on an OpenAI-compatible address: OpenBot's model gateway at `base`. + + Google's own compatible endpoint is signed by its host, which a test cannot serve; the gateway's + path is signed by the same rule for a Gemini model. + """ + return { + "BOT_PROVIDER": "", + "BOT_MODEL": model, + "OPENAI_API_KEY": "contract-key", + "OPENAI_BASE_URL": f"{base}/api/model-provider/v1", + "ANTHROPIC_API_KEY": "", + "GOOGLE_API_KEY": "", + } + + def openai_environment(base: str, model: str = "contract-model") -> dict[str, str]: """An OpenAI-compatible endpoint at `base`, the way the setup screen configures one.""" return { @@ -191,12 +311,32 @@ def check_gateway_keys(app_for, wire: str, *, path: str = "/", token: str = "con check_run_keys(keys[started:], ran_with_token, bodies) +def handback_bodies(app_for, environment, *, path: str = "/", token: str = "contract-token"): + """The model requests a harness sends for `handback()`, on a fresh app in `environment`. + + `app_for(environment)` sets `environment` (a dict) for the harness and answers its app on a + fresh import, as for `check_gateway_keys`. `environment(base)` is an environment function such + as `gemini_environment`. + """ + from fastapi.testclient import TestClient + + with fake_provider() as (base, bodies): + with TestClient(app_for(environment(base))) as client: + response = client.post(path, json=handback(), headers={"x-openbot-agent-token": token}) + assert response.status_code == 200, response.text + types = [e["type"] for e in run_events(response.text) if e["type"].startswith("RUN_")] + assert types == ["RUN_STARTED", "RUN_FINISHED"], response.text + return bodies + + @contextmanager def fake_provider(keys: list[str] | None = None) -> Iterator[tuple[str, list[dict]]]: - """An OpenAI- and Anthropic-compatible model on localhost that answers "ok" and records bodies. + """An OpenAI-, Anthropic- and Gemini-compatible model on localhost that answers "ok" and records + bodies. Yields `(base_url, bodies)`: every request body in arrival order. Serves Chat Completions, - Responses and Messages, streamed and not, since which one a framework uses is its own choice. + Responses, Messages and Gemini's generateContent, streamed and not, since which one a framework + uses is its own choice. Given `keys`, also writes down the key each request presented, as OpenAI's SDK sends it (`Authorization: Bearer`) or Anthropic's (`x-api-key`). """ @@ -332,6 +472,30 @@ async def messages(request: Request): ] return sse([f"event: {name}\ndata: {json.dumps(data)}\n\n" for name, data in events]) + @app.post("/{rest:path}") + async def gemini(rest: str, request: Request): + """Gemini's own API: `.../models/:generateContent`, or `:streamGenerateContent`.""" + if not rest.endswith((":generateContent", ":streamGenerateContent")): + return JSONResponse({"error": {"code": 404, "message": rest}}, status_code=404) + body = await request.json() + bodies.append(body) + answer = { + "candidates": [ + { + "content": {"role": "model", "parts": [{"text": "ok"}]}, + "finishReason": "STOP", + "index": 0, + } + ], + "usageMetadata": {"promptTokenCount": 1, "candidatesTokenCount": 1, "totalTokenCount": 2}, + "modelVersion": rest.rsplit("/", 1)[-1].split(":", 1)[0], + } + if rest.endswith(":generateContent"): + return JSONResponse(answer) + if request.query_params.get("alt") == "sse": + return sse([f"data: {json.dumps(answer)}\r\n\r\n"]) + return JSONResponse([answer]) + with socket.socket() as probe: probe.bind(("127.0.0.1", 0)) port = probe.getsockname()[1] diff --git a/shared/model_providers.py b/shared/model_providers.py index 7137da3e00..7c21dd57c5 100644 --- a/shared/model_providers.py +++ b/shared/model_providers.py @@ -210,3 +210,23 @@ def openai_api(model: str, env: Mapping[str, str] | None = None) -> str: if chosen in ("responses", "chat"): return chosen return "responses" if requires_responses_api(model) else "chat" + + +# LiteLLM's names for the providers it spells differently. LiteLLM reads Gemini's API as `gemini/` +# (its `google/` is no provider at all: "LLM Provider NOT provided"), and finds the key under +# `GOOGLE_API_KEY`, the variable the `google` row names. +_LITELLM_PROVIDERS: dict[str, str] = {"google": "gemini"} + + +def litellm_model(provider: str, model: str) -> str: + """`provider/model`, which is how LiteLLM addresses one, in LiteLLM's spelling of the provider. + + The model half is whatever the endpoint publishes, slashes included. LiteLLM takes the first + path component as the provider and sends the rest as the model name, so a name that already + contains a slash still needs the chosen provider in front: `qwen/qwen3-8b` on an + OpenAI-compatible endpoint is `openai/qwen/qwen3-8b`, and `openai/gpt-5.6-terra` is + `openai/openai/gpt-5.6-terra`. Treating a slash as "already a provider" dropped the prefix, + and LiteLLM then either routed to a provider nobody configured or sent only the second half to + the endpoint. + """ + return f"{_LITELLM_PROVIDERS.get(provider, provider)}/{model}" From e64ad791737db4aa2b3df9d72b19144b8081fe3a Mon Sep 17 00:00:00 2001 From: Lorenze Jay Date: Fri, 27 Nov 2026 12:12:57 -0800 Subject: [PATCH 2/3] Gemini signer: leave a stubbed httpx or aiohttp alone at import tests/compose.test.ts imports the LangChain harness with httpx stubbed as a bare module; the signer, installed at import, assumed httpx.Client and stopped the import. It now patches only a client that is there. --- shared/gemini_signatures.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/shared/gemini_signatures.py b/shared/gemini_signatures.py index c043717f0c..d00d19574e 100644 --- a/shared/gemini_signatures.py +++ b/shared/gemini_signatures.py @@ -139,18 +139,23 @@ def install() -> None: return import importlib + # Whatever is importable and is the client it looks like: a module a test or a framework put + # in its place (a stub with no `Client`) is left alone rather than stop the harness at import. for name in ("httpx", "httpx2"): try: module = importlib.import_module(name) except ImportError: continue - _patch_httpx(module) + if all(hasattr(module, attribute) for attribute in ("Client", "AsyncClient", "Request")): + _patch_httpx(module) try: import aiohttp except ImportError: pass else: - _patch_aiohttp(aiohttp.ClientSession) + session = getattr(aiohttp, "ClientSession", None) + if session is not None and hasattr(session, "_request"): + _patch_aiohttp(session) _installed = True From ba68f20b4ecee577624726a18b16451b664f573d Mon Sep 17 00:00:00 2001 From: Lorenze Jay Date: Fri, 27 Nov 2026 19:25:16 -0800 Subject: [PATCH 3/3] LangGraph (Python): a handed-back Gemini call with no signature on record gets the placeholder thought_signatures.py (#2335) sends back the signature Gemini gave a call, when the thread carries it. A thread without one (a conversation from before it, or a caller that drops encryptedValue) still reached Google's OpenAI-compatible endpoint unsigned and was refused with "Function call is missing a thought_signature". The engine now installs shared/gemini_signatures.py like the other Python engines: it fills in Google's placeholder only where a call has no signature, so a real one still goes as it came, and nothing changes for another provider's model. The LangGraph (TypeScript) engine already does this in thought-signatures.ts. --- CHANGELOG.md | 4 +- agent-langgraph-agui/Dockerfile | 2 +- agent-langgraph-agui/src/main.py | 6 ++ .../tests/test_gemini_handback.py | 67 +++++++++++++++++++ 4 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 agent-langgraph-agui/tests/test_gemini_handback.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5dddce23e3..ce9a1281f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,9 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. OpenBot Desktop and Settings save it. Google ADK, AG2, CrewAI, Langroid, LlamaIndex, Mastra and Strands now send each handed-back tool call to a Gemini model with Google's documented placeholder, and keep a real signature when there is one. Requests to every other provider are - sent as before. Antigravity was not affected. + sent as before. Antigravity was not affected. On LangGraph (Python), a call with no signature on + record, as in a conversation from before 1.2.2, now goes with the placeholder at Google's + OpenAI-compatible endpoint too, as it already did on LangGraph (TypeScript). - **`BOT_PROVIDER=google` works on Google ADK, Strands, Langroid, CrewAI, LlamaIndex and AG2.** The first five stopped before reaching Google ("LLM Provider NOT provided"), and AG2 asked for an OpenAI key. AG2 now answers on Google's own Gemini API with the Google key. diff --git a/agent-langgraph-agui/Dockerfile b/agent-langgraph-agui/Dockerfile index e5aa276331..b0f94a0502 100644 --- a/agent-langgraph-agui/Dockerfile +++ b/agent-langgraph-agui/Dockerfile @@ -9,7 +9,7 @@ COPY agent-langgraph-agui/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY agent-langgraph-agui/src ./src -COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py /shared/ ENV PORT=4206 EXPOSE 4206 diff --git a/agent-langgraph-agui/src/main.py b/agent-langgraph-agui/src/main.py index af344afc0a..e3b6796c3b 100644 --- a/agent-langgraph-agui/src/main.py +++ b/agent-langgraph-agui/src/main.py @@ -16,6 +16,12 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) from model_providers import bot_settings from run_model_key import RunModelKey +import gemini_signatures + +# thought_signatures.py sends back the signature Gemini gave a call. A call with none on record (a +# thread from before it, or a caller that dropped it) gets Google's placeholder here, so Gemini does +# not refuse the step. See gemini_signatures.py. +gemini_signatures.install() from ag_ui_langgraph import add_langgraph_fastapi_endpoint from fastapi import FastAPI, Request diff --git a/agent-langgraph-agui/tests/test_gemini_handback.py b/agent-langgraph-agui/tests/test_gemini_handback.py new file mode 100644 index 0000000000..32ac100556 --- /dev/null +++ b/agent-langgraph-agui/tests/test_gemini_handback.py @@ -0,0 +1,67 @@ +"""A tool call handed back on Gemini reaches it signed; on any other model, as it was. + +See `shared/gemini_signatures.py`. Checked at the model's door, on both ways a Bot reaches Gemini: +its own API (`BOT_PROVIDER=google`) and an OpenAI-compatible address. +""" + +import importlib +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from harness_contract import ( + check_handback_signed, + gemini_environment, + gemini_gateway_environment, + handback_bodies, + openai_environment, + tool_calls_sent, +) + +TOKEN = "contract-token" + + + +@pytest.fixture(autouse=True) +def _no_pooled_provider_connections(): + """`langchain-openai` keeps one HTTP client per base URL for the life of the process; a + connection pooled in one test's event loop cannot be used from another. See + test_conversation_contract.py. + """ + from langchain_openai.chat_models import _client_utils + + def clear(): + _client_utils._cached_async_httpx_client.cache_clear() + _client_utils._cached_sync_httpx_client.cache_clear() + + clear() + yield + clear() + +@pytest.fixture +def app_for(monkeypatch): + def app_for(environment): + monkeypatch.delenv("OPENAI_API_BASE", raising=False) + monkeypatch.delenv("CHATGPT_AUTH_FILE", raising=False) + monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) + for key, value in environment.items(): + monkeypatch.setenv(key, value) + from src import main + + return importlib.reload(main).app + + return app_for + + +@pytest.mark.parametrize("environment", [gemini_environment, gemini_gateway_environment]) +def test_a_handed_back_gemini_call_is_signed(app_for, environment): + check_handback_signed(handback_bodies(app_for, environment, token=TOKEN)) + + +def test_a_handed_back_call_to_another_model_is_sent_as_it_was(app_for): + calls = tool_calls_sent(handback_bodies(app_for, openai_environment, token=TOKEN)[-1]) + assert calls, "the handed-back call never reached the model as a call" + assert not any(call["signature"] for call in calls), calls