[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7C355A44F9KAS6KMTJ23SQC":3,"skill-same:01M7C355A44F9KAS6KMTJ23SQC":63},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":45,"ownerHtmlUrl":46,"ownerBlogUrl":6,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M7C355A44F9KAS6KMTJ23SQC","pydantic-ai",null,"Build production-ready AI agents with PydanticAI — type-safe tool use, structured outputs, dependency injection, and multi-model support.","YYC-Cube\u002FYYC3-Knowledge-Base","YYC-Cube","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F235006543?v=4","01M79J2PH4SWD2X0825X6PN748","yyc3","01M79J2PHVK3F6ZBYT8K2SCZCW",1,"MIT","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Skills-技能包\u002FYYC3-Skills-技能包-antigravity-awesome-skills\u002Fplugins\u002Fantigravity-awesome-skills-claude\u002Fskills\u002Fpydantic-ai\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: pydantic-ai\ndescription: \"Build production-ready AI agents with PydanticAI — type-safe tool use, structured outputs, dependency injection, and multi-model support.\"\ncategory: ai-agents\nrisk: safe\nsource: community\ndate_added: \"2026-03-18\"\nauthor: suhaibjanjua\ntags: [pydantic-ai, ai-agents, llm, openai, anthropic, gemini, tool-use, structured-output, python]\ntools: [claude, cursor, gemini]\n---\n\n# PydanticAI — Typed AI Agents in Python\n\n## Overview\n\nPydanticAI 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.\n\n## When to Use This Skill\n\n- Use when building Python AI agents that call tools and return structured data\n- Use when you need validated, typed LLM outputs (not raw strings)\n- Use when you want to write unit tests for agent logic without hitting a real LLM\n- Use when switching between LLM providers without rewriting agent code\n- Use when the user asks about `Agent`, `@agent.tool`, `RunContext`, `ModelRetry`, or `result_type`\n\n## How It Works\n\n### Step 1: Installation\n\n```bash\npip install pydantic-ai\n\n# Install extras for specific providers\npip install 'pydantic-ai[openai]'       # OpenAI \u002F Azure OpenAI\npip install 'pydantic-ai[anthropic]'    # Anthropic Claude\npip install 'pydantic-ai[gemini]'       # Google Gemini\npip install 'pydantic-ai[groq]'         # Groq\npip install 'pydantic-ai[vertexai]'     # Google Vertex AI\n```\n\n### Step 2: A Minimal Agent\n\n```python\nfrom pydantic_ai import Agent\n\n# Simple agent — returns a plain string\nagent = Agent(\n    'anthropic:claude-sonnet-4-6',\n    system_prompt='You are a helpful assistant. Be concise.',\n)\n\nresult = agent.run_sync('What is the capital of Japan?')\nprint(result.data)  # \"Tokyo\"\nprint(result.usage())  # Usage(requests=1, request_tokens=..., response_tokens=...)\n```\n\n### Step 3: Structured Output with Pydantic Models\n\n```python\nfrom pydantic import BaseModel\nfrom pydantic_ai import Agent\n\nclass MovieReview(BaseModel):\n    title: str\n    year: int\n    rating: float  # 0.0 to 10.0\n    summary: str\n    recommended: bool\n\nagent = Agent(\n    'openai:gpt-4o',\n    result_type=MovieReview,\n    system_prompt='You are a film critic. Return structured reviews.',\n)\n\nresult = agent.run_sync('Review Inception (2010)')\nreview = result.data  # Fully typed MovieReview instance\nprint(f\"{review.title} ({review.year}): {review.rating}\u002F10\")\nprint(f\"Recommended: {review.recommended}\")\n```\n\n### Step 4: Tool Use\n\nRegister tools with `@agent.tool` — the LLM can call them during a run:\n\n```python\nfrom pydantic_ai import Agent, RunContext\nfrom pydantic import BaseModel\nimport httpx\n\nclass WeatherReport(BaseModel):\n    city: str\n    temperature_c: float\n    condition: str\n\nweather_agent = Agent(\n    'anthropic:claude-sonnet-4-6',\n    result_type=WeatherReport,\n    system_prompt='Get current weather for the requested city.',\n)\n\n@weather_agent.tool\nasync def get_temperature(ctx: RunContext, city: str) -> dict:\n    \"\"\"Fetch the current temperature for a city from the weather API.\"\"\"\n    async with httpx.AsyncClient() as client:\n        r = await client.get(f'https:\u002F\u002Fwttr.in\u002F{city}?format=j1')\n        data = r.json()\n        return {\n            'temp_c': float(data['current_condition'][0]['temp_C']),\n            'description': data['current_condition'][0]['weatherDesc'][0]['value'],\n        }\n\nimport asyncio\nresult = asyncio.run(weather_agent.run('What is the weather in Tokyo?'))\nprint(result.data)\n```\n\n### Step 5: Dependency Injection\n\nInject services (database, HTTP clients, config) into agents for testability:\n\n```python\nfrom dataclasses import dataclass\nfrom pydantic_ai import Agent, RunContext\nfrom pydantic import BaseModel\n\n@dataclass\nclass Deps:\n    db: Database\n    user_id: str\n\nclass SupportResponse(BaseModel):\n    message: str\n    escalate: bool\n\nsupport_agent = Agent(\n    'openai:gpt-4o-mini',\n    deps_type=Deps,\n    result_type=SupportResponse,\n    system_prompt='You are a support agent. Use the tools to help customers.',\n)\n\n@support_agent.tool\nasync def get_order_history(ctx: RunContext[Deps]) -> list[dict]:\n    \"\"\"Fetch recent orders for the current user.\"\"\"\n    return await ctx.deps.db.get_orders(ctx.deps.user_id, limit=5)\n\n@support_agent.tool\nasync def create_refund(ctx: RunContext[Deps], order_id: str, reason: str) -> dict:\n    \"\"\"Initiate a refund for a specific order.\"\"\"\n    return await ctx.deps.db.create_refund(order_id, reason, ctx.deps.user_id)\n\n# Usage\nasync def handle_support(user_id: str, message: str):\n    deps = Deps(db=get_db(), user_id=user_id)\n    result = await support_agent.run(message, deps=deps)\n    return result.data\n```\n\n### Step 6: Testing with TestModel\n\nWrite unit tests without real LLM calls:\n\n```python\nfrom pydantic_ai.models.test import TestModel\n\ndef test_support_agent_escalates():\n    with support_agent.override(model=TestModel()):\n        # TestModel returns a minimal valid response matching result_type\n        result = support_agent.run_sync(\n            'I want to cancel my account',\n            deps=Deps(db=FakeDb(), user_id='user-123'),\n        )\n    # Test the structure, not the LLM's exact words\n    assert isinstance(result.data, SupportResponse)\n    assert isinstance(result.data.escalate, bool)\n```\n\n**FunctionModel** for deterministic test responses:\n\n```python\nfrom pydantic_ai.models.function import FunctionModel, ModelContext\n\ndef my_model(messages, info):\n    return ModelResponse(parts=[TextPart('Always this response')])\n\nwith agent.override(model=FunctionModel(my_model)):\n    result = agent.run_sync('anything')\n```\n\n### Step 7: Streaming Responses\n\n```python\nimport asyncio\nfrom pydantic_ai import Agent\n\nagent = Agent('anthropic:claude-sonnet-4-6')\n\nasync def stream_response():\n    async with agent.run_stream('Write a haiku about Python') as result:\n        async for chunk in result.stream_text():\n            print(chunk, end='', flush=True)\n    print()  # newline\n    print(f\"Total tokens: {result.usage()}\")\n\nasyncio.run(stream_response())\n```\n\n### Step 8: Multi-Turn Conversations\n\n```python\nfrom pydantic_ai import Agent\nfrom pydantic_ai.messages import ModelMessagesTypeAdapter\n\nagent = Agent('openai:gpt-4o', system_prompt='You are a helpful assistant.')\n\n# First turn\nresult1 = agent.run_sync('My name is Alice.')\nhistory = result1.all_messages()\n\n# Second turn — passes conversation history\nresult2 = agent.run_sync('What is my name?', message_history=history)\nprint(result2.data)  # \"Your name is Alice.\"\n```\n\n## Examples\n\n### Example 1: Code Review Agent\n\n```python\nfrom pydantic import BaseModel, Field\nfrom pydantic_ai import Agent\nfrom typing import Literal\n\nclass CodeReview(BaseModel):\n    quality: Literal['excellent', 'good', 'needs_work', 'poor']\n    issues: list[str] = Field(default_factory=list)\n    suggestions: list[str] = Field(default_factory=list)\n    approved: bool\n\ncode_review_agent = Agent(\n    'anthropic:claude-sonnet-4-6',\n    result_type=CodeReview,\n    system_prompt=\"\"\"\n    You are a senior engineer performing code review.\n    Evaluate code quality, identify issues, and provide actionable suggestions.\n    Set approved=True only for good or excellent quality code with no security issues.\n    \"\"\",\n)\n\ndef review_code(diff: str) -> CodeReview:\n    result = code_review_agent.run_sync(f\"Review this code:\\n\\n{diff}\")\n    return result.data\n```\n\n### Example 2: Agent with Retry Logic\n\n```python\nfrom pydantic_ai import Agent, ModelRetry\nfrom pydantic import BaseModel, field_validator\n\nclass StrictJson(BaseModel):\n    value: int\n\n    @field_validator('value')\n    def must_be_positive(cls, v):\n        if v \u003C= 0:\n            raise ValueError('value must be positive')\n        return v\n\nagent = Agent('openai:gpt-4o-mini', result_type=StrictJson)\n\n@agent.result_validator\nasync def validate_result(ctx, result: StrictJson) -> StrictJson:\n    if result.value > 1000:\n        raise ModelRetry('Value must be under 1000. Try again with a smaller number.')\n    return result\n```\n\n### Example 3: Multi-Agent Pipeline\n\n```python\nfrom pydantic_ai import Agent\nfrom pydantic import BaseModel\n\nclass ResearchSummary(BaseModel):\n    key_points: list[str]\n    conclusion: str\n\nclass BlogPost(BaseModel):\n    title: str\n    body: str\n    meta_description: str\n\nresearcher = Agent('openai:gpt-4o', result_type=ResearchSummary)\nwriter = Agent('anthropic:claude-sonnet-4-6', result_type=BlogPost)\n\nasync def research_and_write(topic: str) -> BlogPost:\n    # Stage 1: research\n    research = await researcher.run(f'Research the topic: {topic}')\n\n    # Stage 2: write based on research\n    post = await writer.run(\n        f'Write a blog post about: {topic}\\n\\nResearch:\\n' +\n        '\\n'.join(f'- {p}' for p in research.data.key_points) +\n        f'\\n\\nConclusion: {research.data.conclusion}'\n    )\n    return post.data\n```\n\n## Best Practices\n\n- ✅ Always define `result_type` with a Pydantic model — avoid returning raw strings in production\n- ✅ Use `deps_type` with a dataclass for dependency injection — makes agents testable\n- ✅ Use `TestModel` in unit tests — never hit a real LLM in CI\n- ✅ Add `@agent.result_validator` for business-logic checks beyond Pydantic validation\n- ✅ Use `run_stream` for long outputs in user-facing applications to show progressive results\n- ❌ Don't put secrets (API keys) in `Agent()` arguments — use environment variables\n- ❌ 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`\n- ❌ Don't catch `ValidationError` broadly — let PydanticAI retry with `ModelRetry` for recoverable LLM output errors\n\n## Security & Safety Notes\n\n- Set API keys via environment variables (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, etc.) — never hardcode them.\n- Validate all tool inputs before passing to external systems — use Pydantic models or manual checks.\n- Tools that mutate data (write to DB, send emails, call payment APIs) should require explicit user confirmation before the agent invokes them in production.\n- Log `result.all_messages()` for audit trails when agents perform consequential actions.\n- Set `retries=` limits on `Agent()` to prevent runaway loops on persistent validation failures.\n\n## Common Pitfalls\n\n- **Problem:** `ValidationError` on every LLM response — structured output never validates\n  **Solution:** Simplify `result_type` fields. Use `Optional` and `default` where appropriate. The model may struggle with overly strict schemas.\n\n- **Problem:** Tool is never called by the LLM\n  **Solution:** Write a clear, specific docstring for the tool function — PydanticAI sends the docstring as the tool description to the LLM.\n\n- **Problem:** `RunContext` dependency is `None` inside a tool\n  **Solution:** Pass `deps=` when calling `agent.run()` or `agent.run_sync()`. Dependencies are not set globally.\n\n- **Problem:** `asyncio.run()` error when calling `agent.run()` inside FastAPI\n  **Solution:** Use `await agent.run()` directly in async FastAPI route handlers — don't wrap in `asyncio.run()`.\n\n## Related Skills\n\n- `@langchain-architecture` — Alternative Python AI framework (more flexible, less type-safe)\n- `@llm-application-dev-ai-assistant` — General LLM application development patterns\n- `@fastapi-templates` — Serving PydanticAI agents via FastAPI endpoints\n- `@agent-orchestration-multi-agent-optimize` — Orchestrating multiple PydanticAI agents\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","# PydanticAI — Typed AI Agents in Python\n\n## Overview\n\nPydanticAI 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.\n\n## When to Use This Skill\n\n- Use when building Python AI agents that call tools and return structured data\n- Use when you need validated, typed LLM outputs (not raw strings)\n- Use when you want to write unit tests for agent logic without hitting a real LLM\n- Use when switching between LLM providers without rewriting agent code\n- Use when the user asks about `Agent`, `@agent.tool`, `RunContext`, `ModelRetry`, or `result_type`\n\n## How It Works\n\n### Step 1: Installation\n\n```bash\npip install pydantic-ai\n\n# Install extras for specific providers\npip install 'pydantic-ai[openai]'       # OpenAI \u002F Azure OpenAI\npip install 'pydantic-ai[anthropic]'    # Anthropic Claude\npip install 'pydantic-ai[gemini]'       # Google Gemini\npip install 'pydantic-ai[groq]'         # Groq\npip install 'pydantic-ai[vertexai]'     # Google Vertex AI\n```\n\n### Step 2: A Minimal Agent\n\n```python\nfrom pydantic_ai import Agent\n\n# Simple agent — returns a plain string\nagent = Agent(\n    'anthropic:claude-sonnet-4-6',\n    system_prompt='You are a helpful assistant. Be concise.',\n)\n\nresult = agent.run_sync('What is the capital of Japan?')\nprint(result.data)  # \"Tokyo\"\nprint(result.usage())  # Usage(requests=1, request_tokens=..., response_tokens=...)\n```\n\n### Step 3: Structured Output with Pydantic Models\n\n```python\nfrom pydantic import BaseModel\nfrom pydantic_ai import Agent\n\nclass MovieReview(BaseModel):\n    title: str\n    year: int\n    rating: float  # 0.0 to 10.0\n    summary: str\n    recommended: bool\n\nagent = Agent(\n    'openai:gpt-4o',\n    result_type=MovieReview,\n    system_prompt='You are a film critic. Return structured reviews.',\n)\n\nresult = agent.run_sync('Review Inception (2010)')\nreview = result.data  # Fully typed MovieReview instance\nprint(f\"{review.title} ({review.year}): {review.rating}\u002F10\")\nprint(f\"Recommended: {review.recommended}\")\n```\n\n### Step 4: Tool Use\n\nRegister tools with `@agent.tool` — the LLM can call them during a run:\n\n```python\nfrom pydantic_ai import Agent, RunContext\nfrom pydantic import BaseModel\nimport httpx\n\nclass WeatherReport(BaseModel):\n    city: str\n    temperature_c: float\n    condition: str\n\nweather_agent = Agent(\n    'anthropic:claude-sonnet-4-6',\n    result_type=WeatherReport,\n    system_prompt='Get current weather for the requested city.',\n)\n\n@weather_agent.tool\nasync def get_temperature(ctx: RunContext, city: str) -> dict:\n    \"\"\"Fetch the current temperature for a city from the weather API.\"\"\"\n    async with httpx.AsyncClient() as client:\n        r = await client.get(f'https:\u002F\u002Fwttr.in\u002F{city}?format=j1')\n        data = r.json()\n        return {\n            'temp_c': float(data['current_condition'][0]['temp_C']),\n            'description': data['current_condition'][0]['weatherDesc'][0]['value'],\n        }\n\nimport asyncio\nresult = asyncio.run(weather_agent.run('What is the weather in Tokyo?'))\nprint(result.data)\n```\n\n### Step 5: Dependency Injection\n\nInject services (database, HTTP clients, config) into agents for testability:\n\n```python\nfrom dataclasses import dataclass\nfrom pydantic_ai import Agent, RunContext\nfrom pydantic import BaseModel\n\n@dataclass\nclass Deps:\n    db: Database\n    user_id: str\n\nclass SupportResponse(BaseModel):\n    message: str\n    escalate: bool\n\nsupport_agent = Agent(\n    'openai:gpt-4o-mini',\n    deps_type=Deps,\n    result_type=SupportResponse,\n    system_prompt='You are a support agent. Use the tools to help customers.',\n)\n\n@support_agent.tool\nasync def get_order_history(ctx: RunContext[Deps]) -> list[dict]:\n    \"\"\"Fetch recent orders for the current user.\"\"\"\n    return await ctx.deps.db.get_orders(ctx.deps.user_id, limit=5)\n\n@support_agent.tool\nasync def create_refund(ctx: RunContext[Deps], order_id: str, reason: str) -> dict:\n    \"\"\"Initiate a refund for a specific order.\"\"\"\n    return await ctx.deps.db.create_refund(order_id, reason, ctx.deps.user_id)\n\n# Usage\nasync def handle_support(user_id: str, message: str):\n    deps = Deps(db=get_db(), user_id=user_id)\n    result = await support_agent.run(message, deps=deps)\n    return result.data\n```\n\n### Step 6: Testing with TestModel\n\nWrite unit tests without real LLM calls:\n\n```python\nfrom pydantic_ai.models.test import TestModel\n\ndef test_support_agent_escalates():\n    with support_agent.override(model=TestModel()):\n        # TestModel returns a minimal valid response matching result_type\n        result = support_agent.run_sync(\n            'I want to cancel my account',\n            deps=Deps(db=FakeDb(), user_id='user-123'),\n        )\n    # Test the structure, not the LLM's exact words\n    assert isinstance(result.data, SupportResponse)\n    assert isinstance(result.data.escalate, bool)\n```\n\n**FunctionModel** for deterministic test responses:\n\n```python\nfrom pydantic_ai.models.function import FunctionModel, ModelContext\n\ndef my_model(messages, info):\n    return ModelResponse(parts=[TextPart('Always this response')])\n\nwith agent.override(model=FunctionModel(my_model)):\n    result = agent.run_sync('anything')\n```\n\n### Step 7: Streaming Responses\n\n```python\nimport asyncio\nfrom pydantic_ai import Agent\n\nagent = Agent('anthropic:claude-sonnet-4-6')\n\nasync def stream_response():\n    async with agent.run_stream('Write a haiku about Python') as result:\n        async for chunk in result.stream_text():\n            print(chunk, end='', flush=True)\n    print()  # newline\n    print(f\"Total tokens: {result.usage()}\")\n\nasyncio.run(stream_response())\n```\n\n### Step 8: Multi-Turn Conversations\n\n```python\nfrom pydantic_ai import Agent\nfrom pydantic_ai.messages import ModelMessagesTypeAdapter\n\nagent = Agent('openai:gpt-4o', system_prompt='You are a helpful assistant.')\n\n# First turn\nresult1 = agent.run_sync('My name is Alice.')\nhistory = result1.all_messages()\n\n# Second turn — passes conversation history\nresult2 = agent.run_sync('What is my name?', message_history=history)\nprint(result2.data)  # \"Your name is Alice.\"\n```\n\n## Examples\n\n### Example 1: Code Review Agent\n\n```python\nfrom pydantic import BaseModel, Field\nfrom pydantic_ai import Agent\nfrom typing import Literal\n\nclass CodeReview(BaseModel):\n    quality: Literal['excellent', 'good', 'needs_work', 'poor']\n    issues: list[str] = Field(default_factory=list)\n    suggestions: list[str] = Field(default_factory=list)\n    approved: bool\n\ncode_review_agent = Agent(\n    'anthropic:claude-sonnet-4-6',\n    result_type=CodeReview,\n    system_prompt=\"\"\"\n    You are a senior engineer performing code review.\n    Evaluate code quality, identify issues, and provide actionable suggestions.\n    Set approved=True only for good or excellent quality code with no security issues.\n    \"\"\",\n)\n\ndef review_code(diff: str) -> CodeReview:\n    result = code_review_agent.run_sync(f\"Review this code:\\n\\n{diff}\")\n    return result.data\n```\n\n### Example 2: Agent with Retry Logic\n\n```python\nfrom pydantic_ai import Agent, ModelRetry\nfrom pydantic import BaseModel, field_validator\n\nclass StrictJson(BaseModel):\n    value: int\n\n    @field_validator('value')\n    def must_be_positive(cls, v):\n        if v \u003C= 0:\n            raise ValueError('value must be positive')\n        return v\n\nagent = Agent('openai:gpt-4o-mini', result_type=StrictJson)\n\n@agent.result_validator\nasync def validate_result(ctx, result: StrictJson) -> StrictJson:\n    if result.value > 1000:\n        raise ModelRetry('Value must be under 1000. Try again with a smaller number.')\n    return result\n```\n\n### Example 3: Multi-Agent Pipeline\n\n```python\nfrom pydantic_ai import Agent\nfrom pydantic import BaseModel\n\nclass ResearchSummary(BaseModel):\n    key_points: list[str]\n    conclusion: str\n\nclass BlogPost(BaseModel):\n    title: str\n    body: str\n    meta_description: str\n\nresearcher = Agent('openai:gpt-4o', result_type=ResearchSummary)\nwriter = Agent('anthropic:claude-sonnet-4-6', result_type=BlogPost)\n\nasync def research_and_write(topic: str) -> BlogPost:\n    # Stage 1: research\n    research = await researcher.run(f'Research the topic: {topic}')\n\n    # Stage 2: write based on research\n    post = await writer.run(\n        f'Write a blog post about: {topic}\\n\\nResearch:\\n' +\n        '\\n'.join(f'- {p}' for p in research.data.key_points) +\n        f'\\n\\nConclusion: {research.data.conclusion}'\n    )\n    return post.data\n```\n\n## Best Practices\n\n- ✅ Always define `result_type` with a Pydantic model — avoid returning raw strings in production\n- ✅ Use `deps_type` with a dataclass for dependency injection — makes agents testable\n- ✅ Use `TestModel` in unit tests — never hit a real LLM in CI\n- ✅ Add `@agent.result_validator` for business-logic checks beyond Pydantic validation\n- ✅ Use `run_stream` for long outputs in user-facing applications to show progressive results\n- ❌ Don't put secrets (API keys) in `Agent()` arguments — use environment variables\n- ❌ 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`\n- ❌ Don't catch `ValidationError` broadly — let PydanticAI retry with `ModelRetry` for recoverable LLM output errors\n\n## Security & Safety Notes\n\n- Set API keys via environment variables (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, etc.) — never hardcode them.\n- Validate all tool inputs before passing to external systems — use Pydantic models or manual checks.\n- Tools that mutate data (write to DB, send emails, call payment APIs) should require explicit user confirmation before the agent invokes them in production.\n- Log `result.all_messages()` for audit trails when agents perform consequential actions.\n- Set `retries=` limits on `Agent()` to prevent runaway loops on persistent validation failures.\n\n## Common Pitfalls\n\n- **Problem:** `ValidationError` on every LLM response — structured output never validates\n  **Solution:** Simplify `result_type` fields. Use `Optional` and `default` where appropriate. The model may struggle with overly strict schemas.\n\n- **Problem:** Tool is never called by the LLM\n  **Solution:** Write a clear, specific docstring for the tool function — PydanticAI sends the docstring as the tool description to the LLM.\n\n- **Problem:** `RunContext` dependency is `None` inside a tool\n  **Solution:** Pass `deps=` when calling `agent.run()` or `agent.run_sync()`. Dependencies are not set globally.\n\n- **Problem:** `asyncio.run()` error when calling `agent.run()` inside FastAPI\n  **Solution:** Use `await agent.run()` directly in async FastAPI route handlers — don't wrap in `asyncio.run()`.\n\n## Related Skills\n\n- `@langchain-architecture` — Alternative Python AI framework (more flexible, less type-safe)\n- `@llm-application-dev-ai-assistant` — General LLM application development patterns\n- `@fastapi-templates` — Serving PydanticAI agents via FastAPI endpoints\n- `@agent-orchestration-multi-agent-optimize` — Orchestrating multiple PydanticAI agents\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n",{"name":5,"risk":24,"tags":25,"tools":34,"author":37,"source":38,"category":26,"date_added":39,"description":7},"safe",[5,26,27,28,29,30,31,32,33],"ai-agents","llm","openai","anthropic","gemini","tool-use","structured-output","python",[35,36,30],"claude","cursor","suhaibjanjua","community","2026-03-18","main","87afe6ce96220accf50a345dea46784c8c9f210e","YYC3-Skills-技能包\u002FYYC3-Skills-技能包-antigravity-awesome-skills\u002Fplugins\u002Fantigravity-awesome-skills-claude\u002Fskills\u002Fpydantic-ai",0,"https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base","https:\u002F\u002Fkb.yyc3.top\u002F","https:\u002F\u002Fgithub.com\u002FYYC-Cube","万象归元于云枢 | 深栈智启新纪元","2026-11-10 10:37:32",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill pydantic-ai",{"tool":55,"command":56},"bunx","bunx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill pydantic-ai",{"tool":58,"command":59},"pnpm","pnpm dlx skills add YYC-Cube\u002FYYC3-Knowledge-Base --skill pydantic-ai","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-Skills-技能包\u002FYYC3-Skills-技能包-antigravity-awesome-skills\u002Fplugins\u002Fantigravity-awesome-skills-claude\u002Fskills\u002Fpydantic-ai\u002FSKILL.md",true,[],[64,71,78,85,92,99],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M7CTDWHERCXPQCP0K03A86AS","vercel-sandbox","Run agent-browser + Chrome inside Vercel Sandbox microVMs for browser automation from any Vercel-deployed app. Use when the user needs browser automation in a Vercel app (Next.js, SvelteKit, Nuxt, Remix, Astro, etc.), wants to run headless Chrome without binary size limits, needs persistent browser sessions across commands, or wants ephemeral isolated browser environments. Triggers include \"Vercel Sandbox browser\", \"microVM Chrome\", \"agent-browser in sandbox\", \"browser automation on Vercel\", or any task requiring Chrome in a Vercel Sandbox.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fvercel-sandbox\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M7CTD8D2BNJY54S65M47HEJA","slack","Interact with Slack workspaces using browser automation. Use when the user needs to check unread channels, navigate Slack, send messages, extract data, find information, search conversations, or automate any Slack task. Triggers include \"check my Slack\", \"what channels have unreads\", \"send a message to\", \"search Slack for\", \"extract from Slack\", \"find who said\", or any task requiring programmatic Slack interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fslack\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M7CTCSSB8ZP3Q58C3YZDZK1W","electron","Automate Electron desktop apps (VS Code, Slack, Discord, Figma, Notion, Spotify, etc.) using agent-browser via Chrome DevTools Protocol. Use when the user needs to interact with an Electron app, automate a desktop app, connect to a running app, control a native app, or test an Electron application. Triggers include \"automate Slack app\", \"control VS Code\", \"interact with Discord app\", \"test this Electron app\", \"connect to desktop app\", or any task requiring automation of a native Electron application.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Felectron\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7CTCBJY76688V4DCZGWFHGQ","dogfood","Systematically explore and test a web application to find bugs, UX issues, and other problems. Use when asked to \"dogfood\", \"QA\", \"exploratory test\", \"find issues\", \"bug hunt\", \"test this app\u002Fsite\u002Fplatform\", or review the quality of a web application. Produces a structured report with full reproduction evidence -- step-by-step screenshots, repro videos, and detailed repro steps for every issue -- so findings can be handed directly to the responsible teams.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fdogfood\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M7CTC4H0FFGVEAQR9PA4GA1A","agent-browser","Browser automation CLI for AI agents. Use when the user needs to interact with websites, including navigating pages, filling forms, clicking buttons, taking screenshots, extracting data, testing web apps, or automating any browser task. Triggers include requests to \"open a website\", \"fill out a form\", \"click a button\", \"take a screenshot\", \"scrape data from a page\", \"test this web app\", \"login to a site\", \"automate browser actions\", or any task requiring programmatic web interaction.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-WebSpec-Web标准\u002FYYC3-WebSpec-Web标准-standards\u002Fbrowser-agent\u002Fskills\u002Fagent-browser\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M7CTBKVFYBG78FDSABSDJTTQ","shadcn","Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn\u002Fui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for \"shadcn init\", \"create an app with --preset\", \"switch to --preset\", and for building a design system or applying a DESIGN.md or brand spec to shadcn\u002Fui.","https:\u002F\u002Fgithub.com\u002FYYC-Cube\u002FYYC3-Knowledge-Base\u002Fblob\u002Fmain\u002FYYC3-UI-界面组件\u002FYYC3-UI-界面组件-ui\u002Fskills\u002Fshadcn\u002FSKILL.md",[],[]]