How to Build an AI Agent with Claude: A Simple Step-by-Step Guide

AI assistants have become useful for answering questions, writing content, explaining code, and helping people complete everyday tasks. However, there is a difference between an assistant that simply responds to a question and an AI agent that can actually perform work.

Imagine building an application that receives a customer question, checks an order database, retrieves the order information, and then prepares a helpful response. A normal chatbot might explain how to check an order. An AI agent can use the tools you provide to look up the actual order and return the result.

That ability to understand a request, choose an appropriate action, use external tools, and work toward a goal is what makes AI agents interesting.

Claude, developed by Anthropic, provides an API that developers can use to build these kinds of applications. With its tool-use capabilities, Claude can decide when it needs to call a function, send structured arguments to your application, receive the result, and continue working until it can provide a response.

How to Build an AI Agent with Claude: A Simple Step-by-Step Guide

You do not need to train your own language model or build a complicated machine-learning system to get started. You can create a practical AI agent using Python, the Anthropic SDK, a clear system prompt, and a few functions that perform useful tasks.

In this tutorial, we will build a small task-management AI agent with Claude. It will understand natural-language requests, create tasks, list existing tasks, and mark tasks as completed. Along the way, you will learn how the agent works, how to connect tools, how to test its behavior, and what you should consider before using it in a real application.

1. What Is an AI Agent?

An AI agent is a software application that uses an AI model to make decisions and perform actions toward a particular goal.

A traditional application usually follows instructions written directly by a developer. For example, if a user clicks a button, the application executes the function connected to that button.

An AI agent works differently. The developer provides the available tools and explains what each tool does. The AI model then interprets the user's request and decides which tool, if any, should be used.

Consider this request:

User: Create a task called "Prepare the project report"
and mark it as high priority.

A task-management agent might follow this process:

  1. Receive the user's request.
  2. Understand that the user wants to create a task.
  3. Identify the appropriate task-creation function.
  4. Generate the required function arguments.
  5. Ask the application to execute the function.
  6. Receive confirmation that the task was created.
  7. Explain the result to the user.

The language model does not directly create a database record by itself. It requests that your application perform the operation. Your application executes the function and sends the result back to Claude.

This distinction is important because it allows developers to control exactly what an agent can access and what actions it can perform.

How an AI agent differs from a chatbot

Feature Traditional chatbot AI agent
Main purpose Answer questions Complete tasks and answer questions
External tools Usually limited Can use connected tools
Decision-making Primarily generates responses Chooses actions based on the request
Data access Often limited to provided context Can retrieve data through application functions
Task execution Usually explains how to do something Can perform permitted operations

Not every application needs an agent. If your application only needs to answer a few fixed questions, a normal API call might be enough. Agents become useful when the application must choose between different actions or work with external systems.

2. Why Use Claude to Build an AI Agent?

Claude is a useful choice for agent development because Anthropic provides a Messages API with structured tool-use functionality.

Instead of asking the model to invent a function call in ordinary text, you can define tools with names, descriptions, and JSON input schemas. Claude can then return a structured tool request that your application understands.

For example, you might define these tools:

  • create_task: Creates a new task.
  • list_tasks: Returns the user's existing tasks.
  • complete_task: Marks a task as completed.

Claude decides which function best matches the user's request. Your Python application remains responsible for executing that function.

Technologies used in this tutorial

Technology Purpose
Python Application logic and tool execution
Claude API Understanding requests and choosing tools
Anthropic Python SDK Communicating with Claude
python-dotenv Loading environment variables
JSON Representing structured tool arguments
Python dictionaries Storing tasks in our demonstration

We will use the standard Messages API rather than introducing an agent framework. This makes it easier to understand what happens during each step.

3. What You Need Before Getting Started

Before writing code, prepare a few basic development tools.

Python installation

Install a supported Python 3 version on your computer. Python 3.10 or later is a sensible starting point for this tutorial.

Check whether Python is available by opening your terminal and running:

python --version

On some systems, particularly macOS and Linux, you may need to use:

python3 --version

An Anthropic API account

You need access to the Claude API through the Anthropic developer platform. Create an account, configure billing or available credits as required, and generate an API key.

Keep this key private. It gives your application access to your API account, so it should never be placed in public source code or committed to a Git repository.

A code editor

You can use Visual Studio Code, PyCharm, or any editor that supports Python. You should also have access to a terminal for installing packages and running the application.

Developer Note: Claude's consumer chat interface and the Claude API are different products. Having access to a Claude chat subscription does not automatically mean you have API credentials or API usage credits.

4. Setting Up the Development Environment

Now we can create the project that will contain our AI agent.

First, create a directory:

mkdir claude-ai-agent
cd claude-ai-agent

Create a Python virtual environment. This keeps the packages used by this project separate from other Python applications on your computer.

On Windows:

python -m venv venv
venv\Scripts\activate

On macOS or Linux:

python3 -m venv venv
source venv/bin/activate

Once the environment is active, install the required packages:

pip install anthropic python-dotenv

The anthropic package is Anthropic's official Python SDK. It provides a convenient interface for sending requests to Claude.

The python-dotenv package allows us to load configuration values from a local environment file.

Create the project files

Our project will have a simple structure:

claude-ai-agent/
│
├── venv/
├── .env
├── .gitignore
├── requirements.txt
└── agent.py

Create the dependency file:

pip freeze > requirements.txt

For a production project, you may prefer to maintain a deliberately pinned dependency list rather than recording every installed package in the environment.

Next, create a .env file in the project directory.

ANTHROPIC_API_KEY=your_anthropic_api_key_here
CLAUDE_MODEL=claude-sonnet-5-5

Replace the placeholder API key with your actual key.

We are using an explicit model setting so that changing models does not require editing the main application logic. The model identifier in this example should be checked against the current Anthropic model catalogue when setting up a project.

Create a .gitignore file:

venv/
.env
__pycache__/
*.pyc
.pytest_cache/

This prevents local secrets, virtual-environment files, and temporary Python files from being accidentally added to source control.

5. Understanding How Claude Tool Use Works

Before implementing the agent, it helps to understand the communication process.

Claude tool use follows a request-and-response cycle.

  1. Your application sends the user's message and available tool definitions to Claude.
  2. Claude decides whether a tool is necessary.
  3. If a tool is needed, Claude returns a structured tool_use block.
  4. Your application reads the requested tool name and arguments.
  5. Your application executes the corresponding Python function.
  6. The function result is sent back to Claude in a tool_result block.
  7. Claude processes the result and either requests another tool or produces a final response.

This repeated process is commonly called the agentic loop.

One detail is worth remembering: Claude does not automatically execute your custom Python functions. Your application must handle the tool requests and execute the corresponding code.

For example, when Claude requests create_task, your application should check that the function exists, validate the arguments, execute it, and return the result.

6. Building the First AI Agent

We will create a task-management assistant. The agent will support three operations:

  • Create a task with a title and priority.
  • Display all existing tasks.
  • Mark a task as completed.

For this first version, tasks will be stored in a Python dictionary. This is enough to demonstrate the agentic loop without requiring a database installation.

Important: The dictionary is temporary storage. All tasks disappear when the application exits. A real application should use persistent storage such as PostgreSQL or SQLite.

Step 1: Import the required packages

Create or open agent.py and add the following imports:

import os
import json
import uuid

from dotenv import load_dotenv
from anthropic import Anthropic

Here is what each import does:

  • os reads environment variables.
  • json converts structured data into JSON strings.
  • uuid generates unique identifiers for tasks.
  • load_dotenv loads settings from the local environment file.
  • Anthropic creates the API client.

Step 2: Configure the Claude API client

Load the environment variables and initialize the API client.

load_dotenv()

api_key = os.getenv("ANTHROPIC_API_KEY")
MODEL = os.getenv("CLAUDE_MODEL")

if not api_key:
raise ValueError(
"ANTHROPIC_API_KEY is missing from the environment."
)

if not MODEL:
raise ValueError(
"CLAUDE_MODEL is missing from the environment."
)

client = Anthropic(api_key=api_key)

The SDK uses the API key to authenticate requests. Reading it from an environment variable means you can change credentials without modifying your source code.

The model name is also loaded from the environment, making it easier to test another available Claude model later.

Step 3: Create the task storage

We need somewhere to store tasks while the application is running.

tasks = {}

This dictionary will contain task identifiers as keys and task information as values.

For example, a task might look like this:

{
"id": "task-123",
"title": "Prepare the project report",
"priority": "high",
"completed": false
}

Step 4: Implement the create_task function

This function creates a new task and adds it to our dictionary.

def create_task(title: str, priority: str = "medium") -> dict:
"""Create a task with a title and priority."""

if not title or not title.strip():
return {
"success": False,
"error": "Task title cannot be empty."
}

allowed_priorities = ["low", "medium", "high"]

if priority not in allowed_priorities:
return {
"success": False,
"error": "Priority must be low, medium, or high."
}

task_id = str(uuid.uuid4())

task = {
"id": task_id,
"title": title.strip(),
"priority": priority,
"completed": False
}

tasks[task_id] = task

return {
"success": True,
"task": task
}

Notice that the function performs its own validation. Even though Claude is expected to generate valid arguments, we should never rely entirely on the model to protect our application.

The function generates a unique ID, creates the task object, stores it, and returns a confirmation.

Step 5: Implement the list_tasks function

The next function returns the tasks currently stored in memory.

def list_tasks() -> dict:
"""Return all tasks."""

return {
"success": True,
"tasks": list(tasks.values()),
"total": len(tasks)
}

We convert the dictionary values into a list because it is easier to return and process as structured JSON data.

Step 6: Implement the complete_task function

Users should also be able to mark tasks as completed.

def complete_task(task_id: str) -> dict:
"""Mark an existing task as completed."""

if task_id not in tasks:
return {
"success": False,
"error": "Task not found."
}

tasks[task_id]["completed"] = True

return {
"success": True,
"task": tasks[task_id]
}

This function checks whether the requested task exists before updating it. If the identifier is incorrect, it returns a useful error instead of crashing.

7. Defining Tools for Claude

We now have three working Python functions, but Claude does not know they exist.

We need to describe these functions using tool definitions. Each definition contains a name, a description, and an input schema.

The schema tells Claude which arguments are accepted and what data types they should have.

Add the following code to agent.py:

tools = [
{
"name": "create_task",
"description": (
"Create a new task. Use this when the user "
"wants to add something to their task list."
),
"input_schema": {
"type": "object",
"properties": {
"title": {
"type": "string",
"description": "The task title."
},
"priority": {
"type": "string",
"enum": ["low", "medium", "high"],
"description": "The task priority."
}
},
"required": ["title", "priority"]
}
},
{
"name": "list_tasks",
"description": (
"Return all tasks currently stored in the task list."
),
"input_schema": {
"type": "object",
"properties": {},
"required": []
}
},
{
"name": "complete_task",
"description": (
"Mark an existing task as completed using its task ID."
),
"input_schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "The unique ID of the task."
}
},
"required": ["task_id"]
}
}
]

Descriptions deserve more attention than many beginners give them.

Claude uses the tool name, description, and schema to understand when a function is appropriate. A vague description can lead to unnecessary or incorrect tool calls.

For example, compare these two descriptions:

"Manage tasks."

"Create a new task with a title and priority.
Use this function when the user asks to add
a new item to their task list."

The second description gives the model a much clearer idea of what the function does.

Practical Tip: Give every tool one clear responsibility. Avoid creating a single function called manage_everything that accepts dozens of unrelated instructions.

8. Connecting Claude to Your Python Functions

This is where our application starts behaving like an actual AI agent.

We need a function that receives Claude's tool request, finds the corresponding Python function, and executes it.

First, create a tool registry:

tool_functions = {
"create_task": create_task,
"list_tasks": list_tasks,
"complete_task": complete_task
}

A registry provides a controlled mapping between the tool names Claude can request and the functions your application is allowed to execute.

Now create a helper that handles tool execution:

def execute_tool(tool_name: str, tool_input: dict) -> dict:
"""Execute an approved tool."""

function = tool_functions.get(tool_name)

if function is None:
return {
"success": False,
"error": "Unknown tool requested."
}

try:
result = function(**tool_input)
return result

except TypeError:
return {
"success": False,
"error": "Invalid tool arguments."
}

except Exception:
return {
"success": False,
"error": "The requested operation failed."
}

The registry is particularly important from a security perspective. It ensures that Claude can only request functions that you have deliberately made available.

We also catch errors so that a malformed tool request does not immediately terminate the entire application.

9. Building the Agentic Loop

Now comes the most important part of the implementation.

When Claude requests a tool, the application must execute it and send the result back. Claude may then request another tool or return a final answer.

We will implement that process manually so you can understand each stage.

Add the following function:

SYSTEM_PROMPT = """
You are a helpful task management assistant.

You can create tasks, list tasks, and complete tasks.

Rules:
1. Use the available tools when the user requests a task operation.
2. Never claim that a task was created unless the tool confirms it.
3. Never invent task IDs or task information.
4. If a required detail is missing, ask the user.
5. Explain errors clearly.
6. Keep responses concise and helpful.
"""


def run_agent(user_message: str) -> str:
"""Run the Claude agent for one user request."""

messages = [
{
"role": "user",
"content": user_message
}
]

max_iterations = 10

for _ in range(max_iterations):

response = client.messages.create(
model=MODEL,
max_tokens=2048,
system=SYSTEM_PROMPT,
tools=tools,
messages=messages
)

# Save Claude's complete response.
messages.append({
"role": "assistant",
"content": response.content
})

# Stop when Claude has completed its response.
if response.stop_reason != "tool_use":
text_blocks = [
block.text
for block in response.content
if block.type == "text"
]

return "\n".join(text_blocks)

# Execute every requested tool.
tool_results = []

for block in response.content:

if block.type != "tool_use":
continue

result = execute_tool(
block.name,
block.input
)

tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result)
})

# Return tool results to Claude.
messages.append({
"role": "user",
"content": tool_results
})

return (
"The agent reached its maximum number "
"of tool iterations. Please try again."
)

Let's understand what happens inside this function.

Sending the initial request

The application creates a message containing the user's request and sends it to Claude using client.messages.create().

The request includes four important elements:

  • model identifies the Claude model.
  • max_tokens controls the maximum response generation.
  • system provides instructions about the agent's role.
  • tools describes the functions Claude can request.

Checking the stop reason

After receiving a response, the application checks response.stop_reason.

If the value is tool_use, Claude wants the application to execute one or more tools.

If it is not tool_use, the agent has finished the current response, so we collect its text blocks and return the answer.

Executing requested functions

Every tool request includes a name, input arguments, and a unique tool-use ID.

Our application uses the name to find the corresponding function in the registry. It then executes that function with the supplied arguments.

Returning the result

The application sends the result back to Claude using a tool_result block.

The tool_use_id must match the ID of the original tool request. This allows Claude to associate the result with the correct operation.

Claude can then use the returned information to produce a meaningful response.

Developer Note: Tool results are sent in a subsequent user-role message because the Messages API represents tool results that way. This does not mean the application is pretending that the user executed the operation.

10. Adding a Simple Command-Line Interface

Our agent can now understand requests and execute tools, but we need a way to interact with it.

Add the following code at the bottom of agent.py:

def main():
print("Claude Task Management Agent")
print("Type 'exit' to quit.\n")

while True:

user_input = input("You: ").strip()

if user_input.lower() in ["exit", "quit"]:
print("Goodbye!")
break

if not user_input:
continue

try:
response = run_agent(user_input)
print(f"\nAgent: {response}\n")

except Exception as error:
print(
"\nAn error occurred while processing "
"your request."
)
print(f"Details: {error}\n")


if __name__ == "__main__":
main()

This creates a simple interactive terminal application. Users can enter requests continuously without restarting the program after every message.

11. Running Your Claude AI Agent

We have now connected the API client, task functions, tool definitions, and agentic loop.

Run the application from your project directory:

python agent.py

You should see something similar to this:

Claude Task Management Agent
Type 'exit' to quit.

You:

Try creating a task:

You: Create a high-priority task called
Prepare the project report.

Agent: Your task has been created successfully.
The priority is high.

Task ID: 2e4c8d7a-1234-4567-8901-example

The displayed task ID is illustrative. Your application generates a different UUID when you run it.

Now list the tasks:

You: Show me all my tasks.

Agent: Here are your current tasks:

1. Prepare the project report
Priority: High
Status: Pending

Finally, ask the agent to complete a task. Provide the actual ID returned by your application:

You: Mark task 2e4c8d7a-1234-4567-8901-example
as completed.

Claude can request the complete_task function, your application updates the dictionary, and Claude receives confirmation.

12. Making a Direct API Request with cURL

Although the Python SDK is convenient, it is useful to understand what a direct API request looks like.

Anthropic exposes the Messages API through the /v1/messages endpoint.

Here is a basic request using cURL:

curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data '{
"model": "claude-sonnet-5-5",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "Explain what an AI agent is in simple terms."
}
]
}'

This example sends a simple text request. It does not perform tool execution because we have not supplied any tools.

For a request that allows Claude to call a custom function, the JSON body can include a tool definition.

curl https://api.anthropic.com/v1/messages \
--header "x-api-key: $ANTHROPIC_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--data '{
"model": "claude-sonnet-5-5",
"max_tokens": 1024,
"tools": [
{
"name": "create_task",
"description": "Create a task with a title.",
"input_schema": {
"type": "object",
"properties": {
"title": {
"type": "string"
}
},
"required": ["title"]
}
}
],
"messages": [
{
"role": "user",
"content": "Create a task called Review the website."
}
]
}'

If Claude chooses the tool, the response contains a structured tool-use block. A client application must then execute the requested function and submit its result in a follow-up request.

Remember that the tool definition does not provide the implementation. The Python application still needs a matching function and a safe execution mechanism.

13. Integrating External APIs with Claude

Our example uses local Python functions, but the same approach works with external services.

Suppose you want to create an AI agent that retrieves weather information. You could define a weather tool and connect it to a legitimate weather service API.

The architecture would look like this:

User request
|
v
Claude AI model
|
v
Weather tool request
|
v
Python application
|
v
External weather API
|
v
Weather data
|
v
Claude generates final response
|
v
User

The important point is that Claude chooses when to request the weather function, while your application controls the actual HTTP request.

For example, a simplified Python function using the requests library might look like this:

import os
import requests


def get_weather(city: str) -> dict:
"""Retrieve weather data from a configured weather service."""

api_url = os.getenv("WEATHER_API_URL")
api_key = os.getenv("WEATHER_API_KEY")

if not api_url or not api_key:
return {
"success": False,
"error": "Weather service is not configured."
}

try:
response = requests.get(
api_url,
params={
"city": city,
"apikey": api_key
},
timeout=10
)

response.raise_for_status()

return {
"success": True,
"weather": response.json()
}

except requests.RequestException:
return {
"success": False,
"error": "Unable to retrieve weather information."
}

This is an integration pattern rather than a complete integration with a particular weather provider. The actual URL, authentication parameter, and response fields must come from the provider's official API documentation.

To use it in the agent, you would also need to add a matching tool schema and register get_weather in the tool registry.

The same approach can connect Claude to:

  • Customer relationship management systems.
  • Payment and billing services.
  • Inventory management applications.
  • Internal company databases.
  • Project management platforms.
  • Document management services.

14. Real-World Use Cases for Claude AI Agents

Once you understand how tool use works, you can build agents for many practical situations.

Customer support agent

A customer support agent can receive questions, search an order database, retrieve shipping information, and prepare a response.

For example, a customer might ask, "Where is my order?" The agent could identify the order lookup tool, retrieve the relevant record, and explain the latest status.

For sensitive actions such as refunds, cancellations, or changes to account details, require authorization and human approval where appropriate.

Personal productivity agent

A productivity agent can organize tasks, prepare meeting summaries, create reminders, and retrieve calendar information.

Our task-management example is a basic version of this idea. You can extend it by connecting a calendar API or a persistent database.

Research assistant

A research agent can retrieve documents, search approved information sources, extract relevant information, and summarize findings.

For reliable results, it should preserve source references and distinguish retrieved facts from its own interpretation.

E-commerce assistant

An e-commerce agent can check product availability, retrieve order details, explain product specifications, and help users find suitable products.

It should not complete purchases, issue refunds, or change account information without the appropriate user confirmation and permission checks.

Developer assistant

A developer-focused agent can search project documentation, inspect approved code repositories, run controlled tests, and explain errors.

Tools should be restricted to the intended repository and execution environment. Avoid giving a general-purpose model unrestricted access to a developer's computer or production infrastructure.

15. Testing Your AI Agent

Getting a response from Claude does not mean your agent is working correctly. You need to test both the language-model behavior and the actual Python functions.

Start with basic scenarios.

Test Expected behavior
Create a task Creates a task with the correct title.
Create a high-priority task Stores high as the priority.
List tasks Returns the stored tasks.
Complete an existing task Changes its completed status.
Complete a missing task Returns a useful error.
Submit an empty title Rejects the invalid task.
Ask an unrelated question Responds without unnecessarily calling a task tool.

Testing the Python functions independently

You should test the business logic separately from Claude. This makes it easier to find problems without paying for an API request every time you run a test.

Create a file called test_agent.py:

from agent import (
tasks,
create_task,
list_tasks,
complete_task
)


def test_create_task():
tasks.clear()

result = create_task(
"Prepare report",
"high"
)

assert result["success"] is True
assert result["task"]["title"] == "Prepare report"
assert result["task"]["priority"] == "high"


def test_list_tasks():
tasks.clear()

create_task("Write documentation")

result = list_tasks()

assert result["success"] is True
assert result["total"] == 1


def test_complete_task():
tasks.clear()

result = create_task("Finish project")

task_id = result["task"]["id"]

completed = complete_task(task_id)

assert completed["success"] is True
assert completed["task"]["completed"] is True


def test_missing_task():
result = complete_task("missing-task-id")

assert result["success"] is False

Install pytest:

pip install pytest

Run the tests:

pytest -v

These tests verify the main task operations without involving the Claude API.

Testing Claude's decisions

You should also test whether Claude chooses the right tool for different requests.

For example, test variations of the same intention:

  • "Add a task to prepare the presentation."
  • "I need to remember to prepare the presentation."
  • "Can you put presentation preparation on my task list?"

All three requests should lead to an appropriate task-creation operation.

Also test ambiguous requests. If someone says, "Complete my task," without identifying which task, the agent should ask for clarification rather than inventing an identifier.

16. Common Problems and How to Fix Them

Invalid API key

If Claude returns an authentication error, first check that the API key is correct and that your environment variables are loading properly.

Verify that the key exists without printing its actual value:

import os
from dotenv import load_dotenv

load_dotenv()

print(
"API key configured:",
bool(os.getenv("ANTHROPIC_API_KEY"))
)

Model not found

Model identifiers can change as new models become available and older models are retired.

Check the official Claude model overview and confirm that the identifier in your environment file is currently available to your account.

You can also use the Models API to retrieve available model identifiers rather than permanently relying on an outdated example.

Claude does not call a tool

This can happen when the tool description is unclear or when the user's request does not obviously require the function.

Improve the tool description and make its intended use explicit. If you need to enforce tool selection in a particular workflow, review Anthropic's tool_choice options.

Do not force tool calls for requests that do not require them.

Tool arguments are invalid

Check the input schema, required fields, accepted data types, and Python function signature.

For example, if your function expects task_id, your schema should use exactly the same argument name.

API rate limits

Applications can encounter rate limits when they send too many requests within a short period.

Use controlled retries with exponential backoff for temporary rate-limit and server errors. Avoid retrying invalid requests indefinitely.

Agent enters a repeated tool loop

An agent may sometimes keep requesting tools without reaching a useful conclusion.

Our example limits the number of iterations to ten. This is a basic safeguard. For more advanced applications, track the number of tool calls, request cost, execution time, and repeated operations.

17. Security Best Practices

Security becomes especially important when an AI agent can access databases, files, external APIs, or user accounts.

A poorly designed agent may perform actions that the user did not intend or expose information that should remain private.

Protect API credentials

Store API keys in environment variables or a dedicated secrets-management service.

Never place API credentials directly in frontend JavaScript, public repositories, screenshots, or client-side application configuration.

Validate every tool argument

Tool schemas help Claude produce structured arguments, but they are not a replacement for application-side validation.

Validate all inputs before using them. Check string lengths, allowed values, identifiers, permissions, and other business rules.

Use least-privilege permissions

Only expose the functions the agent actually needs.

If an assistant only needs to read customer orders, do not give it unrestricted database write access.

Separate read operations from write operations and restrict access to the minimum required resources.

Require confirmation for important actions

Actions such as deleting records, transferring money, changing account permissions, or sending external messages should have additional safeguards.

A useful pattern is to let the agent prepare an action first and ask the user for confirmation before the application executes it.

Watch for prompt injection

Prompt injection occurs when untrusted content attempts to manipulate the model's instructions.

For example, an agent that reads an email might encounter text telling it to ignore its original instructions and reveal private information.

Never treat instructions found in external documents, emails, websites, or tool outputs as automatically trustworthy.

Enforce permissions in application code rather than relying on the system prompt to prevent unauthorized operations.

Protect personal information

Only send information to the model that is necessary for the task. Avoid placing passwords, payment credentials, private tokens, or unnecessary personal information in prompts and tool results.

Establish clear retention, access-control, and logging policies for user data.

Security Warning: An AI agent should never be treated as a trusted authorization system. Claude can recommend an action, but your backend must decide whether that action is permitted.

18. Improving the Agent for Real Applications

The current project is a working demonstration, but a production application needs more than a few Python functions.

Use a persistent database

Our dictionary loses all information when the process stops. A database solves this problem.

For a small application, SQLite is a reasonable starting point. For a multi-user application, PostgreSQL is often a better choice.

A basic task table might contain:

CREATE TABLE tasks (
id UUID PRIMARY KEY,
user_id UUID NOT NULL,
title TEXT NOT NULL,
priority VARCHAR(20) NOT NULL,
completed BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

The user_id column is particularly important. It allows the backend to associate tasks with the correct account.

Every query should enforce ownership. Never allow the model to choose arbitrary user IDs and use them directly in database operations.

Add conversation history

Our current agent creates a new message list for every request. This means it does not remember previous messages in the same conversation.

For example, if a user says:

User: Create a task called Finish the homepage.

User: Make that task high priority.

The second request requires context about the task created in the first request.

You can support this by storing conversation history on your application server and including the relevant messages in subsequent API requests.

Store conversations separately for each authenticated user and conversation session. Apply retention limits and context-management strategies so that message history does not grow indefinitely.

Add logging and monitoring

Logging makes it easier to understand what happened when an agent produces an unexpected result.

Useful information includes:

  • Request timestamps.
  • Conversation or request identifiers.
  • Tool names and execution durations.
  • Success and failure counts.
  • API usage and token consumption.
  • Application and API error categories.

Avoid recording API keys, passwords, sensitive prompts, or unnecessary personal data in application logs.

Introduce human approval

For sensitive workflows, create an approval stage between tool selection and execution.

For example, an agent could prepare a task deletion request, display the task details, and wait for the user to approve it. Only after approval would the backend execute the operation.

Consider using the SDK Tool Runner

Our manual loop is useful for learning, but Anthropic also provides a tool runner in its SDKs.

The tool runner can handle much of the repetitive work involved in processing tool requests, returning results, and maintaining the request cycle.

It is worth considering when you want less manual orchestration. However, a manual loop can still be preferable when you need detailed control over approval steps, logging, conditional execution, and message-history changes.

Check the official SDK documentation for the current tool-runner availability and beta status before adopting it.

19. Advanced Improvements to Explore

After the basic agent works reliably, you can gradually introduce more advanced capabilities.

Connect multiple services

Instead of limiting the agent to task management, connect it to approved services such as calendars, email systems, project boards, and internal knowledge bases.

Keep each integration in its own module. This makes the code easier to maintain and allows you to test integrations independently.

Use retrieval-augmented generation

Retrieval-augmented generation, commonly called RAG, allows an application to retrieve relevant information from an external knowledge source and include it in the model's context.

For example, a company support agent might search internal product documentation before answering a customer question.

A typical RAG workflow includes document collection, text extraction, chunking, embedding generation, vector storage, retrieval, and answer generation.

The model should receive relevant source material rather than being expected to remember every internal company document.

Introduce structured outputs

When an application needs predictable response formats, structured outputs can help enforce a defined output schema.

For example, a classification agent might return a category, confidence value, and short explanation in a predefined structure.

This is useful when another part of your application needs to process the model's output automatically.

Use Model Context Protocol integrations

The Model Context Protocol, or MCP, provides a standardized way to connect AI applications with external tools and resources.

It can be useful when you want to integrate several existing services without designing every connection from scratch.

Anthropic documents MCP connectors and related integration approaches in its developer documentation. When using external MCP servers, review their permissions and security requirements carefully.

Build a web interface

Once the backend works, you can expose it through a web application.

For example, FastAPI can provide HTTP endpoints while a frontend built with React or another framework provides the chat interface.

A simple application architecture might look like this:

Frontend
|
v
Backend API
|
v
Authentication and authorization
|
v
Claude agent service
|
+------ Task tools
|
+------ Database tools
|
+------ External API tools
|
v
Database and external services

Keep the Anthropic API key on the backend. The browser should communicate with your own application server rather than calling the Anthropic API with a private server credential.

20. Understanding API Costs and Performance

Every API request has a cost determined by the selected model and the amount of input and output processed.

Agentic workflows can require multiple API requests because Claude may need to call a tool, receive its result, and then generate a final response.

For example, a request that requires one tool call generally involves an initial model request followed by another request containing the tool result.

Adding more tools, longer conversation histories, and larger tool outputs can increase token consumption.

To manage costs:

  • Choose a model appropriate for the complexity of the task.
  • Keep tool descriptions clear and reasonably short.
  • Return only the information the model needs from each tool.
  • Limit unnecessary tool calls.
  • Set maximum iteration limits.
  • Monitor input and output token usage.
  • Use prompt caching when appropriate and supported.

Anthropic provides model-specific pricing information in its official documentation. Pricing can change, so check the current pricing page rather than relying on figures copied from an older tutorial.

21. Frequently Asked Questions

Can beginners build an AI agent with Claude?

Yes. You can build a basic AI agent with Python and the Claude API without training a machine-learning model. Understanding functions, API requests, JSON, and basic Python programming is enough to start.

Do I need to train Claude myself?

No. Claude is an existing language model that you access through an API. You provide instructions, tools, and application logic. You do not need to train a new model for the task-management example.

Can I build an AI agent without Python?

Yes. Anthropic provides SDKs for multiple programming languages, including TypeScript, Java, Go, PHP, Ruby, and C#. You can also communicate with the API directly using HTTP requests.

Is the Claude API free?

API usage is subject to Anthropic's pricing and account requirements. Do not assume that access to the Claude chat product includes free API usage. Check the current official pricing and account information before building an application.

Can a Claude agent access my database?

Yes, if you create application functions that interact with the database and expose those functions as tools. The model requests operations, while your backend performs the actual database queries and enforces permissions.

Can one agent use multiple tools?

Yes. You can provide multiple tool definitions in the same request. Claude can choose the appropriate tool or request multiple tool operations when the task requires them and the request configuration permits it.

Does an AI agent always need a database?

No. A small demonstration can use temporary in-memory storage. However, a real application that needs to retain information across sessions should use persistent storage.

Is Claude responsible for executing my Python code?

No. For custom client-side tools, Claude returns structured tool requests. Your application executes the Python functions and sends the results back to Claude. This separation gives developers control over application behavior and permissions.

Conclusion

Building an AI agent with Claude is much easier once you understand the relationship between the language model and the application that executes its tools.

In this tutorial, we created a practical task-management agent using Python and the Anthropic API. We configured the development environment, connected Claude, created custom functions, defined tool schemas, implemented the agentic loop, and tested the application.

We also explored how to integrate external APIs, improve reliability, protect sensitive information, and extend a basic demonstration into a more capable application.

The most useful lesson is that an AI agent is not simply a chatbot with a complicated prompt. It is a system that combines a language model with carefully designed tools, application logic, data access, and security controls.

You do not need to build a large autonomous system as your first project. Start with one useful task, expose one or two well-defined functions, and test the behavior carefully. Once that works, introduce persistent storage, authentication, additional integrations, and a user interface.

That approach will help you build an agent that is not only interesting to experiment with but also useful in a real software application.

References and Official Documentation

The following resources are useful for learning more about Claude, tool use, API integration, and agent development. These are official documentation sources wherever applicable.

Subscribe to Our Newsletter

Join our community and receive the latest articles, tips, and updates directly in your inbox.

We respect your privacy. Unsubscribe at any time.

-

Cookies

We use cookies to enhance your experience. By continuing, you agree to our use of cookies.

Learn More