diff --git a/.github/RELEASING.md b/.github/RELEASING.md index e69753aa1d..8c832efe7e 100644 --- a/.github/RELEASING.md +++ b/.github/RELEASING.md @@ -107,4 +107,4 @@ Publish v1 alpha versions as GitHub Releases marked as prereleases. The `Codex r 1. Choose an unused `v1.X.Y-alpha.N` tag. Set the root `pyproject.toml` version to `1.X.YaN` and `native/codex/Cargo.toml` to `1.X.Y-alpha.N`. Update both lockfiles. Review the changes to confirm that only the two project versions changed. 2. Open `release/v1.X.Y-alpha.N` from this repository into `v1-alpha`. Wait for the regression suite, the v1 session checks, the four release builds and maintainer approval of the same PR head. Each build installs the optimized SDK wheel on CPython 3.10 and 3.14 and exercises an offline conversation. 3. Download the four `codex---` artifacts from the successful run. Verify each SDK wheel against its `SHA256SUMS`. Keep all four wheels, a combined `SHA256SUMS` with one entry per wheel, the run URL and the four hash-pinned install commands from its summary. -4. After merge, verify that the release commit on `v1-alpha` has the same Git tree as the reviewed PR head. If it differs, prepare a fresh candidate. With publication approval, tag the verified commit and create a GitHub **prerelease**. Attach the four wheels and combined checksum file. Include the run URL, the four platform-specific install commands, and a short example using `from openai_agents import Agent, Runner` in the release notes. Confirm that the downloaded assets match the reviewed hashes. +4. After merge, verify that the release commit on `v1-alpha` has the same Git tree as the reviewed PR head. If it differs, prepare a fresh candidate. With publication approval, tag the verified commit and create a GitHub **prerelease**. Attach the four wheels and combined checksum file. Include the run URL, the four platform-specific install commands, and a short example from the [v1 quickstart](../docs/v1/quickstart.md#4-run-the-tutor) using `from openai_agents import Agent` and `await agent.run(prompt)` in the release notes. Confirm that the downloaded assets match the reviewed hashes. diff --git a/MIGRATION.md b/MIGRATION.md index ac0cd2c341..75d160812e 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -10,7 +10,7 @@ Keep your existing v0 dependency lock and [install v1](native/codex/README.md#in To retain the earlier Python loop, move imports to `openai_agents.classic`. Realtime has its own namespace and uses Classic tools. Voice pipelines remain under Classic. -| Earlier import | v1 import | +| v0 import | v1 import | | --- | --- | | `from agents import Agent, Runner` | `from openai_agents.classic import Agent, Runner` | | `from agents import function_tool` | `from openai_agents.classic import function_tool` | @@ -25,7 +25,7 @@ To retain the earlier Python loop, move imports to `openai_agents.classic`. Real Install the [optional dependencies](native/codex/README.md#install-optional-dependencies) for the features you use, such as `voice`, `any-llm`, or `litellm`. Importing the SDK alone does not install those dependencies. -The repository's historical v0 documentation, examples, and tests still use earlier imports in places. Apply this mapping to copied examples. If you used `agents.classic` from an earlier v1 build, replace that prefix with `openai_agents.classic`. +Apply this mapping to imports in examples you copy from the v0 documentation. Check each import before replacing a prefix. An application can also have its own module named `agents`. Update dynamic imports and test patch targets, and check third-party libraries for dependencies on the old package path. @@ -45,7 +45,7 @@ async def answer(model: str, prompt: str) -> str: ## Port a text turn to Codex -Import `Agent` and `Runner` from `openai_agents` to use Codex. These are the same classes exported by `openai_agents.codex`. If you used an earlier Codex build with `agents` imports, move its helpers to `openai_agents.codex` and check the current [session API](native/codex/README.md#run-and-resume-a-conversation). +Import `Agent` from `openai_agents`, omit `name`, and replace `await Runner.run(agent, prompt)` with `await agent.run(prompt)`. Both `Runner` and `Agent.name` are deprecated in the v1 Codex runtime. If you use a Classic model adapter, review routing and credentials before you switch. Codex sends its own model requests. @@ -55,19 +55,19 @@ Set `OPENAI_API_KEY` and `OPENAI_MODEL` in the v1 environment. Save this as `gui import asyncio import os -from openai_agents import Agent, Runner +from openai_agents import Agent async def answer(model: str, prompt: str) -> str | None: - agent = Agent(name="Guide", model=model, instructions="Help plan a trip.") - result = await Runner.run(agent, prompt) + agent = Agent(model=model, instructions="Help plan a trip.") + result = await agent.run(prompt) return result.output_text print(asyncio.run(answer(os.environ["OPENAI_MODEL"], "Suggest a walk in Lisbon."))) ``` -`await agent.run(prompt)` uses the same Codex API as `await Runner.run(agent, prompt)`. Read `output_text` for Codex and `final_output` for Classic. If Codex returns no final text, `output_text` is `None`. +Read `output_text` for Codex and `final_output` for Classic. If Codex returns no final text, `output_text` is `None`. ## Check what the workflow relies on diff --git a/README.md b/README.md index 3773ee44fd..b5a1262b21 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Build a Python agent powered by the **Codex harness**. Give your agent an [order ## Installation 1. Use your project's Python environment, or [create one](native/codex/README.md#create-an-environment). -2. Choose a v1 release from [GitHub Releases](https://github.com/openai/openai-agents-python/releases) whose example imports `openai_agents`. +2. Find the latest v1 release on [GitHub Releases](https://github.com/openai/openai-agents-python/releases). 3. Run the pip command for your platform from the release notes. The wheel includes the compiled Codex engine. 4. Set `OPENAI_API_KEY` and `OPENAI_MODEL` as shown below. @@ -54,7 +54,7 @@ Save this order lookup as `orders.py`. import asyncio import os -from openai_agents import Agent, Runner +from openai_agents import Agent from openai_agents.codex import function_tool @@ -69,7 +69,7 @@ agent = Agent( instructions="Use delivery_date to check the order before you answer.", tools=[delivery_date], ) -result = asyncio.run(Runner.run(agent, "When will order A12 arrive?")) +result = asyncio.run(agent.run("When will order A12 arrive?")) print(result.output_text) ``` @@ -86,6 +86,7 @@ The answer should report Friday as the delivery day. ## Next steps +- Use `agent.stream(prompt)` for live output or `agent.session()` for follow-up questions. Try the [quickstart examples](docs/v1/quickstart.md#stream-the-answer). - Give an agent [access to files or commands](native/codex/README.md#choose-where-to-run-commands). - Continue or resume a conversation with [sessions and checkpoints](native/codex/README.md#run-and-resume-a-conversation). diff --git a/docs/v1/index.md b/docs/v1/index.md index 412a9cc7af..0ab83be83a 100644 --- a/docs/v1/index.md +++ b/docs/v1/index.md @@ -41,7 +41,7 @@ Save this order lookup as `orders.py`. import asyncio import os -from openai_agents import Agent, Runner +from openai_agents import Agent from openai_agents.codex import function_tool @@ -56,7 +56,7 @@ agent = Agent( instructions="Use delivery_date to check the order before you answer.", tools=[delivery_date], ) -result = asyncio.run(Runner.run(agent, "When will order A12 arrive?")) +result = asyncio.run(agent.run("When will order A12 arrive?")) print(result.output_text) ``` @@ -73,6 +73,7 @@ Check that the answer reports Friday as the delivery day. To see each step, [fol ## Next steps +- [Stream the answer](quickstart.md#stream-the-answer) with `agent.stream(prompt)` or [ask a follow-up](quickstart.md#ask-a-follow-up) with `agent.session()`. - Give an agent access to files or commands by choosing [where code runs](runtime.md#where-code-runs). - Continue a conversation or resume it later with [sessions and checkpoints](runtime.md#what-survives-the-turn). - For a v0 workflow, start with [Compare v0 and v1](migration.md). If it uses a Python model adapter such as LiteLLM, keep it on the supported **Classic** subpackage, `openai_agents.classic`, while you migrate. diff --git a/docs/v1/migration.md b/docs/v1/migration.md index f95e688141..6093a6ae62 100644 --- a/docs/v1/migration.md +++ b/docs/v1/migration.md @@ -4,11 +4,11 @@ Both versions use the `openai-agents` distribution name. The **import selects th ## The same tutor, side by side -Both examples use `Runner.run`. The import changes which code runs when you call it. Set `OPENAI_API_KEY` and `OPENAI_MODEL` in each environment as described in the [quickstart](quickstart.md#4-run-the-tutor). +In v1, import `Agent` from `openai_agents` and call `await tutor.run(q)`. Set `OPENAI_API_KEY` and `OPENAI_MODEL` in each environment as described in the [quickstart](quickstart.md#4-run-the-tutor).
-```python title="v0 · Python" hl_lines="4 15" +```python title="v0 · Python" hl_lines="4 10 14 15" import asyncio import os @@ -29,21 +29,18 @@ async def main(): asyncio.run(main()) ``` -```python title="v1 · Codex" hl_lines="4 15" +```python title="v1 · Codex" hl_lines="4 9 11 12" import asyncio import os -from openai_agents import Agent, Runner +from openai_agents import Agent async def main(): model = os.environ["OPENAI_MODEL"] - tutor = Agent( - name="Tutor", - model=model, - ) + tutor = Agent(model=model) q = "Why was Rome built on hills?" - result = await Runner.run(tutor, q) + result = await tutor.run(q) print(result.output_text) @@ -58,10 +55,10 @@ Save either example as `tutor.py` and run `python tutor.py` in its environment. | Task | Python loop (v0) | Codex runtime (v1 default) | | --- | --- | --- | -| Define an agent | `Agent(name=...)` requires a name and can use a default model. | [`Agent(model=...)`](ref/codex/agent.md) requires a model ID. The name is optional. Instructions extend the Codex base instructions. | -| Run a turn | `await Runner.run(agent, prompt)` | The same call, or `await agent.run(prompt)`. | -| Read the answer | `result.final_output` can be text or a typed value. | `result.output_text` is text or `None`. `result.final_output` returns the same value. | -| Register a function | Use a Python-loop tool, such as `agents.function_tool`. | Use [`openai_agents.codex.function_tool`](ref/codex/tool.md). Register the function with the Codex agent. | +| Define an agent | `Agent(name=...)` requires a name and can use a default model. | Pass a model ID to [`Agent(model=...)`](ref/codex/agent.md) and omit the deprecated `name` argument. Codex appends `instructions` to its base instructions. | +| Run a turn | `await Runner.run(agent, prompt)` | Call `await agent.run(prompt)` and drop the `Runner` import. The Codex `Runner` is deprecated. | +| Read the answer | `result.final_output` can be text or a typed value. | `result.output_text` is text or `None`. | +| Register a function | Decorate the function with `agents.decorators.tool` or `agents.function_tool`. | Decorate it with [`openai_agents.codex.function_tool`](ref/codex/tool.md) and pass it in `Agent(tools=[...])`. | | Stream a turn | `Runner.run_streamed(agent, prompt)`, then iterate over `result.stream_events()`. | `async with agent.stream(prompt) as events`, then iterate over `events`. Use `await events.get_final_result()` for the result. The event types differ. | | Continue a conversation | Pass a session to `Runner.run` or reuse `result.to_input_list()`. | Open a [Codex session](ref/codex/session.md) for multiple turns, pass `state=result.state` to the next run, or resume by ID with Codex storage. | diff --git a/docs/v1/quickstart.md b/docs/v1/quickstart.md index d5e66e63ad..e29a97c3bb 100644 --- a/docs/v1/quickstart.md +++ b/docs/v1/quickstart.md @@ -26,7 +26,7 @@ py -3 -m venv .venv If you need v0 and v1 installed side by side, use separate environments. Both versions use the `openai-agents` distribution name, so installing v1 replaces v0 in that environment. -Open [GitHub Releases](https://github.com/openai/openai-agents-python/releases) and choose a v1 release whose examples import `openai_agents`. Earlier v1 releases use the old `agents` imports and cannot run this guide. If no compatible release exists, Linux x86-64 users can [build from source](#build-from-source), while other platforms need a matching release wheel. +Open the latest v1 release on [GitHub Releases](https://github.com/openai/openai-agents-python/releases). Linux x86-64 users can also [build from source](#build-from-source). Use the wheel for the system running Python. @@ -69,7 +69,7 @@ Save this as `tutor.py`. import asyncio import os -from openai_agents import Agent, Runner +from openai_agents import Agent async def main(): @@ -77,7 +77,7 @@ async def main(): model=os.environ["OPENAI_MODEL"], instructions="You answer history questions clearly and concisely.", ) - result = await Runner.run(tutor, "When did the Roman Empire fall?") + result = await tutor.run("When did the Roman Empire fall?") print(result.output_text) @@ -87,4 +87,28 @@ if __name__ == "__main__": Run `python tutor.py`. The tutor makes a billable model request and prints its answer. Codex runs the loop locally and calls the model over the network. This example grants no shell or file tools. -Next, [give the agent a Python tool](runtime.md) or [compare the same call in v0 and v1](migration.md). +## Stream the answer + +To print text as it arrives, add `from openai_agents.codex import TextDelta` to the imports in `tutor.py`. Replace the `tutor.run(...)` assignment and the `print(...)` line in `main()` with this block. + +```python + async with tutor.stream("When did the Roman Empire fall?") as events: + async for event in events: + if isinstance(event, TextDelta): + print(event.delta, end="", flush=True) + print() +``` + +## Ask a follow-up + +To give the tutor access to the first question and its answer during the second turn, keep a session open. Replace the two lines after the tutor definition in the original `main()` with this block. + +```python + async with tutor.session() as session: + first = await session.run("When did the Western Roman Empire fall?") + print(first.output_text) + second = await session.run("Who was emperor at the time?") + print(second.output_text) +``` + +Next, [give the agent a Python tool](runtime.md), [save a conversation](runtime.md#what-survives-the-turn), or [compare the same call in v0 and v1](migration.md). diff --git a/docs/v1/runtime.md b/docs/v1/runtime.md index c7b9a54c08..935f731679 100644 --- a/docs/v1/runtime.md +++ b/docs/v1/runtime.md @@ -1,6 +1,6 @@ # How the Codex runtime works -The **Codex harness** runs the agent loop inside your Python process. In v1, `openai_agents.Runner` calls the Rust Codex core to send a request to the model. If the model requests a tool, the harness runs the tool and sends the result back to the model. This repeats until the turn ends. +The **Codex harness** runs the agent loop inside your Python process. When you call `await agent.run(prompt)`, the Rust Codex core sends a request to the model. If the model requests a tool, the harness runs the tool and sends the result back to the model. This repeats until the turn ends. ## Follow an order lookup through one turn @@ -10,7 +10,7 @@ Suppose a customer asks when their order will arrive. Only your application know import asyncio import os -from openai_agents import Agent, Runner +from openai_agents import Agent from openai_agents.codex import function_tool @@ -26,7 +26,7 @@ async def main(): instructions="Use delivery_date to check the order before you answer.", tools=[delivery_date], ) - result = await Runner.run(agent, "When will order A12 arrive?") + result = await agent.run("When will order A12 arrive?") print(result.output_text) @@ -36,7 +36,7 @@ if __name__ == "__main__": When the model requests the lookup, the turn goes through four steps. -1. **Python starts the turn.** `Runner.run(agent, prompt)` passes the prompt, instructions, and tool definition through a Python binding (PyO3) to the Rust Codex engine in the same process. `agent.run(prompt)` takes the same path. +1. **Python starts the turn.** `agent.run(prompt)` passes the prompt, instructions, and tool definition through a Python binding (PyO3) to the Rust Codex engine in the same process. 2. **Codex calls the model.** The model sees the description and argument schema for `delivery_date`. It can request a call with `order_id="A12"`. The function body stays in your application. 3. **Python runs the tool.** The SDK dispatches the call to `delivery_date` on your worker. Codex adds the returned value, `Friday`, to the conversation and sends the next request. A turn can include several tool calls. 4. **Python receives the result.** When the model finishes, the [result](ref/codex/result.md) includes the reply, the items produced during the turn, usage, and a checkpoint. For a live UI, use `agent.stream(prompt)` to receive [events](ref/codex/events.md) as the turn progresses. diff --git a/examples/codex/tool_access.md b/examples/codex/tool_access.md index 128635e221..984623aedc 100644 --- a/examples/codex/tool_access.md +++ b/examples/codex/tool_access.md @@ -78,29 +78,11 @@ Discovery is eager and reads the server's tool metadata before applying the allo ## Load explicit project guidance -Choose trusted absolute paths for the project root, working directory, and optional user guidance. Review project files before treating their contents as instructions. The loader returns a `ProjectInstructions` snapshot containing `instructions`, `sources`, and hashes. +For an agent that already runs in a trusted workspace, place reviewed project guidance in `AGENTS.md`. Codex discovers the file when it opens the workspace. Passing its contents through `Agent.instructions` as well would duplicate the guidance. -```python -from pathlib import Path - -from openai_agents import Agent -from openai_agents.codex.extensions.project_instructions import load_project_instructions - - -def project_agent(model: str, root: Path, cwd: Path, user_file: Path) -> Agent: - snapshot = load_project_instructions( - root=root, - cwd=cwd, - user_file=user_file, - filenames=("APP_GUIDE.md",), - max_bytes=32768, - ) - return Agent(model=model, instructions=snapshot.instructions) -``` - -Place reviewed application guidance in `APP_GUIDE.md` under the selected root. The loader reads matching files from root to cwd, after the explicit user file. Imports remain disabled unless the application enables them and grants each imported file explicitly. Paths must not contain symlink components, and cwd must be under root. +For a run with `environment=None`, pass reviewed text directly to `Agent(model=model, instructions=trusted_text)`. Enabling a workspace also grants access to shell and file tools. -A workspace can independently discover `AGENTS.md` through the native engine. Passing the same file through `Agent.instructions` would duplicate it. The custom filename above avoids that duplication. The snapshot records what the loader read and does not attest to the engine's separate discovery settings. +If your application reads instructions from custom files, enforce its file access and size limits before passing the text to the agent. ## Handle structured gateway status diff --git a/native/codex/README.md b/native/codex/README.md index 37051d5e44..6403c20b9b 100644 --- a/native/codex/README.md +++ b/native/codex/README.md @@ -33,7 +33,7 @@ py -3 -m venv .venv ### Install from a GitHub Release -Open [GitHub Releases](https://github.com/openai/openai-agents-python/releases) and select a v1 release whose examples import `openai_agents`. Earlier v1 releases can use the old `agents` imports. If no release with the new imports has been published, [build from source](#build-from-source). +Open the latest v1 release on [GitHub Releases](https://github.com/openai/openai-agents-python/releases). Copy the install command for your platform from the release notes and run it in your activated environment. The command pins the wheel URL and SHA-256 digest. pip checks the digest, then installs the wheel and its dependencies. [Check the installation](#check-the-installation) before running an example. @@ -72,19 +72,19 @@ Save this as `first_turn.py` and run `python first_turn.py`. Expect a billable m import asyncio import os -from openai_agents import Agent, Runner +from openai_agents import Agent async def main(): agent = Agent(model=os.environ["OPENAI_MODEL"]) - result = await Runner.run(agent, "Pick a neighborhood in Lisbon.") + result = await agent.run("Pick a neighborhood in Lisbon.") print(result.output_text) asyncio.run(main()) ``` -`await agent.run(...)` accepts the same run arguments and returns the same result as `await Runner.run(agent, ...)`. Both run Codex. Other Codex helpers live under `openai_agents.codex`. Classic uses its own `Agent`, `Runner`, and tools. See the [migration guide](../../MIGRATION.md). +Use `agent.stream(prompt)` for live events or `agent.session()` to keep a conversation open across turns. Other Codex helpers live under `openai_agents.codex`. To port a v0 workflow, follow the [migration guide](../../MIGRATION.md). For Python application patterns on `v1-alpha`, see the [application workflow examples](./../../examples/codex/README.md#application-workflows). @@ -116,7 +116,7 @@ async def main(): asyncio.run(main()) ``` -Keep the database and its adjacent `sessions.db.locks/` directory private on a local filesystem. SQLite holds an exclusive lock per ID throughout each turn. A shared guard protects opening and removing temporary lock files. Normally, only the fixed gate file remains while the store is idle. Abrupt worker death releases ownership. The next owner of that ID can reclaim any unused file left behind. Upgrade all Codex workers sharing the database together. Older pre-release Codex workers did not use the guard. +Keep the database and its adjacent `sessions.db.locks/` directory private on a local filesystem. SQLite holds an exclusive lock per ID throughout each turn. A shared guard protects opening and removing temporary lock files. Normally, only the fixed gate file remains while the store is idle. Abrupt worker death releases ownership. The next owner of that ID can reclaim any unused file left behind. Upgrade all Codex workers sharing the database together. Treat snapshots as trusted application data. They include conversation history and can include instructions and a local workspace path. For multiple hosts, use a shared `SessionStorage` implementation with an exclusive lock per ID. @@ -185,7 +185,7 @@ Pass `Sandbox(id="build-7", url="wss://gateway.example.com/sandboxes/build-7", c ## Store sessions in Postgres -Install the `postgres` extra as described under [optional dependencies](#install-optional-dependencies). Initialize the store once at application startup. Use the same database and conversation ID on each worker. +Install the `postgres` extra as described under [optional dependencies](#install-optional-dependencies). Initialize the store at application startup. Workers can resume a session using the same database and session ID. ```python import asyncio @@ -194,19 +194,23 @@ import os from openai_agents import Agent from openai_agents.codex.postgres import PostgresConversationStore + async def main(): - store = PostgresConversationStore(os.environ["DATABASE_URL"]) - await store.initialize() + storage = PostgresConversationStore(os.environ["DATABASE_URL"]) + await storage.initialize() agent = Agent(model=os.environ["OPENAI_MODEL"]) - first = await agent.run("Pick a cafe.", store=store, conversation_id="booking-42") - second = await agent.run("Which one?", store=store, conversation_id="booking-42") - assert second.state.thread_id == first.state.thread_id + async with agent.session(storage=storage) as session: + session_id = session.id + # Save session_id in your application before starting the first turn. + await session.run("Pick a cafe in Lisbon.") + result = await agent.run("Why that one?", storage=storage, session_id=session_id) + print(result.output_text) asyncio.run(main()) ``` -The store holds a transaction and connection for the turn. A competing worker receives `RunError(code="conversation_busy")`. If a commit fails, inspect the stored state before retrying because tools may already have performed side effects. +The store holds a transaction and connection for each lock. If another worker holds the lock, the SDK raises `RunError` with code `conversation_busy`. If worker A opens a session and worker B updates it before worker A starts its turn, worker A receives `RunError` with code `session_changed`. Reopen the session by ID to read the latest checkpoint. If a commit fails, inspect the stored state before retrying because tools may already have performed side effects. ## Hooks, approvals, and child agents diff --git a/src/openai_agents/codex/agent.py b/src/openai_agents/codex/agent.py index 737ee8cfdd..a4655a006f 100644 --- a/src/openai_agents/codex/agent.py +++ b/src/openai_agents/codex/agent.py @@ -6,6 +6,8 @@ from types import EllipsisType from typing import Literal +from typing_extensions import deprecated as _deprecated + from openai_agents.codex.approvals import ApprovalHandler, ApprovalPolicy from openai_agents.codex.environment import Environment from openai_agents.codex.errors import EngineError @@ -35,7 +37,7 @@ class Agent: """The model ID to use for inference.""" name: str | None = None - """A human-readable name for the agent.""" + """Deprecated. Omit `name` and keep any display label in your application.""" instructions: str | None = None """Instructions to append to the default or custom base instructions.""" @@ -92,9 +94,12 @@ def as_tool( A trusted output extractor can inspect the completed result and validate its returned text. - Errors and cancellation follow the existing function-tool and Runner lifecycle. + Errors and cancellation follow the function-tool and agent run lifecycle. The application owns durable nested resume, execution limits, and completion verification. + + `workspace=path` and `sandbox=box` are deprecated. Use + `environment=LocalEnvironment(workspace_directory=path)` or `environment=box`. """ @function_tool( @@ -127,7 +132,11 @@ def session( storage: SessionStorage | None = None, session_id: str | None = None, ) -> Session: - """Open a conversation for multiple turns with `async with`.""" + """Open a conversation for multiple turns with `async with`. + + `workspace=path` and `sandbox=box` are deprecated. Use + `environment=LocalEnvironment(workspace_directory=path)` or `environment=box`. + """ return Session( self, environment=environment, @@ -152,7 +161,16 @@ async def run( store: ConversationStore | None = None, conversation_id: str | None = None, ) -> RunResult: - """Run one turn in a fresh session from an explicit snapshot or a stored ID.""" + """Run one turn in a fresh session, optionally resuming from a snapshot or stored ID. + + The following arguments are deprecated. + + - `text=` → pass the prompt positionally or use `input=`. + - `workspace=path` → use `environment=LocalEnvironment(workspace_directory=path)`. + - `sandbox=box` → use `environment=box`. + - `store=` and `conversation_id=` → start a session with `storage=`. To resume, + pass `storage=`, the stored Codex `session_id=` and the current `environment=`. + """ text = _turn_input(input, text) return await _drain( self.stream( @@ -183,7 +201,16 @@ async def stream( store: ConversationStore | None = None, conversation_id: str | None = None, ) -> AsyncGenerator[RunEvent, None]: - """Yield live events, then the result after shutdown and any store commit.""" + """Yield live events, then the result after shutdown and any store commit. + + The following arguments are deprecated. + + - `text=` → pass the prompt positionally or use `input=`. + - `workspace=path` → use `environment=LocalEnvironment(workspace_directory=path)`. + - `sandbox=box` → use `environment=box`. + - `store=` and `conversation_id=` → start a session with `storage=`. To resume, + pass `storage=`, the stored Codex `session_id=` and the current `environment=`. + """ text = _turn_input(input, text) if store is not None and storage is not None: raise ValueError("Pass either store or storage") @@ -212,8 +239,9 @@ async def stream( yield result +@_deprecated("Use await agent.run(prompt).", category=None) class Runner: - """Run a turn with a Codex agent.""" + """Deprecated. Use `await agent.run(prompt)` for a Codex turn.""" @staticmethod async def run( @@ -230,7 +258,7 @@ async def run( store: ConversationStore | None = None, conversation_id: str | None = None, ) -> RunResult: - """Run the agent once, using the same session options as Agent.run.""" + """Deprecated. Use `await agent.run(prompt)` and see `Agent.run` for keyword migrations.""" if not isinstance(agent, Agent): raise TypeError("Use openai_agents.classic.Runner for Classic agents") return await agent.run( diff --git a/src/openai_agents/codex/engine.py b/src/openai_agents/codex/engine.py index 54aa927ed9..7e1517e25f 100644 --- a/src/openai_agents/codex/engine.py +++ b/src/openai_agents/codex/engine.py @@ -13,6 +13,8 @@ from types import EllipsisType, ModuleType from typing import TYPE_CHECKING, Any, Protocol +from typing_extensions import deprecated as _deprecated + from openai_agents.codex.approvals import ApprovalHandler, ApprovalRequest, _approve from openai_agents.codex.environment import Environment, LocalEnvironment, _resolve_environment from openai_agents.codex.errors import EngineError, RunError, ToolError, _error_info @@ -257,8 +259,13 @@ def check() -> None: return output +@_deprecated("Use agent.run(), agent.stream(), or agent.session().", category=None) class Engine: - """An embedded Codex engine. Open with `async with Engine()` and run one turn at a time.""" + """Deprecated. Use `agent.run()` or `agent.stream()` for one turn. + + Use `agent.session()` for a live conversation and `openai_agents.codex.codex_version()` + to check the embedded runtime version. + """ def __init__(self) -> None: self.codex_version: str | None = None @@ -302,7 +309,7 @@ async def run( store: ConversationStore | None = None, conversation_id: str | None = None, ) -> RunResult: - """Run one turn from an explicit snapshot or a conversation in a store.""" + """Deprecated. Use `await agent.run(prompt)` and see `Agent.run` for keyword migrations.""" text = _turn_input(input, text) return await _drain( self.stream( @@ -331,7 +338,10 @@ async def stream( store: ConversationStore | None = None, conversation_id: str | None = None, ) -> AsyncGenerator[RunEvent, None]: - """Yield live events followed by a RunResult. Closing early shuts down this engine.""" + """Deprecated. Use `agent.stream(prompt)` and see `Agent.stream` for keyword migrations. + + Closing this stream early shuts down the engine. + """ text = _turn_input(input, text) if self._busy: raise EngineError("Engine is already busy") diff --git a/src/openai_agents/codex/events.py b/src/openai_agents/codex/events.py index 99a8a35897..b9d9d7bb0f 100644 --- a/src/openai_agents/codex/events.py +++ b/src/openai_agents/codex/events.py @@ -3,6 +3,8 @@ from dataclasses import dataclass, field from typing import Any, ClassVar, Literal, TypeAlias +from typing_extensions import deprecated as _deprecated + from openai_agents.codex.errors import EngineError, _error_info from openai_agents.codex.items import RunItem, _parse_item from openai_agents.codex.result import RunResult @@ -55,8 +57,11 @@ class CommandOutputDelta: type: Literal["command_output_delta"] = field(default="command_output_delta", init=False) +@_deprecated("Use TextDelta for streamed plan text.", category=None) @dataclass(frozen=True, kw_only=True) class PlanDelta: + """Deprecated. Plans written as assistant text stream as `TextDelta` events.""" + api_type: ClassVar[str | None] = None item_id: str delta: str diff --git a/src/openai_agents/codex/extensions/output.py b/src/openai_agents/codex/extensions/output.py index cb4dd5905f..1a352acf52 100644 --- a/src/openai_agents/codex/extensions/output.py +++ b/src/openai_agents/codex/extensions/output.py @@ -30,7 +30,7 @@ async def accept_output( ) -> AcceptedOutput: """Consume one turn exclusively and return its text only after application acceptance. - Pass an Agent/Session stream or a Runner/Agent/Session run awaitable. + Pass a stream or a run awaitable from an Agent or Session. Each non-result stream event triggers on_progress without exposing event payloads. diff --git a/src/openai_agents/codex/extensions/project_instructions.py b/src/openai_agents/codex/extensions/project_instructions.py index 1950f3ca55..b1ccfd9d25 100644 --- a/src/openai_agents/codex/extensions/project_instructions.py +++ b/src/openai_agents/codex/extensions/project_instructions.py @@ -20,6 +20,8 @@ from pathlib import Path from typing import Literal +from typing_extensions import deprecated as _deprecated + __all__ = ["InstructionSource", "ProjectInstructions", "load_project_instructions"] @@ -64,6 +66,7 @@ def sha256(self) -> str: return hashlib.sha256(self.instructions.encode("utf-8")).hexdigest() +@_deprecated("Use workspace AGENTS.md or pass trusted text to Agent.instructions.", category=None) def load_project_instructions( *, root: Path, @@ -74,7 +77,12 @@ def load_project_instructions( allow_imports: bool = False, import_files: tuple[Path, ...] = (), ) -> ProjectInstructions: - """Load trusted user guidance, then each root-to-cwd directory's named files. + """Deprecated. Let Codex discover `AGENTS.md` in an existing workspace. + + With `environment=None`, pass trusted text to `Agent(instructions=...)`. + Applications that load files must enforce their own source and size limits. + + This loader reads trusted user guidance, then each root-to-cwd directory's named files. Paths must be absolute, without ``..`` or symlink components; cwd must be under root. All configured filenames are loaded in order in each directory. diff --git a/src/openai_agents/codex/items.py b/src/openai_agents/codex/items.py index 6bd4e4776e..eb31049276 100644 --- a/src/openai_agents/codex/items.py +++ b/src/openai_agents/codex/items.py @@ -4,6 +4,8 @@ from dataclasses import dataclass, field from typing import Any, Literal, TypeAlias, cast +from typing_extensions import deprecated as _deprecated + ExecutionStatus: TypeAlias = Literal["in_progress", "completed", "failed", "declined"] @@ -79,11 +81,16 @@ class WebSearchItem(_Item): query: str action: dict[str, Any] | None results: list[dict[str, Any]] | None + """Deprecated. Hosted search sets this to `None`. Inspect `query` and `action`.""" + type: Literal["web_search"] = field(default="web_search", init=False) +@_deprecated("Use MessageItem for plan text in assistant messages.", category=None) @dataclass(frozen=True, kw_only=True) class PlanItem(_Item): + """Deprecated. Read plans written as assistant text from `MessageItem.text`.""" + text: str type: Literal["plan"] = field(default="plan", init=False) diff --git a/src/openai_agents/codex/result.py b/src/openai_agents/codex/result.py index dc1dae14c8..fbcead8d19 100644 --- a/src/openai_agents/codex/result.py +++ b/src/openai_agents/codex/result.py @@ -76,3 +76,4 @@ def items(self) -> list[RunItem]: TurnResult = RunResult +"""Deprecated. Use `RunResult`.""" diff --git a/src/openai_agents/codex/session.py b/src/openai_agents/codex/session.py index cf1aed1e87..4c2cc83639 100644 --- a/src/openai_agents/codex/session.py +++ b/src/openai_agents/codex/session.py @@ -9,6 +9,8 @@ from typing import TYPE_CHECKING from uuid import uuid4 +from typing_extensions import deprecated as _deprecated + from openai_agents.codex.engine import Engine, _Callbacks, _Interrupted, _TurnControl from openai_agents.codex.environment import Environment, _resolve_environment from openai_agents.codex.errors import EngineError, RunError @@ -54,7 +56,11 @@ async def stop(self) -> None: class Session: - """One live conversation. Open with `async with agent.session() as session`.""" + """One live conversation. Open with `async with agent.session() as session`. + + `workspace=path` and `sandbox=box` are deprecated. Use + `environment=LocalEnvironment(workspace_directory=path)` or `environment=box`. + """ def __init__( self, @@ -192,6 +198,8 @@ async def run(self, input: str | None = None, *, text: str | None = None) -> Run before propagating, leaving the session usable after a successful interruption. Cleanup can exceed the deadline; callbacks must cooperate with cancellation. No successor turn is started automatically. + + `text=` is deprecated. Pass the prompt positionally or use `input=`. """ text = _turn_input(input, text) return await _drain(self.stream(text)) @@ -200,7 +208,10 @@ async def run(self, input: str | None = None, *, text: str | None = None) -> Run async def stream( self, input: str | None = None, *, text: str | None = None ) -> AsyncGenerator[RunEvent, None]: - """Yield one turn's events and final result. Closing the iterator stops that turn.""" + """Yield one turn's events and final result. Closing the iterator stops that turn. + + `text=` is deprecated. Pass the prompt positionally or use `input=`. + """ text = _turn_input(input, text) if self._callbacks is None or self._closing is not None: raise EngineError("Session is closed. Open it with 'async with agent.session()'.") @@ -265,8 +276,9 @@ async def interrupt(self) -> None: if self._turn is not None: await self._turn.stop() + @_deprecated("Use await session.interrupt().", category=None) async def cancel(self) -> None: - """Cancel the current turn and wait for its snapshot to be saved.""" + """Deprecated. Call `await session.interrupt()` to stop the turn and await its snapshot.""" await self.interrupt() async def close(self) -> None: diff --git a/src/openai_agents/codex/store.py b/src/openai_agents/codex/store.py index b8538e0503..00f6a87794 100644 --- a/src/openai_agents/codex/store.py +++ b/src/openai_agents/codex/store.py @@ -19,6 +19,11 @@ class StoredConversation: class ConversationStore(Protocol): + """Session storage with an exclusive lock per ID. + + The `ConversationStore` name is deprecated. Import this protocol as `SessionStorage`. + """ + def lock(self, conversation_id: str) -> AbstractAsyncContextManager[StoredConversation]: """Acquire exclusive access to the ID before reading its last committed state. @@ -31,6 +36,7 @@ def lock(self, conversation_id: str) -> AbstractAsyncContextManager[StoredConver SessionStorage = ConversationStore +"""Protocol for reading and saving session snapshots under an exclusive lock per ID.""" class SessionNotFound(RunError): diff --git a/src/openai_agents/codex/tool.py b/src/openai_agents/codex/tool.py index 50205170b6..634d7c075a 100644 --- a/src/openai_agents/codex/tool.py +++ b/src/openai_agents/codex/tool.py @@ -200,6 +200,7 @@ async def handler(arguments: dict[str, Any]) -> str: tool = function_tool +"""Deprecated. Import `function_tool` from `openai_agents.codex`.""" def _tool_arguments(