• Projects
  • Service
  • About
  • branding.bz
  • Podcast
  • Tips
  • FAQ
  • Recruit
  • Download
  • Contact
  • branding.bz(ブランド構築SaaS)
  • DESIGN NOW(デザインメディア)
  • X
  • LinkedIn
  • Spotify
  • Facebook

213-0011 神奈川県川崎市高津区久本3-6-7-303

© 2026 ID INC. All rights reserved

claude-skills/スキル
SKILLOfficialdevelopment

migrating-openai-agents-sdk-to-pydantic-ai

プラグイン
pydantic-ai
ソース
GitHub で見る ↗
説明

Python OpenAI Agents SDK(OpenAIエージェント開発キット)のアプリケーションを Pydantic AI(別のエージェント構築フレームワーク)に、必要に応じて Pydantic AI Harness(その専用の実行環境)に移行する際に使用します。 **次のような場合に使用:** - `agents.Agent`(エージェントクラス) - `Runner`(実行エンジン) - 関数ツール - ハンドオフ(タスク引き継ぎ) - ガードレール(安全性の制約) - セッション(状態管理) - 人間の承認フロー - ストリーミング出力 - `SandboxAgent`(隔離実行環境) **注意:** OpenAI Responses API を Agents SDK ランタイムなしで直接使用している場合は、このツールの対象外です。

原文を表示

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.

ユースケース
  • OpenAI AgentsをPydantic AIに移行するとき
  • エージェントクラスの実装を変更するとき
  • 実行エンジンを置き換えるとき
  • 安全性制約やガードレール設定を移行するとき
  • 人間承認フロー付きシステムを移行するとき
本文(日本語訳)

OpenAI Agents SDKからPydantic AIへの移行

呼び出し元から見える動作を保つことを優先し、OpenAI Agents SDKのオブジェクト形状にはこだわらない。最小限の完成した動作部分を移行し、アプリケーション基盤はそのままにしておく。

動いているアプリケーションから始める

  1. リポジトリの説明書、依存ファイル、テスト、実行の入口を読む。インストール済みのopenai-agents、Pydantic AI、Harness のバージョンを記録する。

  2. Runner.run、run_sync、run_streamedの呼び出しを1つ代表として選び、説明書、文脈情報、モデル設定、ツール、引き継ぎ(別のエージェントへの処理移行)、ガードレール(安全策)、セッション状態、承認、イベント、トレース、公開結果を通して追跡する。final_output、last_agent、new_items、to_input_list()、中断、ストリーム配信イベントを使う呼び出し元も確認する。

  3. 既存のアプリケーション境界で確定的なベースラインを作る。実際に動く部分が使う動作だけを記録する。

  4. 設計の前に対象の部分を分類する:

    • 通常のエージェント: 型付き依存関係、ツール、出力を持つ再利用可能なPydantic AI Agent を1つ使う。
    • 管理エージェントと専任エージェント: 明示的なアプリケーション制御、エージェントツール、またはHarness SubAgentsを使う。最終的な応答の責任者が誰かで決める。
    • 引き継ぎワークフロー: 現在のエージェント、その指示、次の番のオーナーが変わることが外部から見えるかまず判断する。別のエージェント内のツール呼び出しは引き継ぎではない。
    • サンドボックスまたはコード実行エージェント: Harness Coderと機能要素を評価する。実行環境は別に選ぶ。シェルコマンド許可リストは隔離ではない。
    • リアルタイムまたは音声経路: 通信手段、中断、オーディオ、ライブセッション動作を、Pydantic AI リアルタイムエージェントを使う別の移行対象として扱う。
    • 本番時の動作環境: 認証、ストレージ、キュー、デプロイ、サービス連携は、明確に対象に入れない限り保持する。
  5. 特性確認テストを追加または保持し、既存の公開境界の背後で1つの垂直的な部分を移行して、元のテストと重点的な互換性テストを実行する。

概念対応で見つけた元機能を読む。永続化、引き継ぎ、承認、ストリーム配信、セキュリティ、本番トラフィックを変更する前、また完了を宣言するかopenai-agentsを削除する前に、検証とカットオーバーを読む。

セマンティック(意味的な)チェックポイントで止まる

  • 文脈: RunContextWrapper.contextは信頼できるアプリケーション状態で、通常は型付きのdepsになる。モデルが作った引き継ぎフィールドとツール引数は依存関係ではない。

  • 引き継ぎ: OpenAI の引き継ぎは、1回の実行中に現在のエージェントを置き換え、続行のためにlast_agentを公開する。Pydantic AI のエージェント委譲は通常、ツール呼び出しで戻る。転送の意味を明示的なアプリケーションルーティングで保つか、意図的な変更を記録する。

  • 会話状態: 手動のto_input_list()履歴、SDK のSessionストレージ、OpenAI のconversation_id、OpenAI のprevious_response_id、保存された中断状態RunStateを区別する。Pydantic AI のメッセージ履歴、プロバイダー側での続行、Harness のステップ永続化、堅牢な実行は異なる問題を解く。

  • ガードレール: どの境界でチェックするか、処理開始前にブロックするか、エラー形状、代替動作、順序を保つ。OpenAI の入力ガードレールはデフォルトで並列実行することもあるため、警告信号はモデル処理やツール実行の開始後に到着することがある。

  • 承認: OpenAI の人間による決定(HITL)は保存されたRunStateを再開する。同じ呼び出し中に決定が利用できるなら、HandleDeferredToolCallsを使い、Pydantic AI 実行をインラインで続行できるようにする。実行を先に終わらせるなら、output_typeにDeferredToolRequestsを含め、メッセージと完全なリクエスト(またはカテゴリ、検証済み引数、メタデータを持つ同等の保留中アクション記録)を永続化した後、DeferredToolResultsで再開する。保護されたツール内で再認証する。承認は認可ではない。

  • ツール完了: tool_use_behaviorは普通のツール結果を終了とできる。Pydantic AI では、成功の終了アクションを出力関数またはToolOutputでモデル化する。成功値をツールから密かに持ち出すために例外を投げてはならない。

  • ストリーム配信: 生のResponses APIイベント、実行項目イベント、ライフサイクルイベント、出力差分、最終完了は異なる契約である。完全なエージェントループが終わるまで実行する場合はrun(event_stream_handler=...)、run_stream_events()、iter()を使う。最初にマッチした出力をコミットし、後のツール呼び出しをスキップすることで元の契約を保つ場合だけrun_stream()を使う。選んだ形式を公開スキーマに合わせる。

  • トレース: OpenAI のトレースとPydantic AI のOpenTelemetry(計測の標準規格)計測は異なる運用製品である。ユーザーがより広い移行を認めない限り、既存の計測を保持する。Pydantic AI の第一パーティ体験を選ぶ場合は、Logfire を勧める。

Pydantic AIのデフォルト

  • 認証情報、認証済みアイデンティティ、クライアント、設定は型付き依存関係で保ち、モデル層の下で権限を強制する。

  • 構造化された最終出力にはPydanticモデルを使い、ワイヤプロトコル(データ送受信形式)を保つ。元がプレーンテキスト、構造化出力、または最終ツール出力を使ったか検査する。

  • アプリケーション実行ツールは基本関数ツールとMCPツールセットを使う。プロバイダー固有機能は、選んだプロバイダーが必要なツールをサポートし、見えた結果またはイベント契約を保つときだけ使う。

  • 普通のエージェントはコア機能に保つ。ガードレール、サブエージェント、メモリ、スキル、ファイルシステム/シェルツール、計画、ステップ永続化、サンドボックスのような再利用可能な機能が見えるときだけ、Harness を追加する。

  • 省略されたときのSDKデフォルト値を含めて、有効なmax_turnsを保つ。Pydantic AI の異なるデフォルトを単に引き継ぐのではなく、計算とエラー契約を確認した後でUsageLimits.request_limitでそれを保つ。

  • プロバイダー移行が対象でない限り、既存のモデル/プロバイダーの経路を保つ。OpenAI 固有の選択肢を訳す前に、インストール済みのPydantic AI モデル設定を確認する。

完了

クリーンな環境から移行したプロジェクトをインストールしてインポートし、その依存ファイルが実行時と一致するようにする。すべての見えた公開契約が実行可能なチェックで保たれた、受け入れられた影響で意図的に変更された、名前付き外部要素で所有される、または明確に適用外のいずれかであるとき、その部分は完了している。テストされない契約は未検証であり、未解決の必須契約はカットオーバーをブロックする。

原文(English)を表示

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 with typed dependencies, tools, and outputs.
    • Manager with specialists: use explicit application orchestration, an agent tool, or 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 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.
    • 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 for the source features you found. Read Verification and Cutover 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.

原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。