diff --git a/agent-adk/Dockerfile b/agent-adk/Dockerfile index 9d10294622..2dffe002d8 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/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.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 e97187fd5b..40175bab56 100644 --- a/agent-adk/src/main.py +++ b/agent-adk/src/main.py @@ -14,6 +14,7 @@ # 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 empty_turns import without_empty_turns from progress_reminder import with_litellm_reminders from model_providers import bot_settings, litellm_model_id from run_model_key import RunModelKey @@ -40,17 +41,19 @@ class RemindingLiteLLMClient(LiteLLMClient): - """Reminds the model to say a line after five silent tool steps in a row. - - Applied to the messages each call sends (shared/progress_reminder.py), after ADK has - built them from the session: the session, the run's events and the thread the person sees - never hold it. + """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. + + Applied to the messages each call sends, after ADK has built them from the session: a step + with no words goes as no words, never as LiteLLM's "[System: Empty message content sanitised + to satisfy protocol]" (shared/empty_turns.py), and then the reminder is placed + (shared/progress_reminder.py). The session, the run's events and the thread the person sees + never hold either. """ async def acompletion(self, model, messages, tools, **kwargs): - return await super().acompletion( - model=model, messages=with_litellm_reminders(messages, model), tools=tools, **kwargs - ) + sent = with_litellm_reminders(without_empty_turns(messages), model) + return await super().acompletion(model=model, messages=sent, tools=tools, **kwargs) class CompleteToolCallsLiteLlm(LiteLlm): diff --git a/agent-adk/tests/test_progress_reminder.py b/agent-adk/tests/test_progress_reminder.py index 3889ca5ad2..87df34bfb8 100644 --- a/agent-adk/tests/test_progress_reminder.py +++ b/agent-adk/tests/test_progress_reminder.py @@ -173,8 +173,9 @@ def assistant(message_id): return [*before, *added] -def run_job(monkeypatch, provider, model, steps, lines=()): - """One job, run to its answer the way the server runs it. Returns each run's raw stream.""" +def run_job(monkeypatch, provider, model, steps, lines=(), earlier=()): + """One job, run to its answer the way the server runs it, after the `earlier` messages of the + thread. Returns each run's raw stream.""" base, state = provider state["script"] = lambda index: ( {"text": LINE if index + 1 in lines else None, "call": (f"call_{index + 1}", {"id": f"R{index + 1}"})} @@ -197,6 +198,7 @@ def run_job(monkeypatch, provider, model, steps, lines=()): client = TestClient(importlib.reload(main).app) messages = [ {"id": "standing-role:bot", "role": "system", "content": "You are Ledger Bot."}, + *earlier, {"id": "u1", "role": "user", "content": "Go through the ledger from R1 to the end."}, ] streams = [] @@ -323,3 +325,44 @@ def test_every_model_is_reminded_in_the_form_it_takes(monkeypatch, provider, mod ) assert requests[5]["messages"][at] == expected assert_never_shown(streams) + + +SANITISED = "[System: Empty message content sanitised to satisfy protocol]" + +# An earlier job in the thread, whose step was saved with LiteLLM's placeholder for its words. +EARLIER = [ + {"id": "u0", "role": "user", "content": "Read record R0."}, + {"id": "a0", "role": "assistant", "content": SANITISED, "toolCalls": [ + {"id": "call_0", "type": "function", "function": {"name": TOOL["name"], "arguments": '{"id": "R0"}'}}, + ]}, + {"id": "result-call_0", "role": "tool", "toolCallId": "call_0", "content": '{"id": "R0", "status": "paid"}'}, + {"id": "a0-answer", "role": "assistant", "content": "R0 is paid."}, +] + + +def test_a_step_with_no_words_reaches_claude_as_its_tool_call_and_nothing_said(monkeypatch, provider): + """A step that only called a tool is sent to Claude as that call, with no words in front of it, + in this job and in a thread from before. + + LiteLLM sends Claude an empty turn as "[System: Empty message content sanitised to satisfy + protocol]", as though the model had said it (BerriAI/litellm#24498), and Claude copies it from + its own history and says it to the person. Every LiteLLM Bot sends its steps through one rule, + shared/empty_turns.py, which also takes the placeholder out of a thread that already holds it. + """ + requests, streams = run_job( + monkeypatch, provider, "anthropic/claude-sonnet-5-5", steps=7, earlier=EARLIER + ) + for index, request in enumerate(requests): + assert "sanitised to satisfy protocol" not in json.dumps(request), ( + f"request {index} puts words in the model's mouth" + ) + # The earlier step and each of this job's silent steps went out as just its call. + steps = [ + content for m in requests[-1]["messages"] if m["role"] == "assistant" + for content in [m["content"]] + if isinstance(content, list) and any(block["type"] == "tool_use" for block in content) + ] + assert len(steps) == 8 + assert all([block["type"] for block in content] == ["tool_use"] for content in steps), steps + assert len(reminders_in(requests[5])) == 1, "the stretch was counted as silent" + assert_never_shown(streams) diff --git a/agent-agno/Dockerfile b/agent-agno/Dockerfile index 281da2e41e..c7a13e181e 100644 --- a/agent-agno/Dockerfile +++ b/agent-agno/Dockerfile @@ -9,7 +9,7 @@ COPY agent-agno/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY agent-agno/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/progress_reminder.py shared/empty_turns.py /shared/ ENV PORT=4203 EXPOSE 4203 diff --git a/agent-agno/src/sent.py b/agent-agno/src/sent.py index fdda6bcb85..c110603782 100644 --- a/agent-agno/src/sent.py +++ b/agent-agno/src/sent.py @@ -5,11 +5,11 @@ `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`). +and each copy, being a line, started the reminder's count again. So each call is sent through the +rule every LiteLLM Bot shares (`shared/empty_turns.py`): a step that only called a tool goes as just +that call, 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. 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`). @@ -23,42 +23,10 @@ from typing import Any +from empty_turns import without_empty_turns 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) + return with_litellm_reminders(without_empty_turns(messages), model_id) diff --git a/agent-crewai/Dockerfile b/agent-crewai/Dockerfile index f49e8e0f92..9e5e7bed6a 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/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.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 9b2981eecb..87c9bea648 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -19,6 +19,7 @@ # 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 empty_turns import without_empty_turns from progress_reminder import with_litellm_reminders from model_providers import bot_settings, litellm_model_id from run_model_key import RunModelKey @@ -170,9 +171,13 @@ async def answer(self): model = _model() response = await acompletion( model=model, - # After five silent tool steps in a row, a reminder to say a line, in what the model - # is sent only (shared/progress_reminder.py). - messages=with_litellm_reminders(_provider_messages(messages), model), + # Each step with only the words the model said, never LiteLLM's "[System: Empty + # message content sanitised to satisfy protocol]" (shared/empty_turns.py), and after + # five silent tool steps in a row a reminder to say a line, in what the model is sent + # only (shared/progress_reminder.py). + messages=with_litellm_reminders( + without_empty_turns(_provider_messages(messages)), model + ), tools=self.state.get("tools") or None, stream=False, ) diff --git a/agent-crewai/tests/test_progress_reminder.py b/agent-crewai/tests/test_progress_reminder.py index 8b5436b306..6c5d0ee1cd 100644 --- a/agent-crewai/tests/test_progress_reminder.py +++ b/agent-crewai/tests/test_progress_reminder.py @@ -172,8 +172,9 @@ def assistant(message_id): return [*before, *added] -def run_job(monkeypatch, provider, model, steps, lines=()): - """One job, run to its answer the way the server runs it. Returns each run's raw stream.""" +def run_job(monkeypatch, provider, model, steps, lines=(), earlier=()): + """One job, run to its answer the way the server runs it, after the `earlier` messages of the + thread. Returns each run's raw stream.""" base, state = provider state["script"] = lambda index: ( {"text": LINE if index + 1 in lines else None, "call": (f"call_{index + 1}", {"id": f"R{index + 1}"})} @@ -194,6 +195,7 @@ def run_job(monkeypatch, provider, model, steps, lines=()): client = TestClient(main.app) messages = [ {"id": "standing-role:bot", "role": "system", "content": "You are Ledger Bot."}, + *earlier, {"id": "u1", "role": "user", "content": "Go through the ledger from R1 to the end."}, ] streams = [] @@ -323,3 +325,44 @@ def test_every_model_is_reminded_in_the_form_it_takes(monkeypatch, provider, mod ) assert requests[5]["messages"][at] == expected assert_never_shown(streams) + + +SANITISED = "[System: Empty message content sanitised to satisfy protocol]" + +# An earlier job in the thread, whose step was saved with LiteLLM's placeholder for its words. +EARLIER = [ + {"id": "u0", "role": "user", "content": "Read record R0."}, + {"id": "a0", "role": "assistant", "content": SANITISED, "toolCalls": [ + {"id": "call_0", "type": "function", "function": {"name": TOOL["name"], "arguments": '{"id": "R0"}'}}, + ]}, + {"id": "result-call_0", "role": "tool", "toolCallId": "call_0", "content": '{"id": "R0", "status": "paid"}'}, + {"id": "a0-answer", "role": "assistant", "content": "R0 is paid."}, +] + + +def test_a_step_with_no_words_reaches_claude_as_its_tool_call_and_nothing_said(monkeypatch, provider): + """A step that only called a tool is sent to Claude as that call, with no words in front of it, + in this job and in a thread from before. + + LiteLLM sends Claude an empty turn as "[System: Empty message content sanitised to satisfy + protocol]", as though the model had said it (BerriAI/litellm#24498), and Claude copies it from + its own history and says it to the person. Every LiteLLM Bot sends its steps through one rule, + shared/empty_turns.py, which also takes the placeholder out of a thread that already holds it. + """ + requests, streams = run_job( + monkeypatch, provider, "anthropic/claude-sonnet-5-5", steps=7, earlier=EARLIER + ) + for index, request in enumerate(requests): + assert "sanitised to satisfy protocol" not in json.dumps(request), ( + f"request {index} puts words in the model's mouth" + ) + # The earlier step and each of this job's silent steps went out as just its call. + steps = [ + content for m in requests[-1]["messages"] if m["role"] == "assistant" + for content in [m["content"]] + if isinstance(content, list) and any(block["type"] == "tool_use" for block in content) + ] + assert len(steps) == 8 + assert all([block["type"] for block in content] == ["tool_use"] for content in steps), steps + assert len(reminders_in(requests[5])) == 1, "the stretch was counted as silent" + assert_never_shown(streams) diff --git a/agent-langroid/Dockerfile b/agent-langroid/Dockerfile index e4f2e86723..2b577092c5 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/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/progress_reminder.py shared/empty_turns.py /shared/ ENV PORT=4209 EXPOSE 4209 diff --git a/agent-langroid/src/frontend_tools.py b/agent-langroid/src/frontend_tools.py index 0eeb9a07ab..1a844c2db3 100644 --- a/agent-langroid/src/frontend_tools.py +++ b/agent-langroid/src/frontend_tools.py @@ -13,6 +13,7 @@ from ag_ui_langroid import LangroidAgent from langroid import ChatAgent, ChatAgentConfig, ChatDocument, ToolMessage from langroid.language_models.base import LLMFunctionSpec, LLMMessage, OpenAIToolCall, Role +from empty_turns import without_empty_turns, words from progress_reminder import ( CALLED, OTHER, @@ -59,7 +60,8 @@ def _kind(message) -> str: return RESULT if role != "assistant": return OTHER - if _text(getattr(message, "content", None)).strip(): + # Words as sent (shared/empty_turns.py): LiteLLM's placeholder in a thread from before is none. + if words(_text(getattr(message, "content", None))) is not None: return SAID return CALLED if getattr(message, "tool_calls", None) else QUIET @@ -121,9 +123,30 @@ def _messages(input_data: RunAgentInput, system_message: str, form: str) -> list return messages +def _sending_words_as_said(llm) -> None: + """Each request `llm` builds sends every step with only the words the model said. + + Langroid writes a step that only called a tool with "" for its words, and LiteLLM sends Claude + a "" turn as "[System: Empty message content sanitised to satisfy protocol]", as though the + model had said it. Live, Claude Sonnet 5.5 copied it from its own history and said it to the + person 4 or 5 times on a 30-step job. The request's chat messages go through the rule every + LiteLLM Bot shares (shared/empty_turns.py) once Langroid has built them, for every route, + streamed or not; Langroid's own messages are left as they were. + """ + prepare = llm._prep_chat_completion + + def prepare_words_as_said(*args, **kwargs): + request = prepare(*args, **kwargs) + request["messages"] = without_empty_turns(request["messages"]) + return request + + llm._prep_chat_completion = prepare_words_as_said + + class _RequestAgent(ChatAgent): def __init__(self, config: ChatAgentConfig): super().__init__(config) + _sending_words_as_said(self.llm) self.input_messages: list[LLMMessage] = [] self.response_ids: list[str] = [] self.words: list[str] = [] diff --git a/agent-langroid/tests/test_progress_reminder.py b/agent-langroid/tests/test_progress_reminder.py index a27fc3ed69..d37298e9b2 100644 --- a/agent-langroid/tests/test_progress_reminder.py +++ b/agent-langroid/tests/test_progress_reminder.py @@ -311,3 +311,27 @@ def test_an_openai_model_is_reminded_with_a_system_message(monkeypatch, model): assert sent[at - 1]["role"] == "tool" assert sent[at] == {"role": "system", "content": REMINDER} assert_never_shown(events) + + +SANITISED = "sanitised to satisfy protocol" + + +def test_a_silent_step_reaches_claude_as_its_tool_call_and_nothing_said(monkeypatch): + """A step that only calls a tool is sent to Claude as that call, with no words in front of it. + + The thread hands back a step that only called a tool with empty words, and LiteLLM sends Claude + an empty turn as "[System: Empty message content sanitised to satisfy protocol]", as though the + model had said it (BerriAI/litellm#24498). Claude then copies the line from its own history and + says it to the person, and each copy, being a line, starts the reminder's count again. + """ + requests, events = run_job(monkeypatch, steps=7) + for index, request in enumerate(requests): + assert SANITISED not in json.dumps(request), f"request {index} puts words in the model's mouth" + # Each silent step went out as just its call. + steps = [m["content"] for m in requests[-1]["messages"] if m["role"] == "assistant"] + assert len(steps) == 7 + assert all( + [block["type"] for block in content] == ["tool_use"] for content in steps + ), steps + assert len(reminders_in(requests[5])) == 1, "the stretch was counted as silent" + assert SANITISED not in json.dumps(events) diff --git a/agent-llamaindex/Dockerfile b/agent-llamaindex/Dockerfile index 52d9070a32..5d8c5c5635 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/progress_reminder.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/progress_reminder.py shared/empty_turns.py /shared/ ENV PORT=4204 EXPOSE 4204 diff --git a/agent-llamaindex/src/sent.py b/agent-llamaindex/src/sent.py index 670f25e329..6ec322c234 100644 --- a/agent-llamaindex/src/sent.py +++ b/agent-llamaindex/src/sent.py @@ -30,6 +30,7 @@ import re from typing import Any, Sequence +from empty_turns import SANITISED, words from llama_index.core.llms import ChatMessage, MessageRole, TextBlock from progress_reminder import ( CALLED, @@ -61,22 +62,32 @@ def _as_tool_call(call: dict[str, Any]) -> dict[str, Any]: } -def _native(message: ChatMessage) -> ChatMessage: - """One message of the thread as the model should see it.""" +def _native(message: ChatMessage) -> ChatMessage | None: + """One message of the thread as the model should see it, or `None` when it is not sent.""" kwargs = message.additional_kwargs - calls = kwargs.get("ag_ui_tool_calls") - if message.role == MessageRole.ASSISTANT and calls and not kwargs.get("tool_calls"): - words = _CALL_AS_TEXT.sub("", _words(message)).strip() - sent: dict[str, Any] = {"tool_calls": [_as_tool_call(call) for call in calls]} - if not words: - # A step that only called a tool goes as just that call. LlamaIndex's LiteLLM client - # writes a message with no words as "" (and then lays these keys over the message), - # and LiteLLM sends Claude a "" turn as "[System: Empty message content sanitised to - # satisfy protocol]", as though the model had said it. Claude Sonnet 5.5 then said it - # to the person, live, on 5 or 6 steps of a 30-step job. `None` is no words, and is - # sent as none. - sent["content"] = None - return ChatMessage(role=MessageRole.ASSISTANT, content=words or None, additional_kwargs=sent) + if message.role == MessageRole.ASSISTANT and not kwargs.get("tool_calls"): + # The step's own words, read as every LiteLLM Bot reads them (`shared/empty_turns.py`): + # without LiteLLM's "[System: Empty message content sanitised to satisfy protocol]", and + # `None` when there are none. + text = _words(message) + said = words(_CALL_AS_TEXT.sub("", text)) + calls = kwargs.get("ag_ui_tool_calls") + if calls: + sent: dict[str, Any] = {"tool_calls": [_as_tool_call(call) for call in calls]} + if said is None: + # A step that only called a tool goes as just that call. LlamaIndex's LiteLLM + # client writes a message with no words as "" (and then lays these keys over the + # message), and LiteLLM sends Claude a "" turn as the placeholder, as though the + # model had said it. Claude Sonnet 5.5 then said it to the person, live, on 5 or 6 + # steps of a 30-step job. `None` is no words, and is sent as none. + sent["content"] = None + return ChatMessage(role=MessageRole.ASSISTANT, content=said, additional_kwargs=sent) + if said is None and all(isinstance(block, TextBlock) for block in message.blocks): + # Neither words nor calls: LiteLLM would send it as the placeholder. + return None + if said is not None and SANITISED in text: + return ChatMessage(role=MessageRole.ASSISTANT, content=said, additional_kwargs=kwargs) + return message if message.role == MessageRole.USER and kwargs.get("tool_call_id"): return ChatMessage( role=MessageRole.TOOL, @@ -101,7 +112,7 @@ def _kind(message: ChatMessage) -> str: def as_sent(messages: Sequence[ChatMessage], model_id: str) -> list[ChatMessage]: """What one model call is sent. A new list; the messages given are left as they were.""" - sent = [_native(message) for message in messages] + sent = [native for native in (_native(message) for message in messages) if native is not None] places = set(reminder_places([_kind(message) for message in sent], join_steps=False)) if not places: return sent diff --git a/agent-strands/Dockerfile b/agent-strands/Dockerfile index 534b1eb8a0..6046e687b1 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/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.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 a3f9743a5c..6200acc21a 100644 --- a/agent-strands/src/main.py +++ b/agent-strands/src/main.py @@ -9,6 +9,7 @@ # 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 empty_turns import without_empty_turns from model_providers import bot_settings, litellm_model_id from run_model_key import RunModelKey @@ -39,6 +40,20 @@ def _model_id() -> str: return litellm_model_id(provider, model) +class WordsAsSaid(LiteLLMModel): + """LiteLLM, sending each step with only the words the model said. + + A step with no words goes as no words, never as LiteLLM's "[System: Empty message content + sanitised to satisfy protocol]", which Claude would read as its own line and say again + (`shared/empty_turns.py`). Only the request each call sends changes: the agent's messages are + left as they were. + """ + + def format_request(self, messages, *args, **kwargs): + request = super().format_request(messages, *args, **kwargs) + return {**request, "messages": without_empty_turns(request["messages"])} + + app = FastAPI() # Each run's model calls carry its own gateway token, in its organization. See run_model_key.py. app.add_middleware(RunModelKey) @@ -89,7 +104,7 @@ async def run(self, input_data, *, invocation_state=None): app, WithoutForwardedProps( name="openbot", - agent=Agent(model=LiteLLMModel(model_id=_model_id())), + agent=Agent(model=WordsAsSaid(model_id=_model_id())), hooks=[RunSystemPrompt(), ProgressReminder()], ), "/", diff --git a/agent-strands/tests/test_progress_reminder.py b/agent-strands/tests/test_progress_reminder.py index dc9f9f6ecf..a1aa2eb453 100644 --- a/agent-strands/tests/test_progress_reminder.py +++ b/agent-strands/tests/test_progress_reminder.py @@ -10,6 +10,7 @@ """ import importlib +import json import sys from pathlib import Path @@ -33,7 +34,7 @@ TOKEN = "job-token" -def _job(monkeypatch, environment, model, steps, lines=None): +def _job(monkeypatch, environment, model, steps, lines=None, earlier=None): with scripted_provider(steps, lines) as (base, bodies): monkeypatch.delenv("OPENAI_API_BASE", raising=False) monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) @@ -48,7 +49,7 @@ def post(body): assert response.status_code == 200, response.text return response.text - streamed = run_job(post, model=model) + streamed = run_job(post, model=model, earlier=earlier) return bodies, streamed @@ -116,3 +117,44 @@ def test_every_model_is_reminded_in_the_turn_right_after_the_results(monkeypatch assert sent[calls + 1].get("tool_call_id") == call_id(5), sent[calls + 1] assert holder == calls + 2, sent[calls:] check_never_shown(streamed) + + +SANITISED = "[System: Empty message content sanitised to satisfy protocol]" + +# An earlier job in the thread, whose step was saved with LiteLLM's placeholder for its words. +EARLIER = [ + {"id": "u0", "role": "user", "content": "Read record R0."}, + {"id": "a0", "role": "assistant", "content": SANITISED, "toolCalls": [ + {"id": "call_0", "type": "function", "function": {"name": "read_record", "arguments": '{"id": "R0"}'}}, + ]}, + {"id": "result-call_0", "role": "tool", "toolCallId": "call_0", "content": "R0: paid."}, + {"id": "a0-answer", "role": "assistant", "content": "R0 is paid."}, +] + + +def test_a_step_with_no_words_reaches_claude_as_its_tool_call_and_nothing_said(monkeypatch): + """A step that only called a tool is sent to Claude as that call, with no words in front of it, + in this job and in a thread from before. + + LiteLLM sends Claude an empty turn as "[System: Empty message content sanitised to satisfy + protocol]", as though the model had said it (BerriAI/litellm#24498), and Claude copies it from + its own history and says it to the person. Every LiteLLM Bot sends its steps through one rule, + shared/empty_turns.py, which also takes the placeholder out of a thread that already holds it. + """ + bodies, streamed = _job( + monkeypatch, anthropic_environment, "claude-sonnet-5-5", 7, earlier=EARLIER + ) + for index, body in enumerate(bodies): + assert "sanitised to satisfy protocol" not in json.dumps(body), ( + f"request {index} puts words in the model's mouth" + ) + # The earlier step and each of this job's silent steps went out as just its call. + steps = [ + content for m in bodies[-1]["messages"] if m["role"] == "assistant" + for content in [m["content"]] + if isinstance(content, list) and any(block["type"] == "tool_use" for block in content) + ] + assert len(steps) == 8 + assert all([block["type"] for block in content] == ["tool_use"] for content in steps), steps + assert reminders_in(bodies[5]) == [5], "the stretch was counted as silent" + check_never_shown(streamed) diff --git a/shared/empty_turns.py b/shared/empty_turns.py new file mode 100644 index 0000000000..0e8753dcbd --- /dev/null +++ b/shared/empty_turns.py @@ -0,0 +1,75 @@ +"""No words is no words: how every Bot that calls its model through LiteLLM sends the model's own +earlier steps. + +THE PLACEHOLDER. LiteLLM sends Claude every user or assistant turn with empty text (`""`, or a text +part of `""`) as "[System: Empty message content sanitised to satisfy protocol]" +(`_sanitize_empty_text_content` in `litellm/litellm_core_utils/prompt_templates/factory.py`, +BerriAI/litellm#24498), since the Messages API refuses empty text. In an assistant turn that reads +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, several times on a 30-step job, and each copy, being a line, started the +progress reminder's count again (`progress_reminder.py`). + +THE RULE, the same for every LiteLLM Bot. In what one model call is sent: + +- a step that only called a tool goes as just that call: its content is `None`, which LiteLLM sends + as no words at all; +- a message of the model's with neither words nor calls is left out; +- the placeholder in a thread from before is taken out, so the model is not taught it again, and a + step left with no words by that goes as above. + +Only the model's own messages change, and only in what is sent: the Bot's thread, its events and +the thread the person sees are left as they were. Each Bot applies it where it hands LiteLLM its +chat messages, before the progress reminder is placed, so the placeholder never counts as a line. +The LlamaIndex Bot, whose messages are LlamaIndex's own, reads each step's words through `words`. +""" + +from __future__ import annotations + +from typing import Any + +# What LiteLLM writes in place of an empty turn it sends Claude. +SANITISED = "[System: Empty message content sanitised to satisfy protocol]" + + +def _empty_text_part(part: Any) -> bool: + return ( + isinstance(part, dict) + and part.get("type") == "text" + and not str(part.get("text") or "").replace(SANITISED, "").strip() + ) + + +def words(content: Any) -> Any: + """`content` without the placeholder, or `None` when it holds no words. + + A string comes back stripped; a list of parts comes back without its empty text parts, and with + the placeholder taken out of the rest. Anything else (`None`) is no words. + """ + if isinstance(content, str): + text = content.replace(SANITISED, "").strip() + return text or None + if isinstance(content, list): + parts = [ + {**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 _empty_text_part(part) + ] + return parts or None + return None + + +def step(message: dict[str, Any]) -> dict[str, Any] | None: + """One LiteLLM chat message as it is sent, or `None` when it is not sent at all.""" + if message.get("role") != "assistant": + return message + content = words(message.get("content")) + if content is None and not message.get("tool_calls"): + return None + return {**message, "content": content} + + +def without_empty_turns(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: + """What one LiteLLM call is sent. A new list; the messages given are left as they were.""" + return [sent for sent in (step(message) for message in messages) if sent is not None] diff --git a/shared/progress_reminder.py b/shared/progress_reminder.py index 465fe5eef3..92437d9823 100644 --- a/shared/progress_reminder.py +++ b/shared/progress_reminder.py @@ -196,7 +196,8 @@ def with_litellm_reminders(messages: list[dict[str, Any]], model_id: str) -> lis """What one LiteLLM call is sent: `messages` with a reminder after each place in them. Every chat message is a step of its own here. A new list; `messages` and the dicts in it are - left as they were. + left as they were. The Bots pass messages already through `empty_turns.without_empty_turns`, + so LiteLLM's placeholder for an empty turn never counts as a line. """ places = set(reminder_places([_litellm_kind(message) for message in messages], join_steps=False)) if not places: diff --git a/shared/progress_reminder_contract.py b/shared/progress_reminder_contract.py index 1d398f6cb2..adbab6da54 100644 --- a/shared/progress_reminder_contract.py +++ b/shared/progress_reminder_contract.py @@ -231,14 +231,18 @@ def assistant(message_id: str) -> dict: return [*before, *added.values()] -def run_job(post: Callable[[dict], str], *, model: str, runs: int = 64) -> list[str]: +def run_job( + post: Callable[[dict], str], *, model: str, runs: int = 64, earlier: list[dict] | None = None +) -> list[str]: """Drives the job to its answer through `post` (one AG-UI run, its SSE body back). - Every run's handed-back call is answered with `result_of` its step and the whole thread sent - back. Returns each run's SSE body, for what the person would see. + The thread starts with the `earlier` messages, if any, before the job's question. Every run's + handed-back call is answered with `result_of` its step and the whole thread sent back. Returns + each run's SSE body, for what the person would see. """ messages: list[dict] = [ {"id": "standing-role:job-bot", "role": "system", "content": "You are Ledger Bot."}, + *(earlier or []), {"id": "u1", "role": "user", "content": QUESTION}, ] streamed: list[str] = []