Build Your First AI Agent with Tool Use
Build a Python AI agent that autonomously selects and calls tools.
Introduction
30 Second Summary
When you ask someone to calculate a dinner tip and check your schedule, they grab a calculator and look at a calendar. The most capable AI systems today work the exact same way.
In this project, you'll build a Python command-line AI agent that decides which tools to use based on your questions. You'll watch it pick the right tool, run calculations, read files, and combine results into a final answer.
What You'll Build
Picture asking your terminal "What's 18% tip on an $85.50 dinner, and what's today's date?" and watching your agent select the right tools, run them, and deliver a polished combined answer.
By the end of this project, you'll have:
- A terminal-based AI agent powered by Claude that you can chat with and watch make its own decisions about which tools to call.
- Three custom tools your agent calls on its own to answer questions: crunch numbers, check the date, or read your notes file.
- A hands-on feel for the agentic loop pattern, the same architecture powering every production AI assistant and copilot today.
- Secret Mission: Add a personality and a note-writing tool to your agent, turning it into a full read-write assistant.
Are there any prerequisites?
You'll need basic Python familiarity (variables, functions, loops) and an Anthropic API key. Step 1 walks you through installing the SDK and configuring your environment.
Before We Start
Before We Start...
Before we dive in, let's lock in what you're about to build and why it matters.
You're creating an AI agent that autonomously picks and runs tools in a loop. This is the exact architecture powering every chatbot, copilot, and AI assistant in production today.
Set Up Your Environment
You're building an AI agent that autonomously selects and uses tools to answer your questions. All of this starts with connecting your Python code to Claude through Anthropic's API.
This step gets your development environment ready so you can start writing agent code in the next step.
In this step, get ready to:
- Install the Anthropic Python SDK.
- Set your API key as an environment variable.
- Create your project folder and starter files.
Install the Anthropic Python SDK
The Anthropic Python SDK is the library that lets your Python code communicate with Claude's API. Without it, your script has no way to send requests to Claude or receive responses.
- In VS Code, click Terminal in the top menu bar.
- Click New Terminal.
- Install the Anthropic SDK by running this command:
pip install anthropic
What does this install?
pip downloads the anthropic package from PyPI and installs it into your Python environment. This gives your code access to the Anthropic() client class, which handles authentication and request formatting when talking to Claude.
- Verify the install worked by running:
python -c "import anthropic; print(anthropic.__version__)"
You should see a version number like 0.104.1 printed in your terminal.
Seeing an error?
- If pip is not recognized, try pip3 install anthropic instead.
- If python is not recognized, try python3 instead.
- If the import fails with a ModuleNotFoundError, pip may have installed to a different Python version. Try pip3 install anthropic to target Python 3 specifically.
Help me fix my Anthropic SDK installation
Set your API key as an environment variable
Claude needs your API key to verify that you're authorized to use the API. An environment variable stores this key in your terminal session so your code can access it without hardcoding it into your script.
- In your terminal, set the ANTHROPIC_API_KEY environment variable by running this command:
macOS
export ANTHROPIC_API_KEY="your-api-key-here"
Windows
In PowerShell:
$env:ANTHROPIC_API_KEY = "your-api-key-here"
Or in Command Prompt:
set ANTHROPIC_API_KEY=your-api-key-here
- Replace your-api-key-here with your actual Anthropic API key.
- Confirm it's set by running:
python -c "import os; print(os.environ.get('ANTHROPIC_API_KEY', 'NOT SET')[:10] + '...')"
You should see the first 10 characters of your API key followed by ... printed in the terminal.
Why an environment variable?
Storing your API key in an environment variable keeps it out of your source code. If you ever share or publish your script, the key stays private.
This variable is session-only. It disappears when you close the terminal. You'll need to set it again each time you open a new terminal session.
Seeing 'NOT SET'?
- Double-check that you replaced your-api-key-here with your actual key.
- Make sure you ran the export (macOS) or $env: (Windows PowerShell) command in the same terminal window where you're running the verification.
Help me set my ANTHROPIC_API_KEY environment variable
Create your project folder and files
- Move to your Desktop and create your project folder by running these commands:
cd ~/Desktop
mkdir ai-agent
cd ai-agent
- Confirm the folder was created by running:
ls
The output should be empty since the folder is brand new.
- In VS Code, click File in the top menu bar.
- Click Open Folder.
- Navigate to your Desktop.
- Select the ai-agent folder and click Open.
Your terminal session resets here
When VS Code opens a new folder, it starts a fresh terminal session. Your ANTHROPIC_API_KEY environment variable from the previous substep is no longer set.
If VS Code asks whether you trust the authors of the files in this folder, click Yes, I trust the authors.
- Open a new terminal by pressing Ctrl+` (the backtick key, above Tab).
- Set your API key again in this new terminal:
macOS
export ANTHROPIC_API_KEY="your-api-key-here"
Windows
In PowerShell:
$env:ANTHROPIC_API_KEY = "your-api-key-here"
Or in Command Prompt:
set ANTHROPIC_API_KEY=your-api-key-here
Now you'll create the two files your project needs. agent.py will hold your agent's code, and notes.txt will give it sample data to read.
- In the Explorer panel on the left, click the New File icon at the top of the panel.
- Type agent.py and press Enter.
- Click the New File icon again.
- Type notes.txt and press Enter.
- Click notes.txt in the Explorer to open it.
- Paste the following sample meeting notes into the file:
Meeting Notes - May 2026
- Project deadline: June 15th
- Budget: $5,000 remaining
- Team members: Alice, Bob, Charlie
- Next meeting: Thursday at 2pm
What are these notes for?
Your agent will have a read_file tool that can open and read text files. This sample data gives it something meaningful to work with when you test the agent later.
- Save notes.txt by pressing Cmd+S (macOS) or Ctrl+S (Windows).
✔️ Awesome, I've got everything!
Great. Double check that you've saved notes.txt.
ⓧ I'd like to double check the full code
Here is the full content that notes.txt should contain:
Meeting Notes - May 2026
- Project deadline: June 15th
- Budget: $5,000 remaining
- Team members: Alice, Bob, Charlie
- Next meeting: Thursday at 2pm
The agent.py file should be empty for now. You'll add code to it in the next step.
- Confirm both files exist by running this in your terminal:
ls
You should see agent.py and notes.txt listed in the output.
Don't see both files?
- Make sure your terminal is in the ai-agent folder. Run pwd (macOS) or Get-Location (Windows) to check your current directory.
- If a file is missing, create it again using the New File icon in the Explorer panel.
Help me set up my ai-agent project folder
Your environment is ready. Next up, you'll define the tools that give your agent its superpowers.
Define Your Agent's Tools
Your environment is set up. Python, the Anthropic SDK, and your project files are all in place.
An AI model on its own can only generate text. To make it useful as an agent, you need to describe the actions it can take. These descriptions are called tool schemas, and they're what Claude reads to decide which action to take for any given question.
In this step, get ready to:
- Set up the imports and initialize the Anthropic client.
- Define three tool schemas that give your agent calculator, date/time, and file reading abilities.
Set up the imports and client
Every Python script starts with its imports. Your agent needs three libraries: the Anthropic SDK to talk to Claude, json to format tool data, and datetime to power the date/time tool you'll build shortly.
- In VS Code, switch to your empty agent.py file and add the imports and client initialization by pasting this code:
import anthropic
import json
from datetime import datetime
# Initialize the Anthropic client (reads ANTHROPIC_API_KEY automatically)
client = anthropic.Anthropic()
What does this code do?
- anthropic is the official Anthropic SDK that connects your Python code to Claude's API.
- json and datetime are built-in Python libraries you'll use in your tool functions later.
- anthropic.Anthropic() creates the client. It automatically reads the ANTHROPIC_API_KEY environment variable you set in Step 1.
- Save agent.py.
- Verify the imports work by running this in your terminal:
python agent.py
The script exits immediately with no output. That means your imports loaded and the client initialized successfully.
Seeing an error?
- ModuleNotFoundError: No module named 'anthropic' means the SDK isn't installed. Return to Step 1 and run pip install anthropic again.
- Make sure you're running the command from inside your ai-agent folder where agent.py lives.
Help me debug why my agent.py won't run
Define the tool schemas
Tool schemas are like instruction manuals for Claude. Each one describes a tool's name, what it does, and what inputs it needs. Claude reads these descriptions to decide which tool to call.
- In agent.py, start the tools list below the client line by adding your first tool, the calculator:
# Define the tools Claude can use
tools = [
{
"name": "calculator",
"description": "Performs mathematical calculations. Use this for any math operations like addition, subtraction, multiplication, division, percentages, etc.",
"input_schema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "The mathematical expression to evaluate, e.g. '15 * 0.15' or '100 / 3'"
}
},
"required": ["expression"]
}
},
What does this code do?
- tools is a list of dictionaries. Each dictionary describes one tool Claude can use.
- The description field is what Claude reads to decide WHEN to use this tool. A vague description means Claude won't know when to pick it.
- The input_schema tells Claude what parameters the tool accepts. Here, the calculator takes a single expression string like 15 * 0.15.
- Directly below the calculator tool (after the trailing comma), add the remaining two tools to complete the list:
# Date/time tool (no inputs needed)
{
"name": "get_datetime",
"description": "Gets the current date and time.",
"input_schema": {
"type": "object",
"properties": {},
"required": []
}
},
# File reader tool
{
"name": "read_file",
"description": "Reads the content of a text file.",
"input_schema": {
"type": "object",
"properties": {
"filename": {
"type": "string",
"description": "The name of the file to read"
}
},
"required": ["filename"]
}
}
]
What do these tools do?
- get_datetime has an empty properties object and an empty required array. It doesn't need any input because it just checks the clock.
- read_file takes a filename string so Claude can specify which file to read. This is the tool that will access your notes.txt.
- Notice the closing ] at the bottom. This closes the tools list you opened in the previous chunk.
Before you run this, how many tools do you think your agent has access to?
- Save agent.py.
- Verify your tools loaded correctly by running:
python -c "import agent; print(len(agent.tools), 'tools defined')"
You should see 3 tools defined in your terminal. That confirms Python parsed all three tool schemas without errors.
Not seeing 3 tools defined?
- A SyntaxError usually means a missing comma between tool dictionaries, a missing closing brace }, or a missing closing bracket ]. Check that each tool dictionary ends with }, except the last one, which ends with just }.
- If you see an error about ANTHROPIC_API_KEY, your environment variable from Step 1 may have expired. Re-run the export command from Step 1 to set it again.
- Make sure your terminal is in the ai-agent folder so Python can find agent.py.
Help me debug my tool schemas in agent.py
Understand the schema structure
Why does the schema structure matter?
Each tool has three fields: name, description, and input_schema.
The description is the most important field. Claude reads it to decide WHEN to use each tool. A vague description like "does stuff" would leave Claude guessing. A specific description like "Performs mathematical calculations" tells Claude exactly when to reach for the calculator.
The input_schema uses JSON Schema format to define what parameters the tool accepts. Claude uses this to generate valid inputs automatically. You never have to parse user input yourself.
✔️ Awesome, I've got everything!
Great. Double check you've saved agent.py and you're ready for the next step.
ⓧ I'd like to double check the full code
Scroll up through your agent.py and confirm these sections appear in order:
- Imports: import anthropic, import json, and from datetime import datetime.
- Client: client = anthropic.Anthropic().
- Tools list: tools = [...] containing three tool dictionaries: calculator, get_datetime, and read_file.
Make sure the list opens with tools = [ and closes with a matching ] at the end.
Your agent now knows what tools exist. Next up, you'll build the function that actually runs those tools when Claude calls them.
Build the Tool Executor
Your tool schemas tell Claude what tools exist and what inputs they accept. But schemas alone can't do anything.
In this step, you'll build the execute_tool function. This is the bridge between Claude's decisions and real-world actions: when Claude says "use the calculator," your executor is what actually computes the answer.
In this step, get ready to:
- Build the execute_tool function that handles all three tools.
- Test it to verify each tool runs correctly.
Create the function that runs tools
Claude will pick a tool name and generate its inputs. Your job is to write the function that takes those values and actually runs the tool.
- In agent.py, scroll to the bottom of the file, below the closing ] of the tools list.
- Add the execute_tool function by pasting this code below the tools list:
def execute_tool(tool_name, tool_input):
# Handle calculator tool
if tool_name == "calculator":
try:
result = eval(tool_input["expression"])
return f"Result: {result}"
except Exception as e:
return f"Error calculating: {e}"
# Handle date/time tool
elif tool_name == "get_datetime":
now = datetime.now()
return f"Current date and time: {now.strftime('%Y-%m-%d %H:%M:%S')}"
# Handle file reading tool
elif tool_name == "read_file":
try:
with open(tool_input["filename"], "r") as f:
return f.read()
except FileNotFoundError:
return f"Error: File '{tool_input['filename']}' not found."
# Fallback for unknown tools
else:
return f"Error: Unknown tool '{tool_name}'"
What does this code do?
- The function receives a tool_name (which tool Claude chose) and tool_input (the inputs Claude generated), then runs the matching tool.
- calculator uses Python's eval() to compute math expressions. This works for learning, but is not safe for production code because it can execute arbitrary Python.
- read_file includes a FileNotFoundError handler. Error handling matters here because Claude receives the error message and can use it to respond helpfully.
- The else fallback catches any tool name that doesn't match, returning an error message instead of crashing.
Why does the executor matter?
Claude decides WHAT to do (which tool to call, which inputs to provide). Your executor does the actual work. This separation is the core of every AI agent: the LLM reasons, your code acts.
In production, these tool handlers would call real APIs, query databases, or trigger workflows. The pattern stays the same.
- Save agent.py.
Before you run a test, what do you think will happen if you call execute_tool('calculator', {'expression': '2 + 2'})?
- Test the calculator tool by running this command in your terminal:
python -c "from agent import execute_tool; print(execute_tool('calculator', {'expression': '2 + 2'}))"
You should see Result: 4 in your terminal. Your executor is working.
- Now test the file reader by running this command:
python -c "from agent import execute_tool; print(execute_tool('read_file', {'filename': 'notes.txt'}))"
You should see the full contents of your notes.txt file printed in the terminal.
Seeing an error?
- If you see ModuleNotFoundError: No module named 'anthropic', the Anthropic SDK is not installed in the Python environment you're running from. Run pip install anthropic again.
- If you see an error about ANTHROPIC_API_KEY, the import also initializes the Anthropic client. Make sure your API key environment variable is still set in this terminal session.
- If you see FileNotFoundError for notes.txt, make sure your terminal is inside the ai-agent folder where both agent.py and notes.txt live.
Still stuck? Help me debug why my execute_tool function isn't working when I import it.
✔️ Awesome, I've got everything!
Great. Double check you've saved agent.py.
ⓧ I'd like to double check the full code
Your agent.py should now have these sections in order. Scroll through your file and confirm each one is present.
- Imports at the top: anthropic, json, and datetime.
- Client initialization: client = anthropic.Anthropic().
- The tools list with three tool schemas: calculator, get_datetime, and read_file.
- The execute_tool function at the bottom, with branches for all three tools and an else fallback.
Your tools can now execute. Next up, you'll build the agentic loop that lets Claude call these tools autonomously and keep going until the task is done.
Build the Agentic Loop
You have three tools defined and an executor that can run them. Right now, though, nothing actually calls those tools. Your agent needs a brain: the logic that sends a question to Claude, checks whether Claude wants to use a tool, runs it, and loops back until Claude has a complete answer.
This loop is called the agentic loop. It is the core pattern behind every AI assistant, copilot, and enterprise agent in production today. In this step, you will build it from scratch and run your agent for the first time.
In this step, get ready to:
- Build the run_agent function that implements the agentic while-loop.
- Add an interactive chat interface so you can talk to your agent in the terminal.
- Run your agent and watch it make its first autonomous tool call.
Create the core agent function
The run_agent function is the heart of your project. It takes a user message, sends it to Claude along with your tool definitions, and enters a loop that keeps running until Claude has a final answer.
- In agent.py, scroll to the bottom of the file, below the execute_tool function.
- Start building the run_agent function by adding this code:
def run_agent(user_message):
# Display the user's message
print(f"\nYou: {user_message}")
print("-" * 50)
# Start a fresh conversation with the user's question
messages = [{"role": "user", "content": user_message}]
# The agentic loop: keep calling Claude until it's done
while True:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
tools=tools,
messages=messages,
)
What does this code do?
This sets up the conversation and makes the first API call to Claude.
- messages is a list that accumulates the full conversation: the user's question, Claude's responses, and any tool results. Claude reads this entire list on every loop iteration to maintain context.
- client.messages.create() sends the conversation to Claude along with your tools list, so Claude knows what tools are available.
- while True creates the loop. Claude might need multiple tool calls to answer one question, so the loop keeps going until Claude is satisfied.
The function is not complete yet. Next, you will add the logic that decides what to do with Claude's response.
- Still inside the while True loop, add this code directly below the messages.create() call:
# Claude wants to use a tool
if response.stop_reason == "tool_use":
tool_results = []
for block in response.content:
if block.type == "tool_use":
tool_name = block.name
tool_input = block.input
print(f" 🔧 Using tool: {tool_name}({json.dumps(tool_input)})")
# Run the tool and collect the result
result = execute_tool(tool_name, tool_input)
print(f" 📋 Result: {result}")
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result,
})
# Add Claude's response and tool results to the conversation
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
# Claude is done - print the final answer
else:
for block in response.content:
if block.type == "text":
print(f"\nAgent: {block.text}")
break
What is the agentic loop pattern?
This is the core decision point. Claude's response includes a stop_reason that tells your code why Claude stopped generating.
- When stop_reason == "tool_use", Claude wants to call a tool. Your code runs the tool, appends the result to messages, and loops back so Claude can see the result.
- When stop_reason is anything else (like "end_turn"), Claude is done. Your code prints the final text answer and breaks out of the loop.
- Tool results get sent back as user messages containing "tool_result" objects with the matching tool_use_id. This is how Claude connects each result to the tool it requested.
- Save agent.py.
- Confirm there are no syntax errors by running this command:
python agent.py
The script should exit immediately with no output and no errors. That means the function is defined correctly.
Seeing a SyntaxError or IndentationError?
- Make sure the if response.stop_reason block is indented inside the while True loop (two levels of indentation from the function).
- Check that the else: is at the same indent level as the if response.stop_reason line.
- Verify that the break statement is inside the else block, not outside it.
Help me debug my run_agent function
Add the main chat loop
Your run_agent function handles a single question. Now you need an interactive loop that keeps asking for input so you can have a back-and-forth conversation with your agent.
- At the very bottom of agent.py, below the run_agent function, add the main entry point:
if __name__ == "__main__":
print("=" * 50)
print(" AI Agent with Tool Use")
print(" Type 'quit' to exit")
print("=" * 50)
# Interactive chat loop
while True:
user_input = input("\nYou: ").strip()
if user_input.lower() == "quit":
print("Goodbye!")
break
if user_input:
run_agent(user_input)
What does this code do?
- if __name__ == "__main__": ensures this code only runs when you execute the file directly, not when it is imported as a module.
- The while True loop reads your input and passes each question to run_agent(). Typing quit breaks out of the loop and ends the program.
- Save agent.py.
✔️ Awesome, I've got everything!
Great. Make sure you have saved the file before moving on.
ⓧ I'd like to double check the full code
Your agent.py file is now too long to show in one block. Scroll up and confirm these sections appear in order:
- Imports (anthropic, json, datetime) and client = anthropic.Anthropic() at the top.
- The tools list with three tool definitions: calculator, get_datetime, and read_file.
- The execute_tool(tool_name, tool_input) function with handlers for all three tools.
- The run_agent(user_message) function with the while True agentic loop you just added.
- The if __name__ == "__main__": block at the very bottom.
Run your agent for the first time
Your agent is complete. Before you run it, think about this: when you type "What time is it?", do you think Claude will answer from its own knowledge, or will it use one of your tools? Why?
- Start your agent by running this command:
python agent.py
You should see the welcome banner with the text AI Agent with Tool Use and a You: prompt waiting for your input.
- Type the following and press Enter:
What time is it right now?
Watch your terminal. You should see a line like 🔧 Using tool: get_datetime({}) followed by a result with the current date and time. Then Claude responds with a natural-language answer using that result.
Why did Claude use a tool instead of guessing?
Claude knows its training data has a cutoff date, so it cannot know the current time from memory. Your get_datetime tool description says "Gets the current date and time," so Claude chose it autonomously. This autonomous decision-making is what makes it an agent, not just a chatbot.
- Type quit and press Enter to exit the agent.
Agent not responding or showing an error?
- If you see AuthenticationError, your ANTHROPIC_API_KEY environment variable is not set or is incorrect. Set it again in the same terminal session you are using to run the agent.
- If you see NameError, check that run_agent is defined above the if __name__ == "__main__": block, not below it.
- If the agent hangs for more than 30 seconds, Claude may be experiencing high traffic. Press Ctrl+C to cancel and try running the agent again.
Help me debug my AI agent
Your agent is alive and making autonomous decisions. Next up, you will put it through its paces with multi-tool questions and edge cases to see just how smart it really is.
Test Your Agent
You've built a complete AI agent with three tools, an executor, and the agentic loop that ties everything together. Now it's time to see it in action.
In this step, you'll run the agent and put it through a range of tests. You'll watch Claude autonomously decide which tools to call and how to combine their results.
In this step, get ready to:
- Run the agent and test each tool individually.
- Observe multi-tool chaining and autonomous decision-making.
- Test error handling with edge cases.
Start the agent and test individual tools
Each of your three tools handles a different type of question. Let's start the agent and try a question that targets each tool one at a time.
- In your terminal, make sure you're inside the ai-agent folder, then start the agent by running:
python agent.py
You should see a welcome banner with the text AI Agent with Tool Use and a You: prompt waiting for your input.
Seeing an error when you run the command?
If you see ModuleNotFoundError: No module named 'anthropic', make sure you installed the SDK with pip install anthropic in the same terminal session.
If you see an authentication error, your ANTHROPIC_API_KEY environment variable may not be set. Re-run the export command from Step 1.
Still stuck? Help me debug my agent.py startup error.
- Test the calculator tool by typing this query at the You: prompt:
What's 18% tip on a $85.50 dinner?
Watch the output. You should see a line starting with Using tool: calculator followed by a Result: line with the calculated tip, and then the agent's final answer combining everything into a sentence.
- Now test the get_datetime tool by typing:
What time is it right now?
This time you should see Using tool: get_datetime and the current date and time in the result.
- Test the read_file tool by typing:
What are my meeting notes?
You should see Using tool: read_file with the filename notes.txt, followed by the contents of your meeting notes in the result.
How does Claude know which file to read?
You never told Claude the filename. It inferred notes.txt from the context of your question. This is the power of the tool description field you defined earlier. Claude reads those descriptions to decide both WHICH tool to use and WHAT inputs to generate.
Watch multi-tool chaining in action
So far, each question only needed one tool. The real power of an agent shows up when a single question requires multiple tools working together.
- Before you type the next query, predict: how many tools do you think Claude will use to answer a question about calculating a percentage of a budget that lives in a file?
- Type this query:
What's 20% of the remaining budget in my notes file?
Claude uses BOTH read_file and calculator in sequence. It first reads notes.txt to find the budget ($5,000), then calculates 20% of that amount.
What is tool chaining?
This is the agentic loop at work. Claude's first response has a stop_reason of tool_use, so your while True loop executes the tool, sends the result back, and Claude decides it needs ANOTHER tool. The loop continues until Claude has all the information it needs to answer.
- Now try a question that needs no tools at all:
What's the capital of France?
No tool lines appear this time. Claude answers directly from its own knowledge because no tool was needed.
What makes this an agent?
A simple chatbot follows a fixed script. An agent makes autonomous decisions about what to do next. Your agent reads each question, decides whether tools are needed, picks the right ones, chains them if necessary, and stops when it has a complete answer.
This autonomous decision-making loop is the exact same architecture behind every production AI assistant, copilot, and enterprise agent.
Test error handling and edge cases
A good agent handles failures gracefully. What happens when a tool returns an error instead of a result?
- Before you type the next query, predict: what do you think will happen when Claude tries to read a file that doesn't exist?
- Type this query:
Read the file called secret.txt
Claude calls read_file with secret.txt, and the result shows the error message from your execute_tool function. Claude then uses that error to give the user a helpful response instead of crashing.
Why does error handling matter here?
Your execute_tool function returns an error string instead of raising an exception. Claude receives that error string as a tool result and decides what to do with it. In production, this pattern lets agents recover from failures, try alternative approaches, or explain the problem to the user.
- Test one more multi-tool query to see a different combination:
What's the square root of 144, and what day of the week is it?
Claude uses both calculator and get_datetime to answer. It may even call them in a single round, since neither depends on the other's result.
- When you're done experimenting, type quit to exit the agent.
What did you just prove?
You've seen your agent autonomously select individual tools, chain multiple tools together, skip tools entirely when they aren't needed, and recover gracefully from errors. This is the foundational architecture behind every AI assistant in production today.
Secret mission
Give Your Agent Superpowers
Your agent can read files and crunch numbers, but it can't remember anything you tell it. Transform it from a read-only assistant into a read-write one by giving it a personality and a brand new note-taking tool.
Clean Up Your Resources
Clean Up Your Resources
This project runs entirely locally, so there are no ongoing costs. The only charges were the Anthropic API calls you made while testing your agent.
Decide whether to keep your resources as they are, pause them to come back later, or delete them entirely.
Resources you used:
- ai-agent folder on your Desktop (containing agent.py, notes.txt, and agent_notes.txt).
- Anthropic Python SDK installed via pip.
- ANTHROPIC_API_KEY environment variable (session-only, clears when you close your terminal).
Keep everything running
No action needed. Choose this if you want to keep experimenting with your agent or adding new tools.
- Your ai-agent folder stays on your Desktop, ready for you to open and run anytime.
- Your ANTHROPIC_API_KEY environment variable is session-only. You will need to set it again each time you open a new terminal.
- The Anthropic Python SDK stays installed in your Python environment. No ongoing cost from having it installed.
Pause - I'll come back to this later
Close any terminals running the agent to free up memory. Your project files stay on disk so you can pick up where you left off.
- Close the terminal where you ran agent.py. This also clears your ANTHROPIC_API_KEY environment variable.
- When you come back, open a new terminal, re-set your ANTHROPIC_API_KEY environment variable, and run python agent.py again.
Delete - I don't want to use this again
Remove all project files and the installed SDK to start fresh.
- Delete the ai-agent folder. On macOS/Linux, run:
rm -rf ~/Desktop/ai-agent
- On Windows, run this in Command Prompt:
rmdir /s /q %USERPROFILE%\Desktop\ai-agent
- Uninstall the Anthropic Python SDK by running:
pip uninstall anthropic
- When prompted, press y to confirm the uninstall.
- Close your terminal to clear the ANTHROPIC_API_KEY environment variable. Since it was set for the session only, it disappears automatically.
Nice Work!
Nice Work!
You just built the foundational architecture that powers every AI assistant, copilot, and enterprise agent in production today. From a blank Python file to a fully autonomous agent that decides which tools to call, executes them, and loops until the job is done.
You've learned how to:
- Built a working AI agent with the agentic loop pattern, the core architecture behind autonomous AI systems that keeps running until the task is complete.
- Defined tool schemas using JSON Schema and built a tool executor that bridges Claude's decisions with real-world actions like math, file reading, and date lookups.
- Experienced Claude's autonomous decision-making firsthand, watching it choose tools, handle errors gracefully, and chain multiple tool calls together to answer complex questions.
- Added a system prompt and a save_note write tool in the Secret Mission, turning your read-only agent into a full read-write assistant.
Ready to quiz yourself?