Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)48k · #5541

pydantic-ai

Skill này làm gì

PydanticAI là bộ công cụ để xây dựng agent AI bằng Python. Nó đảm bảo phản hồi của AI có cấu trúc và đúng kiểu dữ liệu, giúp dễ tạo các ứng dụng AI vững chắc và có thể kiểm thử.

Khi nào nên dùng

  • ✓Khi xây dựng agent AI bằng Python cần tương tác với các công cụ khác.
  • ✓Khi bạn muốn AI trả về dữ liệu có tổ chức và đã kiểm chứng, không chỉ là văn bản rời rạc.
  • ✓Để kiểm thử logic của agent AI mà không cần gọi AI thật mỗi lần.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/pydantic-ai/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để tạo agent AI bằng Python trả về bản tóm tắt văn bản theo một định dạng cụ thể?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Bạn định nghĩa cấu trúc phản hồi mong muốn bằng các model Pydantic. PydanticAI đảm bảo AI tuân theo cấu trúc này và kiểm tra đầu ra. Nó cũng cho phép kết nối AI với các công cụ khác và kiểm thử mọi thứ dễ dàng.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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

…
Câu hỏi thường gặp

“Pydantic models” là gì?

Đó giống như các biểu mẫu bạn định nghĩa trong Python để mô tả cấu trúc dữ liệu mong đợi. Ví dụ, một biểu mẫu dữ liệu phim có thể gồm các trường như “title”, “year” và “rating”.

“Type-safe” nghĩa là gì?

Nghĩa là code kiểm tra kiểu dữ liệu (như văn bản, số, đúng/sai) để ngăn lỗi. PydanticAI mang sự an toàn này vào các tương tác với AI.

Làm sao để kiểm thử agent AI mà không tốn tiền hay thời gian?

PydanticAI cho phép dùng các model kiểm thử mô phỏng phản hồi AI, giúp bạn kiểm tra logic của agent mà không gọi dịch vụ AI tốn kém.

Chi tiết

Mô tả gốc của tác giả

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

repo: sickn33/agentic-awesome-skills

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#5541
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự