---
title: "Google ADK: Structuring Large Contexts — Optimal Placement of Instructions, Tools, and Data"
date: "2026-12-04T08:54:43+07:00"
description: "Where each piece of a large ADK prompt belongs, based on Gemini's fixed serialization order — and what each placement choice costs in cache hits and quality."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/structuring-large-contexts-placement.jpg"
alt: "Layered blocks of a prompt arranged in order: model config, tools, system instruction, history, and user input"
tags: ['google-adk', 'context-engineering', 'prompt-management', 'caching', 'gemini']
---

Ask ten engineers where the tool definitions go in a large prompt and you will get ten answers — usually "somewhere in there, the model will sort it out." The model does sort it out for *quality*, but the runtime does not sort it out for *cost*: Gemini serializes every request in a fixed four-part order, and the first byte that differs between two requests kills the cache for everything below it. Placement is therefore a billing decision as much as a quality decision.

The second problem is subtler. In a 500K-token context, instructions, tool schemas, retrieved documents, and chat history all compete for the same budget, and each has a different failure mode when it is misplaced. Instructions in the wrong slot get invalidated by a tool edit. Volatile timestamps in the system prompt bust the entire history. Retrieval data crammed above the question forces the model to scan it three times per turn. A 40-tool schema block can push a medium request below the cache floor or above the point where attention degrades.

This article maps each element of an ADK agent to its exact slot in the request, explains what each slot costs, and gives a reference layout with a token budget you can adapt.

## 1. The four-slot request

Gemini 4's documented serialization order — top to bottom, first change breaks everything below it:

| Slot | Contents | Volatility | ADK field you control |
| --- | --- | --- | --- |
| **1. Model config + built-in server tools** | `thinking_level` first, generic structured-output instructions, built-in tools (`code_execution`, `google_search`, `url_context`) | Must be constant per session | `generate_content_config` (temperature, `max_output_tokens`, thinking config) |
| **2. Tools and function declarations** | Built-in tools, deferred tools sorted alphabetically, your custom `function` declarations in array order | Very low — reorder busts slot 3 + 4 | `tools=[...]` on `LlmAgent` |
| **3. `system_instruction`** | Your developer prompt | Low — edits invalidate history below | `instruction=` |
| **4. History + user input** | Prior turns oldest-first, injected `response_format` schema, grounding context, then the latest user message | Highest — changes every turn | `include_contents`, session events, the message you send |

Two consequences worth memorizing:

> Because tools serialize **before** `system_instruction`, adding, removing, or reordering non-deferred tools invalidates both the instruction and the entire conversation history. Changing `thinking_level` alone invalidates 100% of the prefix.

> Volatile values belong in the final content block of slot 4 — the one place where change is expected and free.

The ADK equivalents of these rules: never put timestamps, UUIDs, or session ids into `instruction`; pass them in the user message or in session state.

## 2. Slot 1 — model configuration

Set it once per workflow and never touch it mid-session. `thinking_level` serializes first, so flipping thinking on for "hard turns" silently converts every cache hit into a miss — route different reasoning depths to different workflows instead. Same story for structured output: toggling JSON mode invalidates the prefix from slot 1 onward, while *changing only the JSON schema* keeps slots 1–3 and earlier turns cached.

Practical ADK note: `generate_content_config` is where temperature and `max_output_tokens` live, but ADK raises `ValueError` if you put `tools`, `system_instruction`, or `response_schema` there — those have dedicated fields precisely because they occupy fixed slots of their own.

## 3. Slot 2 — tools, the most expensive mistake

Tool schemas are the classic "write once, resend forever" payload: a 30-tool library can be 4–6K tokens re-read on *every* turn. Three placement strategies, in increasing sophistication:

1. **Curate.** Only attach tools the agent can plausibly use this session. A sub-agent reached through `sub_agents`/`AgentTool` carries its own schema and keeps it out of the parent's slot 2 entirely.
2. **Defer.** On the Gemini API, `{"type": "tool_search"}` plus `defer_loading: true` emits only each deferred tool's name and short description in the prefix, sorted alphabetically by name; the full schema is appended inline later when retrieved, so earlier turns stay cached. Watch the floor: deferring aggressively can drop a medium request below the 4,096-token minimum where implicit caching stops applying.
3. **Freeze the order.** Reordering your non-deferred `tools` array is a cache-busting change with zero benefit. Alphabetical-at-definition-time is fine; alphabetical-*at-runtime* is not something you should re-derive per call.

Also budget for ADK's built-in constraint: Code Execution, Google Search, and Agent Search must be used alone in an agent. The documented workarounds — wrapping each in its own agent and exposing them via `AgentTool` — double as a context win: the parent's slot 2 holds only tool *descriptions of agents*, not the underlying schemas.

## 4. Slot 3 — instructions: static core, dynamic edge

ADK offers four mechanisms with different cache properties. Use them deliberately:

| Mechanism | Cache effect | Use for |
| --- | --- | --- |
| Static `instruction="..."` | Perfect — part of the stable prefix | Policy, persona, output format, tool guidance |
| `{state_key}` templating | Value is rendered into the instruction each turn; a changing value rewrites slot 3 and invalidates history below it | Stable-per-session values (plan, phase) |
| `{state_key?}` optional templating | Same, but tolerates missing keys | Values that may be absent |
| `InstructionProvider` (function) | Full control; ADK skips state injection unless you call `inject_session_state` | Instructions containing literal braces (JSON examples) or computed text |

Rules of thumb: put **rules** in the static string and **variables** in state or the user message. If a templated value changes every turn — a running clock, a queue length — it does not belong in slot 3; it belongs in slot 4 where change is free. And if you need the same sentence appended to *every* agent's prompt, `static_instruction` (shown in ADK's context-caching samples) is the documented hook rather than copy-pasting strings.

## 5. Slot 4 — history and data

This is the only slot that is *supposed* to change, which makes it the right home for everything volatile:

- **History volume** is governed by `include_contents`: `'default'` sends the relevant conversation, `'none'` sends only the current turn. Stateless workers get `'none'`; the conversational agent keeps `'default'`.
- **History height** is governed by compaction — `EventsCompactionConfig(compaction_interval, overlap_size, token_threshold, event_retention_size)` folds older events into a summary and keeps a raw tail, so the transcript stops growing linearly with turns.
- **Retrieval data** goes *before* the variable question, in a stable order. Upload reusable documents once with the Files API and place file references above the query text (`{"type": "document", "uri": ..., "mime_type": ...}` then `{"type": "text", "text": question}`), keeping file order identical across requests so the tokenized document forms a reusable prefix.
- **Timestamps, request ids, session ids** go in the final content block. Never above.

```python
from datetime import datetime, timezone
import uuid
from google.adk import Agent

# Slots 1-3: frozen for the lifetime of the session.
root_agent = Agent(
    name="claims_agent",
    model="gemini-3.8-flash",
    instruction=(
        "You adjudicate insurance claims. Follow the handbook rules, call "
        "lookup_policy before ruling, and answer with a decision plus a one-line rationale."
    ),
    tools=[lookup_policy, open_claim],   # fixed array, fixed order
    include_contents="default",           # history lives here, in slot 4
)

# Slot 4: everything volatile rides with the turn, not the instruction.
def build_turn(question: str) -> str:
    return (
        f"Request ID: {uuid.uuid4()}\n"
        f"Timestamp: {datetime.now(timezone.utc).isoformat()}\n"
        f"Question: {question}"
    )
```

## 6. A reference budget for a large context

For an agent operating inside a 1M-token-class window, allocate before you optimize:

| Region | Share of window | Contents | Primary risk if oversized |
| --- | --- | --- | --- |
| Slots 1–2 | 1–3% | Thinking config, curated tool schemas | Re-read every turn; reorder busts everything |
| Slot 3 | <1% | Static instruction + rendered state | A single volatile `{key}` here costs all of slot 4's cache |
| Retrieved data | 10–40% | Files API documents, tool results | Placed above the question → re-scanned every turn |
| Raw history tail | 5–15% | Recent turns after compaction | Too small → pronoun resolution fails |
| Reserve | ≥20% | Output + thinking + tool round-trips | Truncation of the answer you actually wanted |

Fill slots in that order, leave the reserve, and push anything that does not fit into compaction or a retrieval tool rather than compressing it into the instruction.

## 7. Measure the placement, do not argue it

Two cheap, objective checks:

```python
from google.genai import types

def log_prefix_health(label: str, response) -> None:
    """Read the cache meter after every turn; a drop means a prefix changed."""
    meta = response.usage_metadata
    cached = getattr(meta, "cached_content_token_count", None) or 0
    total = getattr(meta, "prompt_token_count", 0) or 1
    print(f"{label}: cached={cached}, prompt={total}, hit={cached / total:.1%}")
```

and, at the ADK level, the evaluation framework's efficiency criteria — `token_usage_v1`, `tool_call_count_v1`, `inference_call_count_v1`, and `invocation_duration_v1` are reported automatically on every eval run. Compare them across releases: a placement change that keeps quality flat but doubles `token_usage_v1` is a regression, and these metrics catch it without any extra model calls.

## Checklist

- [ ] Write down the four slots and decide which of your fields belongs in each one.
- [ ] Freeze `thinking_level`, tool array, and order per session; never vary them mid-conversation.
- [ ] Keep timestamps, UUIDs, and session ids out of `instruction` — put them in the final user message.
- [ ] Prune or defer tool schemas; wrap mutually exclusive built-in tools in separate agents via `sub_agents`.
- [ ] Separate static rules from dynamic values: string vs `{key}` templating vs `InstructionProvider`.
- [ ] Apply `include_contents` and `EventsCompactionConfig` so history volume is a setting, not an accident.
- [ ] Place retrieved documents above the question and keep their order byte-stable across calls.
- [ ] Reserve ≥20% of the window for output, thinking, and tool round-trips.
- [ ] Log cache hit rate and `token_usage_v1` per turn so placement regressions surface immediately.

## Conclusion

Large-context design is mostly an ordering problem. Gemini's fixed serialization — config, tools, instruction, history — means the cheapest prompt is one that changes only in its last block, and every ADK field maps cleanly onto one of those four slots. Freeze the top three, concentrate volatility in the fourth, and put the bulk of your tokens behind retrieval and compaction rather than in front of the model's attention.

Do it deliberately and the same agent gets cheaper *and* more predictable: fewer cache misses, fewer tokens per turn, and a context structure you can explain to a reviewer in four lines.

## References

- https://adk.dev/
- https://ai.google.dev/gemini-api/docs/caching
- https://adk.dev/agents/llm-agents/
- https://adk.dev/sessions/state/
- https://adk.dev/context/compaction/
- https://adk.dev/tools/limitations/
