Python is widely used to build applications, automate tasks, and work with AI models. It also gives developers the tools to build AI agents that can perform tasks by calling functions and using the results.
To build a basic AI agent using Python, you can connect a language model to custom functions. For example, a calculator agent can call a Python function to solve a math problem and use the result to answer the user. OpenAI’s Function Calling guide explains how models can call functions defined in your application.
In this tutorial, you’ll learn how to build an AI agent using Python and the OpenAI API. You’ll set up the project, create a calculator tool, write the agent loop, and test how it works. You’ll also learn to handle errors, limit repeated model calls, and protect your API key.
How Does an AI Agent Work in Python?
An AI agent connects a language model to Python tools through a loop. The model decides when to use a tool, Python executes the function, and the model uses the result to answer the user or decide what to do next.
For example, when a user asks for a calculation, the model can call a Python function, receive the result, and return an answer. Unlike a basic chatbot that only responds with text, an agent can also take actions through its available tools.
Anthropic’s guide to building effective agents explains how models use tools and manage multi-step tasks. This tutorial applies the same basic idea using direct API calls and Python.
The workflow has four main steps:
- Receive the request: The agent sends the user’s question to the language model.
- Select a tool: If a calculation is needed, the model requests the calculate function and provides an expression.
- Execute the function: Python validates the expression, performs the calculation, and returns the result.
- Generate the answer: The model uses the tool result to respond to the user or request another tool call.
The model does not execute Python code directly. Your Python program decides which registered function to run and sends the result back to the model.
What Libraries Are Needed to Build an AI Agent in Python?
You only need Python and the openai library to build this tutorial’s agent. Python’s built-in json, ast, math, and operator modules handle tool arguments and calculations, so you don’t need to install them separately.
Install the OpenAI library with:
pip install openai
If you want to load API keys from a .env file, you can also install python-dotenv. You don’t need requests for this example because the calculator doesn’t call external web services.
Set up a Python virtual environment to keep the project’s dependencies separate from other Python projects.
How Do You Build an AI Agent Step by Step?
This tutorial builds a small Python AI agent that solves math questions with a custom calculator tool. The same tool-calling pattern can support other tasks when you add suitable functions.
Step 1: Set Up Your Project
Create a folder and a virtual environment. Then install the OpenAI library.
mkdir python-ai-agent
cd python-ai-agent
python -m venv venv
Activate the environment.
source venv/bin/activate
.\venv\Scripts\Activate.ps1
Install the dependency: pip install openai
Create two files in the project folder:
- tools.py – contains the calculator function.
- agent.py – connects the language model to the calculator.
Step 2: Create Your Calculator Tool
A tool is a normal Python function that the model can request by name. Your program runs the function and returns its result to the model.
Save the following code in tools.py.
import ast
import math
import operator
OPERATORS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
}
MAX_EXPRESSION_LENGTH = 200
MAX_AST_NODES = 50
MAX_ABS_RESULT = 10**100
def check_number(value):
if type(value) not in (int, float):
raise ValueError("Only integer and decimal numbers are allowed.")
if abs(value) > MAX_ABS_RESULT:
raise ValueError("Number exceeds the allowed limit.")
if isinstance(value, float) and not math.isfinite(value):
raise ValueError("Non-finite numbers are not allowed.")
return value
def evaluate(node):
if isinstance(node, ast.Constant):
return check_number(node.value)
if isinstance(node, ast.BinOp) and type(node.op) in OPERATORS:
left = evaluate(node.left)
right = evaluate(node.right)
result = OPERATORS[type(node.op)](left, right)
return check_number(result)
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
return check_number(-evaluate(node.operand))
if (
isinstance(node, ast.Call)
and isinstance(node.func, ast.Name)
and node.func.id == "sqrt"
and len(node.args) == 1
and not node.keywords
):
return check_number(math.sqrt(evaluate(node.args[0])))
raise ValueError("Unsupported expression.")
def calculate(expression: str) -> str:
try:
if not isinstance(expression, str):
return "Error: expression must be a string."
if len(expression) > MAX_EXPRESSION_LENGTH:
return "Error: expression is too long."
tree = ast.parse(expression, mode="eval")
if sum(1 for _ in ast.walk(tree)) > MAX_AST_NODES:
return "Error: expression is too complex."
result = evaluate(tree.body)
return f"Result: {result}"
except (
SyntaxError,
ValueError,
TypeError,
ArithmeticError,
) as error:
return f"Error: {error}"
AVAILABLE_TOOLS = {"calculate": calculate}
The calculator supports numbers, addition, subtraction, multiplication, division, unary minus, and sqrt(). It rejects unsupported operations such as exponentiation.
Using Python’s eval() on model-generated expressions can execute arbitrary code. This implementation avoids eval() and parses expressions with Python’s Abstract Syntax Tree (AST) module instead.
The expression-length, AST-node, and numeric limits help restrict inputs. However, these checks alone don’t make an AI agent production-ready. Real applications also need suitable timeouts, resource limits, input validation, monitoring, and access controls.
Step 3: Write the Agent Loop
The agent loop connects the language model to the calculator. It sends the user’s prompt to the model, checks whether the model requests a tool, runs the function, and returns its result. The loop continues until the model provides a final answer or reaches the step limit.
Save the following code in agent.py.
import json
from openai import OpenAI
from tools import AVAILABLE_TOOLS
client = OpenAI()
MODEL = "gpt-4o-mini"
MAX_STEPS = 5
tools_schema = [
{
"type": "function",
"function": {
"name": "calculate",
"description": (
"Evaluate basic arithmetic expressions using numbers, "
"+, -, *, /, and sqrt(). "
"Do not use unsupported operators."
),
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": (
"Expression to evaluate, "
"such as sqrt(144) * 5"
),
}
},
"required": ["expression"],
"additionalProperties": False,
},
"strict": True,
},
}
]
def run_agent(user_prompt):
messages = [
{
"role": "system",
"content": (
"You are a helpful assistant. Use the calculate tool "
"for arithmetic that requires computation. Explain "
"tool errors honestly and never invent calculation results."
),
},
{"role": "user", "content": user_prompt},
]
for _ in range(MAX_STEPS):
response = client.chat.completions.create(
model=MODEL,
messages=messages,
tools=tools_schema,
tool_choice="auto",
parallel_tool_calls=False,
)
message = response.choices[0].message
# Preserve the assistant message and its tool calls.
messages.append(message.model_dump(exclude_none=True))
if not message.tool_calls:
return message.content or "The model returned no text response."
for call in message.tool_calls:
name = call.function.name
try:
args = json.loads(call.function.arguments)
if not isinstance(args, dict):
raise ValueError(
"Tool arguments must be a JSON object."
)
if name not in AVAILABLE_TOOLS:
output = f"Error: unknown tool '{name}'."
elif set(args) != {"expression"}:
output = "Error: invalid calculator arguments."
else:
print(f"Running tool {name} with {args}")
output = AVAILABLE_TOOLS[name](**args)
except (json.JSONDecodeError, TypeError, ValueError) as error:
output = f"Error: invalid tool call: {error}"
except Exception as error:
output = f"Error: tool execution failed: {error}"
# Add one result for each tool call.
messages.append(
{
"role": "tool",
"tool_call_id": call.id,
"content": str(output),
}
)
return "Stopped: the agent reached its step limit."
if __name__ == "__main__":
try:
result = run_agent(
"What is the square root of 144 multiplied by 5?"
)
print("Agent:", result)
except Exception as error:
print(f"Agent failed: {error}")
The tool schema tells the model what the calculator does and which argument it requires. The strict setting requests structured arguments that follow the schema. The program also checks the tool name and arguments before executing the function.
The loop preserves the assistant’s tool-call message and adds one result for each tool call. The model then receives that result and can produce an answer. MAX_STEPS limits the number of model requests made by this loop.
Step 4: Run and Check the Output
Before running the agent, create an API key through your OpenAI account and set it as an environment variable. Keep the actual key private.
export OPENAI_API_KEY="your-actual-api-key-here"
python agent.py
$env:OPENAI_API_KEY = "your-actual-api-key-here"
python agent.py
The agent should request the calculator tool for the example question. Python evaluates the expression, and the model uses the result to answer.
Running tool calculate with {'expression': 'sqrt(144) * 5'}
Agent: The square root of 144 multiplied by 5 is 60.
The exact wording may vary, but the expected calculator result is 60.
If you receive an authentication error, verify that the API key is valid and available in the terminal where you’re running the program. Other API errors may require checking your model access, account limits, or network connection.
The example output illustrates the expected behavior; run the project with a valid API key to verify it in your environment.
How Do You Test and Secure Your Python AI Agent?
Test your agent with valid calculations, unsupported expressions, and questions that don’t require a tool. Check the calculator’s output and the agent’s tool-calling behavior rather than comparing the model’s final wording exactly.
Test Your AI Agent
| Test case | Example input | Expected behavior |
|---|---|---|
| Basic calculation | What is 12 multiplied by 5? | Calculator returns 60. |
| Square root | What is the square root of 144? | Calculator returns 12. |
| No tool needed | What is an AI agent? | Model answers without calling the calculator. |
| Division by zero | Calculate 10 / 0. | The calculator returns an error, which the model can explain. |
| Unsupported expression | Calculate 2 ** 10. | Calculator rejects the unsupported operator. |
| Invalid API key | Run the agent with an invalid key. | API request fails with an authentication error. |
If a test fails, inspect the tool arguments, return result, and API error before changing the code. The agent can pass calculator errors back to the model, but successful recovery is not guaranteed.
Protect Your Python AI Agent
Use these practices to improve reliability and protect your application:
- Validate tool inputs: Accept only the arguments your function needs and reject unsupported operations.
- Limit model calls: Keep MAX_STEPS to control repeated requests and unexpected API usage.
- Protect your API key: Store it in an environment variable instead of hardcoding it in your source code.
- Keep secrets out of Git: If you use a .env file, add it to .gitignore before committing your project.
- Handle API failures: Distinguish authentication errors, rate limits, timeouts, and connection failures so you can troubleshoot them separately.
- Restrict tool permissions: Give each tool access only to the data and actions it needs.
- Set resource limits: Restrict input sizes and execution time, especially when tools process untrusted inputs.
If you expose an API key, revoke it and create a replacement. Follow OpenAI’s production best practices for API key safety and application security.
Also, check the OpenAI models documentation to confirm that your chosen model is available to your account and supports the features your agent needs.
Can You Build an AI Agent in Python Without LangChain?
Yes. You can build an AI agent using plain Python and the openai library, as this example demonstrates.
Starting without a framework helps you understand how the agent calls tools, processes results, and decides what to do next. You can inspect API requests and tool responses directly, which makes debugging easier and builds the skills required to become an AI agent developer.
As your project grows, frameworks such as LangChain can help organize multiple tools, retrieval, and more complex workflows. However, a framework doesn’t automatically make an agent more accurate or secure. For a first project, plain Python is a practical starting point.
| Follow Us for Daily Tech Tips |
|
How Can TISA-TECH Help You Learn AI Agent Development?
Learning AI agent development takes more than reading code examples. You need to practice Python, connect AI models with tools, and learn how to handle errors. TISA-TECH’s AI/ML and Generative AI courses in Jaipur can help you learn these skills through hands-on practice and projects.
As you work on projects, you’ll understand how AI agents process inputs, use tools, and return results. You can also learn to test your code, find errors, and improve how your applications work. This practical experience helps you understand the concepts better and gives you projects to discuss during job interviews.
If you’re new to AI development, start by building a strong foundation in Python and gradually move to AI-based projects. Explore the available courses to find a learning path that matches your current skills and career goals. You can also ask for course guidance to understand which option suits your learning needs.
Conclusion
Building an AI agent with Python helps you understand how language models use tools to complete tasks. By connecting a model to Python functions, you can create agents that perform calculations, process results, and handle errors. Start with a simple use case and test each function before expanding the agent’s capabilities.
FAQs Section
Ans. Yes, basic Python knowledge helps. You should understand functions, variables, loops, dictionaries, and how to install libraries before connecting an AI model to Python tools.
Ans. You can write and test the Python code for free, but calling a hosted AI model may cost money. Check the provider’s pricing and account limits before running your agent.
Ans. First, check whether your API key is valid and the selected model supports tool calling. Then inspect the tool name, JSON arguments, and return the result. Handle input errors separately from API errors so you can identify the cause.
Ans. You can build a study assistant that searches your notes, a file-reading agent, or a research assistant that retrieves information from approved sources. Start with one task, define what each tool can access, and test the agent before adding more features.
Ans. A normal Python program generally follows predefined instructions. An AI agent uses a model to select an available tool or action based on the task, while Python executes the tool and returns its result.