繁體中文

Codex SDK

以程式設計方式控制本機 Codex 智能體

如果你已經在使用 Codex CLI、IDE 擴充套件或 Codex 雲端,也可以進一步通過 SDK 以程式設計方式控制它。

SDK 適合下面這些場景:

  • 需要把 Codex 接入自己的 CI/CD 流程
  • 需要建置能夠與 Codex 協作完成複雜工程任務的自定義智能體
  • 需要把 Codex 整合進內部工具和工作流程
  • 需要在自己的應用裡嵌入 Codex

Codex SDK 適合面向編碼任務的 Codex 對話執行緒。如果 Codex 只是更大編排工作流程中的一個專門角色,請改為把 Codex CLI 作為 MCP server 執行,並用 Agents SDK 編排

如果你擁有 Beta 存取權限,並需要對儲存庫或程式碼變更執行掃描,同時獲取結構化安全發現與覆蓋範圍,請使用 Codex Security TypeScript SDK

TypeScript 庫

TypeScript 庫讓應用能夠啟動、繼續和恢復本機 Codex thread

這個庫應該執行在服務端環境中,要求 Node.js 18 或更高版本。

安裝

安裝方式:

npm install @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 仍處於 beta 階段時,pip install openai-codex 會選擇最新發布的 beta 建置版本。等到穩定版 SDK 釋出後,如需選擇更新的預釋出版本,請使用 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:讀取檔案,並可在工作區和已設定 writable roots 內寫入。
  • Sandbox.full_access:不施加檔案系統存取限制。

省略 sandbox= 時,app-server 會使用其設定的預設值。傳給 run(...)turn(...) 的 sandbox 會應用於當前會話輪次及該對話執行緒後續會話輪次。

更多細節請檢視 Python 儲存庫


來源:</zh-TW/docs/codex-sdk> 更新時間:2026-07-10(UTC)