Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,23 @@ 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. 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.
- **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.**
Expand Down
2 changes: 1 addition & 1 deletion agent-adk/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 7 additions & 14 deletions agent-adk/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand Down
50 changes: 50 additions & 0 deletions agent-adk/tests/test_gemini_handback.py
Original file line number Diff line number Diff line change
@@ -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
157 changes: 157 additions & 0 deletions agent-adk/tests/test_gemini_signatures.py
Original file line number Diff line number Diff line change
@@ -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]
2 changes: 1 addition & 1 deletion agent-ag2/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions agent-ag2/requirements.txt
Original file line number Diff line number Diff line change
@@ -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]
39 changes: 34 additions & 5 deletions agent-ag2/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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"
Expand Down
Loading