Pydantic Ai Common Pitfalls logo

Pydantic Ai Common Pitfalls

Organization
existential-birds
pydantic-ai-common-pitfalls

Avoid common mistakes and debug issues in PydanticAI agents. Use when encountering errors, unexpected behavior, or when reviewing agent implementations.

Overview

Publisherexistential-birds
Repositorybeagle
Skill namepydantic-ai-common-pitfalls
Stars
82
Forks
8
Bundled files
Instructions only
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by existential-birds on GitHub. Read the source before you install it.

Installation

Install the Pydantic Ai Common Pitfalls AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/existential-birds/beagle.git /tmp/beagle
mkdir -p .claude/skills
cp -r /tmp/beagle/plugins/beagle-ai/skills/pydantic-ai-common-pitfalls .claude/skills/pydantic-ai-common-pitfalls
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Pydantic Ai Common Pitfalls in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Pydantic Ai Common Pitfalls on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Pydantic Ai Common Pitfalls is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

PydanticAI Common Pitfalls and Debugging

Tool Decorator Errors

Wrong: RunContext in tool_plain

python
# 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:

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

Wrong: Missing RunContext in tool

python
# 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:

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

Wrong: RunContext not first

python
# 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:

python
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

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

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

Wrong: Wrong deps type

python
@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

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

python
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

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

Fix: Simplify or use intermediate models:

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

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

Async vs Sync Mistakes

Wrong: Calling async in sync context

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

Fix: Use run_sync or make handler async:

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

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

Wrong: Blocking in async tools

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

Fix: Use async I/O:

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

Model Configuration Errors

Missing API key

python
# 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:

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

Invalid model string

python
# 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

python
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

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

# Stream was never read - output may be incomplete

Fix: Always consume the stream:

python
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

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

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

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

Debugging Tips

Gates (ambiguous failures)

When the agent misbehaves but the stack trace or error string is unclear, follow in order; do not skip ahead.

  1. Capture evidence — Re-run with capture_run_messages() or, after run/run_sync, inspect result.all_messages() (or print message types in order). Pass: You can name the message part type and one line of content that explains the failure (e.g. RetryPromptPart, tool return, model text).
  2. Separate model from schema — If validation or RetryPromptPart appears, compare the last model message to your output_type fields and types. Pass: You identified a concrete mismatch (missing field, wrong type, refusal) before only raising retries or changing the model.
  3. Confirm deps on every path — If tools or deps fail, verify each call site (run, run_sync, run_stream) supplies deps=... when deps_type is set. Pass: A minimal repro with explicit deps matches or rules out a deps wiring bug.

Enable tracing

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

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

Capture messages

python
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

python
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

Frequently asked questions

What does the Pydantic Ai Common Pitfalls AI skill do?

Avoid common mistakes and debug issues in PydanticAI agents. Use when encountering errors, unexpected behavior, or when reviewing agent implementations.

Why use Pydantic Ai Common Pitfalls on TypingMind?

Because you install it once and use it with any model. Pydantic Ai Common Pitfalls is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Pydantic Ai Common Pitfalls in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/existential-birds/beagle/tree/main/plugins/beagle-ai/skills/pydantic-ai-common-pitfalls. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Pydantic Ai Common Pitfalls?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Pydantic Ai Common Pitfalls?

As many as you like. As long as a model supports skills, you can use Pydantic Ai Common Pitfalls with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Pydantic Ai Common Pitfalls AI skill free?

Yes. It is published on GitHub by existential-birds under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇