Skip to content

Agent State

AgentState is a shared, mutable key-value store that tools and hooks can read and write during an agent session. It's useful for passing data between tool calls, tracking task progress, or storing user context.

Basic usage

python
from elsai import Agent, tool
from elsai.agent.state import AgentState

@tool
def increment_counter(amount: int, agent) -> str:
    """Increment a counter by the given amount.

    Args:
        amount: How much to add to the counter.
    """
    current = agent.state.get("counter", 0)
    agent.state["counter"] = current + amount
    return f"Counter is now {current + amount}"

agent = Agent(
    tools=[increment_counter],
    state={"counter": 0}
)

agent("Increment the counter by 5, then by 3")
print(agent.state["counter"])  # 8

Initialising state

Pass a dict or AgentState object to the constructor:

python
# From a dict
agent = Agent(state={"user_id": "u123", "session_count": 0})

# From an AgentState object
initial_state = AgentState({"preferences": {"language": "en", "timezone": "UTC"}})
agent = Agent(state=initial_state)

Reading and writing state

python
# Read with a default
value = agent.state.get("key", default_value)

# Write
agent.state["key"] = new_value

# Dict-style access
agent.state["counter"] += 1

# Get entire state as dict
snapshot = agent.state.get()

Accessing state inside tools

Inject the agent via a parameter named agent:

python
from elsai import tool

@tool
def remember_preference(preference: str, agent) -> str:
    """Remember a user preference.

    Args:
        preference: The preference to remember in 'key=value' format.
    """
    key, value = preference.split("=", 1)
    agent.state[key.strip()] = value.strip()
    return f"Remembered: {key.strip()} = {value.strip()}"

INFO

The agent parameter is injected automatically at runtime — do not include it in your docstring's Args section or the model will try to fill it in.

State in hooks

Hooks also receive the agent and can read/write state:

python
from elsai.hooks import AfterToolCallEvent

def track_tool_usage(event: AfterToolCallEvent) -> None:
    state = event.agent.state
    calls = state.get("tool_calls", {})
    tool_name = event.tool.name
    calls[tool_name] = calls.get(tool_name, 0) + 1
    state["tool_calls"] = calls

agent = Agent(hooks=[track_tool_usage])
agent("Call a tool")
print(agent.state["tool_calls"])

Persisting state across sessions

Combine with a session manager to persist state:

python
from elsai import Agent
from elsai.session import FileSessionManager

session_manager = FileSessionManager(storage_dir="./sessions")

agent = Agent(
    agent_id="user-123",
    session_manager=session_manager,
    state={"created_at": "2025-01-01"},
)

# State is saved and restored across process restarts

Snapshots

Take a point-in-time snapshot of the agent state:

python
snapshot = agent.take_snapshot(preset="session")

# Later, restore from snapshot
new_agent = Agent(...)
new_agent.load_snapshot(snapshot)

Available preset fields: messages, state, conversation_manager_state, interrupt_state, system_prompt.

Copyright © 2026 Elsai Foundry.