OpenAI Codex 中文文档(4.14更新)
联系我
官方文档

Codex SDK

以编程方式控制本地 Codex 智能体

如果你已经在使用 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 或更高版本,并且需要本地检出开源版 Codex 仓库。

安装

在 Codex 仓库根目录执行:

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

如果你是手动在本地使用 SDK,可以通过 AppServerConfig(codex_bin=...) 指向本地 codex 二进制;也可以直接复用仓库中的示例和 notebook 启动方式。

用法

启动 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

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


来源:https://developers.openai.com/codex/sdk