Conversation Variables#
Variables hold serializable conversation state, such as session data, user preferences, and task progress. Tools can read and update this state without adding it to the model's input; use dependencies for secrets and runtime objects such as clients, connections, and locks.
Passing Variables to a Conversation#
You can pass variables at different levels depending on how long they need to persist and which parts of the system need access to them.
Agent Variables#
Initialize an agent with default variables to make them available to each new invocation. A fresh ask() or run() deep-copies the merged defaults and per-call values, so separate root invocations do not share their mutable state. Reply continuations keep the current invocation's variables.
Conversation Variables#
If a variable is only relevant for a specific conversation, you can pass it directly when calling the ask method.
Mixed Variables#
When both agent-level and call-level variables are provided, they are merged. If there is a key collision, the variables provided during the ask call will override the agent's default variables.
Variable Scopes Across Subagents#
Use ScopedValue(value, scope=Scope.SHARED) to choose how a variable crosses a subagent delegation. Import Scope, ScopedValue, and ScopeError from ag2.
| Scope | What the child receives | Where changes are visible |
|---|---|---|
Scope.COPIED | A deep copy of the current value | In that branch; changes do not sync back to the parent or siblings |
Scope.LOCAL | Nothing; the binding stays in its current branch | In the branch that owns it |
Scope.SHARED | Access to the same binding | Across the invocation's delegation tree, including replacement of the value |
Plain values use Scope.COPIED, as does ScopedValue(value) without an explicit scope. Tools and Variable() injection receive the underlying value, not the ScopedValue declaration.
Share findings while keeping drafts independent#
The worker contributes to shared findings and edits its own copy of a draft. It cannot see the root's local note. The example calls the OpenAI Responses API: install ag2[openai] and set OPENAI_API_KEY as described in the Quick Start.
Read the resulting state from reply.context.variables. Even shared values belong to this invocation's tree; they do not mutate the original input container or become shared with a separate root invocation. The model chooses its tool calls; after record_finding runs, the root sees the saved finding while its own draft and the caller's input remain unchanged.
Declare shared names at the root#
Declare shared bindings in the root agent's defaults or the root call's variables=. Descendants can mutate or replace an existing shared binding, but introducing a new shared name below the root, changing an existing scope, or sharing a reserved ag: / a2a: name raises ScopeError at the assignment. Inside a worker's tool, that error becomes the tool's error result for the worker's model; it does not propagate to the root ask(). Per-call plain overrides preserve a scope declared in agent defaults.
For open-ended contributions, declare a shared dictionary at the root, such as ScopedValue({}, scope=Scope.SHARED), then add entries inside it. This adds data without declaring new tree-wide variable names.
Sharing does not provide synchronization
Supply an application lock through dependencies when concurrent workers need to coordinate updates. The dependency mapping is shallow-copied, so its referenced lock can be shared. Use asyncio.Lock for cooperating async code; synchronous tools run in threads and need a suitable synchronization strategy. Shared changes are not rolled back when a worker fails.
Context Variables Access#
The most straightforward way to access variables inside a tool is by requesting the Context object. By adding an argument annotated with Context, the framework will automatically inject the current execution context, which contains the .variables dictionary.
Special Variable Access#
Instead of passing the entire Context object, you can instruct the framework to inject specific variables directly into your tool's arguments using the Variable annotation. This makes your tool's signature cleaner and more explicit.
If the name of the argument in your function doesn't match the key in the variables dictionary, you can specify the key explicitly:
Note
Important remark: these annotations have no effect on the tool schema for the LLM. They are only used for the framework to inject the value into the function.
Variables with Default Values#
Sometimes a variable might not be provided by the user. You can define fallback behaviors directly within the Variable annotation using either default or default_factory.
Static Defaults#
Use default for simple, immutable fallback values.
Dynamic Defaults#
For mutable objects (like lists or dictionaries) or values that need to be computed at runtime, use default_factory. The framework ensures that the factory function is only called once per execution context, preserving state across multiple tool calls in the same turn.
Updating Variables in Tools#
Variables are mutable. If a tool updates the context.variables dictionary, that change is preserved in the context and will be available to subsequent tool calls within the same conversation.
This is highly useful for sharing state or caching results between different tools without requiring the LLM to pass the data back and forth.
Variables Over a Protocol Connection#
When an agent is served over — or delegates through — A2A, NLIP, A2UI or AG-UI, the conversation's variables are synced with the peer on every message. An inbound payload is merged into the turn's variables before the agent runs, and the turn's variables are sent back to the peer with the reply.
That makes variables a channel, not just local state: the peer reads what you put there, and writes what the turn sees.
Reserved namespaces are never authored by a peer
Variable keys beginning with ag: or a2a: are the framework's own control-plane state — the approval_required() allow-always bypass, the A2A context-id bookkeeping, the per-call tenant override. They are stripped from every payload crossing a protocol boundary, in both directions: a caller cannot pre-approve a gated tool by sending one, and a peer is not shown yours. Do not use those prefixes for your own variables; they will not survive the wire.
Everything else round-trips. Treat a variable as readable by the peer and writable by it: keep secrets in dependencies instead, which are never synced, and do not let a variable a peer can set decide something the peer should not control.