Codex SDK
如果你通过 Codex CLI、Codex IDE extension 或 Codex cloud 使用 Codex,也可以通过编程方式控制它。
在以下情况下,你可以使用 SDK:
- 将 Codex 集成到 CI/CD 流程中
- 创建能够与 Codex 交互以执行复杂工程任务的智能体
- 将 Codex 集成到你自己的内部工具和工作流中
- 在你自己的应用中集成 Codex
将 Codex SDK 用于以编码为重点的 Codex 线程。如果 Codex 是更广泛编排工作流中的一个专业组件,请将 Codex CLI 作为 MCP 服务器运行,并使用 Agents SDK 对其进行编排。
TypeScript 库
Section titled “TypeScript 库”TypeScript 库提供了一种在应用中控制 Codex 的方式,相比非交互模式更加全面、灵活。
在服务器端使用该库;它要求 Node.js 18 或更高版本。
首先,使用 npm 安装 Codex SDK:
npm install @openai/codex-sdk启动一个 Codex 线程,并使用你的提示词运行它。
const codex = new Codex();const thread = codex.startThread();const result = await thread.run( "Make a plan to diagnose and fix the CI failures");
console.log(result.finalResponse);再次调用 run() 可在同一线程上继续操作;也可以提供线程 ID 来恢复过去的线程。
// running the same threadconst result = await thread.run("Implement the plan");
console.log(result.finalResponse);
// resuming past thread
const threadId = "<thread-id>";const thread2 = codex.resumeThread(threadId);const result2 = await thread2.run("Pick up where you left off");
console.log(result2.finalResponse);如需了解详情,请参阅 TypeScript 仓库。
Python 库
Section titled “Python 库”Python SDK 通过 JSON-RPC 控制本地 Codex app-server。它要求 Python 3.10 或更高版本。已发布的 SDK 构建版本包含固定版本的 Codex CLI 运行时依赖。
如需安装 SDK,请运行:
pip install openai-codex已发布的 SDK 构建版本会自动使用其固定版本的运行时。仅当你明确希望使用特定的本地 Codex 可执行文件运行时,才传入 CodexConfig(codex_bin=...)。
Python SDK 处于 beta 阶段时,pip install openai-codex 会选择最新发布的 beta 构建版本。稳定版 SDK 发布后,使用 pip install --pre openai-codex 以选择加入更新的预发布构建版本。
启动 Codex,创建一个线程,并运行提示词:
from openai_codex import Codex, Sandbox
with Codex() as codex: thread = codex.thread_start( model="gpt-5.4", sandbox=Sandbox.workspace_write, ) result = thread.run("Make a plan to diagnose and fix the CI failures") print(result.final_response)如果你的应用已经是异步的,请使用 AsyncCodex:
import asyncio
from openai_codex import AsyncCodex
async def main() -> None: async with AsyncCodex() as codex: thread = await codex.thread_start(model="gpt-5.4") result = await thread.run("Implement the plan") print(result.final_response)
asyncio.run(main())创建线程或更改线程的文件系统访问权限,以便在后续轮次中使用相同的 Sandbox 预设:
from openai_codex import Codex, Sandbox
with Codex() as codex: thread = codex.thread_start(sandbox=Sandbox.workspace_write) thread.run("Make the requested change.") review = thread.run("Review the diff only.", sandbox=Sandbox.read_only)可用预设:
Sandbox.read_only:读取文件,但不允许写入。Sandbox.workspace_write:读取文件,并在工作区和配置的可写根目录中写入。Sandbox.full_access:运行时不受文件系统访问限制。
省略 sandbox= 时,app-server 会使用其配置的默认值。传递给 run(...) 或 turn(...) 的沙箱设置会应用于当前轮次以及该线程的后续轮次。
如需了解详情,请参阅 Python 仓库。