Configuring System Instructions: Dynamic Prompt Templating with State Injection
Learn how ADK's LlmAgent instruction templating injects session state with {key} syntax, when to use {key?} and InstructionProvider, and how to update state safely.
Published on • November 24, 2026
AI Assistant

An ADK agent’s instruction is more than a static system prompt. In LlmAgent, the instruction is a string template: the framework replaces {key} placeholders with values from session.state before the prompt ever reaches the model. That gives you per-user, per-session personalization without asking the LLM to “remember” anything or parse natural-language directives.
This tutorial covers the full templating surface — {key}, {artifact.var}, the {key?} escape hatch, and the InstructionProvider function form for literal braces — plus the state mechanics that feed it. If you are new to what actually lives in an agent’s context window, read context-engineering-managing-what-agent-sees.md first.
The {key} templating syntax
From the ADK docs on simple agents, the rules are small but strict:
{key}inserts the value of the state variable namedkey.{artifact.var}inserts the text content of the artifact namedvar.- If the state variable or artifact does not exist, the agent raises an error.
- Append
?to make a variable optional:{var?}.
from google.adk.agents import LlmAgent
story_generator = LlmAgent(
name="StoryGenerator",
model="gemini-flash-latest",
instruction="""Write a short story about a cat, focusing on the theme: {topic}."""
)
# With session.state['topic'] == "friendship", the LLM receives:
# "Write a short story about a cat, focusing on the theme: friendship."
Values should be strings, or types that convert cleanly to strings. The state page also warns that the {key} syntax matches any valid Python identifier inside single braces — so a stray {not_a_state_key} in your prompt will fail at runtime unless you make it optional.
instruction="""You are a billing assistant for {user:account_tier}.
Optional context: {temp:last_tool_output?}
Never disclose {app:internal_policy_version} internals to the user."""
Note how the prefixed keys above map to real state scopes: user: is shared across all sessions for that user, app: is shared across the whole application, and temp: exists only for the current invocation and is discarded when it ends.
Avoiding the missing-key error
The safest default for anything that may not be populated is the ? suffix. A hard {topic} throws if a session was created without that key — common when older sessions predate a new instruction you just shipped.
| Syntax | Missing key behavior | Use when |
|---|---|---|
{topic} | Raises an error | The key is always set before the agent runs |
{topic?} | Silently skipped | The key is optional or sessions predate it |
{user:language} | Raises an error | User-scoped preference is guaranteed |
{artifact.report} | Raises if artifact absent | Artifact is a hard requirement |
A good pattern is to seed defaults at session creation rather than relying on ? everywhere:
session = await session_service.create_session(
app_name="support_app",
user_id="user_42",
state={"user:account_tier": "premium", "topic": "refund_policy"},
)
You can also read user-scoped keys before a session exists with await session_service.get_user_state(app_name=..., user_id=...), which returns user:-prefixed keys with the prefix stripped.
Literal braces need an InstructionProvider
JSON examples, Jinja snippets, and format strings all contain curly braces that the templater will try to resolve. When instruction is a plain string, ADK always attempts injection. The fix is to pass a function instead — an InstructionProvider — which receives a ReadonlyContext and is passed to the model as-is with no state injection:
from google.adk.agents import LlmAgent
from google.adk.agents.readonly_context import ReadonlyContext
def my_instruction_provider(context: ReadonlyContext) -> str:
# No state injection occurs — curly braces are treated as literal text.
return 'Format your output as JSON: {"city": "<name>", "population": <number>}'
agent = LlmAgent(
model="gemini-flash-latest",
name="template_helper_agent",
instruction=my_instruction_provider,
)
If you want both — a provider function plus selective state injection — call the inject_session_state utility from google.adk.utils.instructions_utils. Only {key} placeholders matching valid state variable names are replaced; other braces are left alone:
from google.adk.utils import instructions_utils
async def my_dynamic_instruction_provider(context: ReadonlyContext) -> str:
template = 'This is a {adjective} instruction. Use JSON like: {"key": "value"}.'
# Injects 'adjective' but leaves the JSON braces untouched.
return await instructions_utils.inject_session_state(template, context)
One classic pitfall from the docs: some ADK examples use Python f-strings like f"Topic: {{initial_topic}}". The doubled braces are f-string escaping, not ADK syntax — Python collapses them to {initial_topic} at runtime, which ADK then treats as a normal placeholder. If you are not using f-strings, write single braces directly.
Feeding the template: how state gets written
Injection only works if the keys exist, so state updates matter. ADK recommends two routes, both of which flow through events so persistence, threading, and tracking stay correct:
output_key— set a string key on the agent and its final response is saved tosession.state[output_key]automatically. Withoutput_schemaalso set, the parsed value is stored instead of raw text.EventActions.state_delta— build a dict of changes, attach it to anEvent, and callsession_service.append_event(session, event).
from google.adk.events import Event, EventActions
state_changes = {
"task_status": "active", # session scope
"user:login_count": 1, # user scope
"temp:validation_needed": True, # discarded after this invocation
}
event = Event(
invocation_id="inv_login_update",
author="system",
actions=EventActions(state_delta=state_changes),
timestamp=time.time(),
)
await session_service.append_event(session, event)
Avoid mutating session.state on a Session object fetched from the SessionService — that bypasses ADK’s event tracking and can lose data. Inside tools and callbacks, mutate the state object on the context instead (for example callback_context.state['my_key'] = 'new_value'), which the framework tracks. For a deeper look at event history and when it gets trimmed, see context-compaction-in-google-adk.md.
Takeaway: ADK turns LlmAgent.instruction into a live, state-aware prompt — {key} and {artifact.var} inject session.state values, {key?} tolerates missing keys, and an InstructionProvider function (optionally combined with instructions_utils.inject_session_state) is the escape hatch for literal braces; pair the template with safe state writes via output_key or EventActions.state_delta and your system prompt becomes data instead of dead text.