Token导航 LogoToken导航TokenDH.com
研究检索敏感数据github未标认证来源可访问clear审计通过

pydantic-ai-common-pitfallspydantic ai 常见陷阱

Agent Skill

pydantic-ai-common-pitfalls 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

4,657

周安装

198

GitHub Stars

54

下载量

1,632
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:pydantic-ai-common-pitfalls(pydantic ai 常见陷阱)
来源仓库:https://github.com/existential-birds/beagle
仓库路径:skills/pydantic-ai-common-pitfalls
安装命令:
npx skills add https://github.com/existential-birds/beagle --skill pydantic-ai-common-pitfalls
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/existential-birds/beagle --skill pydantic-ai-common-pitfalls

简介

用于查找、检索和筛选相关信息。pydantic-ai-common-pitfalls 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

  • 适合根据关键词或任务场景快速定位候选结果。
  • 可结合来源仓库与原始 README 进一步核验具体用法。
  • 安装前需确认权限范围及是否会触发联网或文件读写操作。
  • 建议检查维护状态,避免使用不稳定或已弃用的技能。

SKILL.md

PydanticAI Common Pitfalls and Debugging

Tool Decorator Errors

Wrong: RunContext in tool_plain

# ERROR: RunContext not allowed in tool_plain
@agent.tool_plain
async def bad_tool(ctx: RunContext[MyDeps]) -> str:
    return "oops"
# UserError: RunContext annotations can only be used with tools that take context

Fix: Use @agent.tool if you need context:

@agent.tool
async def good_tool(ctx: RunContext[MyDeps]) -> str:
    return "works"

Wrong: Missing RunContext in tool

# ERROR: First param must be RunContext
@agent.tool
def bad_tool(user_id: int) -> str:
    return "oops"
# UserError: First parameter of tools that take context must be annotated with RunContext[...]

Fix: Add RunContext as first parameter:

@agent.tool
def good_tool(ctx: RunContext[MyDeps], user_id: int) -> str:
    return "works"

Wrong: RunContext not first

# ERROR: RunContext must be first parameter
@agent.tool
def bad_tool(user_id: int, ctx: RunContext[MyDeps]) -> str:
    return "oops"

Fix: RunContext must always be the first parameter.

Valid Patterns (Not Errors)

Raw Function Tool Registration

The following pattern IS valid and supported by pydantic-ai:

from pydantic_ai import Agent, RunContext

async def search_db(ctx: RunContext[MyDeps], query: str) -> list[dict]:
    """Search the database."""
    return await ctx.deps.db.search(query)

async def get_user(ctx: RunContext[MyDeps], user_id: int) -> dict:
    """Get user by ID."""
    return await ctx.deps.db.get_user(user_id)

# Valid: Pass raw functions to Agent(tools=[...])
agent = Agent(
    'openai:gpt-4o',
    deps_type=MyDeps,
    tools=[search_db, get_user]  # RunContext detected from signature
)

Why this works: PydanticAI inspects function signatures. If the first parameter is RunContext[T], it's treated as a context-aware tool. No decorator required.

Reference: https://ai.pydantic.dev/agents/#registering-tools-via-the-tools-argument

Do NOT flag code that passes functions with RunContext signatures to Agent(tools=[...]). This is equivalent to using @agent.tool and is explicitly documented.

Dependency Type Mismatches

Wrong: Missing deps at runtime

agent = Agent('openai:gpt-4o', deps_type=MyDeps)

# ERROR: deps required but not provided
result = agent.run_sync('Hello')  # Missing deps!

Fix: Always provide deps when deps_type is set:

result = agent.run_sync('Hello', deps=MyDeps(...))

Wrong: Wrong deps type

@dataclass
class AppDeps:
    db: Database

@dataclass
class WrongDeps:
    api: ApiClient

agent = Agent('openai:gpt-4o', deps_type=AppDeps)

# Type error: WrongDeps != AppDeps
result = agent.run_sync('Hello', deps=WrongDeps(...))

Output Type Issues

Pydantic validation fails

class Response(BaseModel):
    count: int
    items: list[str]

agent = Agent('openai:gpt-4o', output_type=Response)
result = agent.run_sync('List items')
# May fail if LLM returns wrong structure

Fix: Increase retries or improve prompt:

agent = Agent(
    'openai:gpt-4o',
    output_type=Response,
    retries=3,  # More attempts
    instructions='Return JSON with count (int) and items (list of strings).'
)

Complex nested types

# May cause schema issues with some models
class Complex(BaseModel):
    nested: dict[str, list[tuple[int, str]]]

Fix: Simplify or use intermediate models:

class Item(BaseModel):
    id: int
    name: str

class Simple(BaseModel):
    items: list[Item]

Async vs Sync Mistakes

Wrong: Calling async in sync context

# ERROR: Can't await in sync function
def handler():
    result = await agent.run('Hello')  # SyntaxError!

Fix: Use run_sync or make handler async:

def handler():
    result = agent.run_sync('Hello')

# Or
async def handler():
    result = await agent.run('Hello')

Wrong: Blocking in async tools

@agent.tool
async def slow_tool(ctx: RunContext[Deps]) -> str:
    time.sleep(5)  # WRONG: Blocks event loop!
    return "done"

Fix: Use async I/O:

@agent.tool
async def slow_tool(ctx: RunContext[Deps]) -> str:
    await asyncio.sleep(5)  # Correct
    return "done"

Model Configuration Errors

Missing API key

# ERROR: OPENAI_API_KEY not set
agent = Agent('openai:gpt-4o')
result = agent.run_sync('Hello')
# ModelAPIError: Authentication failed

Fix: Set environment variable or use defer_model_check:

# For testing
agent = Agent('openai:gpt-4o', defer_model_check=True)
with agent.override(model=TestModel()):
    result = agent.run_sync('Hello')

Invalid model string

# ERROR: Unknown provider
agent = Agent('unknown:model')
# ValueError: Unknown model provider

Fix: Use valid provider:model format.

Streaming Issues

Wrong: Using result before stream completes

async with agent.run_stream('Hello') as response:
    # DON'T access .output before streaming completes
    print(response.output)  # May be incomplete!

# Correct: access after context manager
print(response.output)  # Complete result

Wrong: Not iterating stream

async with agent.run_stream('Hello') as response:
    pass  # Never consumed!

# Stream was never read - output may be incomplete

Fix: Always consume the stream:

async with agent.run_stream('Hello') as response:
    async for chunk in response.stream_output():
        print(chunk, end='')

Tool Return Issues

Wrong: Returning non-serializable

@agent.tool_plain
def bad_return() -> object:
    return CustomObject()  # Can't serialize!

Fix: Return serializable types (str, dict, Pydantic model):

@agent.tool_plain
def good_return() -> dict:
    return {"key": "value"}

Debugging Tips

Enable tracing

import logfire
logfire.configure()
logfire.instrument_pydantic_ai()

# Or per-agent
agent = Agent('openai:gpt-4o', instrument=True)

Capture messages

from pydantic_ai import capture_run_messages

with capture_run_messages() as messages:
    result = agent.run_sync('Hello')

for msg in messages:
    print(type(msg).__name__, msg)

Check model responses

result = agent.run_sync('Hello')
print(result.all_messages())  # Full message history
print(result.response)  # Last model response
print(result.usage())  # Token usage

Common Error Messages

ErrorCauseFix
First parameter... RunContext@agent.tool missing ctxAdd ctx: RunContext[...]
RunContext... only... context@agent.tool_plain has ctxRemove ctx or use @agent.tool
Unknown model providerInvalid model stringUse valid provider:model
ModelAPIErrorAPI auth/quotaCheck API key, limits
RetryPromptPart in messagesValidation failedCheck output_type, increase retries

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

30.47%
按下载量换算497

OpenCode

21.77%
按下载量换算355

Gemini CLI

16.36%
按下载量换算267

Antigravity

12.13%
按下载量换算198

Codex

6.87%
按下载量换算112

Cursor

3.55%
按下载量换算58

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills