AI Agents by HandAll problemsAbout

All problems › Agent problem · medium · ~15 min

Stream a chat agent

streaming conversation state

Solve it in your browser →

Stream the help-desk chat (~15 min)

streaming_chat.py has an IT help-desk Agent: two tools (search_kb, get_ticket) and a send that keeps the conversation in self.messages across calls and runs the tool loop. It works, but the chat UI sits blank until the whole answer, tool calls included, is finished. send already takes an on_text callback; today it's ignored.

Change Agent.send(user_message, on_text=None) -> str so that:

  1. Every model call uses the SDK's streaming helper, client.messages.stream(...), with the same arguments as today. Don't call messages.create.
  2. Each piece of text is passed to on_text(chunk) as it arrives, from every model call in the loop, in order. Text the model writes before a tool call ("Let me check that ticket.") reaches on_text before that tool runs.
  3. Tool calls are handled exactly as now, from the complete message at the end of each stream (look at what the stream object gives you besides text). send returns the text of the last response, and self.messages holds the same history as before.
  4. on_text=None still works (stream anyway, show nothing), and each stream is closed when you're done with it, even if something raises.
  5. max_turns, history across send calls and is_error results for failing or unknown tools keep working.

Be ready to explain why streaming matters for latency the user perceives even though the total time is the same, and how you'd show the user that a tool is running.

Try it: python -m streaming_chat Check it: pytest tests/test_streaming_chat.py

Starter code and hidden tests open in the editor. Nothing to install.