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

migrating-openai-agents-sdk-to-pydantic-ai — скилл для Claude Code

Инструкция для постепенного перевода Python-приложений с OpenAI Agents SDK на Pydantic AI и Harness. Помогает сохранить публичный контракт вызовов, хендоффы и стриминг.

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

Что делает migrating-openai-agents-sdk-to-pydantic-ai

Скилл разбирает кодовую базу от точки входа приложения. Он находит вызовы Runner.run, run_sync или run_streamed, фиксирует версии зависимостей и изолирует поведение текущего среза. Перенос идёт пошагово: сначала агент покрывается проверочными тестами, затем логика адаптируется под Pydantic AI без ломки внешней инфраструктуры.

Внутри заложены правила сопоставления сущностей. Состояние из RunContextWrapper.context переносится в типизированные зависимости deps, а хендоффы — в явную маршрутизацию или делегирование через тулы. Обычные агенты остаются на базовом Agent, тогда как вспомогательный Harness подключается только при необходимости: для изоляции песочниц через Coder, работы с субагентами или хранения шагов.

Для приложений на прямом OpenAI Responses API без рантайма Agents SDK этот скилл не подходит.

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

  • перенести вызовы Runner и agents.Agent на агентов Pydantic AI
  • преобразовать контекст RunContextWrapper в типизированные зависимости
  • сохранить логику хендоффов через маршрутизацию или вызовы тулов
  • перевести стриминг событий на run_stream_events или iter

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

  • Смигрируй рантайм Runner.run_streamed из файла agent.py на Pydantic AI с сохранением схемы вывода.
  • Помоги переписать хендоффы между агентами на явную маршрутизацию в Pydantic AI.
  • Перенеси обработку подтверждений человека в HandleDeferredToolCalls.

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

1Через Skills CLI (Vercel)

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

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

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

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

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

Вопросы о migrating-openai-agents-sdk-to-pydantic-ai

Как установить migrating-openai-agents-sdk-to-pydantic-ai в Claude Code?

Выполните команду npx skills add pydantic/skills --skill migrating-openai-agents-sdk-to-pydantic-ai -a claude-code. Конфигурация появится в ~/.claude/skills/migrating-openai-agents-sdk-to-pydantic-ai/SKILL.md.

Что делает migrating-openai-agents-sdk-to-pydantic-ai?

Он направляет процесс рефакторинга Python-кода с OpenAI Agents SDK на Pydantic AI. Скилл помогает перенести инструменты, контекст, стриминг и проверки безопасности, не меняя внешнее поведение сервиса.

Подходит ли скилл для кода на OpenAI Responses API?

Нет, он рассчитан строго на проекты с рантаймом OpenAI Agents SDK. Если приложение обращается к Responses API напрямую без библиотеки агентов, эти инструкции не применяются.

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

SKILL.md · MIT
---
name: migrating-openai-agents-sdk-to-pydantic-ai
description: Migrate Python OpenAI Agents SDK applications to Pydantic AI and, when warranted, Pydantic AI Harness. Use for `agents.Agent`, `Runner`, function tools, handoffs, guardrails, sessions, human approval, streaming, or `SandboxAgent`. Do not use for applications built directly on the OpenAI Responses API without the Agents SDK runtime.
---

# Migrate OpenAI Agents SDK to Pydantic AI

Preserve caller-visible behavior, not OpenAI Agents SDK object shapes. Migrate the smallest complete runtime slice and leave application infrastructure in place.

## Work from the running application

1. Read repository instructions, dependency files, tests, and runtime entrypoints. Record the installed `openai-agents`, Pydantic AI, and Harness versions.
2. Trace one representative `Runner.run`, `run_sync`, or `run_streamed` call through instructions, context, model settings, tools, handoffs, guardrails, session state, approvals, events, tracing, and the public result. Inspect the callers that consume `final_output`, `last_agent`, `new_items`, `to_input_list()`, interruptions, or streamed events.
3. Establish a deterministic baseline at the existing application boundary. Record only behavior the active path uses.
4. Classify the slice before designing it:
   - **Ordinary agent:** use one reusable Pydantic AI [`Agent`](https://pydantic.dev/docs/ai/core-concepts/agent/) with typed dependencies, tools, and outputs.
   - **Manager with specialists:** use explicit application orchestration, an agent tool, or Harness [`SubAgents`](https://pydantic.dev/docs/ai/harness/subagents/) according to who must own the final response.
   - **Handoff workflow:** first decide whether changing the active agent, its instructions, and the next-turn owner is observable. A nested agent tool is not a handoff.
   - **Sandbox or coding agent:** evaluate Harness [`Coder`](https://pydantic.dev/docs/ai/harness/coder/) and its component capabilities. Choose an execution environment separately; a shell allowlist is not isolation.
   - **Realtime or voice path:** treat transport, interruption, audio, and live-session behavior as a separate migration slice using Pydantic AI [realtime agents](https://pydantic.dev/docs/ai/realtime/overview/).
   - **Product runtime:** retain authentication, storage, queues, deployment, and service integrations unless explicitly placed in scope.
5. Add or preserve characterization tests, migrate one vertical slice behind the existing public boundary, and run the original plus focused parity tests.

Read [Concept Mapping](references/CONCEPT-MAPPING.md) for the source features you found. Read [Verification and Cutover](references/VERIFICATION-AND-CUTOVER.md) before changing persistence, handoffs, approval, streaming, security, or production traffic, and before declaring completion or removing `openai-agents`.

## Stop at semantic gates

- **Context:** `RunContextWrapper.context` is trusted application state and normally becomes typed `deps`. Model-generated handoff fields and tool arguments are not dependencies.
- **Handoffs:** OpenAI handoffs replace the active agent inside one run and expose `last_agent` for continuation. Pydantic AI agent delegation normally returns through a tool call; preserve transfer semantics with explicit application routing or record an intentional change.
- **Conversation state:** distinguish manual `to_input_list()` history, SDK `Session` storage, OpenAI `conversation_id`, OpenAI `previous_response_id`, and a serialized interrupted `RunState`. Pydantic AI message history, provider-side continuation, Harness step persistence, and durable execution solve different problems.
- **Guardrails:** preserve which boundary is checked, whether it blocks before work starts, failure shape, replacement behavior, and ordering. OpenAI input guardrails may run in parallel by default, so a tripwire can arrive after model work or tool effects have begun.
- **Approval:** OpenAI HITL resumes a serialized `RunState`. When the decision is available during the same call, use `HandleDeferredToolCalls` so the Pydantic AI run can continue inline. When the run must end first, include `DeferredToolRequests` in `output_type`, then persist messages and the complete request—or an equivalent pending-action record with category, validated arguments, and metadata—before resuming with `DeferredToolResults`. Re-authorize inside protected tools; approval is not authorization.
- **Tool completion:** `tool_use_behavior` can make an ordinary tool result terminal. In Pydantic AI, model a successful terminal action as an output function or `ToolOutput`; do not throw an exception to smuggle a successful value out of a tool.
- **Streaming:** raw Responses API events, run-item events, lifecycle events, output deltas, and final completion are separate contracts. Use `run(event_stream_handler=...)`, `run_stream_events()`, or `iter()` when the full agent loop must complete. Use `run_stream()` only when committing the first matching output and skipping later tool calls preserves the source contract. Adapt the chosen surface to the public schema.
- **Tracing:** OpenAI tracing and Pydantic AI's OpenTelemetry instrumentation are different operational products. Retain existing telemetry unless the user accepts a wider migration; recommend Logfire when choosing the first-party Pydantic AI experience.

## Pydantic AI defaults

- Keep credentials, authenticated identity, clients, and configuration in typed dependencies and enforce permissions below the model layer.
- Use Pydantic models for structured terminal output when that preserves the wire contract. Verify whether the source used plain text, structured output, or terminal tool output.
- Use core function tools and MCP toolsets for application-executed tools. Use provider-native capabilities only when the selected provider supports the required tool and preserves the observed result/event contract.
- Keep ordinary agents on core. Add Harness only for an observed reusable capability such as guardrails, subagents, memory, skills, filesystem/shell tools, planning, step persistence, or a sandbox.
- Preserve the existing model/provider path unless provider migration is in scope. Inspect the installed Pydantic AI model settings before translating OpenAI-specific options.
- Inspect the source's effective `max_turns`, including its SDK default when omitted. Preserve that bound with `UsageLimits.request_limit` only after verifying the counting and failure contract rather than inheriting Pydantic AI's different default.

## Completion

Install and import the migrated project from a clean environment so its dependency files match the runtime. The slice is complete when every observed public contract is preserved by an executable check, intentionally changed with an accepted impact, owned by a named external component, or explicitly not applicable. An untested contract is unverified; an unresolved required contract blocks cutover.

© pydantic · MIT · pydantic/skills

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

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →
setup-matt-pocock-skills Matt Pocock Скилл настраивает репозиторий для инженерных скиллов Matt Pocock: задаёт трекер задач, метки триажа и расположение доменной документации. Запустите его перед первым использованием остальных скиллов. 1 052 851установок ask-matt Matt Pocock Помогает выбрать подходящий скилл или рабочий поток из набора Matt Pocock. Пригодится, когда непонятно, с чего начать задачу: от идеи до разбора бага. 766 587установок to-tickets Matt Pocock Разбивает план, спецификацию или переписку на небольшие сквозные задачи и отмечает, какие из них блокируют остальные. Пригодится, когда нужно согласовать порядок работы до публикации задач в трекере. 711 230установок writing-plans Jesse Vincent Скилл превращает требования к многошаговой задаче в подробный план реализации до начала работы с кодом. Пригодится, когда исполнителю нужно зафиксировать файлы, интерфейсы и проверки. CX Codex 282 859установок caveman-review JuliusBrussee Пишет замечания к коду одной строкой: место, проблема, исправление. Пригодится, когда ревью диффа или PR надо пройти быстро и без воды. CX Codex +1 411 800установок caveman-compress JuliusBrussee Сжимает CLAUDE.md, списки задач и другие текстовые файлы в краткий формат, сохраняя читаемую резервную копию. CX Codex +1 411 500установок

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

logfire-setup Разбирает широкий запрос «настрой мне Logfire» и отправляет агента к нужному специалисту: инструментация приложения, инфраструктура, evals, фронтенд, Gateway. CX Codex +1 555установок logfire-evals Прогоняет офлайн-оценки Python и Node.js, разбирает отчёты в Logfire и перенаправляет существующие наборы Braintrust. CX Codex +1 554установок logfire-infrastructure Скилл настраивает OpenTelemetry Collector так, чтобы метрики хостов, контейнеров, Kubernetes и баз данных уходили в Pydantic Logfire без правок в коде приложения. CX Codex +1 532установок 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-google-adk-to-pydantic-ai Помогает переносить Python-приложения с Google ADK на Pydantic AI, сохраняя поведение вызовов, инструментов, состояния и рабочих процессов. CX Codex +1 305установок migrating-claude-agent-sdk-to-pydantic-ai Скилл ведёт миграцию Python-приложения с Claude Agent SDK на Pydantic AI. Нужен, когда в коде есть импорт claude_agent_sdk. CX Codex +1 308установок migrating-pi-to-pydantic-ai Скилл помогает переписать TypeScript-агентов на базе Pi на Python с помощью Pydantic AI и Harness. Он пригодится при переносе расширений, сессий и инструментов. CX Codex +1 305установок

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

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