openai-agents-python/MIGRATION.md
Mark Stuart 3db0653fca
docs: Clarify Python SDK setup, tool names, and output limits (#6014)
docs: simplify Python SDK guides and correct examples

Co-authored-by: markstuart-oai <323302876+markstuart-oai@users.noreply.github.com>
2026-11-14 21:47:20 -08:00

16 KiB

Migrate from v0 to native v1

For an existing v0 application, migrate directly to the native v1 API when you are ready to upgrade. Port each workflow's agent declarations, tools, configuration, and execution together. Use v1 classic only when you need to upgrade the package before you can complete that port.

You can continue using v0. Upgrading to v1 is optional, and classic is not a required intermediate step.

This guide tracks the v1 design on feat/codex-harness, rather than announcing a GA release. The source guides include APIs absent from earlier preview wheels. The contributor setup covers this source; the version guide links documentation for installed releases. Keep the SDK build, documentation, and examples aligned.

Choose your path

Starting point and goal Path Execution after the change
Keep a working v0 application Keep its v0 dependency and imports. The existing Python runner.
Adopt native v1 Upgrade the package and port the workflow to the root agents API. Recommended. The embedded Codex runtime.
Upgrade the package while a workflow still needs the v0 contract Use agents.classic for that workflow, then complete the native port separately. The retained Python runner until the port is complete.
Move a v1 classic workflow to native Follow the same native port below, starting from agents.classic imports. The embedded Codex runtime.

There are two execution APIs in v1: native and classic. SDKRunner and its run handles/results are removed from this development branch. It is not a migration step or an alternative runner.

Prepare the application

  1. Keep the current dependency lock, deployable v0 build, and a copy of persisted application data.
  2. Record the behavior each workflow must retain: model/provider configuration, tool effects, approvals and guardrails, output validation, streaming, cancellation, tracing, and conversation recovery.
  3. Run the existing application tests and evaluations to establish a baseline. Include a representative tool call and a failure or denied-action case.
  4. Install the target SDK in a separate environment using the matching-source setup. Check its platform requirements before replacing a deployment.

You can port and deploy workflows independently. Direct migration means each port goes from the v0 API to native v1 without first rewriting it to classic.

Check compatibility before porting

Classify each required contract before editing imports. Port a whole workflow only when its replacement preserves the behavior your application needs.

Required contract Decision before native cutover
Business functions, typed application context, structured output Port declarations and validation, then test actual tool inputs, outputs, and effects.
Custom Python models/clients or non-Responses endpoints Matching source builds support application-owned model clients, including Chat Completions. Applications check adapter limits and required behavior before native cutover. The published alpha.7 wheel requires Responses support.
Handoffs, guardrails, hooks, or specialized agent settings Redesign and test routing, policy timing, context transfer, and next-turn ownership. A specialist that returns a result is not a handoff. Keep the original engine until those contracts are verified.
Existing sessions, serialized runs, or pending approvals Keep existing work on its owning engine. Start native conversations separately from reviewed business facts; do not convert execution state.
Streaming, cancellation, tracing, and effect recovery Port and verify consumers and resource cleanup. A completed effect is not rolled back by a later failure or cancellation.
MCP, sandbox, voice, or other useful integrations Retain or adapt the existing integration where its API and resource ownership fit. Do not discard working business services just because the loop changes.
Unsupported native platform or a contract with no adequate replacement Stay on v0, or use classic where its package/platform requirements fit. An upgrade is optional.

Port one workflow

Follow the read-only invoice walkthrough for a direct released-v0-to-native port. It uses one agent, one useful tool, typed application context, and typed output. Its matching-source setup keeps the SDK and example code on the same source commit; older preview wheels do not include every migration API from this source snapshot.

The port keeps the business function and data models. Change RunContextWrapper[Application] to ToolContext[Application], declare the tool with the native function_tool, and replace Runner.run(agent, ...) with agent.run(...). The walkthrough includes complete source files, live run commands, and tests without model credentials. Its optional classic step changes imports before applying the same native port.

Native and classic objects are not interchangeable. Keep each workflow's Agent, tools, execution, and state in the same API.

Map the remaining contracts

v0 or v1 classic Native v1 migration
Runner.run() / Runner.run_sync() await agent.run() / agent.run_sync(). Use the synchronous form outside an existing event loop.
Runner.run_streamed() and classic stream events Open agent.session(), submit a Turn, and read turn.events() while awaiting its result. Update event consumers to native observations.
RunContextWrapper[T] in a function tool Use native ToolContext[T] as the first parameter and pass the application object as context=. See application context.
Decorator options such as name_override Re-declare the tool using the native options, such as name=. Check argument, result, and callback rules.
RunConfig, ModelSettings, and mutable Agent fields Set native Agent and Session options explicitly. Native Agents are immutable and native ModelSettings has a different contract. See configuration.
Model, ModelProvider, custom OpenAI clients, or a Chat Completions endpoint Configure NativeProvider for a compatible Responses endpoint. Matching source builds also accept application-owned clients through NativeProvider(model_backend=...), including ChatCompletionsModel(client) and ResponsesModel(client) adapters. The 0.24.0-alpha.7 wheel does not include this option. See application models and provider compatibility.
output_type and result processing Declare the native output type and validate the returned final_output. Check schema limits and validation failures.
Handoffs or agents used as tools Port the application routing or choose native child agents when their model, environment, and lifecycle requirements fit. These are not automatic handoff conversions.
Guardrails, approval callbacks, and lifecycle hooks Map each policy to application validation, native tool policies, or live interactions. Preserve when an action is blocked; do not drop a policy to make the port run.
Classic tracing and usage consumers Configure native telemetry separately and update consumers to the native events and usage contract.
Classic Session stores and RunState Choose native storage separately. Keep existing work on its original engine as described below.

Model defaults, request shapes, tool timing, and event ordering can change when the harness changes. Port the behavior your application needs instead of assuming a name-for-name substitution. In particular, native provider configuration does not read OPENAI_BASE_URL; pass a custom URL explicitly as described in provider configuration.

Keep conversation state with its engine

A classic Session is a history-store interface. A native Session is a live conversation and resource owner; native storage is a separate choice. Reusing an Agent does not preserve conversation history.

For new native conversations, open one Session for follow-up turns:

async with agent.session() as session:
    first = await session.submit("Remember the label atlas.")
    await first.get_result()
    second = await session.submit("What label did I give you?")
    result = await second.get_result()

This fragment belongs inside an async function and uses a configured native agent. The context manager closes the Session and its owned resources.

There is no automatic conversion from v0/classic session history or RunState to native checkpoints. Finish in-flight runs and pending approvals with the engine that created them. You can drain existing conversations on v0 or, after validating the namespace change, on v1 classic while routing new conversations to native.

If an application needs continuity in a fresh native conversation, supply a deliberately prepared summary or application data as new input. That starts a new conversation; it does not resume old tool calls, approval handles, response IDs, or execution state. Reconcile any tool effect with an unknown outcome before continuing.

Keep classic data and native state separate. Native portable checkpoints have their own compatibility rules, including an exact Codex-revision requirement. Retain the producer SDK needed to resume saved work. Switching the package back to v0 does not make native state readable by v0.

Use classic only when staging is necessary

Classic is useful when a package upgrade must happen before a workflow's custom model integration, guardrail/handoff behavior, or stored conversations can move to native. Keep that workflow on agents.classic and verify it independently. Follow classic setup and import mapping; Python classic needs its dependency extra and the same native package/platform requirements still apply.

When the blocker is resolved, apply this guide to that classic workflow. Do not introduce a second compatibility runner or an automatic fallback between engines.

Classic remains available in v1 and is not deprecated by this change. The intended lifecycle is to announce deprecation in a later v1 minor release before removal in v2. No deprecation release or removal date is set here. v0 users can keep their existing version; classic's lifecycle does not force a v0 upgrade.

Preserve useful integrations

Native sandbox and voice integrations remain available under their existing APIs. Prefer direct native MCP declarations for a new integration. Keep an existing client adapter when its authentication, discovery, or connection ownership is useful; it does not make arbitrary classic Agent or Model objects native-compatible.

Reuse a classic MCP client with native declarations

agents.migration.mcp adapts tools from an application-owned Classic MCP client. Use a matching development build for the adapter. If the SDK can own the connection, use native MCP declarations.

Follow the adapter procedure for imports and a runnable selection fragment. The sequence is:

  1. Create an MCPNamespace for your Classic MCPServer. Open the server connection before discovery, either directly or through the namespace's authenticate callback.
  2. Call select_mcp_tools() before opening a native Session. Selection refreshes the client's supported tool cache.
  3. Attach the returned tools to the native Agent. Pass the exact same application context object to selection and execution; an equal but different object is rejected.

Your application owns authentication and connection cleanup. Closing the native Session leaves the Classic client open. Use a separate client for each credential scope and keep that scope stable while its selected tools are in use.

Select tools and preserve policies

Pass tool_names=["search"] to select one tool, omit tool_names to select all tools allowed by the client's filter, or pass an empty list to select none. A missing or filtered-out requested name fails selection. A callable Classic filter also requires filter_context=(run_context, agent), using Classic objects whose run_context.context is the same application context object.

Classic approval requirements, metadata or result hooks, custom error policies, and tool guardrails are unsupported for selected tools. Keep workflows that need them on Classic Runner until you port those policies. For a per-call native policy, the optional approval callback receives a native ToolContext and returns Allow() or Deny(reason), directly or through an awaitable.

MCPNamespace.name has been accepting ASCII letters, digits, underscores, or hyphens. The adapter has been accepting peer tool names containing punctuation or Unicode, up to 4,096 UTF-8 bytes. tool_names has been selecting original peer names, such as read.records.

The adapter has been projecting peer names into native references. Each returned tool's .ref has been supplying its native identity for turn selections. tool_name_overrides has been allowing explicit model-visible names, with projection still resolving collisions and length limits. The combined projected namespace and tool name, including the two separator bytes, has been fitting within 128 bytes. Selected tools have been requiring object input schemas.

Restore selected tools

To restore an idle native checkpoint, select tools again from the current clients with the destination application's context. Match the saved namespace, tool names, and schemas. Discovery and selection do not transfer credentials or persist client connections.

A Session whose catalog contains selected MCP tools cannot suspend for portable manual restore. Answer manual requests in the live Session.

Migrate with a coding agent

A frontier coding agent can confidently carry out the code migration with this guide, your application source, and its tests. Give it the target SDK's matching source or documentation so it can verify APIs rather than infer replacements from v0 names. Ask it to make the direct native port and demonstrate the required behavior.

Use this brief, replacing the bracketed details:

Migrate [workflows] from [current SDK version] directly to the native API
in [target SDK version or source commit]. Follow its MIGRATION.md.
Inspect the application and establish its existing tests/evaluation baseline.
Port declarations, function tools, application context, provider settings,
execution, streaming, approvals/guardrails, tracing, and state ownership together.
Preserve the required application outcomes and effect-prevention policies.
Reuse business logic and independently useful MCP/sandbox/voice integrations.
Do not use SDKRunner, silently switch engines, or convert old RunState/checkpoints.
Keep existing conversations on their original engine and start new native ones.
Use classic only for an identified blocker that makes staging necessary;
explain that blocker and the work needed to remove it.
Run focused tests for tool effects, output validation, denied actions, streaming,
cancellation/cleanup, provider configuration, and conversation recovery as relevant.
Report changes, validation results, remaining gaps, and deployment/state cutover steps.

Review the resulting diff and test evidence before deployment. Compare application outcomes and policy enforcement, rather than requiring identical model text or internal tool ordering. Start new native traffic only after those checks pass, and keep the prior deployment available for conversations that still need it.