Build a stateful chat agent (~15 min)
stateful_chat.py has a to-do assistant: three tools (add_task, list_tasks, complete_task), their schemas, and an Agent class whose send is a stub.
Unlike a one-shot run_agent, an Agent is a conversation: the user calls send many times and the assistant must remember earlier turns ("add milk" ... "now mark it done").
Implement Agent.send(user_message) -> str so that:
- The conversation history lives in
self.messagesand persists acrosssendcalls. Each model call getsmodel,max_tokens,system=self.system,tools=TOOLSand the running history. - While the model wants tools, run every
tool_useblock throughHANDLERSand call the model again with the results. When it's done, return the final text (text blocks joined). - If a tool raises (including bad arguments), or the model asks for an unknown tool, don't crash: send an
is_error: Trueresult with a useful message. One bad call must not drop the other results from the same turn. - If
self.on_tool_callis set, call it once per tool call, in order, ason_tool_call(name, input, output, is_error)(outputis the string that went back to the model). max_turnslimits model calls persend. Still calling tools after that many calls: raiseRuntimeError.- If the model stops with
stop_reason == "max_tokens"(the answer was cut off), raiseTruncatedErrorinstead of returning half an answer. - A failed
sendmust not poison the conversation. AfterRuntimeErrororTruncatedError(or any exception from the client),self.messagesis exactly what it was before thatsend, so the nextsendstill works.
Tool results go back as strings. Think about what the API requires after an assistant message that contains tool_use blocks, and what a half-finished loop leaves behind in the history.
Try it: python -m stateful_chat
Check it: pytest tests/test_stateful_chat.py