Skip to content
Index Ai Academy
Phase 10 · Scaling & shipping

Streaming, interrupts and sessions

Live output, stopping safely, and saving and resuming transcripts.

About 40 minutes · Model names checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers9

First principles

When is a streamed tool request complete enough to run?

Treat stream fragments as partial data until the API reports a complete tool block. An append-only event record gives recovery code a way to distinguish a complete request from an interrupted one.

  1. Starting point

    Stream delivers pieces of the tool arguments

  2. What changes

    Harness assembles and validates the complete block

  3. Result

    Only the completed request is eligible for execution

Compare all three steps
  1. Starting point

    Stream delivers pieces of the tool arguments

  2. What changes

    Harness assembles and validates the complete block

  3. Result

    Only the completed request is eligible for execution

Complete and reverse the trace

Given Stream delivers pieces of the tool arguments and Only the completed request is eligible for execution, write down the missing step that connects them.

Compare with the worked step

Harness assembles and validates the complete block

Now take Harness assembles and validates the complete block and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Stream delivers pieces of the tool arguments. Check that your implementation produces the result shown above.

Try it on a new case

A connection drops after half of the tool's JSON arguments arrive. Can a resumed run execute that request?

Show worked reasoning

The incomplete block must stay unexecuted. Resume from a stable event and let the next valid turn produce a complete request.

Try a different case

A note is visible after a crash but the event log ends at pending. Which identifiers should a recovery test keep fixed across both processes?

Show reasoning for this case

Keep the operation ID, caller scope, and intended payload stable. Assert that recovery finds the committed note, records the result, and leaves the note count unchanged.

Run, change, and build

Check this when debugging. Parsing each tool input piece as it arrives.

Trace the cause · Harness decision and state
  1. Trace the action from the proposed tool call through validation to the recorded result. Predict what survives a stop.
  2. Change one permission, cost limit, or interruption point. Compare the trace and persistent state to see which rule determined the outcome.
  3. Try the same reasoning on this case. A connection drops after half of the tool's JSON arguments arrive. Can a resumed run execute that request?

Why it matters

A harness is software people use, not a batch job. They want to see the reply as it's written, stop the agent when it heads the wrong way, close the laptop and carry on tomorrow. Each needs care: streamed tool inputs arrive as half-finished JSON, a stop in the middle of a turn can break the transcript, and a session file that's only written at the end is lost in a crash.

What you'll be able to do

  • Rebuild a message from the Messages API's stream of events, including tool inputs sent in pieces
  • Stop an agent mid-turn and leave the transcript valid
  • Save sessions as append-only logs, then resume and fork them
  • Tell the model what changed when a session resumes
Quick check
A user sees the agent heading the wrong way. What should the harness let them do?
  1. Nothing: an agent can't be stopped once started
  2. Close the window, losing the whole session
  3. Interrupt it, keeping the work done so far
  4. Wait until it finishes, then undo everything
Show the answer

Interrupt it, keeping the work done so far

A good harness streams events as they happen, so the user can stop it mid-step and redirect it, and it saves the session so it can be resumed or forked later.

The idea: events arrive in order, and a message assembles

Recall: Streaming responses showed text arriving in pieces, and The core loop, built properly appended each finished message. Here the pieces are tool inputs and thinking too.

Quick check
From the lesson on streaming responses: reply text arrives in content_block_delta events of the text_delta kind, and the stop reason arrives in message_delta, near the end. What does this print?
events = [
    {"type": "message_start"},
    {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hel"}},
    {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "lo"}},
    {"type": "message_delta", "delta": {"stop_reason": "end_turn"}},
]
text = "".join(e["delta"]["text"] for e in events
               if e["type"] == "content_block_delta"
               and e["delta"]["type"] == "text_delta")
stop = [e["delta"]["stop_reason"] for e in events if e["type"] == "message_delta"][0]
print(text, stop)
  1. lo end_turn
  2. Hello end_turn
  3. Hel end_turn
  4. Hello message_start
Show the answer

Hello end_turn

The two text pieces are joined in the order they arrived, and the stop reason is read from the event near the end. A harness has to assemble every stream this way. Tool input arrives in pieces too, as fragments of JSON. This lesson builds that, and what to do when someone presses Stop halfway through.

The event stream

Think of a news ticker, or a parcel tracker that updates as things happen. With "stream": true, the Messages API sends server-sent events as the reply is generated:

eventcarries
message_startthe message shell, with starting usage
content_block_starta new block at an index: text, tool_use (name and id), or thinking
content_block_deltaa piece of that block: text_delta, input_json_delta, thinking_delta or signature_delta
content_block_stopthat block is complete
message_deltathe stop_reason, and final output usage
message_stopthe end

There are also ping events to ignore, and error events to handle.

Text pieces can be shown at once: that's the live typing effect. Tool inputs are more like flat-pack furniture arriving in several boxes. They come as fragments of a JSON string ({"pa, th": "src/, app.py"}), and you can't build anything until the last box arrives. Join them, and parse only at content_block_stop. Parsing early fails, or worse, gives a partial input.

Thinking pieces (thinking_delta) join into the block's thinking text, and its signature arrives in a signature_delta before the block stops. Send it back exactly as it came, signature included, or the API rejects it. The text may be empty; the signature still comes.

The SDKs do this assembly for you (client.messages.stream(...) with get_final_message()). Knowing how it works helps when you show partial output or debug a stream that broke halfway.

Try it now

Eleven events, one message. The thinking block keeps both its text and its signature.

Quick check
What does this print?
parts = ['{"sku"', ': "TENT', '-2"}']
import json
print(json.loads("".join(parts))["sku"])
  1. TENT
  2. TENT-2
  3. sku
  4. an error
Show the answer

TENT-2

join puts the pieces back together as {"sku": "TENT-2"}, and ["sku"] reads TENT-2. Tool input arrives as pieces of JSON. Only the joined whole can be parsed.

Quick check
A tool_use block's input arrives in three input_json_delta pieces. When should the harness parse it?
  1. Never: tool inputs arrive as plain text, not as JSON
  2. At that block's content_block_stop, after joining all the pieces
  3. At message_start, before any of the pieces have arrived
  4. As each piece arrives, so the tool can start running sooner
Show the answer

At that block's content_block_stop, after joining all the pieces

Pieces are fragments of one JSON string. Only the joined whole is valid.

In your own words
When should the harness parse a tool call's input from the stream, and why not sooner?

Write a sentence or two, then compare it with a good answer in the lesson.

In code: assemble, stop safely and save

Worked example

Joining tool input pieces

Each piece alone is broken JSON. Together they parse.

import json

pieces = ['{"pa', 'th": "src/', 'app.py", "li', 'mit": 50}']
for p in pieces:
    try:
        json.loads(p)
        print("parsed alone:", p)
    except json.JSONDecodeError:
        print("not JSON alone:", repr(p))
print(json.loads("".join(pieces)))
It runs right here in your browser, with nothing to install.

This is why a harness keeps a buffer per block index and parses at the block's stop event.

Assembling a stream correctly

Don't parse tool input until it's finished. Tool input arrives as pieces of JSON text, and each piece on its own is usually invalid.

import json

pieces = ['{"path": "sr', 'c/app.py", ', '"limit": 10}']

try:
    json.loads(pieces[0])
except ValueError as err:
    print("too soon:", err.msg)

print(json.loads("".join(pieces)))

Collect the pieces by the block's index, and parse once at content_block_stop. If you want to show progress before then, display the raw text.

Save as you go

If you only save the transcript when a session ends, then a crash loses everything, including what the agent did to your files. So append each message when it happens. Disk writes cost almost nothing next to a model call.

Resuming isn't simply reloading

A person might come back to a session hours or days later. In that time, files can change, branches can move, and a test that was failing may have been fixed. The transcript still describes the old world, and the model will trust it. So when resuming, tell the model that time has passed, and what's changed if you can tell. For example, add a note: "This session resumed after 3 days. Files may have changed, so read them again before editing." It's a small message, and it prevents the agent from confidently editing code that's no longer there.

Quick check
A person resumes a session two days later. What should the harness tell the model first?
  1. That time has passed, and what has changed since the transcript ended
  2. That the earlier tool results should all be treated as errors
  3. To start again from the first message and redo every tool call
  4. Nothing: the transcript already holds everything the model needs
Show the answer

That time has passed, and what has changed since the transcript ended

The transcript describes the world as it was, and the model will trust it. Files, branches and test results may have moved, so say that time has passed and what is different now.

Stopping safely

A factory line has a stop cord, and everyone knows what happens when it's pulled. When the person presses Stop, the harness must:

  1. Stop generating. Close the stream.
  2. Stop work. Cancel running tools, killing their processes.
  3. Leave a valid transcript. If the last assistant message has tool_use blocks without results, add a user message of tool_result blocks saying they were interrupted, with is_error: true. Or drop that unfinished assistant message entirely.
  4. Wait for the person. Their next message joins the conversation as usual.

Skip step 3, and the next request fails: every tool_use needs a tool_result. The interruption note also tells the model why its plan stopped, so it doesn't assume the tool ran.

Worked example

Repairing a transcript after Stop

If someone presses Stop during a tool call, the last message has a tool_use with no result, and the next API call would fail. Repair it before saving.

def repair(messages):
    last = messages[-1]
    if last["role"] != "assistant":
        return messages
    open_calls = [b["id"] for b in last["content"] if b["type"] == "tool_use"]
    if open_calls:
        messages.append({"role": "user", "content": [
            {"type": "tool_result", "tool_use_id": i,
             "content": "Interrupted by the user.", "is_error": True}
            for i in open_calls]})
    return messages

messages = [
    {"role": "user", "content": [{"type": "text", "text": "Run the tests"}]},
    {"role": "assistant",
     "content": [{"type": "tool_use", "id": "t1", "name": "bash"}]},
]
repair(messages)
print(messages[-1])
In the lesson you can change this and run it.

Now the transcript is valid and it's honest about what happened. When the session resumes, the model knows the tests didn't finish, so it won't assume they passed.

Stop means stop

The emergency stop on a machine doesn't wait for the current cycle to finish. When a person presses Stop, they may have spotted the agent doing something wrong. So stopping must take effect at once: close the stream, kill running commands, and don't start anything new. A Stop that waits for the current tool to finish isn't really a Stop. Test it on purpose, with a long-running command, since this is the kind of path that nobody exercises until the day it matters, and then it really has to work.

Quick check
In the stream, which event first tells you a tool call's name and id?
  1. message_delta
  2. content_block_delta
  3. message_stop
  4. content_block_start
Show the answer

content_block_start

The block starts with its type, name and id. The input then arrives in input_json_delta pieces.

Sessions on disk

Save each session as an append-only log, like a ship's log written one line at a time: one JSON object per line (JSONL), written as each message is added. A crash loses at most the line being written. Resuming means reading the lines back into a message list.

  • Resume: load the log and carry on.
  • Fork: copy the first n messages into a new session, to try a different approach from the same point. It's like photocopying a draft up to page 10, then trying another ending.
  • Metadata: session ID, start time, working folder, model. Never the API key.

The world moves on. After a vacation, you'd check what changed before picking up old work. Between sessions, files change and branches move. On resume, tell the model: "Session resumed. Files may have changed since; read them again before editing." The stale-edit check from the file tools lesson is your safety net.

Worked example

A transcript that survives a crash

One JSON object per line means each message is saved as it happens. If the power goes mid-write, only the last line is damaged, and you can skip it.

import json

lines = [
    json.dumps({"role": "user", "content": "Fix the bug"}),
    json.dumps({"role": "assistant", "content": "On it"}),
    '{"role": "user", "cont',   # the crash happened here
]

def load(lines):
    messages = []
    for n, line in enumerate(lines):
        try:
            messages.append(json.loads(line))
        except ValueError:
            if n != len(lines) - 1:
                raise        # damage in the middle isn't a crash: stop and look
    return messages

print(load(lines))
In the lesson you can change this and run it.

Everything before the crash is safe. Note that only a bad last line is forgiven. A bad line in the middle means something else is wrong, and quietly skipping it would hide lost messages.

Drill

Load a transcript after a crash

Sessions are saved one JSON record per line, so a crash can leave a half-written last line. Write load(text): parse each non-blank line with json.loads; if the last line is broken, drop it; if any earlier line is broken, raise ValueError (that's real corruption, not a crash mid-write).

import json


def load(text):
    return [json.loads(line) for line in text.splitlines()]


text = '{"role": "user", "content": "hi"}\n{"role": "assistant", "content": "hel'
print(load(text))
In the lesson, your code is checked as you write it.
Quick check
What does forking a session do?
  1. Copies the first part of a session into a new one, to try another approach from that point
  2. Deletes the session and starts a fresh one with the same system prompt and tools
  3. Merges two sessions into one, so their transcripts are combined in order
  4. Runs the same session on two models at once and keeps the better answer
Show the answer

Copies the first part of a session into a new one, to try another approach from that point

The original stays untouched, so you can compare approaches from the same starting point.

Drill

Fork a session

Forking starts a new session from an earlier point, leaving the original untouched. Write fork(messages, upto): return a deep copy (copy.deepcopy) of the first upto messages, so changes to the fork, even inside nested content blocks, can't reach the original.

import copy


def fork(messages, upto):
    return messages[:upto]


ask = [{"type": "text", "text": "Plan the migration."}]
original = [{"role": "user", "content": ask},
            {"role": "assistant", "content": "Step 1..."}]
branch = fork(original, 1)
branch[0]["content"][0]["text"] = "Plan it differently."
print(original[0]["content"][0]["text"])
In the lesson, your code is checked as you write it.
Quick check
A session is resumed after 3 days. What should the harness tell the model?
  1. Nothing: the transcript already says it all
  2. That time has passed and files may have changed
  3. To delete the old transcript
  4. To start the whole task again
Show the answer

That time has passed and files may have changed

The transcript describes the world as it was. Without a note, the model will trust it and may edit code that is no longer there.

In your own words
What does resuming a session need beyond reloading the log?

Write a sentence or two, then compare it with a good answer in the lesson.

In a production harness: streams, sessions and background jobs

A real harness gets all of this from the SDK. What stays yours is the stop button, the session log and where the run lives, which is often not a browser tab.

Agents as background jobs

A long run should not hold a connection open. Put the harness in a worker, put each message in the session log, and let callers read a status endpoint or get a webhook. Caches, queues and background jobs builds the queue and the worker; the loop inside is the one you wrote.

In your own words
Why does a background agent write every message to a log as it goes?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 7 review cards for spaced repetition

Try a quiz question

Which stream event carries the stop_reason?

  1. message_delta
  2. message_start
  3. content_block_stop
  4. ping

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 10 · about 20 hours of study

Agent harnesses

Build the software around a model that turns it into a capable, safe agent 24 lessons 1 free
  1. What an agent harness is FreeThe software around a model that turns it into an agent.35 min
  2. The core loop, built properlyStop reasons, parallel tool calls, errors and turn budgets.40 min
  3. A tool registry for agentsSchemas from functions, validation, output limits and helpful errors.40 min
  4. File and search toolsRead, write, edit by exact replacement, glob and grep inside one folder.45 min
  5. Running code safelyExecution tools, step limits, output caps and real sandboxes.45 min
  6. Giving an agent a databaseSchema as context, a query tool with caps and readable errors, guards in layers, and execution accuracy.45 min
  7. Permissions and approvalsRules, modes and approval prompts that keep a person in control.40 min
  8. Hooks and skillsExtend a harness at lifecycle events, and load know-how on demand.40 min
  9. Multi-agent systemsCoordinating many agents on one large job.35 min
  10. Managing the context windowBudgets, clearing old tool results, compaction and a cacheable prefix.45 min
  11. Memory, plans and long tasksTo-do lists, progress notes, memory files and checkpoints.45 min
  12. SubagentsHand a focused task to a fresh context with fewer tools.40 min
  13. Streaming, interrupts and sessionsLive output, stopping safely, and saving and resuming transcripts.40 min
  14. Agents as graphsState, reducers and routing, a checkpoint after every step, and pausing for a person's approval.45 min
  15. Evaluation harnessesRun agents on tasks in fresh environments and grade what they leave behind.45 min
  16. Tracing, budgets and guardrailsSee what an agent did, cap what it spends, and stop it when it loops.40 min
  17. Attack your own harnessRun fourteen attacks against a harness with switches, read which layer stops each one, score attacks stopped against ordinary tasks done, and keep every finding as a release test.40 min
  18. Capstone: build a coding agentA harness that edits a project, runs its tests and stops when they pass.45 min
  19. The same agent on the real SDKsPut the parts you built beside the tool runner and the Agent SDK, choose a surface for a job, and take an MCP server's tools into your registry with prefixed names, one rule per server and a capped result.35 min
  20. Agents that use a computerAn agent with a screen, a mouse and a keyboard: the observe-decide-act loop, what a click lands on, why a wrong hit is worse than a miss, what happens when the screen changes under a plan, and what screenshots cost.45 min
  21. Sandboxes for agents that browseTreat every page as untrusted input: check hosts properly, gate actions by their effect, and layer the defenses.45 min
  22. Protocols between agentsHand a task to an agent someone else built: agent cards, the life of a task, the messages on the wire, safe retries, and whom to trust.45 min
  23. Tracing a run end to endFollow one run across an orchestrator, subagents and tool servers: trace ids, the traceparent header, the critical path, tokens by branch, and which traces to keep.45 min
  24. Retrieval over a graphAnswer questions that hop between documents: facts as triples, a walk out from the entities a question names, and the hubs and missed facts that limit it.45 min
Practice for interviews 21 questions

AI agent interview questions and answers

Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.

Part of a free course 29 lessons

Free AI agents course

Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.

Part of a free course 13 lessons

LLM Harness

Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write