- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- AI
Claude AI Agents
Build an autonomous AI Shopping Assistant using the Claude Agent SDK in this hands-on lab. You will learn how to design and configure Claude agents, define their roles and behaviors, and extend their capabilities using built-in tools, custom tools, and the Model Context Protocol (MCP). You will integrate external APIs, build multi-step workflows, and manage multi-turn conversations and agent sessions. You will also add persistent memory using SQLite to personalize product recommendations across conversations. Finally, you will develop a multi-agent Shopping Assistant using specialized subagents, configure permissions and safeguards, and validate its functionality through automated testing. By the end of the lab, you will be able to design, build, and test autonomous AI agents using the Claude Agent SDK.
Lab Info
Table of Contents
-
Challenge
Introduction
Welcome to the Claude AI Agents lab. In this hands-on lab, you will build an autonomous Shopping Assistant with
mini_claude_agent_sdk, a small package that mimics the Claude Agent SDK. The package has the same names and options as the Claude Agent SDK for the features that this lab covers. You will learn how to configure Claude agents, define their roles and behaviors, and extend their capabilities using built-in tools, custom tools, and the Model Context Protocol (MCP). You will also integrate external APIs and implement multi-step workflows to search, compare, and recommend products.You will explore conversation and session management, implement persistent memory using SQLite to personalize recommendations, and create specialized subagents that each recommend one product category. Finally, you will implement agent permissions and safeguards to improve reliability, integrate the parts in one assistant, and test it with
pytestand mocked responses. By the end of this lab, you will have built and safeguarded an autonomous Shopping Assistant, delegated work to subagents, and gained practical experience designing and developing AI agents with the names and options of the Claude Agent SDK. ### Key takeaways- Build and configure AI agents with the names and options of the Claude Agent SDK.
- Define agent roles, behaviors, and instructions using system prompts and
CLAUDE.md. - Create custom tools, integrate external APIs, and connect tools using MCP.
- Implement multi-step workflows and manage agent sessions.
- Build persistent memory using SQLite to personalize recommendations.
- Create specialized subagents for task delegation and coordination.
- Protect an autonomous Shopping Assistant using permissions and safeguards.
- Integrate the complete assistant and test it using
pytest,pytest-asyncio, and mocked responses. ### Claude runtimes
An agent is an application that completes a task by planning its own steps and calling tools. Anthropic offers four ways to build and run a Claude agent, with different levels of control.
Four ways to build and run Claude agents
- Messages API / Client SDK: Direct API access to Claude, with developers controlling the agent loop and tool execution.
- Claude Code CLI: Interactive terminal agent for reading files, editing code, and executing commands.
- Managed Agents: Hosted agent execution with managed sessions and sandbox environments.
- Claude Agent SDK: Runs Claude Code's agent engine within Python or TypeScript applications.
Runtime comparison
| Runtime | Best For | Trade-off | | --- | --- | --- | | Messages API | Direct API interactions | Manage agent logic | | Claude Code CLI | Interactive coding | Difficult to embed | | Managed Agents | Managed agent execution | Less control over the agent harness | | Claude Agent SDK | Autonomous agents | Manage infrastructure |
Agent SDKs
An agent SDK is a library that provides the parts every agent needs, so that you do not write them yourself.
Why use an agent SDK
With the Messages API alone, you write the agent loop. Your code sends the request, runs each tool that the model asks for, returns the result, and repeats until the model answers. Anthropic's client SDKs also have a beta tool runner that can run this loop for you. You also write the code that keeps the conversation, saves sessions, checks permissions, and stops a run that takes too long.
An agent SDK provides parts like these, and the exact set differs between SDKs. You write what is specific to your agent: its instructions, its tools, and its rules.
Agent SDKs from different providers
Several providers publish an agent SDK or framework. The names and the details differ, but the main ideas are shared: an agent loop, tools, sessions, and safeguards.
| SDK or framework | Provider | | --- | --- | | Claude Agent SDK | Anthropic | | OpenAI Agents SDK | OpenAI | | Agent Development Kit (ADK) | Google | | LangGraph | LangChain |
Introduction to the Claude Agent SDK
The Claude Agent SDK is an Anthropic library for building production-ready AI agents using Python or TypeScript. It provides the same agent loop, built-in tools, and context management capabilities that power Claude Code.
Key features
- Agent loop: Plans tasks, runs tools, observes the results, and repeats until the task is complete.
- Built-in tools: Provides
Read,Write,Edit,Bash, and search tools. - Custom tools and MCP: Connects custom functions, APIs, and external data sources.
- Sessions: Keeps the conversation context and lets you resume or fork a session.
- Subagents: Delegates specialized tasks to independent agents.
- Skills and project context: Loads reusable instructions through skills and project context through
CLAUDE.md. - Hooks and permissions: Controls agent behavior, tool access, and execution.
- Plugins: Packages reusable skills, agents, hooks, and MCP servers. ### The agent loop
The agent loop is the core of the SDK. Claude repeats the Plan, Action, and Observation stages until it has enough information to respond.
Customer request | v +---------------+ | Plan |<----------+ +---------------+ | | | | | | needs a tool | | v | | +---------------+ | | | Action | | | +---------------+ | | | | | v | | +---------------+ | | | Observation |------+ | +---------------+ | | has enough information v +---------------+ | Response | +---------------+- Plan: Claude reads the request and decides what it needs to do.
- Action: Claude asks to use a tool.
- Observation: The SDK runs the tool and returns the result to Claude.
- Response: Claude writes the final answer.
The agent SDK in this lab
In this lab, you do not install the Claude Agent SDK. You use
mini_claude_agent_sdk, a small package in themini_claude_agent_sdkfolder that mimics version 0.2.179 of the Claude Agent SDK. The package is built on the Messages API and has the same names and inputs for the features that this lab uses:query(),ClaudeSDKClient, andClaudeAgentOptionsrun and configure an agent.@toolandcreate_sdk_mcp_server()add custom tools.- Sessions, subagents, hooks, and permissions use the same options.
To use the Claude Agent SDK, install the
claude-agent-sdkpackage and import the same names fromclaude_agent_sdk. The Claude Agent SDK runs Claude Code, so some behavior differs, such as the built-in tools and where sessions are saved. ### Claude Shopping AssistantA Claude Shopping Assistant project is provided for this lab. It uses a fictional product catalog containing laptops and headphones, including product prices, specifications, and features.
During the lab, you will use
mini_claude_agent_sdkto build an autonomous AI agent that searches for and compares products using built-in tools, custom MCP tools, and external APIs. In this lab, the external API is a small product API that runs on your machine. You will also implement conversation management, persistent memory using SQLite, and specialized subagents to deliver personalized product recommendations. ### SolutionsThe finished file of each task is in the
__solutionfolder, for example__solution/Step03/task3.3_mcp_shopping_assistant.py. Use it to compare with your code if a task does not work. -
Challenge
Configure your first Claude agent
In this step, you will create a shopping assistant, structure its instructions with the RTCF format, and load project context from a
CLAUDE.mdfile.Before Task 1, get the API key from the top of the screen and run the commands below to set it. The key is hidden as you paste it and stays set until you close the Terminal.
read -rs -p 'LAB_API_KEY: ' LAB_API_KEY; echo export LAB_API_KEYKeep these points in mind in each task:
- Before you make the changes, go through all the files of the task to understand the code and how it runs.
- In the code of this lab, a
....line stands for lines that are not shown. - A
TODOline marks the place of a change. Remove the line after you make the change. - A
passline under aTODOonly keeps the file valid, so replace it with your code. ### Create a basic shopping assistant
An agent is an application that completes a task by planning its own steps and calling tools. Claude, the model, plans the steps and decides which tools to call, and the SDK runs the tools and returns the results. In this lab, "Claude" means the model, and "the agent" means Claude together with that loop.
An agent's behavior is defined by its configuration. Before an agent handles any request, it needs a clear role, rules to follow, and limits on how much work it can do. You work with two parts of the SDK in this task:
ClaudeAgentOptionsdefines how the agent is configured:system_promptsets the agent's role, goals, expected behavior, and constraints. Claude uses these instructions for every response, so the system prompt is the main way to guide the agent's behavior.max_turnsandmax_budget_usdlimit how many turns the agent can take and how much a run can cost. The cost is an estimate that the SDK calculates, and a run can pass the budget. A turn is one pass through the agent loop: Claude responds, and if the response asks for tools, the SDK runs them. The final answer is a turn too. These limits prevent runaway runs and unexpected costs.toolscontrols which built-in tools the agent can use. An empty list disables all built-in tools, so this agent answers only from its instructions and the model's own knowledge.
query()sends a prompt to the agent and returns the results as an asynchronous stream of messages:AssistantMessagecontains the agent's response as a list of content blocks. The response text is inTextBlockblocks.ResultMessagemarks the end of the run. It reports the run's status, number of turns, and total cost.
In this task, you build a shopping assistant that recommends one of two laptops listed in its system prompt, without inventing prices or specifications.
Task explanation model="claude-haiku-4-5-20251001"selects Claude Haiku 4.5, a fast, low-cost model suitable for a simple assistant.productsis stored in a separate variable, so you can change the products without editing the instructions.+ productsadds the product list to the end of the system prompt.- Each sentence in the system prompt serves a specific purpose, in this order: the role, the goal, the behavior, the constraint, and the fallback. The fallback asks one clarifying question only when the product type or budget is missing. The request in this task provides both, so the agent makes a recommendation.
- If
max_turns=3ormax_budget_usd=0.10stops the run before the final answer,ResultMessage.subtypereportserror_max_turnsorerror_max_budget_usdinstead ofsuccess. The run still ends with aResultMessage, so the script can print the status. setting_sources=[]prevents the SDK from loading user, project, and local settings. These can includeCLAUDE.mdfiles and the skills, agents, and commands in.claudefolders. By default, the SDK loads these settings, which can affect the agent's behavior.env=lab_env()passes the additional environment variables the agent needs to run in this lab.message.usagecontains the token counts for the run. Tokens are units of text that the model reads and writes, and they help determine the cost.token_summary()is a helper from the providedagents/token_usage.pyfile. It returns the input and output token counts.total_cost_usdcan beNone, soor 0provides a default value and prevents the cost formatting from failing.
Navigate to the Terminal and execute the following command to test the above changes.
python3 agents/02_first_agent/basic_shopping_assistant.py --user-prompt="Recommend a laptop for Python development under AUD 1500."You should see a response in your terminal similar to the example response below. Your response may vary.
User prompt: Recommend a laptop for Python development under AUD 1500. I recommend the **LAP-101 Developer Lite** at AUD 1,199. It's well-suited for Python development with 16 GB RAM and a 512 GB SSD, providing plenty of memory for coding and testing. At under your AUD 1,500 budget, it's the more affordable option and offers excellent portability at 1.3 kg with 10 hours of battery life, making it ideal for development work whether at home or on the go. Status: success Turns: 1 Tokens: 174 input, 109 output Cost: $0.0007### Structure agent instructions using RTCFExplanation
The agent recommends LAP-101 Developer Lite in one paragraph, with the price and specifications from the system prompt. LAP-102 costs
AUD1,799, which is over the budget ofAUD1,500, so the agent does not recommend it. This shows that the agent followed the behavior and constraint instructions of the system prompt for this request.The system prompt in Task 1 was a single paragraph. It works, but as instructions grow, a paragraph becomes hard to read and to maintain. Role–Task–Context–Format (RTCF) is a prompting framework that organizes a system prompt into four labeled sections:
| Component | Purpose | Shopping assistant example | | --- | --- | --- | | Role | Who the agent is | Shopping assistant | | Task | What the agent should do | Identify the customer's needs, recommend suitable products, and ask questions when information is missing | | Context | Information and constraints | Australian shoppers, budgets in AUD, and the two laptops the store sells | | Format | How responses should appear | Three headings, an advantage and a trade-off for each product, and a word limit |
Each section answers one question, so the agent knows who it is, what to do, what limits apply, and how to present its answer. The Format section has the most visible effect: it asks for the same layout in every response.
Use RTCF to keep instructions clear as they grow and to make responses more consistent. RTCF is a way to structure a prompt, not a feature of the SDK.
In this task, you rewrite the Task 1 system prompt with RTCF, send a laptop request to the new agent, and compare the response with the one from Task 1.
Task Explanation PRODUCTSholds the two laptops from Task 1 in its own variable.RTCF_SYSTEM_PROMPTis an f-string, so Python replaces{PRODUCTS}with the product list. The## PRODUCTSheading inside# CONTEXTseparates the product data from the rules above it. The#headings are plain text inside the string, not Python comments or SDK commands. They separate the four sections for Claude and for anyone reading the code.# ROLEgives the agent an identity and a purpose in one sentence.# TASKlists the agent's responsibilities as numbered steps, in a clear order. Item 3 names the three details that the agent needs, so it asks a question only if one of them is missing. The request in this task provides all three.# CONTEXTcontains the facts and constraints the agent cannot work out by itself: customers are in Australia, budgets are inAUD, and the store sells the two laptops from Task 1. The agent may recommend only these products.# FORMATdefines the response layout. The three##headings set the order of the agent's response, and the word limit keeps the response short.
Navigate to the Terminal and execute the following command to test the above changes.
python3 agents/02_first_agent/rtcf_shopping_assistant.py --user-prompt="I need a laptop for Python development under AUD 1500. I prefer good battery life and something lightweight. I mainly do web development, and I am happy with any operating system."You should see a response in your terminal similar to the example response below. Your response may vary.
========== RTCF PROMPT ========== User prompt: I need a laptop for Python development under AUD 1500. I prefer good battery life and something lightweight. I mainly do web development, and I am happy with any operating system. ## Understanding Your Needs You're looking for a lightweight laptop with excellent battery life for Python web development within a AUD 1,500 budget. ## Recommended Options **LAP-101 Developer Lite** – AUD 1,199 - **Advantage:** Exceptional 10-hour battery life and lightest option at 1.3 kg - **Trade-off:** 16 GB RAM and 512 GB SSD are modest for larger projects ## Final Recommendation The **LAP-101 Developer Lite** is your best fit. It's well under budget, prioritizing your battery life and portability needs. The 16 GB RAM and 512 GB SSD are solid for typical web development work, though you may need external storage if managing large datasets. Status: success Turns: 1 Tokens: 341 input, 177 output Cost: $0.0012### Load project contextExplanation
| | Task 1 prompt | RTCF prompt | | --- | --- | --- | | Layout | One free-form paragraph | The three headings from
# FORMAT| | Content | The product and the reasons, in running text | A summary of needs, followed by the product, price, an advantage, and a trade-off |Both prompts recommend LAP-101 because it is the only laptop under the
AUD1,500 budget. They contain the same product list, so RTCF changes the answer's layout, not what the agent knows. The layout is also more consistent between runs. However, the comparison is not exact because this task's request also includes preferences for battery life and weight.A structured prompt improves consistency but does not guarantee that every instruction is followed. For example, the response may exceed the word limit. Test the prompt and refine it when needed.
A system prompt defines how the agent behaves. An agent also needs facts about the business it works for, such as the store name and what it sells. Keeping these facts in a separate file makes them easier to manage and share across agents in the project. The SDK supports this with a project context file named
CLAUDE.md.CLAUDE.mdis a Markdown file that holds reusable instructions and facts for a project. At the start of each run, the SDK loads its content and provides it to the model with every request. The agent uses this context alongside the system prompt. You can update the file without changing any code, and the changes take effect in the next run.setting_sourcescontrols which settings the SDK loads from disk.setting_sources=["project"]loads the project's settings, includingCLAUDE.md. Settingsetting_sources=[]disables user, project, and local settings, soCLAUDE.mdis ignored.cwdsets the agent's working directory. The SDK treats this folder as the project folder and looks forCLAUDE.mdthere. In this lab, the file is in the top-level folder, alongside theagentsfolder, so all agents in the project can share it.
In this task, you add the store information to
CLAUDE.mdand run an agent that loads it.Task Explanation CLAUDE.mdnow contains the store's name and what it sells. These facts are not inSHOPPING_SYSTEM_PROMPT, so the agent can get them only fromCLAUDE.md.SHOPPING_SYSTEM_PROMPTcomes from theagents/prompts.pyfile, which holds the Shopping Assistant prompt that this task and the later tasks share. The system prompt defines the agent's behavior, andCLAUDE.mdsupplies the store's facts.cwd=str(APP_DIR)sets the working directory to the project folder, whereCLAUDE.mdis stored.APP_DIRis defined at the top of the file from the path of the script, so the agent findsCLAUDE.mdno matter which folder you run the command from.setting_sources=["project"]loads the project settings, includingCLAUDE.md, from the working directory.- The SDK sends the
CLAUDE.mdcontent to the model together with your system prompt. In this lab, it adds the content to the end of the system prompt. - The agents from Task 1 and Task 2 use
setting_sources=[], so they do not loadCLAUDE.md. An agent loads it whensetting_sourcesincludes"project"or is left out, because the default loads all sources.
Navigate to the Terminal and execute the following command to test the above changes.
python3 agents/02_first_agent/context_shopping_assistant.py --user-prompt="What is the name of this store, and what does it sell?"You should see a response in your terminal similar to the example response below. Your response may vary.
User prompt: What is the name of this store, and what does it sell? This store is called Globomantics. We sell laptops and headphones. All prices are in Australian dollars (AUD). Status: success Turns: 1 Tokens: 106 input, 33 output Cost: $0.0003Congratulations! In this step, you ran your first agent, gave it a clear role and response format, and supplied store information from a project file. So far, the agent can only talk. In the next step, you give it tools.Explanation
The store name and the products are not in
SHOPPING_SYSTEM_PROMPTor in the question. The agent answers from the store information inCLAUDE.md. In this example, the last sentence, about prices inAUD, comes fromSHOPPING_SYSTEM_PROMPT. -
Challenge
Understand the agent loop and build custom tools
In this step, you will observe the agent loop with the built-in
Readtool, build custom product search tools, and connect them to the agent with an in-process MCP server in a multi-tool workflow. ### Observe the agent loop with built-in toolsIn Step 2, the agent answered every request in a single turn, using only its instructions and what the model already knew. The two laptops were written into the system prompt, which does not suit a real catalog: it can be too large for a prompt, and it changes. An agent becomes more useful when it can take actions, such as reading a file, and then use what it finds. The SDK manages this with the agent loop:
- Plan: Claude reads the request and decides what it needs to do.
- Action: Claude asks to use a tool, such as
Read. - Observation: The SDK runs the tool and returns the result to Claude.
- Response: Claude writes its final answer.
After each observation, Claude plans again: it either asks for another tool or responds. The Plan, Action, and Observation stages repeat until Claude has enough information to respond. When a request can be answered from the instructions alone, the agent responds without an action, and the loop ends after one turn. You do not write the loop yourself. The SDK runs it, and
query()returns messages that show the stages:| Stage | Message | Content block | | --- | --- | --- | | Action |
AssistantMessage|ToolUseBlock: the tool name and its input | | Observation |UserMessage|ToolResultBlock: the result of the tool, which the SDK sends back to Claude as a user message | | Plan or response |AssistantMessage|TextBlock: Claude's own text. Claude does not always write a plan before an action | | End of run |ResultMessage| The status, number of turns, and cost |The actions in the loop are tool calls. An agent SDK includes built-in tools, so an agent can work with files, commands, and the web without any tool code from you:
| Tool | What it does | | --- | --- | |
Read| Reads a file | |Glob| Finds files whose names match a pattern, such ascatalog/*.md| |Grep| Searches for text inside files | |Write| Creates or overwrites a file | |Edit| Changes part of an existing file | |Bash| Runs a terminal command | |WebSearch| Searches the web | |WebFetch| Retrieves the content of a web page |Read,Glob, andGreponly read information.Write,Edit, andBashcan change files, so give them to an agent only when the task needs them.In this lab, the SDK provides only
Readfrom this table. If you list another tool from the table intools, the SDK ignores it. You useReadin this task.You do not call these tools from your code. The agent chooses which tool to use and how many times. Two options control the tools:
toolssets which built-in tools the agent has.allowed_toolslists the tools that are approved in advance, so that their calls run without asking for approval. It does not change which tools the agent has.
The catalog files are provided in the
catalogfolder:laptops.mdlists two laptops, andheadphones.mdlists four headphones. Theagents/03_loop_and_tools/agent_loop.pyfile already containsCATALOG_INSTRUCTIONS, which tells the agent where the catalogs are and how to use its tool:CATALOG_INSTRUCTIONS = """ The product catalogs are two Markdown files: - catalog/laptops.md - catalog/headphones.md Use Read to read the one you need before you recommend or describe a product. """In this task, you give the Shopping Assistant the built-in
Readtool. The agent reads the catalog file that the request needs, and you print each stage of the loop.Task Explanation CATALOG_INSTRUCTIONSis added to the system prompt. It tells the agent where the catalogs are. The customer's request does not mention files or tools.tools=["Read"]makes only this built-in tool available. The agent can read files, but it cannot write files, run commands, or search the web.allowed_tools=["Read"]approves the tool in advance, so it runs without a permission prompt. This script has no user to answer a prompt, so a call that is not approved in advance is denied. List every tool that the agent is expected to use. In this lab, the SDK needs this entry for everyReadcall.cwd=str(APP_DIR)sets the working directory to the project folder, so the agent resolvescatalog/laptops.mdfrom there. In this lab, the SDK takes the path relative to the working directory.strict_mcp_config=Truemakes the agent use only the MCP servers listed inmcp_servers. This agent lists none, so it starts no MCP server. Without it, an agent that loads the project settings can also start the MCP servers listed in the.mcp.jsonfile of the project folder, and their tools add input tokens to the agent's requests.max_turns=5now matters. Each round of tool calls uses a turn, so this limit stops the agent if it keeps calling tools without finishing.ToolUseBlockis the action.block.nameis the tool the agent chose, andblock.inputis what it passed to the tool, such as the path of the file to read.ToolResultBlockis the observation. It arrives in aUserMessage, because the SDK sends the tool result back to Claude as the next message in the conversation.str(block.content)[:500]prints only the first 500 characters of the content, which is always text in this lab, to keep the output short.TextBlockis the agent's own text. Text after the last observation is the response. The agent may also write a short plan before its first action, but it does not always do so.
Navigate to the Terminal and execute the following command to test the above changes.
python3 agents/03_loop_and_tools/agent_loop.py --user-prompt="Recommend a lightweight laptop for Python development under AUD 1500."You should see a response in your terminal similar to the example response below. Your response may vary.
========== PRODUCT REQUEST ========== User prompt: Recommend a lightweight laptop for Python development under AUD 1500. [ACTION] Tool: Read Input: {'file_path': 'catalog/laptops.md'} [OBSERVATION] Tool result received # Laptop Product Catalog ## LAP-101: Developer Lite - Price: AUD 1,199 - RAM: 16 GB - Storage: 512 GB SSD - Weight: 1.3 kg - Battery Life: 10 hours ## LAP-102: Developer Pro - Price: AUD 1,799 - RAM: 32 GB - Storage: 1 TB SSD - Weight: 1.7 kg - Battery Life: 7 hours [ASSISTANT] I recommend the **Developer Lite (LAP-101)** at AUD 1,199—it's under your budget and perfect for Python development with 16GB RAM and 512GB SSD. At just 1.3 kg with 10-hour battery life, it's also lightweight and portable for coding on the go. The LAP-102 Pro exceeds your budget at AUD 1,799, so the Lite is your best option. [COMPLETE] success Turns: 2 Tokens: 1532 input, 162 output Cost: $0.0023### Build custom product search toolsExplanation
Follow the loop in the output:
| Stage | What happened | | --- | --- | | Plan | The agent decides to read
laptops.mdbecause the request is for a laptop. This run printed no plan, but yours may show a short[ASSISTANT]line before the action | | Action |Readwith the path of that file | | Observation | The laptop catalog | | Response | The recommendation |- File: the instructions name two catalog files. The agent chose
laptops.mdbecause the customer asked for a laptop. - Recommendation: LAP-101 at
AUD1,199 is the only laptop within theAUD1,500 budget. LAP-102 costsAUD1,799. The price and specifications now come from the catalog file, not the system prompt. - Turns: the run took two turns, one for the tool call and one for the answer. When the agent needs more information, the loop repeats. In Task 3, the agent makes two rounds of tool calls before it answers.
The built-in
Readtool from Task 1 works with files. It can read a catalog, but the agent still has to work out for itself which products fit a budget. A custom tool is a Python function that you write and the agent can call. It lets the agent run your own logic, such as filtering products by category and price, and get back an exact result.Custom tools are useful for two main reasons:
- Accuracy: code gives the same result every time, and you can test it. With a built-in tool, the agent reads the catalog as text and compares prices itself, so it can miss a product or misread a price. A custom tool filters by price in Python, so the comparison does not depend on how the model reads the text.
- Control: you decide what the agent can do and what input is valid. A custom tool can reject an unknown category or a negative budget and return a clear error message.
A custom tool also returns only the products that match, so the agent has less text to process. And it can run any Python code, so it can query a database or call an API with your own logic and error handling.
You create a custom tool with the SDK's
@tooldecorator. A decorator is a line that starts with@, placed above a function, that adds behavior to the function.@tooltakes a name, a description, and an input schema, and wraps anasyncfunction. A complete tool has five parts:| Component | Meaning | | --- | --- | | Name, such as
"search_products"| The tool name Claude uses to call it | | Description | Explains what the tool does, so Claude knows when to use it | | Input schema, such as{"category": str, "max_price_aud": int}| The arguments the tool needs and their types | |async deffunction | The code that runs when the tool is called | | Return value | The information sent back to Claude |A tool returns a dictionary with a
contentlist. To report a failure, it adds"is_error": True, and Claude reads the message and decides what to do next.Use a custom tool when the agent needs an operation that must be exact and repeatable, such as a search, a calculation, or a lookup. The Shopping Assistant needs two tools:
| Tool | Purpose | Example | | --- | --- | --- | |
search_products| Find products by category and budget | Find headphones forAUD220 or less | |get_product_details| Retrieve the specifications of one product | Get details forHP-201|The
tools/shopping_tools.pyfile already contains the helper functions that the tools use:search_catalog()andfind_product()read the product catalog incatalog/products.json.tool_result()andtool_error()build the dictionary that a tool returns.
In this task, you complete the two tools in that file and test them directly, without an agent. In the next task, you connect them to the agent.
Task Explanation "search_products"is the name Claude uses to call the tool. Choose a name that describes the action.- The description tells Claude what the tool does and what it returns. Claude reads it to decide when to use the tool, so a clear description matters as much as the code. Here it also points Claude to
get_product_detailsfor the full specifications. {"category": str, "max_price_aud": int}is the input schema. It lists each argument and its Python type. Claude must provide both values when it calls the tool.- The function reads the values that Claude passed from
args, asargs["category"]andargs["max_price_aud"]. tool_result(...)returns{"content": [{"type": "text", "text": ...}]}. The data is converted to JSON text, because atextblock holds a string.tool_error(...)returns the same structure with"is_error": True. Claude sees the message and can correct its input or tell the customer. The error does not stop the run.except ValueErrorturns an invalid category or a negative budget into a tool error with a clear message, such as"Category must be laptops or headphones".- The search and lookup logic is in plain functions,
search_catalog()andfind_product(). This keeps the tools short and lets you test the logic without an agent. @toolturns each function into a tool object. The object keeps the name in.nameand the original function in.handler, which is how the test calls the tools directly.
The provided
tests/check_shopping_tools.pyfile tests the tools without an agent. It searches for headphones with two budgets, sends the search tool three inputs that find nothing, and looks up one product that exists and one that does not.Navigate to the Terminal and execute the following command to test the above changes.
python3 tests/check_shopping_tools.pyYou should see a response in your terminal as shown in the example response below.
Product search passed Product details passed Missing product test passed search_products returned for headphones up to AUD 220 (3 products): Input: {'category': 'headphones', 'max_price_aud': 220} Result: {'content': [{'type': 'text', 'text': '{"count": 3, "products": [{"id": "HP-204", "name": "Wireless Basic", "price_aud": 89}, {"id": "HP-202", "name": "Studio Comfort", "price_aud": 129}, {"id": "HP-201", "name": "Focus Wireless", "price_aud": 199}]}'}]} search_products returned for headphones up to AUD 150 (2 products): Input: {'category': 'headphones', 'max_price_aud': 150} Result: {'content': [{'type': 'text', 'text': '{"count": 2, "products": [{"id": "HP-204", "name": "Wireless Basic", "price_aud": 89}, {"id": "HP-202", "name": "Studio Comfort", "price_aud": 129}]}'}]} search_products returned for headphones up to AUD 50 (no products): Input: {'category': 'headphones', 'max_price_aud': 50} Result: {'content': [{'type': 'text', 'text': '{"count": 0, "products": []}'}]} search_products returned for phones up to AUD 220 (unknown category): Input: {'category': 'phones', 'max_price_aud': 220} Result: {'content': [{'type': 'text', 'text': 'Category must be laptops or headphones'}], 'is_error': True} search_products returned for headphones up to AUD -10 (negative budget): Input: {'category': 'headphones', 'max_price_aud': -10} Result: {'content': [{'type': 'text', 'text': 'Budget must not be negative'}], 'is_error': True} get_product_details returned for HP-201 (found): Input: {'product_id': 'HP-201'} Result: {'content': [{'type': 'text', 'text': '{"id": "HP-201", "name": "Focus Wireless", "category": "headphones", "price_aud": 199, "connectivity": "Wireless", "microphone": "Clear voice", "comfort": "High"}'}]} get_product_details returned for INVALID-123 (not found): Input: {'product_id': 'INVALID-123'} Result: {'content': [{'type': 'text', 'text': 'Product not found'}], 'is_error': True}### Connect custom tools using MCP in a multi-tool workflowExplanation
Check the output:
- The first three lines confirm that the search and lookup logic works.
Input:is the dictionary of arguments that the test passed to the tool, andResult:is what the tool returned. An agent passes arguments and receives results in the same form.search_productsreturned three headphones that costAUD220 or less, sorted by price.HP-203atAUD239 is left out. With a budget ofAUD150, it returned two, becauseHP-201atAUD199 is over that budget.- A budget of
AUD50 returned an empty list, which is a result, not an error. The unknown categoryphonesand the negative budget each returned a tool error with a clear message. get_product_detailswas called twice. ForHP-201, it returned the full specifications as JSON text. ForINVALID-123, which does not exist, it returned a tool error with'is_error': True.
In Task 2, you built two custom tools and tested them directly. The agent cannot use them yet, because it does not know they exist. You connect them through the Model Context Protocol (MCP), a standard way to give an agent access to tools.
Tools are grouped in an MCP server. Most MCP servers run as separate programs, but the SDK can also create one inside your own Python process with
create_sdk_mcp_server. This is called an in-process MCP server. The server needs no separate program and no network connection, so it is the simplest way to connect your own tools. In this lab, the SDK does not start a real server. It groups your tools under the server name and calls your functions directly.Connecting custom tools takes three steps:
| Step | Code | Purpose | | --- | --- | --- | | Create the server |
create_sdk_mcp_server(name=..., tools=[...])| Groups your tools under one server name | | Connect the server |mcp_servers={"shopping": shopping_server}| Makes the server's tools available to the agent | | Allow the tools |allowed_tools=["mcp__shopping__search_products", ...]| Lets the tools run without a permission prompt |When a tool is connected through MCP, its full name follows the pattern
mcp__<server name>__<tool name>. The server name in this pattern is the key that you use inmcp_servers, not thenamethat you pass tocreate_sdk_mcp_server. This task usesshoppingfor both. Thesearch_productstool on theshoppingserver becomesmcp__shopping__search_products.You do not call the tools in your code. The agent reads each tool's name and description and calls the tools itself. The system prompt tells it the order of the steps.
A recommendation needs both tools. The search returns only IDs, names, and prices, so the agent must also retrieve each product's specifications before it can compare them. A multi-tool workflow is a sequence of tool calls in which the result of one call can decide the next call:
| Stage | What the agent does | Tool | | --- | --- | --- | | Search | Finds the products in the category and budget |
search_products| | Retrieve | Gets the specifications of each product found |get_product_details| | Filter | Excludes products that fail a mandatory requirement | None, the agent reasons | | Compare | Weighs the prices and features of the rest | None, the agent reasons | | Recommend | Names the best product and explains why | None, the agent responds |The product IDs for the second tool come from the result of the first. This is called tool chaining: the output of one tool becomes the input of the next. You do not write this sequence as code. You describe the steps in the system prompt, and the agent loop from Task 1 carries them out. The steps guide Claude. No code enforces their order.
Two settings matter in a workflow:
- Clear, ordered instructions. Numbered steps in the system prompt help the agent follow the same path on each run.
- A higher turn limit. Each round of tool calls uses a turn, so a workflow needs a larger
max_turnsthan a one-tool task.
The
agents/03_loop_and_tools/mcp_shopping_assistant.pyfile contains the workflow steps:WORKFLOW_INSTRUCTIONS = """ For a product recommendation, complete these steps in order: 1. Use search_products to find products in the category and budget. 2. Use get_product_details for every product found. 3. Exclude the products that fail a mandatory requirement. 4. Compare the prices and features of the rest. 5. Recommend the best product and explain why. Use only the tool results. """In this task, you create the
shoppingserver, connect it to the agent, approve its two tools, and send a customer request.Task Explanation create_sdk_mcp_server(...)groups the two tools under one server name.nameidentifies the server, andversionis the server's version string.tools=[search_products, get_product_details]passes the tool objects that@toolcreated in Task 2. The file already imports them fromtools/shopping_tools.py.mcp_servers={"shopping": shopping_server}connects the server to the agent. The key"shopping"becomes the middle part of each tool's full name.allowed_toolslists the full tool names,mcp__shopping__search_productsandmcp__shopping__get_product_details, so the agent can run them without a permission prompt.- The provided
system_prompt=SHOPPING_SYSTEM_PROMPT + "\n" + WORKFLOW_INSTRUCTIONSline adds the workflow steps to the agent's role and rules. The customer's request does not mention tools or steps. - Item 3 of
WORKFLOW_INSTRUCTIONStells the agent to treat "mandatory" as a rule: it excludes a product that fails a mandatory requirement, however good its other features are. This is an instruction to the model, not a check in code. max_turns=12leaves room for the search, one details call for each product, and the final answer.query()and the provided message handling are the same as in the earlier tasks. Only the options change.
Navigate to the Terminal and execute the following command to test the above changes.
python3 agents/03_loop_and_tools/mcp_shopping_assistant.py --user-prompt="I need headphones under AUD 220 for working from home. Wireless is mandatory, and a clear microphone matters most."You should see a response in your terminal similar to the example response below. Your response may vary.
User prompt: I need headphones under AUD 220 for working from home. Wireless is mandatory, and a clear microphone matters most. [ASSISTANT] I'll search for wireless headphones under AUD 220 and check their microphone quality. [TOOL CALL] mcp__shopping__search_products Input: {'category': 'headphones', 'max_price_aud': 220} [TOOL RESULT] {"count": 3, "products": [{"id": "HP-204", "name": "Wireless Basic", "price_aud": 89}, {"id": "HP-202", "name": "Studio Comfort", "price_aud": 129}, {"id": "HP-201", "name": "Focus Wireless", "price_aud": 199}]} [ASSISTANT] Now let me get the full specifications for each headphone to check wireless capability and microphone quality. [TOOL CALL] mcp__shopping__get_product_details Input: {'product_id': 'HP-204'} [TOOL CALL] mcp__shopping__get_product_details Input: {'product_id': 'HP-202'} [TOOL CALL] mcp__shopping__get_product_details Input: {'product_id': 'HP-201'} [TOOL RESULT] {"id": "HP-204", "name": "Wireless Basic", "category": "headphones", "price_aud": 89, "connectivity": "Wireless", "microphone": "Basic", "comfort": "Medium"} [TOOL RESULT] {"id": "HP-202", "name": "Studio Comfort", "category": "headphones", "price_aud": 129, "connectivity": "Wired", "microphone": "Built-in", "comfort": "High"} [TOOL RESULT] {"id": "HP-201", "name": "Focus Wireless", "category": "headphones", "price_aud": 199, "connectivity": "Wireless", "microphone": "Clear voice", "comfort": "High"} [ASSISTANT] **I recommend the Focus Wireless (HP-201) at AUD 199.** It's the only option that meets both your mandatory requirements—it's wireless and has a clear voice microphone, which directly addresses your priority for call quality. The Studio Comfort is wired (doesn't meet your requirement), and while the Wireless Basic is budget-friendly, it only has a basic microphone that won't deliver the clarity you need for professional work-from-home calls. Status: success Turns: 3 Tokens: 3407 input, 384 output Cost: $0.0053Congratulations! In this step, you saw how the agent decides to call a tool, reads the result, and continues until it can answer, and you gave it tools of your own that it chains into a search workflow. You also saw what the tools give the agent and what they cost. The tools read a local file. You connect an external API next.Explanation
Check the output:
- Each tool call shows the full MCP name, such as
mcp__shopping__search_products. - The agent chose the inputs itself. It turned "headphones under
AUD220" into{'category': 'headphones', 'max_price_aud': 220}. - The agent called
search_productsfirst, and thenget_product_detailsfor each product that the search returned. The product IDs in the second tool's input came from the first tool's result. - The agent excluded Studio Comfort (
HP-202) because it is wired, although it costs less. It recommended Focus Wireless (HP-201), the only wireless product with a clear microphone. - In this example, the response calls both requirements mandatory, but the customer made only wireless mandatory. The recommendation is still correct. However, a model can blur a detail like this, so read each response against the request.
- Turns: each request to the model counts as one turn. The agent asked for the details of all three products in one request, so the search, the details, and the final answer give
Turns: 3.
What the tools give the agent:
- Data that is not in the prompt: the agent fetches only the products that the request needs.
- Exact values: the prices and product IDs come from code, not from what the model recalls.
- Control:
allowed_toolsand the code of each tool decide what the agent can read.
What the tools cost:
- More requests: each round of tool calls is one more turn, which sends the conversation again.
- More input tokens: in this lab, the SDK sends the description of each tool to the model in every request.
- Less certainty: the model decides whether to call a tool and which input to send.
- A new way to fail: a tool can return an error, which you handle in the next step.
-
Challenge
Connect external APIs and handle API failures
In this step, you will connect the agent to an external product API, complete the retry logic of API tools that also use timeouts and validation, and test the tools against an API that fails. ### Connect the agent to an external product API
In Step 3, your custom tools read products from a local file. In a real store, product data usually comes from another system, such as an inventory service, behind a REST API.
In this task, the agent does not call the API itself. It calls a custom tool, exactly as it did in Step 3, and the tool makes the HTTP request. The work is split between the two:
| | The agent | The tool | | --- | --- | --- | | Decides | When to search, and which category and budget to send | How to call the API | | Sees | The tool's name, description, inputs, and result | The API address, the token, and the raw response | | When the API fails | Reads a short tool error and tells the customer | Catches the failed request and returns the error |
This split shapes how you design an agent that uses an API:
- The description is the agent's main guide. The agent chooses the tool from its name and description, and fills the inputs from the customer's request. It knows nothing about URLs or HTTP.
- The agent receives one product format. The API uses its own field names, such as
skuandpricing.amount. The tool converts them toidandprice_aud, so the agent reads the same field names as in Step 3, wherever the data comes from. - Secrets stay outside the conversation. The tool reads the API address and token from the
.envfile. They never appear in the prompt, the tool input, or the tool result, so the model never sees them. - A failure becomes something the agent can act on. A network call can fail at any time. The tool returns a tool error, and your instructions tell the agent what to say when it receives one.
The lab provides everything on the tool's side of the table:
- A small product API in the
api/mock_product_api.pyfile. It runs on your machine, serves the same six products as thecatalog/products.jsonfile, and rejects requests without the correct token. - The API address and a demo token in the
.envfile. The token is a fixed value for this lab, not a real secret. - The
search_api_productstool in thetools/shopping_api_tools.pyfile. It callsGET /productswith the category and the budget.
This is what the agent sees of the tool:
@tool( "search_api_products", "Search the external product API by category and " "maximum price in AUD. Supported categories are " "laptops and headphones.", {"category": str, "max_price_aud": int}, )In this task, you connect the agent to the
search_api_productstool, start the product API, and ask the agent for headphones within a budget.Task Explanation tools=[search_api_products]registers the API tool with the MCP server. The agent connects to it in the same way as to the local tools in Step 3, so changing the data source does not change how you build the agent.API_INSTRUCTIONSis added to the system prompt. Its first line keeps the answer to the data that the API returned. Its second line tells the agent what to say when the tool returns an error.allowed_toolsapproves the API tool in advance.tools=[]removes every built-in tool, so the API tool is the agent's only way to reach product data.- The prompt does not mention a tool, a category field, or a price field. The agent chooses the tool from its description and builds the input
{'category': 'headphones', 'max_price_aud': 150}from the customer's words.
The tool then does its side of the work. The main part of
search_api_productsis shown below. You do not need to change it.try: async with httpx.AsyncClient(timeout=5.0) as client: response = await client.get( f"{api_url.rstrip('/')}/products", params={"category": category, "max_price_aud": max_price}, headers={"Authorization": f"Bearer {api_token}"}, ) response.raise_for_status() products = normalize_products(response.json()) return tool_result({"count": len(products), "products": products}) except httpx.HTTPStatusError as exc: return tool_error(f"Product API returned HTTP {exc.response.status_code}") except httpx.RequestError: return tool_error("Unable to connect to the product API") except (ValueError, KeyError, TypeError): return tool_error("Invalid product API response")paramscarries the inputs that the agent chose, andheaderscarries the token that the agent never sees.normalize_products()converts the API's field names into the field names from Step 3 before the result goes back to the agent.- Each
exceptblock turns one kind of failure into a tool error.HTTPStatusErroris a response with an error status, whichresponse.raise_for_status()raises.RequestErroris a failed connection or a timeout. The last block catches a response that is not the JSON that the tool expects. The messages are short and contain no token or URL, because the agent may repeat them to the customer. - If a tool raises an exception that it does not catch, the SDK returns the exception message to the agent as a tool error. That message is not written for a customer and can contain details such as a URL, so catch every failure that you expect.
Navigate to the second Terminal and execute the following command to start the product API. Leave it running.
uvicorn --app-dir api mock_product_api:app --host 127.0.0.1 --port 8000Navigate to the first Terminal and execute the following command to check that the API responds.
curl -H "Authorization: Bearer lab-demo-token" "http://127.0.0.1:8000/products?category=headphones&max_price_aud=220"You should see the API's own response format, with
sku,title, andpricingfields. The agent never sees this format.{"data":[{"sku":"HP-201","title":"Focus Wireless","category":"headphones","pricing":{"amount":199,"currency":"AUD"}},{"sku":"HP-202","title":"Studio Comfort","category":"headphones","pricing":{"amount":129,"currency":"AUD"}},{"sku":"HP-204","title":"Wireless Basic","category":"headphones","pricing":{"amount":89,"currency":"AUD"}}],"meta":{"count":3}}Then execute the following command to test the above changes.
python3 agents/04_external_apis/api_agent.py --user-prompt="List the headphones under AUD 150 with their product IDs and prices."You should see a response in your terminal as shown in the example response below. Your response may vary.
User prompt: List the headphones under AUD 150 with their product IDs and prices. [TOOL] mcp__shopping_api__search_api_products Input: {'category': 'headphones', 'max_price_aud': 150} [API RESULT] {"count": 2, "products": [{"id": "HP-202", "name": "Studio Comfort", "category": "headphones", "price_aud": 129}, {"id": "HP-204", "name": "Wireless Basic", "category": "headphones", "price_aud": 89}]} [ASSISTANT] Here are the headphones under AUD 150: 1. **Studio Comfort** (ID: HP-202) - $129 AUD 2. **Wireless Basic** (ID: HP-204) - $89 AUD Status: success Turns: 2 Tokens: 1579 input, 142 output Cost: $0.0023### Handle API errors and unexpected responsesExplanation
Check the output:
- The agent called
mcp__shopping_api__search_api_productsand chose the inputs from the customer's request. It sent a maximum price of150, not the 220 of thecurlcheck. [API RESULT]is what the agent read: the normalized format, withid,name, andprice_aud, and not the API'ssku,title, andpricingfields. No address or token appears in it.- The answer lists only the two headphones that the tool returned. The
curlcheck asked for headphones up toAUD220 and received three, so the API filtered by the price that the agent sent.HP-201atAUD199 is left out.
An external API can fail in many ways: it can be busy, slow, or offline, or it can return data in a format you did not expect. The tool from Task 1 reports each failure, but it gives up after one request. A reliable tool separates failures into two groups and treats them differently:
| Failure | Example | What the tool does | | --- | --- | --- | | Temporary | HTTP 503 (service outage), HTTP 429 (too many requests), a timeout | Retries the request, because the next attempt may succeed | | Permanent | HTTP 401 (wrong token), HTTP 404 (product not found), invalid data | Fails immediately, because a retry gives the same result |
The two groups are a policy that you choose for an API, not a fixed rule. A temporary failure can last, so the number of retries has a limit.
Several techniques make an API tool more reliable. The tools in this task use three of them:
- Timeout: a limit on how long the tool waits for a response, so a slow API cannot block the agent.
- Retry: the tool repeats a request that failed for a temporary reason, up to a maximum number of attempts.
- Response validation: the tool checks that the response has the expected structure before it uses the data.
When every attempt fails, the tool returns a tool error with a clear message. The agent receives that message in place of the products, so it can tell the customer what is unavailable.
A tool is a function, so you can test how it handles each failure without an agent. Such a test uses no tokens, and its result does not depend on what a model writes.
In this task, you complete the retry loop in
fetch_api()and test the two API tools against an API that fails in different ways. You then record the failures in theobservation.mdfile.Task Explanation MAX_ATTEMPTS = 3allows one request and two retries. More attempts make the tool more tolerant, but the customer waits longer for an answer.httpx.AsyncClient(timeout=0.75)stops waiting when connecting takes more than 0.75 seconds, or when the API sends no data for 0.75 seconds. A timeout raiseshttpx.TimeoutException, which is a kind ofhttpx.RequestError, so it is retried in the same way as a connection failure.try,except, andelsesplit each attempt in two:excepthandles a request that did not get a complete response, andelsehandles a response that arrived. The code underelse:is already in the file. The next three points describe it.- HTTP 401 and HTTP 404 raise
ProductAPIErrorimmediately. A wrong token or an unknown product ID gives the same result on every attempt. RETRYABLE_STATUS_CODESlists the temporary failures. For these, the loop continues to the next attempt, and raises an error only on the last one.response.json()raisesValueErrorwhen the response is not valid JSON, and the function turns it into aProductAPIError.- The two tools call
fetch_api()and check the structure of the response before they use it, because valid JSON can still have the wrong structure. Whenfetch_api()raisesProductAPIError, the tool returnstool_error(str(exc)). print(f"[API] Attempt ...")shows each attempt in your terminal, so you can see the retries. An agent that calls the tool does not see this line.
The provided API can simulate failures. The provided
tests/check_api_tools.pyfile calls the search tool once with no failure and once for each failure, and then asksget_api_product_details, the second tool of thetools/reliable_api_tools.pyfile, for a product that does not exist. It selects a failure with theSHOPPING_API_TEST_SCENARIOenvironment variable. The tool reads this variable and sends it to the API in a test header. This variable exists for testing only.The product API from Task 1 must be running in the second Terminal. If you stopped it, start it again with the command below.
uvicorn --app-dir api mock_product_api:app --host 127.0.0.1 --port 8000Navigate to the first Terminal and execute the following command to test the above changes.
python3 tests/check_api_tools.pyYou should see a response in your terminal as shown in the example response below.
=== no failure: The API works === Input: {'category': 'headphones', 'max_price_aud': 220} [API] Attempt 1/3 Is error: False {"count": 3, "products": [{"id": "HP-201", "name": "Focus Wireless", "category": "headphones", "price_aud": 199}, {"id": "HP-202", "name": "Studio Comfort", "category": "headphones", "price_aud": 129}, {"id": "HP-204", "name": "Wireless Basic", "category": "headphones", "price_aud": 89}]} === fail-once: The API fails the first attempt with HTTP 503 === Input: {'category': 'headphones', 'max_price_aud': 220} [API] Attempt 1/3 [API] Attempt 2/3 Is error: False {"count": 3, "products": [{"id": "HP-201", "name": "Focus Wireless", "category": "headphones", "price_aud": 199}, {"id": "HP-202", "name": "Studio Comfort", "category": "headphones", "price_aud": 129}, {"id": "HP-204", "name": "Wireless Basic", "category": "headphones", "price_aud": 89}]} === rate-limit: The API refuses every attempt with HTTP 429 === Input: {'category': 'headphones', 'max_price_aud': 220} [API] Attempt 1/3 [API] Attempt 2/3 [API] Attempt 3/3 Is error: True Product API unavailable after retries (HTTP 429) === timeout: The API takes too long to answer === Input: {'category': 'headphones', 'max_price_aud': 220} [API] Attempt 1/3 [API] Attempt 2/3 [API] Attempt 3/3 Is error: True Unable to connect to the product API === invalid-json: The API returns text that is not JSON === Input: {'category': 'headphones', 'max_price_aud': 220} [API] Attempt 1/3 Is error: True Invalid JSON returned by product API === invalid-schema: The API returns JSON with the wrong structure === Input: {'category': 'headphones', 'max_price_aud': 220} [API] Attempt 1/3 Is error: True Invalid product data returned by product API === not found: The product does not exist (HTTP 404) === Input: {'product_id': 'HP-999'} [API] Attempt 1/3 Is error: True Product not foundExplanation
Check the output:
Input:is the dictionary of arguments that the test passed to the tool. Every search sends the same input, so the results differ only because of the failure.fail-once: the first attempt failed and the second succeeded. The result showsIs error: Falseand the same products as the run with no failure, so an agent would never see this failure.rate-limitandtimeout: these failures are temporary, so the tool used all three attempts and then returned a tool error withIs error: True. Thetimeoutrun takes about two seconds, because each of the three attempts waits 0.75 seconds.Unable to connect to the product APIis the error that you raised in theexcept httpx.RequestErrorblock.invalid-json,invalid-schema, andnot found: a retry cannot fix these failures, so the tool stopped after one attempt.- Every result is what an agent would receive: the products, or one short message. A tool error holds no URL, token, or stack trace.
Note: This tool retries immediately, which keeps the task short. In production, a tool usually waits between attempts, for example for the time in the API's
Retry-Afterheader, so that the retries do not add load to a busy API.Open the
observation.mdfile in the project folder. In theFailures of the product APIsection, record the number of attempts and the message returned by the tool for each of the five failures. Congratulations! In this step, you connected the agent to a tool that calls an API, and tested how the API tools handle a failing API without running an agent. You recorded the failures in theobservation.mdfile. Each request is still a separate conversation. You manage conversations next. -
Challenge
Manage conversations, sessions, and memory
In this step, you will hold a multi-turn conversation with
ClaudeSDKClient, keep it inside a token limit with a summary, resume a saved session, save a customer preference with code, and build a personalized agent that reads it from memory in a new conversation. ### Build multi-turn shopping conversationsEvery agent so far has answered one request and stopped. By default, each
query()call starts a new session, which is the SDK's record of one conversation, so the agent does not see earlier requests. A real customer does not shop that way: they ask, change their mind, and ask a follow-up question that only makes sense in context, such as "What was my original budget?".A multi-turn conversation keeps one session open across several messages. The session stores the conversation history: every customer message and response, and every tool call and tool result when the agent uses tools. The SDK sends the history to the model with each request, so the agent can use what was said before. In this lab, the SDK sends every message of the history each time. A model can read only a limited amount of text in one request, which is called its context window. A conversation that nears this limit must be shortened, for example by replacing older messages with a summary.
Here, a turn means one customer message and the agent's reply. It is not the turn that
max_turnscounts: the agent can use several of those, one for each round of tool calls and one for the final answer, to answer a single customer message.The SDK provides
ClaudeSDKClientfor this:| |
query()|ClaudeSDKClient| | --- | --- | --- | | Session | A new session for each call | One session for many messages | | What the agent sees | Only the current request, by default | The conversation history | | Use it for | One-off tasks | Conversations and follow-up questions |A conversation with the client has three parts:
| Code | Purpose | | --- | --- | |
async with ClaudeSDKClient(options=options) as client:| Starts one conversation, and closes the client when the block ends | |await client.query(prompt)| Sends one customer message in that session | |async for message in client.receive_response():| Reads the messages of the response, up to its result |The options are the same
ClaudeAgentOptionsas before. Only the way you send messages changes.Because the history is sent with each request, a conversation holds more tokens with every message. Your code can keep it inside a limit in three steps:
- Read the context usage with
await client.get_context_usage(). It returns a dictionary, in whichtotalTokensis the number of tokens the conversation holds now andmaxTokensis the most tokens the conversation can hold, which is the context window of the model in this lab. - Compare
totalTokenswith a limit that you choose, belowmaxTokens. - When the limit is passed, start a new conversation and send a summary of the earlier messages in place of the history.
In this lab, the SDK does not shorten the history for you, so your code checks the usage and starts a new conversation. In this lab, the SDK also fills in only the totals of the dictionary, and the lists that break the usage down by part are empty.
In this task, the customer sends three messages: a request, a change of budget, and a question about the earlier request. You set a limit of
300tokens, which is far below the context window, so that the conversation already passes it after the second message. The third message then goes to a new conversation with a summary. The agent has no tools, so that you can see the conversation history at work on its own. Its instructions list the four headphones it can recommend, with their prices and features.Task Explanation async with ClaudeSDKClient(options=options) as client:opens one session.send_message()is called twice with thisclientinside the block, so the two messages share one conversation history, and the agent can use the first message when it answers the second.await client.query(prompt)sends a message without waiting for the response. It does not return the answer.- The rest of
send_message()is provided. It readsclient.receive_response(), which yields the messages of the response and stops after theResultMessage. - The second message changes only the budget, to
AUD150. It does not repeat the product type, because the agent already has it in the history. usage = await client.get_context_usage()asks the client how much of the context window the conversation uses.usage["totalTokens"]counts the instructions, both customer messages and both responses, which the next request would send again, together with the new message.CONTEXT_LIMIT = 300is the number of tokens above which the code starts a new conversation, andif usage["totalTokens"] > CONTEXT_LIMIT:compares the two.- The provided
summarize_requests()function builds the summary in code: it keeps the customer's two requests and leaves out the agent's responses. No request to the model is needed for it. async with ClaudeSDKClient(options=options) as new_client:opens a second session with an empty history.summary + thirdis its first message, so the request holds the instructions, the summary and the question, and not the two earlier responses.- The third message asks for the original budget. No instruction or file holds this value. The agent can answer because the summary holds the first request.
- The
elseblock is provided. When the conversation is within the limit, the third message continues in the first conversation. CONVERSATION_INSTRUCTIONSis added to the system prompt. It lists the four headphones with their prices and features, and tells the agent to keep earlier requirements when one changes.- The agent has no tools, so every answer comes from the instructions and the messages of its conversation, and each response takes one turn.
Execute the following command to test the above changes.
python3 agents/05_sessions_and_memory/multi_turn_agent.py --user-prompt="Find headphones under AUD 220 for working from home." --user-prompt="Actually, reduce my budget to AUD 150. What options do I have?" --user-prompt="What was my original budget? Does HP-201 meet my new budget?"You should see a response in your terminal similar to the example response below. Your response may vary.
Note: The limit is compared with the tokens of your own run. If your conversation holds
300tokens or fewer after the second message, the second[CONTEXT]line does not appear, and the third message continues in the first conversation.USER: Find headphones under AUD 220 for working from home. CLAUDE: For working from home under AUD 220, I'd recommend the **HP-201 Focus Wireless** (AUD 199) – it has wireless connectivity, a clear voice microphone perfect for calls, and high comfort for all-day wear. If you prefer a wired option to save money, the **HP-202 Studio Comfort** (AUD 129) is excellent value with a built-in microphone and the same high comfort level. Status: success Turns: 1 Tokens: 200 input, 100 output Cost so far: $0.0007 USER: Actually, reduce my budget to AUD 150. What options do I have? CLAUDE: Under AUD 150, you have two great options: the **HP-202 Studio Comfort** (AUD 129, wired with built-in microphone and high comfort) or the **HP-204 Wireless Basic** (AUD 89, wireless but with a basic microphone and medium comfort). The HP-202 is better for call quality, while the HP-204 gives you wireless freedom at a lower price. Status: success Turns: 1 Tokens: 320 input, 97 output Cost so far: $0.0015 [CONTEXT] 417 of 200000 tokens used [CONTEXT] Over the limit of 300: starting a new conversation with a summary USER: Summary of the conversation so far. The customer said: - Find headphones under AUD 220 for working from home. - Actually, reduce my budget to AUD 150. What options do I have? What was my original budget? Does HP-201 meet my new budget? CLAUDE: Your original budget was AUD 220, and you've now reduced it to AUD 150. The HP-201 Focus Wireless at AUD 199 does **not** meet your new budget. Your options under AUD 150 are the **HP-202 Studio Comfort** (AUD 129, wired) and **HP-204 Wireless Basic** (AUD 89, wireless). Both are suitable for working from home. Status: success Turns: 1 Tokens: 249 input, 103 output Cost so far: $0.0008### Manage agent sessions and conversation contextExplanation
Follow the conversation in the output:
- First message: three of the four headphones cost less than
AUD220, andHP-203atAUD239 is left out. The agent recommendedHP-201because it is wireless and has a clear voice microphone and high comfort, and offeredHP-202as a wired option. - Second message: the customer changed only the budget, but the agent kept both earlier requirements and listed the two headphones under
AUD150,HP-202andHP-204. This answer came from the conversation history. Its input tokens rose from 200 to 320, because the request sent the first message and its response again. - Context usage: the conversation holds 417 tokens, the 320 input tokens of the second request and the 97 tokens of its response. This is a small part of the 200,000-token context window, but it is over the limit of
300, so the code starts a new conversation. - Third message: the
USER:text begins with the summary. The agent answered"AUD 220"and said thatHP-201atAUD199 does not fit the new budget ofAUD150. Both budgets came from the summary. - Tokens and cost: the third request used 249 input tokens. In the first conversation, it would have sent the 417 tokens of history and the new question.
Cost so faris the total for one conversation, so it starts again in the new conversation.
In Task 1, the conversation lasted only while the script was running, but a real customer may come back an hour later and expect the assistant to remember. The SDK makes this possible, because it saves every session on disk. Every session has a session ID, and the final
ResultMessageof every run carries it insession_id. If you save the ID, you can return to the conversation later, from a new run of your program. A session file is local to the machine that created it.In this lab, the SDK stores each session as a file in the
sessionsfolder of the agent's working directory:sessions/<session ID>.jsonlIn this lab, the SDK writes one message of the conversation on each line, and keeps the file until you delete it. Your code needs only the session ID, which this task saves in the
sessions.jsonfile.ClaudeAgentOptionshas two settings for this:| Setting | What it does | Session ID | | --- | --- | --- | |
resume="<session ID>"| Continues an earlier conversation with its full history | Stays the same | |resume="<session ID>"withfork_session=True| Copies the history into a new session and continues there | A new ID; the original is unchanged |Resume continues one conversation. Fork creates a branch, so the customer can explore an alternative, such as a higher budget, without changing the original conversation. A fork copies only the conversation history. It does not copy files or data that the agent changes.
In this task, you save the session ID and set
resumeandfork_sessionin theagents/05_sessions_and_memory/session_agent.pyfile. You then start a conversation and resume it from a separate run, to check that the agent still knows the budget.Task Explanation resume=resumepasses a saved session ID to the agent. When the value isNone, the agent starts a new session.fork_session=forktells the agent whether to copy the resumed session into a new one.forkisTruein theforkaction andFalsein every other action. Use it together withresume.session_id = message.session_idreads the ID from the finalResultMessage. This is the value you must save to return to the conversation.- The
startaction saves the ID insessions.json, in the same folder as the script, under the nameoriginal. Theforkaction saves the new ID under the namefork. - The
resumeaction passessessions["original"], and theresume-forkaction passessessions["fork"]. The ID you pass decides which conversation continues. cwd=str(APP_DIR)is the same in every run. In this lab, the SDK looks for a resumed session only in thesessionsfolder of the working directory, so keepingcwdthe same lets every run of this script find the saved sessions.- The
showaction prints the path of the session file and the messages saved in it. --user-promptgives the customer's message, as in the earlier tasks. Without it, each action sends the message in the code.
Navigate to the Terminal and execute the following command to start a conversation.
python3 agents/05_sessions_and_memory/session_agent.py start --user-prompt="I am looking for wireless headphones for working from home. My budget is AUD 220."You should see a response in your terminal similar to the example response below. Your session IDs differ.
USER: I am looking for wireless headphones for working from home. My budget is AUD 220. CLAUDE: I'd be happy to help you find wireless headphones for working from home within your AUD 220 budget! To narrow down the best options for you, could you tell me what features matter most—for example, do you prioritize comfort for long wear, noise cancellation, battery life, or microphone quality for calls? Also, do you have any preference for over-ear or in-ear styles? Session ID: dacc5bca-65ea-4e5f-bcc4-e5bb0e139421 Tokens: 120 input, 88 output Cost: $0.0006Execute the following command to resume the conversation in a new run.
python3 agents/05_sessions_and_memory/session_agent.py resume --user-prompt="What is my budget?"USER: What is my budget? CLAUDE: Your budget is AUD 220 for wireless headphones suitable for working from home. Session ID: dacc5bca-65ea-4e5f-bcc4-e5bb0e139421 Tokens: 216 input, 21 output Cost: $0.0003Explanation
In the first run, the agent named no product, because its instructions give it no product list in this task.
The second run is a new program run, but the agent knows the budget. The session ID is the same as before, and the input tokens are higher because the SDK sent the first exchange to the model again, with the new message. In this lab, the SDK starts the cost of a resumed run from zero, so the cost is for this run only.
The
forkaction that you completed and theresume-forkaction work in the same way.forkcopies this conversation into a new session with a new ID and raises the budget toAUD300there, andresume-forkcontinues that copy. The original conversation keeps its budget ofAUD220. You do not need to run them in this task.Execute the following command to see the messages that were saved.
python3 agents/05_sessions_and_memory/session_agent.py showSession file: <your-workspace>/sessions/dacc5bca-65ea-4e5f-bcc4-e5bb0e139421.jsonl USER: I am looking for wireless headphones for working from home. My budget is AUD 220. CLAUDE: I'd be happy to help you find wireless headphones for working from home within your AUD 220 budget! To narrow down the best options for you, could you tell me what features matter most—for example, do you prioritize comfort for long wear, noise cancellation, battery life, or microphone quality for calls? Also, do you have any preference for over-ear or in-ear styles? USER: What is my budget? CLAUDE: Your budget is AUD 220 for wireless headphones suitable for working from home.Note: Storing session files on the local disk is fine for a lab, but it may not be suitable for production applications running across multiple servers. In production, applications typically use shared, durable storage, such as a database or object storage, so sessions can be resumed across servers and survive the failure of a server. Depending on the storage solution and its configuration, this can also support replication, backups, and disaster recovery. ### Build a personalized shopping agent with persistent memory
In Task 2, a session let the agent remember one conversation. A session stores the whole history of that conversation, and a new session starts with none of it. A returning customer who starts a new conversation must repeat every preference.
Persistent memory solves this. A few important facts, such as the customer's preferences, are saved in a store outside the conversation. Any later session can read them.
| | Session (Task 2) | Persistent memory (this task) | | --- | --- | --- | | What it stores | The full history of one conversation | A few chosen facts | | Where it lives | Session files that the SDK manages | Your own database | | Who can read it | Only the resumed or forked session | Any session of an agent that has a tool to read it |
A memory is written when a preference is saved or changed, and it is read in many later sessions. Your code or the agent can do each of these:
| | Your code | The agent, through a tool | | --- | --- | --- | | Suits | A fact that your application already has, such as a preference that the customer chose in a form | A fact that appears in a conversation, which the agent must understand first | | Cost | No tokens | Requests to the model, which use tokens | | Result | The same every time | It depends on what the model decides |
In this task, your code writes the preference and the agent reads it. The agent cannot read a database itself, so it gets a tool for that.
This split shapes how you build an agent with memory:
- The agent does not remember by itself. A new session has none of the earlier conversations. The agent recalls a preference only if it calls
search_memory, so your instructions must tell it to search before it recommends. When a preference must be used in every answer, your code can read it and add it to the prompt instead. - The agent gets only the tools that it needs, because in this lab, the SDK sends the description of each tool with every request, which adds input tokens. This agent only reads the memory, so its only tool is
search_memory. - Memory is useful when the agent acts on it. The agent recalls what the customer wants, and then chooses the product that matches. The customer repeats nothing.
The lab provides the
search_memorytool in thetools/memory_tools.pyfile. Thesaveaction of this task's script, which the lab also provides, writes a preference to the database with code. This is what the agent sees of its tool:@tool( "search_memory", "Search saved customer shopping preferences by keyword, such as " "'headphone' or 'laptop'. Use this before answering questions " "about preferences from earlier conversations.", {"query": str}, )The lab stores the data in SQLite, a database that is a single file and is built into Python. It needs no server. The lab creates the file
memory/shopping_memory.dbwith one table,memories, and uses one fixed customer,demo_customer.This agent brings together what you have built so far: instructions that say how to behave, a tool that the agent chooses to call, and its own reasoning about which product fits. Memory adds what it knows about the customer. To keep the task about memory, the agent does not use the product API. Its instructions list four headphones with their specifications.
In this task, you connect the search tool to the agent, run the provided code that saves a preference, and ask for a recommendation in a new session.
Task Explanation tools=[search_memory]registers the search tool with an MCP server namedmemory. The agent connects to it in the same way as to the product tools.MEMORY_INSTRUCTIONSis added to the system prompt. It is what turns a database tool into a memory: it tells the agent to search before it recommends, and to ask the customer when nothing is found. It also lists the products the agent can recommend.- The agent uses
query()withoutresume, so every run is a new session with no history. Only the database connects one run to the next.
Navigate to the Terminal and execute the following command to save a preference. No agent runs, so the command uses no tokens.
python3 agents/05_sessions_and_memory/memory_agent.py save --key="headphone_preference" --preference="wireless headphones with a clear microphone"The
--keyoption names the preference, and the--preferenceoption holds its text. Without an option, or without a value for it, the script uses the value that is shown here.You should see a response in your terminal as shown in the example response below.
save_memory returned: {"saved": true, "key": "headphone_preference", "value": "wireless headphones with a clear microphone"} search_memory returned: {"count": 1, "memories": [{"key": "headphone_preference", "value": "wireless headphones with a clear microphone"}]}Explanation
The first result confirms the key and the value that were stored.
search_memorythen read the row back from the database. This is the result that the agent receives when it searches.You can run the command again with your own text in
--preference, such aswired headphones with high comfort. Saving a key that exists replaces its value.Execute the following command to ask for a recommendation in a new session.
python3 agents/05_sessions_and_memory/memory_agent.py recommend --user-prompt="Recommend headphones based on my saved preferences."You should see a response in your terminal similar to the example response below. Your response may vary.
USER: Recommend headphones based on my saved preferences. [TOOL] mcp__memory__search_memory Input: {'query': 'headphone'} [MEMORY RESULT] {"count": 1, "memories": [{"key": "headphone_preference", "value": "wireless headphones with a clear microphone"}]} CLAUDE: Based on your saved preference for wireless headphones with a clear microphone, I recommend the **HP-201 Focus Wireless** at AUD 199. It features wireless connectivity, a clear voice microphone, and high comfort—perfectly matching what you're looking for. Session ID: b7655c6a-4924-427a-abd6-cc6cab14681a Turns: 2 Tokens: 1743 input, 119 output Cost: $0.0023Explanation
Check the output:
- A new session: the agent started with no history, and the customer's message did not contain a preference. Only the database connects this run to the
savecommand. - Recall: the agent called
search_memorybefore it recommended, asMEMORY_INSTRUCTIONStells it to. It used the keywordheadphone, which the instructions give as an example. - Match: three of the four headphones are wireless, but only
HP-201has a clear voice microphone. The agent chose it from the saved preference.
A different saved preference can give a different recommendation for the same request. That is what makes the answer personal.
Note: Local SQLite is suitable for this lab. This lab uses one fixed demo customer ID, so all runs share the same preferences. A production application should identify signed-in customers, let each customer read only their own memories, and decide how long a memory is kept and how a customer can change or delete it. With many customers or several servers, it should use a shared database that supports concurrent access, replication, backups, and high availability. Congratulations! In this step, you kept context across several messages, stayed inside a token limit by replacing the history with a summary, continued a conversation from a saved session, and built an agent that combines instructions, tools, and memory to make a personal recommendation. The agent still gives its first answer without checking it. You build a workflow that evaluates and refines an answer next.
- Read the context usage with
-
Challenge
Build workflows and specialized subagents
In this step, you will build a workflow in which your code evaluates the agent's recommendation and the agent refines it, and delegate a request to specialized subagents that a main agent chooses and starts. ### Plan, evaluate, and refine recommendations
An agent can give a confident answer that is wrong. In a shopping assistant, a wrong answer is a product that breaks one of the customer's mandatory requirements. A reliable workflow does not trust the first answer. It checks the answer, and asks the agent to correct it when the check fails.
The Plan → Execute → Evaluate → Refine workflow has four phases:
| Phase | Who does it | What happens | | --- | --- | --- | | Plan | The agent | Describes the steps it will take, before it recommends anything | | Execute | The agent | Carries out the plan and returns a recommendation | | Evaluate | Your code | Checks the recommendation against the mandatory requirements | | Refine | The agent | Receives the validation errors as feedback and tries again |
In Step 3, the agent carried out every step itself from numbered instructions, and nothing checked its answer. In this workflow, your code decides the order of the phases and checks the result. A recommendation that breaks a mandatory requirement is rejected, and the agent is asked to correct it before an answer is accepted.
Checking the final answer is one kind of safeguard. In Step 7, you add another: a
PreToolUsehook, which checks each tool call before it runs, while the agent stays in charge of the steps.Two ideas make this workflow dependable:
- Evaluate with code, not with the model. Rules such as "the price must not exceed
AUD220" are exact, so plain Python checks them and gives the same result every time. The agent finds and compares products, and your code verifies the outcome. The check covers only the rules that you write. It does not show that the product is the best choice or that the reason is accurate. - Limit the attempts. The Execute, Evaluate, and Refine phases form a loop. A maximum number of attempts stops the loop if the agent never produces a valid answer.
In this task, you set the maximum number of attempts, complete the Plan, Execute, and Evaluate phases of the workflow, and run it with a simulated first candidate that is wrong.
Task Explanation plan = await send_message(client, PLAN_REQUEST)is the Plan phase.PLAN_REQUESTtells the agent not to recommend a product yet, so it only describes its steps.for attempt in range(1, MAX_ATTEMPTS + 1)is the loop of the Execute, Evaluate, and Refine phases. WithMAX_ATTEMPTS = 2, the workflow checks at most two candidates, so a rejected candidate can be corrected once.candidate = await send_message(client, SHOPPING_REQUEST + feedback)is the Execute phase. The candidate is the agent's answer, as JSON text that code can read, such as{"product_id": "HP-201", "reason": "..."}. On the first attemptfeedbackis empty. On the second attempt it contains the validation errors.issues = check_candidate(candidate)is the Evaluate phase. The providedcheck_candidate()function reads the JSON withparse_recommendation(), then callsevaluate_recommendation(), which looks up the product in the catalog and checks the category, the budget, the connectivity, and the comfort rating. It returns a list of problems, and an empty list means the recommendation is valid.parse_recommendation()andevaluate_recommendation()are in the providedagents/recommendation_validator.pyfile.describe_candidate(candidate)returns the price and features of the recommended product from the catalog, so that you can see what the code checks.- An answer that is not a JSON object is returned as a problem too. The agent is then asked again, and the workflow does not stop with an error.
- The code after the Evaluate phase is provided. When
issuesis empty, it accepts the recommendation and ends the workflow withreturn. - When
issuesis not empty, it prints the problems and runsfeedback = build_feedback(candidate, issues), which starts the Refine phase. The providedbuild_feedback()function returns a short text with the rejected candidate and its problems. The next pass of the loop sends it with the request, so the agent knows exactly what to correct. - When every candidate is rejected, the last line prints
No validated recommendation after 2 attempts., and the workflow accepts no answer. - The same
clientsends every message, so the plan and the feedback are in one conversation history. --simulate-invalidusesWRONG_CANDIDATE,HP-204, as the first candidate. It is for testing only, so that you can see the Refine phase.
Execute the following command to test the above changes. The
--simulate-invalidoption makes the first candidate a deliberately wrong one, so that you see all four phases.python3 agents/06_workflows_and_subagents/planning_workflow.py --simulate-invalidYou should see a response in your terminal similar to the example response below. Your response may vary.
=== PLAN === [USAGE] Tokens: 230 input, 118 output [USAGE] Cost so far: $0.0008 1. Filter headphones under AUD 220 with wireless connectivity: HP-201 Focus Wireless (AUD 199), HP-203 Travel ANC (AUD 239 - excluded), and HP-204 Wireless Basic (AUD 89). 2. From the wireless options within budget, identify models with high comfort: HP-201 Focus Wireless is the only one with high comfort rating. 3. Verify the final recommendation meets all criteria: wireless, under AUD 220, and high comfort. === ATTEMPT 1 === [SIMULATION] Using a wrong candidate, not the agent's Candidate: {"product_id": "HP-204", "reason": "Cheapest wireless option"} Catalog: HP-204 Wireless Basic: AUD 89, Wireless connectivity, Medium comfort [INVALID] Recommendation rejected - Product does not meet the comfort requirement === ATTEMPT 2 === [USAGE] Tokens: 483 input, 61 output [USAGE] Cost so far: $0.0016 Candidate: ```json {"product_id": "HP-201", "reason": "HP-201 Focus Wireless meets all mandatory requirements (AUD 199, wireless, high comfort) and has the clear voice microphone preferred for work-from-home calls."} ``` Catalog: HP-201 Focus Wireless: AUD 199, Wireless connectivity, High comfort [VALID] Recommendation acceptedExplanation
Follow the workflow in the output:
- Plan: the agent listed three steps. It named products in them, although it was asked not to recommend one yet. The check reads the catalog, not the plan.
- Attempt 1: the
Catalogline shows that the simulated candidateHP-204is wireless and costsAUD89, within the budget, but its comfort rating is Medium. The code rejected it with"Product does not meet the comfort requirement". - Attempt 2: the agent received the rejected candidate and its problem as feedback, and recommended
HP-201. TheCatalogline showsAUD199, wireless, and High comfort, so the code accepted it.
Your code decided that
HP-204was wrong, not the model, and the agent used the feedback to give a valid answer. The model also sometimes wraps the JSON in a code fence, although it is asked not to.parse_recommendation()removes the fence, because code should not assume that a model follows a format exactly.Note: In this task, your code runs the workflow, so the order of the steps is guaranteed. An agent can also run a workflow itself from its instructions, but nothing forces it to follow the order. Hooks can check its tool calls, and you write one in Step 7. ### Delegate tasks to specialized subagents
In Task 1, your code split the work of one agent into phases. Until now, that one agent has done every job: it searched for products, compared them, and wrote the answer. As an assistant grows, one agent with every instruction and every tool becomes harder to control. A common solution is to split the work between subagents.
A subagent is a separate agent that the main agent starts for one job. Each subagent has its own system prompt, its own tools, and its own context. It does the job, and returns only a final report to the main agent. This has three benefits:
- Focus: Each subagent has a short prompt for one job.
- Least privilege: Each subagent gets only the tools that its job needs.
- A smaller main context: The subagent's knowledge and work stay inside the subagent. The main agent receives only the report.
You define a subagent with
AgentDefinitionand register it in theagentssetting ofClaudeAgentOptions:| Field | Purpose | | --- | --- | |
description| Tells the main agent when to use the subagent. The main agent uses it to decide which subagent fits the request | |prompt| The subagent's own system prompt | |tools| The tools that the subagent can use. In this lab, the SDK gives a subagent with an empty list no tools | |model| The model that the subagent runs on |The main agent starts a subagent with the built-in
Agenttool. It chooses the subagent from the descriptions and writes the task for it. The subagent starts with its own prompt and that task. It does not see the customer's conversation, so the main agent must pass on everything the subagent needs.The main agent is an orchestrator. It knows no products. It chooses between two specialists, and each specialist knows one part of the store:
| Agent | Job | What it knows | | --- | --- | --- | | Main agent (orchestrator) | Chooses a specialist, delegates, and writes the recommendation | Nothing about products | |
headphone-specialist| Recommends headphones | The four headphones, in its own prompt | |laptop-specialist| Recommends laptops | The two laptops, in its own prompt |To keep the task about delegation, the specialists have no tools. In Step 7, you add a
PreToolUsehook, which also checks the tool calls that subagents make.In this task, you complete the headphone specialist, give the main agent the
Agenttool and the two subagents, and send a headphone request.Task Explanation descriptionis what the main agent reads to choose a subagent. The two descriptions name different products and features, and that is enough for the main agent to route the request.promptis the subagent's own system prompt. Each specialist has its product list there, so the main agent's context never holds the catalog.tools=[]gives the specialist no tools in this lab. It can only work from its prompt and the task it receives. Without thetoolsfield, a subagent gets the tools of the main agent. In this lab, the SDK never gives a subagent theAgenttool.model=MODELruns the subagent on the same model as the main agent.tools=["Agent"]gives the main agent one built-in tool,Agent, which starts a subagent.- Each subagent is defined in its own variable,
HEADPHONE_SPECIALISTandLAPTOP_SPECIALIST, so you can read and change each definition separately. TheAGENTSdictionary gives each one a name. agents=AGENTSregisters the two subagents. The dictionary keys,headphone-specialistandlaptop-specialist, are the names that the main agent uses to select a subagent. In this lab, the SDK offers the main agent only these two subagents.- The provided
ORCHESTRATOR_INSTRUCTIONStext tells the main agent to choose a specialist, to pass on every requirement, and to write the answer from the report. The customer's request does not mention subagents. - In this lab, the SDK runs a subagent to its end before the
Agenttool returns, and the result of the tool is the report. - In the message loop of the provided
main()function, a tool call namedAgentis a delegation. Inblock.input, thesubagent_typevalue is the name of the subagent, and thepromptvalue is the task that the main agent wrote for it.
Execute the following command to test the above changes.
python3 agents/06_workflows_and_subagents/multi_agent_shopping.py --user-prompt="I need headphones for working from home under AUD 220. Wireless and high comfort are mandatory, and a clear microphone matters most."You should see a response in your terminal similar to the example response below. Your response may vary.
User prompt: I need headphones for working from home under AUD 220. Wireless and high comfort are mandatory, and a clear microphone matters most. [DELEGATION] headphone-specialist Task: I need headphones for working from home with the following requirements: - Budget: under AUD 220 - Must be wireless - Must have high comfort - Clear microphone is the most important feature Please recommend the best option that meets these criteria, prioritizing microphone quality above all other factors. [REPORT] headphone-specialist **HP-201 Focus Wireless - AUD 199** This is the only model that meets all your mandatory requirements: wireless, high comfort, and within budget. It's the ideal choice for your work-from-home setup, as it's the only option with a clear voice microphone—exactly matching your top priority for call quality. === FINAL RECOMMENDATION === The **HP-201 Focus Wireless** at AUD 199 is perfect for you—it's wireless, highly comfortable, and features a clear microphone that excels for work calls. It meets all your mandatory requirements and is the only option in your budget with the high-quality microphone you prioritize. Delegations: ['headphone-specialist'] Status: success Turns: 2 Tokens: 2151 input, 282 output Cost: $0.0036Congratulations! In this step, you checked a recommendation with code and refined it, and delegated a request to a specialist subagent. So far, no code checks a tool call before it runs. You add that safeguard next.Explanation
Check the output:
- Routing: the main agent chose
headphone-specialistfrom the two descriptions. The laptop specialist was not started. The main agent decides whether to delegate, and theDelegationsline shows what it did. - The task: the text after
Task:is what the main agent wrote for the specialist. It repeats every requirement, because the specialist cannot see the customer's message. - The report: the text under
[REPORT]is what the specialist sent back. The main agent has no product list, so the product in the final recommendation came from this report. - Turns and tokens:
Turns: 2counts the two requests of the main agent, the delegation and the final answer. In this lab, the SDK adds the tokens of the specialist to theTokensline.
- Evaluate with code, not with the model. Rules such as "the price must not exceed
-
Challenge
Add safeguards and test the assistant
In this step, you will limit what an agent may do with permissions and a
PreToolUsehook, and join the earlier parts in one shopping assistant that you test withpytest. You also record the test results in theobservation.mdfile. ### Implement agent permissions and safeguardsAn autonomous agent decides for itself which tools to call and with which arguments. That freedom is useful, but it is also a risk: an agent can call a tool it should not use, pass an argument that makes no sense, run for too long, or return a wrong answer. Instructions in a prompt reduce these risks, but a model does not always follow instructions. Safeguards are limits that your code enforces, whatever the model decides.
A dependable agent uses several layers, so that a problem missed by one layer is caught by the next:
| Layer | Setting or code | What it stops | | --- | --- | --- | | Available tools |
tools| Tools that the agent does not need | | Permission rules |allowed_toolsanddisallowed_tools|allowed_toolsapproves a tool in advance.disallowed_toolsstops a tool that must never run | | Permission mode |permission_mode="dontAsk"| A tool call that needs approval and that nothing has approved. It is denied, and nobody is asked | |PreToolUsehook |hooks| A tool call with invalid arguments, even for an approved tool | | Execution limits |max_turns,max_budget_usd| A run that takes too many turns or costs too much | | Output validation | Your own code | A recommendation that breaks a mandatory requirement |A subagent can have its own turn limit,
maxTurns, in itsAgentDefinition.The table lists the layers from the widest to the most specific. It is not the order in which the SDK checks a tool call. For each call, the SDK runs the
PreToolUsehook first, then the deny rules, and then the allow rules. A call that nothing has approved by then would go to acan_use_toolcallback, and indontAskmode it is denied.A hook is a function of yours that the SDK calls at a fixed point in the agent loop. A
PreToolUsehook runs before every tool call, including the tool calls of subagents. It receives the tool name and the tool input, and it returns a decision:- An empty dictionary,
{}, lets the call continue. - A
permissionDecisionof"deny"blocks the call. The agent receives the reason, and it may call the tool again with a corrected input.
For example, a hook returns this dictionary to block a search with a price that is too high:
{ "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Maximum price must be between 0 and 2000", } }In this task, you complete the hook that blocks an invalid tool call, add the hook and the
dontAskpermission mode to the agent, and run the agent with a request that goes over the price limit.Task Explanation validate_tool_request(), in the sameagent_safeguards.pyfile, holds the rules. For the search tool, the category must belaptopsorheadphones, and the maximum price must be a whole number from 0 toMAX_SEARCH_PRICE_AUD, which is 2000. A tool that the function does not know is refused. The function returns the reason a call is refused, orNonewhen the call is allowed. It is a plain function, so you can test it without an agent. It also has a rule for the details tool. This agent has only the search tool, so that rule is not used in this task.deny_tool(reason)builds the output that blocks a call."hookEventName"names the event of the hook,"permissionDecision": "deny"is the decision, and"permissionDecisionReason"is the message that the agent receives.validate_before_tool_use()is the hook. The SDK passes itinput_data, which containstool_nameandtool_input. It returnsdeny_tool(reason)to block the call, or{}to let it continue.hooks={"PreToolUse": [HookMatcher(hooks=[validate_before_tool_use], on_failure="block")]}registers the hook. AHookMatcherwithout amatchervalue applies to every tool.on_failure="block"tells the SDK what to do when the hook itself fails, for example with an error in its code. Without it, the SDK treats a failed hook as a hook with no objection, and the call can run. With it, the call is blocked. A safeguard must block when it breaks.disallowed_toolsnames tools that must never run. A deny rule wins over every other setting.permission_mode="dontAsk"denies any tool call that needs approval and that nothing has approved, and nobody is asked, neither a user nor acan_use_toolfunction. This suits an agent that runs unattended.- The agent returns a small JSON object. After the run, the
main()function of thesafe_shopping_agent.pyfile checks it with code:parse_recommendation()reads it, andevaluate_recommendation()checks the product against the catalog. The script prints what the agent receives for each tool call as anOutput:line. It also prints the response so that you can inspect it, and then checks it. A recommendation that fails is marked[INVALID]and reported as withheld. A real application would check it before it shows anything to the customer. - The provided
AGENT_INSTRUCTIONStext tells the agent not to call the tool again after a blocked call, and to report the reason. This is an instruction, so the model may not follow it. max_turns=2is the limit that the code enforces. The agent gets one turn to search and one turn to answer, and the run ends before a third request to the model. A blocked call uses a turn too, so an agent that searches again has no turn left for the answer.
Navigate to the Terminal and execute the following command to run the protected agent. The request has a budget of
AUD8000, which is above the search limit ofAUD2000.python3 agents/07_safeguards_and_testing/safe_shopping_agent.py --user-prompt="I need headphones for working from home under AUD 8000. Wireless and high comfort are mandatory, and a clear microphone matters most."You should see a response in your terminal similar to the example response below. Your response may vary.
User prompt: I need headphones for working from home under AUD 8000. Wireless and high comfort are mandatory, and a clear microphone matters most. [BLOCKED] mcp__shopping__search_products: Maximum price must be between 0 and 2000 Input: {'category': 'headphones', 'max_price_aud': 8000} Output: Maximum price must be between 0 and 2000 [HOOK OK] mcp__shopping__search_products Input: {'category': 'headphones', 'max_price_aud': 2000} Output: {"count": 4, "products": [{"id": "HP-204", "name": "Wireless Basic", "price_aud": 89}, {"id": "HP-202", "name": "Studio Comfort", "price_aud": 129}, {"id": "HP-201", "name": "Focus Wireless", "price_aud": 199}, {"id": "HP-203", "name": "Travel ANC", "price_aud": 239}]} Status: error_max_turns Turns: 2 Tokens: 1921 input, 175 output Cost: $0.0028 === VALIDATION === Agent response: None [INVALID] The response is not a JSON object Recommendation withheld### Integrate and test the complete Shopping AssistantExplanation
Check the output:
- First call: the agent searched with
max_price_audset to8000, the customer's budget. The hook blocked the call with a reason, and the tool did not run. TheOutput:line shows the reason, which the agent received in place of the tool's output. - Second call:
AGENT_INSTRUCTIONStells the agent not to call the tool again, but it searched again withmax_price_audset to2000. The input is valid, so the hook had no objection and printed[HOOK OK]. The call ran becauseallowed_toolsapproves the tool, and itsOutput:line shows the four products that it returned. The instruction did not stop the model. - The limit: the run had used its two turns, so it ended with
Status: error_max_turnsbefore a third request. The agent gave no response. - The code withheld the result. There is no JSON object to check, so no recommendation reaches the customer.
If your agent does not search again, it returns
NONEwith the reason for the block. The run then ends withStatus: success, and the code withholds that response as well, because the catalog has a product that meets the requirements.A complete shopping assistant joins the parts that you built in the earlier steps in one program, which sends one customer message and prints the agent's answer.
No new SDK feature is needed. Each part is a setting that you have already used:
| Part | Built in | Setting or code | | --- | --- | --- | | Instructions and limits | Step 2 |
system_prompt,max_turns, andmax_budget_usd| | Custom tools | Step 3 |mcp_serversandallowed_tools| | Product search with error handling | Step 4 | Theshopping_apiMCP server | | Client and persistent memory | Step 5 |ClaudeSDKClient, and thememoryMCP server | | Permission mode | Task 1 |permission_mode|The workflow and the subagents of Step 6, and the hook of Task 1, are not part of this assistant. They stay in their own scripts.
Until now, you tested each agent by running it and reading the answer. Every run uses tokens, takes time, and gives a slightly different answer. A check such as "the answer must equal this text" does not work on a real answer.
A test with mocks avoids this problem. It replaces the product API and the model with mocks. A mock is a stand-in that returns a fixed response. The result then does not depend on what a model writes, so the test can compare it with an exact value. Four of the five tests in this task call no real API and no real model:
| Replaced with a mock | What the test checks | | --- | --- | | The product API | The tool converts the API data into the format that the agent uses | | The SDK client, and with it the model | The assistant sends the customer's message and returns the answer |
The tests use three Python tools:
pytestfinds every function whose name starts withtest_, runs it, and reports whether it passed or failed.pytest-asyncioletspytestrun a test that is anasyncfunction. Such a test is marked with@pytest.mark.asyncio.unittest.mockis part of Python. ItsMagicMockclass is a stand-in for any object, and itsAsyncMockclass is a mock of anasyncfunction.
Each test has three parts, marked with comments. Arrange prepares the input and the mocks. Act calls the code under test. Assert checks the result with
assert.A mock of the model cannot show what the model decides. The last test in the file is a live test: it runs the real agent and checks what must hold in every run: the answer names the product, and the agent called the product API. It still replaces the product API with a mock and uses a temporary database, so the model is the only part that can vary. A live test uses tokens on every run, so it carries the
@pytest.mark.livemarker. A marker is a label, and the-moption ofpytestselects tests by their labels.In this task, you connect the parts in one assistant, complete the mock client and two of the five tests, send the assistant a message, and run the four tests that are not live. You then make one test fail, and record both test runs in the
observation.mdfile.Task Explanation The assistant:
mcp_servers={"memory": memory_server, "shopping_api": shopping_server}connects both MCP servers to one agent. For each message, the agent decides whether to search memory, call the product API, or do both.allowed_toolsapprovessave_memoryas well assearch_memory. Unlike the agent of Step 5, this assistant can save a preference, and its instructions tell it to save only when the customer asks.send_message()is provided. Themain()function calls it once, with the message of the--user-promptoption. It returns the answer and does not only print it, which lets a test check it.
The tests, in the order of the file:
| Test | Arrange and mocks | Act | Assert | | --- | --- | --- | --- | |
test_search_returns_products_from_a_mocked_api|monkeypatch.setattr()replacesapi.fetch_api, the function that sends the HTTP request, with anAsyncMockthat returnsAPI_RESPONSE| Calls the tool directly through.handler, where@toolkeeps the original function | The tool returned one product, with the IDHP-201and the price 199 | |test_memory_saves_and_finds_a_preference| No mock.DB_PATHis replaced with a file intmp_path, a temporary folder frompytest, so your real database is not changed | Saves one preference, and then searches for it | The search found one memory with the saved value | |test_assistant_connects_memory_and_product_tools| No mock.LAB_ENVIRONMENTis set tofalse, so the test needs no API key | Callscreate_agent_options()| Both MCP servers are connected, andpermission_modeis"dontAsk". The test fails until you setmcp_servers| |test_assistant_returns_the_answer_of_the_agent|mock_client()returns aMagicMockin place ofClaudeSDKClient. Itsqueryis anAsyncMock, which can be awaited and records its calls. Itsreceive_responsegives oneResultMessagewith the fixed answer | Callssend_message()with the mock client, so no model is called |assert_awaited_once_with()checks that the message was sent once, andassert answer == ...checks that the answer came back unchanged | |test_assistant_returns_the_answer_of_the_real_agent| The product API request is replaced as in the first test.DB_PATHis replaced abovememory.init_db(), so the table is created in the temporary database. The model is not mocked | Opens a realClaudeSDKClientand callssend_message()| The answer containsHP-201, andapi.fetch_api.assert_awaited()checks that the agent called the product tool, which called the mocked request |monkeypatchis provided bypytest. It puts the real value back when the test ends.The
livemarker is registered in thepytest.inifile. In the lab environment,skipifskips the live test whenLAB_API_KEYis not set.The assistant calls the product API from Step 4, which must be running in the second Terminal. If you stopped it, start it again with the command below. The tests in this task do not need it.
uvicorn --app-dir api mock_product_api:app --host 127.0.0.1 --port 8000Navigate to the first Terminal and execute the following command to send the assistant a message. The message uses the preference that you saved in Step 5.
python3 agents/07_safeguards_and_testing/integrated_shopping_assistant.py --user-prompt="Recommend headphones under AUD 220 from my saved preferences."You should see a response in your terminal similar to the example response below. Your response may vary.
Globomantics Shopping Assistant YOU: Recommend headphones under AUD 220 from my saved preferences. [TOOL] mcp__memory__search_memory [TOOL] mcp__shopping_api__search_api_products [API] Attempt 1/3 Turns: 2 Tokens: 2551 input, 189 output Cost: $0.0035 CLAUDE: Based on your saved preference for wireless headphones with a clear microphone, I recommend the **HP-201 Focus Wireless** at AUD $199. It features wireless connectivity, a clear voice microphone, and high comfort—perfectly matching your requirements and staying within your budget.The program ends after the answer.
Explanation
Check the output:
- Memory: the agent called
search_memoryand found the preference from Step 5. The customer's message did not repeat it. If no preference is saved, the instructions tell the agent to say so and still recommend a product that the search returned. - Product API: the agent called
search_api_productsfor the products within the budget. The[API] Attempt 1/3line is printed by the request code from Step 4. - One answer from both: the agent recommended the product that the API returned and that matches the saved preference.
Execute the following command to run the four tests that are not live. The
-m "not live"option leaves out the live test, so the command uses no tokens.python3 -m pytest tests/test_shopping_assistant.py -m "not live"You should see a response in your terminal similar to the example response below. The first lines describe your environment and are not shown here. The time varies.
collected 5 items / 1 deselected / 4 selected tests/test_shopping_assistant.py::test_search_returns_products_from_a_mocked_api PASSED [ 25%] tests/test_shopping_assistant.py::test_memory_saves_and_finds_a_preference PASSED [ 50%] tests/test_shopping_assistant.py::test_assistant_connects_memory_and_product_tools PASSED [ 75%] tests/test_shopping_assistant.py::test_assistant_returns_the_answer_of_the_agent PASSED [100%] ======================= 4 passed, 1 deselected in 0.03s ========================Explanation
Check the output:
- The four tests: they call no model and no API, run in less than a second, and use no tokens. They pass even when the product API is stopped, because the first test replaces
fetch_apiand the other three do not call the API. - The live test:
1 deselectedis the live test. The-m "not live"option left it out, so the real agent did not run. - A failure names its cause: when a test fails,
pytestprints theassertline and the values that it compared.
These four tests check your code, not the model. The live test checks what the model decides: the answer names the product, and the agent called the product API.
Note: The
-moption chooses which tests run. To run only the live test, replace-m "not live"with-m livein the command. The live test runs the real agent, so it uses about as many tokens as one message to the assistant. Without the-moption, the command runs all five tests.Record this run. Open the
observation.mdfile in the project folder. In theTest run of the assistantsection, write the number of tests that passed and the number that were deselected.Next, make one test fail. In the
agents/07_safeguards_and_testing/integrated_shopping_assistant.pyfile, in thecreate_agent_options()function, changepermission_mode="dontAsk"topermission_mode="default". Then execute the same command again.python3 -m pytest tests/test_shopping_assistant.py -m "not live"You should see a response in your terminal similar to the example response below. The time varies.
collected 5 items / 1 deselected / 4 selected tests/test_shopping_assistant.py::test_search_returns_products_from_a_mocked_api PASSED [ 25%] tests/test_shopping_assistant.py::test_memory_saves_and_finds_a_preference PASSED [ 50%] tests/test_shopping_assistant.py::test_assistant_connects_memory_and_product_tools FAILED [ 75%] tests/test_shopping_assistant.py::test_assistant_returns_the_answer_of_the_agent PASSED [100%] =================================== FAILURES =================================== _______________ test_assistant_connects_memory_and_product_tools _______________ tests/test_shopping_assistant.py:108: in test_assistant_connects_memory_and_product_tools assert options.permission_mode == "dontAsk" E AssertionError: assert 'default' == 'dontAsk' E E - dontAsk E + default =========================== short test summary info ============================ FAILED tests/test_shopping_assistant.py::test_assistant_connects_memory_and_product_tools ================== 1 failed, 3 passed, 1 deselected in 0.07s ===================Explanation
Check the output:
- One test failed:
test_assistant_connects_memory_and_product_toolsreads the options of the assistant, so it is the test that sees the changed setting. The other three tests do not readpermission_mode, and they still pass. - The cause:
pytestprints theassertline that failed. In the lines below it,- dontAskis the value that the test expects, and+ defaultis the value that your code has now. - No tokens: the test found a wrong setting in less than a second, without a run of the agent.
In the
observation.mdfile, in theA failing testsection, write the change that you made and the name of the test that failed. In theLimitations and improvementssection, write one thing that the four tests cannot check and one improvement to the tools or the tests.Hint
- What the four tests cannot check: each of the four tests either replaces the model with a mock or does not call it. Consider which part of the assistant never runs in these tests.
- An improvement: think of a situation that the tests do not try, such as a product API that returns an error.
Then change
permission_modeback to"dontAsk"and execute the command again. All four tests pass again. Congratulations! In this step, you limited the tools and arguments that an agent may use, integrated and tested the complete assistant, and recorded a passing and a failing test run in theobservation.mdfile.Before you run an agent like this one in production, consider the following:
- Storage: keep sessions and memory in shared, durable storage, so that any server can resume a conversation.
- Customers: identify each signed-in customer, and check in code that a customer reads and changes only their own sessions and memories.
- Limits: set
max_turnsandmax_budget_usdon every agent, and give each agent only the tools and permissions that it needs. - Retries: retry only temporary failures, limit the attempts, and wait longer before each one, with a small random delay. This is called exponential backoff with jitter, and it spreads the retries out, so that they do not all reach a busy API at the same moment.
- Tests: test the code around the model with mocks, and run each live scenario several times, because a model can answer differently each time.
- Monitoring: record the token usage, cost, response time, errors, and tool calls of each run, so that you notice unexpected behavior.
You have completed the lab and can apply the same patterns to your own agents.
- An empty dictionary,
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.