Pydantic AI
Text-to-SQL Agent with Pydantic AI
Build a natural language to SQL agent that converts questions into database queries, validates them, and returns formatted results — using Pydantic AI.
SQLdatabaseNL2SQLdata
Working Code
from pydantic_ai import Agent, RunContextfrom langchain_community.utilities import SQLDatabasefrom langchain_community.agent_toolkits import SQLDatabaseToolkit
agent = Agent( "openai:gpt-4o", system_prompt="You are a SQL analyst. Convert natural language questions into SQL queries. Only use SELECT statements. Limit results to 10 rows.",)
@agent.toolasync def list_tables(ctx: RunContext) -> str: """List all tables in the database.""" return "\n".join(inspector.get_table_names())
@agent.toolasync def run_query(ctx: RunContext, sql: str) -> str: """Execute a read-only SQL query and return results.""" if not sql.strip().upper().startswith("SELECT"): return "Error: Only SELECT queries are allowed." result = db.execute(text(sql)) rows = result.fetchmany(10) return "\n".join(str(row) for row in rows)
result = await agent.run("Show me top 5 customers by total spending this quarter")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.
Build with other frameworks
Ready to build with Pydantic AI?
Generate a production-ready project with Pydantic AI pre-configured — FastAPI + Next.js, auth, streaming, and more.
Get StartedReady to build your first production AI agent?
Open-source tools, battle-tested patterns, zero boilerplate. Configure your stack and ship in minutes — not months.