AI Agents with Python 2026 — Part 3: Build Your First Simple AI Agent with Python

In Part 1, we explored what AI agents are and how they differ from traditional software and chatbots.
In Part 2, we went under the hood and examined the architecture behind an AI agent — models, tools, memory, knowledge, planning, tool calling, observation, and guardrails.
Now it’s time to write some code.
Welcome to Part 3 of AI Agents with Python 2026 — From Automation to Autonomous Systems.
In this article, we’ll build our first simple AI agent with Python.
We won’t start with a complicated framework or a multi-agent architecture.
Instead, we’ll build a small agent that demonstrates the fundamental idea behind agentic systems:
Give an AI a goal, provide it with a tool, allow it to decide when the tool is useful, execute the tool, and return the result.
Once you understand this foundation, more advanced agent architectures become much easier to understand.
What Are We Building?
Our first project will be a simple Python AI Research Assistant.
The agent will be able to:
- Receive a user’s request.
- Understand the task.
- Determine whether it needs a tool.
- Call an appropriate Python function.
- Receive the tool’s result.
- Use the result to produce a response.
For example:
User: What is 25% of 8,000?
Instead of relying entirely on the language model to perform the calculation, our agent can use a Python calculator function.
The architecture looks like this:
User
↓
Goal
↓
AI Model
↓
Does a tool need to be used?
↓
Calculator Tool
↓
Result
↓
AI Model
↓
Final Response
It’s simple, but it contains the fundamental building blocks of an AI agent.
What You Need
To follow this tutorial, you should have:
- Basic Python knowledge
- Python 3 installed
- A code editor such as VS Code
- Access to an AI model/API
- Basic understanding of functions
- Basic understanding of dictionaries and JSON
You don’t need to be an advanced Python developer.
If you’ve been following my AI With Python 2026 series, you already have much of the foundation required.
Project Code
Ready to build the agent?
The complete project files for this tutorial are available in the AI Agents with Python 2026 GitHub repository.
AI Agents with Python 2026 — GitHub Repository
Navigate to:
03-first-simple-agent
From there, you can follow the project’s README and run the example locally.
Step 1: Create the Project
Let’s create a project directory.
ai-agent-python/
│
├── main.py
├── tools.py
├── agent.py
└── requirements.txt
We’re deliberately keeping the project small.
As our agents become more sophisticated later in the series, we’ll introduce better project structures.
Step 2: Create a Python Virtual Environment
Virtual environments are useful because they isolate your project’s dependencies from other Python projects.
On Windows:
python -m venv .venv
Activate it:
.venv\Scripts\activate
On Linux or macOS:
python3 -m venv .venv
Activate:
source .venv/bin/activate
You should now see something similar to:
(.venv)
in your terminal.
Step 3: Install the Required Libraries
The exact libraries depend on the AI provider and framework we choose.
For this first implementation, we’ll keep the architecture simple and use Python’s standard functionality alongside an AI API client.
For example:
pip install openai
You can then record the dependency:
pip freeze > requirements.txt
The important lesson isn’t the specific package.
The important lesson is understanding how the Python application, model, and tools interact.
Step 4: Protect Your API Key
Never put your API key directly into your Python source code.
Avoid this:
api_key = "my-secret-api-key"
If you upload the project to GitHub, your key could accidentally become public.
Instead, use an environment variable.
For example:
set OPENAI_API_KEY=your_api_key
On Linux/macOS:
export OPENAI_API_KEY="your_api_key"
You can also use a .env file with an appropriate environment-variable library.
For example:
OPENAI_API_KEY=your_api_key_here
And make sure .env is included in .gitignore.
.env
.venv/
__pycache__/
This is a small habit that makes a major difference in real-world development.
Step 5: Create Our First Tool
Let’s create tools.py.
Our first tool will be a calculator.
def calculate(expression):
try:
result = eval(expression)
return str(result)
except Exception:
return "Unable to calculate the expression."
We now have a Python function that can perform calculations.
For example:
print(calculate("25 * 400"))
Output:
10000
Our AI agent can potentially use this function when the user asks a calculation-related question.
Important Security Warning
You may have noticed that we’re using:
eval()
This is convenient for demonstrating the concept, but you should not expose unrestricted eval() to untrusted user input in a production application.
Why?
Because eval() can execute arbitrary Python expressions.
For a real application, you should implement a safe mathematical expression parser or restrict the allowed operations.
For example, a production calculator tool could explicitly support:
- Addition
- Subtraction
- Multiplication
- Division
- Percentages
without executing arbitrary Python code.
This is an important lesson:
Never sacrifice security simply to make an AI demonstration shorter.
Step 6: Create a Tool Registry
Our agent needs to know which tools are available.
We can create a simple dictionary:
tools = {
"calculator": calculate
}
Now our application knows:
calculator → calculate()
As we add more tools, the registry can grow.
For example:
tools = {
"calculator": calculate,
"search": search_web,
"weather": get_weather,
}
This is the beginning of a tool-enabled AI system.
Step 7: Give the AI Access to the Tool
Now we need to connect our Python application to an AI model.
Conceptually, we’re giving the model information like:
Available tool:
calculator
Description:
Performs mathematical calculations.
Input:
A mathematical expression.
The model can then determine whether that tool is useful.
For example:
User
What is 15% of 40,000?
AI
The model identifies that a calculation is required.
Agent
Calls:
calculator("40000 * 0.15")
Tool
Returns:
6000
AI
Produces:
15% of 40,000 is 6,000.
That is a basic tool-calling workflow.
Step 8: Understanding Tool Calling
Tool calling is an important concept in modern agentic AI.
The model does not directly execute the Python function.
Instead, it can request that the application execute a particular tool.
Conceptually:
AI Model
│
│ “I need calculator”
↓
Python Application
│
│ Executes calculator()
↓
Tool Result
│
↓
AI Model
This distinction is extremely important.
The model proposes an action.
Your application decides whether and how that action is executed.
This gives developers an opportunity to implement:
- Permission checks
- Input validation
- Logging
- Rate limits
- Security policies
- Human approval
Step 9: A Simple Agent Loop
Let’s create the conceptual agent loop.
while True:
response = model(user_input)
if response_requires_tool(response):
tool_result = execute_tool(response)
response = model(tool_result)
else:
break
The loop can be summarized as:

This is one of the most important concepts in agent development.
Step 10: A More Structured Tool
Instead of simply storing a function, we can describe our tool using metadata.
calculator_tool = {
"name": "calculator",
"description": "Perform mathematical calculations",
"function": calculate
}
Now the application knows three things:
Name
calculator
Description
Perform mathematical calculations
Function
calculate()
This pattern becomes especially useful when an agent has multiple tools.
Multiple Tools
Imagine our agent has three tools:
tools = {
"calculator": calculate,
"weather": get_weather,
"search": search_information
}
The user could ask:
“What is the weather in Accra?”
The agent could select:
weather
Or:
“Calculate the annual cost if I spend GHS 250 every week.”
The agent could select:
calculator
Or:
“Find information about Python AI frameworks.”
The agent could select:
search
Now we have something more interesting.
The AI is not simply answering questions.
It is determining which capability is appropriate for the task.
Tool Descriptions Matter
A poorly described tool can lead to poor tool selection.
Compare these two descriptions.
Poor
Does something with data.
Better
Calculates mathematical expressions such as
addition, subtraction, multiplication, division,
and percentages.
The second description gives the model much more useful information.
When designing tools, describe:
- What the tool does
- When it should be used
- What input it expects
- What output it returns
- Any limitations
Good tool descriptions are part of good agent design.
Step 11: Add Input Validation
Never assume that tool input is valid.
For example:
def calculate(expression):
if not isinstance(expression, str):
return "Invalid expression."
if len(expression) > 100:
return "Expression is too long."
# Perform safe calculation here
Input validation provides another security layer.
This becomes even more important when tools interact with:
- Databases
- Operating systems
- Cloud infrastructure
- Financial systems
- Customer information
Step 12: Add Logging
When an agent performs multiple actions, debugging becomes more difficult.
Logging helps you understand what happened.
For example:
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Agent started")
logging.info("Calculator tool selected")
logging.info("Calculator tool executed")
In a production environment, you may want to record:
- User request
- Agent decision
- Tool selected
- Tool arguments
- Tool result
- Execution time
- Errors
- Final response
However, be careful not to log sensitive information unnecessarily.
Step 13: Add an Execution Limit
Agents can sometimes enter loops.
Imagine:
Agent → Tool → Agent → Tool → Agent → Tool...
Without a limit, the application could continue indefinitely.
Add a maximum number of steps:
MAX_STEPS = 5
for step in range(MAX_STEPS):
# Agent logic here
if task_complete:
break
This protects your application against runaway execution.
Step 14: Add Error Handling
Tools can fail.
For example:
def run_tool(tool, arguments):
try:
return tool(**arguments)
except Exception as error:
return {
"success": False,
"error": str(error)
}
The agent can then determine what to do next.
Possible options include:
- Retry
- Use another tool
- Ask the user
- Escalate
- Stop
A reliable agent isn’t one that never encounters errors.
It’s one that handles errors predictably.
Step 15: Understanding the Complete Flow
Let’s put everything together.
Suppose the user asks:
“What is 18% of GHS 25,000?”
The process could look like this:
1. User
Provides the request.
2. Python Application
Sends the request and available tool definitions to the model.
3. AI Model
Determines that the calculator is appropriate.
4. Tool Request
The model requests:
calculator
25000 * 0.18
5. Python Application
Validates the request.
6. Calculator
Returns:
4500
7. AI Model
Uses the result to formulate the final response.
8. User
Receives:
18% of GHS 25,000 is GHS 4,500.
The agent has completed its task.
Agent vs Function
At this point, you might ask:
Why not simply write a Python calculator function?
That’s a very good question.
For a simple calculation, you absolutely should.
You don’t need an AI agent to calculate:
25000 * 0.18
The reason we’re using a calculator is to demonstrate a larger concept.
The agent can determine:
“This task requires a calculation, and I have a calculator tool available.”
That same architecture becomes more useful when the problem is less predictable.
For example:
“Analyze this sales report, identify unusual trends, calculate the percentage changes, and prepare a summary.”
Now the system may need:
- File-reading tools
- Data-analysis functions
- Calculator tools
- Knowledge retrieval
- Report generation
This is where agentic architectures become more valuable.
Building an Agent Incrementally
A common mistake when learning agentic AI is trying to build a highly autonomous system immediately.
Instead, build progressively.
Level 1 — Simple AI Response
User → Model → Response
Level 2 — AI + One Tool
User → Model → Tool → Response
Level 3 — AI + Multiple Tools
User → Model → Tool 1/2/3 → Response
Level 4 — Agent Loop
Goal → Decide → Act → Observe → Decide → Result
Level 5 — Memory
Goal → Memory → Decide → Act → Observe → Update Memory
Level 6 — RAG
Goal → Retrieve → Decide → Act → Observe → Result
Level 7 — Multi-Agent System
Agent A
↓
Agent B
↓
Agent C
↓
Final Result
This progression will form the foundation of the rest of this series.
A Simple Project Structure
As your agent grows, keeping everything in one file becomes difficult.
A better structure could look like:

Don’t worry if this looks complicated.
At this stage, the objective is simply to understand how a real project can eventually be organized.
We’ll revisit project architecture later.
Testing Your AI Agent
AI applications need testing just like traditional software.
You should test individual tools independently.
For example:
def test_calculator():
assert calculate("10 + 5") == "15"
You should also test invalid input.
def test_invalid_input():
result = calculate("invalid")
assert result is not None
And eventually test the complete agent workflow.
For example:
Input
↓
Agent
↓
Tool Selection
↓
Tool Execution
↓
Result
↓
Final Response
Testing becomes more important as agents gain more tools and autonomy.
What About AI Hallucinations?
Our agent can still make mistakes.
The model might:
- Select the wrong tool
- Provide incorrect arguments
- Misinterpret the result
- Generate an inaccurate final answer
This is why tool execution should be validated.
For example, don’t blindly execute:
tool(**model_generated_arguments)
Instead:

This creates a safer architecture.
Human Approval
For low-risk tools such as a calculator, automatic execution is usually reasonable.
But imagine an agent wants to:
Delete a database record.
That should probably require additional authorization.
A safer workflow could be:
AI Agent
↓
Proposes Action
↓
Security Check
↓
Human Approval
↓
Execute
This is called Human-in-the-Loop (HITL).
We’ll explore this more when we discuss agent security and guardrails.
Our First Agent Architecture
By now, our simple project can be represented as:
USER
│
▼
┌─────────────┐
│ PYTHON │
│ APPLICATION │
└──────┬──────┘
│
▼
┌─────────────┐
│ AI MODEL │
└──────┬──────┘
│
Tool Request
│
▼
┌─────────────┐
│ VALIDATION │
└──────┬──────┘
│
▼
┌─────────────┐
│ CALCULATOR │
│ TOOL │
└──────┬──────┘
│
Result
│
▼
┌─────────────┐
│ AI MODEL │
└──────┬──────┘
│
▼
FINAL ANSWER
This may look simple.
But conceptually, we’ve built the foundation of an agentic application.
What We Have Learned
In this part, we moved from theory to implementation.
We learned how to:
Create a Python AI project
Set up a virtual environment
Protect API credentials
Create a Python tool
Register tools
Understand tool calling
Build a basic agent loop
Validate tool inputs
Handle errors
Add execution limits
Implement logging
Think about security
Organize an AI agent project
Most importantly, we learned that an AI agent isn’t necessarily a complicated piece of software.
At its core, it can be:
Model + Goal + Tools + Logic + Feedback
The Bigger Picture
Our calculator agent is intentionally simple.
Real-world agents can connect to much more powerful tools.
Imagine a Network Troubleshooting Agent with access to approved diagnostic tools:

Or a Broadcast Operations Assistant:

The possibilities become much more interesting when agents can safely interact with real tools and information.
But Don’t Give Your Agent Too Much Power
This is perhaps the most important lesson from today’s article.
It’s tempting to create an agent that can:
“Do anything.”
That’s usually a bad idea.
Instead, ask:
What does this agent actually need to accomplish its job?
Then provide only those capabilities.
For example:
Research Agent
Give it:
- Search
- Document retrieval
- Summarization
Don’t give it:
- Database deletion
- Server administration
- Financial transaction access
This is the principle of least privilege applied to AI agents.
What’s Coming in Part 4?
We’ve now built an agent with a basic tool.
But our agent is still limited.
It only has a small number of capabilities, and we haven’t explored how to connect agents to external services.
That’s where Part 4 comes in.
AI Agent Tools and APIs — Giving Your Python Agent Real-World Capabilities
We’ll explore how AI agents can interact with external services through APIs and tools.
We’ll look at:
- What APIs are
- REST APIs
- HTTP requests with Python
- API authentication
- Tool schemas
- Function calling
- Connecting AI agents to external services
- Error handling
- Rate limits
- API security
- Building a practical API-powered agent
For example, we’ll move from:

to:

This is where our agents begin to interact with the real world.
Final Thoughts
Building AI agents can initially seem complicated.
There are LLMs, APIs, tools, memory, RAG, frameworks, vector databases, function calling, security, and many other concepts.
But you don’t need to learn everything at once.
Start with the fundamentals.
Goal.
Model.
Tool.
Action.
Observation.
Result.
Then gradually add more capabilities.
Our first agent may only be able to perform a calculation.
But the architecture we’ve introduced today is the same basic idea we’ll continue expanding throughout this series.
We’re no longer just asking:
“How can Python talk to AI?”
We’re asking a more interesting question:
“How can Python help AI accomplish useful tasks?”
And that’s where the real potential of AI agents begins.
AI Agents with Python 2026
From Automation to Autonomous Systems.
See you in Part 4.
Previous: AI Agents with Python 2026 (Part 2): How AI Agents Work — Models, Tools, Memory and Reasoning
Next: Building a Reliable Media Network: Why Ghanaian Media Companies Need to Rethink Storage, Networking…
Leave a comment