Lesson 42.4 · 4 of 4 · 6 min read · Reviewed 24 Nov 2026
Session state across turns
By the end, you can
- Explain where an agent's state lives between turns and between sessions.
- Resume an Agent SDK session and decide what to persist outside it.
The model is stateless. Everything an agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. “knows” between turns is what your code sends back.
Within a run
The history is the state: the user’s request, every tool call and every result. The SDK manages it, and compactsCompaction: Summarising older conversation history so a long session fits in the context window while keeping what matters. it when it gets long (chapter 60).
Across runs: sessions
The first message from query() is a system message with a session_id. Save it. Later:
for await (const m of query({ prompt: 'Any update on the refund?', options: { resume: sessionId } })) { /* ... */ }
The agent continues with the earlier conversation. You can also fork a session to try two approaches from the same point (chapter 61).
What to keep outside the session
Conversations get compacted and sessions expire. Keep durable facts somewhere you control: a progress file the agent reads at the start, a database row for the case, a ticket id. Long-running agents work best when they write short notes as they go, and read them back after a restart. Chapter 58 calls this a notes file.
Key points
- Within a run, state is the conversation history the loop sends each turn.
- Agent SDK sessions can be resumed by id, so a later query continues with the same history.
- Store durable facts (decisions, progress, ids) outside the conversation, in files or a database.
Keep durable notes across sessions
Show why durable facts belong outside the conversation by resuming a session after its history has been compacted.
You will have: A small session store with resume by id and a notes file, and a printed comparison of what survives compaction with and without notes.
Steps
- Read the simulated sessions: each has an id and a message history.
- Write start() that returns a new session id, and resume(session_id) that returns the same history.
- Write compact(history) that keeps only the last two messages, as long histories get summarised.
- Add a notes dictionary keyed by case id where the agent records decisions and progress.
- Ask 'what was the refund amount?' after compaction, with and without the notes, and print both answers.
Done when
- Resuming by id returns the same session's history.
- After compaction, the answer without notes is 'unknown'.
- With notes, the agent still finds the refund amount and the ticket id.
Open in the Playground No API key needed.
Starter code (Python)
sessions, notes = {}, {}
counter = {"n": 0}
def start():
counter["n"] += 1
sid = f"sess-{counter['n']:03d}"
sessions[sid] = []
return sid
def resume(sid):
# TODO: return the stored history for this session id
return []
def compact(history):
# TODO: keep only the last two messages
return history
sid = start()
for m in ["Customer asks for a refund on order A-1042", "Agreed refund: 35 credits", "Opened ticket T-889",
"Customer asks about delivery times", "Explained standard delivery"]:
sessions[sid].append(m)
# TODO: record durable facts in notes["A-1042"]
print("resumed:", resume(sid))
Show a solution
sessions, notes = {}, {}
counter = {"n": 0}
def start():
counter["n"] += 1
sid = f"sess-{counter['n']:03d}"
sessions[sid] = []
return sid
def resume(sid):
return sessions[sid]
def compact(history):
return history[-2:]
def answer(question, history, case_notes):
"""Stands in for the model: it can only use what is in the history or the notes."""
facts = history + [f"{k}: {v}" for k, v in case_notes.items()]
for line in facts:
if "refund" in question and "credits" in line:
return line
return "unknown"
sid = start()
for m in ["Customer asks for a refund on order A-1042", "Agreed refund: 35 credits", "Opened ticket T-889",
"Customer asks about delivery times", "Explained standard delivery"]:
sessions[sid].append(m)
notes["A-1042"] = {"refund_amount": "35 credits", "ticket": "T-889", "status": "awaiting finance"}
saved_id = sid
print("resumed same session:", resume(saved_id) is sessions[sid])
sessions[saved_id] = compact(resume(saved_id))
print("after compaction:", sessions[saved_id])
print("without notes:", answer("what was the refund amount?", sessions[saved_id], {}))
print("with notes:", answer("what was the refund amount?", sessions[saved_id], notes["A-1042"]), "| ticket", notes["A-1042"]["ticket"])
Finished the chapter? Take the chapter check.