如果你已经在使用 Codex CLI、IDE 扩展或 Codex Web,也可以进一步通过 SDK 以编程方式控制它。

SDK 适合下面这些场景:

  • 需要把 Codex 接入自己的 CI/CD 流程
  • 需要构建能够与 Codex 协作完成复杂工程任务的自定义智能体
  • 需要把 Codex 集成进内部工具和工作流
  • 需要在自己的应用里嵌入 Codex

TypeScript 库

TypeScript SDK 提供了一种比非交互模式更全面、更灵活的服务端集成方式。

这个库应该运行在服务端环境中,要求 Node.js 18 或更高版本。

安装

安装方式:

npm install @openai/codex-sdk

用法

先启动一个线程,再用提示词运行它:

import { Codex } from "@openai/codex-sdk";

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);

如果你想在同一个线程中继续执行,可以再次调用 run();如果你要恢复一条过去的线程,可以提供 thread ID:

// running the same thread
const result = await thread.run("Implement the plan");

console.log(result);

// 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);

更多细节请查看 TypeScript 仓库

Python 库

Python SDK 通过 JSON-RPC 控制本地的 Codex app-server。它要求 Python 3.10 或更高版本。已发布的 SDK build 会包含固定版本的 Codex CLI runtime 依赖。

安装

安装 SDK:

pip install openai-codex

已发布的 SDK build 会自动使用它们固定的 runtime。只有当你明确想针对某个本地 Codex 可执行文件运行时,才传入 CodexConfig(codex_bin=...)

Python SDK 仍处于 beta 阶段时,pip install openai-codex 会选择最新发布的 beta build。等到稳定版 SDK 发布后,如需选择更新的 prerelease build,请使用 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 presets

创建线程或为后续 turn 改变文件系统访问权限时,可以使用相同的 Sandbox presets:

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)

可用 presets:

  • Sandbox.read_only:读取文件,但不允许写入。
  • Sandbox.workspace_write:读取文件,并可在工作区和已配置 writable roots 内写入。
  • Sandbox.full_access:不施加文件系统访问限制。

省略 sandbox= 时,app-server 会使用其配置的默认值。传给 run(...)turn(...) 的 sandbox 会应用于当前 turn 及该线程后续 turn。

更多细节请查看 Python 仓库