К основному содержанию
скилл CX Codex

migrating-claude-agent-sdk-to-pydantic-ai — скилл для Claude Code

Скилл ведёт миграцию Python-приложения с Claude Agent SDK на Pydantic AI. Нужен, когда в коде есть импорт claude_agent_sdk.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add pydantic/skills --skill migrating-claude-agent-sdk-to-pydantic-ai -a claude-code
Открыть на GitHub

Что делает migrating-claude-agent-sdk-to-pydantic-ai

Скилл разбирает исходный код перед тем, как что-то менять. Он читает инструкции репозитория, зависимости, тесты и точку входа, фиксирует версии Claude Agent SDK, встроенного Claude CLI, Pydantic AI и Harness. Потом прослеживает один реальный запрос от query() или ClaudeSDKClient через промпты, инструменты, события, состояние, согласования и побочные эффекты. Так появляется база для характеризационного теста.

Дальше выбирается минимальная цель. Ядро — pydantic_ai.Agent: вызовы модели, цикл агента, типизированные зависимости, инструменты, стриминг, MCP, лимиты. pydantic-ai-harness добавляется только под реально наблюдаемое поведение: файловые и shell-инструменты, планирование, память, субагенты, Agent Skills. Аутентификация, базы, очереди и деплой остаются в приложении.

Есть места, где перенос ломается тихо. allowed_tools в Claude Agent SDK означает автосогласование, а не ограничение доступности и не изоляцию — эти три вещи скилл советует разводить отдельно. message_history в Pydantic AI явно переигрывает нормализованные сообщения, а conversation_id только связывает запуски и не заменяет токен возобновления сессии Claude. Хуки сверяются по точке срабатывания, порядку и обработке ошибок, и для любого видимого контракта требуется golden trace. Перемотка файлов, пресеты промптов Claude и упаковка плагинов остаются пробелами, если конкретному вызывающему коду они не нужны.

Какие задачи решает

  • перевести Python-приложение с claude_agent_sdk на Pydantic AI
  • сохранить наблюдаемое поведение агента, а не форму API
  • развести доступность инструментов, автосогласование и изоляцию
  • сверить порядок срабатывания хуков до и после миграции
  • убрать claude-agent-sdk из зависимостей после переноса

Примеры запросов агенту

  • Разбери этот репозиторий и предложи план миграции с Claude Agent SDK на Pydantic AI
  • Проследи один запрос от query() и покажи, какие контракты придётся сохранить
  • Проверь, нужен ли здесь pydantic-ai-harness, или хватит ядра

Как установить migrating-claude-agent-sdk-to-pydantic-ai

1Через Skills CLI (Vercel)

npx skills add pydantic/skills --skill migrating-claude-agent-sdk-to-pydantic-ai -a claude-code

2Вручную: положить файлы

~/.claude/skills/migrating-claude-agent-sdk-to-pydantic-ai/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/migrating-claude-agent-sdk-to-pydantic-ai/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о migrating-claude-agent-sdk-to-pydantic-ai

Как установить migrating-claude-agent-sdk-to-pydantic-ai в Claude?

Выполните npx skills add pydantic/skills --skill migrating-claude-agent-sdk-to-pydantic-ai -a claude-code. Скилл окажется в ~/.claude/skills/migrating-claude-agent-sdk-to-pydantic-ai/SKILL.md.

Что делает этот скилл?

Проводит миграцию Python-приложения с Claude Agent SDK на Pydantic AI: сначала трассирует исходный код и фиксирует контракты, затем переносит минимальный полный путь вызова и проверяет результат тестами.

Когда скилл не подходит?

Он не для Anthropic Messages SDK и не для Claude Managed Agents. Также он не берётся за возможности Claude, которые в коде не наблюдаются.

Исходный текст

SKILL.md · MIT
---
name: migrating-claude-agent-sdk-to-pydantic-ai
description: Migrate Python applications from the Claude Agent SDK to Pydantic AI and, only when needed, Pydantic AI Harness. Use when source code imports `claude_agent_sdk` or relies on Claude Code's agent loop, sessions, built-in tools, hooks, permissions, skills, or subagents. Do not use for the Anthropic Messages SDK or Claude Managed Agents.
---

# Migrate Claude Agent SDK to Pydantic AI

Preserve observable behavior, not the Claude Code process or API shape. Migrate the smallest complete caller path and keep application infrastructure in place.

## Trace the source before choosing a target

1. Read repository instructions, dependencies, tests, and the runtime entrypoint. Record the installed Claude Agent SDK, bundled Claude Code CLI, Pydantic AI, and Harness versions.
2. Trace one real request from `query()` or `ClaudeSDKClient` through prompts, tools, events, results, state, persistence, approvals, and side effects that callers use. Establish a focused baseline or characterization test.
3. Separate these source contracts when present:
   - fresh `query()` calls, live `ClaudeSDKClient` continuation, disk/external-store resume, transcript forks, and file rewind;
   - tool availability, automatic approval, policy callbacks, and OS/container isolation;
   - completed messages, raw token deltas, lifecycle events, and terminal results;
   - conversation history, workflow checkpoints, model-owned plans, long-term memory, and workspace state;
   - model-directed subagents from application-owned loops, queues, retries, and schedulers.
4. Record each observed contract, its owner, semantic difference, and executable proof. An unobserved Claude Code feature is not migration scope.

Read [Research and concept mapping](references/RESEARCH-AND-MAPPING.md) for the detected source features. Read [Verification and cutover](references/VERIFICATION-AND-CUTOVER.md) before implementation.

## Choose the smallest target

- **Core:** use `pydantic_ai.Agent` for model calls, the agent loop, typed dependencies, tools, outputs, normalized messages, generic hooks, streaming, MCP, approvals, usage limits, instrumentation, and durable-runtime integrations.
- **Harness:** add `pydantic-ai-harness` only for observed reusable policy such as coding filesystem/shell tools, repository context, planning, memory, model-directed subagents, model-agnostic context management, or Agent Skills. Harness capabilities compose through the core agent loop; Harness is not a second runtime.
- **Application:** retain authentication, service clients, databases, queues, schedulers, deployment, product state, session lookup, tenant policy, and existing transports unless the requested slice includes them.
- **Gap:** name behavior that no supported public seam preserves, explain its impact, and test a bounded adapter. Do not create a lookalike `ClaudeSDKClient` or emulate Claude transcript files merely to hide a difference.

The normal migration is one reusable `Agent`, application services supplied through typed dependencies, ordinary Pydantic AI tools, a typed output when the caller expects structure, and application-owned storage of `result.all_messages()` when later turns need context. Preserve the existing public request/response/event boundary with a small adapter while callers migrate.

## Apply high-risk gates

- `allowed_tools` in the Claude Agent SDK means auto-approval, not exclusive availability and not isolation. Map availability, approval, policy, and sandboxing independently.
- Pydantic AI `message_history` explicitly replays normalized messages. `conversation_id` correlates runs; it is not a Claude session-resume token. Prove restart and fork behavior rather than renaming IDs.
- Pydantic AI approval defers a validated tool call. The application still owns authenticated authorization, identity, and audit, and the protected effect must not run before approval.
- Map hooks by firing point, inputs, ordering, mutation, blocking, and error behavior. Claude hook matchers may run concurrently. Pydantic AI runs `before_*` hooks in capability order, `after_*` hooks in reverse order, and nests `wrap_*` hooks with the first capability outermost. Require a golden trace for any hook-visible contract.
- Map consumer intent for streaming. Pydantic AI output streaming, run-event streaming, and graph iteration are different surfaces; none promises the Claude SDK message taxonomy.
- Use Harness `SubAgents` only for model-directed delegation. Keep deterministic orchestration and verification loops in application code.
- Harness `Skills` supplies on-demand `SKILL.md` instructions; verify resources and scripts separately instead of assuming Claude Code skill or plugin loading parity.
- Harness command controls are best-effort policy, not an OS security boundary. For untrusted execution, use `ModalSandbox` where it fits or retain application-owned container, VM, or sandbox isolation.
- File rewind, Claude Code prompt presets, plugin packaging, raw stream-event identity, and dynamic MCP control are gaps unless the migrated caller actually needs them and a public target seam is proven.

## Implement and prove one vertical slice

1. Preserve the supported caller boundary and replace only the agent-owned internals.
2. Start core-only. Add the narrowest Harness capabilities only after a source contract requires them.
3. Test inputs, typed outputs, errors, event order, tool arguments/results, approval decisions, state across turns, and side effects at that boundary. Use deterministic models and fake application services for offline tests; add a focused recorded/live test only when provider behavior is the contract.
4. For resume, durability, approvals, concurrent tools, or external effects, test interruption/restart, lineage, authorization, and idempotency at the exact boundary promised by the source.
5. Remove `claude-agent-sdk` only after no retained path imports it, spawns Claude Code, reads its transcripts, or consumes its event/result types.

Explain any consequential semantic change before implementing it: state the source behavior, target behavior, caller impact, recommended choice, and remaining risk.

## Completion

Apply the completion criterion in [Verification and cutover](references/VERIFICATION-AND-CUTOVER.md). Label evidence from fakes, recordings, and live providers accurately.

© pydantic · MIT · pydantic/skills

Похожие скиллы

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
migrating-ai-sdk-to-common-ai astronomer Переводит Airflow-проекты с airflow-ai-sdk на официальный провайдер apache-airflow-providers-common-ai 0.4.0+. Пригодится, когда LLM-декораторы и конфигурация моделей переезжают на соединения. CX Codex +1 348установок agent-sdk-verifier-py официальный Anthropic Проверяет Python-приложение на базе Agent SDK: конфигурацию, вызовы SDK, безопасность и готовность к тестированию или развёртыванию. ★ 44 635звёзд репо migrating-airflow-2-to-3 astronomer Помогает перевести код DAG с Airflow 2.x на 3.x: импорты, операторы, хуки, работа с метаданными. Пригодится, когда проект пора обновлять, а вручную искать все breaking changes лень. CX Codex +1 1 100установок migrating-motoko-actors caffeinelabs Помогает переносить состояние актора Motoko между апгрейдами канистры и менять схему stable-полей через цепочку миграций в migrations/. CX Codex +1 4 300установок migrating-to-workflow-sdk Vercel Inc. Помогает перевести оркестрацию с Temporal, Inngest, Trigger.dev или AWS Step Functions на Workflow SDK и выдаёт готовый план миграции с кодом. CX Codex +1 734установок migrating-workflow-v4-to-v5 Vercel Inc. Переводит приложение с Workflow SDK 4.x на 5.0: подсказывает, какие зависимости поднять и какие вызовы переписать. CX Codex +1 310установок

Из того же набора12

pydantic Скилл для работы с Pydantic: подсказывает, как описывать модели, ограничения полей и валидаторы, когда агенту нужно разобрать внешние данные. CX Codex +1 2 200установок logfire-query Выполняет SQL-запросы к телеметрии Logfire прямо через агента. Скилл нужен для поиска медленных спанов, группировки исключений и расчёта метрик. CX Codex +1 1 900установок logfire-ui Открывает экраны Logfire, трейсы и живой просмотр в браузере без предварительных запросов к телеметрии. CX Codex +1 1 600установок logfire-setup Разбирает широкий запрос «настрой мне Logfire» и отправляет агента к нужному специалисту: инструментация приложения, инфраструктура, evals, фронтенд, Gateway. CX Codex +1 555установок logfire-evals Прогоняет офлайн-оценки Python и Node.js, разбирает отчёты в Logfire и перенаправляет существующие наборы Braintrust. CX Codex +1 554установок migrating-langchain-to-pydantic-ai Скилл для переноса Python-приложений с LangChain, LangGraph и Deep Agents на Pydantic AI. Пригодится, когда нужно сохранить поведение, а не форму фреймворка. CX Codex +1 314установок migrating-vercel-ai-sdk-and-eve-to-pydantic-ai Переводит приложения на TypeScript Vercel AI SDK или Eve на Python с Pydantic AI. Полезен, когда нужно сохранить поведение, а не API исходника. CX Codex +1 306установок migrating-mastra-to-pydantic-ai Скилл переносит TypeScript-приложения на Mastra в Python с Pydantic AI. Пригодится, когда код импортирует @mastra/* или использует агентов, инструменты и воркфлоу Mastra. CX Codex +1 304установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой