Claude With The Anthropic Api
← All lessons
Lesson 38Claude With The Anthropic Api

Implementing multiple turns

Summary audio

No audio recap for this lesson.

Study notes

Core Concept

  • Keep calling Claude in a loop until it stops requesting tool use
  • When stop_reason ≠ "tool_use", Claude has a final response ready

Detecting Tool Requests

  • Check the stop_reason field in Claude's response
  • stop_reason = "tool_use" means Claude wants to call a tool
  • Cleaner than manually searching response content

Run Conversation Loop Structure

  • Call Claude via chat function with messages and available tools
  • Add Claude's response to conversation history
  • Check response. stop_reason
  • If "tool_use": execute tools and loop back with results
  • If not "tool_use": return final response (conversation complete)

Run Tools Function

  • Takes Claude's message containing one or more tool use blocks
  • Iterates through all tool use blocks and executes each one
  • Returns list of tool result blocks to send back to Claude

Tool Result Block Structure

  • type: "tool_result"
  • tool_use_id: Must match the corresponding tool use block's id
  • content: Tool output as string (use JSON for structured data)
  • is_error: Boolean (false for success, true for errors)

Error Handling

  • Wrap tool execution in try-except
  • On error: create tool result block with is_error = true and error message
  • Claude may retry with better arguments when informed of errors

Scalability Pattern

  • Use a helper run_tool(tool_name, tool_input) function with if statements
  • Call this from run_tools instead of checking tool names directly
  • Easily extensible for adding new tools

Multi-Turn Capability

  • System handles multiple tool use blocks in a single response
  • Handles multiple turns (Claude makes requests, tools execute, loop continues)
  • Continues until Claude stops requesting tools and provides final text response

Takeaways

  • Keep calling Claude in a loop until stop_reason ≠ "tool_use", then return the final response
  • Check the stop_reason field to detect tool requests instead of manually searching response content
  • Execute all tool use blocks from Claude's message, wrap each in a tool result block with matching tool_use_id, and send results back to Claude
  • Create tool result blocks with type: "tool_result", content as string, and is_error boolean; use try-except to catch errors and set is_error = true
  • Use a helper run_tool(tool_name, tool_input) function with if statements for easy extensibility when adding new tools
Flashcards 8 cards
Question
click to reveal · ←/→
Answer
click to flip back
Export to Anki (.tsv) ↓
Knowledge check 6 questions