本文为非官方中文翻译,内容以 OpenAI 官方英文文档为准。
官方来源:https://developers.openai.com/codex/sdk
Codex SDK
以编程方式控制本地 Codex agent
如果你通过 Codex CLI、IDE 扩展或 Codex Web 使用 Codex,你也可以通过编程方式控制它。
在以下情况下,请使用 SDK:
- 将 Codex 作为 CI/CD 流水线的一部分进行控制
- 创建你自己的 agent,使其能够与 Codex 交互以执行复杂的工程任务
- 将 Codex 构建到你自己的内部工具和工作流中
- 在你自己的应用程序中集成 Codex
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);
再次调用 run() 以在同一线程上继续,或通过提供线程 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 repo。
Python 库
Python SDK 仍处于实验阶段,并通过 JSON-RPC 控制本地 Codex app-server。它要求 Python 3.10 或更高版本,以及 open-source Codex repo 的本地检出副本。
安装
在 Codex repo 根目录下,以可编辑模式安装 SDK:
cd sdk/python
python -m pip install -e .
对于手动本地 SDK 用法,请传入 AppServerConfig(codex_bin=...) 以指向本地 codex 二进制文件,或者使用 repo 示例和 notebook bootstrap。
用法
启动 Codex,创建一个线程,并运行提示词:
from codex_app_server import Codex
with Codex() as codex:
thread = codex.thread_start(model="gpt-5.4")
result = thread.run("Make a plan to diagnose and fix the CI failures")
print(result.final_response)
当你的应用程序本身已经是异步的时,请使用 AsyncCodex:
from codex_app_server 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())
更多详情,请查看 Python repo。