Store and sync agent state in Python
An agent has two places to keep data:
- State is one JSON value. The SDK saves it and sends it to every connected client whenever it changes. Use it for what the UI shows.
- SQL is the agent's own SQLite database. Use it for rows you query, such as messages, orders or logs.
Both live in the agent's Durable Object storage, so they survive restarts and deploys.
Type the state
Pass a TypedDict to Agent and annotate initial_state with it. A type
checker then checks self.state and set_state():
from typing import TypedDict
from agents import Agent, callable
class CounterState(TypedDict):
count: int
class Counter(Agent[CounterState]):
initial_state: CounterState = {"count": 0}
@callable
async def increment(self, by: int = 1) -> int:
count = self.state["count"] + by
self.set_state({"count": count})
return count
initial_state seeds the state the first time an agent has nothing stored.
Each agent gets its own copy. Without initial_state, self.state is None
until the first set_state().
Change the state
set_state(state) replaces the whole state. It runs these steps in order:
- Calls
validate_state_change(state, "server"). If it raises, nothing changes and the error propagates. - Saves the state.
- Sends it to every connected client.
- Calls
on_state_changed(state, "server")in the background.
Treat self.state as read-only. Changing the dict in place doesn't save it or
notify clients, so always build a new value and pass it to set_state().
Accept state changes from clients
Clients can change the state too, with setState in useAgent or
AgentClient. The SDK runs the same steps, with the client's Connection as
the source instead of "server". It sends the new state to every client
except the one that sent it.
Override validate_state_change to reject a change. It is a plain def, not
async. Raise any exception to reject:
from typing import Any
class Counter(Agent[CounterState]):
def validate_state_change(self, next_state: CounterState, source: Any) -> None:
if next_state["count"] < 0:
raise ValueError("count can't be negative")
A rejected client gets the error State update rejected in its
onStateUpdateError callback. The client never sees your exception's
message. The server logs it with a traceback.
To stop a client from changing the state at all, mark its connection
readonly. Its setState then fails with Connection is readonly. See
Readonly connections.
React to changes
on_state_changed runs after every saved change, from either side:
from agents import Connection, StateSource
class Counter(Agent[CounterState]):
async def on_state_changed(self, state: CounterState, source: StateSource) -> None:
if isinstance(source, Connection):
print(f"client {source.id} set count to {state['count']}")
The SDK logs an exception raised here and passes it to on_error. The
exception doesn't undo the change.
Store rows with SQL
self.sql(query, *params) runs one statement against the agent's SQLite
database and returns a list of dicts. Each agent instance has its own
database and handles one request at a time, so data every request reads, kept
in one instance such as "main", puts all your traffic through that one
instance. Cloudflare compares D1, KV and the other options in
Choosing a data or storage product.
Use ? placeholders for values:
from workers import Request, Response
from agents import Agent
class Notes(Agent):
async def on_start(self) -> None:
self.sql(
"CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT NOT NULL)"
)
async def on_request(self, request: Request) -> Response:
if request.method == "POST":
self.sql("INSERT INTO notes (text) VALUES (?)", await request.text())
rows = self.sql("SELECT id, text FROM notes ORDER BY id")
return Response.json(list(rows))
curl -X POST -d 'buy milk' http://localhost:8787/agents/notes/home
[{"id": 1, "text": "buy milk"}]
self.sql is synchronous, so don't await it. It runs the statement right
away, and the
Durable Object output gate
holds the response until the write is durable.
on_start runs every time the agent wakes up, so use IF NOT EXISTS in
schema statements.
Rules for queries and parameters
querymust be a string literal (LiteralString). Pass values as parameters, never with an f-string, so a type checker catches SQL injection.- Parameters can be
int,float,str,bytesorNone. Aboolis stored as1or0. - An
intoutside ±253 raisesValueError. - A statement SQLite rejects raises
SqlError, with the statement onerror.query.
Annotate rows with row= to get typed results. The SDK doesn't validate the
rows, so the type is only for the type checker:
class Note(TypedDict):
id: int
text: str
notes = self.sql("SELECT id, text FROM notes", row=Note) # Sequence[Note]
The SDK keeps its own tables in the same database. Their names start with
cf_agents_, so don't create tables with that prefix.