google adk - compactiing conversation
We can easily compact our conversation by using the following code. Notice we are using App and EventsCompactionConfig (it is experimental) that can help to optimized latency and reduces cost.
How we choose to compact our conversation is defined here
Threshold approach
# 3. Compaction config
compaction_config = EventsCompactionConfig(
# Token-based (primary): compact when the prompt exceeds this many tokens
token_threshold=1000,
event_retention_size=3, # keep the last 3 events raw
# Sliding window (supplementary): compact every N invocations
compaction_interval=3,
overlap_size=1,
summarizer=summarizer,
)
If you opt for sliding window compact approach
Sliding window approach
compaction_config = EventsCompactionConfig(
compaction_interval=10, # Number of new invocations between standard compactions
overlap_size=2, # Number of prior invocations to retain as overlapping context
)
Custom summarizer
We can define our own customizer.
from google.adk.apps.app import App, EventsCompactionConfig
from google.adk.apps.llm_event_summarizer import LlmEventSummarizer
from google.adk.models import Gemini
# Define the AI model to be used for summarization:
summarization_llm = Gemini(model="gemini-flash-latest")
# Create the summarizer with the custom model:
# 1. Custom prompt. It MUST contain {conversation_history}.
CUSTOM_PROMPT = """You are compressing the history of a conversation between a user and an AI agent.
Write a compact summary that the agent can rely on instead of the original messages.
Always preserve:
- The user's name, preferences, constraints and goals
- Decisions that were made, with the reason
- Facts, numbers, names, IDs and file/tool outputs that may be needed later
- Open questions and unfinished tasks
Drop greetings, filler, repetition and anything already resolved.
Use short bullet points. Do not invent anything not in the conversation.
Conversation history:
{conversation_history}
"""
# 2. Summarizer with the custom prompt
summarizer = LlmEventSummarizer(
llm=summarization_llm,
prompt_template=CUSTOM_PROMPT,
)# Configure the App with the custom summarizer and compaction settings:
app = App(
name='my-agent',
root_agent=root_agent,
events_compaction_config=EventsCompactionConfig(
compaction_interval=3,
overlap_size=1,
summarizer=my_summarizer,
),
)
And the full code is here :-
# run_with_compaction.py
import asyncio
import os
# Vertex AI auth (ADC). Remove these lines if you use an API key instead.
os.environ.setdefault("GOOGLE_GENAI_USE_VERTEXAI", "TRUE")
os.environ.setdefault("GOOGLE_CLOUD_PROJECT", "your-project-id")
os.environ.setdefault("GOOGLE_CLOUD_LOCATION", "us-central1")
from google.adk.agents import Agent
from google.adk.apps.app import App, EventsCompactionConfig
from google.adk.apps.llm_event_summarizer import LlmEventSummarizer
from google.adk.models import Gemini
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
MODEL = "gemini-flash-latest"
USER_ID = "user_1"
SESSION_ID = "session_1"
# 1. Root agent
root_agent = Agent(
name="root_agent",
model=MODEL,
description="General assistant.",
instruction="You are a helpful assistant. Keep answers short.",
)
# 2. Summarizer used for compaction (can be a cheaper/faster model)
summarizer = LlmEventSummarizer(llm=Gemini(model=MODEL))
# 3. Compaction config
compaction_config = EventsCompactionConfig(
# Token-based (primary): compact when the prompt exceeds this many tokens
token_threshold=1000,
event_retention_size=3, # keep the last 3 events raw
# Sliding window (supplementary): compact every N invocations
compaction_interval=3,
overlap_size=1,
summarizer=summarizer,
)
# 4. App wraps the root agent + compaction config
app = App(
name="compaction_demo_app",
root_agent=root_agent,
events_compaction_config=compaction_config,
)
# 5. Runner takes the app + services
session_service = InMemorySessionService()
runner = Runner(app=app, session_service=session_service)
async def ask(text: str) -> str:
message = types.Content(role="user", parts=[types.Part(text=text)])
reply = ""
async for event in runner.run_async(
user_id=USER_ID, session_id=SESSION_ID, new_message=message
):
if event.is_final_response() and event.content and event.content.parts:
reply = "".join(p.text or "" for p in event.content.parts)
return reply
async def main():
await session_service.create_session(
app_name=app.name, user_id=USER_ID, session_id=SESSION_ID
)
prompts = [
"My name is Sam and I'm planning a trip to Japan.",
"Suggest 3 cities to visit.",
"Tell me more about the second one.",
"What food should I try there?",
"How many days should I spend?",
"What's my name and where am I travelling?", # tests recall after compaction
]
for p in prompts:
print(f"\nUSER: {p}")
print(f"AGENT: {await ask(p)}")
# Check whether compaction events were written to the session
session = await session_service.get_session(
app_name=app.name, user_id=USER_ID, session_id=SESSION_ID
)
compactions = [
e for e in session.events
if getattr(e.actions, "compaction", None) is not None
]
print(f"\nTotal events: {len(session.events)}, compaction events: {len(compactions)}")
if __name__ == "__main__":
asyncio.run(main())
Comments