AI Agents by HandAll problemsAbout

All problems › Agent problem · medium · ~15 min

Build a stateful chat agent

conversation state failure recovery

Solve it in your browser →

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:

  1. The conversation history lives in self.messages and persists across send calls. Each model call gets model, max_tokens, system=self.system, tools=TOOLS and the running history.
  2. While the model wants tools, run every tool_use block through HANDLERS and call the model again with the results. When it's done, return the final text (text blocks joined).
  3. If a tool raises (including bad arguments), or the model asks for an unknown tool, don't crash: send an is_error: True result with a useful message. One bad call must not drop the other results from the same turn.
  4. If self.on_tool_call is set, call it once per tool call, in order, as on_tool_call(name, input, output, is_error) (output is the string that went back to the model).
  5. max_turns limits model calls per send. Still calling tools after that many calls: raise RuntimeError.
  6. If the model stops with stop_reason == "max_tokens" (the answer was cut off), raise TruncatedError instead of returning half an answer.
  7. A failed send must not poison the conversation. After RuntimeError or TruncatedError (or any exception from the client), self.messages is exactly what it was before that send, so the next send still 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

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