agentic-ai-course

Module 7 — Streaming Responses

Every previous module waited for Claude’s entire reply before doing anything with it. For a long answer that can be several seconds of silence. Streaming prints text as it’s generated — the same experience as claude.ai’s own chat interface.

What you’ll learn

The core idea

with client.messages.stream(model=MODEL, max_tokens=1024, messages=messages) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
    final_message = stream.get_final_message()

Streaming changes when you see the text, not what you do with it afterward — you still end up with a complete message to append to history, exactly like create() returns. The only new idea is the intermediate loop over text_stream for the live typing effect. (Tool use can be streamed too — Claude emits input_json deltas as a tool call’s arguments are generated — but that adds real complexity for a UI benefit only; this module keeps to text streaming, the form you’ll use almost everywhere.)

Files

Run it

pip install -r requirements.txt
export ANTHROPIC_API_KEY=your_key_here
python exercise.py   # after filling in the TODOs
python solution.py   # to compare against a working version

Next

Module 8 — Retrieval-Augmented Generation — giving an agent a knowledge base to search, instead of relying only on what Claude already knows.