diff --git a/agent-llamaindex/Dockerfile b/agent-llamaindex/Dockerfile index 7e94d0976f..52d9070a32 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/ +COPY shared/model_providers.py shared/model-providers.json shared/run_model_key.py shared/progress_reminder.py /shared/ ENV PORT=4204 EXPOSE 4204 diff --git a/agent-llamaindex/src/main.py b/agent-llamaindex/src/main.py index d13297de13..c44c439be2 100644 --- a/agent-llamaindex/src/main.py +++ b/agent-llamaindex/src/main.py @@ -1,7 +1,7 @@ """LlamaIndex as a Bot. The AG-UI support is LlamaIndex's own package, `llama-index-protocols-ag-ui`, and it hands back a -FastAPI router. Mount it and stop. +FastAPI router. Mount it, and change only what its model is sent on each call (`sent.py`). """ import hmac @@ -21,9 +21,24 @@ from llama_index.llms.litellm import LiteLLM from llama_index.protocols.ag_ui.router import get_ag_ui_workflow_router +from .sent import as_sent + TOKEN_HEADER = "x-openbot-agent-token" +class _BotLiteLLM(LiteLLM): + """LiteLLM, sending the thread with earlier steps as real tool calls and results, and a + reminder to say a line on a long job (`sent.py`). The AG-UI workflow's own messages are left + as they were: only what each call sends changes.""" + + def _prepare_chat_with_tools(self, tools, user_msg=None, chat_history=None, **kwargs): + prepared = super()._prepare_chat_with_tools( + tools, user_msg=user_msg, chat_history=list(chat_history or []), **kwargs + ) + prepared["messages"] = as_sent(prepared["messages"], self.model) + return prepared + + def _model_id() -> str: """`provider/model`, which is how litellm addresses one. @@ -41,7 +56,7 @@ def _model_id() -> str: return litellm_model_id(provider, model) -def _llm() -> LiteLLM: +def _llm() -> _BotLiteLLM: model = _model_id() if not litellm.supports_function_calling(model): litellm.register_model( @@ -53,7 +68,7 @@ def _llm() -> LiteLLM: } } ) - return LiteLLM(model=model, additional_kwargs={"drop_params": True}) + return _BotLiteLLM(model=model, additional_kwargs={"drop_params": True}) app = FastAPI() diff --git a/agent-llamaindex/src/sent.py b/agent-llamaindex/src/sent.py new file mode 100644 index 0000000000..670f25e329 --- /dev/null +++ b/agent-llamaindex/src/sent.py @@ -0,0 +1,118 @@ +"""What the model is sent on each call: the thread, with earlier steps as real tool calls and +results, and a reminder to say a line on a long job. + +EARLIER STEPS AS THE TOOL CALLS AND RESULTS THEY WERE. Every step of a job is a run of its own, so +every run hands the model the whole thread back. The LlamaIndex AG-UI package +(`llama-index-protocols-ag-ui`, 0.7.0 and every release before it) reads that thread into +LlamaIndex's messages with each earlier tool call as `...` +text in the assistant's message, and each result as a plain message from the person. Live, Claude +Sonnet 5.5 on a 30-step job read two or three steps of that, then stopped calling tools and never +answered. Upstream: run-llama/llama_index issue 23500, fixed in pull request 23501, not released. + +The package keeps what it needs to put them back: the assistant message holds the calls as they +arrived (`ag_ui_tool_calls`), and a result keeps its `tool_call_id`. So each call is sent as the +model's own tool call, in the shape LiteLLM sends one (`tool_calls`), and each result as a `tool` +message for that call, which LiteLLM turns into whatever the provider takes (`tool_use` and +`tool_result` for Claude). Only what the model is sent changes: the package's own messages, its +snapshot and the thread the person sees are left as they were. Drop this when a release of the +package sends them natively. + +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; one per silent stretch, reset +by a line from the model or the person. The rule, its words and its form for each model are every +Python Bot's (`shared/progress_reminder.py`), read here as the other LiteLLM Bots read it: every +chat message a step of its own. It is worked out from the thread on every call, so it lands in the +same place every time, and it is only ever in what the model is sent. +""" + +from __future__ import annotations + +import re +from typing import Any, Sequence + +from llama_index.core.llms import ChatMessage, MessageRole, TextBlock +from progress_reminder import ( + CALLED, + OTHER, + PERSON, + QUIET, + REMINDER, + REMINDER_IN_TURN, + RESULT, + SAID, + SYSTEM, + litellm_reminder_form, + reminder_places, +) + +# The text the package writes each earlier call as, after the assistant's own words. +_CALL_AS_TEXT = re.compile(r"[\s\S]*?") + + +def _words(message: ChatMessage) -> str: + return "".join(block.text for block in message.blocks if isinstance(block, TextBlock)) + + +def _as_tool_call(call: dict[str, Any]) -> dict[str, Any]: + return { + "id": call["id"], + "type": "function", + "function": {"name": call["name"], "arguments": call.get("arguments") or "{}"}, + } + + +def _native(message: ChatMessage) -> ChatMessage: + """One message of the thread as the model should see it.""" + 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.USER and kwargs.get("tool_call_id"): + return ChatMessage( + role=MessageRole.TOOL, + content=_words(message), + additional_kwargs={"tool_call_id": kwargs["tool_call_id"]}, + ) + return message + + +def _kind(message: ChatMessage) -> str: + """What one message, as sent, is for the reminder rule.""" + if message.role == MessageRole.USER: + return PERSON + if message.role == MessageRole.TOOL: + return RESULT + if message.role != MessageRole.ASSISTANT: + return OTHER + if _words(message).strip(): + return SAID + return CALLED if message.additional_kwargs.get("tool_calls") else QUIET + + +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] + places = set(reminder_places([_kind(message) for message in sent], join_steps=False)) + if not places: + return sent + system = litellm_reminder_form(model_id) == SYSTEM + out: list[ChatMessage] = [] + for index, message in enumerate(sent): + out.append(message) + if index in places: + out.append( + ChatMessage(role=MessageRole.SYSTEM, content=REMINDER) + if system + else ChatMessage(role=MessageRole.USER, content=REMINDER_IN_TURN) + ) + return out diff --git a/agent-llamaindex/tests/long_job.py b/agent-llamaindex/tests/long_job.py new file mode 100644 index 0000000000..2e89fa714a --- /dev/null +++ b/agent-llamaindex/tests/long_job.py @@ -0,0 +1,96 @@ +"""A long job run through this Bot's real AG-UI endpoint, the way OpenBot's server runs it. + +Each step is a run of its own: the run hands back the model's tool call, the server answers it, and +the whole thread goes back on the next run. The model is `scripted_provider` from +`shared/progress_reminder_contract.py`, real LiteLLM in between, so what is checked is what a +provider would receive. + +The contract's own driver rebuilds the thread from TOOL_CALL_START events. LlamaIndex's router +streams TOOL_CALL_CHUNK events, which a client expands, and a MESSAGES_SNAPSHOT of the whole thread +after every step, so the thread is read from the snapshot here, as OpenBot's client reads it. +""" + +import importlib +import sys +from pathlib import Path + +from fastapi.testclient import TestClient + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from harness_contract import run_events # noqa: E402 +from progress_reminder_contract import QUESTION, TOOL, result_of, scripted_provider # noqa: E402 + +TOKEN = "job-token" + + +def _drive(client: TestClient, runs: int = 64) -> tuple[list[str], list[dict]]: + """Runs the job to its answer. Returns each run's SSE body and the thread the person sees.""" + messages: list[dict] = [ + {"id": "standing-role:job-bot", "role": "system", "content": "You are Ledger Bot."}, + {"id": "u1", "role": "user", "content": QUESTION}, + ] + streamed: list[str] = [] + for run in range(runs): + response = client.post( + "/run", + headers={"x-openbot-agent-token": TOKEN}, + json={ + "threadId": "job-thread", + "runId": f"job-run-{run}", + "state": {}, + "messages": messages, + "tools": [TOOL], + "context": [], + "forwardedProps": {}, + }, + ) + assert response.status_code == 200, response.text + streamed.append(response.text) + events = run_events(response.text) + types = [event["type"] for event in events] + assert "RUN_FINISHED" in types and "RUN_ERROR" not in types, response.text + snapshots = [event["messages"] for event in events if event["type"] == "MESSAGES_SNAPSHOT"] + assert snapshots, response.text + thread = snapshots[-1] + answered = {message.get("toolCallId") for message in thread if message["role"] == "tool"} + pending = [ + call + for message in thread + if message["role"] == "assistant" + for call in message.get("toolCalls") or [] + if call["id"] not in answered + ] + if not pending: + return streamed, thread + messages = [ + *thread, + *( + { + "id": f"result-{call['id']}", + "role": "tool", + "toolCallId": call["id"], + "content": result_of(int(call["id"].split("_")[-1])), + } + for call in pending + ), + ] + raise AssertionError(f"the job did not end in {runs} runs") + + +def run_job(monkeypatch, environment, model: str, steps: int, lines: set[int] | None = None): + """A `steps`-step job on `model`. Returns every request the provider got, each run's stream, + and the thread the person sees at the end.""" + with scripted_provider(steps, lines) as (base, bodies): + monkeypatch.delenv("OPENAI_API_BASE", raising=False) + monkeypatch.delenv("ANTHROPIC_AUTH_TOKEN", raising=False) + monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) + for key, value in environment(base, model).items(): + monkeypatch.setenv(key, value) + from src import main + + # The model is built when the app is, from the environment just set. + client = TestClient(importlib.reload(main).app) + streamed, thread = _drive(client) + assert len(bodies) == steps + 1, "every step and the answer" + return bodies, streamed, thread diff --git a/agent-llamaindex/tests/test_progress_reminder.py b/agent-llamaindex/tests/test_progress_reminder.py new file mode 100644 index 0000000000..d5ad2dd0aa --- /dev/null +++ b/agent-llamaindex/tests/test_progress_reminder.py @@ -0,0 +1,92 @@ +"""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 (`src/sent.py`, the rule in +`shared/progress_reminder.py`). One per silent stretch, none on a short job, a line from the +model starts the count again, and the person never sees it. + +Driven as the server drives a long job (`long_job.py`), and read where it matters: the requests the +model provider receives and the AG-UI events the person's screen is drawn from. +""" + +import json + +import pytest + +from long_job import run_job +from harness_contract import anthropic_environment, openai_environment +from progress_reminder import REMINDER, REMINDER_IN_TURN +from progress_reminder_contract import ( + HEARD, + LINE, + check_never_shown, + check_reminder_follows, + prefix_through_reminders, + reminders_in, +) + + +def test_a_30_step_job_that_stays_silent_is_reminded_once_after_the_fifth_step_and_it_stays_put(monkeypatch): + bodies, streamed, thread = run_job(monkeypatch, anthropic_environment, "claude-sonnet-5-5", 30) + assert len(bodies) == 31, "30 steps and the answer" + # Requests 0 to 4 make steps 1 to 5: nothing yet. + for body in bodies[:5]: + assert reminders_in(body) == [] + # Request 5 makes step 6, the first after five silent steps: the reminder follows step 5's + # result, in the person's turn and said to be the app's, not in the system prompt. + assert reminders_in(bodies[5]) == [5] + check_reminder_follows(bodies[5], 5) + assert REMINDER_IN_TURN in json.dumps(bodies[5]["messages"]) + assert REMINDER not in json.dumps(bodies[5].get("system")) + # Every later request keeps it in the same place, with everything before it unchanged, and gets + # no second one: one per silent stretch. + first = prefix_through_reminders(bodies[5]) + for body in bodies[6:]: + assert reminders_in(body) == [5] + assert prefix_through_reminders(body) == first, "an unchanged prefix, so the cache holds" + check_never_shown(streamed) + assert HEARD not in json.dumps(thread) + + +def test_a_short_job_is_never_reminded(monkeypatch): + bodies, streamed, _ = run_job(monkeypatch, anthropic_environment, "claude-sonnet-5-5", 4) + for body in bodies: + assert reminders_in(body) == [] + check_never_shown(streamed) + + +def test_a_line_from_the_model_starts_the_count_again(monkeypatch): + # Steps 1-4 silent, 5 says a line, 6-11 silent, 12 says a line, 13-20 silent. + bodies, streamed, thread = run_job(monkeypatch, anthropic_environment, "claude-sonnet-5-5", 20, {5, 12}) + first = next(index for index, body in enumerate(bodies) if reminders_in(body)) + assert first == 10, "the call after step 10, five silent steps after the line, not after step 5" + check_reminder_follows(bodies[10], 10) + for body in bodies[11:17]: + assert reminders_in(body) == [10] + # After step 12's line, five more silent steps (13-17) earn a second one, after step 17. + assert reminders_in(bodies[17]) == [10, 17] + check_reminder_follows(bodies[17], 17) + check_never_shown(streamed) + # The model's two lines reach the person. + assert [m["content"] for m in thread if m["role"] == "assistant" and m.get("content") == LINE] == [LINE, LINE] + + +@pytest.mark.parametrize( + "model,form", + [("gpt-5.5", "system"), ("qwen/qwen3-8b", "turn")], +) +def test_every_model_is_reminded_in_the_form_it_takes(monkeypatch, model, form): + bodies, streamed, _ = run_job(monkeypatch, openai_environment, model, 7) + for body in bodies[:5]: + assert reminders_in(body) == [], model + for body in bodies[5:]: + assert reminders_in(body) == [5], model + check_reminder_follows(bodies[5], 5) + holder = next(message for message in bodies[5]["messages"] if REMINDER in str(message.get("content"))) + expected = ( + {"role": "system", "content": REMINDER} + if form == "system" + else {"role": "user", "content": REMINDER_IN_TURN} + ) + assert {key: holder[key] for key in ("role", "content")} == expected + previous = bodies[5]["messages"][bodies[5]["messages"].index(holder) - 1] + assert previous["role"] == "tool" and previous["tool_call_id"] == "call_5" + check_never_shown(streamed) diff --git a/agent-llamaindex/tests/test_tool_history.py b/agent-llamaindex/tests/test_tool_history.py new file mode 100644 index 0000000000..20427473ef --- /dev/null +++ b/agent-llamaindex/tests/test_tool_history.py @@ -0,0 +1,101 @@ +"""A LONG JOB SENDS ITS EARLIER STEPS TO THE MODEL AS REAL TOOL CALLS AND RESULTS. + +Every step of a job is a run of its own, so every run hands the model the whole thread back. The +LlamaIndex AG-UI package (`llama-index-protocols-ag-ui`, 0.7.0 and every release before it) turns +each earlier tool call into `...` text in an assistant message, +and each result into a plain user message. Live, Claude Sonnet 5.5 on a 30-step job read two or +three steps of that, then stopped calling tools and never answered. Upstream: run-llama/llama_index +issue 23500, fix in pull request 23501, not released. + +Driven as the server drives a job, with real LiteLLM and a scripted provider, and read where it +matters: what each request to the provider carries, and the thread the person sees. +""" + +import json + +import pytest + +from long_job import run_job +from harness_contract import anthropic_environment, openai_environment +from progress_reminder_contract import ANSWER, TOOL, call_id, result_of + +STEPS = 8 + + +def _anthropic_history(body): + """Each earlier step as the request carries it: (call id, name, input) and (result id, text).""" + calls, results = [], [] + for message in body["messages"]: + content = message["content"] + if isinstance(content, str): + continue + for block in content: + if block.get("type") == "tool_use": + assert message["role"] == "assistant", message + calls.append((block["id"], block["name"], block["input"])) + elif block.get("type") == "tool_result": + assert message["role"] == "user", message + text = block["content"] + if not isinstance(text, str): + text = "".join(part.get("text", "") for part in text) + results.append((block["tool_use_id"], text)) + return calls, results + + +def _openai_history(body): + calls, results = [], [] + for message in body["messages"]: + for call in message.get("tool_calls") or []: + assert message["role"] == "assistant", message + calls.append( + (call["id"], call["function"]["name"], json.loads(call["function"]["arguments"])) + ) + if message["role"] == "tool": + results.append((message["tool_call_id"], message["content"])) + return calls, results + + +@pytest.mark.parametrize( + "environment,model,history", + [ + (anthropic_environment, "claude-sonnet-5-5", _anthropic_history), + (openai_environment, "gpt-5.5", _openai_history), + ], +) +def test_every_earlier_step_reaches_the_model_as_a_tool_call_and_its_result( + monkeypatch, environment, model, history +): + bodies, streamed, thread = run_job(monkeypatch, environment, model, STEPS) + + for index, body in enumerate(bodies): + sent = json.dumps(body["messages"]) + assert "" not in sent, f"request {index} carries a call as text" + # A step that only called a tool is sent as just that call, never with words the model + # did not say (LiteLLM writes an empty turn to Claude as "[System: Empty message ...]"). + assert "sanitised" not in sent, f"request {index} puts words in the model's mouth" + for message in body["messages"]: + if message["role"] == "assistant": + content = message.get("content") + assert not content or all( + block.get("type") != "text" for block in content if isinstance(block, dict) + ), f"request {index}: {message}" + calls, results = history(body) + # Request N is sent after steps 1 to N: each as the model's own call, then its answer. + assert calls == [ + (call_id(step), TOOL["name"], {"id": f"R{step}"}) for step in range(1, index + 1) + ], f"request {index}" + assert results == [(call_id(step), result_of(step)) for step in range(1, index + 1)], ( + f"request {index}" + ) + + # The job ends with the answer, and the person's thread keeps each call as it was made. + assert ANSWER in streamed[-1] + assert thread[-1]["role"] == "assistant" and thread[-1]["content"] == ANSWER + made = [ + (call["id"], call["function"]["name"], json.loads(call["function"]["arguments"])) + for message in thread + if message["role"] == "assistant" + for call in message.get("toolCalls") or [] + ] + assert made == [(call_id(step), TOOL["name"], {"id": f"R{step}"}) for step in range(1, STEPS + 1)] + assert "" not in json.dumps(thread)