Back to paths

Context engineering at scale

Context is a per-call budget. Break a turn into its parts, cut each one with the right technique, know what context caching does and does not do, and prove every change with an evalset.

advanced~35 min#agentic-ai#adk#context#evaluation
Chapter 4Custom agentsLesson 8 of 8Show

Prerequisites: Building agents with ADK


Context is a budget

Every model call an agent makes carries a : everything the model sees in that one call. At low traffic you can ignore it. At scale, it decides three things:

  • Cost. Input tokens are billed on every call, and an agent makes several calls per turn.
  • Latency. More tokens take longer to process before the first output token.
  • Quality. Material the model does not need still competes for its attention: an extra tool is one more wrong choice, an old turn is one more thing to misread.

So treat context as a budget, and spend it on what the current step needs.

Break a turn into its parts

On each call an ADK agent sends the model these parts, in roughly this order: the parts that stay the same on every call first, then the parts that change.

ComponentWhat it isGrows with
InstructionsThe agent's instruction (system prompt)Fixed per agent (except values filled in from session state, covered below)
Tool declarationsName, description and parameters of every tool the agent can callNumber of tools
HistoryEarlier turns, including tool calls and tool resultsEvery turn
MemoryFacts recalled from past sessionsHow memory is recalled
Retrieved contentChunks of documents fetched from a knowledge baseNumber of chunks and their size
User messageThe new inputMessage length

To find the largest part, measure it. Each model response carries usage metadata, a set of token counts for that call, including the prompt's total. The Gemini API's count_tokens call counts any piece on its own, such as the instructions, the declarations or the retrieved chunks. Measure on real long sessions, because history is small at turn 2 and dominant at turn 20.

Take a support agent at ten times its launch traffic. Two MCP servers have been connected (MCP, the Model Context Protocol, is the standard way to plug a server's ready-made tools into an agent), so it now has 40 tools, and its conversations run long. A turn late in a long session looks like this (illustrative numbers):

  • instructions 3,000 tokens
  • tool declarations 10,000 (40 tools at about 250 each)
  • history 18,000
  • preloaded memory 6,000
  • retrieved chunks 10,000 (ten chunks of about 1,000 tokens)

That is 47,000 tokens before the user's message, and history is the largest part.

How do you find which part of an agent's context to cut first?

Cut each part with the right technique

Predict first: after the cuts, you cache the prefix. How many tokens does the model still read? Then step through the same late turn in Context budget explorer: each cut shrinks one component, and each subsection below explains one step.

Simulation: context-budget-explorer

Tool declarations: expose only what the step needs

Every declaration is in front of the model on every call, so 40 tools mean 40 candidates for each choice, many with similar names, and about 10,000 tokens of declarations. Give each agent, or each step, only the tools it needs:

  • Filter a toolset. An ADK McpToolset connects to one MCP server and exposes its tools to the agent. It takes a tool_filter list, and ADK's security and scoping guidance is to always supply one, so the model sees only the necessary actions.
  • Split by task. A coordinator delegates to sub-agents (topic 3.2), each with a short instruction and the handful of tools its task needs.
from google.adk.tools.mcp_tool import McpToolset
from google.adk.tools.mcp_tool.mcp_session_manager import StreamableHTTPConnectionParams
 
orders_tools = McpToolset(
    connection_params=StreamableHTTPConnectionParams(url=ORDERS_MCP_URL),
    tool_filter=["get_order", "get_refund_status", "check_warranty"],
)

With the other server filtered the same way, the agent sees 8 tools instead of 40, and the declarations drop to about 2,000 tokens. A model with a larger context window does not help here: it fits all 40 declarations, and all 40 choices are still in front of the model.

History: compact it

ADK records a session as events: each user message, model reply, tool call and tool result is one event, and one user turn with everything it triggers is one invocation. summarises older events and keeps the most recent ones as they were. In ADK you set an EventsCompactionConfig on the App, ADK's top-level object that wraps the root agent together with app-wide settings such as compaction and caching, and the runner compacts the session's events for you. Token-based compaction triggers once a model call's prompt reaches a threshold, and keeps the last few events raw; a sliding window instead compacts every few invocations.

from google.adk.apps.app import App, EventsCompactionConfig
 
app = App(
    name="support_app",
    root_agent=root_agent,
    events_compaction_config=EventsCompactionConfig(
        token_threshold=30000,    # compact once a call's whole prompt reaches this
        event_retention_size=5,   # keep the 5 most recent events as they were
    ),
)

The threshold counts the whole prompt, so set it above the fixed part (instructions, tools, memory and retrieval), or every call compacts. Pass the App to the runner, Runner(app=app, session_service=...); compaction runs only through the App.

A summary can drop a detail. Facts the agent will need again, such as an order id, belong in session state: key-value pairs stored on the session for the whole conversation, which compaction does not summarise (Sessions, state and Memory Bank covers state in full). A tool writes a key, for example tool_context.state["order_id"] = order_id, and an optional placeholder such as {order_id?} in the agent's instruction puts the value back in front of the model on every call. The ? makes it render empty until the key is set. Put placeholders at the end of the instruction, so the fixed text before them stays the same on every call. With ADK's explicit caching (below), a change to a placeholder's value means a new cache wherever the placeholder sits.

Memory: recall it on demand

Long-term memory is a store, searchable across sessions, that ADK's memory service fills from past conversations. It is separate from session state, which lasts for one session. ADK offers two ways to bring memory into a turn. The preload_memory tool searches memory with the turn's user message before every model call and adds the results, so what it adds changes from turn to turn. The load_memory tool lets the model search memory only when it judges a turn needs it. If most turns are about the current order, preloading spends memory tokens on every call for nothing; load_memory fetches them only on the turns that ask.

Fetching less often is not the whole story. Preloaded memory is added to each call and not kept, but a load_memory result is an ordinary tool result, so it stays in the history and rides along on later calls until compaction summarises it. Count both the newly fetched tokens and the recalled tokens still in history, and measure prompt totals over several turns rather than inferring them from how often the tool is called. In the example, assume one turn in four recalls memory and compaction summarises each recall within a turn or so: memory then costs about 1,500 tokens per late turn instead of 6,000. That is an assumption to check with measurements, not a rule.

Retrieved content: pass fewer, better chunks

Retrieval splits documents into chunks, finds the k chunks that best match the query (the top-k), and adds them to every call that answers from retrieved content. A reranker rescores those candidates for relevance so you can pass fewer of them. Reranking plus a smaller top-k (the RAG lesson goes deeper) usually keeps the right evidence in fewer tokens. Retrieve only on the steps that need it.

Images, video and PDFs: send by reference, cap the tokens

Media raises two separate problems, with two separate fixes.

  • Payload size and reuse. Inline bytes travel inside every request that carries them, and requests have a size limit (the Gemini API documents 100 MB per request inline, 50 MB for PDFs; check your endpoint's limit). For a large file, or one used on many calls, pass a Cloud Storage URI (gs://...) instead: Agent Platform accepts one directly, and the Gemini Developer API takes it once registered through its Files API. The request then carries a reference, and the bytes are not uploaded again on each call.
  • Tokens. A referenced file still costs tokens every time it is in the context. The media_resolution setting caps how many tokens each image or video frame may use, and the visual tokens of each PDF page; text extracted natively from a PDF counts on top, so a text-heavy PDF costs more than its visual budget even at low. For Gemini 3 and later images, low is 280 tokens, medium 560, high 1,120 (also the default) and ultra_high 2,240. Video frames use 70 tokens at low or medium and 280 at high. Lower it when the task does not need fine detail, such as classifying a photo, and raise it for small text in a scanned document.

A support agent receives large product photos and reuses them across a session. What do a Cloud Storage URI and media_resolution each fix?

In the support agent above, which cut alone removes the most tokens per late turn?

Context caching: cheaper, not smaller

The model reads a request from front to back. The parts that are the same on every call (instructions and tool declarations) form its front, or prefix; history, memory, retrieved chunks and the new message come after it.

reuses the processing of a prefix that repeats across calls. It cuts the cost and latency of that prefix. It does not cut the context: the cached tokens still form part of the input context, still count in the context window, and are still in front of the model.

  • Implicit caching is on by default for Gemini 2.5 and newer models. It applies when a request's prefix matches an earlier one and is above a model-specific minimum. On Agent Platform that is 2,048 tokens on Gemini 2 family models, 4,096 on most Gemini 3 and on Gemini 4 models, and 6,144 on a few Flash and Preview models (Gemini 3.0 Flash Preview, 3.1 Pro Preview, 3.7 Flash and 3.8 Flash). An implicitly cached prefix lives for up to 24 hours. Put large, common content at the start of the prompt and changing content, such as the date, after it.
  • ADK's context caching is configured on the App with a ContextCacheConfig (min_tokens, ttl_seconds, cache_intervals). ADK then creates and refreshes cache entries itself, with a lifetime and a reuse count you set, instead of relying on automatic matching. The class is experimental, and explicit caches are not available on every model: Gemini 4 models and the four 6,144-token models above support implicit caching only, so ContextCacheConfig won't help there and prompt order is the lever.
  • The response's usage metadata reports how many tokens came from the cache (cached_content_token_count in the Gemini API's usage_metadata), so check that count, not the input total.

On Agent Platform, implicitly cached tokens are discounted 95% on Gemini 4 and later models, 90% on Gemini 3 and 2.5, and 75% on earlier models (so on Gemini 3.5 Flash they bill at a tenth of the input rate). Explicit caches, such as those ADK's ContextCacheConfig creates, also bill storage for each hour they live. Rates vary by model, so check the current pricing page for yours.

Caching pairs with the cuts above: it makes a lean, stable prefix cheap. It is not a substitute for them.

Prove every change with an evalset

A context change can save tokens and quietly break an answer: a filter drops a tool a rare request needs, or a summary drops a detail. Token counts show the saving; only evaluation shows the cost.

An is a fixed set of cases. Each case is a conversation that records the user's input, the tool calls you expect (with arguments) and a reference reply. ADK runs the agent on every case and scores it:

  • tool_trajectory_avg_score checks that the agent made the expected tool calls. Default threshold 1.0, an exact match.
  • response_match_score checks how close the reply is to the reference. Default threshold 0.8.

Each criterion scores a case from 0 to 1, averaged over its turns, and a case passes when its score reaches the threshold.

The same run also reports efficiency values that never pass or fail a case. One of them, token_usage_v1, gives the average tokens per invocation, with a breakdown that includes input, cached and output tokens. So one run measures both the quality and the saving. Building evaluation datasets and Choosing evaluation criteria go deeper.

The loop for each change:

  1. Run the evalset on the current agent and record the scores and token_usage_v1.
  2. Make one change, such as the tool filter.
  3. Run the same evalset again with adk eval.
  4. Ship only if the scores hold and the tokens fell. If a score drops, look at which cases failed: they usually share a cause, such as a missing tool.

Here is a ready-made evalset for the support agent. It has three cases: a refund status check, a warranty question that needs the tool a careless filter drops, and a conversation whose last turn needs the order id from the first, which catches compaction that loses it. Once the state fix is in, get_order stores the id in session state; before it, the id survives only if the compaction summary happens to keep it.

{
  "eval_set_id": "support_context_checks",
  "eval_cases": [
    {
      "eval_id": "refund_status",
      "conversation": [
        {
          "user_content": {"role": "user", "parts": [{"text": "Where is my refund for order A1234?"}]},
          "final_response": {"role": "model", "parts": [{"text": "The refund for order A1234 was issued and should reach you within 5 business days."}]},
          "intermediate_data": {"tool_uses": [{"name": "get_refund_status", "args": {"order_id": "A1234"}}]}
        }
      ],
      "session_input": {"app_name": "support_app", "user_id": "eval_user", "state": {}}
    },
    {
      "eval_id": "warranty_question",
      "conversation": [
        {
          "user_content": {"role": "user", "parts": [{"text": "Is the blender from order B5678 still under warranty?"}]},
          "final_response": {"role": "model", "parts": [{"text": "Yes, the blender from order B5678 is under warranty until March 2027."}]},
          "intermediate_data": {"tool_uses": [{"name": "check_warranty", "args": {"order_id": "B5678"}}]}
        }
      ],
      "session_input": {"app_name": "support_app", "user_id": "eval_user", "state": {}}
    },
    {
      "eval_id": "long_session_recall",
      "conversation": [
        {
          "user_content": {"role": "user", "parts": [{"text": "Hi, I'm asking about order C9012."}]},
          "final_response": {"role": "model", "parts": [{"text": "I found order C9012. How can I help with it?"}]},
          "intermediate_data": {"tool_uses": [{"name": "get_order", "args": {"order_id": "C9012"}}]}
        },
        {
          "user_content": {"role": "user", "parts": [{"text": "What is your return window?"}]},
          "final_response": {"role": "model", "parts": [{"text": "You can return items within 30 days of delivery."}]},
          "intermediate_data": {"tool_uses": []}
        },
        {
          "user_content": {"role": "user", "parts": [{"text": "OK, then please check my refund."}]},
          "final_response": {"role": "model", "parts": [{"text": "The refund for order C9012 is being processed."}]},
          "intermediate_data": {"tool_uses": [{"name": "get_refund_status", "args": {"order_id": "C9012"}}]}
        }
      ],
      "session_input": {"app_name": "support_app", "user_id": "eval_user", "state": {}}
    }
  ]
}

The replies and tool results in these cases depend on your own test data. Point the tools at a fixed test store so the expected replies stay true from run to run. A real evalset needs many more cases; this one is sized to catch the changes in this lesson.

In the file, user_content is the input, intermediate_data.tool_uses the expected tool calls, final_response the reference reply, and session_input the session's starting state.

Two settings make the run test what you changed. First, expose the App as app in your agent module: adk eval uses the App's compaction and caching settings only then. Second, the third case has only three turns, so with the production settings above compaction never reaches its first turn. In a test copy of the App, set a threshold and retention that are low on purpose, such as token_threshold=2000 and event_retention_size=2. That is below the agent's fixed prompt, so every call compacts and turn 1 is summarised before turn 3 runs. Check the first reply's prompt_token_count to confirm the prompt is above the threshold, or nothing is compacted and the case passes without testing anything.

adk eval support_agent support_agent/support_context_checks.evalset.json --print_detailed_results

The first argument is the agent's folder; the second is the evalset file, saved inside it. Here is what the loop might show for this lesson's changes (illustrative results; token figures come from long real sessions, and the failures from the evalset with the test settings above):

ChangeTokens per late turnFailing caseVerdict
Tool filter that left out check_warranty39,000warranty_questionAdd the tool back to the filter
Compaction, order id kept only in history25,000long_session_recallStore the id in state
Both fixed, plus on-demand memory20,500NoneShip

How do you decide whether a context change ships?

Try it: cut the budget without losing the evidence

The simulation below packs the same late turn, 47,000 tokens, into a backpack, one block per component. Three gems ride inside: the evidence each evalset case needs (the check_warranty declaration, order id C9012 in the history, and the return-policy fact in retrieved chunk 7). A cut that drops a gem sends it to the "lost" tray, and its case fails. Predict first: if you compact the history and change nothing else, which case breaks?

Then find a set of cuts that brings the turn under the goal line, about 21,000 tokens, with all three gems still in the bag. Turn on caching last and watch what changes on the receipt, and what does not.

Simulation: context-budget-explorer

Explain it: when long_session_recall failed, which removed item caused it, and why does session state fix one of its causes but not the other?

Recap

  • Context is a per-call budget: it drives cost, latency and quality.
  • Measure tokens by component on long sessions, and cut the largest first.
  • Filter tools, compact history (keep needed facts in state), recall memory on demand, and pass fewer, better chunks.
  • Caching makes a stable prefix cheaper; it does not make the context smaller.
  • Run the same evalset before and after each change, one change at a time.

Sources

Show 14 sourcesHide sources
SourcePublisherWhat it supports
File input methods (opens in a new tab)ai.google.devGoogle, Gemini API documentationinline data up to 100 MB per request, 50 MB for PDFs; Cloud Storage URI registration and the Files API for large or reused files
Media resolution (opens in a new tab)ai.google.devGoogle, Gemini API documentationmedia_resolution caps tokens per media item, with PDF native text counted on top; Gemini 3 images: low 280, medium 560, high 1,120, ultra_high 2,240, default 1,120; video frames 70 at low or medium and 280 at high
Compress agent context for performance (opens in a new tab)github.comGoogle, Agent Development Kit documentationEventsCompactionConfig on the App; token-based compaction with token_threshold and event_retention_size; sliding window with compaction_interval and overlap_size; pass the App to the Runner
Context caching with Gemini (opens in a new tab)github.comGoogle, Agent Development Kit documentationContextCacheConfig on the App with min_tokens, ttl_seconds and cache_intervals; experimental
MCP tools (opens in a new tab)github.comGoogle, Agent Development Kit documentationtool_filter on McpToolset; always supply tool_filter to expose only necessary actions
Memory (opens in a new tab)github.comGoogle, Agent Development Kit documentationpreload_memory and load_memory; load_memory retrieves memory when the agent decides it would help
Agent Development Kit, adk-python source, src/google/adk/tools/preload_memory_tool.py (process_llm_request runs on each model request, searching memory with the turn's user message) and src/google/adk/flows/llm_flows/prompt/_instructions_utils.pyGooglea missing state key raises an error unless the placeholder ends in ?
Why evaluate agents (opens in a new tab)github.comGoogle, Agent Development Kit documentationevalset structure; tool_trajectory_avg_score default 1.0 and response_match_score default 0.8; the adk eval command
Agent Development Kit, adk-python source, src/google/adk/cli/cli_eval.py (get_app_or_root_agent) and src/google/adk/evaluation/evaluation_generator.pyGooglethe eval runner is built from the module's app when present
Evaluation criteria (opens in a new tab)github.comGoogle, Agent Development Kit documentationefficiency criteria are always on and informational; token_usage_v1 reports tokens per invocation with input, cached and output breakdown
Context caching (opens in a new tab)ai.google.devGoogle, Gemini API documentationimplicit caching on by default for Gemini 2.5 and newer; minimum input tokens per model; put large and common content at the start of the prompt; cached tokens reported in the response's usage data
Context caching overview (opens in a new tab)docs.cloud.google.comGoogle Cloudretrieved 2026-12-02: minimum cache tokens of 4,096 for Gemini 3 (with exceptions) and Gemini 4 models (Gemini 4: implicit caching only); 6,144 for Gemini 3.0 Flash Preview, 3.1 Pro Preview, 3.7 Flash and 3.8 Flash, implicit caching only; 2,048 for Gemini 2 family models; implicitly cached prefixes live up to 24 hours; implicit caching discount 95% for Gemini 4 and later, 90% for Gemini 3 and 2.5, 75% for Gemini 2 and earlier
Generative AI pricing (opens in a new tab)and Gemini API pricing, ai.google.dev/gemini-api/docs/pricing (opens in a new tab)cloud.google.comGoogle Cloudcached input rates, for example $0.15 against $1.50 per million input tokens for Gemini 3.5 Flash, plus hourly storage for explicit caches; retrieved 2026-11-17
Gen AI SDK, google-genai types, GenerateContentResponseUsageMetadata.cached_content_token_countGooglethe cached-token count on generateContent responses, which ADK events carry as usage_metadata

Suggested videos

Show 2 videosHide videos

Review

Flashcards1 / 3

What goes into an agent's context on each model call?

Check yourself

Quick exam1 / 9 · 0 correct

A support agent's turn 20 carries 3,000 tokens of instructions, 10,000 of tool declarations, 18,000 of conversation history, 6,000 of preloaded memory and 10,000 of retrieved chunks. Which component should you work on first?

Your notes on this lesson