Enterprise agent platform for building, deploying, and operating AI teammates.
perf(toby): keep the system prompt stable when the stored-result reader joins (#3804)
OliverBryantd9e0bb56e371
diff --git a/src/xagent/core/agent/pattern/react/react.py b/src/xagent/core/agent/pattern/react/react.pyindex 54d1d515d..98511b0a9 100644--- a/src/xagent/core/agent/pattern/react/react.py+++ b/src/xagent/core/agent/pattern/react/react.py@@ -98,6 +98,7 @@ from ....tools.adapters.vibe.mcp_approval_gate import (bind_tool_call_execution_context,)from ....tools.tool_result_spill import (+ SPILL_READ_AVAILABLE_NOTE,SPILL_READ_TOOL_NAME,SPILL_RESERVED_RESULT_KEY,normalize_spilled_relative_path,@@ -821,6 +822,9 @@ class ReActPattern(AgentPattern):for c in (defer_builtin_tool_categories or ())if isinstance(c, str) and c.strip())+ # Whether this run has a stored-result reader tool (offered only+ # after a result is stored). Fixed per run so the system text is too.+ self._spill_reader_present = Falseself._deferred_tool_names: frozenset[str] = frozenset()self._deferred_order: tuple[str, ...] = ()# Deferred built-in tools: category -> names in tool order.@@ -1096,6 +1100,7 @@ class ReActPattern(AgentPattern):None,))+ self._spill_reader_present = spill_read_tool is not Nonespill_read_schema = (Noneif spill_read_tool is None@@ -2097,8 +2102,13 @@ class ReActPattern(AgentPattern):# after it) would change on the call that follows a load. Loaded# deferred tools are therefore left out of the list below and the# inventory is built from the whole deferred index.+ # The stored-result reader joins the schema mid-run, once a result+ # has been stored, so it is kept out of the names too and the+ # sentence below states its availability instead.stable_tool_names = [- n for n in active_tool_names if n not in self._deferred_tool_names+ n+ for n in active_tool_names+ if n not in self._deferred_tool_names and n != SPILL_READ_TOOL_NAME]inventory_tool_names = [*stable_tool_names, *self._deferred_order]available_tools = ", ".join(stable_tool_names) or "(none)"@@ -2207,6 +2217,7 @@ class ReActPattern(AgentPattern):f"\n\nAvailable tool names for this LLM call are exactly: {available_tools}. ""Never call a tool name that is not in this list."f"{AVAILABLE_NAMES_SUFFIX if self._deferred_tool_names else ''}"+ f"{SPILL_READ_AVAILABLE_NOTE if self._spill_reader_present else ''}")access_context = tool_access_context(self._connector_tool_sources,diff --git a/src/xagent/core/tools/tool_result_spill.py b/src/xagent/core/tools/tool_result_spill.pyindex 6d377a4c2..39d7fa85b 100644--- a/src/xagent/core/tools/tool_result_spill.py+++ b/src/xagent/core/tools/tool_result_spill.py@@ -124,6 +124,13 @@ SPILL_READ_UNAVAILABLE_MESSAGES = {# It is the most one reply ever carries; spill_read_page_chars lowers the# page further when the tool output limit is smaller.SPILL_READ_TOOL_NAME = "read_tool_result"+# Stands in for the reader's name in the system prompt's tool-name list: the+# reader joins the tool schema mid-run, so naming it there would change the+# system text (and the provider's cached prefix) on that call.+SPILL_READ_AVAILABLE_NOTE = (+ f" {SPILL_READ_TOOL_NAME} is also available once the engine has stored "+ "a large tool result; the stored-result notice then names it."+)SPILL_READ_MAX_CHARS = 12_000SPILL_READ_TRUNCATED_INSTRUCTION = ("Call read_tool_result again with the same path, start, and end and "diff --git a/tests/core/agent/test_react_prefix_stability.py b/tests/core/agent/test_react_prefix_stability.pynew file mode 100644index 000000000..1b022bfaf--- /dev/null+++ b/tests/core/agent/test_react_prefix_stability.py@@ -0,0 +1,141 @@+"""The request prefix (system message, then tools) must not change mid-run.++Providers cache by prefix, and the system message comes first. A tool joining+the schema mid-run (a loaded deferred tool, or the stored-result reader after a+spill) may only append to the tools array; it must never alter the system text.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import pytest++from tests.core.agent.test_react import (+ FakeLLM,+ FakeReadToolResultTool,+ FakeTool,+ _tool_call_response,+)+from tests.core.agent.test_react_deferred_builtin_schemas import (+ CATEGORIES,+ BuiltinTool,+)+from tests.core.agent.test_react_deferred_connector_schemas import ConnectorTool+from xagent.core.agent.context.execution import ExecutionContext+from xagent.core.agent.deferred_tools import LOAD_TOOLS_NAME+from xagent.core.agent.pattern.react import ReActPattern+from xagent.core.tools.adapters.vibe.base import ToolCategory+from xagent.core.tools.tool_result_spill import (+ SPILL_READ_TOOL_NAME,+ SPILL_RESERVED_RESULT_KEY,+ SpillTarget,+ spill_dir_for_workspace,+ spill_oversized_values,+)+++def _system(call: dict[str, Any]) -> str:+ return "\n".join(+ str(m["content"]) for m in call["messages"] if m.get("role") == "system"+ )+++def _tools(call: dict[str, Any]) -> list[str]:+ return [json.dumps(t, sort_keys=True) for t in call.get("tools") or []]+++def _names(call: dict[str, Any]) -> list[str]:+ return [t["function"]["name"] for t in call.get("tools") or []]+++def _spilling_tool(tmp_path: Path) -> FakeTool:+ target = SpillTarget(spill_dir=spill_dir_for_workspace(tmp_path), max_chars=100)++ class SpillingTool(FakeTool):+ async def run_json_async(self, args: dict[str, Any]) -> Any:+ spilled, records = spill_oversized_values(+ {"output": "x" * 300},+ target,+ tool_name="calculator",+ max_recursion=20,+ )+ return {**spilled, SPILL_RESERVED_RESULT_KEY: records}++ return SpillingTool()+++def _ctx(tmp_path: Path) -> ExecutionContext:+ context = ExecutionContext()+ context.attach_workspace("ws", str(tmp_path))+ context.add_user_message("q")+ return context+++def _assert_prefix_stable(before: dict[str, Any], after: dict[str, Any]) -> None:+ assert _system(before) == _system(after)+ old, new = _tools(before), _tools(after)+ assert new[: len(old)] == old+++def _spill_call() -> dict[str, Any]:+ return _tool_call_response("s", "calculator", '{"expression": "1+1"}')+++def _final() -> dict[str, Any]:+ return _tool_call_response("f", "final_answer", '{"answer": "done"}')+++async def test_spill_reader_joining_mid_run_leaves_the_system_message_alone(+ tmp_path: Path,+) -> None:+ llm = FakeLLM(responses=[_spill_call(), _final()])+ await ReActPattern(max_iterations=4).run(+ context=_ctx(tmp_path),+ tools=[_spilling_tool(tmp_path), FakeReadToolResultTool()],+ llm=llm,+ )++ assert SPILL_READ_TOOL_NAME not in _names(llm.calls[0])+ assert _names(llm.calls[1])[-1] == SPILL_READ_TOOL_NAME+ _assert_prefix_stable(llm.calls[0], llm.calls[1])+ # The reader is still announced, by a sentence that never changes.+ assert SPILL_READ_TOOL_NAME in _system(llm.calls[0])+++async def test_loads_then_a_spill_never_touch_the_system_message(+ tmp_path: Path,+) -> None:+ tools = [+ _spilling_tool(tmp_path),+ FakeReadToolResultTool(),+ ConnectorTool("notion_search", "notion"),+ BuiltinTool("generate_image", ToolCategory.IMAGE),+ ]+ llm = FakeLLM(+ responses=[+ _tool_call_response("l1", LOAD_TOOLS_NAME, '{"names": ["notion_search"]}'),+ _tool_call_response("l2", LOAD_TOOLS_NAME, '{"names": ["image"]}'),+ _spill_call(),+ _final(),+ ]+ )+ await ReActPattern(+ max_iterations=8,+ defer_connector_schemas=True,+ defer_builtin_tool_categories=CATEGORIES,+ ).run(context=_ctx(tmp_path), tools=tools, llm=llm)++ assert len(llm.calls) == 4+ assert _names(llm.calls[1])[-1] == "notion_search"+ assert _names(llm.calls[2])[-1] == "generate_image"+ assert SPILL_READ_TOOL_NAME in _names(llm.calls[3])+ for before, after in zip(llm.calls, llm.calls[1:]):+ assert _system(before) == _system(after)+ # Each load only appends. (The reader is placed ahead of loaded tools, so+ # the spill call is checked on the system message alone.)+ assert _tools(llm.calls[2])[: len(_tools(llm.calls[1]))] == _tools(llm.calls[1])