Dynamic Context Assembly: Injecting RAG Chunks Just-in-Time in Google ADK
Master just-in-time context assembly in Google ADK agents to dynamically query, rank, and inject relevant RAG passages into prompt windows without token bloat.
Published on • December 5, 2026
AI Assistant

In complex enterprise agent architectures, shoving entire document repositories or indiscriminate vector search dumps into an LLM’s system instructions leads to ballooning token costs, slower time-to-first-token (TTFT), and middle-of-the-prompt recall degradation.
Dynamic Context Assembly (DCA) solves this by retrieving, filtering, and assembling domain-specific knowledge chunks just-in-time (JIT) immediately before execution turns or model calls. In Google Agent Development Kit (ADK), DCA transforms retrieval from a static prompt prefix into an adaptive pipeline synchronized with the agent’s turn lifecycle.
The Static RAG vs. Dynamic JIT Context Paradigm
In naive Retrieval-Augmented Generation (RAG), retrieval occurs once at the gateway level before the agent begins reasoning. This presents several critical flaws in multi-turn agentic workflows:
- Context Staling: Chunks retrieved on Turn 1 may be irrelevant by Turn 4 as the agent refines its goal.
- Prompt Pollution: Unused documents consume working memory and increase cognitive load.
- Cache Invalidation: Changing the prompt prefix dynamically invalidates prefix caches in Gemini 3.8.
Traditional Pre-Turn Retrieval (Static):
User Query ──> Embed ──> Vector Search ──> [Concat Chunks + History] ──> Model Turn
Dynamic Just-In-Time Assembly (ADK):
User Query ──> Agent Orchestrator ──> Tool Call / Reasoning Loop
│
┌──────────────────────────────────────┴──────────────────────────────────────┐
▼ ▼
Step-Specific Query Formulation Dynamic Context Assembler
│ │
Semantic Search + Hybrid Filter ────────────────────────────────────► Rank, Deduplicate & Token-Budget
│
▼
Inject into InvocationContext
│
▼
Targeted LlmAgent Step
Key Components of JIT Context Assembly in ADK
Dynamic context assembly relies on three core primitives within the Google ADK execution lifecycle:
- InvocationContext Hooks: Intercepting agent steps to inject retrieved fragments directly into the working context or system instructions.
- Context Budget Allocator: Enforcing strict upper token limits on injected chunks per turn.
- Relevance & Freshness Scoring: Evaluating chunks not just on semantic similarity, but on recent conversation delta.
Practical Implementation: Custom ADK Context Assembler
Below is a production-grade implementation of a JIT Context Assembler integrated as an ADK middleware hook.
import asyncio
from typing import List, Dict, Any
from dataclasses import dataclass
from google.genai import Client
from google.genai.types import Part
@dataclass
class RetrievedChunk:
chunk_id: str
text: str
score: float
source: str
token_count: int
class VectorKnowledgeStore:
"""Mock enterprise retrieval store (e.g., Vertex AI Search / Milvus)."""
async def search(self, query: str, top_k: int = 5) -> List[RetrievedChunk]:
await asyncio.sleep(0.05) # Simulated retrieval latency
return [
RetrievedChunk(
chunk_id=f"doc_{i}",
text=f"Relevant knowledge snippet {i} explaining {query}.",
score=0.92 - (i * 0.05),
source=f"kb_kb_{i}.pdf",
token_count=120
)
for i in range(top_k)
]
class DynamicContextAssembler:
def __init__(self, store: VectorKnowledgeStore, max_rag_tokens: int = 1500):
self.store = store
self.max_rag_tokens = max_rag_tokens
self.client = Client()
def assemble_context_block(self, chunks: List[RetrievedChunk]) -> str:
"""Packs chunks within token budget, formatting with clear boundary tags."""
allocated_tokens = 0
accepted_chunks = []
for chunk in chunks:
if allocated_tokens + chunk.token_count <= self.max_rag_tokens:
accepted_chunks.append(chunk)
allocated_tokens += chunk.token_count
else:
break
formatted_blocks = []
for c in accepted_chunks:
formatted_blocks.append(
f'<context_chunk id="{c.chunk_id}" source="{c.source}" score="{c.score:.2f}">\n'
f'{c.text}\n'
f'</context_chunk>'
)
return (
"<retrieved_knowledge>\n"
+ "\n".join(formatted_blocks)
+ "\n</retrieved_knowledge>"
)
async def pre_turn_hook(self, agent_name: str, user_turn: str, context: Dict[str, Any]) -> str:
"""Injects targeted context immediately before agent prompt compilation."""
retrieved = await self.store.search(user_turn, top_k=6)
context_block = self.assemble_context_block(retrieved)
# Store metadata for tracing and evaluation
context["injected_rag_chunks"] = [c.chunk_id for c in retrieved]
context["injected_rag_tokens"] = sum(c.token_count for c in retrieved)
return context_block
Integrating with ADK LlmAgent and Execution Runners
In Google ADK, agents compile their system instructions and active turn history inside Runner.run_async. Using dynamic instructions with state placeholders allows JIT injection without polluting long-term chat memory.
from google_adk.agents import LlmAgent
from google_adk.runners import Runner
from google_adk.sessions import InMemorySessionService
async def main():
knowledge_store = VectorKnowledgeStore()
assembler = DynamicContextAssembler(knowledge_store, max_rag_tokens=1000)
# Dynamic system instruction utilizing state placeholder
agent = LlmAgent(
name="SupportAnalyst",
model="gemini-3.8-flash",
system_instruction=(
"You are a technical support analyst. Use the provided retrieved knowledge "
"to answer accurately. If knowledge is missing, do not speculate.\n\n"
"{jit_context}"
)
)
runner = Runner(agent=agent, session_service=InMemorySessionService())
session = await runner.session_service.create_session("session_user_42")
query = "How do I configure mutual TLS in ingress controllers?"
# 1. Assemble context just-in-time
context_data = {}
jit_block = await assembler.pre_turn_hook("SupportAnalyst", query, context_data)
# 2. Update session ephemeral state
session.state["jit_context"] = jit_block
# 3. Execute runner turn
response = await runner.run_async(
session_id=session.id,
user_message=query
)
print("Agent Response:", response.text)
print("Injected chunks:", context_data.get("injected_rag_chunks"))
if __name__ == "__main__":
asyncio.run(main())
Trade-Offs and Architectural Considerations
| Dimension | Static RAG Pre-loading | Dynamic JIT Context Assembly |
|---|---|---|
| Token Efficiency | Low (over-fetches broad context) | High (calibrated to step objectives) |
| Context Freshness | Low (fixed at conversation start) | High (re-computed per sub-turn) |
| Prefix Cache Hit Rate | High if static system prompt stays untouched | Requires placing JIT context at predictable boundary |
| Latency Overhead | Single query up front (~150ms) | Per-turn query overhead (50–100ms) |
Best Practices for JIT Context in Production
- Preserve Prefix Caching: Place the static persona and tool definitions at the very beginning of the prompt. Place the
{jit_context}block after the static instructions or as a system user turn immediately preceding the user prompt. This preserves Gemini’s automatic prefix cache for the static agent instructions. - Deterministic Chunk Delimiters: Use strict XML-like tags (e.g.,
<retrieved_knowledge>) so models reliably distinguish between user directions and external facts. - Hard Token Guardrails: Always enforce an absolute cap on chunk size using token counters before passing content into the prompt.