Skip to content
Open
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
27 changes: 21 additions & 6 deletions src/google/adk/tools/preload_memory_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,20 @@ class PreloadMemoryTool(BaseTool):
NOTE: Currently this tool only uses text part from the memory.
"""

def __init__(self) -> None:
def __init__(self, *, anchor_to_user_turn: bool = False) -> None:
"""Initializes the preload memory tool.

Args:
anchor_to_user_turn: If True, inserts the preloaded memory block right
before the current turn's user message instead of appending it as
trailing transient user content. This keeps the request prefix stable
across tool-call iterations for prefix-based prompt caches (e.g.
OpenAI/LiteLLM).
"""
# Name and description are not used because this tool only
# changes llm_request.
super().__init__(name='preload_memory', description='preload_memory')
self.anchor_to_user_turn = anchor_to_user_turn

@override
async def process_llm_request(
Expand Down Expand Up @@ -89,11 +99,16 @@ async def process_llm_request(
{full_memory_text}
</PAST_CONVERSATIONS>
"""
llm_request._insert_transient_user_content([ # pylint: disable=protected-access
types.Content(
role='user', parts=[types.Part.from_text(text=memory_context)]
)
])
memory_content = types.Content(
role='user', parts=[types.Part.from_text(text=memory_context)]
)
if self.anchor_to_user_turn and tool_context.user_content is not None:
for i in range(len(llm_request.contents) - 1, -1, -1):
if llm_request.contents[i] == tool_context.user_content:
llm_request.contents.insert(i, memory_content)
return

llm_request._insert_transient_user_content([memory_content]) # pylint: disable=protected-access


preload_memory_tool = PreloadMemoryTool()
87 changes: 87 additions & 0 deletions tests/unittests/tools/test_preload_memory_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,3 +378,90 @@ async def test_preload_memory_logs_search_failure_on_own_logger(caplog):
assert warnings[0].name == 'google_adk.google.adk.tools.preload_memory_tool'
assert warnings[0].exc_info is not None
assert 'current query' not in caplog.text


@pytest.mark.asyncio
async def test_preload_memory_anchor_to_user_turn_preserves_prefix():
"""With anchor_to_user_turn=True, memory stays before the turn's user message."""
from google.adk.agents import Agent
from google.adk.memory.base_memory_service import BaseMemoryService
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_response import LlmResponse
from google.adk.runners import Runner
from google.adk.sessions.in_memory_session_service import InMemorySessionService

class _OneMemory(BaseMemoryService):

async def add_session_to_memory(self, session):
pass

async def search_memory(self, **kwargs):
del kwargs
return SearchMemoryResponse(memories=[_memory('remembered fact')])

def _lookup() -> dict:
return {'result': 1}

recorded_requests: list[LlmRequest] = []

class _ScriptedLlm(BaseLlm):
model: str = 'scripted'

async def generate_content_async(self, llm_request, stream=False):
del stream
recorded_requests.append(llm_request.model_copy(deep=True))
if len(recorded_requests) < 3:
part = types.Part.from_function_call(name='_lookup', args={})
else:
part = types.Part.from_text(text='done')
yield LlmResponse(content=types.Content(role='model', parts=[part]))

sessions = InMemorySessionService()
await sessions.create_session(app_name='app', user_id='u', session_id='s')
agent = Agent(
name='agent',
model=_ScriptedLlm(),
tools=[_lookup, PreloadMemoryTool(anchor_to_user_turn=True)],
)
runner = Runner(
app_name='app',
agent=agent,
session_service=sessions,
memory_service=_OneMemory(),
)
async for _ in runner.run_async(
user_id='u',
session_id='s',
new_message=types.UserContent('question'),
):
pass

assert len(recorded_requests) == 3

def _labels(req: LlmRequest) -> list[str]:
out = []
for c in req.contents:
p = c.parts[0]
if p.text and '<PAST_CONVERSATIONS>' in p.text:
out.append('MEMORY')
elif p.function_call:
out.append('CALL')
elif p.function_response:
out.append('RESULT')
else:
out.append('USER')
return out

assert _labels(recorded_requests[0]) == ['MEMORY', 'USER']
assert _labels(recorded_requests[1]) == ['MEMORY', 'USER', 'CALL', 'RESULT']
assert _labels(recorded_requests[2]) == [
'MEMORY',
'USER',
'CALL',
'RESULT',
'CALL',
'RESULT',
]
# Every earlier request is an exact prefix of the next request.
assert recorded_requests[1].contents[:2] == recorded_requests[0].contents
assert recorded_requests[2].contents[:4] == recorded_requests[1].contents