Create an AI Agent with PydanticAI in Minutes
Creating an AI agent might sound like a daunting task, but with modern tools like Pydantic and OpenAI, it's surprisingly straightforward. In this guide, we’ll walk through building a simple AI agent step by step. Step 1: Set Up Your Environment To begin, we’ll create a virtual environment and install the required library: pydantic-ai. A virtual environment ensures your project dependencies are isolated and manageable. python -m venv venv source venv/bin/activate # Use `venv\Scripts\activate` on Windows pip install pydantic-ai Step 2: Configure Your OpenAI API Key Before interacting with OpenAI’s models, you’ll need an API key. Set this as an environment variable to keep it secure: OPENAI_API_KEY="your_openai_api_key" Step 3: Write the Script Now, let’s create the main script for our AI agent. The agent will use a system prompt and answer user questions by leveraging OpenAI’s API. Import Libraries We’ll begin by importing the necessary modules: from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIModel Define the Model and Agent Next, define the model and create an agent instance: # define the model model = OpenAIModel("gpt-4o") # define the agent agent = Agent( model=model, system_prompt="Be concise, reply with one sentence.", ) Finally, we use the run_sync method to send a query to the agent and print the response: # run the agent result = agent.run_sync("What does AGI mean?") # print the result print("\n=== Data ===") print(result.data) # print the Usage print("\n=== usage ===") print(result.usage()) # print the Messages print("\n=== messages ===") print(result.all_messages()) Step 4: Execute the Script Run the script to see the agent in action: python your_script_name.py When executed, the agent will communicate with OpenAI’s API, process the query, and return a response. For example, if you ask, “What does AGI mean?” the agent might reply: === Data === AGI stands for Artificial General Intelligence, which refers to a machine's ability to understand, learn, and apply intelligence across any task like a human. === usage === Usage(requests=1, request_tokens=25, response_tokens=31, total_tokens=56, details={'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0, 'cached_tokens': 0}) === messages === [ModelRequest(parts=[SystemPromptPart(content='Be concise, reply with one sentence.', dynamic_ref=None, part_kind='system-prompt'), UserPromptPart(content='What does AGI mean?', timestamp=datetime.datetime(2025, 1, 18, 19, 17, 51, 503464, tzinfo=datetime.timezone.utc), part_kind='user-prompt')], kind='request'), ModelResponse(parts=[TextPart(content="AGI stands for Artificial General Intelligence, which refers to a machine's ability to understand, learn, and apply intelligence across any task like a human.", part_kind='text')], timestamp=datetime.datetime(2025, 1, 18, 19, 17, 52, tzinfo=datetime.timezone.utc), kind='response')] Conclusion In just a few lines of code, we built a functional AI agent using Pydantic and OpenAI. This setup provides a robust foundation for building more complex AI-driven applications. Whether you’re answering questions, summarizing text, or performing advanced data analysis, this simple architecture can adapt to a variety of use cases. Let us know what you’ll create with your new AI agent! Links: AI Agents Community on Skool YouTube GitHub
Creating an AI agent might sound like a daunting task, but with modern tools like Pydantic and OpenAI, it's surprisingly straightforward. In this guide, we’ll walk through building a simple AI agent step by step.
Step 1: Set Up Your Environment
To begin, we’ll create a virtual environment and install the required library: pydantic-ai. A virtual environment ensures your project dependencies are isolated and manageable.
python -m venv venv
source venv/bin/activate # Use `venv\Scripts\activate` on Windows
pip install pydantic-ai
Step 2: Configure Your OpenAI API Key
Before interacting with OpenAI’s models, you’ll need an API key. Set this as an environment variable to keep it secure:
OPENAI_API_KEY="your_openai_api_key"
Step 3: Write the Script
Now, let’s create the main script for our AI agent. The agent will use a system prompt and answer user questions by leveraging OpenAI’s API.
Import Libraries
We’ll begin by importing the necessary modules:
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
Define the Model and Agent
Next, define the model and create an agent instance:
# define the model
model = OpenAIModel("gpt-4o")
# define the agent
agent = Agent(
model=model,
system_prompt="Be concise, reply with one sentence.",
)
Finally, we use the run_sync method to send a query to the agent and print the response:
# run the agent
result = agent.run_sync("What does AGI mean?")
# print the result
print("\n=== Data ===")
print(result.data)
# print the Usage
print("\n=== usage ===")
print(result.usage())
# print the Messages
print("\n=== messages ===")
print(result.all_messages())
Step 4: Execute the Script
Run the script to see the agent in action:
python your_script_name.py
When executed, the agent will communicate with OpenAI’s API, process the query, and return a response. For example, if you ask, “What does AGI mean?” the agent might reply:
=== Data ===
AGI stands for Artificial General Intelligence, which refers to a machine's ability to understand, learn, and apply intelligence across any task like a human.
=== usage ===
Usage(requests=1, request_tokens=25, response_tokens=31, total_tokens=56, details={'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0, 'cached_tokens': 0})
=== messages ===
[ModelRequest(parts=[SystemPromptPart(content='Be concise, reply with one sentence.', dynamic_ref=None, part_kind='system-prompt'), UserPromptPart(content='What does AGI mean?', timestamp=datetime.datetime(2025, 1, 18, 19, 17, 51, 503464, tzinfo=datetime.timezone.utc), part_kind='user-prompt')], kind='request'), ModelResponse(parts=[TextPart(content="AGI stands for Artificial General Intelligence, which refers to a machine's ability to understand, learn, and apply intelligence across any task like a human.", part_kind='text')], timestamp=datetime.datetime(2025, 1, 18, 19, 17, 52, tzinfo=datetime.timezone.utc), kind='response')]
Conclusion
In just a few lines of code, we built a functional AI agent using Pydantic and OpenAI. This setup provides a robust foundation for building more complex AI-driven applications. Whether you’re answering questions, summarizing text, or performing advanced data analysis, this simple architecture can adapt to a variety of use cases.
Let us know what you’ll create with your new AI agent!