Building Your First AI Agent in Python with the OpenAI Agents SDK
Artificial intelligence is moving beyond simple chatbots. Modern AI applications can interpret instructions, use tools, perform multiple steps, and delegate work to specialised agents. These applications are commonly called AI agents.
Python developers can build these applications with the OpenAI Agents SDK, a framework that provides components for defining agents, executing tasks, connecting tools, and coordinating multiple agents. In this tutorial, you will create a beginner-friendly AI study assistant using Python.
What Is an AI Agent?
An AI agent is a software system that uses an AI model to work towards a specified goal. Depending on its configuration, it can interpret a request, decide which tool to use, gather information, and return a response.
For example, a conventional chatbot might explain how to solve a mathematics problem. An AI agent equipped with suitable tools could also retrieve information from a permitted source, perform a calculation, or organise a study plan.
An agent's capabilities depend on its instructions, available tools, permissions, and the model powering it. An agent does not automatically have access to the internet, private files, or external applications.
What Is the OpenAI Agents SDK?
The OpenAI Agents SDK is a Python framework for developing applications that use AI agents. It provides a structured way to define an agent, run it, connect Python functions as tools, and coordinate specialised agents.
Its major building blocks include:
- Agents: AI assistants configured with instructions and optional tools.
- Runner: Executes an agent and manages its interaction cycle.
- Tools: Functions and supported integrations that allow agents to perform specific tasks.
- Handoffs: Allow one agent to transfer responsibility to another specialised agent.
- Guardrails: Help validate inputs or outputs and enforce application rules.
- Tracing: Helps developers inspect and debug agent workflows.
These features make it possible to start with a small assistant and gradually develop a more advanced AI application.
Official documentation: OpenAI Agents SDK Quickstart.
Prerequisites
Before starting, make sure you have the following:
- Python installed on your computer.
- A basic understanding of Python functions and variables.
- An OpenAI API key.
- An internet connection for API requests.
- A code editor or terminal.
You should also understand that API usage may incur charges. Check your account's current pricing and usage limits before running your application.
Step 1: Create a Python Project
Start by creating a separate folder for your AI agent project. Open your terminal and execute these commands:
mkdir ai-agent-project
cd ai-agent-project
python -m venv .venv
A virtual environment keeps the project's Python dependencies separate from other applications.
Activate the environment on Windows PowerShell:
.venv\Scripts\Activate.ps1
On macOS or Linux, use:
source .venv/bin/activate
Step 2: Install the OpenAI Agents SDK
Install the required package with pip:
pip install openai-agents
This installs the Python package needed to define and run agents. You can find installation instructions and additional examples in the official GitHub repository.
Step 3: Configure Your API Key
The SDK needs an API key to authenticate requests to OpenAI. Set the OPENAI_API_KEY environment variable before running the program.
For Windows PowerShell:
$env:OPENAI_API_KEY = "your-api-key"
For macOS or Linux:
export OPENAI_API_KEY="your-api-key"
Replace the example value with your actual API key. Obtain it through the official OpenAI API keys page.
Security tip: Never publish your API key in a blog post, upload it to a public GitHub repository, or include it in frontend JavaScript. Keep it in a secure environment variable or an appropriate secrets manager.
Step 4: Build Your First AI Agent
Now create a Python file named main.py. This first example creates an AI study assistant that explains programming concepts in simple language.
import asyncio
from agents import Agent, Runner
study_agent = Agent(
name="Python Study Assistant",
instructions=(
"You are a friendly Python tutor. "
"Explain programming concepts in simple language. "
"Use short examples when helpful. "
"If you are unsure about a fact, say so."
),
)
async def main():
result = await Runner.run(
study_agent,
"Explain Python lists with a simple example."
)
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
Run the application with:
python main.py
The program sends the question to the agent, waits for the result, and displays the final response. The exact wording will depend on the model and its response.
Understanding the Code
Agentdefines the assistant's name, instructions, and optional capabilities.Runnerexecutes the agent's task.Runner.run()is asynchronous, so it is called withawaitinside an asynchronous function.result.final_outputcontains the final answer returned by the run.asyncio.run(main())starts the asynchronous program.
This is the foundation of your first agent. It can answer questions, but it does not yet have a custom Python tool to perform a specific action.
Step 5: Give the Agent a Python Tool
One important advantage of AI agents is their ability to use tools. A tool connects the model's decision-making process to a function that performs a defined task.
For example, you can create a Python function that calculates the average of a list of marks. The agent can call this function when a user requests a calculation.
Replace the contents of main.py with the following example:
import asyncio
from agents import Agent, Runner, function_tool
@function_tool
def calculate_average(marks: list[float]) -> float:
"""Calculate the average of a list of student marks."""
if not marks:
return 0.0
return sum(marks) / len(marks)
study_agent = Agent(
name="Study Assistant",
instructions=(
"Help students understand their marks. "
"When asked to calculate an average, use "
"the calculate_average tool. "
"Explain the result clearly."
),
tools=[calculate_average],
)
async def main():
result = await Runner.run(
study_agent,
"Calculate the average of these marks: 80, 90, 70, 100."
)
print(result.final_output)
if __name__ == "__main__":
asyncio.run(main())
Run the program again:
python main.py
The expected numerical result is 85, because the sum of the four marks is 340 and dividing it by four gives 85. The agent may express the result in different words.
How Does the Tool Work?
- The user asks the agent to calculate an average.
- The agent recognises that the calculation tool is relevant.
- The SDK validates the tool arguments and invokes the Python function.
- The function calculates the average and returns the result.
- The agent uses the returned value to formulate its answer.
The @function_tool decorator makes the Python function available to the agent. Its name, description, and type information help the SDK expose the function to the model.
Always validate inputs and restrict tool permissions appropriately. For example, a tool that modifies files or sends emails should have stricter controls than a tool that performs arithmetic.
Step 6: Add More Useful Capabilities
After your first tool works, you can extend the assistant with additional functions. Consider adding these features:
- Study planner: Generate a revision schedule based on subjects and available study time.
- Quiz generator: Create practice questions for a selected topic.
- Calculator: Perform supported mathematical operations.
- Document assistant: Summarise content from files that your application is authorised to access.
- Research assistant: Use an appropriately configured search tool to retrieve information.
Each function should have a clear purpose, a precise description, and sensible input validation. Avoid giving an agent unrestricted access to your computer or sensitive data.
Step 7: Understand Multi-Agent Workflows
Some projects need more than one specialised agent. Instead of asking a single assistant to handle every task, you can create agents with different responsibilities.
For example, a learning platform could contain:
- Planner Agent: Organises the learning task.
- Research Agent: Collects relevant information using approved tools.
- Tutor Agent: Explains the material in student-friendly language.
- Review Agent: Checks the draft for clarity and completeness.
The SDK supports two useful coordination patterns. With a handoff, one agent transfers control to a specialist. With an agent-as-tool design, a coordinating agent can call another agent while retaining responsibility for the final response.
These patterns are helpful when responsibilities are genuinely different. For a small project, a single agent with a few well-designed tools is usually easier to build, test, and maintain.
Step 8: Test and Debug Your AI Agent
Getting a response does not automatically mean that your agent is reliable. Test it with a variety of normal, unusual, and invalid requests.
- Ask a question that matches the agent's intended role.
- Check whether the agent uses its tool when appropriate.
- Test empty lists, invalid values, and unexpected inputs.
- Verify calculations independently.
- Check how the agent responds when it lacks enough information.
- Inspect traces to understand model calls and tool execution.
The SDK includes tracing features that can help you understand the steps involved in a run. For production applications, also add logging, error handling, usage monitoring, and automated tests.
Common Mistakes Beginners Should Avoid
1. Forgetting the API key: Check that the environment variable is configured in the same environment where the application runs.
2. Installing the wrong package: Use pip install openai-agents for the Python Agents SDK.
3. Expecting automatic tool access: An agent can only use tools that are available and correctly configured for it.
4. Writing vague instructions: Clearly explain the agent's role, boundaries, output style, and preferred tool usage.
5. Trusting every response: AI-generated information can be incorrect. Validate important results, especially in financial, legal, medical, and other high-impact applications.
6. Giving excessive permissions: Use the least privilege necessary, and require human approval for sensitive or irreversible actions.
Where Can You Use Python AI Agents?
Once you understand the basic workflow, you can explore several practical applications:
- Customer-support assistants that use approved knowledge sources.
- AI research tools that organise information from permitted sources.
- Educational assistants that generate quizzes and explain concepts.
- Business automation systems that prepare reports or classify requests.
- Developer assistants that review code or explain programming errors.
- Document-processing applications that extract and summarise information.
For each application, define the task clearly, select the appropriate tools, protect sensitive information, and test the system before deploying it to users.
Conclusion
Building your first AI agent in Python with the OpenAI Agents SDK is a practical way to move from ordinary chatbot development to tool-enabled AI applications. You begin by defining an agent and running it, then extend its capabilities with Python functions and, when necessary, specialised agents.
The best approach is to start small. Build one useful feature, test it carefully, and improve it before introducing complex workflows. With a strong foundation in Python, tool design, validation, and debugging, you can gradually develop AI assistants for education, research, productivity, and business automation.
Next step: Explore the official Agents SDK Quickstart and Tools documentation to learn more about building reliable agent workflows.
Frequently Asked Questions
1. Is the OpenAI Agents SDK suitable for beginners?
Yes. Developers with basic Python knowledge can begin with a simple agent and add tools as they become more comfortable with the framework.
2. Do I need an API key?
For this OpenAI API-based example, yes. You need a valid API key and an account with access to the required model and API usage.
3. Can an AI agent execute Python code?
An agent can call Python functions that you expose as tools. Arbitrary code execution requires a separately configured execution environment and appropriate security controls.
4. What is the difference between an AI agent and a chatbot?
A basic chatbot primarily responds to messages. An AI agent can also use configured tools and follow a managed sequence of steps to accomplish a task.
5. Can I build a multi-agent application?
Yes. The SDK supports handoffs and agent-as-tool patterns, allowing specialised agents to cooperate on more complex tasks.
Learn how to build your first AI agent in Python with the OpenAI Agents SDK. Follow a beginner-friendly tutorial covering setup, tools, execution, and multi-agent workflows.