본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)48k · #5541

pydantic-ai

하는 일

PydanticAI는 Python으로 AI 에이전트를 만드는 도구 모음입니다. AI의 응답이 구조화되고 올바른지 보장해, 견고하고 테스트 가능한 AI 애플리케이션을 더 쉽게 만들 수 있게 합니다.

사용하는 경우

  • ✓다른 도구와 연동해야 하는 Python AI 에이전트를 만들 때.
  • ✓AI가 느슨한 글이 아니라 정리되고 검증된 데이터를 반환하기를 원할 때.
  • ✓매번 실제 AI를 호출하지 않고 AI 에이전트의 로직을 테스트하고 싶을 때.

스킬 링크

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/pydantic-ai/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/pydantic-ai/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“특정 형식의 텍스트 요약을 반환하는 Python AI 에이전트는 어떻게 만들 수 있나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

Pydantic 모델을 사용해 기대하는 응답 구조를 정의합니다. PydanticAI는 AI가 이 구조를 따르도록 하고 출력을 검증합니다. 또한 AI를 다른 도구와 연결하고 모든 것을 쉽게 테스트할 수 있게 합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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

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

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

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:

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:

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):

…
자주 묻는 질문

'Pydantic 모델'이란 무엇인가요?

기대하는 데이터 구조를 설명하기 위해 Python에서 정의하는 양식 같은 것입니다. 예를 들어 영화 데이터 양식에는 '제목', '연도', '평점' 같은 항목이 있을 수 있습니다.

'타입 안전성'은 무엇을 뜻하나요?

텍스트, 숫자, 불리언 같은 데이터 타입을 검사해 오류를 막는다는 뜻입니다. PydanticAI는 이런 안전성을 AI와의 상호작용에도 적용합니다.

비용이나 시간을 들이지 않고 AI 에이전트를 테스트하려면 어떻게 하나요?

PydanticAI는 AI 응답을 흉내 내는 테스트 모델을 사용할 수 있습니다. 비싼 AI 서비스를 실제로 호출하지 않고도 에이전트의 로직을 테스트할 수 있습니다.

상세 정보

작성자의 원본 설명

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

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#5541
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬