diff --git a/CHANGELOG.md b/CHANGELOG.md index 736e27b98d..6129879efd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,15 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **A Bot on Gemini 3 or later finishes what it started with a tool, on every engine.** 1.2.2 fixed + this on the LangGraph engines. On Google ADK, AG2, CrewAI, Langroid, Mastra and Strands, a Bot on a + Gemini key saved in Settings or OpenBot Desktop, or on OpenBot Cloud's AI connection, still stopped + once a tool's result came back, with Google's "Function call is missing a thought_signature". CrewAI + now sends each call back with the signature Gemini gave it, as LangGraph does, and so does ADK when + the same process answers the result. Where an engine cannot keep it, the call goes with Google's + documented placeholder for a call whose signature is not available. Requests to every other + provider and model are sent as before. + ## 1.2.3 **Before upgrading.** diff --git a/agent-adk/Dockerfile b/agent-adk/Dockerfile index 2dffe002d8..da27fde97a 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/progress_reminder.py shared/empty_turns.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py shared/progress_reminder.py shared/empty_turns.py /shared/ ENV PORT=4208 EXPOSE 4208 diff --git a/agent-adk/src/main.py b/agent-adk/src/main.py index 40175bab56..e439d0a8da 100644 --- a/agent-adk/src/main.py +++ b/agent-adk/src/main.py @@ -18,6 +18,13 @@ from progress_reminder import with_litellm_reminders from model_providers import bot_settings, litellm_model_id from run_model_key import RunModelKey +import gemini_signatures + +# A tool call handed back to Gemini 3 by a process that did not make it goes with Google's +# placeholder for its thought signature: `ag_ui_adk` sends no signature out with a client tool's +# call, so the thread has none to bring back. The process that made the call keeps the real one +# in its session. See gemini_signatures.py. +gemini_signatures.install() from ag_ui.core import ( AssistantMessage, diff --git a/agent-adk/tests/test_gemini_signatures.py b/agent-adk/tests/test_gemini_signatures.py new file mode 100644 index 0000000000..1e1a367095 --- /dev/null +++ b/agent-adk/tests/test_gemini_signatures.py @@ -0,0 +1,92 @@ +"""Which model requests `shared/gemini_signatures.py` changes, and which it sends as they were. + +The module is shared by the Python engines; its rule is checked once, here, on the requests the +engines send. Each engine's `test_gemini_thought_signature.py` checks a run through it. +""" + +import json +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from gemini_signatures import GEMINI_SKIP_SIGNATURE, checks_signatures, signed_body + +GOOGLE = "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions" +GATEWAY = "http://openbot:3010/api/model-provider/v1/chat/completions" + + +def chat(model="gemini-3.8-flash", calls=1, signature=None): + tool_calls = [ + {"id": f"c{n}", "type": "function", "function": {"name": "f", "arguments": "{}"}} + for n in range(calls) + ] + if signature: + tool_calls[0]["extra_content"] = {"google": {"thought_signature": signature}} + return json.dumps( + { + "model": model, + "messages": [ + {"role": "user", "content": "hi"}, + {"role": "assistant", "content": None, "tool_calls": tool_calls}, + *({"role": "tool", "tool_call_id": f"c{n}", "content": "{}"} for n in range(calls)), + ], + } + ).encode() + + +def signatures(body): + return [ + ((call.get("extra_content") or {}).get("google") or {}).get("thought_signature") + for message in json.loads(body)["messages"] + for call in message.get("tool_calls") or [] + ] + + +@pytest.mark.parametrize( + "model", ["gemini-3.8-flash", "gemini-4-hydrogen", "models/gemini-3.6-flash", "google/gemini-4-neon"] +) +def test_gemini_3_on_checks_signatures(model): + assert checks_signatures(model) + + +@pytest.mark.parametrize( + "model", ["gemini-2.5-flash", "gemini-1.5-pro", "gemma-4-31b-it", "gpt-5.5", "claude-sonnet-5-5", "", None] +) +def test_other_models_do_not(model): + assert not checks_signatures(model) + + +@pytest.mark.parametrize("url", [GOOGLE, GATEWAY]) +def test_the_first_call_of_an_unsigned_step_gets_the_placeholder(url): + assert signatures(signed_body("POST", url, chat(calls=2))) == [GEMINI_SKIP_SIGNATURE, None] + + +def test_a_real_signature_is_sent_as_it_was(): + assert signed_body("POST", GOOGLE, chat(signature="real")) is None + + +@pytest.mark.parametrize( + "url", + [ + "https://api.openai.com/v1/chat/completions", + "https://openrouter.ai/api/v1/chat/completions", + "http://127.0.0.1:11434/v1/chat/completions", + ], +) +def test_another_provider_is_sent_its_request_as_it_was(url): + assert signed_body("POST", url, chat()) is None + + +def test_a_model_that_does_not_check_is_sent_its_request_as_it_was(): + assert signed_body("POST", GOOGLE, chat(model="gemini-2.5-flash")) is None + assert signed_body("POST", GATEWAY, chat(model="gpt-5.5")) is None + + +def test_anything_but_a_chat_with_calls_is_sent_as_it_was(): + assert signed_body("GET", GOOGLE, chat()) is None + assert signed_body("POST", GOOGLE.replace("chat/completions", "embeddings"), chat()) is None + assert signed_body("POST", GOOGLE, b"not json") is None + plain = json.dumps({"model": "gemini-3.8-flash", "messages": [{"role": "user", "content": "hi"}]}) + assert signed_body("POST", GOOGLE, plain.encode()) is None diff --git a/agent-adk/tests/test_gemini_thought_signature.py b/agent-adk/tests/test_gemini_thought_signature.py new file mode 100644 index 0000000000..790cc094d1 --- /dev/null +++ b/agent-adk/tests/test_gemini_thought_signature.py @@ -0,0 +1,45 @@ +"""A Bot on Gemini 3 finishes a tool call the server ran between two runs. + +Gemini refuses the run after a tool's result unless the call comes back with the thought signature +it gave it ("Function call is missing a thought_signature"). See `check_gemini_handback`. +""" + +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_gemini_handback +from gemini_signatures import GEMINI_SKIP_SIGNATURE + +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 + + +def test_the_process_that_made_the_call_sends_back_its_signature(app_for): + state = check_gemini_handback(app_for, token=TOKEN, warm=True) + # ADK's session keeps the signature Gemini gave the call. + assert state["returned"] == list(state["issued"].values()), state + + +def test_a_fresh_process_sends_the_call_back_with_googles_placeholder(app_for): + state = check_gemini_handback(app_for, token=TOKEN, warm=False) + # `ag_ui_adk` sends no signature out with a client tool's call, so the thread brings none back. + assert state["returned"] == [GEMINI_SKIP_SIGNATURE], state diff --git a/agent-ag2/Dockerfile b/agent-ag2/Dockerfile index c78a335166..0c133f6e7d 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/progress_reminder.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py shared/progress_reminder.py /shared/ ENV PORT=4210 EXPOSE 4210 diff --git a/agent-ag2/src/main.py b/agent-ag2/src/main.py index 85f67354d3..57be7935e4 100644 --- a/agent-ag2/src/main.py +++ b/agent-ag2/src/main.py @@ -10,6 +10,12 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) from model_providers import bot_settings, openai_api from run_model_key import RunModelKey +import gemini_signatures + +# A tool call handed back to Gemini 3 goes with Google's placeholder for its thought signature, +# which AG2 keeps between runs only on its own Gemini config, not on an OpenAI-compatible +# endpoint. See gemini_signatures.py. +gemini_signatures.install() from ag2 import Agent from ag2.ag_ui import AGUIStream diff --git a/agent-ag2/tests/test_gemini_thought_signature.py b/agent-ag2/tests/test_gemini_thought_signature.py new file mode 100644 index 0000000000..668682e8c5 --- /dev/null +++ b/agent-ag2/tests/test_gemini_thought_signature.py @@ -0,0 +1,41 @@ +"""A Bot on Gemini 3 finishes a tool call the server ran between two runs. + +Gemini refuses the run after a tool's result unless the call comes back with the thought signature +it gave it ("Function call is missing a thought_signature"). See `check_gemini_handback`. +""" + +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_gemini_handback +from gemini_signatures import GEMINI_SKIP_SIGNATURE + +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("warm", [True, False], ids=["same-process", "fresh-process"]) +def test_a_tool_call_on_gemini_goes_back_signed(app_for, warm): + state = check_gemini_handback(app_for, token=TOKEN, warm=warm) + # The integration does not carry the signature between runs: Google's placeholder goes in + # its place. + assert state["returned"] == [GEMINI_SKIP_SIGNATURE], state diff --git a/agent-crewai/Dockerfile b/agent-crewai/Dockerfile index 9e5e7bed6a..70d8029058 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/progress_reminder.py shared/empty_turns.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py shared/progress_reminder.py shared/empty_turns.py /shared/ ENV PORT=4202 EXPOSE 4202 diff --git a/agent-crewai/src/main.py b/agent-crewai/src/main.py index 87c9bea648..6eb3b78ac6 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -23,6 +23,11 @@ from progress_reminder import with_litellm_reminders from model_providers import bot_settings, litellm_model_id from run_model_key import RunModelKey +import gemini_signatures + +# A call the thread brings back with no thought signature goes to Gemini 3 with Google's +# placeholder. One it brings back with its signature goes with that (`_sealed`). +gemini_signatures.install() import ag_ui_crewai.endpoint as crewai_endpoint from ag_ui.core import Message, Tool @@ -89,22 +94,47 @@ def _strip_none(message: dict[str, Any]) -> dict[str, Any]: return {key: value for key, value in message.items() if value is not None} +def _google_signature(tool_call: Mapping) -> str | None: + """Gemini's thought signature on a call from its OpenAI-compatible endpoint, if it gave one.""" + extra = tool_call.get("extra_content") + google = extra.get("google") if isinstance(extra, Mapping) else None + signature = google.get("thought_signature") if isinstance(google, Mapping) else None + return signature if isinstance(signature, str) and signature else None + + +def _sealed(message: dict[str, Any]) -> dict[str, Any]: + """The model's message, each call Gemini signed carrying its signature as its `encryptedValue`. + + Gemini 3 refuses the run that brings a tool's result unless the call comes back with the + thought signature it gave it. The call leaves in the run's snapshot and comes back in the + thread, which keeps a call's `encryptedValue` and nothing else a provider put on it. + """ + for tool_call in message.get("tool_calls") or []: + if isinstance(tool_call, dict) and _google_signature(tool_call): + tool_call["encrypted_value"] = _google_signature(tool_call) + return message + + def _provider_tool_calls(tool_calls: Any) -> Any: if not isinstance(tool_calls, list): return deepcopy(tool_calls) + # A call's `encryptedValue` goes back only to Gemini, the one provider that can read it. + gemini = gemini_signatures.checks_signatures(_model()) projected = [] for tool_call in tool_calls: if not isinstance(tool_call, Mapping): tool_call = tool_call.model_dump() - projected.append( - _strip_none( - { - key: deepcopy(tool_call[key]) - for key in ("id", "type", "function") - if key in tool_call - } - ) + call = _strip_none( + { + key: deepcopy(tool_call[key]) + for key in ("id", "type", "function") + if key in tool_call + } ) + sealed = tool_call.get("encrypted_value") or tool_call.get("encryptedValue") + if gemini and isinstance(sealed, str) and sealed: + call["extra_content"] = {"google": {"thought_signature": sealed}} + projected.append(call) return projected @@ -182,7 +212,7 @@ async def answer(self): stream=False, ) self.state.setdefault("messages", []).append( - response.choices[0].message.model_dump() + _sealed(response.choices[0].message.model_dump()) ) diff --git a/agent-crewai/tests/test_gemini_thought_signature.py b/agent-crewai/tests/test_gemini_thought_signature.py new file mode 100644 index 0000000000..6750f22042 --- /dev/null +++ b/agent-crewai/tests/test_gemini_thought_signature.py @@ -0,0 +1,49 @@ +"""A Bot on Gemini 3 finishes a tool call the server ran between two runs. + +Gemini refuses the run after a tool's result unless the call comes back with the thought signature +it gave it ("Function call is missing a thought_signature"). See `check_gemini_handback`. +""" + +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_gemini_handback +from gemini_signatures import GEMINI_SKIP_SIGNATURE + +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: + # restore the library first, then import `main` anew, as a fresh process does. + 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("warm", [True, False], ids=["same-process", "fresh-process"]) +def test_a_tool_call_on_gemini_goes_back_signed(app_for, warm): + state = check_gemini_handback(app_for, token=TOKEN, warm=warm) + # The signature Gemini gave: out on the call as its `encryptedValue`, back from the thread. + assert state["returned"] == list(state["issued"].values()), state + + +def test_a_call_the_thread_has_no_signature_for_goes_with_googles_placeholder(app_for): + state = check_gemini_handback(app_for, token=TOKEN, thread_keeps_signature=False) + assert state["returned"] == [GEMINI_SKIP_SIGNATURE], state diff --git a/agent-langroid/Dockerfile b/agent-langroid/Dockerfile index 2b577092c5..a298a6d184 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/progress_reminder.py shared/empty_turns.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py shared/progress_reminder.py shared/empty_turns.py /shared/ ENV PORT=4209 EXPOSE 4209 diff --git a/agent-langroid/src/main.py b/agent-langroid/src/main.py index 7b09437cb1..f311864303 100644 --- a/agent-langroid/src/main.py +++ b/agent-langroid/src/main.py @@ -10,6 +10,11 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) from model_providers import bot_settings, litellm_model_id, openai_api from run_model_key import RunModelKey +import gemini_signatures + +# A tool call handed back to Gemini 3 goes with Google's placeholder for its thought signature, +# which the integration does not carry between runs. See gemini_signatures.py. +gemini_signatures.install() import litellm from ag_ui_langroid import create_langroid_app diff --git a/agent-langroid/tests/test_gemini_thought_signature.py b/agent-langroid/tests/test_gemini_thought_signature.py new file mode 100644 index 0000000000..bc9c1fd563 --- /dev/null +++ b/agent-langroid/tests/test_gemini_thought_signature.py @@ -0,0 +1,52 @@ +"""A Bot on Gemini 3 finishes a tool call the server ran between two runs. + +Gemini refuses the run after a tool's result unless the call comes back with the thought signature +it gave it ("Function call is missing a thought_signature"). See `check_gemini_handback`. +""" + +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_gemini_handback +from gemini_signatures import GEMINI_SKIP_SIGNATURE + +TOKEN = "contract-token" + + +@pytest.fixture(autouse=True) +def _no_cached_clients(): + """Langroid keeps one model client per key for the life of the process, which a fresh one has + not; the address the fake answers on is not part of that key.""" + 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("warm", [True, False], ids=["same-process", "fresh-process"]) +def test_a_tool_call_on_gemini_goes_back_signed(app_for, warm): + state = check_gemini_handback(app_for, token=TOKEN, warm=warm) + # The integration does not carry the signature between runs: Google's placeholder goes in + # its place. + assert state["returned"] == [GEMINI_SKIP_SIGNATURE], state diff --git a/agent-mastra/src/mastra/gemini-signatures.ts b/agent-mastra/src/mastra/gemini-signatures.ts new file mode 100644 index 0000000000..7275eb3b9c --- /dev/null +++ b/agent-mastra/src/mastra/gemini-signatures.ts @@ -0,0 +1,92 @@ +/** + * Google's placeholder on a tool call that goes back to Gemini without its thought signature. The + * same rule as `shared/gemini_signatures.py`, which the Python engines use. + * + * Gemini 3 and later give the first function call of each model step a thought signature, and + * refuse a request whose current turn holds a step whose first call comes back without it: 400, + * "Function call is missing a thought_signature in functionCall parts" + * (https://ai.google.dev/gemini-api/docs/thought-signatures). On Google's OpenAI-compatible + * endpoint it is the call's `extra_content.google.thought_signature`. OpenBot runs a Bot's tool + * between two runs and hands the call back without it, and `@ai-sdk/openai` neither reads it nor + * writes it, so this Bot's run that brought a tool's result to a Gemini 3 model was refused. + * + * Google documents a value for a call whose signature is not available, + * `skip_thought_signature_validator`. `signingFetch` wraps the fetch this Bot's model client is + * given and puts it on the first call of each assistant step that has none, in a request that is a + * POST to Chat Completions, on Google's own host or OpenBot's model gateway, for a Gemini model that + * checks signatures (Gemini 3 on). A signature already there is kept, and every other request is + * sent exactly as it was built. + */ + +export const GEMINI_SKIP_SIGNATURE = "skip_thought_signature_validator"; + +const GOOGLE_HOST = "generativelanguage.googleapis.com"; +const GATEWAY_PATH = "/api/model-provider/"; + +type Json = Record; +const isObject = (value: unknown): value is Json => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** Whether a model name is a Gemini model that checks thought signatures: Gemini 3 on. */ +export function checksSignatures(model: unknown): boolean { + if (typeof model !== "string") return false; + const name = model.trim().split("/").at(-1) ?? ""; + return /^gemini-/i.test(name) && !/^gemini-[12][.-]/i.test(name); +} + +/** Each assistant step's first call given the placeholder where it has no signature. */ +function signSteps(messages: unknown): boolean { + let changed = false; + for (const message of Array.isArray(messages) ? messages : []) { + if (!isObject(message) || message.role !== "assistant") continue; + const [first] = Array.isArray(message.tool_calls) ? message.tool_calls : []; + if (!isObject(first)) continue; + const extra = isObject(first.extra_content) ? first.extra_content : {}; + const google = isObject(extra.google) ? extra.google : {}; + if (google.thought_signature) continue; + first.extra_content = { + ...extra, + google: { ...google, thought_signature: GEMINI_SKIP_SIGNATURE }, + }; + changed = true; + } + return changed; +} + +/** A Chat Completions body for Gemini with its unsigned steps signed, or undefined to send as is. */ +export function signedBody(url: string, body: string): string | undefined { + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return undefined; + } + if (!parsed.pathname.endsWith("/chat/completions")) return undefined; + if ( + parsed.hostname.toLowerCase() !== GOOGLE_HOST && + !parsed.pathname.includes(GATEWAY_PATH) + ) + return undefined; + let json: unknown; + try { + json = JSON.parse(body); + } catch { + return undefined; + } + if (!isObject(json) || !checksSignatures(json.model)) return undefined; + return signSteps(json.messages) ? JSON.stringify(json) : undefined; +} + +/** `inner` (the global fetch by default), with each Gemini request's unsigned steps signed. */ +export function signingFetch(inner?: typeof fetch): typeof fetch { + return (async (input: string | URL | Request, init?: RequestInit) => { + const send = inner ?? globalThis.fetch; + const url = input instanceof Request ? input.url : String(input); + const signed = + typeof init?.body === "string" && + (init.method ?? "GET").toUpperCase() === "POST" + ? signedBody(url, init.body) + : undefined; + return send(input, signed === undefined ? init : { ...init, body: signed }); + }) as typeof fetch; +} diff --git a/agent-mastra/src/mastra/index.test.ts b/agent-mastra/src/mastra/index.test.ts index ba639d15a7..4706367c6d 100644 --- a/agent-mastra/src/mastra/index.test.ts +++ b/agent-mastra/src/mastra/index.test.ts @@ -798,6 +798,133 @@ describe("OpenBot Mastra on OpenBot's model gateway", () => { } }); +/** + * Gemini 3 refuses the run that brings a tool's result unless the call comes back with the thought + * signature it gave it, and the call comes back from the thread without one. The gateway below + * keeps Google's rule for the call handed back: missing, refused with Google's 400. See + * gemini-signatures.ts. + */ +describe("OpenBot Mastra hands a tool call back to Gemini", () => { + for (const [model, placeholder] of [ + ["gemini-3.8-flash", "skip_thought_signature_validator"], + ["gpt-5.5", undefined], + ] as const) { + test(`${model}: the call goes back ${placeholder ? "with Google's placeholder" : "as it was"}`, async () => { + const sent: unknown[] = []; + const gateway = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + async fetch(request) { + const body = await request.json(); + const [call] = (body.messages ?? []).flatMap( + (message: { tool_calls?: unknown[] }) => message.tool_calls ?? [], + ) as { + extra_content?: { google?: { thought_signature?: string } }; + }[]; + sent.push(call); + const signature = call?.extra_content?.google?.thought_signature; + if (model.startsWith("gemini-") && !signature) + return Response.json( + [ + { + error: { + code: 400, + message: + "Function call is missing a thought_signature in functionCall parts.", + status: "INVALID_ARGUMENT", + }, + }, + ], + { status: 400 }, + ); + return Response.json({ + id: "chat", + object: "chat.completion", + created: 0, + model: body.model, + choices: [ + { + index: 0, + finish_reason: "stop", + message: { + role: "assistant", + content: "Order 42 has shipped.", + }, + }, + ], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, + }); + }, + }); + 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: `${gateway.url.toString().replace(/\/+$/, "")}/api/model-provider/v1`, + 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":"Order 42 has shipped."'); + expect(sent).toHaveLength(1); + expect( + ( + sent[0] as { + extra_content?: { google?: { thought_signature?: string } }; + } + ).extra_content?.google?.thought_signature, + ).toBe(placeholder); + } finally { + await gateway.stop(true); + } + }, 15_000); + } +}); + describe("OpenBot Mastra compatible-endpoint tool-call chunks", () => { test("defaults a missing tool-call index to its position in the array", () => { const chunk = { diff --git a/agent-mastra/src/mastra/index.ts b/agent-mastra/src/mastra/index.ts index dab5213c47..6b10f2d8a8 100644 --- a/agent-mastra/src/mastra/index.ts +++ b/agent-mastra/src/mastra/index.ts @@ -21,6 +21,7 @@ import { botSettings, providerSpec, } from "../../../shared/model-providers"; +import { signingFetch } from "./gemini-signatures"; import { progressReminder } from "./progress-reminder"; import { withDefaultToolCallIndexes } from "./tool-call-index"; @@ -82,8 +83,11 @@ async function buildModel(runKey?: string) { ? apiKeyOrPlaceholder(process.env[spec.keyVariable]) : undefined), // A compatible address may stream tool calls without the index the SDK requires - // (tool-call-index.ts). OpenAI's own Responses path never sees a chat chunk. - ...(compatible ? { fetch: withDefaultToolCallIndexes() } : {}), + // (tool-call-index.ts), and may serve Gemini, which refuses a handed-back call without its + // thought signature (gemini-signatures.ts). OpenAI's own Responses path needs neither. + ...(compatible + ? { fetch: withDefaultToolCallIndexes(signingFetch()) } + : {}), }); // Compatible endpoints commonly expose Chat Completions; OpenAI keeps its Responses default. return compatible ? openai.chat(model) : openai(model); diff --git a/agent-strands/Dockerfile b/agent-strands/Dockerfile index 6046e687b1..43f61a1dc0 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/progress_reminder.py shared/empty_turns.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/gemini_signatures.py shared/progress_reminder.py shared/empty_turns.py /shared/ ENV PORT=4207 EXPOSE 4207 diff --git a/agent-strands/src/main.py b/agent-strands/src/main.py index 6200acc21a..f3546b07f4 100644 --- a/agent-strands/src/main.py +++ b/agent-strands/src/main.py @@ -12,6 +12,11 @@ from empty_turns import without_empty_turns from model_providers import bot_settings, litellm_model_id from run_model_key import RunModelKey +import gemini_signatures + +# A tool call handed back to Gemini 3 goes with Google's placeholder for its thought signature, +# which the integration does not carry between runs. See gemini_signatures.py. +gemini_signatures.install() from ag_ui_strands import StrandsAgent, add_strands_fastapi_endpoint from fastapi import FastAPI, Request diff --git a/agent-strands/tests/test_gemini_thought_signature.py b/agent-strands/tests/test_gemini_thought_signature.py new file mode 100644 index 0000000000..3b73c273bb --- /dev/null +++ b/agent-strands/tests/test_gemini_thought_signature.py @@ -0,0 +1,40 @@ +"""A Bot on Gemini 3 finishes a tool call the server ran between two runs. + +Gemini refuses the run after a tool's result unless the call comes back with the thought signature +it gave it ("Function call is missing a thought_signature"). See `check_gemini_handback`. +""" + +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_gemini_handback +from gemini_signatures import GEMINI_SKIP_SIGNATURE + +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("warm", [True, False], ids=["same-process", "fresh-process"]) +def test_a_tool_call_on_gemini_goes_back_signed(app_for, warm): + state = check_gemini_handback(app_for, token=TOKEN, warm=warm) + # The integration does not carry the signature between runs: Google's placeholder goes in + # its place. + assert state["returned"] == [GEMINI_SKIP_SIGNATURE], state diff --git a/shared/gemini_signatures.py b/shared/gemini_signatures.py new file mode 100644 index 0000000000..bc617dd795 --- /dev/null +++ b/shared/gemini_signatures.py @@ -0,0 +1,153 @@ +"""Google's placeholder on a tool call that goes back to Gemini without its thought signature. + +Gemini 3 and later give the first function call of each model step a thought signature, and refuse +a request whose current turn (everything after the newest user message with words) holds a step +whose first call comes back without it: 400, "Function call is missing a thought_signature in +functionCall parts" (https://ai.google.dev/gemini-api/docs/thought-signatures). On Google's +OpenAI-compatible endpoint, which a Gemini key saved in Settings or OpenBot Desktop and OpenBot's +model gateway both use, the signature is `tool_calls[i].extra_content.google.thought_signature`. + +OpenBot runs a Bot's tool between two runs and sends the call back in the thread with its result. +An engine whose AG-UI integration does not carry the signature on the call (as its +`encryptedValue`) sends the call back unsigned, and Gemini refuses the run that brings the tool's +result. Where an engine can carry the real signature it does (see agent-adk and agent-crewai). +Where it cannot, or the thread has none for a call (a conversation from before, or a call another +provider's model made), Google documents a value for a call whose signature is not available, +`skip_thought_signature_validator`, and this module puts it on that call. + +AT THE HTTP REQUEST, as `run_model_key.py` puts a run's key in: each framework builds its model +request its own way (LiteLLM, the OpenAI SDK under AG2 or Langroid), and every one of them sends it +through `httpx`. `install()` wraps `httpx`'s and `httpx2`'s sends, and changes only a request that +is all of these: +- a POST to Chat Completions, +- on Google's own host or OpenBot's model gateway, +- for a Gemini model that checks signatures (Gemini 3 on; Gemini 1 and 2 never asked for them). +In it, the first call of each assistant step that has no signature gets the placeholder, which is +all Gemini checks. A signature already there is kept. Every other request is sent as it was built. +""" + +from __future__ import annotations + +import json +import re +from typing import Any +from urllib.parse import urlsplit + +GEMINI_SKIP_SIGNATURE = "skip_thought_signature_validator" + +GOOGLE_HOST = "generativelanguage.googleapis.com" +GATEWAY_PATH = "/api/model-provider/" + +# A Gemini model by Google's name, after any namespace a gateway puts in front (`google/gemini-…`). +_GEMINI = re.compile(r"^gemini-", re.IGNORECASE) +_BEFORE_SIGNATURES = re.compile(r"^gemini-[12][.-]", re.IGNORECASE) + + +def checks_signatures(model: Any) -> bool: + """Whether a model name is a Gemini model that checks thought signatures: Gemini 3 on.""" + if not isinstance(model, str): + return False + name = model.strip().rsplit("/", 1)[-1] + return bool(_GEMINI.match(name)) and not _BEFORE_SIGNATURES.match(name) + + +def sign_steps(messages: Any) -> bool: + """Each assistant step's first call given the placeholder where it has no signature. + + Gemini checks only a step's first call, and gives only that one a signature. Whether any call + was changed. + """ + changed = False + for message in messages if isinstance(messages, list) else []: + if not isinstance(message, dict) or message.get("role") != "assistant": + continue + calls = message.get("tool_calls") + if not isinstance(calls, list) or not calls or not isinstance(calls[0], dict): + continue + first = calls[0] + extra = first.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 + first["extra_content"] = { + **extra, + "google": {**google, "thought_signature": GEMINI_SKIP_SIGNATURE}, + } + changed = True + return changed + + +def signed_body(method: str, url: str, content: bytes | None) -> bytes | None: + """A Chat Completions body for Gemini with its unsigned steps signed, or None to send it as is.""" + if (method or "").upper() != "POST" or not content: + return None + parts = urlsplit(url) + path = parts.path or "" + if not path.endswith("/chat/completions"): + return None + if (parts.hostname or "").lower() != GOOGLE_HOST and GATEWAY_PATH not in path: + return None + try: + body = json.loads(content) + except ValueError: + return None + if not isinstance(body, dict) or not checks_signatures(body.get("model")): + return None + if not sign_steps(body.get("messages")): + 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 step. Idempotent.""" + global _installed + if _installed: + return + import importlib + + for name in ("httpx", "httpx2"): + try: + module = importlib.import_module(name) + except ImportError: + continue + _patch(module) + _installed = True + + +def _signed(module, request): + """`request`, or a copy of it with its Gemini steps signed.""" + try: + content = request.content + except Exception: # A streamed body, which no framework sends 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(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, _signed(module, request), *args, **kwargs) + + async def asend(self, request, *args, **kwargs): + return await async_send(self, _signed(module, request), *args, **kwargs) + + client.send = send + async_client.send = asend diff --git a/shared/harness_contract.py b/shared/harness_contract.py index d000fe0107..6916df2146 100644 --- a/shared/harness_contract.py +++ b/shared/harness_contract.py @@ -18,6 +18,7 @@ harnesses build provider messages from `input.messages` in their own code and test it there. """ +import base64 import json import socket import threading @@ -200,7 +201,6 @@ def fake_provider(keys: list[str] | None = None) -> Iterator[tuple[str, list[dic Given `keys`, also writes down the key each request presented, as OpenAI's SDK sends it (`Authorization: Bearer`) or Anthropic's (`x-api-key`). """ - import uvicorn from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, StreamingResponse @@ -332,9 +332,263 @@ async def messages(request: Request): ] return sse([f"event: {name}\ndata: {json.dumps(data)}\n\n" for name, data in events]) + with _serving(app) as base: + yield base, bodies + + +# Gemini 3 and later give the first function call of each model step a thought signature, and refuse +# a request whose current turn (everything after the newest user message) holds a step whose first +# call comes back without it: https://ai.google.dev/gemini-api/docs/thought-signatures. Google's +# OpenAI-compatible endpoint carries it as `tool_calls[i].extra_content.google.thought_signature`. +GEMINI_MODEL = "gemini-3.8-flash" +# Google's documented values for a call whose signature is not available, which skip the check. +GEMINI_DUMMY_SIGNATURES = ("skip_thought_signature_validator", "context_engineering_is_the_way_to_go") +GEMINI_MISSING = ( + "Function call is missing a thought_signature in functionCall parts. This is required for " + "tools to work correctly, and missing thought_signature may lead to degraded model " + "performance. Additional data, function call `default_api:{name}` , position {position}. " + "Please refer to https://ai.google.dev/gemini-api/docs/thought-signatures for more details." +) +LOOK_UP_ORDER = { + "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"], + }, +} + + +def gemini_environment(base: str, model: str = GEMINI_MODEL) -> dict[str, str]: + """A Gemini model on OpenBot's model gateway at `base`, as OpenBot Cloud's AI connection runs it. + + An OpenAI-compatible address, as a Gemini key saved in Settings or OpenBot Desktop is too + (Google's own host, which a test cannot serve). + """ + 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 tool_call_run(thread_id: str, messages: list[dict], run_id: str = "gemini-run") -> dict: + return { + "threadId": thread_id, + "runId": run_id, + "state": {}, + "messages": messages, + "tools": [LOOK_UP_ORDER], + "context": [], + "forwardedProps": {}, + } + + +@contextmanager +def fake_gemini() -> Iterator[tuple[str, dict]]: + """Gemini at its OpenAI-compatible Chat Completions, with its thought-signature rule. + + A request with no tool result pending gets a call to `look_up_order`, signed. A request after a + tool result is checked as Gemini checks it: the first call of each step in the current turn must + carry the signature Gemini gave it, or one of Google's documented dummies; otherwise it is + refused with Google's 400. Yields `(base_url, state)`, where `state` holds `issued` (the + signature given, by call id), `returned` (the signature each checked step carried) and + `refusals`. Served at `/v1/...` and at the gateway's `/api/model-provider/v1/...`. + """ + from fastapi import FastAPI, Request + from fastapi.responses import JSONResponse, StreamingResponse + + state: dict[str, Any] = {"issued": {}, "returned": [], "refusals": [], "bodies": []} + app = FastAPI() + + def says_something(message: dict) -> bool: + content = message.get("content") + if isinstance(content, list): + return any(isinstance(part, dict) and (part.get("text") or "").strip() for part in content) + return bool((content or "").strip()) if isinstance(content, str) else False + + def turn_start(messages: list[dict]) -> int: + """The newest user message with words: where Gemini's current turn begins.""" + return max( + (i for i, m in enumerate(messages) if m.get("role") == "user" and says_something(m)), + default=-1, + ) + + def refusal(body: dict) -> str | None: + messages = body.get("messages") or [] + start = turn_start(messages) + for index, message in enumerate(messages[start + 1 :], start + 1): + calls = message.get("tool_calls") if message.get("role") == "assistant" else None + if not calls: + continue + first = calls[0] + google = (first.get("extra_content") or {}).get("google") or {} + signature = google.get("thought_signature") + state["returned"].append(signature) + if signature in GEMINI_DUMMY_SIGNATURES: + continue + if not signature: + return GEMINI_MISSING.format(name=first["function"]["name"], position=index) + if signature != state["issued"].get(first.get("id")): + return "Thought signature is not valid." + return None + + @app.post("/v1/chat/completions") + async def chat(request: Request): + body = await request.json() + state["bodies"].append(body) + refused = refusal(body) + if refused: + state["refusals"].append(refused) + error = {"code": 400, "message": refused, "status": "INVALID_ARGUMENT"} + return JSONResponse([{"error": error}], status_code=400) + messages = body.get("messages") or [] + model = body.get("model", GEMINI_MODEL) + if any(m.get("role") == "tool" for m in messages[turn_start(messages) + 1 :]): + message = {"role": "assistant", "content": "Order 42 has shipped."} + finish = "stop" + else: + number = len(state["issued"]) + 1 + call_id = f"call_gemini_{number}" + signature = base64.b64encode(f"gemini-signature-{number}".encode()).decode() + state["issued"][call_id] = signature + message = { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": call_id, + "type": "function", + "function": {"name": "look_up_order", "arguments": '{"order": "42"}'}, + "extra_content": {"google": {"thought_signature": signature}}, + } + ], + } + finish = "tool_calls" + usage = {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2} + head = {"id": "gemini", "created": 0, "model": model} + if not body.get("stream"): + choice = {"index": 0, "finish_reason": finish, "message": message} + return JSONResponse({**head, "object": "chat.completion", "choices": [choice], "usage": usage}) + delta = dict(message) + if "tool_calls" in delta: + delta["tool_calls"] = [{"index": 0, **call} for call in delta["tool_calls"]] + chunks = [ + {**head, "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}, + {**head, "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {}, "finish_reason": finish}], "usage": usage}, + ] + + async def stream(): + for chunk in chunks: + yield f"data: {json.dumps(chunk)}\n\n" + yield "data: [DONE]\n\n" + + return StreamingResponse(stream(), media_type="text/event-stream") + + with _serving(app) as base: + yield base, state + + +def check_gemini_handback( + app_for, + *, + path: str = "/", + token: str = "contract-token", + warm: bool = True, + thread_keeps_signature: bool = True, +) -> dict: + """A Bot on Gemini 3 finishes a tool call the server ran between two runs. + + Run one: the person asks, the model calls `look_up_order`, and the run ends with the call, as it + does for every tool the server runs. Run two: the thread comes back as the server sends it, the + call (with the `encryptedValue` the run gave it, if any, unless not `thread_keeps_signature`, as + in a thread from before) and its result. `warm` sends run two to the same process; otherwise to + a fresh one, as on a second replica or after a restart. Answers the fake's state. + """ + from fastapi.testclient import TestClient + + headers = {"x-openbot-agent-token": token} + thread = f"gemini-{'warm' if warm else 'cold'}" + asked = {"id": "u1", "role": "user", "content": "What is the status of order 42?"} + with fake_gemini() as (base, state): + environment = gemini_environment(base) + with TestClient(app_for(environment)) as client: + first = client.post(path, json=tool_call_run(thread, [asked], "run-1"), headers=headers) + assert first.status_code == 200, first.text + tool_call = _the_call(run_events(first.text)) + if not thread_keeps_signature: + tool_call.pop("encryptedValue", None) + messages = [ + asked, + {"id": "a1", "role": "assistant", "content": "", "toolCalls": [tool_call]}, + {"id": "t1", "role": "tool", "toolCallId": tool_call["id"], "content": '{"status": "shipped"}'}, + ] + second_run = tool_call_run(thread, messages, "run-2") + if warm: + second = client.post(path, json=second_run, headers=headers) + if not warm: + with TestClient(app_for(environment)) as client: + second = client.post(path, json=second_run, headers=headers) + assert second.status_code == 200, second.text + assert state["refusals"] == [], state["refusals"] + types = [e["type"] for e in run_events(second.text)] + assert "RUN_ERROR" not in types and "RUN_FINISHED" in types, second.text + assert state["returned"], "the handed-back call never reached Gemini as a call" + return state + + +def _the_call(events: list[dict]) -> dict: + """The one tool call a run made, as the thread keeps it after the run. + + From the run's last MESSAGES_SNAPSHOT when it sent one, otherwise from its tool call events + (START, ARGS and END, or CHUNKs, as the integration chooses). A REASONING_ENCRYPTED_VALUE for the + call becomes its `encryptedValue`, as AG-UI's client applies it. + """ + snapshots = [e for e in events if e["type"] == "MESSAGES_SNAPSHOT"] + if snapshots: + [call] = [ + call + for message in snapshots[-1]["messages"] + if message.get("role") == "assistant" + for call in message.get("toolCalls") or [] + ] + # Only what an AG-UI tool call holds comes back in the thread; anything else a snapshot + # carries (a provider's own fields) does not. + call = {key: call[key] for key in ("id", "type", "function", "encryptedValue") if key in call} + else: + [started] = [ + e for e in events if e["type"] in ("TOOL_CALL_START", "TOOL_CALL_CHUNK") and e.get("toolCallName") + ] + call_id = started["toolCallId"] + arguments = "".join( + e.get("delta") or "" + for e in events + if e["type"] in ("TOOL_CALL_ARGS", "TOOL_CALL_CHUNK") and e.get("toolCallId", call_id) == call_id + ) + call = { + "id": call_id, + "type": "function", + "function": {"name": started["toolCallName"], "arguments": arguments or "{}"}, + } + for e in events: + if e["type"] == "REASONING_ENCRYPTED_VALUE" and e.get("subtype") == "tool-call" and e.get("entityId") == call["id"]: + call["encryptedValue"] = e["encryptedValue"] + return call + + +@contextmanager +def _serving(app) -> Iterator[str]: + """`app` on 127.0.0.1, also at OpenBot's model gateway addresses. Yields its base url.""" + import uvicorn + with socket.socket() as probe: probe.bind(("127.0.0.1", 0)) port = probe.getsockname()[1] + async def served(scope, receive, send): # Also at OpenBot's model gateway addresses (`gateway_environment`), as the gateway serves # each wire: `/api/model-provider/v1/...` and `/api/model-provider/anthropic/v1/...`. @@ -353,7 +607,7 @@ async def served(scope, receive, send): while not server.started and time.monotonic() < deadline: time.sleep(0.01) try: - yield f"http://127.0.0.1:{port}", bodies + yield f"http://127.0.0.1:{port}" finally: server.should_exit = True thread.join(timeout=10)