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:
- Every model call uses the SDK's streaming helper,
client.messages.stream(...), with the same arguments as today. Don't callmessages.create. - 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.") reacheson_textbefore that tool runs. - 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).
sendreturns the text of the last response, andself.messagesholds the same history as before. on_text=Nonestill works (stream anyway, show nothing), and each stream is closed when you're done with it, even if something raises.max_turns, history acrosssendcalls andis_errorresults 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