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/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
Expand Down
19 changes: 11 additions & 8 deletions agent-adk/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down
47 changes: 45 additions & 2 deletions agent-adk/tests/test_progress_reminder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"})}
Expand All @@ -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 = []
Expand Down Expand Up @@ -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)
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/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
Expand Down
46 changes: 7 additions & 39 deletions agent-agno/src/sent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand All @@ -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)
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/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
Expand Down
11 changes: 8 additions & 3 deletions agent-crewai/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
)
Expand Down
47 changes: 45 additions & 2 deletions agent-crewai/tests/test_progress_reminder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"})}
Expand All @@ -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 = []
Expand Down Expand Up @@ -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)
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/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
Expand Down
25 changes: 24 additions & 1 deletion agent-langroid/src/frontend_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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] = []
Expand Down
24 changes: 24 additions & 0 deletions agent-langroid/tests/test_progress_reminder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
2 changes: 1 addition & 1 deletion agent-llamaindex/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading