Skip to main content

Subagent toolset for pydantic-ai with dual-mode execution and dynamic agent creation

Project description

Subagents for Pydantic AI

Multi-Agent Orchestration for Pydantic AI

PyPI version Python 3.10+ License: MIT Coverage Status Pydantic AI

Nested Subagents — subagents spawn their own subagents  •  Runtime Agent Creation — create specialists on-the-fly  •  Auto-Mode Selection — intelligent sync/async decision


Subagents for Pydantic AI adds multi-agent delegation to any Pydantic AI agent. Spawn specialized subagents that run synchronously (blocking), asynchronously (background), or let the system auto-select the best mode.

Full framework? Check out Pydantic Deep Agents - complete agent framework with planning, filesystem, subagents, and skills.

Use Cases

What You Want to Build How Subagents Help
Research Assistant Delegate research to specialists, synthesize with a writer agent
Code Review System Security agent, style agent, and performance agent work in parallel
Content Pipeline Researcher → Analyst → Writer chain with handoffs
Data Processing Spawn workers dynamically based on data volume
Customer Support Route to specialized agents (billing, technical, sales)
Document Analysis Extract, summarize, and categorize with focused agents

Installation

pip install subagents-pydantic-ai

Or with uv:

uv add subagents-pydantic-ai

Quick Start

from dataclasses import dataclass, field
from typing import Any
from pydantic_ai import Agent
from subagents_pydantic_ai import create_subagent_toolset, SubAgentConfig

# Dependencies must implement SubAgentDepsProtocol
@dataclass
class Deps:
    subagents: dict[str, Any] = field(default_factory=dict)

    def clone_for_subagent(self, max_depth: int = 0) -> "Deps":
        return Deps(subagents={} if max_depth <= 0 else self.subagents.copy())

# Define specialized subagents
subagents = [
    SubAgentConfig(
        name="researcher",
        description="Researches topics and gathers information",
        instructions="You are a research assistant. Investigate thoroughly.",
    ),
    SubAgentConfig(
        name="writer",
        description="Writes content based on research",
        instructions="You are a technical writer. Write clear, concise content.",
    ),
]

# Create toolset and agent
toolset = create_subagent_toolset(subagents=subagents)
agent = Agent(
    "openai:gpt-4o",
    deps_type=Deps,
    toolsets=[toolset],
    system_prompt="You can delegate tasks to specialized subagents.",
)

# Run the agent
result = agent.run_sync(
    "Research Python async patterns and write a blog post about it",
    deps=Deps(),
)
print(result.output)

Execution Modes

Choose how subagents execute their tasks:

Mode Description Use Case
sync Block until complete Quick tasks, when result is needed immediately
async Run in background Long research, parallel tasks
auto Smart selection Let the system decide based on task characteristics

Sync Mode (Default)

# Agent calls: task(description="...", subagent_type="researcher", mode="sync")
# Parent waits for result before continuing

Async Mode

# Agent calls: task(description="...", subagent_type="researcher", mode="async")
# Returns task_id immediately, agent continues working
# Later: check_task(task_id) to get result

Auto Mode

# Agent calls: task(description="...", subagent_type="researcher", mode="auto")
# System decides based on:
# - Task complexity (simple → sync, complex → async)
# - Independence (can run without user context → async)
# - Subagent preferences (from config)

Give Subagents Tools

Provide toolsets so subagents can interact with files, APIs, or other services:

from pydantic_ai_backends import create_console_toolset

def my_toolsets_factory(deps):
    """Factory that creates toolsets for subagents."""
    return [
        create_console_toolset(),  # File operations
        create_search_toolset(),   # Web search
    ]

toolset = create_subagent_toolset(
    subagents=subagents,
    toolsets_factory=my_toolsets_factory,
)

Dynamic Agent Creation

Create agents on-the-fly based on task requirements:

from subagents_pydantic_ai import (
    create_subagent_toolset,
    create_agent_factory_toolset,
    DynamicAgentRegistry,
)

registry = DynamicAgentRegistry()

agent = Agent(
    "openai:gpt-4o",
    deps_type=Deps,
    toolsets=[
        create_subagent_toolset(),
        create_agent_factory_toolset(
            registry=registry,
            allowed_models=["openai:gpt-4o", "openai:gpt-4o-mini"],
            max_agents=5,
        ),
    ],
)

Subagent Questions

Enable subagents to ask the parent for clarification:

SubAgentConfig(
    name="analyst",
    description="Analyzes data",
    instructions="Ask for clarification when data is ambiguous.",
    can_ask_questions=True,
    max_questions=3,
)

The parent agent can then respond using answer_subagent(task_id, answer).

Available Tools

Tool Description
task Delegate a task to a subagent (sync, async, or auto)
check_task Check status and get result of a background task
answer_subagent Answer a question from a blocked subagent
list_active_tasks List all running background tasks
soft_cancel_task Request cooperative cancellation
hard_cancel_task Immediately cancel a task

Architecture

┌─────────────────────────────────────────────────────────┐
│                     Parent Agent                        │
│  ┌─────────────────────────────────────────────────┐    │
│  │              Subagent Toolset                   │    │
│  │  task() │ check_task() │ answer_subagent()      │    │
│  └─────────────────────────────────────────────────┘    │
│                         │                               │
│         ┌───────────────┼───────────────┐               │
│         ▼               ▼               ▼               │
│  ┌────────────┐  ┌────────────┐  ┌────────────┐         │
│  │ researcher │  │   writer   │  │   coder    │         │
│  │  (sync)    │  │  (async)   │  │  (auto)    │         │
│  └────────────┘  └────────────┘  └────────────┘         │
│                                                         │
│              Message Bus (pluggable)                    │
└─────────────────────────────────────────────────────────┘

Related Projects

Package Description
Pydantic Deep Agents Full agent framework (uses this library)
pydantic-ai-backend File storage and Docker sandbox backends
pydantic-ai-todo Task planning toolset
summarization-pydantic-ai Context management processors
pydantic-ai The foundation - agent framework by Pydantic

Contributing

git clone https://github.com/vstorm-co/subagents-pydantic-ai.git
cd subagents-pydantic-ai
make install
make test  # 100% coverage required
make all   # lint + typecheck + test

See CONTRIBUTING.md for full guidelines.

License

MIT License - see LICENSE for details.

Built with ❤️ by vstorm-co

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

subagents_pydantic_ai-0.0.2.tar.gz (144.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

subagents_pydantic_ai-0.0.2-py3-none-any.whl (28.0 kB view details)

Uploaded Python 3

File details

Details for the file subagents_pydantic_ai-0.0.2.tar.gz.

File metadata

  • Download URL: subagents_pydantic_ai-0.0.2.tar.gz
  • Upload date:
  • Size: 144.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for subagents_pydantic_ai-0.0.2.tar.gz
Algorithm Hash digest
SHA256 90c817653cbba2137b58bebc416d4364d328600dc8f52ec02c56fc4d1a12ba1c
MD5 6bd93fd507e5c13a9604063a69a762ed
BLAKE2b-256 d28d8f8ad1211b2372dcba7109e80c2c5a885fe5b3048f46b63ae7cd803e74cd

See more details on using hashes here.

Provenance

The following attestation bundles were made for subagents_pydantic_ai-0.0.2.tar.gz:

Publisher: publish.yml on vstorm-co/subagents-pydantic-ai

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file subagents_pydantic_ai-0.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for subagents_pydantic_ai-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 50f0dff1249860966761c47d09df2127d0b372e7980d15e76383ddf623411a89
MD5 ab9928b141c5e9ebc3c6873c1d86959d
BLAKE2b-256 11e8945bda2f11a89cffadefd3100ba193777460881913f552d9b5f371002ffe

See more details on using hashes here.

Provenance

The following attestation bundles were made for subagents_pydantic_ai-0.0.2-py3-none-any.whl:

Publisher: publish.yml on vstorm-co/subagents-pydantic-ai

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page