pythonintermediate

PydanticAI Structured AI Agent

Build a type-safe AI agent using PydanticAI for validated inputs, outputs, and tool definitions.

python
from pydantic_ai import Agent, RunContext
from pydantic import BaseModel
from dataclasses import dataclass

@dataclass
class Deps:
    api_key: str

class ResearchResult(BaseModel):
    topic:   str
    summary: str
    sources: list[str]
    confidence: float

agent = Agent(
    'openai:gpt-4o-mini',
    deps_type=Deps,
    result_type=ResearchResult,
    system_prompt='You are a research assistant. Provide structured summaries.',
)

@agent.tool
async def fetch_data(ctx: RunContext[Deps], topic: str) -> str:
    '''Simulate fetching data about a topic.'''
    return f'Data about {topic}: It is widely used in industry and academia.'

import asyncio

async def main():
    deps   = Deps(api_key='demo')
    result = await agent.run('Research Python asyncio', deps=deps)
    print(result.data.model_dump_json(indent=2))

asyncio.run(main())

Use Cases

  • type-safe agents
  • structured AI outputs
  • validated tools

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.