For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
主导航

Codex SDK

如果您通过 Codex CLI、IDE 扩展或 Codex 云端使用 Codex,也可以通过编程方式控制它。

当您需要执行以下操作时,请使用该 SDK:

  • 在 CI/CD 流水线中控制 Codex
  • 创建您自己的智能体,使其能够与 Codex 交互并执行复杂的工程任务
  • 将 Codex 集成到您自己的内部工具和工作流中
  • 在您自己的应用中集成 Codex

对于以编程为重点的 Codex 线程,请使用 Codex SDK。如果 Codex 是更广泛的编排工作流中负责专项任务的智能体,请 将 Codex CLI 作为 MCP 服务器运行,并使用 Agents SDK 对其进行编排

如果您拥有 Beta 版访问权限,并需要对代码仓库或变更进行扫描,以获取结构化的 安全发现结果和覆盖范围,请使用 Codex Security TypeScript SDK

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 thread
const 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 库

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 已发布稳定版本。pip install openai-codex 会安装最新的稳定版本。使用 pip install --pre openai-codex 可选择 使用更新的预发布构建版本。

用法

启动 Codex,创建一个线程,然后运行提示:

from openai_codex import Codex, Sandbox

with Codex() as codex:
    thread = codex.thread_start(
        model="gpt-5.6-terra",
        sandbox=Sandbox.workspace_write,
    )
    result = thread.run("Make a plan to diagnose and fix the CI failures")
    print(result.final_response)

如果您的应用已采用异步方式运行,请使用 AsyncCodex



from openai_codex import AsyncCodex


async def main() -> None:
    async with AsyncCodex() as codex:
        thread = await codex.thread_start(model="gpt-5.6-terra")
        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 代码仓库