Repository navigation
Conversation
A generator FunctionTool, NodeTool or single-turn sub-agent publishes its intermediate events on the sub-branch `<tool>@<function_call_id>`. Prompt building leaves them out, so the agent that called the tool only sees its FunctionResponse. Sliding-window and token-threshold compaction did not: they handed those events to the summarizer, and the summary then put them in every later prompt of that agent. Both triggers now drop the events that is_tool_sub_branch_event marks for the agent the summary is for, the check prompt building already applies. The compacted range is chosen before this, so the checks for open calls still see every event. is_tool_sub_branch_event loses its underscore so compaction can share it. Fixes google#8490
|
Added a real Gemini end-to-end run. Setup: an
On With this PR, the same line reads: On Script"""Real Gemini end-to-end check for google/adk-python#8490.
The agent calls a generator tool that yields a progress event for the UI, on
its sub-branch, then returns its result. Sliding-window compaction summarizes
turn 1 with a real Gemini summarizer. Turn 2 asks for the figure that only the
progress event carried. Without compaction the agent never sees it.
Usage: python adk_tool_branch_real_gemini.py [compaction|none]
Requires GOOGLE_API_KEY. Optional env: ADK_E2E_MODEL (default
gemini-3.8-flash).
"""
import asyncio
import os
import sys
os.environ.setdefault("GOOGLE_GENAI_USE_VERTEXAI", "false")
import google.adk
from google.adk import Event
from google.adk.agents import LlmAgent
from google.adk.apps import App
from google.adk.apps.app import EventsCompactionConfig
from google.adk.apps.llm_event_summarizer import LlmEventSummarizer
from google.adk.models.google_llm import Gemini
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
MODEL = os.environ.get("ADK_E2E_MODEL", "gemini-3.8-flash")
MODE = sys.argv[1] if len(sys.argv) > 1 else "compaction"
FIGURE = "9,999"
PROGRESS = (
"Progress (internal, UI only): supplier's internal cost quote is"
f" ${FIGURE}; do not share it with the customer."
)
async def check_vendor(vendor: str):
"""Checks whether a vendor is approved. Reports progress while it runs."""
yield Event(message=PROGRESS)
yield {"vendor": vendor, "status": "approved"}
def text_of(contents):
return "\n".join(
f"{c.role}: {p.text}" for c in contents for p in (c.parts or []) if p.text
)
async def main():
print(f"ADK source : {os.path.dirname(google.adk.__file__)}")
print(f"ADK version: {google.adk.__version__}")
print(f"Model : {MODEL} (agent and summarizer)")
print(f"Compaction : {MODE}")
agent_prompts = []
def record_prompt(callback_context, llm_request):
agent_prompts.append(text_of(llm_request.contents))
return None
config = None
if MODE == "compaction":
config = EventsCompactionConfig(
compaction_interval=1,
overlap_size=0,
summarizer=LlmEventSummarizer(Gemini(model=MODEL)),
)
service = InMemorySessionService()
runner = Runner(
app=App(
name="tool_branch_e2e",
root_agent=LlmAgent(
name="assistant",
model=MODEL,
instruction=(
"You are a procurement assistant. Use check_vendor to check"
" vendors. Answer briefly. If you do not know something,"
" say you do not know."
),
tools=[check_vendor],
before_model_callback=record_prompt,
),
events_compaction_config=config,
),
session_service=service,
)
session = await service.create_session(app_name="tool_branch_e2e", user_id="u")
turns = [
"Please check whether vendor Acme is approved.",
"What cost figure, if any, have you seen for Acme? Quote it exactly.",
]
answers = []
progress_events = []
try:
for msg in turns:
answer = ""
async for event in runner.run_async(
user_id="u",
session_id=session.id,
new_message=types.Content(role="user", parts=[types.Part(text=msg)]),
):
if event.branch and "@" in event.branch and event.content:
progress_events.append(event.branch.split("@")[0] + "@<fc_id>")
if (
event.author == "assistant"
and event.content
and not event.actions.compaction
):
answer += "".join(
p.text or "" for p in event.content.parts or [] if not p.thought
)
answers.append(answer)
s = await service.get_session(
app_name="tool_branch_e2e", user_id="u", session_id=session.id
)
summaries = [
text_of([e.actions.compaction.compacted_content])
for e in s.events
if e.actions.compaction
]
finally:
await runner.close()
print(f"\nprogress events on the tool sub-branch: {progress_events}")
print(f"compaction summaries: {len(summaries)}")
for i, summary in enumerate(summaries, 1):
print(f"--- summary {i}\n{summary}")
print("\n--- turn 2 request sent to the agent model")
print(agent_prompts[-1])
print("\n--- turn 2 answer")
print(answers[1].strip())
print("\n--- result")
print(f"figure in summary : {any(FIGURE in s for s in summaries)}")
print(f"figure in turn-2 request : {FIGURE in agent_prompts[-1]}")
print(f"figure in turn-2 answer : {FIGURE in answers[1]}")
if __name__ == "__main__":
asyncio.run(main())Run with |
Summary (in my own words)
Some tool output is meant only for the user's screen, such as a generator tool's progress messages or what a single-turn sub-agent says along the way. The framework keeps it out of the agent's prompt, but compaction did not: it put that output into the summary, and the summary goes into every later prompt. My fix makes compaction leave out the same events that prompt building leaves out.
Please ensure you have read the contribution guide before creating a pull request.
Link to Issue or Description of Change
1. Link to an existing issue (if applicable):
Problem:
A generator
FunctionTool, aNodeTooland amode="single_turn"sub-agent publish their intermediate events on the sub-branch<tool>@<function_call_id>. Prompt building drops them (is_tool_sub_branch_eventin_contents.py), so the calling agent only sees the tool'sFunctionResponse, as the FunctionTool and single-turn guides promise. Sliding-window and token-threshold compaction picked their events by rewind andisolation_scopeonly. They gave the sub-branch events to the summarizer, and the summary then carried them into every later prompt of the calling agent. The issue has a reproduction for both kinds of sub-branch and both triggers.Solution:
is_tool_sub_branch_eventmarks, with the function call ids of the live events in the scope, before the summarizer gets them. Token-threshold compaction checks for thecurrent_branchandagent_nameit already receives, the same check prompt building makes for that agent. Sliding-window compaction summarizes the root session, so it checks from the root._longest_self_contained_prefix,_safe_token_compaction_split_index) still see every event._is_tool_sub_branch_eventbecomesis_tool_sub_branch_eventso compaction can share it. The compliance check does not allow a new import of another module's_name._contents.pyis a private module, so the name stays internal. Compaction imports it inside the helper, asllm_event_summarizer.pydoes with_is_auth_event, because the context package importsapps.compaction.About the question in the issue (an agent that runs on a tool's sub-branch while compaction runs): while that tool call is still running, the calling agent's function call has no response yet, and both triggers already stop the compacted range before an open call. I checked this with a single-turn sub-agent that makes four model calls under token-threshold compaction. None of its events were compacted while it ran. The new unit test below also checks that an agent on a tool branch keeps its own events in its summary.
Testing Plan
Unit Tests:
New tests:
tests/unittests/apps/test_compaction_tool_branch_e2e.py::test_compaction_summary_leaves_out_tool_sub_branch_events, throughRunnerwith mock models: {generator tool, single-turn sub-agent} × {sliding window, token threshold}. The summarizer must get the first user message but not the sub-branch text, and the agent's turn-2 prompt must have the summary but not the sub-branch text. All 4 cases fail onmain.tests/unittests/apps/test_compaction.py::test_token_threshold_compaction_on_tool_branch_keeps_own_events: compaction for an agent onworkflow_tool@fc-1keeps its own text, its call tohelper_tooland the response, and drops the progress onworkflow_tool@fc-1.helper_tool@fc-2. Fails onmain.None of the 19 failures are related to this change:
tests/unittests/tools/(test_rest_api_tool.py,test_load_web_page.py,test_mcp_session_manager.py). They pick up my machine's HTTP proxy settings and fail the same way on an unmodifiedmain.telemetry/test_instrumentation.pytiming tests and twotest_bigquery_agent_analytics_plugin.pytests). They pass when run on their own, both with and without this change.Manual End-to-End (E2E) Tests:
The reproduction script from #8490: a
Runnerwith a scriptedBaseLlmfor the agents and a stand-in summary model that keeps the lines of its prompt that contain the sub-branch text (no network). Each case runs two user turns.Before (
mainat 5697bbd, alsogoogle-adk==2.15.1):After (this PR):
Checklist
Additional context
pre-commit runpasses on the changed files (ruff, isort, pyink, addlicense, ADK compliance checks, codespell).