diff --git a/agent-agno/src/main.py b/agent-agno/src/main.py index 7f068e8939..05551b39d9 100644 --- a/agent-agno/src/main.py +++ b/agent-agno/src/main.py @@ -14,7 +14,6 @@ # 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 progress_reminder import with_litellm_reminders from model_providers import bot_settings, litellm_model_id from run_model_key import RunModelKey @@ -27,6 +26,8 @@ from .conversation import PausedRunsDb, add_run_context from .conversation import install as answer_from_the_whole_thread +from .said_once import install as say_each_line_once +from .sent import as_sent TOKEN_HEADER = "x-openbot-agent-token" # Agno-internal metadata serialized into every `Function.to_dict()` (`agno.tools.function.SERIALIZED_FIELDS`). @@ -38,14 +39,13 @@ @dataclass class _CleanToolsLiteLLM(LiteLLM): - """LiteLLM model that strips Agno-internal metadata from outgoing tool schemas, and reminds the - model to say a line after five silent tool steps in a row (shared/progress_reminder.py). - The reminder is only in the messages each call sends; Agno's own run messages never hold it.""" + """LiteLLM model that strips Agno-internal metadata from outgoing tool schemas, sends each step + with only the words the model said, and reminds the model to say a line after five silent tool + steps in a row (`sent.py`). Both are only in the messages each call sends; Agno's own run + messages never hold them.""" def _format_messages(self, messages, compress_tool_results=False): - return with_litellm_reminders( - super()._format_messages(messages, compress_tool_results), self.id - ) + return as_sent(super()._format_messages(messages, compress_tool_results), self.id) def _format_tools(self, tools): formatted = super()._format_tools(tools) @@ -91,6 +91,8 @@ def _sampling() -> dict: # Before the app is built: Agno's AG-UI router would otherwise send the model only the newest line. answer_from_the_whole_thread(_model_id()) +# And a line said alongside a tool call streams once, not again with the paused call. +say_each_line_once() agent = Agent( # In memory, because a Bot's history lives in OpenBot's database and not in the harness. Two diff --git a/agent-agno/src/said_once.py b/agent-agno/src/said_once.py new file mode 100644 index 0000000000..d269bfbc75 --- /dev/null +++ b/agent-agno/src/said_once.py @@ -0,0 +1,44 @@ +"""Each line the Bot says reaches the person once. + +When a run pauses on a client tool, Agno's AG-UI stream ends with a new assistant message holding +the paused calls, and with the run's text as that message's words +(`agno/os/interfaces/agui/handlers.py`, `on_run_completed`). That text has already streamed, as it +came, in the message the model's step opened. So every line the model said alongside a tool call +reached the person twice, as two messages: on a long job, every progress line was doubled. + +Instead the paused calls go on the message the step already streamed, as Agno does for a call it +runs itself (`on_tool_call_started`), and no second copy of the words is sent. `process_completion` +looks `on_run_completed` up in its module on every run, which is the seam `install` replaces; +`agent-agno/tests/test_said_once.py` fails if an Agno upgrade moves it. +""" + +import dataclasses + +from ag_ui.core import EventType +from agno.os.interfaces.agui import handlers +from agno.run.agent import RunPausedEvent +from agno.run.team import RunPausedEvent as TeamRunPausedEvent + +_agno_on_run_completed = handlers.on_run_completed + + +def on_run_completed(chunk, state): + streamed = state.text_message_id + if not isinstance(chunk, (RunPausedEvent, TeamRunPausedEvent)) or not streamed: + return _agno_on_run_completed(chunk, state) + events = _agno_on_run_completed(dataclasses.replace(chunk, content=None), state) + # The message Agno made for the paused calls: the only one it starts here. + made = next((e.message_id for e in events if e.type == EventType.TEXT_MESSAGE_START), None) + kept = [] + for event in events: + if event.type in (EventType.TEXT_MESSAGE_START, EventType.TEXT_MESSAGE_END): + if event.message_id == made: + continue + if event.type == EventType.TOOL_CALL_START and event.parent_message_id == made: + event = event.model_copy(update={"parent_message_id": streamed}) + kept.append(event) + return kept + + +def install() -> None: + handlers.on_run_completed = on_run_completed diff --git a/agent-agno/src/sent.py b/agent-agno/src/sent.py new file mode 100644 index 0000000000..fdda6bcb85 --- /dev/null +++ b/agent-agno/src/sent.py @@ -0,0 +1,64 @@ +"""What the model is sent on each call: each step with only the words the model said, and a +reminder to say a line on a long job. + +NO WORDS IS NONE. Agno's LiteLLM client writes a message with no words as "" (`_format_messages`, +`agno/models/litellm/chat.py`), and LiteLLM sends Claude an assistant turn of "" as "[System: Empty +message content sanitised to satisfy protocol]", as though the model had said it. Claude Sonnet 5.5 +then copied it from its own history and said it to the person, live, 4 to 9 times on a 30-step job, +and each copy, being a line, started the reminder's count again. So a step that only called a tool +goes as just that call (`None`, which is sent as no words), a message with neither words nor calls +is not sent at all (Agno's AG-UI stream left one before each call, and LiteLLM fills it the same +way), and the placeholder in threads from before is sent as nothing, so the model is not taught it +again. The LlamaIndex Bot sends its steps the same way (`agent-llamaindex/src/sent.py`). + +A WORD NOW AND THEN ON A LONG JOB. After five silent tool steps in a row, the next model call is +sent a short reminder to say a line, right after the latest results (`shared/progress_reminder.py`). +It reads the messages as sent here, so the placeholder never counts as a line. + +Only what each call sends changes: Agno's run messages, its events and the thread the person sees +are left as they were. +""" + +from __future__ import annotations + +from typing import Any + +from progress_reminder import with_litellm_reminders + +# What LiteLLM writes in place of an empty turn it sends Claude (BerriAI/litellm#24498). +SANITISED = "[System: Empty message content sanitised to satisfy protocol]" + + +def _without_placeholder(content: Any) -> Any: + if isinstance(content, str): + return content.replace(SANITISED, "").strip() + if isinstance(content, list): + return [ + {**part, "text": part["text"].replace(SANITISED, "").strip()} + if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) + else part + for part in content + if not ( + isinstance(part, dict) + and part.get("type") == "text" + and not str(part.get("text") or "").replace(SANITISED, "").strip() + ) + ] + return content + + +def _step(message: dict[str, Any]) -> dict[str, Any] | None: + if message.get("role") != "assistant": + return message + content = _without_placeholder(message.get("content")) + if not content: + if not message.get("tool_calls"): + return None + content = None + return {**message, "content": content} + + +def as_sent(messages: list[dict[str, Any]], model_id: str) -> list[dict[str, Any]]: + """What one LiteLLM call is sent. A new list; the messages given are left as they were.""" + sent = [step for step in (_step(message) for message in messages) if step is not None] + return with_litellm_reminders(sent, model_id) diff --git a/agent-agno/tests/test_progress_reminder.py b/agent-agno/tests/test_progress_reminder.py index 1920558add..8022eab015 100644 --- a/agent-agno/tests/test_progress_reminder.py +++ b/agent-agno/tests/test_progress_reminder.py @@ -1,6 +1,6 @@ """A WORD NOW AND THEN ON A LONG JOB. Live, Claude Sonnet 5.5 on this Bot wrote one line on a 30-step job, three at best. After five silent tool steps in a row, the next model call is sent a short reminder to -say a line, right after the latest results (shared/litellm_progress_reminder.py). One per silent +say a line, right after the latest results (shared/progress_reminder.py). One per silent stretch, none on a short job, a line from the model starts the count again, and the person never sees it. @@ -306,6 +306,26 @@ def test_a_line_from_the_model_starts_the_count_again(monkeypatch, provider): assert_never_shown(streams) +def test_a_silent_step_reaches_claude_as_its_tool_call_and_nothing_said(monkeypatch, provider): + """A step that only calls a tool is sent to Claude as that call, with no words in front of it. + + Agno writes such a step with empty text, and LiteLLM sends Claude an empty turn as "[System: + Empty message content sanitised to satisfy protocol]", as though the model had said it. + Live, Claude Sonnet 5.5 copied the line from its own history and said it to the person 4 to 9 + times on a 30-step job, and each one, being a line, started the reminder's count again. + """ + requests, streams = run_job(monkeypatch, provider, "anthropic/claude-sonnet-5-5", steps=7) + for request in requests: + assert "sanitised to satisfy protocol" not in json.dumps(request) + # Each silent step went out as just its call. + silent = [m["content"] for m in requests[-1]["messages"] if m["role"] == "assistant"] + assert len(silent) == 7 + assert all([block["type"] for block in content] == ["tool_use"] for content in silent), silent + assert len(reminders_in(requests[5])) == 1, "the stretch was counted as silent" + for stream in streams: + assert "sanitised to satisfy protocol" not in stream + + @pytest.mark.parametrize( ("model", "form"), [("openai/gpt-4.1", "system"), ("openai/qwen/qwen3-8b", "turn")], diff --git a/agent-agno/tests/test_said_once.py b/agent-agno/tests/test_said_once.py new file mode 100644 index 0000000000..cefb5082e4 --- /dev/null +++ b/agent-agno/tests/test_said_once.py @@ -0,0 +1,98 @@ +"""What the person sees of a long job on Claude: each line once, and never LiteLLM's placeholder. + +Live, Claude Sonnet 5.5 on a 30-step job showed the person "[System: Empty message content +sanitised to satisfy protocol]" 4 to 9 times, and each progress line twice. Driven here as the +server drives a job (see test_progress_reminder.py), with real LiteLLM and Agno and only the +provider's HTTP answers scripted. +""" + +import importlib +import json + +from fastapi.testclient import TestClient +from test_progress_reminder import ( # noqa: F401 (`provider` is a fixture) + LINE, + TOKEN, + TOOL, + _events, + provider, + reminders_in, + run_job, +) + +SANITISED = "[System: Empty message content sanitised to satisfy protocol]" + + +def _said(stream): + """Every piece of text the stream sent the person, one entry per message.""" + words = {} + for event in _events(stream): + if event["type"] == "TEXT_MESSAGE_CONTENT": + words[event["messageId"]] = words.get(event["messageId"], "") + event["delta"] + return list(words.values()) + + +def test_a_line_said_alongside_a_tool_call_streams_once(monkeypatch, provider): + # Steps 2 and 4 say a line with their call; the others only call. + _, streams = run_job(monkeypatch, provider, "anthropic/claude-sonnet-5-5", steps=5, lines=(2, 4)) + said = [_said(stream) for stream in streams] + assert said[1] == [LINE], said[1] + assert said[3] == [LINE], said[3] + for index in (0, 2, 4): + assert said[index] == [], said[index] + # Each step is one message: its words, if any, with its call. + steps = [m for m in provider[1]["thread"] if m["role"] == "assistant"] + assert [(m["content"], [c["id"] for c in m.get("toolCalls") or []]) for m in steps] == [ + ("", ["call_1"]), + (LINE, ["call_2"]), + ("", ["call_3"]), + (LINE, ["call_4"]), + ("", ["call_5"]), + ("The total overdue is 5,305.", []), + ] + + +def test_a_thread_holding_the_placeholder_is_replayed_without_it(monkeypatch, provider): + """A thread from before the fix holds the placeholder as the Bot's own words, step after step. + + Replayed as it stands, it teaches the model to say it again. Each such step is a silent step, + so the reminder still comes after the fifth; the placeholder never counted as a line. + """ + base, state = provider + state["script"] = lambda index: {"text": "The total overdue is 5,305."} + messages = [ + {"id": "standing-role:bot", "role": "system", "content": "You are Ledger Bot."}, + {"id": "u1", "role": "user", "content": "Go through the ledger from R1 to the end."}, + ] + for step in range(1, 7): + call = {"id": f"call_{step}", "type": "function", + "function": {"name": TOOL["name"], "arguments": json.dumps({"id": f"R{step}"})}} + messages += [ + # What Agno's stream leaves before each call: a message with no words. + {"id": f"empty-{step}", "role": "assistant", "content": ""}, + {"id": f"a{step}", "role": "assistant", "content": SANITISED, "toolCalls": [call]}, + {"id": f"t{step}", "role": "tool", "toolCallId": f"call_{step}", "content": '{"status": "paid"}'}, + ] + monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) + monkeypatch.setenv("BOT_PROVIDER", "anthropic") + monkeypatch.setenv("BOT_MODEL", "claude-sonnet-5-5") + monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key") + monkeypatch.setenv("ANTHROPIC_BASE_URL", base) + monkeypatch.delenv("OPENAI_API_BASE", raising=False) + from src import main + + response = TestClient(importlib.reload(main).app).post( + "/agui", + headers={"x-openbot-agent-token": TOKEN}, + json={"threadId": "legacy", "runId": "run-legacy", "state": {}, "messages": messages, + "tools": [TOOL], "context": [], "forwardedProps": {}}, + ) + assert response.status_code == 200 + assert '"RUN_FINISHED"' in response.text + [request] = state["requests"] + assert SANITISED not in json.dumps(request) + steps = [m["content"] for m in request["messages"] if m["role"] == "assistant"] + assert len(steps) == 6 + assert all([block["type"] for block in content] == ["tool_use"] for content in steps), steps + assert len(reminders_in(request)) == 1, "six silent steps, reminded once" + assert _said(response.text) == ["The total overdue is 5,305."]