如果您通过 Codex CLI、IDE 扩展或 Codex Web 使用 Codex,您还可以通过编程方式控制它。
当您需要执行以下操作时,请使用 SDK:
将 Codex 控制为 CI/CD 管道的一部分
创建您自己的代理,可以与 Codex 交互来执行复杂的工程任务
将 Codex 构建到您自己的内部工具和工作流程中
将 Codex 集成到您自己的应用程序中
TypeScript 库
TypeScript 库提供了一种从应用程序内控制 Codex 的方法,该方法比 non-interactive 模式更全面、更灵活。
使用库server-side;它需要 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); 再次调用 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 存储库 。
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 选择最新发布的测试版本。存在稳定的 SDK 版本后,使用 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()) 沙盒预设
创建线程或更改其文件系统访问权限以供稍后使用时,请使用相同的沙箱预设:
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 存储库。