Agent skill

Pydantic AI

by davila7 in davila7/claude-code-templates

Build production-ready AI agents with PydanticAI — type-safe tool use, structured outputs, dependency injection, and multi-model support.

MITAuto-check passedAI & LLM Engineering

Install Pydantic AI

skills CLI
$ npx skills add davila7/claude-code-templates --skill pydantic-ai -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install davila7/claude-code-templates pydantic-ai --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/davila7/claude-code-templates.git skills-src && mkdir -p .claude/skills && cp -r skills-src/cli-tool/components/skills/ai-research/pydantic-ai .claude/skills/pydantic-ai && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
pydantic-ai
GitHub stars
33k
Used in
3 other repos
Token cost
~2.9k tokens
SKILL.md length
543 words
Files
1
Skills in repo
479
Repo updated
First seen
Licence
MIT

At a glance

Build production-ready AI agents with PydanticAI — type-safe tool use, structured outputs, dependency injection, and multi-model support.

  • Works in 8 steps: Installation → A Minimal Agent → Structured Output with Pydantic Models → …
  • Tasks that involve Structured output and tool calling
  • SKILL.md covers Overview, When to Use This Skill, How It Works and Examples, plus 4 more sections
  • Calls pip; reaches wttr.in; needs OPENAI_API_KEY and ANTHROPIC_API_KEY

What it does

Pydantic AI is an agent skill from davila7/claude-code-templates. Build production-ready AI agents with PydanticAI — type-safe tool use, structured outputs, dependency injection, and multi-model support.

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in AI & LLM Engineering, covering Structured output and tool calling, Design patterns and Type safety. It works with Pydantic AI, Pydantic and Python. The repository describes itself as: CLI tool for configuring and monitoring Claude Code. The licence is MIT.

When your agent uses it

  • Tasks that involve Structured output and tool calling
  • Tasks that involve Design patterns
  • Tasks that involve Type safety

Example prompts

  • “/pydantic-ai”

Requirements

  • Python 3
  • A credential in OPENAI_API_KEY
  • A credential in ANTHROPIC_API_KEY

Workflow steps

8 steps, taken from the step headings in SKILL.md.

  1. Installation
  2. A Minimal Agent
  3. Structured Output with Pydantic Models
  4. Tool Use
  5. Dependency Injection
  6. Testing with TestModel
  7. Streaming Responses
  8. Multi-Turn Conversations

What it can do on your machine

Read from SKILL.md and the folder at commit c0ca7da. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • pip

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • wttr.in

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • OPENAI_API_KEY
    • ANTHROPIC_API_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Pydantic AI loads about 2.9k tokens when it runs. Until then it costs about 37 tokens; SKILL.md has 543 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~37
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from davila7/claude-code-templates at commit c0ca7da, republished under its MIT licence (© davila7). 543 words, ~2,939 tokens.

Download SKILL.mdSave it as .claude/skills/pydantic-ai/SKILL.md (or your agent's skills folder).
name
pydantic-ai
description
Build production-ready AI agents with PydanticAI — type-safe tool use, structured outputs, dependency injection, and multi-model support.
category
ai-agents
risk
safe
source
community
date_added
2026-03-18
author
suhaibjanjua
tags
pydantic-ai, ai-agents, llm, openai, anthropic, gemini, tool-use, structured-output, python
tools
claude, cursor, gemini

PydanticAI — Typed AI Agents in Python

Overview

PydanticAI is a Python agent framework from the Pydantic team that brings the same type-safety and validation guarantees as Pydantic to LLM-based applications. It supports structured outputs (validated with Pydantic models), dependency injection for testability, streamed responses, multi-turn conversations, and tool use — across OpenAI, Anthropic, Google Gemini, Groq, Mistral, and Ollama. Use this skill when building production AI agents, chatbots, or LLM pipelines where correctness and testability matter.

When to Use This Skill

  • Use when building Python AI agents that call tools and return structured data
  • Use when you need validated, typed LLM outputs (not raw strings)
  • Use when you want to write unit tests for agent logic without hitting a real LLM
  • Use when switching between LLM providers without rewriting agent code
  • Use when the user asks about Agent, @agent.tool, RunContext, ModelRetry, or result_type

How It Works

Step 1: Installation
bash
pip install pydantic-ai

# Install extras for specific providers
pip install 'pydantic-ai[openai]'       # OpenAI / Azure OpenAI
pip install 'pydantic-ai[anthropic]'    # Anthropic Claude
pip install 'pydantic-ai[gemini]'       # Google Gemini
pip install 'pydantic-ai[groq]'         # Groq
pip install 'pydantic-ai[vertexai]'     # Google Vertex AI
Step 2: A Minimal Agent
python
from pydantic_ai import Agent

# Simple agent — returns a plain string
agent = Agent(
    'anthropic:claude-sonnet-4-6',
    system_prompt='You are a helpful assistant. Be concise.',
)

result = agent.run_sync('What is the capital of Japan?')
print(result.data)  # "Tokyo"
print(result.usage())  # Usage(requests=1, request_tokens=..., response_tokens=...)
Step 3: Structured Output with Pydantic Models
python
from pydantic import BaseModel
from pydantic_ai import Agent

class MovieReview(BaseModel):
    title: str
    year: int
    rating: float  # 0.0 to 10.0
    summary: str
    recommended: bool

agent = Agent(
    'openai:gpt-4o',
    result_type=MovieReview,
    system_prompt='You are a film critic. Return structured reviews.',
)

result = agent.run_sync('Review Inception (2010)')
review = result.data  # Fully typed MovieReview instance
print(f"{review.title} ({review.year}): {review.rating}/10")
print(f"Recommended: {review.recommended}")
Step 4: Tool Use

Register tools with @agent.tool — the LLM can call them during a run:

python
from pydantic_ai import Agent, RunContext
from pydantic import BaseModel
import httpx

class WeatherReport(BaseModel):
    city: str
    temperature_c: float
    condition: str

weather_agent = Agent(
    'anthropic:claude-sonnet-4-6',
    result_type=WeatherReport,
    system_prompt='Get current weather for the requested city.',
)

@weather_agent.tool
async def get_temperature(ctx: RunContext, city: str) -> dict:
    """Fetch the current temperature for a city from the weather API."""
    async with httpx.AsyncClient() as client:
        r = await client.get(f'https://wttr.in/{city}?format=j1')
        data = r.json()
        return {
            'temp_c': float(data['current_condition'][0]['temp_C']),
            'description': data['current_condition'][0]['weatherDesc'][0]['value'],
        }

import asyncio
result = asyncio.run(weather_agent.run('What is the weather in Tokyo?'))
print(result.data)
Step 5: Dependency Injection

Inject services (database, HTTP clients, config) into agents for testability:

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

@dataclass
class Deps:
    db: Database
    user_id: str

class SupportResponse(BaseModel):
    message: str
    escalate: bool

support_agent = Agent(
    'openai:gpt-4o-mini',
    deps_type=Deps,
    result_type=SupportResponse,
    system_prompt='You are a support agent. Use the tools to help customers.',
)

@support_agent.tool
async def get_order_history(ctx: RunContext[Deps]) -> list[dict]:
    """Fetch recent orders for the current user."""
    return await ctx.deps.db.get_orders(ctx.deps.user_id, limit=5)

@support_agent.tool
async def create_refund(ctx: RunContext[Deps], order_id: str, reason: str) -> dict:
    """Initiate a refund for a specific order."""
    return await ctx.deps.db.create_refund(order_id, reason, ctx.deps.user_id)

# Usage
async def handle_support(user_id: str, message: str):
    deps = Deps(db=get_db(), user_id=user_id)
    result = await support_agent.run(message, deps=deps)
    return result.data
Step 6: Testing with TestModel

Write unit tests without real LLM calls:

python
from pydantic_ai.models.test import TestModel

def test_support_agent_escalates():
    with support_agent.override(model=TestModel()):
        # TestModel returns a minimal valid response matching result_type
        result = support_agent.run_sync(
            'I want to cancel my account',
            deps=Deps(db=FakeDb(), user_id='user-123'),
        )
    # Test the structure, not the LLM's exact words
    assert isinstance(result.data, SupportResponse)
    assert isinstance(result.data.escalate, bool)

FunctionModel for deterministic test responses:

python
from pydantic_ai.models.function import FunctionModel, ModelContext

def my_model(messages, info):
    return ModelResponse(parts=[TextPart('Always this response')])

with agent.override(model=FunctionModel(my_model)):
    result = agent.run_sync('anything')
Step 7: Streaming Responses
python
import asyncio
from pydantic_ai import Agent

agent = Agent('anthropic:claude-sonnet-4-6')

async def stream_response():
    async with agent.run_stream('Write a haiku about Python') as result:
        async for chunk in result.stream_text():
            print(chunk, end='', flush=True)
    print()  # newline
    print(f"Total tokens: {result.usage()}")

asyncio.run(stream_response())
Step 8: Multi-Turn Conversations
python
from pydantic_ai import Agent
from pydantic_ai.messages import ModelMessagesTypeAdapter

agent = Agent('openai:gpt-4o', system_prompt='You are a helpful assistant.')

# First turn
result1 = agent.run_sync('My name is Alice.')
history = result1.all_messages()

# Second turn — passes conversation history
result2 = agent.run_sync('What is my name?', message_history=history)
print(result2.data)  # "Your name is Alice."

Examples

Example 1: Code Review Agent
python
from pydantic import BaseModel, Field
from pydantic_ai import Agent
from typing import Literal

class CodeReview(BaseModel):
    quality: Literal['excellent', 'good', 'needs_work', 'poor']
    issues: list[str] = Field(default_factory=list)
    suggestions: list[str] = Field(default_factory=list)
    approved: bool

code_review_agent = Agent(
    'anthropic:claude-sonnet-4-6',
    result_type=CodeReview,
    system_prompt="""
    You are a senior engineer performing code review.
    Evaluate code quality, identify issues, and provide actionable suggestions.
    Set approved=True only for good or excellent quality code with no security issues.
    """,
)

def review_code(diff: str) -> CodeReview:
    result = code_review_agent.run_sync(f"Review this code:\n\n{diff}")
    return result.data
Example 2: Agent with Retry Logic
python
from pydantic_ai import Agent, ModelRetry
from pydantic import BaseModel, field_validator

class StrictJson(BaseModel):
    value: int

    @field_validator('value')
    def must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('value must be positive')
        return v

agent = Agent('openai:gpt-4o-mini', result_type=StrictJson)

@agent.result_validator
async def validate_result(ctx, result: StrictJson) -> StrictJson:
    if result.value > 1000:
        raise ModelRetry('Value must be under 1000. Try again with a smaller number.')
    return result
Example 3: Multi-Agent Pipeline
python
from pydantic_ai import Agent
from pydantic import BaseModel

class ResearchSummary(BaseModel):
    key_points: list[str]
    conclusion: str

class BlogPost(BaseModel):
    title: str
    body: str
    meta_description: str

researcher = Agent('openai:gpt-4o', result_type=ResearchSummary)
writer = Agent('anthropic:claude-sonnet-4-6', result_type=BlogPost)

async def research_and_write(topic: str) -> BlogPost:
    # Stage 1: research
    research = await researcher.run(f'Research the topic: {topic}')

    # Stage 2: write based on research
    post = await writer.run(
        f'Write a blog post about: {topic}\n\nResearch:\n' +
        '\n'.join(f'- {p}' for p in research.data.key_points) +
        f'\n\nConclusion: {research.data.conclusion}'
    )
    return post.data

Best Practices

  • ✅ Always define result_type with a Pydantic model — avoid returning raw strings in production
  • ✅ Use deps_type with a dataclass for dependency injection — makes agents testable
  • ✅ Use TestModel in unit tests — never hit a real LLM in CI
  • ✅ Add @agent.result_validator for business-logic checks beyond Pydantic validation
  • ✅ Use run_stream for long outputs in user-facing applications to show progressive results
  • ❌ Don't put secrets (API keys) in Agent() arguments — use environment variables
  • ❌ Don't share a single Agent instance across async tasks if deps differ — create per-request instances or use agent.run() with per-call deps
  • ❌ Don't catch ValidationError broadly — let PydanticAI retry with ModelRetry for recoverable LLM output errors
Show full SKILL.md (208 more words)Show less

Security & Safety Notes

  • Set API keys via environment variables (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.) — never hardcode them.
  • Validate all tool inputs before passing to external systems — use Pydantic models or manual checks.
  • Tools that mutate data (write to DB, send emails, call payment APIs) should require explicit user confirmation before the agent invokes them in production.
  • Log result.all_messages() for audit trails when agents perform consequential actions.
  • Set retries= limits on Agent() to prevent runaway loops on persistent validation failures.

Common Pitfalls

  • Problem: ValidationError on every LLM response — structured output never validates Solution: Simplify result_type fields. Use Optional and default where appropriate. The model may struggle with overly strict schemas.

  • Problem: Tool is never called by the LLM Solution: Write a clear, specific docstring for the tool function — PydanticAI sends the docstring as the tool description to the LLM.

  • Problem: RunContext dependency is None inside a tool Solution: Pass deps= when calling agent.run() or agent.run_sync(). Dependencies are not set globally.

  • Problem: asyncio.run() error when calling agent.run() inside FastAPI Solution: Use await agent.run() directly in async FastAPI route handlers — don't wrap in asyncio.run().

  • @langchain-architecture — Alternative Python AI framework (more flexible, less type-safe)
  • @llm-application-dev-ai-assistant — General LLM application development patterns
  • @fastapi-templates — Serving PydanticAI agents via FastAPI endpoints
  • @agent-orchestration-multi-agent-optimize — Orchestrating multiple PydanticAI agents

© davila7, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in cli-tool/components/skills/ai-research/pydantic-ai of davila7/claude-code-templates.

Open the folder on GitHubat commit c0ca7da

Used in 3 other repositories

We found 12 copies of this SKILL.md (exact, near-identical or edited) in other folders, from 3 other GitHub owners. This page covers the copy in davila7/claude-code-templates, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Pydantic AI next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Pydantic AI compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Pydantic AI this skilldavila7/claude-code-templates33k3 repos~2.9kAutomated safety check: PassMIT
Pydantic AIdiegosouzapw/awesome-omni-skills159—~3.2kAutomated safety check: PassMIT
Building Pydantic AI Agentsdocling-project/docling69k—~2.8kAutomated safety check: PassMIT
Outlines Structured GenerationOrchestra-Research/AI-Research-SKILLs13k9 repos~4kAutomated safety check: PassMIT
Building Pydantic AI Agentspydantic/skills140—~5.4kAutomated safety check: PassMIT
Pydanticaimagnus919/agent-skills115—~4.3kAutomated safety check: PassMIT

Similar skills

  • Pydantic AI

    diegosouzapw/awesome-omni-skills

    PydanticAI — Typed AI Agents in Python workflow skill. An agent skill from diegosouzapw/awesome-omni-skills.

    159 GitHub stars~3.2k tokensUpdated 3 mo ago
    AI & LLM EngineeringAuto-check passed
  • Building Pydantic AI Agents

    docling-project/docling

    Patterns and tested examples for building agents with Pydantic AI: tools, capabilities, structured output, dependency injection, hooks, YAML specs, streaming and testing.

    69k GitHub stars~2.8k tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • Outlines Structured Generation

    Orchestra-Research/AI-Research-SKILLs

    Uses the Outlines library to constrain model output to a JSON schema, Pydantic model, regex or fixed set of choices when running local models.

    13k GitHub starsUsed in 9 repos~4k tokens
    AI & LLM EngineeringAuto-check passed
  • Official

    Build AI agents with Pydantic AI — tools, capabilities (including on-demand loading), structured output, streaming, testing, and multi-agent patterns.

    140 GitHub stars~5.4k tokensUpdated 9 days ago
    AI & LLM EngineeringAuto-check passed
  • Pydanticai

    magnus919/agent-skills

    Build type-safe AI agents and graph-based workflows with PydanticAI and PydanticGraph.

    115 GitHub stars~4.3k tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • Mastering Python Skill

    SpillwaveSolutions/agent-brain

    Modern Python coaching covering language foundations through advanced production patterns.

    119 GitHub stars~1.4k tokensUpdated 20 days ago
    DevelopmentAuto-check: notes

More from davila7/claude-code-templates

All 479 skills in this repo
  • Perplexity Web Search

    davila7/claude-code-templates

    Runs web-grounded searches through Perplexity's Sonar models over OpenRouter for current events, recent literature and cited facts beyond the model's training cutoff.

    33k GitHub starsUsed in 11 repos~3.5k tokens
    Auto-check: notes
  • Neuropixels Data Analysis

    davila7/claude-code-templates

    Analyzes Neuropixels recordings from SpikeGLX or Open Ephys through preprocessing, drift correction, Kilosort4 spike sorting, quality metrics and curation.

    33k GitHub starsUsed in 9 repos~2.8k tokens
    Auto-check passed
  • Scientific Venue Templates

    davila7/claude-code-templates

    Supplies LaTeX templates and formatting rules for journals, conferences, posters, and grant proposals, then can check a draft against them.

    33k GitHub starsUsed in 9 repos~5.1k tokens
    Auto-check: notes
  • Brand Voice Content Creator

    davila7/claude-code-templates

    Analyzes a brand's existing writing to lock in a consistent voice, then builds SEO blog posts and platform-specific social content around it.

    33k GitHub starsUsed in 3 repos~1.9k tokens
    Auto-check passed
  • CAPA Officer

    davila7/claude-code-templates

    Guides corrective and preventive action (CAPA) work in a quality management system, from initiation and root cause analysis through effectiveness verification.

    33k GitHub starsUsed in 1 repo~2k tokens
    Auto-check passed
  • Fda Consultant Specialist

    davila7/claude-code-templates

    Senior FDA consultant and specialist for medical device companies including HIPAA compliance and requirement management.

    33k GitHub starsUsed in 1 repo~2.7k tokens
    Auto-check passed

Questions about Pydantic AI

What does Pydantic AI do?

Build production-ready AI agents with PydanticAI — type-safe tool use, structured outputs, dependency injection, and multi-model support. Pydantic AI is an agent skill from davila7/claude-code-templates. Build production-ready AI agents with PydanticAI — type-safe tool use, structured outputs, dependency injection, and multi-model support.

When should I use Pydantic AI?

Pydantic AI fits situations like: tasks that involve Structured output and tool calling; tasks that involve Design patterns; tasks that involve Type safety.

How do I install Pydantic AI in Claude Code?

Run `npx skills add davila7/claude-code-templates --skill pydantic-ai -a claude-code`. Or copy the skill folder (cli-tool/components/skills/ai-research/pydantic-ai in davila7/claude-code-templates) into .claude/skills/pydantic-ai in your project. Claude Code loads it when a task matches its description.

How do I install Pydantic AI in Codex?

Run `npx skills add davila7/claude-code-templates --skill pydantic-ai -a codex`. Or copy the skill folder (cli-tool/components/skills/ai-research/pydantic-ai in davila7/claude-code-templates) into .agents/skills/pydantic-ai in your project. Codex loads it when a task matches its description.

Can I use Pydantic AI in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add davila7/claude-code-templates --skill pydantic-ai -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/pydantic-ai, .gemini/skills/pydantic-ai, .github/skills/pydantic-ai and .opencode/skills/pydantic-ai in your project.

What does Pydantic AI need to run?

Going by SKILL.md and its folder, Pydantic AI needs the command-line tools its instructions call (pip) and credentials named OPENAI_API_KEY and ANTHROPIC_API_KEY. Our summary lists: Python 3; A credential in OPENAI_API_KEY; A credential in ANTHROPIC_API_KEY.

Does Pydantic AI access the network?

SKILL.md names 1 domain. In commands or code: wttr.in; the agent is likely to contact it when it follows the instructions. This is read from the text; nothing was executed.

Is Pydantic AI safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Pydantic AI use?

Pydantic AI is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Pydantic AI use?

About 2.9k tokens (SKILL.md is roughly 12k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Pydantic AI?

Skills that share tags, products or a category with Pydantic AI: Pydantic AI (diegosouzapw/awesome-omni-skills, 159 stars), Building Pydantic AI Agents (docling-project/docling, 69k stars), Outlines Structured Generation (Orchestra-Research/AI-Research-SKILLs, 13k stars) and Building Pydantic AI Agents (pydantic/skills, 140 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Pydantic AI?

davila7 (a GitHub user) maintains it in davila7/claude-code-templates, which has 32,512 GitHub stars. The repository holds 479 skills in this directory. The repository was last updated on October 10, 2026.

Source: davila7/claude-code-templates on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.