Skip to content

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.

1
2
3
4
from ag2 import Agent

# This variable will be available in all tool calls executed by this agent
agent = Agent(name="WeatherBot", variables={"units": "celsius"})

Conversation Variables#

If a variable is only relevant for a specific conversation, you can pass it directly when calling the ask method.

1
2
3
4
await agent.ask(
    "What is the weather?",
    variables={"session_id": "12345"},
)

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.

agent = Agent(
    name="Bot",
    variables={"global_param": "A", "override_me": "AgentLevel"}
)

# Inside the tool, variables will be:
# {"global_param": "A", "override_me": "CallLevel", "call_param": "B"}
await agent.ask(
    "Hello!",
    variables={"override_me": "CallLevel", "call_param": "B"}
)

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.

import asyncio

from ag2 import Agent, Context, Scope, ScopedValue, tool
from ag2.config import OpenAIResponsesConfig

@tool
def record_finding(finding: str, context: Context) -> str:
    """Save a finding and update this worker's draft."""
    context.variables["findings"].append(finding)
    context.variables["draft"].append(finding)
    print(f"Root note visible: {'root_note' in context.variables}")  # False
    return "Finding saved"

async def main():
    worker = Agent(
        "worker",
        config=OpenAIResponsesConfig(model="gpt-5"),
        prompt="Use record_finding exactly once to save the requested finding, then report completion.",
        tools=[record_finding],
    )
    coordinator = Agent(
        "coordinator",
        config=OpenAIResponsesConfig(model="gpt-5"),
        prompt="Delegate the task to task_worker exactly once, then summarize its response.",
        tools=[worker.as_tool(description="Record a finding in the shared collection.")],
    )
    initial_variables = {
        "findings": ScopedValue([], scope=Scope.SHARED),
        "draft": [],
        "root_note": ScopedValue("Coordinator's note", scope=Scope.LOCAL),
    }
    reply = await coordinator.ask(
        "Record that each delegated invocation has its own conversation history.",
        variables=initial_variables,
    )
    print(reply.context.variables["findings"])  # Contains the worker's finding
    print(reply.context.variables["draft"])  # []
    print(initial_variables["findings"].value)  # []: the caller's input was copied

if __name__ == "__main__":
    asyncio.run(main())

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.

1
2
3
4
5
6
7
8
9
from ag2 import Context, tool

@tool
def process_data(context: Context) -> str:
    # Access variables directly from the context dictionary
    api_key = context.variables.get("api_key")
    session = context.variables.get("session_id")

    return f"Processed using key: {api_key}"

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.

from typing import Annotated
from ag2 import Variable, tool

@tool
def fetch_user_data(
    user_id: str,
    # The framework automatically looks for a variable named "api_key"
    # and injects its value here.
    api_key: Annotated[str, Variable()],
) -> str:
    return f"Fetching {user_id} using {api_key}"

If the name of the argument in your function doesn't match the key in the variables dictionary, you can specify the key explicitly:

1
2
3
4
5
6
7
@tool
def fetch_user_data(
    user_id: str,
    # Looks for "api_key" in variables, but binds it to the "key" argument
    key: Annotated[str, Variable("api_key")],
) -> str:
    return f"Fetching {user_id} using {key}"

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.

1
2
3
4
5
6
@tool
def get_settings(
    # If "theme" is not provided in the variables, it defaults to "dark"
    theme: Annotated[str, Variable(default="dark")],
) -> str:
    return f"Using theme: {theme}"

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.

def create_default_state() -> dict:
    return {"status": "init"}

@tool
def update_status(
    state: Annotated[
        dict[str, str],
        # Uses the dynamically created dictionary if "state" wasn't provided
        Variable(default_factory=create_default_state),
    ],
) -> str:
    state["status"] = "running"
    return "Status updated"

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.

@tool
def authenticate(context: Context) -> str:
    # Generate and store a token in the context variables
    context.variables["auth_token"] = "abc-123"
    return "Successfully authenticated."

@tool
def fetch_secure_data(
    auth_token: Annotated[str | None, Variable(default=None)],
) -> str:
    if not auth_token:
        return "Error: Not authenticated."
    return f"Data fetched with token {auth_token}"

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.