DEV Community

Kiu Subscriber for BUSINESS24.AI

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.",
)
Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode

Step 4: Execute the Script
Run the script to see the agent in action:

python your_script_name.py
Enter fullscreen mode Exit fullscreen mode

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')]
Enter fullscreen mode Exit fullscreen mode

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (1)

Collapse
 
james_antony_c5a7a1d12b51 profile image
James Antony

Real

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay