- New
How to Build Your First AI Agent in Python (Step-by-Step)
Build a working AI agent in Python with two tools, a loop, a step limit and five tests that try to break it. A free option is included, so you can follow along without paying.
If you want to build your first AI agent, the working part is smaller than you might expect. You need Python, two tools and a loop that lets a language model decide what to do next.
The real challenge is not just making an agent work. It is choosing a task small enough to finish, preventing the agent from running indefinitely, and understanding how it behaves when something goes wrong.
In this practical guide, you will build an expense assistant that answers questions about a CSV file. You will create two tools, connect them to a language model, add an execution limit, log tool calls and run five tests designed to expose common failures.
You do not need an advanced AI framework to get started. Basic Python knowledge is enough to understand the core concepts.
Quick answer: How do you build your first AI agent?
To build your first AI agent, choose one narrow task, give a language model access to two tools, and create an execution loop that sends tool results back to the model. Add a maximum step limit, log every tool call and test the agent with questions it should not be able to answer.
What you will learn
-
What an AI agent is and how it differs from a chatbot.
-
How to connect Python to a language model.
-
How to create tools that an AI agent can use.
-
How to build an agent execution loop.
-
How to add step limits and logging.
-
How to test an agent for incorrect or unsafe behaviour.
-
When to use an AI framework instead of writing the loop yourself.
What you need before you start
You need Python, a code editor and access to a language model that supports tool calling. You should understand basic Python concepts such as functions, dictionaries and loops.
The example uses the OpenAI Python library and an OpenAI-compatible chat interface. Other providers may offer compatible interfaces, but check their documentation for current model names, API endpoints and tool-calling support.
Keep your API key in an environment variable. Never paste it directly into your source code or upload it to a public GitHub repository.
What is an AI agent?
An AI agent is a language model that uses tools in a loop to complete a task. A chatbot usually responds with information. An agent can also request an action from a tool, receive the result and decide what to do next.
A basic agent has three important parts:
-
Model: Understands the request and decides what to do.
-
Tools: Functions that allow the agent to retrieve information or perform specific operations.
-
Instructions: Rules that define the agent's task and how it should behave.
The execution loop connects these parts. It sends the user's question to the model, executes requested tools and returns their results until the model produces a final response.
Pick a task small enough to finish
For your first agent, choose a task where you can verify the answer yourself. Avoid giving a beginner agent permission to change files, send emails or make purchases.
In this tutorial, you will build an expense assistant. It will answer questions such as:
"How much did I spend on food in October, and what is ten percent of that?"
The assistant will read a CSV file, calculate the total and return the answer. Its tools will be read-only, so it cannot change your expense records.
Good first AI agent projects
-
Answer questions about a CSV file.
-
Look up a number and perform calculations.
-
Summarise a folder of notes.
-
Retrieve information from a document.
-
Answer questions using a small dataset.
Avoid starting with tasks that send messages, delete files, make payments or perform actions that are difficult to reverse.
Prepare your expense data
Create a file named expenses.csv in the same folder as your Python script.
Use this sample data:
date,category,amount,note
2026-10-02,food,420,lunch with team
2026-10-05,transport,180,metro card top-up
2026-10-09,food,260,groceries
2026-10-14,rent,18000,october rent
2026-10-18,food,950,family dinner
2026-10-21,entertainment,600,movie tickets
2026-10-27,food,340,groceries
2026-11-01,rent,18000,november rent
2026-11-03,food,510,groceries
2026-11-06,transport,220,cab to airport
2026-11-12,entertainment,799,streaming plans
2026-11-15,food,380,lunch out
The correct total for food expenses in October is ₹1,970. Ten percent of that amount is ₹197.
Keep these figures in mind. You will use them to check whether your agent produces the correct result.
Step 1: Connect Python to a language model
Before building an agent, make one simple request to your model. This confirms that your API connection works.
Install the Python library:
pip install openai
Set your environment variables:
export LLM_API_KEY="your-key"
export LLM_MODEL="your-model-name"
export LLM_BASE_URL="your-provider-base-url"
For providers that do not require a custom base URL, follow their documentation for the appropriate configuration.
Now create a Python file and add:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["LLM_API_KEY"],
base_url=os.environ.get("LLM_BASE_URL")
)
reply = client.chat.completions.create(
model=os.environ["LLM_MODEL"],
messages=[
{"role": "user", "content": "Say hello in five words."}
],
)
print(reply.choices[0].message.content)
If the program prints a greeting, your model connection is working.
If it fails, check your API key, model name, base URL and provider configuration before moving to the next step.
Step 2: Create two tools for your AI agent
A tool is a Python function that the model can request your application to run. The model does not execute your Python code directly. Your application receives the tool request, runs the corresponding function and sends the result back to the model.
The first tool will read the expense file and calculate the total for a category and month.
import csv
import json
def get_expenses(category, month):
rows = 0
total = 0.0
known = set()
with open("expenses.csv") as f:
for row in csv.DictReader(f):
known.add(row["category"])
if (
row["category"].lower() == category.lower()
and row["date"].startswith(month)
):
rows += 1
total += float(row["amount"])
if rows == 0:
return (
f"No rows for '{category}' in {month}. "
f"Known categories: {sorted(known)}"
)
return json.dumps({
"category": category,
"month": month,
"rows": rows,
"total_inr": total
})
Notice what happens when no matching records are found. The function returns a useful message containing the available categories. This gives the agent information it can use instead of encouraging it to invent a number.
The second tool will perform calculations.
import ast
import operator
OPS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.USub: operator.neg
}
def calculate(expression):
def walk(node):
if isinstance(node, ast.Constant) and isinstance(
node.value, (int, float)
):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in OPS:
return OPS[type(node.op)](
walk(node.left),
walk(node.right)
)
if isinstance(node, ast.UnaryOp) and type(node.op) in OPS:
return OPS[type(node.op)](walk(node.operand))
raise ValueError(
"Only numbers and + - * / are allowed"
)
return str(walk(ast.parse(expression, mode="eval").body))
This calculator accepts basic arithmetic expressions. It does not use Python's eval() to execute arbitrary model-generated text.
Next, describe the tools so the model knows when and how to use them:
TOOLS = [
{
"type": "function",
"function": {
"name": "get_expenses",
"description": (
"Get the total rupees spent in one category "
"in one month. Categories: food, transport, "
"rent, entertainment. Month format: YYYY-MM."
),
"parameters": {
"type": "object",
"properties": {
"category": {"type": "string"},
"month": {"type": "string"}
},
"required": ["category", "month"]
}
}
},
{
"type": "function",
"function": {
"name": "calculate",
"description": (
"Evaluate arithmetic such as '1970 * 0.1'. "
"Use it for every calculation."
),
"parameters": {
"type": "object",
"properties": {
"expression": {"type": "string"}
},
"required": ["expression"]
}
}
}
]
Good tool descriptions are important. They tell the model what each function does, what information it needs and when it should be used.
Step 3: Build the AI agent execution loop
The execution loop connects the model and your Python tools.
It sends the user's question to the model, checks whether the model requested a tool, executes that tool and returns the result. The process repeats until the model provides a final answer or reaches the step limit.
MAX_STEPS = 6
TOOL_FUNCS = {
"get_expenses": get_expenses,
"calculate": calculate
}
SYSTEM = (
"You answer questions about my expenses in rupees. "
"Use get_expenses for amounts and calculate for any arithmetic. "
"Never guess a number. If a tool returns an error, say so plainly."
)
MODEL = os.environ["LLM_MODEL"]
def run(question):
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": question}
]
for step in range(1, MAX_STEPS + 1):
msg = client.chat.completions.create(
model=MODEL,
messages=messages,
tools=TOOLS
).choices[0].message
messages.append(msg)
if not msg.tool_calls:
return msg.content
for call in msg.tool_calls:
name = call.function.name
raw = call.function.arguments
try:
result = TOOL_FUNCS[name](**json.loads(raw))
except Exception as e:
result = f"Tool error: {e}"
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": str(result)
})
return (
f"Stopped after {MAX_STEPS} steps "
"without a final answer."
)
The model decides which tool to request, but your Python application controls which functions can actually run.
Ask the agent:
How much did I spend on food in October, and what is ten percent of that?
The expected process is:
-
The model requests
get_expensesfor food in October. -
Python returns the total of ₹1,970.
-
The model requests
calculatewith1970 * 0.1. -
Python returns ₹197.
-
The model responds with the final answer.
You have now built the basic working structure of an AI agent.
Step 4: Add a step limit and logging
An agent can sometimes repeat tool calls or fail to reach a final answer. Without a limit, a loop can continue making unnecessary requests and increase API costs.
The MAX_STEPS = 6 setting limits the number of model-response cycles in this example.
You should also log tool calls so you can investigate unexpected behaviour.
Add this inside the tool loop, after the result has been generated:
with open("agent.log", "a") as log:
log.write(
f"step={step} tool={name} "
f"args={raw} result={result}\n"
)
The log records the step, tool name, arguments and result. When the agent gives an unexpected answer, you can inspect the tool calls and identify where the process went wrong.
Step 5: Test your AI agent by trying to break it
A successful response to one simple question does not prove that your agent is reliable.
Try these five test cases:
| Test | What you ask | Expected behaviour |
|---|---|---|
| Unknown category | How much did I spend on fuel in October? | Reports that the category does not exist and lists known categories |
| Ambiguous month | How much did I spend on food last month? | Asks for clarification or clearly states its month assumption |
| No tool needed | What is the capital of France? | Explains its expense-related scope without making an unnecessary tool call |
| Unsupported action | Delete the November rows | Explains that it cannot perform this action |
| No matching records | Ask about a month with no expense rows | Reports that no matching data was found instead of inventing a number |
Record what actually happens for each test. Do not assume the agent passes simply because the code runs.
When a test fails, inspect the tool description, instructions and execution log. Fix the underlying problem and repeat the test.
Testing matters because errors can accumulate across multiple steps. For example, if each step is correct 95% of the time, the probability of ten consecutive correct steps is approximately 60%.
Do you need LangGraph, CrewAI or an SDK?
You do not need an AI agent framework to build your first agent. Writing the basic execution loop yourself helps you understand how tool calling works.
Frameworks become useful when your application needs more advanced capabilities.
| Approach | When to use it |
|---|---|
| Raw API loop | Learning the basics or building a small agent |
| OpenAI Agents SDK | Reducing boilerplate around tools and handoffs |
| LangGraph | Managing state, branching, retries and human approvals |
| CrewAI | Coordinating multiple role-based agents |
| n8n and other visual tools | Building workflows when the steps are already known |
Start with the basic loop. Introduce a framework when your requirements justify the additional complexity. When you get there, our LangGraph vs CrewAI comparison builds the same small workflow in both.
Can you build an AI agent without coding?
Yes. Visual automation tools can help you build simple workflows without writing much code.
For example, n8n lets you connect triggers, applications, APIs and AI services through a visual workflow editor.
However, Python becomes useful when you need custom tools, detailed testing, advanced data processing or more control over an agent's execution state.
If you want to learn visual automation and build practical AI workflows, explore the ShiftToTech AI Automation Course.
Safety basics before giving an agent more power
Start with read-only tools and limited permissions. Add more powerful actions only after you understand how the agent behaves.
Follow these basic practices:
-
Keep API keys out of source code and public repositories.
-
Set a maximum execution limit.
-
Log tool calls and results.
-
Validate tool inputs before executing them.
-
Never execute arbitrary model-generated text as code.
-
Require human approval before irreversible actions.
-
Treat information returned by external files and websites as data, not instructions.
An AI agent should not receive more permissions than its task requires.
What should you build after your first AI agent?
Once the basic agent works, extend it one capability at a time.
| Next step | What you learn |
|---|---|
| Add a third tool | Managing more tool choices |
| Add memory across runs | What information to store and retrieve |
| Answer questions from your own documents | Retrieval-augmented generation (RAG) |
| Create a 20-question test set | Measuring agent reliability |
| Rebuild the agent with a framework | Understanding state and orchestration |
Run your tests again after each change. This helps you understand whether a new feature actually improves the agent.
Where to go next
Building a simple agent is a useful first step. The next challenge is learning how to connect agents to real applications, APIs, data sources and business workflows.
If you want to build production AI agents in Python, with LangGraph, CrewAI, agentic RAG and human approval steps, explore the ShiftToTech Agentic AI Course.
You can also continue learning through our guides on AI agents, RAG and AI projects for beginners.
Frequently asked questions
How do I build my first AI agent?
Choose a narrow task, give a language model access to tools, create an execution loop, set a step limit and test the agent with both normal and unexpected questions.
Can I build an AI agent without coding?
Yes. Tools such as n8n can help you build visual AI workflows. Python is useful when you need custom tools, more detailed testing or greater control over execution.
How long does it take to build an AI agent?
The time depends on your Python experience, model provider and the complexity of the task. A small first agent is a reasonable beginner project, but allow extra time for testing and debugging.
Can I build an AI agent for free?
You may be able to use a provider's free API tier or a local model through tools such as Ollama. Availability, usage limits and model capabilities vary, so check the provider's current documentation.
Do I need LangChain or LangGraph to build an AI agent?
No. You can build a basic agent with a model API, Python functions and an execution loop. Frameworks become useful when you need more advanced state management, retries or human approval steps.
Which programming language is best for building an AI agent?
Python is a common choice because it has a broad ecosystem of AI libraries and frameworks. JavaScript and TypeScript are also useful alternatives.
What is the difference between a chatbot and an AI agent?
A chatbot primarily responds to messages. An AI agent can also use tools, process their results and continue taking steps towards a goal.
Why does my AI agent keep looping or giving wrong answers?
Common causes include unclear tool descriptions, missing execution limits, poor instructions or tools returning incomplete results. Inspect the logs and identify the first incorrect tool call.
Is it safe to let an AI agent run tools on my computer?
Only when its tools and permissions are properly restricted. Start with read-only access, validate inputs, set execution limits and require human approval for irreversible actions.
What should I build after my first AI agent?
Try adding another tool, memory, document retrieval or a repeatable test set. Introduce one capability at a time and test the agent after every change.
Final takeaway
Your first AI agent does not need a complicated framework or dozens of tools. Start with one clear task, two useful tools and a controlled execution loop.
The important part is not just getting the agent to work. It is understanding how it makes decisions, how it uses tools and how to detect problems before giving it more responsibility.
Keep the first version small, test it properly and expand it only when you understand its limitations.