Skip to content

Examples

This section contains practical examples demonstrating pydantic-deep features.

Running Examples

All examples are in the examples/ directory:

Bash
# Set your API key
export OPENAI_API_KEY=your-api-key  # or ANTHROPIC_API_KEY

# Run an example
uv run python examples/<example_name>.py

Example Overview

:material-rocket-launch: Basic Usage

Getting started with pydantic-deep. Create agents, use todos, work with files.

View Example →

:material-folder: Filesystem

Real filesystem operations with FilesystemBackend.

View Example →

:material-layers: Composite Backend

Combine multiple backends with path-based routing.

View Example →

:material-target: Skills

Modular capability packages with progressive disclosure.

View Example →

:material-account-group: Subagents

Delegate specialized tasks to subagents.

View Example →

:material-wrench: Custom Tools

Add your own tools alongside built-in toolsets.

View Example →

:material-upload: File Uploads

Upload files for agent processing with run_with_files() or deps.upload_file().

View Example →

:material-docker: Docker Sandbox

Isolated code execution in Docker containers.

View Example →

:material-cog: Docker Runtimes

Pre-configured execution environments with RuntimeConfig.

View Example →

:material-play-speed: Streaming

Real-time output with agent.iter() for progress tracking.

View Example →

:material-shield-check: Human-in-the-Loop

Approval workflows for sensitive operations.

View Example →

:material-chat: Interactive Chat

CLI chatbot with streaming and tool visibility.

View Example →

:material-star: Full Application

Complete FastAPI app with WebSocket streaming, Docker, uploads, and more.

View Example →

Quick Examples

Hello World

Python
import asyncio
from pydantic_deep import create_deep_agent, DeepAgentDeps, StateBackend

async def main():
    agent = create_deep_agent()
    deps = DeepAgentDeps(backend=StateBackend())

    result = await agent.run("Say hello!", deps=deps)
    print(result.output)

asyncio.run(main())

Create a File

Python
async def main():
    agent = create_deep_agent()
    deps = DeepAgentDeps(backend=StateBackend())

    result = await agent.run(
        "Create a Python function that calculates factorials and save it to /math/factorial.py",
        deps=deps,
    )

    # Check what was created
    print("Files:", list(deps.backend.files.keys()))
    print("\nContent:")
    print(deps.backend.read("/math/factorial.py"))

Plan a Task

Python
async def main():
    agent = create_deep_agent()
    deps = DeepAgentDeps(backend=StateBackend())

    result = await agent.run(
        """
        Create a simple CLI calculator with the following features:
        1. Add, subtract, multiply, divide
        2. Input validation
        3. Help command

        Plan the task first using todos, then implement.
        """,
        deps=deps,
    )

    # Check the todo list
    print("Todos:")
    for todo in deps.todos:
        status = "✓" if todo.status == "completed" else "○"
        print(f"  {status} {todo.content}")

Delegate to Subagent

Python
from pydantic_deep import SubAgentConfig

async def main():
    subagents = [
        SubAgentConfig(
            name="code-reviewer",
            description="Reviews code for quality",
            instructions="You are a code review expert...",
        ),
    ]

    agent = create_deep_agent(subagents=subagents)
    deps = DeepAgentDeps(backend=StateBackend())

    # Create some code
    deps.backend.write("/src/app.py", "def add(a, b): return a + b")

    result = await agent.run(
        "Delegate a code review of /src/app.py to the code-reviewer",
        deps=deps,
    )

    print(result.output)

Use Skills

Python
async def main():
    agent = create_deep_agent(
        skill_directories=[
            {"path": "./skills", "recursive": True},
        ],
    )
    deps = DeepAgentDeps(backend=StateBackend())

    result = await agent.run(
        """
        1. List available skills
        2. Load the code-review skill
        3. Use it to review /src/app.py
        """,
        deps=deps,
    )

    print(result.output)

Testing Without API

Use TestModel for testing without API calls:

Python
from pydantic_ai.models.test import TestModel

async def main():
    agent = create_deep_agent(model=TestModel())
    deps = DeepAgentDeps(backend=StateBackend())

    # TestModel will return predefined responses
    result = await agent.run("Test prompt", deps=deps)

Example Files Reference

File Description Docs Page
basic_usage.py Core functionality demonstration Basic Usage
filesystem_backend.py Real filesystem operations Filesystem
composite_backend.py Mixed storage strategies Composite Backend
skills_usage.py Skills system Skills
subagents.py Task delegation Subagents
custom_tools.py Adding custom tools Custom Tools
file_uploads.py File uploads for agent processing File Uploads
docker_sandbox.py Isolated execution Docker Sandbox
streaming.py Real-time output Streaming
human_in_the_loop.py Approval workflows Human-in-the-Loop
interactive_chat.py CLI chatbot Interactive Chat
full_app/ Complete FastAPI application Full App

Next Steps