Skip to content
Pydantic AI

Data Analysis Agent with Pydantic AI

Build an AI data analysis agent that processes datasets, runs Python computations, generates charts, and produces insights — powered by Pydantic AI.

data analysisPythonchartsanalytics

Working Code

Pydantic AI
from pydantic_ai import Agent, RunContext
agent = Agent(
"openai:gpt-4o",
system_prompt="You are a data analyst. Explore datasets using read_csv_info, then use execute_python to run analysis code. Present findings clearly with numbers.",
)
@agent.tool
async def execute_python(ctx: RunContext, code: str) -> str:
"""Execute Python code for data analysis. pandas and matplotlib are available."""
import subprocess
result = subprocess.run(
["python", "-c", code],
capture_output=True, text=True, timeout=30,
)
return result.stdout or f"Error: {result.stderr}"
@agent.tool
async def read_csv_info(ctx: RunContext, path: str) -> str:
"""Get info about a CSV file (columns, types, shape)."""
import pandas as pd
df = pd.read_csv(path)
return f"Shape: {df.shape}\nColumns: {list(df.columns)}\nTypes:\n{df.dtypes}"
result = await agent.run("Analyze sales_data.csv and find the top performing products by revenue")
print(result.output)

Step by Step

1

Install dependencies

Install Pydantic AI and the required tools for this use case.

2

Define your tools

Create the domain-specific tool functions your agent will use to interact with external services.

3

Create the agent and run

Initialize the Pydantic AI agent with your tools, set the system prompt, and execute a query.

Ready to build with Pydantic AI?

Generate a production-ready project with Pydantic AI pre-configured — FastAPI + Next.js, auth, streaming, and more.

Get Started

Ready to build your first production AI agent?

Open-source tools, battle-tested patterns, zero boilerplate. Configure your stack and ship in minutes — not months.