Skip to content

Build and run agents you can see, understand and trust.

fix(tool): clean the file cache of the builtin Read tool (#1735)

CYJiang998bb03f85f4
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.py
index 310db9b58..aa8097295 100644
--- a/src/agentscope/agent/_agent.py
+++ b/src/agentscope/agent/_agent.py
@@ -480,6 +480,8 @@ class Agent:
f"'{path}', you can refer to it when needed.</system-reminder>"
)
+ await self._clear_unreserved_read_cache(msgs_to_reserve)
+
# Update the context
self.state.context = msgs_to_reserve
@@ -1774,6 +1776,32 @@ class Agent:
return msgs_to_compress, msgs_to_reserve
+ async def _clear_unreserved_read_cache(
+ self,
+ msgs_to_reserve: list[Msg],
+ ) -> None:
+ """Clean Read caches not referenced by reserved Read tool calls."""
+ reserved_paths: set[str] = set()
+ for msg in msgs_to_reserve:
+ for block in msg.get_content_blocks("tool_call"):
+ if not (
+ isinstance(block, ToolCallBlock) and block.name == "Read"
+ ):
+ continue
+
+ try:
+ tool_input = _json_loads_with_repair(block.input)
+ except Exception: # pylint: disable=broad-exception-caught
+ continue
+
+ file_path = tool_input.get("file_path")
+ if isinstance(file_path, str):
+ reserved_paths.add(file_path)
+
+ await self.state.tool_context.clean_file_cache(
+ reserved_file_paths=reserved_paths,
+ )
+
async def _split_tool_result_for_compression(
self,
tool_result: ToolResultBlock,
diff --git a/src/agentscope/state/_state.py b/src/agentscope/state/_state.py
index b20c85cbb..44de5fa55 100644
--- a/src/agentscope/state/_state.py
+++ b/src/agentscope/state/_state.py
@@ -110,6 +110,25 @@ class ToolContext(BaseModel):
),
)
+ async def clean_file_cache(
+ self,
+ reserved_file_paths: set[str] | None = None,
+ ) -> None:
+ """Drop read caches whose paths are not in ``reserved_file_paths``.
+
+ Args:
+ reserved_file_paths: File paths from Read calls that remain in the
+ context. Caches for these files are kept; all others are
+ evicted.
+ """
+ reserved_file_paths = reserved_file_paths or set()
+
+ self.read_file_cache = [
+ entry
+ for entry in self.read_file_cache
+ if entry.file_path in reserved_file_paths
+ ]
+
class TaskContext(BaseModel):
"""The task context."""
diff --git a/tests/compress_context_test.py b/tests/compress_context_test.py
index b1bb16692..24f0e34b7 100644
--- a/tests/compress_context_test.py
+++ b/tests/compress_context_test.py
@@ -1,6 +1,10 @@
# -*- coding: utf-8 -*-
"""A template test case."""
# pylint: disable=protected-access
+import json
+import os
+import tempfile
+
from unittest.async_case import IsolatedAsyncioTestCase
from utils import MockModel, AnyString
@@ -8,7 +12,7 @@ from utils import MockModel, AnyString
from agentscope.model import StructuredResponse
from agentscope.agent import Agent, ContextConfig
from agentscope.state import AgentState
-from agentscope.message import UserMsg, AssistantMsg, TextBlock
+from agentscope.message import UserMsg, AssistantMsg, TextBlock, ToolCallBlock
from agentscope.tool import Toolkit
@@ -658,5 +662,214 @@ class ContextCompressionTest(IsolatedAsyncioTestCase):
],
)
+ async def test_context_compression_clears_evicted_read_cache(self) -> None:
+ """Read cache is cleared when its Read block is compressed out."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_path = os.path.join(temp_dir, "test.txt")
+ with open(file_path, "w", encoding="utf-8") as f:
+ f.write("content\n")
+
+ model = MockModel(context_size=100)
+ agent = Agent(
+ name="Friday",
+ system_prompt="".join(["0" for _ in range(20 * 4)]),
+ model=model,
+ context_config=ContextConfig(
+ trigger_ratio=0.7,
+ reserve_ratio=0.4,
+ ),
+ state=AgentState(
+ session_id="123",
+ context=[
+ AssistantMsg(
+ "Friday",
+ [
+ ToolCallBlock(
+ id="read-call-1",
+ name="Read",
+ input=json.dumps(
+ {"file_path": file_path},
+ ),
+ ),
+ ],
+ id="1",
+ ),
+ UserMsg(
+ "User",
+ "".join(["2" for _ in range(30 * 4)]),
+ id="2",
+ ),
+ UserMsg(
+ "User",
+ "".join(["3" for _ in range(10 * 4)]),
+ id="3",
+ ),
+ ],
+ ),
+ toolkit=Toolkit(),
+ )
+ await agent.state.tool_context.cache_file(
+ file_path=file_path,
+ lines=["content\n"],
+ )
+ self.assertIsNotNone(
+ await agent.state.tool_context.get_cache(file_path),
+ )
+
+ model.set_structured_response(
+ StructuredResponse(
+ content={
+ "task_overview": "1",
+ "current_state": "2",
+ "important_discoveries": "3",
+ "next_steps": "4",
+ "context_to_preserve": "5",
+ },
+ ),
+ )
+
+ await agent.compress_context()
+
+ self.assertIsNone(
+ await agent.state.tool_context.get_cache(file_path),
+ )
+
+ async def test_context_compression_keeps_reserved_read_cache(
+ self,
+ ) -> None:
+ """Read cache is kept when the same file is still read in context."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_path = os.path.join(temp_dir, "test.txt")
+ with open(file_path, "w", encoding="utf-8") as f:
+ f.write("content\n")
+
+ model = MockModel(context_size=100)
+ agent = Agent(
+ name="Friday",
+ system_prompt="".join(["0" for _ in range(20 * 4)]),
+ model=model,
+ context_config=ContextConfig(
+ trigger_ratio=0.7,
+ reserve_ratio=0.6,
+ ),
+ state=AgentState(
+ session_id="123",
+ context=[
+ AssistantMsg(
+ "Friday",
+ [
+ ToolCallBlock(
+ id="read-call-1",
+ name="Read",
+ input=json.dumps(
+ {"file_path": file_path},
+ ),
+ ),
+ ],
+ id="1",
+ ),
+ UserMsg(
+ "User",
+ "".join(["2" for _ in range(30 * 4)]),
+ id="2",
+ ),
+ AssistantMsg(
+ "Friday",
+ [
+ ToolCallBlock(
+ id="read-call-2",
+ name="Read",
+ input=json.dumps(
+ {"file_path": file_path},
+ ),
+ ),
+ ],
+ id="3",
+ ),
+ ],
+ ),
+ toolkit=Toolkit(),
+ )
+ await agent.state.tool_context.cache_file(
+ file_path=file_path,
+ lines=["content\n"],
+ )
+
+ model.set_structured_response(
+ StructuredResponse(
+ content={
+ "task_overview": "1",
+ "current_state": "2",
+ "important_discoveries": "3",
+ "next_steps": "4",
+ "context_to_preserve": "5",
+ },
+ ),
+ )
+
+ await agent.compress_context()
+
+ self.assertIsNotNone(
+ await agent.state.tool_context.get_cache(file_path),
+ )
+
+ async def test_context_compression_clears_unreferenced_read_cache(
+ self,
+ ) -> None:
+ """Read cache is cleared when no reserved Read references it."""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_path = os.path.join(temp_dir, "test.txt")
+ with open(file_path, "w", encoding="utf-8") as f:
+ f.write("content\n")
+
+ model = MockModel(context_size=100)
+ agent = Agent(
+ name="Friday",
+ system_prompt="".join(["0" for _ in range(20 * 4)]),
+ model=model,
+ context_config=ContextConfig(
+ trigger_ratio=0.7,
+ reserve_ratio=0.4,
+ ),
+ state=AgentState(
+ session_id="123",
+ context=[
+ UserMsg(
+ "User",
+ "".join(["2" for _ in range(60 * 4)]),
+ id="1",
+ ),
+ UserMsg(
+ "User",
+ "".join(["3" for _ in range(30 * 4)]),
+ id="2",
+ ),
+ ],
+ ),
+ toolkit=Toolkit(),
+ )
+ await agent.state.tool_context.cache_file(
+ file_path=file_path,
+ lines=["content\n"],
+ )
+
+ model.set_structured_response(
+ StructuredResponse(
+ content={
+ "task_overview": "1",
+ "current_state": "2",
+ "important_discoveries": "3",
+ "next_steps": "4",
+ "context_to_preserve": "5",
+ },
+ ),
+ )
+
+ await agent.compress_context()
+
+ self.assertIsNone(
+ await agent.state.tool_context.get_cache(file_path),
+ )
+
async def asyncTearDown(self) -> None:
"""The async teardown method."""