Skip to content
FunCoding

Search

Search docs, Skills and MCP

Python SDK

用同步或异步 Python 客户端启动本地 Codex,并为线程和回合选择 sandbox。

This page has not been translated into English yet. The original Chinese version is shown below.

Python SDK 通过 JSON-RPC 控制本地 Codex App Server,要求 Python 3.10 或更高版本。发布的 SDK 包含固定版本的 Codex CLI 运行时依赖,正常使用无需自己选择 CLI 二进制。

安装与版本选择

pip install openai-codex

官方将 Python SDK 标为稳定发布;普通安装取得稳定版本,需要较新的预发布构建时才用 pip install --pre openai-codex。只有刻意使用指定本地 Codex 时,才传 CodexConfig(codex_bin=...)。

同步调用

下面省略模型,让运行时使用已有默认设置;需要指定模型时,应确认账号可访问该模型。

from openai_codex import Codex, Sandbox

with Codex() as codex:
    thread = codex.thread_start(sandbox=Sandbox.workspace_write)
    result = thread.run("Make a plan to diagnose and fix the CI failures")
    print(result.final_response)

异步调用

已有 asyncio 应用可使用 AsyncCodex:

import asyncio
from openai_codex import AsyncCodex

async def main() -> None:
    async with AsyncCodex() as codex:
        thread = await codex.thread_start()
        result = await thread.run("Implement the plan")
        print(result.final_response)

asyncio.run(main())

沙箱预设与持续作用

预设文件系统行为
Sandbox.read_only允许读取,不允许写入
Sandbox.workspace_write允许读取,在工作区及配置的可写根中写入
Sandbox.full_access不施加文件系统访问限制

不传 sandbox 时使用 App Server 配置默认值。可以在后续回合收紧为只读:

review = thread.run("Review the diff only.", sandbox=Sandbox.read_only)

传给 run(...) 或 turn(...) 的 sandbox 不只作用于这一回合,还作用于该线程之后的回合。应用如果需要恢复原来的写权限,应在后续调用明确设置,而不是假定会自动复原。