如果您透過 Codex CLI、IDE 擴充功能或 Codex 雲端使用 Codex,也可以透過程式控制 Codex。
需要進行下列操作時,請使用 SDK:
- 在 CI/CD 管線中控制 Codex
- 建立自己的智慧體,讓它能與 Codex 互動,以執行複雜的工程任務
- 將 Codex 整合至您自己的內部工具與工作流程
- 將 Codex 整合至您自己的應用程式
使用 Codex SDK 自動執行程式碼編寫任務,包括 CI 中的作業。使用 Codex app server 建立自訂用戶端,處理身分驗證、對話紀錄、核准及串流傳送的智慧體事件。
codex mcp-server 指令與獨立的 codex-mcp-server 二進位執行檔已移除。現有整合請改用 Codex app server。
如果您具備 Beta 版存取權,需要掃描程式碼庫或變更,並取得結構化的 安全性檢查結果與涵蓋範圍資訊,請使用 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 程式碼庫。