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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion agent-adk/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ COPY agent-adk/requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY agent-adk/src ./src
COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/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
Expand Down
6 changes: 3 additions & 3 deletions agent-adk/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
)


Expand Down
2 changes: 1 addition & 1 deletion agent-ag2/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ COPY agent-ag2/requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY agent-ag2/src ./src
COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/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
Expand Down
11 changes: 6 additions & 5 deletions agent-ag2/src/progress_reminder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
)

Expand All @@ -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.
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion agent-agno/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions agent-agno/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion agent-crewai/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions agent-crewai/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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,
)
Expand Down
2 changes: 1 addition & 1 deletion agent-langgraph-agui/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
104 changes: 45 additions & 59 deletions agent-langgraph-agui/src/progress_reminder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -31,6 +31,8 @@
"""

import re
import sys
from pathlib import Path

from langchain_core.messages import (
AIMessage,
Expand All @@ -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
Expand All @@ -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()

Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -179,46 +177,34 @@ 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.

The last result of the step that ended a silent stretch, when the model went on after it: a
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:
Expand Down
2 changes: 1 addition & 1 deletion agent-langroid/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 14 additions & 9 deletions agent-langroid/src/frontend_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@
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,
REMINDER,
REMINDER_IN_TURN,
RESULT,
SAID,
SILENT,
is_openai_model,
reminder_places,
)
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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)
Expand Down
Loading
Loading