Building the Agent Loop: Client SDK from Scratch
Build and understand a functional agent loop using the Claude Client SDK from scratch. Learn how to set up API calls, handle tool requests, dispatch functions, and process responses, culminating in a working system that manages order status lookups through clear protocol steps.
In the previous chapter, we read the protocol. Now we build with it. By the end of this lesson, we will have a working agent loop that sends a task to Claude, handles tool calls, and returns a final answer. It is written from first principles, so every line has a clear reason to exist. By the end of this lesson, we will have:
A complete, runnable agent loop in under 50 lines of Python
A mock tool implementation to observe the full tool cycle
A labeled trace of what happened during a real run
A clear map between the code we wrote and the life cycle concepts from the previous chapter
Client SDK vs. Agent SDK: In this chapter, we use the Anthropic Client SDK (
pip install anthropic), whereclient.messages.create()is our API call, and we implement the tool loop ourselves. This is distinct from the Claude Agent SDK (pip install claude-agent-sdk), which ships with built-in tools (Read, Edit, Bash, and more) and handles the loop autonomously via aquery()function. We will learn the Client SDK because understanding the protocol at a foundational level is what lets you debug and customize any agent system.
What we are building
The agent we will build handles order status lookups for a customer support scenario. A user asks about an order, the agent calls a lookup tool, and Claude reads the result and replies. Simple enough to fit on one screen, complex enough to exercise every part of the loop. Here is the target behavior:
User sends: “What is the status of order #5678?”
Claude decides to call
get_order_status.Our loop runs the function and returns the result.
Claude reads the result and replies with a natural language answer.
The loop returns that answer.
The ...