Skip to content

Codex SDK 让你在代码里直接控制 Codex agent,适合 CI/CD 流水线、内部工具和自定义 agent 集成。TypeScript 版本已稳定发布(需要 Node.js 18+),Python 版本为实验性(需要 Python 3.10+),通过 app-server JSON-RPC 调用本地 Codex 二进制文件。两者都支持创建 thread、运行 prompt、续接历史会话。

Codex SDK

如果你通过 Codex CLI、IDE 扩展或 Codex Web 使用 Codex,同样可以通过 SDK 对其进行编程控制。

适合使用 SDK 的场景:

  • 在 CI/CD 流水线中以代码方式调用 Codex
  • 构建自定义 agent,让它能与 Codex 协作完成复杂工程任务
  • 将 Codex 集成到内部工具和工作流中
  • 在自己的应用内嵌入 Codex 能力

TypeScript SDK

TypeScript SDK 提供比非交互模式更完整、更灵活的编程控制方式,需要在服务端使用(Node.js 18 或更高版本)。

安装

bash
npm install @openai/codex-sdk

基础用法

创建 thread 并执行 prompt:

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

在同一 thread 上继续执行,或通过 thread ID 恢复历史会话:

ts
// 在同一 thread 上继续
const result = await thread.run("Implement the plan");

console.log(result);

// 恢复历史 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 SDK(实验性)

Python SDK 为实验性功能,通过 JSON-RPC 调用本地 Codex app-server。需要:

  • Python 3.10 或更高版本
  • Codex 开源仓库本地 checkout

安装

在 Codex 仓库根目录以可编辑模式安装:

bash
cd sdk/python
python -m pip install -e .

如需手动指定本地 Codex 二进制文件,传入 AppServerConfig(codex_bin=...),或使用仓库示例和 notebook 的 bootstrap 脚本。

基础用法

启动 Codex、创建 thread 并运行 prompt:

python
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

python
import asyncio

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 仓库


常见问题

Q: TypeScript SDK 和 codex exec 非交互模式有什么区别?

A: codex exec 适合一次性脚本和 CI,简单直接。TypeScript SDK 更灵活,支持管理多个 thread、续接历史会话、在应用内作为服务长期运行,适合需要深度集成的场景。

Q: Python SDK 稳定吗,能用于生产环境吗?

A: Python SDK 目前为实验性,基于 app-server JSON-RPC 调用本地 Codex 二进制,API 可能变化。生产环境建议优先使用 TypeScript SDK。

Q: 如何在 CI 中使用 SDK 认证?

A: 设置环境变量 OPENAI_API_KEY,SDK 会自动读取。也可以在代码里显式传入 API Key,但不建议硬编码,应从环境变量或 secret 管理系统读取。