如果您通过 Codex CLI、IDE 扩展或 Codex 云端使用 Codex,也可以以编程方式控制它。
当您需要执行以下操作时,请使用 SDK:
- 在您的 CI/CD 流水线中控制 Codex
- 创建自己的智能体,让它与 Codex 交互以执行复杂的工程任务
- 将 Codex 集成到您自己的内部工具和工作流中
- 将 Codex 集成到您自己的应用中
使用 Codex SDK 自动执行编码任务,包括 CI 中的作业。使用 Codex App Server 构建自定义客户端,处理身份验证、对话历史记录、审批和以流式方式传输的智能体事件。
codex mcp-server 命令和独立的 codex-mcp-server 二进制文件已被移除。对于现有集成,请使用 Codex App Server。
如果您拥有测试版访问权限,并且需要扫描代码仓库或变更,以获取结构化的 安全发现和覆盖情况,请使用 Codex Security TypeScript SDK。
TypeScript 库
TypeScript 库让您的应用能够启动、继续和恢复本地 Codex 对话线程。
请在服务端使用此库;它需要 Node.js 18 或更高版本。
安装
首先,使用 npm 安装 Codex SDK:
npm install @openai/codex-sdk
用法
启动一个 Codex 对话线程,并使用您的提示运行它。
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.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:
import asyncio
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 代码仓库。