Introduction
Artificial intelligence is changing how we write code, search for information, automate tasks, and build applications. One exciting area of AI is the use of AI agents.
An AI agent is a system that can understand a goal, decide what steps to take, use tools, and work toward completing a task. For example, an AI study assistant could answer student questions, search a collection of notes, and create a revision plan.
Python is a popular choice for building AI agents because it has a large ecosystem of libraries, model APIs, and development tools.
In this tutorial, you will learn how to build AI agents in Python using three different methods:
- Build a simple tool-using agent with Python code.
- Build an agent using LangChain.
- Build an agent using the OpenAI Agents SDK.
Each method has different advantages. The first helps you understand the basic logic, the second provides a framework for connecting models and tools, and the third offers built-in support for agent execution, tools, and safety controls.
You do not need to master advanced AI concepts before starting. Basic Python knowledge will help you understand the examples.
What Is an AI Agent?
An AI agent is a software system that uses instructions and, often, an AI model to work toward a goal. Depending on its design, it may use external tools, keep track of context, and complete multiple steps before returning an answer.
Consider a student who asks:
“Help me prepare for my Python practical exam.”
A basic chatbot might respond with general study advice. An AI agent could be designed to perform additional tasks, such as:
- Identify important Python topics.
- Retrieve questions from an approved study-note collection.
- Organize the questions by difficulty.
- Create a revision timetable.
- Present the final plan to the student.
The tools and permissions determine which actions the agent can actually perform. An agent does not automatically have access to websites, files, or applications unless you connect them.
What are the main parts of an AI agent?
| Component | Purpose | Example |
|---|---|---|
| AI model | Understands requests and generates decisions or responses | A language model |
| Instructions | Explain the agent’s role and limits | “Act as a Python tutor” |
| Tools | Let the agent perform specific tasks | A calculator or search function |
| Context or memory | Helps retain relevant information | Previous questions in a session |
| Control logic | Manages the steps of a task | Decide whether to use a tool |
| Guardrails | Limit unsafe or unwanted actions | Require approval before deleting data |
Not every agent needs every component. A small learning project may need only a model, instructions, and one tool. A larger application may require memory, logging, testing, and approval steps.
Method 1: Build a Simple AI Agent with Python
The first method is to write the basic agent logic yourself. This is a good starting point because it helps you understand how tools, decisions, and results fit together.
For this example, we will create a small study assistant agent with two tools: one that calculates a sum and another that returns a Python learning tip.
To keep the first example easy to run, the tool selection uses simple Python rules rather than a language model. This is a tool-using agent prototype, not a full generative AI agent. You can later connect a language model to help interpret more complex requests.
Step 1: Install Python
Install a supported version of Python from the official website:
https://www.python.org/downloads
You can write and run the program using Visual Studio Code, PyCharm, IDLE, or another Python editor.
Step 2: Create a Python file
Create a file named simple_agent.py.
Step 3: Write the code
def calculate_sum(a, b):
"""Add two numbers."""
return a + b
def get_python_tip():
"""Return a beginner Python tip."""
return "Practise Python loops with small programs."
def simple_agent(user_input):
"""Choose a tool based on simple rules."""
text = user_input.lower()
if "add" in text or "sum" in text:
return calculate_sum(10, 20)
if "python tip" in text:
return get_python_tip()
return "Try asking me to add numbers or give a Python tip."
print(simple_agent("Please add two numbers"))
print(simple_agent("Give me a Python tip"))
Step 4: Run the program
Open your terminal in the folder containing the file and run:
python simple_agent.py
Output:
30
Practise Python loops with small programs.
How does this agent work?
The program follows a simple process:
- It receives a request from the user.
- It checks the request for certain words.
- It selects a matching Python function.
- The function performs the task.
- The program returns the result.
The functions are tools because they perform specific jobs. The simple_agent() function acts as the basic controller that decides which tool to use.
What are the advantages of building an agent from scratch?
- You can understand the logic clearly.
- You have direct control over how tools are selected.
- You do not need an external AI API for this demonstration.
- It is useful for learning Python functions and conditions.
- You can customize the program for a small task.
What are the limitations?
This program does not understand language in the same way that an AI model does. It depends on simple keyword rules and cannot reliably interpret requests outside those rules.
For example, “Can you total these values?” may not match the word add or sum.
To build a more flexible agent, connect the controller to a language model that can interpret user requests and select tools. The next two methods use frameworks designed to help with this kind of development.
Method 2: Build an AI Agent Using LangChain
LangChain is a framework for developing applications powered by language models. It provides tools for connecting models, prompts, functions, and other components.
LangChain is useful when you want to build an agent that can decide when to use available tools instead of relying entirely on fixed keyword rules.
Official documentation: https://docs.langchain.com/
What do you need?
Before starting, make sure you have:
- Python installed.
- Basic knowledge of Python functions.
- Access to a supported language model.
- An API key from the model provider you choose.
Some model providers charge for API usage. Check the current pricing and limits before running your application.
Step 1: Install the required packages
For an example using LangChain with an OpenAI model integration, install:
pip install -U langchain langchain-openai
Step 2: Set your API key
Create an API key through your chosen provider’s official platform.
In Windows PowerShell, set an environment variable for the current terminal session:
$env:OPENAI_API_KEY = "your-api-key"
On macOS or Linux, use:
export OPENAI_API_KEY="your-api-key"
Replace the placeholder with your real key. Never publish your API key in a blog post, GitHub repository, screenshot, or frontend JavaScript file.
Step 3: Create a tool-using agent
Create a file called langchain_agent.py.
The following example uses LangChain’s agent creation interface. It assumes the provider account has access to the selected model.
from langchain.agents import create_agent
def add_numbers(a: int, b: int) -> int:
"""Add two numbers and return the result."""
return a + b
agent = create_agent(
model="openai:gpt-4.1-mini",
tools=[add_numbers],
system_prompt=(
"You are a helpful Python study assistant. "
"Answer clearly and use the add_numbers tool "
"when a calculation is needed."
),
)
result = agent.invoke(
{
"messages": [
{
"role": "user",
"content": "What is 25 plus 35?",
}
]
}
)
print(result["messages"][-1].content)
Expected answer: The final response should report that 25 plus 35 equals 60. Exact wording can vary because the model generates the response.
Model availability and package interfaces can change. Check the current LangChain documentation for supported model names and the latest agent API before using this code in a project.
Step 4: Understand the code
The add_numbers() function
This function is a tool. It accepts two integers and returns their sum.
The create_agent() function
This creates the agent using a model, a list of available tools, and a system prompt.
The system prompt
The instructions tell the agent to behave like a study assistant and use the calculator tool when needed.
The invoke() method
This sends the user’s request to the agent and runs the agent workflow.
The final result
The program prints the content of the final message.
The important difference from Method 1 is that the language model can interpret the user’s request and determine whether a tool is appropriate. The framework manages much of the tool-calling workflow.
When should you use LangChain?
LangChain can be a good choice when you want to:
- Connect a language model to multiple Python functions.
- Build a question-answering assistant.
- Combine model calls with data retrieval.
- Work with different model providers and integrations.
- Develop an application that may need more complex workflows.
It is important to remember that adding a framework does not automatically make an application accurate. You still need to test tool selection, handle errors, and check the quality of the model’s answers.
Method 3: Build an AI Agent Using the OpenAI Agents SDK
The OpenAI Agents SDK is a Python toolkit for building agents that use instructions, tools, and structured workflows. It includes support for tool execution, agent handoffs, guardrails, and tracing.
Official documentation: https://openai.github.io/openai-agents-python/
This method is useful when you want an agent framework that manages more of the execution process for you.
Step 1: Install the SDK
Run this command in your terminal:
pip install openai-agents
It is a good idea to use a virtual environment for each Python project. This helps keep the project’s packages separate from those used by other projects.
Step 2: Configure your API key
On Windows PowerShell:
$env:OPENAI_API_KEY = "your-api-key"
On macOS or Linux:
export OPENAI_API_KEY="your-api-key"
Keep your key private. If a key is accidentally exposed, revoke it through the provider’s account dashboard and create a replacement.
Step 3: Create your first agent
Create a file named openai_agent.py.
import asyncio
from agents import Agent, Runner
agent = Agent(
name="Python Study Assistant",
instructions=(
"You are a friendly Python tutor. "
"Explain programming concepts in simple English. "
"Use short examples when helpful."
),
)
async def main():
result = await Runner.run(
agent,
"Explain Python for loops with a simple example.",
)
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
Step 4: Run the agent
Run this command:
python openai_agent.py
Example of the kind of response you may receive:
A for loop repeats a block of code for each item
in a sequence.
Example:
for i in range(1, 4):
print(i)
Output:
1
2
3
The exact response depends on the model and its configuration.
How does this agent work?
Agent
The Agent object defines the assistant’s name and instructions.
Runner
The runner executes the agent and returns a result.
Runner.run()
This starts an agent run with the user’s input. The example uses asyncio to run the asynchronous function.
result.final_output
This contains the final response produced by the agent workflow.
This basic example is a model-powered agent, but it does not yet use an external tool. You can add tools as the application grows.
Step 5: Add a Python tool
The following example gives the agent a tool that can calculate the sum of two numbers.
import asyncio
from agents import Agent, Runner, function_tool
@function_tool
def add_numbers(a: int, b: int) -> int:
"""Add two numbers and return their sum."""
return a + b
agent = Agent(
name="Math Study Assistant",
instructions=(
"Help students with simple calculations. "
"Use the add_numbers tool when addition is needed. "
"Explain the result clearly."
),
tools=[add_numbers],
)
async def main():
result = await Runner.run(
agent,
"Calculate 45 plus 55.",
)
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
Expected result: The agent should answer that 45 plus 55 equals 100.
The @function_tool decorator makes the Python function available as a tool. The agent can use the tool when appropriate based on the user’s request and the instructions.
For the current installation and supported options, follow the official OpenAI Agents SDK quickstart.
What can you build with the OpenAI Agents SDK?
You could create:
- A Python tutor that explains programming topics.
- A study assistant that uses approved notes as a source.
- A customer support assistant connected to selected business functions.
- A workflow where one specialist agent passes a task to another.
- An assistant that uses tools and asks for human approval before important actions.
The SDK provides building blocks, but you must still design the tools, define access limits, and test the application before using it with real users.
4. Comparison: Which Method Is Best?
| Feature | Method 1: Python from scratch | Method 2: LangChain | Method 3: OpenAI Agents SDK |
|---|---|---|---|
| Beginner learning | Very good | Good with basic Python | Good with basic Python |
| Language model required | No, for the simple prototype | Yes for a model-powered agent | Yes for the model-powered example |
| Tool calling | Manual rules | Framework-managed | SDK-managed |
| Flexibility | Depends on your code | Broad integrations | Agent-focused workflow tools |
| Setup effort | Low | Moderate | Moderate |
| Best use | Learning basic agent logic | Model and data integrations | Tool-using agents and coordinated workflows |
There is no single best method for every project.
Choose Method 1 to learn the core logic. Choose LangChain when you need its model and data integrations. Choose the OpenAI Agents SDK when you want its agent runtime and tools for managing execution.
5. What Are the Best Beginner Projects for Python AI Agents?
Once you understand the three methods, try building a small project with a clear purpose.
Project 1: AI Study Assistant
Build an assistant that explains Python, DBMS, operating systems, or computer networks.
Possible features:
- Answer student questions.
- Explain code step by step.
- Generate practice questions.
- Use a collection of approved study notes.
- Create a revision checklist.
Start with a small set of notes rather than allowing unrestricted access to every file on your computer.
Project 2: AI Calculator Agent
Create an agent that can answer simple math questions by calling Python functions.
Possible features:
- Addition and subtraction.
- Multiplication and division.
- Percentage calculations.
- Basic unit conversion.
Validate inputs and prevent invalid operations, such as division by zero.
Project 3: AI Content Planning Agent
Create an assistant that organizes blog ideas for an educational website.
Possible features:
- Group ideas by topic.
- Suggest article outlines.
- Generate draft titles.
- Create a publishing checklist.
- Recommend related articles.
Require human review before publishing content. Generated text should be checked for accuracy, originality, and source quality.
Project 4: AI Customer Support Agent
Build an assistant that answers common questions using approved documentation.
Possible features:
- Search a knowledge base.
- Identify the type of customer question.
- Draft an answer.
- Send complex questions to a human representative.
Do not let an early prototype issue refunds, change customer accounts, or modify important records without proper authorization and approval.
6. Best Practices for Building Reliable AI Agents
AI agents can make mistakes. They may misunderstand a request, choose an unsuitable tool, or generate an incorrect answer. Use these practices to make your application more dependable.
1. Give the agent one clear job
Start with a narrow goal. A Python tutor is easier to test than an assistant that tries to manage every part of a student’s life.
2. Provide only the tools it needs
Each tool should have a clear purpose and limited permissions. Do not give an agent access to files, databases, or services it does not need.
3. Validate tool inputs
Check that numbers, strings, and other inputs meet the expected rules before a tool acts on them.
4. Keep secrets private
Store API keys in environment variables or a suitable secret manager. Do not include them in public source code or browser-based applications.
5. Ask for approval before important actions
Actions such as deleting records, sending external messages, making purchases, or changing account settings should have suitable checks and approval steps.
6. Test normal and unusual requests
Try correct inputs, missing information, unexpected requests, and invalid values. Check both the final answer and the actions taken by the agent.
7. Track cost and usage
Model requests may incur charges. Monitor usage, set appropriate limits, and avoid unnecessary repeated calls.
8. Check answers against trusted sources
For educational applications, use official documentation, textbooks, and verified study materials where appropriate. Do not assume that a confident-sounding AI response is automatically correct.
7. Frequently Asked Questions
Can I build an AI agent using Python?
Yes. Python can be used to build agents from basic functions and control logic or with frameworks such as LangChain and the OpenAI Agents SDK. The right approach depends on your goals and the tools you need.
Do I need advanced Python knowledge?
No. Beginners can start with functions, conditions, and loops. To build model-powered agents, you should also learn how to install packages, configure API keys, handle errors, and work with external APIs.
Are Python AI agents free to build?
The Python language and many libraries are free to use. However, model APIs, hosting, databases, and other services may cost money. The simple rule-based example in Method 1 runs without a model API.
What is the difference between an AI chatbot and an AI agent?
A chatbot mainly responds to messages. An AI agent may also select tools, perform steps, and take actions within the permissions it has been given. Some applications combine both approaches.
Is LangChain necessary to build an AI agent?
No. You can write your own control logic or use another framework. LangChain is useful when its abstractions and integrations fit your project.
What is the OpenAI Agents SDK used for?
It helps developers build model-powered agents with instructions, tools, execution management, and other agent workflow features. The official documentation describes the supported capabilities and setup.
Can AI agents work without an API key?
Yes, if you build a rule-based agent or use a compatible local model that does not require an external API key. The model-powered examples in this article require provider access and appropriate credentials.
Are AI agents suitable for college projects?
Yes. A study assistant, calculator agent, or question-answering tool can be a useful college project. Document the design, explain the limitations, and test the application rather than relying only on a demonstration.
Conclusion
Python provides several ways to build AI agents, from simple programs that select tools to framework-based applications that use language models.
In this guide, you learned three approaches:
- Python from scratch: Best for understanding basic agent logic.
- LangChain: Useful for connecting language models, tools, and data sources.
- OpenAI Agents SDK: Useful for building model-powered agents with managed execution and tool support.
Start with a small project, test it with realistic inputs, and add more tools only when they solve a real problem. Focus on accuracy, security, clear permissions, and human review for important actions.
For beginners, a Python study assistant is a practical first project because it lets you apply programming concepts while learning how agents use tools.
Trusted References
- OpenAI – Building Agents — Core concepts, tools, guardrails, and orchestration.
- OpenAI Agents SDK – Python Quickstart — Installation, agent creation, and execution.
- OpenAI Agents SDK – Documentation — Tools, sessions, handoffs, and other agent capabilities.
- LangChain Documentation — Framework documentation for building applications with language models.
- Python Official Documentation — Python fundamentals, functions, and control flow.
Suggested Images and Alt Text
Image 1: Featured image
Alt text: How to build AI agents in Python using three methods
Image 2: AI agent workflow diagram
Alt text: Python AI agent workflow showing user input model tools and final response
Image 3: Python agent code example
Alt text: Python code for creating a tool-using AI agent



