Sandbox
@vstorm-co/pydantic-deepagents

Python agent framework and terminal assistant for Pydantic AI

Pydantic Deep Agents gives you a terminal AI assistant and the Python framework behind it. The assistant can plan, edit files, run commands, use MCP servers, keep memory, and fork a run into branches; the library exposes the same harness through `create_deep_agent()`.

1,061 stars131 forksPythonUpdated 26d ago
Who it's for

Builders who want reusable agent behavior in the terminal or in their own Python app.

What it delivers

You can run a Claude Code-style agent on any model, or embed the same harness in your own agent app.

What it does

Terminal assistant

Runs a Claude Code-style TUI with chat, tool calls, file edits, shell access, and session controls.

Deep agent framework

Provides `create_deep_agent()` for planning, tools, memory, checkpoints, and cost tracking in Python.

Live run forking

Splits one agent run into parallel branches and lets a judge or tests pick the winner.

Subagents and teams

Spawns subagents for parallel work and shared task coordination.

MCP support

Connects to MCP servers such as GitHub, Figma, Context7, and custom servers.

Sandboxed execution

Supports Docker sandboxed command execution with named workspaces.

Skills and context files

Loads skills from `SKILL.md` files and project context from `AGENTS.md`, `CLAUDE.md`, `MEMORY.md`, and `.cursorrules`.

How to get it

  1. 1Run
    curl -fsSL https://raw.githubusercontent.com/vstorm-co/pydantic-deep/main/install.sh | bash
  2. 2No Python setup required — the script installs uv and the CLI automatically. Then
    export ANTHROPIC_API_KEY=sk-ant-...
    pydantic-deep

README

Pydantic Deep Agents

Open-source Claude Code — that you can also build on.
A self-hosted terminal AI assistant and the Python framework behind it.
Use it today, or ship your own agent in one function call. Any model. 100% type-safe. MIT.

Pydantic Deep Agents CLI demo

Docs · PyPI · Forking · Why · CLI · Framework · Examples

PyPI version PyPI Downloads GitHub Stars Python 3.10+ License: MIT Coverage Status CI OpenSSF Best Practices Security Policy Pydantic AI X


Pydantic Deep Agents is two things in one repo:

🖥️ A terminal AI assistant — a self-hosted, open-source alternative to Claude Code. Install it, point it at any model, and it plans, edits files, runs commands, searches the web, remembers across sessions, spawns sub-agents, and connects to MCP servers. Almost everything Claude Code does — on the model you choose.

🐍 A Python framework — the exact same harness behind a single function call. create_deep_agent() hands a model a filesystem, shell, planning, memory, sub-agents, sandboxed execution, MCP, and unlimited context. Build your own assistant, research agent, or coding tool without rewiring the plumbing every time.

Both run on Pydantic AI, work with any model (Claude, GPT, Gemini, local), and are 100% type-safe and MIT-licensed — and they share one trick nothing else has: Live Run Forking, splitting a single run into parallel branches an AI judge merges back together.

Two ways to use it

🖥️ 1. Use the assistant

A Claude-Code-style TUI in your terminal, on any model — no Python setup (the script installs uv + the CLI for you):

curl -fsSL https://raw.githubusercontent.com/vstorm-co/pydantic-deep/main/install.sh | bash
pydantic-deep

Windows / manual: pip install "pydantic-deep[cli]"

🐍 2. Build your own

One function call gives you a full deep agent:

pip install pydantic-deep
from pydantic_deep import create_deep_agent

agent = create_deep_agent(model="anthropic:claude-sonnet-4-6")
result = await agent.run("Build a REST API for auth")

⑂ Live Run Forking — the feature no one else has

Claude Code can't do this. Aider can't. LangGraph and CrewAI can't. It's the reason to use pydantic-deep.

When an agent hits a fork in the road — "should I refactor this with a decorator or a context manager?" — most tools force one bet. Pydantic Deep Agents lets the run branch:

                                  ┌──  branch A: "use a decorator"      ── tests: 8/8 ✓  conf 0.71
   agent.run("refactor auth") ──┬─┼──  branch B: "use a context manager" ── tests: 6/8 ✗  conf 0.42
       (shared history)         │ └──  branch C: "extract a base class"   ── tests: 8/8 ✓  conf 0.55
                                │
                                └──►  ⚖️  AI judge weighs quality + tests + consistency
                                          → adopts branch A, continues the run

Each branch is fully isolated: a copy-on-write filesystem overlay (reads fall through to the parent, writes stay local), its own steering message, and its own budget_usd cap. The coordinator resolves the fork with one of four acceptance modes — manual, auto, auto_with_fallback (default), or vote — and the winning branch's history is adopted as the parent run's continuation.

Framework — opt in with one flag:

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    forking=True,                 # gives the agent: fork_run, inspect_branches,
)                                 # merge_or_select, diff_branches, fork_cost, terminate_branch

Or run a real test command against every branch and let exit codes decide the winner:

from pydantic_deep import LiveForkCapability

agent = create_deep_agent(
    forking=LiveForkCapability(test_command="pytest -q", test_timeout_s=120),
)
# confidence = quality_spread·0.4 + test_pass_ratio·0.4 + internal_consistency·0.2

CLI — fork an in-flight conversation, watch branches stream live, merge the best:

/fork                 # split the current run into N parallel branches
>>A try a decorator   # steer branch A
>>B use a contextmgr  # steer branch B
/merge                # resolve — manual picker, AI judge, or vote

Live per-branch panels stream each approach side by side; a judge screen scores them; you accept, review the diff, or decline. Configure branch count, budgets, per-branch models, and merge strategy with /fork-config.

📖 Full reference: docs/capabilities/live-fork.md


🆚 Why pydantic-deep?

The only tool that is a terminal assistant and a Python framework and can fork its own runs — without giving up type safety or your choice of model.

Pydantic DeepClaude CodeAiderLangGraphCrewAI
Terminal TUI assistant
Python framework / library~
Live run forking + AI judge
Multi-agent swarm + message bus~
Any model / any providerAnthropic
Sandboxed Docker execution~DIYDIY
Persistent memory + skillsDIY~
Type-safe structured output~~
MCP servers~~
Self-hosted, open source✅ MIT

✅ first-class · ~ partial / via extensions · — not available · DIY you wire it yourself. Comparison reflects each project as of 2026-06; corrections welcome via PR.


What's New

  • 2026-06-01  v0.3.24Live Run Forking — split an in-flight agent.run() into N parallel branches with copy-on-write isolation, per-branch budgets, a test-runner hook, and four merge modes (manual / auto / auto_with_fallback / vote). Opt in with forking=True.
  • 2026-06-01  v0.3.23MCP client support (framework + CLI). Connect GitHub, Figma (OAuth), Context7, DeepWiki, or any custom server. Import servers straight from Claude Code. New interactive /mcp command. Plus a full CLI presentation pass: clipboard image paste, real +/- diffs, tool icons, turn summaries.
  • 2026-06-01  v0.3.23Automatic fallback-model retryfallback_model= wraps your primary in a FallbackModel chain; fires on API errors but never on auth errors. Plus a batteries-included security hook preset (default_security_hook()) and three new output styles (markdown, json-only, bullet).
  • 2026-04-22  v0.3.17 — LiteParse document parsing (include_liteparse=True) — PDFs, DOCX, XLSX, PPTX, and images with optional OCR, all local.
  • 2026-04-10  v0.3.5 — Headless runner (pydantic-deep run), Docker sandbox with named workspaces, browser automation via Playwright.

Full history: CHANGELOG.md


The Agent Harness

Pydantic Deep Agents is an agent harness — the complete infrastructure that wraps an LLM and makes it a functional autonomous agent. The model provides intelligence; the harness provides planning, tools, memory, sandboxed execution, unlimited context, and — uniquely — the ability to fork.

⑂ Live run forkingSplit a run into N isolated branches, each trying a different approach. AI judge or test results pick the winner. No other agent framework has this.
🔧 Tool-callingFile read/write/edit, shell execution, glob, grep, web search, web fetch, browser automation — wired up and ready.
🤝 Multi-agent / swarmSpawn subagents for parallel workstreams. Shared TODO lists with claiming. Peer-to-peer message bus. Full team coordination.
🧠 Persistent memoryMEMORY.md persists across sessions. Auto-injected into the system prompt. Each agent has isolated memory by default.
♾️ Unlimited contextAuto-summarization when approaching the token budget. LLM-based or zero-cost sliding window. Never hits a context wall.
🐳 Sandboxed executionDocker sandbox with named workspaces. Installed packages persist between sessions. Project dir mounted at /workspace.
🗂️ Plan ModeDedicated planner subagent asks clarifying questions and structures the work before execution begins. Headless-compatible.
🔖 CheckpointsSave conversation state at any point. Rewind to any checkpoint. Fork sessions to explore alternative approaches.
📚 Skills systemDomain-specific knowledge loaded on demand from SKILL.md files. Built-in: code-review, refactor, test-writer, git-workflow, and more.
📄 Document parsingParse PDFs, DOCX, XLSX, PPTX, and images with optional OCR via LiteParse. Runs locally — no cloud services required.
🔌 MCPConnect any Model Context Protocol server — GitHub, Figma (OAuth), Context7, DeepWiki, or custom. Import straight from Claude Code.
⚡ Lifecycle hooks + security presetClaude Code-style PRE/POST_TOOL_USE hooks. Shell or Python handlers. default_security_hook() blocks destructive commands out of the box.
📐 Structured outputType-safe Pydantic model responses via output_type. No JSON parsing. No dict["key"]. Full IDE autocomplete.
🔁 Fallback modelsPrimary model fails? fallback_model= hops to the next in the chain — on API errors, never on auth errors.
🔄 Stuck loop detectionDetects repeated identical tool calls, A-B-A-B alternating patterns, and no-op calls. Warns the model or stops the run.
💰 Cost trackingReal-time token and USD cost tracking per run and cumulative. Hard budget limits with BudgetExceededError.
✨ Self-improving/improve analyzes past sessions and proposes updates to MEMORY.md, SOUL.md, and AGENTS.md.
🏷️ 100% type-safePyright strict + MyPy strict. 100% test coverage. Every public API is fully typed — safe to use in production.

Built natively on pydantic-ai — uses the Capabilities API directly, inherits all pydantic-ai streaming, multi-model support, and Pydantic validation automatically.


🖥️ CLI — Terminal AI Assistant

A Claude Code-style terminal AI assistant that works with any model and any provider — and forks.

Install (macOS & Linux)

curl -fsSL https://raw.githubusercontent.com/vstorm-co/pydantic-deep/main/install.sh | bash

No Python setup required — the script installs uv and the CLI automatically. Then:

export ANTHROPIC_API_KEY=sk-ant-...
pydantic-deep

Windows / manual: pip install "pydantic-deep[cli]"  ·  Update: pydantic-deep update

Model & Provider Support

Works with any model that supports tool-calling:

ProviderExample models
Anthropicanthropic:claude-opus-4-6, claude-sonnet-4-6
OpenAIopenai:gpt-5.4, gpt-4.1
OpenRouteropenrouter:anthropic/claude-opus-4-6 (200+ models)
Google Geminigoogle-gla:gemini-2.5-pro
Ollama (local)ollama:qwen3, ollama:llama3.3
Any OpenAI-compatibleCustom base URL via env

Switch model anytime: pydantic-deep config set model openai:gpt-5.4 or /model in the TUI.

What you get in the TUI

Feature
Live run forking — split a run into branches, stream them side by side, merge the winner
💬Streaming chat with tool call visualization, icons, and real +/- diffs
📁File read / write / edit, shell execution, glob, grep
🤝Task planning, plan mode, and subagent delegation
🧠Persistent memory and self-improvement across sessions
♾️Context compression for unlimited conversations
🔖Checkpoints — save, rewind, and fork any session
🔌MCP servers via /mcp — GitHub, Figma (OAuth), and more; import from Claude Code
🌐Web search & fetch built-in · 🖥️ browser automation via Playwright (--browser)
🐳Docker sandbox — sandboxed execution with named workspaces
💭Extended thinking — minimal / low / medium / high / xhigh
📋Clipboard image paste (Ctrl+V / /paste) — multimodal prompts
💰Real-time cost and token tracking per session
🛡️Tool approval dialogs — approve, auto-approve, or deny per tool call
@@filename file references · !command shell passthrough
/fork, /merge, /improve, /skills, /mcp, /model, /theme, /compact, and more

Usage

# Interactive TUI (default)
pydantic-deep
pydantic-deep tui --model openrouter:anthropic/claude-opus-4-6

# Headless deep agent — benchmarks, CI/CD, scripted automation
pydantic-deep run "Fix the failing test in test_auth.py"
pydantic-deep run --task-file task.md --json

# Docker sandbox — sandboxed execution, project dir mounted at /workspace
pydantic-deep tui --sandbox docker
pydantic-deep tui --workspace ml-env     # named workspace, packages persist

# Browser automation (requires pydantic-deep[browser])
pydantic-deep tui --browser

# Config & skills
pydantic-deep config set model anthropic:claude-sonnet-4-6
pydantic-deep skills list
pydantic-deep update                     # update to latest version

See CLI docs for the full reference.


🐍 Framework — Build Your Own Agent

pip install pydantic-deep

One function call gives you a production deep agent with planning, tool-calling, multi-agent delegation, persistent memory, unlimited context, forking, and cost tracking. Everything is a toggle:

from pydantic_ai_backends import StateBackend
from pydantic_deep import create_deep_agent, create_default_deps

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    forking=True,               # ⑂ split a run into parallel branches + AI judge
    include_todo=True,          # Task planning with subtasks and dependencies
    include_subagents=True,     # Multi-agent swarm — delegate to subagents
    include_skills=True,        # Domain-specific skills from SKILL.md files
    include_memory=True,        # Persistent memory across sessions
    include_plan=True,          # Structured planning before execution
    include_teams=True,         # Agent teams with shared TODO lists + message bus
    include_liteparse=True,     # Document parsing — PDF, DOCX, XLSX + OCR
    web_search=True,            # Tool-calling: web search
    thinking="high",            # Extended thinking / reasoning effort
    context_manager=True,       # Unlimited context via auto-summarization
    cost_tracking=True,         # Token/USD budget enforcement
    fallback_model="openai:gpt-5.4",   # auto-retry if the primary model fails
    include_checkpoints=True,   # Save, rewind, and fork conversations
)

deps = create_default_deps(StateBackend())
result = await agent.run("Build a REST API for user auth", deps=deps)

Structured Output

Type-safe responses with Pydantic models — no JSON parsing, no dict["key"]:

from pydantic import BaseModel

class CodeReview(BaseModel):
    summary: str
    issues: list[str]
    score: int

agent = create_deep_agent(output_type=CodeReview)
result = await agent.run("Review the auth module", deps=deps)
print(result.output.score)  # fully typed

Multi-Agent Swarm

Spawn isolated subagents for parallel workstreams. Each subagent is a full deep agent with its own tool-calling, memory, and context:

agent = create_deep_agent(
    subagents=[
        {
            "name": "researcher",
            "description": "Researches topics using web search",
            "instructions": "Search the web, synthesize findings, cite sources.",
        },
        {
            "name": "code-reviewer",
            "description": "Reviews code for quality, security, and performance",
            "instructions": "Check for security issues, N+1 queries, missing tests...",
        },
    ],
)
# Main agent delegates: task(description="Review auth.py", subagent_type="code-reviewer")

Claude Code-Style Lifecycle Hooks + Security Preset

from pydantic_deep import create_deep_agent, default_security_hook, Hook, HookEvent

agent = create_deep_agent(
    hooks=[
        *default_security_hook(),   # blocks destructive shell, path traversal, secret leaks
        Hook(
            event=HookEvent.PRE_TOOL_USE,
            command="echo 'Tool: $TOOL_NAME args: $TOOL_INPUT' >> /tmp/audit.log",
        ),
    ],
)

MCP Servers

Connect GitHub, Figma (OAuth), Context7, DeepWiki, or any custom server — auth handled for you:

from pydantic_deep import create_deep_agent, build_mcp_server, MCPServerConfig

deepwiki = build_mcp_server(
    MCPServerConfig(name="deepwiki", transport="http", url="https://mcp.deepwiki.com/mcp")
)

agent = create_deep_agent(mcp_servers=[deepwiki])   # curated defaults via builtin_mcp_servers()

Context Files

Pydantic Deep Agents auto-discovers and injects project-specific context into every conversation:

FilePurposeWho Sees It
AGENTS.mdProject conventions, architecture, instructionsMain agent + all subagents
CLAUDE.mdClaude Code project instructionsMain agent + all subagents
SOUL.mdAgent personality, style, communication preferencesMain agent only
.cursorrulesCursor editor conventionsMain agent only
MEMORY.mdPersistent memory — read/write/update toolsPer-agent (isolated)

Compatible with Claude Code, Cursor, GitHub Copilot, and other agent frameworks. AGENTS.md follows the agents.md spec.

See the full API reference for all options.


🔬 DeepResearch — Reference App

A full-featured research deep agent with web UI — built entirely on Pydantic Deep Agents.

Planner subagent asks clarifying questions

Plan Mode — planner asks clarifying questions

Parallel subagent research

Multi-Agent Swarm — 5 subagents researching in parallel

Excalidraw canvas

Excalidraw Canvas — live diagrams synced with agent

File browser

File Browser — workspace files with inline preview

Web search (Tavily, Brave, Jina), sandboxed code execution, Excalidraw diagrams, plan mode, report export.

cd apps/deepresearch && uv sync && cp .env.example .env
uv run deepresearch    # → http://localhost:8080

See apps/deepresearch/README.md for full setup.


Architecture

Pydantic Deep Agents uses pydantic-ai's native Capabilities API for all cross-cutting concerns — forking, hooks, memory, skills, context files, teams, and plan mode are all first-class pydantic-ai capabilities.

                         Pydantic Deep Agents
+---------------------------------------------------------------------+
|                                                                     |
|   +----------+ +----------+ +----------+ +----------+ +---------+   |
|   | Planning | |Filesystem| | Subagents| |  Skills  | |  Teams  |   |
|   +----+-----+ +----+-----+ +----+-----+ +----+-----+ +----+----+   |
|        |            |            |            |            |        |
|        +------------+-----+------+------------+------------+        |
|                           |                                         |
|                           v                                         |
|  Forking       --> +------------------+ <-- Capabilities            |
|  Summarization --> |    Deep Agent    | <-- Hooks                   |
|  Checkpointing --> |   (pydantic-ai)  | <-- Memory                  |
|  Cost Tracking --> |                  | <-- MCP                     |
|                    +--------+---------+                             |
|                             |                                       |
|           +-----------------+-----------------+                     |
|           v                 v                 v                     |
|    +------------+    +------------+    +------------+               |
|    |   State    |    |   Local    |    |   Docker   |               |
|    |  Backend   |    |  Backend   |    |  Sandbox   |               |
|    +------------+    +------------+    +------------+               |
|                                                              

Files in the repo

Repository payload24 top-level entries
  • .github
  • apps
  • assets
  • docs
  • examples
  • jobs
  • pydantic_deep
  • tests
  • .gitignore
  • .pre-commit-config.yaml
  • CHANGELOG.md
  • CLAUDE.md
  • CODE_QUALITY_REPORT.md
  • CONTRIBUTING.md
  • GOVERNANCE.md
  • install.sh
  • LICENSE
  • Makefile
  • mkdocs.yml
  • pyproject.toml
  • README.md
  • renovate.json
  • SECURITY.md
  • SYSTEM_REVIEW.md

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More frameworks & sdks

HKUDS/nanobotFrameworks & SDKs

Ultra-lightweight, open-source, self-hosted personal AI agent framework in Python with WebUI, tools, memory, MCP, multi-agent workflows, automation, and chat apps

48k
microsoft/
SkillOpt
microsoft/SkillOptFrameworks & SDKs

SkillOpt is a text-space optimizer that trains reusable natural-language skills for frozen LLM agents through trajectory-driven edits, validation-gated updates, and deployable best_skill.md artifacts.

17k
omnigent-ai/omnigentFrameworks & SDKs

Omnigent is an open-source AI agent framework and meta-harness: orchestrate Claude Code, Codex, Cursor, Pi, and custom agents — swap harnesses without rewriting, enforce policies and sandboxing, and collaborate in real time from any device.

9.8k
kyegomez/
OpenMythos
kyegomez/OpenMythosFrameworks & SDKs

A theoretical reconstruction of the Claude Mythos architecture, built from first principles using the available research literature.

15k
D4Vinci/ScraplingFrameworks & SDKs

🕷️ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!

80k