diff --git a/agent-adk/Dockerfile b/agent-adk/Dockerfile index 301a8f6d5b..9d10294622 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/litellm_progress_reminder.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/progress_reminder.py /shared/ ENV PORT=4208 EXPOSE 4208 diff --git a/agent-adk/src/main.py b/agent-adk/src/main.py index 9a056abe22..e97187fd5b 100644 --- a/agent-adk/src/main.py +++ b/agent-adk/src/main.py @@ -14,7 +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 litellm_progress_reminder import with_reminders +from progress_reminder import with_litellm_reminders from model_providers import bot_settings, litellm_model_id from run_model_key import RunModelKey @@ -42,14 +42,14 @@ 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/litellm_progress_reminder.py), after ADK has + 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. """ async def acompletion(self, model, messages, tools, **kwargs): return await super().acompletion( - model=model, messages=with_reminders(messages, model), tools=tools, **kwargs + model=model, messages=with_litellm_reminders(messages, model), tools=tools, **kwargs ) diff --git a/agent-ag2/Dockerfile b/agent-ag2/Dockerfile index f8dee3f5b4..c78a335166 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/silent_steps.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/progress_reminder.py /shared/ ENV PORT=4210 EXPOSE 4210 diff --git a/agent-ag2/src/progress_reminder.py b/agent-ag2/src/progress_reminder.py index 65fbf5d859..4c8511e884 100644 --- a/agent-ag2/src/progress_reminder.py +++ b/agent-ag2/src/progress_reminder.py @@ -3,7 +3,7 @@ Measured live, Claude Sonnet 5.5 on this Bot wrote one or two lines on a 30-step 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; one per silent stretch, none on a short job (the rule and its source are in -shared/silent_steps.py). +shared/progress_reminder.py). It is AG2 middleware on the model call (`on_llm_call`), the hook AG2's own HistoryLimiter trims history in: what it hands on is only what that one call sends. The run's history, the events it @@ -27,14 +27,14 @@ ToolResultsEvent, ) from ag2.middleware import BaseMiddleware, LLMCall -from silent_steps import ( +from progress_reminder import ( + CALLED, OTHER, PERSON, QUIET, REMINDER_IN_TURN, RESULT, SAID, - SILENT, reminder_places, ) @@ -44,7 +44,7 @@ def _kind(event: BaseEvent) -> str: if isinstance(event, ModelResponse): if (event.content or "").strip(): return SAID - return SILENT if event.tool_calls.calls else QUIET + return CALLED if event.tool_calls.calls else QUIET if isinstance(event, (ToolResultsEvent, ToolResultEvent)): return RESULT # A run that carries tool results asks with an empty request: nobody said anything. @@ -55,7 +55,8 @@ def _kind(event: BaseEvent) -> str: def with_reminders(events: Sequence[BaseEvent]) -> list[BaseEvent]: """The history one model call is sent, with a reminder after each silent stretch.""" - after = set(reminder_places([_kind(event) for event in events])) + # Only ever after results: a call AG2 never answered gets no reminder after it. + after = set(reminder_places([_kind(event) for event in events], only_after_results=True)) sent: list[BaseEvent] = [] for index, event in enumerate(events): sent.append(event) diff --git a/agent-agno/Dockerfile b/agent-agno/Dockerfile index c5b42008db..281da2e41e 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/litellm_progress_reminder.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/progress_reminder.py /shared/ ENV PORT=4203 EXPOSE 4203 diff --git a/agent-agno/src/main.py b/agent-agno/src/main.py index 5c3450f1aa..7f068e8939 100644 --- a/agent-agno/src/main.py +++ b/agent-agno/src/main.py @@ -14,7 +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 litellm_progress_reminder import with_reminders +from progress_reminder import with_litellm_reminders from model_providers import bot_settings, litellm_model_id from run_model_key import RunModelKey @@ -39,11 +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/litellm_progress_reminder.py). + 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.""" def _format_messages(self, messages, compress_tool_results=False): - return with_reminders(super()._format_messages(messages, compress_tool_results), self.id) + return with_litellm_reminders( + super()._format_messages(messages, compress_tool_results), self.id + ) def _format_tools(self, tools): formatted = super()._format_tools(tools) diff --git a/agent-crewai/Dockerfile b/agent-crewai/Dockerfile index e7e62d4865..f49e8e0f92 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/litellm_progress_reminder.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/progress_reminder.py /shared/ ENV PORT=4202 EXPOSE 4202 diff --git a/agent-crewai/src/main.py b/agent-crewai/src/main.py index db5c8806ab..9b2981eecb 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -19,7 +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 litellm_progress_reminder import with_reminders +from progress_reminder import with_litellm_reminders from model_providers import bot_settings, litellm_model_id from run_model_key import RunModelKey @@ -171,8 +171,8 @@ async def answer(self): 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/litellm_progress_reminder.py). - messages=with_reminders(_provider_messages(messages), model), + # is sent only (shared/progress_reminder.py). + messages=with_litellm_reminders(_provider_messages(messages), model), tools=self.state.get("tools") or None, stream=False, ) diff --git a/agent-langgraph-agui/Dockerfile b/agent-langgraph-agui/Dockerfile index e5aa276331..e78d16bfd1 100644 --- a/agent-langgraph-agui/Dockerfile +++ b/agent-langgraph-agui/Dockerfile @@ -9,7 +9,7 @@ COPY agent-langgraph-agui/requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY agent-langgraph-agui/src ./src -COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/progress_reminder.py /shared/ ENV PORT=4206 EXPOSE 4206 diff --git a/agent-langgraph-agui/src/progress_reminder.py b/agent-langgraph-agui/src/progress_reminder.py index 5017df7378..79418594c0 100644 --- a/agent-langgraph-agui/src/progress_reminder.py +++ b/agent-langgraph-agui/src/progress_reminder.py @@ -11,12 +11,12 @@ preserved thinking stay intact, and do not keep sending them to a turn that stays quiet, since frequent harness text after tool results reads as a possible prompt injection. -WHAT THIS BOT DOES. A step that calls tools and says nothing is a silent step. After five in a row, -the next model call is sent the reminder right after the fifth step's results. One per silent -stretch: the count starts again only when the model says a line (or the person speaks), so a job -that stays quiet hears it once, and a short job never. Each run carries the whole thread, so the -reminders are worked out from it on every call and land in the same places every time: nothing is -remembered between runs, and a reminder never moves once sent. +WHAT THIS BOT DOES. The rule, its count and its words are every Python Bot's, in +shared/progress_reminder.py: a step that calls tools and says nothing is a silent step, and after +five in a row the next model call is sent the reminder right after the fifth step's results, once +per silent stretch. What is this Bot's own is how LangChain's messages read as steps (each AI +message a step of its own; Claude's shown progress updates count as a line), that a reminder goes +in only when the model goes on after the results, and the form each LangChain chat model takes. The reminder is only in what the model is sent. The graph's state, the run's events and its snapshot do not carry it, so the person never sees it, and nothing else in the model's history @@ -31,6 +31,8 @@ """ import re +import sys +from pathlib import Path from langchain_core.messages import ( AIMessage, @@ -41,23 +43,22 @@ convert_to_messages, ) -# Silent tool steps in a row before the reminder, as Anthropic's example gives it. -SILENT_STEPS = 5 - -# Anthropic's wording, for the person rather than "the user", with the one case where no line is -# wanted: a run nobody is watching is told to write none while it works. -REMINDER = ( - "The person hasn't heard from you in a while: say in a few words what you're doing, then " - "continue. If your instructions say nobody is watching this run, just continue." -) - -# The same words in the person's turn, said to be the app's and not theirs. -REMINDER_IN_TURN = ( - "(A note from the app running this conversation, not a message from the person.) " + REMINDER +# The rule every Python Bot shares, imported here before main.py has put shared/ on the path. +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from progress_reminder import ( # noqa: E402 + CALLED, + OTHER, + PERSON, + QUIET, + REMINDER, + REMINDER_IN_TURN, + RESULT, + SAID, + SYSTEM, + TURN, + is_openai_model, ) - -SYSTEM = "system" -TURN = "turn" +from progress_reminder import reminder_places as _places # noqa: E402 # The Claude models that take a system message mid-conversation, as Anthropic lists them: Fable 5, # 5.1 and 5.2, Mythos 5, 5.1 and 5.2, Opus 5.5, Opus 5, Opus 4.8, Sonnet 5.5 and Haiku 5.5 (not @@ -68,9 +69,6 @@ r"|sonnet-5-5|haiku-5-5)(?!-\d{1,2}(?:\D|$))(?![a-z0-9.])" ) -# OpenAI's own models, which take a system or developer message anywhere in the thread. -_OPENAI_MODEL = re.compile(r"^(?:openai[:/])?(?:gpt-|chatgpt-|codex-|o\d)") - # The Claude addresses that refused a system message mid-thread, for the life of the process. _system_refused: set[str] = set() @@ -114,7 +112,7 @@ def reminder_form(model) -> str: except ImportError: return TURN if isinstance(model, ChatOpenAI): - return SYSTEM if _OPENAI_MODEL.match(_name(model).strip().lower()) else TURN + return SYSTEM if is_openai_model(_name(model)) else TURN return TURN @@ -179,6 +177,19 @@ def said_line(message: AIMessage, updates: bool) -> bool: return _words(message.content, updates).strip() != "" +def _kind(message: BaseMessage, updates: bool) -> str: + """What a LangChain message is, for the rule (its `type`, so a chunk is none of these).""" + if message.type == "human": + return PERSON + if message.type == "tool": + return RESULT + if message.type != "ai": + return OTHER + if said_line(message, updates): + return SAID + return CALLED if message.tool_calls else QUIET + + def reminder_places(messages, updates: bool) -> list[str]: """Where the reminders go: the call id of each result a reminder follows. @@ -186,39 +197,14 @@ def reminder_places(messages, updates: bool) -> list[str]: step answered and followed by the person's own words is left alone, since their turn starts the count again anyway. """ - places: list[str] = [] - silent = 0 - reminded = False - # The step whose results end with a reminder, once they are all in. - due = False - previous: BaseMessage | None = None - for message in convert_to_messages(messages): - kind = message.type - if due and kind != "tool": - if kind == "ai" and isinstance(previous, ToolMessage): - places.append(previous.tool_call_id) - due = False - previous = message - if kind == "human": - silent = 0 - reminded = False - continue - if kind != "ai": - continue - if said_line(message, updates): - silent = 0 - reminded = False - continue - if not message.tool_calls: - continue - silent += 1 - if silent >= SILENT_STEPS and not reminded: - due = True - reminded = True - # The latest results: the call about to be made is the first one sent the reminder. - if due and isinstance(previous, ToolMessage): - places.append(previous.tool_call_id) - return places + thread = convert_to_messages(messages) + places = _places( + [_kind(message, updates) for message in thread], + join_steps=False, + only_after_results=True, + only_before_model=True, + ) + return [thread[index].tool_call_id for index in places] def _reminder(form: str) -> BaseMessage: diff --git a/agent-langroid/Dockerfile b/agent-langroid/Dockerfile index ed0f692b1e..e4f2e86723 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/silent_steps.py /shared/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/progress_reminder.py /shared/ ENV PORT=4209 EXPOSE 4209 diff --git a/agent-langroid/src/frontend_tools.py b/agent-langroid/src/frontend_tools.py index eb3754a88e..0eeb9a07ab 100644 --- a/agent-langroid/src/frontend_tools.py +++ b/agent-langroid/src/frontend_tools.py @@ -13,7 +13,8 @@ from ag_ui_langroid import LangroidAgent from langroid import ChatAgent, ChatAgentConfig, ChatDocument, ToolMessage from langroid.language_models.base import LLMFunctionSpec, LLMMessage, OpenAIToolCall, Role -from silent_steps import ( +from progress_reminder import ( + CALLED, OTHER, PERSON, QUIET, @@ -21,7 +22,6 @@ REMINDER_IN_TURN, RESULT, SAID, - SILENT, is_openai_model, reminder_places, ) @@ -51,7 +51,7 @@ def _text(content) -> str: def _kind(message) -> str: - """What an AG-UI message is, for the reminder rule (silent_steps.py).""" + """What an AG-UI message is, for the reminder rule (shared/progress_reminder.py).""" role = getattr(message, "role", None) if role == "user": return PERSON @@ -61,7 +61,7 @@ def _kind(message) -> str: return OTHER if _text(getattr(message, "content", None)).strip(): return SAID - return SILENT if getattr(message, "tool_calls", None) else QUIET + return CALLED if getattr(message, "tool_calls", None) else QUIET def reminder_form(chat_model: str) -> str: @@ -78,7 +78,7 @@ def reminder_form(chat_model: str) -> str: if not route.startswith("litellm/openai/"): return "turn" model = route.removeprefix("litellm/openai/").removeprefix("responses/") - return "system" if is_openai_model(model) else "turn" + return "system" if is_openai_model(model, prefixed=False) else "turn" def _reminder(form: str) -> LLMMessage: @@ -90,11 +90,16 @@ def _reminder(form: str) -> LLMMessage: def _messages(input_data: RunAgentInput, system_message: str, form: str) -> list[LLMMessage]: """What the model is sent: the run's thread, with a reminder after a long silent stretch. - The reminders are worked out from the thread on every run (silent_steps.py), so each one lands - where it was first sent. They are only in what the model is sent: the events this run streams - come from the model's answer, never from these messages. + The reminders are worked out from the thread on every run (shared/progress_reminder.py), so + each one lands where it was first sent, and only ever after results. They are only in what the + model is sent: the events this run streams come from the model's answer, never from these + messages. """ - after = set(reminder_places([_kind(message) for message in input_data.messages])) + after = set( + reminder_places( + [_kind(message) for message in input_data.messages], only_after_results=True + ) + ) messages = [LLMMessage(role=Role.SYSTEM, content=system_message)] for index, message in enumerate(input_data.messages): content = getattr(message, "content", None) diff --git a/agent-microsoft/src/reminders.py b/agent-microsoft/src/reminders.py index 392119e48f..250761a71f 100644 --- a/agent-microsoft/src/reminders.py +++ b/agent-microsoft/src/reminders.py @@ -31,13 +31,12 @@ REMINDER_IN_TURN, RESULT, SAID, + SYSTEM, + TURN, is_openai_model, reminder_places, ) -SYSTEM = "system" -TURN = "turn" - def form_for(provider: str, model: str) -> str: """How this Bot's model is sent the reminder: `system` or `turn`.""" diff --git a/shared/litellm_progress_reminder.py b/shared/litellm_progress_reminder.py deleted file mode 100644 index 03a31a46c9..0000000000 --- a/shared/litellm_progress_reminder.py +++ /dev/null @@ -1,134 +0,0 @@ -"""A word now and then on a long job, for the Bots that call their model through LiteLLM. - -The Bot's instructions already ask for a line every so often on a long job. Measured live, that -was not enough on these Bots: Claude Sonnet 5.5 wrote one line or none on a 30-step job. Anthropic's -answer for a harness whose long tool-calling turns still go quiet (Prompting Claude Sonnet 5.5, -"User-facing progress updates", -https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#user-facing-progress-updates): -count consecutive tool-calling steps that send the person no text, and after several in a row, -for example five, append a one-turn reminder after the latest tool results. Leave each reminder in -place on later requests, so the prompt cache stays intact, and do not keep sending them to a turn -that stays quiet. The TypeScript engine does the same (agent-langgraph-ts/src/progress-reminder.ts), -in the same words. - -WHAT THIS DOES. A step that calls tools and says nothing is a silent step. After five in a row, the -next model call is sent the reminder right after the fifth step's results. One per silent stretch: -the count starts again only when the model says a line (or the person speaks), so a job that stays -quiet hears it once, and a short job never. The reminders are worked out from the messages of each -call, so they land in the same places every time: nothing is remembered between calls, and a -reminder never moves once sent. - -It is applied to the messages a LiteLLM call is about to send, in the chat format LiteLLM takes, -and nowhere else: the Bot's thread, its events and its snapshot never carry it, so the person never -sees it, and nothing else in the model's history changes. - -FOR EVERY MODEL, in the form it can be sent. LiteLLM moves every system message into the request's -system prompt for Claude and Gemini, so a system message there would land at the top and change -the cached prefix. Those models, and any other but OpenAI's own, get it in the person's turn, -saying it comes from the app; LiteLLM sends it in the same turn as the tool results. OpenAI's own -models take a system message anywhere in the thread, so they get one. -""" - -from __future__ import annotations - -import re -from typing import Any - -# Silent tool steps in a row before the reminder, as Anthropic's example gives it. -SILENT_STEPS = 5 - -# Anthropic's wording, for the person rather than "the user", with the one case where no line is -# wanted: a run nobody is watching is told to write none while it works. -REMINDER = ( - "The person hasn't heard from you in a while: say in a few words what you're doing, then" - " continue. If your instructions say nobody is watching this run, just continue." -) - -# The same words in the person's turn, said to be the app's and not theirs. -REMINDER_IN_TURN = ( - "(A note from the app running this conversation, not a message from the person.) " + REMINDER -) - -# OpenAI's own models, which take a system message anywhere in the thread. -_OPENAI_MODEL = re.compile(r"^(?:openai[:/])?(?:gpt-|chatgpt-|codex-|o\d)") - - -def reminder_form(model_id: str) -> str: - """`system` or `turn`: how the model LiteLLM addresses as `model_id` is sent the reminder.""" - provider, _, model = model_id.strip().lower().partition("/") - if provider == "openai" and _OPENAI_MODEL.match(model): - return "system" - return "turn" - - -def _said(message: dict[str, Any]) -> bool: - """Whether an assistant message says something to the person.""" - content = message.get("content") - if isinstance(content, str): - return bool(content.strip()) - if isinstance(content, list): - return any( - isinstance(part, dict) - and part.get("type") == "text" - and isinstance(part.get("text"), str) - and part["text"].strip() - for part in content - ) - return False - - -def reminder_places(messages: list[dict[str, Any]]) -> list[int]: - """The index of each message a reminder follows: the last result of a step that ended a stretch.""" - places: list[int] = [] - silent = 0 - reminded = False - # The step whose results end with a reminder, once they are all in. - due = False - for index, message in enumerate(messages): - role = message.get("role") - if due and role != "tool": - # Never between the results and the person's own next words: their turn starts again. - if role != "user": - places.append(index - 1) - due = False - if role == "user": - silent = 0 - reminded = False - continue - if role != "assistant": - continue - if _said(message): - silent = 0 - reminded = False - continue - if not message.get("tool_calls"): - continue - silent += 1 - if silent >= SILENT_STEPS and not reminded: - due = True - reminded = True - # The latest results: the call about to be made is the first one sent the reminder. - if due and messages and messages[-1].get("role") == "tool": - places.append(len(messages) - 1) - return places - - -def with_reminders(messages: list[dict[str, Any]], model_id: str) -> list[dict[str, Any]]: - """What one LiteLLM call is sent: `messages` with a reminder after each place in them. - - A new list; `messages` and the dicts in it are left as they were. - """ - places = set(reminder_places(messages)) - if not places: - return list(messages) - reminder = ( - {"role": "system", "content": REMINDER} - if reminder_form(model_id) == "system" - else {"role": "user", "content": REMINDER_IN_TURN} - ) - sent: list[dict[str, Any]] = [] - for index, message in enumerate(messages): - sent.append(message) - if index in places: - sent.append(dict(reminder)) - return sent diff --git a/shared/progress_reminder.py b/shared/progress_reminder.py index 7a1f099b70..465fe5eef3 100644 --- a/shared/progress_reminder.py +++ b/shared/progress_reminder.py @@ -1,10 +1,9 @@ -"""A word now and then on a long job: the rule the Python Bots share for when to remind the model. +"""A word now and then on a long job: the one rule every Python Bot reminds its model by. The Bot's instructions already ask for a line every so often on a long job. Measured live, that was -not enough on the Pydantic AI, Microsoft Agent Framework and Strands Bots: Claude Sonnet 5.5 wrote -one line, at the start, on a 30-step job (two at most on Strands). Anthropic's answer for a harness -whose long tool-calling turns still go quiet (Prompting Claude Sonnet 5.5, "User-facing progress -updates", +not enough: on a 30-step job Claude Sonnet 5.5 wrote three lines at most, and mostly one or none, +on the Python Bots. Anthropic's answer for a harness whose long tool-calling turns still go quiet +(Prompting Claude Sonnet 5.5, "User-facing progress updates", https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#user-facing-progress-updates): count consecutive tool-calling steps that send the person no text or progress update, and after several in a row, for example five, append a one-turn reminder after the latest tool results. @@ -22,13 +21,15 @@ run's events, its snapshot or the thread the person sees. Each Bot reads its own framework's messages into the kinds below, asks `reminder_places` where the -reminders go, and puts them there in the form its framework sends the model. +reminders go, and puts them there in the form its framework sends the model. The Bots that call +their model through LiteLLM (CrewAI, Agno, Google ADK) share one such reader, `with_litellm_reminders`, +since they all hand LiteLLM the same chat messages. """ from __future__ import annotations import re -from typing import Sequence +from typing import Any, Sequence # Silent tool steps in a row before the reminder, as Anthropic's example gives it. SILENT_STEPS = 5 @@ -51,34 +52,66 @@ SAID = "said" # the model, with words for the person (tool calls or not) CALLED = "called" # the model calling tools and saying nothing: a silent step QUIET = "quiet" # the model with neither words nor calls -OTHER = "other" # anything else: system rows and the like +OTHER = "other" # anything else: system rows, reasoning, an empty request and the like _MODEL = (SAID, CALLED, QUIET) -# OpenAI's own models, which take a system or developer message anywhere in the thread. -_OPENAI_MODEL = re.compile(r"^(?:openai[:/])?(?:gpt-|chatgpt-|codex-|o\d)") +# The two forms a reminder is sent in: a system message, or a note in the person's turn. +SYSTEM = "system" +TURN = "turn" +# OpenAI's own models, which take a system or developer message anywhere in the thread. +_OPENAI_MODEL = re.compile(r"^(?:gpt-|chatgpt-|codex-|o\d)") +_OPENAI_PREFIX = re.compile(r"^openai[:/]") -def is_openai_model(model: str) -> bool: - """Whether `model` is one of OpenAI's own, which take a system message mid-thread.""" - return bool(_OPENAI_MODEL.match((model or "").strip().lower())) +def is_openai_model(model: str, *, prefixed: bool = True) -> bool: + """Whether `model` is one of OpenAI's own, which take a system message mid-thread. -def reminder_places(kinds: Sequence[str]) -> list[int]: + With `prefixed`, an `openai:` or `openai/` in front is read past; without it, `model` is a bare + id and such a prefix makes it not one. + """ + name = (model or "").strip().lower() + if prefixed: + name = _OPENAI_PREFIX.sub("", name, count=1) + return bool(_OPENAI_MODEL.match(name)) + + +def _step(first: str, second: str) -> str: + """Two messages of the model's in a row, as one step: it said a line if either did.""" + if SAID in (first, second): + return SAID + if CALLED in (first, second): + return CALLED + return QUIET + + +def reminder_places( + kinds: Sequence[str], + *, + join_steps: bool = True, + only_after_results: bool = False, + only_before_model: bool = False, +) -> list[int]: """Where the reminders go: the index of each message a reminder follows. - `kinds` is the thread, one kind per message. Messages of the model's that come one after - another are one step (some integrations put a step's words and its calls in two messages), and - the step said a line if any of them did. A reminder follows the last result of the step that - ended a silent stretch, and never sits between those results and the person's own next words. + `kinds` is the thread, one kind per message. A reminder follows the last result of the step + that ended a silent stretch, and is never put between those results and the person's own next + words. How a Bot's framework lays out its thread decides the rest: + + - `join_steps`: messages of the model's that come one after another are one step, since some + integrations put a step's words and its calls in two messages; the step said a line if any of + them did. Off, every message of the model's is a step of its own. + - `only_after_results`: a reminder only ever follows results, so a step whose calls were never + answered gets none. + - `only_before_model`: a reminder only goes in when the model's own next message follows the + results; anything else there (a system row) drops it. """ - # The steps and everything else, each with the index of its last message. + # Each step, or other message, with the index of its last message. units: list[tuple[str, int]] = [] for index, kind in enumerate(kinds): - if kind in _MODEL and units and units[-1][0] in _MODEL and index == units[-1][1] + 1: - previous = units[-1][0] - merged = SAID if SAID in (previous, kind) else CALLED if CALLED in (previous, kind) else QUIET - units[-1] = (merged, index) + if join_steps and kind in _MODEL and units and units[-1][0] in _MODEL: + units[-1] = (_step(units[-1][0], kind), index) else: units.append((kind, index)) @@ -89,15 +122,13 @@ def reminder_places(kinds: Sequence[str]) -> list[int]: due = False for position, (kind, index) in enumerate(units): if due and kind != RESULT: + previous, last = units[position - 1] # Never between the results and the person's own next words: their turn starts again. - if kind != PERSON: - places.append(units[position - 1][1]) + allowed = kind in _MODEL if only_before_model else kind != PERSON + if allowed and (previous == RESULT or not only_after_results): + places.append(last) due = False - if kind == PERSON: - silent = 0 - reminded = False - continue - if kind == SAID: + if kind in (PERSON, SAID): silent = 0 reminded = False continue @@ -111,3 +142,73 @@ def reminder_places(kinds: Sequence[str]) -> list[int]: if due and units and units[-1][0] == RESULT: places.append(units[-1][1]) return places + + +# The Bots that call their model through LiteLLM. +# +# Applied to the messages a LiteLLM call is about to send, in the chat format LiteLLM takes, and +# nowhere else: the Bot's thread, its events and its snapshot never carry it, so the person never +# sees it, and nothing else in the model's history changes. +# +# FOR EVERY MODEL, in the form it can be sent. LiteLLM moves every system message into the +# request's system prompt for Claude and Gemini, so a system message there would land at the top +# and change the cached prefix. Those models, and any other but OpenAI's own, get it in the person's +# turn, saying it comes from the app; LiteLLM sends it in the same turn as the tool results. +# OpenAI's own models take a system message anywhere in the thread, so they get one. + + +def litellm_reminder_form(model_id: str) -> str: + """`system` or `turn`: how the model LiteLLM addresses as `model_id` is sent the reminder.""" + provider, _, model = model_id.strip().lower().partition("/") + if provider == "openai" and _OPENAI_MODEL.match(model): + return SYSTEM + return TURN + + +def _litellm_kind(message: dict[str, Any]) -> str: + """What one LiteLLM chat message is, for the rule.""" + role = message.get("role") + if role == "user": + return PERSON + if role == "tool": + return RESULT + if role != "assistant": + return OTHER + content = message.get("content") + if isinstance(content, str): + said = bool(content.strip()) + elif isinstance(content, list): + said = any( + isinstance(part, dict) + and part.get("type") == "text" + and isinstance(part.get("text"), str) + and part["text"].strip() + for part in content + ) + else: + said = False + if said: + return SAID + return CALLED if message.get("tool_calls") else QUIET + + +def with_litellm_reminders(messages: list[dict[str, Any]], model_id: str) -> list[dict[str, Any]]: + """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. + """ + places = set(reminder_places([_litellm_kind(message) for message in messages], join_steps=False)) + if not places: + return list(messages) + reminder = ( + {"role": "system", "content": REMINDER} + if litellm_reminder_form(model_id) == SYSTEM + else {"role": "user", "content": REMINDER_IN_TURN} + ) + sent: list[dict[str, Any]] = [] + for index, message in enumerate(messages): + sent.append(message) + if index in places: + sent.append(dict(reminder)) + return sent diff --git a/shared/silent_steps.py b/shared/silent_steps.py index fc97008dce..5826af3831 100644 --- a/shared/silent_steps.py +++ b/shared/silent_steps.py @@ -1,116 +1,9 @@ -"""A word now and then on a long job: where a Python Bot reminds its model to say a line. +"""The reminder's words under the name the AG2 and Langroid tests read them by. -The Bot's instructions already ask for a line every so often on a long job. Measured live on the -AG2 and Langroid Bots, that was not enough: Claude Sonnet 5.5 wrote one line or none on a 30-step -job. Anthropic's answer for a harness whose long tool-calling turns still go quiet (Prompting -Claude Sonnet 5.5, "User-facing progress updates", -https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5#user-facing-progress-updates): -count consecutive tool-calling steps that send the person no text or progress update, and after -several in a row, for example five, append a one-turn reminder after the latest tool results. Leave -each reminder in place on later requests, so the prompt cache and the model's preserved thinking -stay intact, and do not keep sending them to a turn that stays quiet, since frequent harness text -after tool results reads as a possible prompt injection. - -THE RULE, the same as every other engine's (agent-langgraph-ts/src/progress-reminder.ts was the -first). A step that calls tools and says nothing is a silent step. After five in a row, the next -model call is sent the reminder right after the fifth step's results. One per silent stretch: the -count starts again only when the model says a line or the person speaks, so a job that stays quiet -hears it once, and a short job never. A run carries the whole thread, so each Bot works the places -out from the thread on every model call: they land in the same places every time, nothing is kept -between runs, and a reminder never moves once sent. - -Each Bot reads its framework's messages as the kinds below, asks `reminder_places` where the -reminders go, and puts them only into what its model is sent, in the form that model takes. The -person never sees one: not in the run's events, its snapshot, or the thread. +The rule and its words live once, in `progress_reminder.py`; nothing else is here, and no Bot's +image carries this file. """ -from __future__ import annotations - -import re -from typing import Sequence - -#: Silent tool steps in a row before the reminder, as Anthropic's example gives it. -SILENT_STEPS = 5 - -#: Anthropic's wording, for the person rather than "the user", with the one case where no line is -#: wanted: a run nobody is watching is told to write none while it works. -REMINDER = ( - "The person hasn't heard from you in a while: say in a few words what you're doing, then " - "continue. If your instructions say nobody is watching this run, just continue." -) - -#: The same words in the person's turn, said to be the app's and not theirs. -REMINDER_IN_TURN = ( - "(A note from the app running this conversation, not a message from the person.) " + REMINDER -) - -# What each message of a thread is, for the rule. -PERSON = "person" #: the person's own words -RESULT = "result" #: tool results -SAID = "said" #: the model, with words for the person, calls or not -SILENT = "silent" #: the model calling tools and saying nothing -QUIET = "quiet" #: the model with neither words nor calls -OTHER = "other" #: anything else: system rows, reasoning, an empty request - -_MODEL = (SAID, SILENT, QUIET) - -#: OpenAI's own models, which take a system or developer message anywhere in the thread. -_OPENAI_MODEL = re.compile(r"^(?:gpt-|chatgpt-|codex-|o\d)") - - -def is_openai_model(model: str) -> bool: - """Whether `model` (a bare id, without a provider prefix) is one of OpenAI's own.""" - return bool(_OPENAI_MODEL.match((model or "").strip().lower())) - - -def _step(first: str, second: str) -> str: - """Two messages of the model's in a row, as one step: it said a line if either did.""" - if SAID in (first, second): - return SAID - if SILENT in (first, second): - return SILENT - return QUIET - - -def reminder_places(kinds: Sequence[str]) -> list[int]: - """Where the reminders go: the index of each message a reminder follows. - - `kinds` is the thread, one kind per message. Messages of the model's that come one after - another are one step, since some integrations stream a step's words and its calls as two - messages. A reminder follows the last result of the step that ended a silent stretch, and is - never put between those results and the person's own next words. - """ - # Each step, or other message, with the index of its last message. - units: list[tuple[str, int]] = [] - for index, kind in enumerate(kinds): - if kind in _MODEL and units and units[-1][0] in _MODEL: - units[-1] = (_step(units[-1][0], kind), index) - else: - units.append((kind, index)) +from progress_reminder import REMINDER, REMINDER_IN_TURN - places: list[int] = [] - silent = 0 - reminded = False - # The step whose results end with a reminder, once they are all in. - due = False - for position, (kind, index) in enumerate(units): - if due and kind != RESULT: - # Never between the results and the person's own next words: their turn starts again. - # And only after results: a step whose calls were never answered gets none. - if kind != PERSON and units[position - 1][0] == RESULT: - places.append(units[position - 1][1]) - due = False - if kind in (PERSON, SAID): - silent = 0 - reminded = False - continue - if kind != SILENT: - continue - silent += 1 - if silent >= SILENT_STEPS and not reminded: - due = True - reminded = True - # The latest results: the call about to be made is the first one sent the reminder. - if due and units and units[-1][0] == RESULT: - places.append(units[-1][1]) - return places +__all__ = ["REMINDER", "REMINDER_IN_TURN"]