🚀 Codex CLI SDK 开发指南:用代码调用 AI 编程能力

📅 更新于 2026年6月 | ✍️ 原创文章,转载请注明出处

本系列共12篇,本文是第9篇



1. 什么是 Codex SDK

📖 SDK 定义

Codex SDK 是 Codex CLI 提供的编程接口,让你可以用代码调用 AI 编程能力。

🔧 SDK 类型

SDK 语言 安装 适用场景
Node.js SDK JavaScript/TypeScript npm install @openai/codex-sdk Node.js 应用、前端工具
Python SDK Python pip install codex-sdk Python 应用、数据处理
REST API HTTP 直接调用 任何语言、跨平台

💡 工作原理

你的代码
    ↓ 调用 SDK
Codex SDK
    ↓ API 请求
OpenAI 服务器
    ↓ 返回结果
你的代码

🎯 使用场景

  • 构建自定义开发工具
  • 集成到现有应用
  • 创建自动化工作流
  • 开发 IDE 插件
  • 构建 AI 辅助平台

2. 为什么使用 SDK

🎯 核心价值

CLI 工具 SDK
命令行交互 编程接口
手动操作 自动化
单次任务 批量处理
终端输出 结构化数据

📊 使用场景对比

场景 CLI SDK
快速任务
脚本集成
Web 应用
IDE 插件
批量处理 ⚠️
实时交互

✅ 什么时候用 SDK

  • 需要集成到应用
  • 需要结构化输出
  • 需要流式处理
  • 需要批量处理
  • 需要自定义 UI

❌ 什么时候不用 SDK

  • 简单的命令行任务
  • 一次性操作
  • 不需要编程接口

3. Node.js SDK

📦 安装

# npm
npm install @openai/codex-sdk

# yarn
yarn add @openai/codex-sdk

# pnpm
pnpm add @openai/codex-sdk

🚀 快速开始

import { CodexSDK } from '@openai/codex-sdk';

// 初始化 SDK
const codex = new CodexSDK({
  apiKey: process.env.OPENAI_API_KEY,
});

// 执行任务
async function main() {
  const result = await codex.execute({
    task: '创建一个 Hello World 的 Python 脚本',
    workingDirectory: './project',
  });
  
  console.log(result.output);
}

main();

📝 核心 API

1. 初始化
import { CodexSDK } from '@openai/codex-sdk';

const codex = new CodexSDK({
  // API Key(必需)
  apiKey: process.env.OPENAI_API_KEY,
  
  // 模型(可选)
  model: 'gpt-5-codex',
  
  // 工作目录(可选)
  workingDirectory: './project',
  
  // 审批模式(可选)
  approvalMode: 'suggest', // 'suggest' | 'auto-edit' | 'full-auto'
  
  // 超时时间(可选)
  timeout: 60000, // 毫秒
  
  // 最大 tokens(可选)
  maxTokens: 4096,
});
2. 执行任务
// 基本执行
const result = await codex.execute({
  task: '为 UserService 编写单元测试',
});

console.log(result.output); // 输出内容
console.log(result.files);  // 修改的文件列表
console.log(result.cost);   // 使用成本
3. 流式执行
// 流式输出
const stream = await codex.executeStream({
  task: '重构这个函数',
});

for await (const chunk of stream) {
  process.stdout.write(chunk);
}
4. 会话管理
// 创建会话
const session = await codex.createSession();

// 在会话中执行任务
const result1 = await session.execute({
  task: '读取 src/main.py',
});

const result2 = await session.execute({
  task: '重构这个文件',
});

// 关闭会话
await session.close();
5. 文件操作
// 读取文件
const content = await codex.readFile('src/main.py');

// 写入文件
await codex.writeFile('src/main.py', 'print("Hello")');

// 列出文件
const files = await codex.listFiles('src/');

🎯 完整示例

import { CodexSDK } from '@openai/codex-sdk';
import * as fs from 'fs/promises';

async function codeReview(projectDir: string) {
  // 初始化 SDK
  const codex = new CodexSDK({
    apiKey: process.env.OPENAI_API_KEY,
    workingDirectory: projectDir,
  });

  // 获取修改的文件
  const diff = await codex.execute({
    task: '显示 git diff',
  });

  // 代码审查
  const review = await codex.execute({
    task: `审查以下代码修改,找出问题:
    
${diff.output}

重点关注:
1. 安全漏洞
2. 性能问题
3. 代码规范
`,
  });

  // 保存审查结果
  await fs.writeFile('review.md', review.output);

  return review.output;
}

// 使用
codeReview('./my-project')
  .then(console.log)
  .catch(console.error);

📊 TypeScript 类型定义

interface CodexSDKOptions {
  apiKey: string;
  model?: string;
  workingDirectory?: string;
  approvalMode?: 'suggest' | 'auto-edit' | 'full-auto';
  timeout?: number;
  maxTokens?: number;
}

interface ExecuteOptions {
  task: string;
  workingDirectory?: string;
  model?: string;
  approvalMode?: 'suggest' | 'auto-edit' | 'full-auto';
}

interface ExecuteResult {
  output: string;
  files: string[];
  cost: {
    inputTokens: number;
    outputTokens: number;
    totalCost: number;
  };
  duration: number;
}

interface StreamChunk {
  type: 'output' | 'error' | 'progress';
  content: string;
}

class CodexSDK {
  constructor(options: CodexSDKOptions);
  
  execute(options: ExecuteOptions): Promise<ExecuteResult>;
  executeStream(options: ExecuteOptions): AsyncGenerator<StreamChunk>;
  createSession(): Promise<Session>;
  readFile(path: Promise<string>;
  writeFile(path: string, content: string): Promise<void>;
  listFiles(path: string): Promise<string[]>;
}

interface Session {
  execute(options: ExecuteOptions): Promise<ExecuteResult>;
  close(): Promise<void>;
}

4. Python SDK

📦 安装

# pip
pip install codex-sdk

# poetry
poetry add codex-sdk

# conda
conda install -c conda-forge codex-sdk

🚀 快速开始

from codex_sdk import CodexSDK
import os

# 初始化 SDK
codex = CodexSDK(
    api_key=os.environ['OPENAI_API_KEY'],
)

# 执行任务
result = codex.execute(
    task='创建一个 Hello World 的 Python 脚本',
    working_directory='./project',
)

print(result.output)

📝 核心 API

1. 初始化
from codex_sdk import CodexSDK

codex = CodexSDK(
    # API Key(必需)
    api_key=os.environ['OPENAI_API_KEY'],
    
    # 模型(可选)
    model='gpt-5-codex',
    
    # 工作目录(可选)
    working_directory='./project',
    
    # 审批模式(可选)
    approval_mode='suggest',  # 'suggest' | 'auto-edit' | 'full-auto'
    
    # 超时时间(可选)
    timeout=60000,  # 毫秒
    
    # 最大 tokens(可选)
    max_tokens=4096,
)
2. 执行任务
# 基本执行
result = codex.execute(
    task='为 UserService 编写单元测试',
)

print(result.output)  # 输出内容
print(result.files)   # 修改的文件列表
print(result.cost)    # 使用成本
3. 流式执行
# 流式输出
for chunk in codex.execute_stream(task='重构这个函数'):
    print(chunk, end='', flush=True)
4. 会话管理
# 创建会话
session = codex.create_session()

# 在会话中执行任务
result1 = session.execute(
    task='读取 src/main.py',
)

result2 = session.execute(
    task='重构这个文件',
)

# 关闭会话
session.close()
5. 异步支持
import asyncio
from codex_sdk import AsyncCodexSDK

async def main():
    codex = AsyncCodexSDK(
        api_key=os.environ['OPENAI_API_KEY'],
    )
    
    result = await codex.execute(
        task='创建一个 Python 脚本',
    )
    
    print(result.output)

asyncio.run(main())

🎯 完整示例

from codex_sdk import CodexSDK
import os
from pathlib import Path

def generate_tests(src_dir: str, test_dir: str):
    """为源代码生成单元测试"""
    
    # 初始化 SDK
    codex = CodexSDK(
        api_key=os.environ['OPENAI_API_KEY'],
        working_directory='.',
    )
    
    # 确保测试目录存在
    Path(test_dir).mkdir(parents=True, exist_ok=True)
    
    # 遍历源文件
    for src_file in Path(src_dir).glob('*.py'):
        # 生成测试文件名
        test_file = Path(test_dir) / f'test_{src_file.name}'
        
        # 跳过已存在的测试
        if test_file.exists():
            print(f'跳过: {test_file} (已存在)')
            continue
        
        # 生成测试
        print(f'生成测试: {src_file} -> {test_file}')
        
        result = codex.execute(
            task=f'为 {src_file} 生成 pytest 单元测试,覆盖所有公开方法',
        )
        
        # 保存测试文件
        test_file.write_text(result.output)
        
        print(f'✅ 完成: {test_file}')

# 使用
generate_tests('src/', 'tests/')

📊 类型定义

from dataclasses import dataclass
from typing import List, Optional, AsyncIterator, Iterator
from enum import Enum

class ApprovalMode(Enum):
    SUGGEST = 'suggest'
    AUTO_EDIT = 'auto-edit'
    FULL_AUTO = 'full-auto'

@dataclass
class Cost:
    input_tokens: int
    output_tokens: int
    total_cost: float

@dataclass
class ExecuteResult:
    output: str
    files: List[str]
    cost: Cost
    duration: float

@dataclass
class StreamChunk:
    type: str  # 'output' | 'error' | 'progress'
    content: str

class CodexSDK:
    def __init__(
        self,
        api_key: str,
        model: str = 'gpt-5-codex',
        working_directory: Optional[str] = None,
        approval_mode: ApprovalMode = ApprovalMode.SUGGEST,
        timeout: int = 60000,
        max_tokens: int = 4096,
    ):
        ...
    
    def execute(
        self,
        task: str,
        working_directory: Optional[str] = None,
        model: Optional[str] = None,
        approval_mode: Optional[ApprovalMode] = None,
    ) -> ExecuteResult:
        ...
    
    def execute_stream(
        self,
        task: str,
        **kwargs,
    ) -> Iterator[StreamChunk]:
        ...
    
    def create_session(self) -> 'Session':
        ...
    
    def read_file(self, path: str) -> str:
        ...
    
    def write_file(self, path: str, content: str) -> None:
        ...
    
    def list_files(self, path: str) -> List[str]:
        ...

class AsyncCodexSDK:
    async def execute(self, task: str, **kwargs) -> ExecuteResult:
        ...
    
    async def execute_stream(self, task: str, **kwargs) -> AsyncIterator[StreamChunk]:
        ...

class Session:
    def execute(self, task: str, **kwargs) -> ExecuteResult:
        ...
    
    def close(self) -> None:
        ...

5. REST API

🌐 API 端点

POST https://api.openai.com/v1/codex/execute
POST https://api.openai.com/v1/codex/stream
GET  https://api.openai.com/v1/codex/sessions
POST https://api.openai.com/v1/codex/sessions

📝 请求格式

执行任务
curl -X POST https://api.openai.com/v1/codex/execute \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "task": "创建一个 Hello World 的 Python 脚本",
    "model": "gpt-5-codex",
    "working_directory": "./project",
    "approval_mode": "suggest",
    "max_tokens": 4096
  }'
响应格式
{
  "id": "exec_abc123",
  "output": "#!/usr/bin/env python3\nprint('Hello, World!')",
  "files": ["hello.py"],
  "cost": {
    "input_tokens": 150,
    "output_tokens": 50,
    "total_cost": 0.001
  },
  "duration": 2.5,
  "created_at": "2026-05-26T10:00:00Z"
}

🔧 各语言调用示例

Python (requests)
import requests
import os

response = requests.post(
    'https://api.openai.com/v1/codex/execute',
    headers={
        'Authorization': f'Bearer {os.environ["OPENAI_API_KEY"]}',
        'Content-Type': 'application/json',
    },
    json={
        'task': '创建一个 Hello World 的 Python 脚本',
        'model': 'gpt-5-codex',
    },
)

result = response.json()
print(result['output'])
JavaScript (fetch)
const response = await fetch('https://api.openai.com/v1/codex/execute', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    task: '创建一个 Hello World 的 Python 脚本',
    model: 'gpt-5-codex',
  }),
});

const result = await response.json();
console.log(result.output);
Go (net/http)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

type Request struct {
	Task  string `json:"task"`
	Model string `json:"model"`
}

type Response struct {
	Output string   `json:"output"`
	Files  []string `json:"files"`
}

func main() {
	reqBody, _ := json.Marshal(Request{
		Task:  "创建一个 Hello World 的 Python 脚本",
		Model: "gpt-5-codex",
	})

	req, _ := http.NewRequest("POST", "https://api.openai.com/v1/codex/execute", bytes.NewBuffer(reqBody))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENAI_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, _ := client.Do(req)
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	var result Response
	json.Unmarshal(body, &result)

	fmt.Println(result.Output)
}

📊 流式 API

curl -X POST https://api.openai.com/v1/codex/stream \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "task": "重构这个函数",
    "stream": true
  }'

响应(Server-Sent Events):

data: {"type": "output", "content": "正在分析代码..."}
data: {"type": "output", "content": "重构完成"}
data: {"type": "progress", "content": "100%"}
data: [DONE]

6. 高级用法

🔄 流式处理

import { CodexSDK } from '@openai/codex-sdk';

const codex = new CodexSDK({
  apiKey: process.env.OPENAI_API_KEY,
});

async function processStream() {
  const stream = await codex.executeStream({
    task: '重构这个函数',
  });

  let fullOutput = '';
  
  for await (const chunk of stream) {
    switch (chunk.type) {
      case 'output':
        process.stdout.write(chunk.content);
        fullOutput += chunk.content;
        break;
      case 'error':
        console.error('错误:', chunk.content);
        break;
      case 'progress':
        console.log('进度:', chunk.content);
        break;
    }
  }
  
  return fullOutput;
}

📦 批量处理

import { CodexSDK } from '@openai/codex-sdk';

const codex = new CodexSDK({
  apiKey: process.env.OPENAI_API_KEY,
});

async function batchProcess(tasks: string[]) {
  const results = await Promise.all(
    tasks.map(task => codex.execute({ task }))
  );
  
  return results;
}

// 使用
const tasks = [
  '为 UserService 生成测试',
  '为 OrderService 生成测试',
  '为 PaymentService 生成测试',
];

const results = await batchProcess(tasks);
results.forEach((result, i) => {
  console.log(`任务 ${i + 1}:`, result.output.substring(0, 100));
});

🔁 重试机制

import { CodexSDK } from '@openai/codex-sdk';

const codex = new CodexSDK({
  apiKey: process.env.OPENAI_API_KEY,
});

async function executeWithRetry(
  task: string,
  maxRetries: number = 3
) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await codex.execute({ task });
    } catch (error) {
      console.error(`尝试 ${i + 1} 失败:`, error.message);
      if (i === maxRetries - 1) throw error;
      await new Promise(r => setTimeout(r, 1000 * (i + 1)));
    }
  }
}

// 使用
const result = await executeWithRetry('重构这个函数');

🎯 上下文管理

import { CodexSDK } from '@openai/codex-sdk';

const codex = new CodexSDK({
  apiKey: process.env.OPENAI_API_KEY,
});

async function withContext(files: string[], task: string) {
  // 读取文件内容
  const context = await Promise.all(
    files.map(async file => {
      const content = await codex.readFile(file);
      return `## ${file}\n\`\`\`\n${content}\n\`\`\``;
    })
  );
  
  // 执行任务
  return await codex.execute({
    task: `${task}\n\n上下文:\n${context.join('\n\n')}`,
  });
}

// 使用
const result = await withContext(
  ['src/user.py', 'src/order.py'],
  '重构这两个文件,提取共同的基类'
);

📊 进度跟踪

import { CodexSDK } from '@openai/codex-sdk';

const codex = new CodexSDK({
  apiKey: process.env.OPENAI_API_KEY,
});

interface ProgressCallback {
  onProgress?: (progress: number) => void;
  onOutput?: (output: string) => void;
  onError?: (error: string) => void;
}

async function executeWithProgress(
  task: string,
  callbacks: ProgressCallback
) {
  const stream = await codex.executeStream({ task });
  
  for await (const chunk of stream) {
    switch (chunk.type) {
      case 'output':
        callbacks.onOutput?.(chunk.content);
        break;
      case 'progress':
        const progress = parseInt(chunk.content) || 0;
        callbacks.onProgress?.(progress);
        break;
      case 'error':
        callbacks.onError?.(chunk.content);
        break;
    }
  }
}

// 使用
await executeWithProgress('重构这个函数', {
  onProgress: (p) => console.log(`进度: ${p}%`),
  onOutput: (o) => process.stdout.write(o),
  onError: (e) => console.error('错误:', e),
});

7. 实战案例

💼 案例1:自动化代码审查工具

import { CodexSDK } from '@openai/codex-sdk';
import * as fs from 'fs/promises';
import { execSync } from 'child_process';

class CodeReviewer {
  private codex: CodexSDK;

  constructor(apiKey: string) {
    this.codex = new CodexSDK({ apiKey });
  }

  async reviewPR(repoDir: string, prNumber: number) {
    // 获取 PR diff
    const diff = execSync(`git diff main`, { cwd: repoDir }).toString();

    // 代码审查
    const review = await this.codex.execute({
      task: `审查以下 PR 代码:

${diff}

请检查:
1. 安全漏洞
2. 性能问题
3. 代码规范
4. 潜在 bug

输出格式:
## 严重问题
- [问题描述]

## 警告
- [警告描述]

## 建议
- [建议]
`,
      workingDirectory: repoDir,
    });

    return review.output;
  }

  async saveReview(review: string, outputFile: string) {
    await fs.writeFile(outputFile, review);
  }
}

// 使用
const reviewer = new CodeReviewer(process.env.OPENAI_API_KEY!);
const review = await reviewer.reviewPR('./my-project', 123);
await reviewer.saveReview(review, 'review.md');
console.log(review);

💼 案例2:测试生成器

from codex_sdk import CodexSDK
from pathlib import Path
import os

class TestGenerator:
    def __init__(self):
        self.codex = CodexSDK(
            api_key=os.environ['OPENAI_API_KEY'],
        )
    
    def generate_tests(self, src_dir: str, test_dir: str):
        """为源代码生成测试"""
        
        # 确保测试目录存在
        Path(test_dir).mkdir(parents=True, exist_ok=True)
        
        # 遍历源文件
        for src_file in Path(src_dir).glob('*.py'):
            # 生成测试文件名
            test_file = Path(test_dir) / f'test_{src_file.name}'
            
            # 跳过已存在的测试
            if test_file.exists():
                print(f'跳过: {test_file}')
                continue
            
            # 读取源文件
            src_content = src_file.read_text()
            
            # 生成测试
            print(f'生成测试: {src_file}')
            result = self.codex.execute(
                task=f'为以下 Python 代码生成 pytest 单元测试:\n\n```python\n{src_content}\n```\n\n要求:\n1. 覆盖所有公开方法\n2. 测试边界条件\n3. 使用 mock',
            )
            
            # 保存测试文件
            test_file.write_text(result.output)
            print(f'✅ 完成: {test_file}')

# 使用
generator = TestGenerator()
generator.generate_tests('src/', 'tests/')

💼 案例3:文档生成器

import { CodexSDK } from '@openai/codex-sdk';
import * as fs from 'fs/promises';
import * as path from 'path';

class DocGenerator {
  private codex: CodexSDK;

  constructor(apiKey: string) {
    this.codex = new CodexSDK({ apiKey });
  }

  async generateAPIDocs(srcDir: string, outputDir: string) {
    // 确保输出目录存在
    await fs.mkdir(outputDir, { recursive: true });

    // 获取所有源文件
    const files = await this.codex.listFiles(srcDir);
    const sourceFiles = files.filter(f => f.endsWith('.py'));

    // 为每个文件生成文档
    for (const file of sourceFiles) {
      const content = await this.codex.readFile(file);
      const basename = path.basename(file, '.py');

      console.log(`生成文档: ${file}`);

      const doc = await this.codex.execute({
        task: `为以下 Python 代码生成 API 文档:

\`\`\`python
${content}
\`\`\`

要求:
1. 类和函数说明
2. 参数说明
3. 返回值说明
4. 使用示例
`,
      });

      // 保存文档
      const outputFile = path.join(outputDir, `${basename}.md`);
      await fs.writeFile(outputFile, doc.output);
      console.log(`✅ 完成: ${outputFile}`);
    }
  }

  async generateREADME(projectDir: string) {
    // 获取项目结构
    const files = await this.codex.listFiles(projectDir);
    
    // 生成 README
    const readme = await this.codex.execute({
      task: `根据以下项目结构生成 README.md:

文件列表:
${files.join('\n')}

要求:
1. 项目介绍
2. 快速开始
3. 目录结构
4. 开发指南
5. 部署说明
`,
      workingDirectory: projectDir,
    });

    // 保存 README
    await fs.writeFile(
      path.join(projectDir, 'README.md'),
      readme.output
    );

    console.log('✅ README.md 已生成');
  }
}

// 使用
const generator = new DocGenerator(process.env.OPENAI_API_KEY!);
await generator.generateAPIDocs('src/', 'docs/');
await generator.generateREADME('./');

💼 案例4:代码重构助手

from codex_sdk import CodexSDK
from pathlib import Path
import os
import shutil

class RefactoringAssistant:
    def __init__(self):
        self.codex = CodexSDK(
            api_key=os.environ['OPENAI_API_KEY'],
        )
    
    def refactor_directory(self, src_dir: str, backup_dir: str = 'backup'):
        """重构目录中的所有文件"""
        
        # 创建备份
        if Path(backup_dir).exists():
            shutil.rmtree(backup_dir)
        shutil.copytree(src_dir, backup_dir)
        
        # 遍历源文件
        for src_file in Path(src_dir).glob('*.py'):
            print(f'重构: {src_file}')
            
            # 读取源文件
            src_content = src_file.read_text()
            
            # 重构
            result = self.codex.execute(
                task=f'重构以下 Python 代码,优化结构和可读性:\n\n```python\n{src_content}\n```\n\n要求:\n1. 保持功能不变\n2. 提高可读性\n3. 遵循 PEP 8\n4. 添加类型提示',
            )
            
            # 保存重构后的文件
            src_file.write_text(result.output)
            print(f'✅ 完成: {src_file}')
    
    def compare_changes(self, src_dir: str, backup_dir: str):
        """比较重构前后的变化"""
        
        for src_file in Path(src_dir).glob('*.py'):
            backup_file = Path(backup_dir) / src_file.name
            
            if not backup_file.exists():
                print(f'新增文件: {src_file}')
                continue
            
            src_content = src_file.read_text()
            backup_content = backup_file.read_text()
            
            if src_content != backup_content:
                print(f'修改文件: {src_file}')

# 使用
assistant = RefactoringAssistant()
assistant.refactor_directory('src/')
assistant.compare_changes('src/', 'backup/')

8. 最佳实践

✅ DO - 推荐做法

  1. 使用环境变量管理 API Key

    const codex = new CodexSDK({
      apiKey: process.env.OPENAI_API_KEY,
    });
    
  2. 处理错误

    try {
      const result = await codex.execute({ task: '...' });
    } catch (error) {
      console.error('执行失败:', error.message);
    }
    
  3. 使用流式处理

    const stream = await codex.executeStream({ task: '...' });
    for await (const chunk of stream) {
      process.stdout.write(chunk.content);
    }
    
  4. 批量处理时使用并发控制

    const results = await Promise.all(
      tasks.map(task => codex.execute({ task }))
    );
    
  5. 保存日志

    const result = await codex.execute({ task: '...' });
    await fs.writeFile('output.log', result.output);
    

❌ DON’T - 避免事项

  1. 不要硬编码 API Key

    // ❌ 错误
    const codex = new CodexSDK({
      apiKey: 'sk-xxx',
    });
    
    // ✅ 正确
    const codex = new CodexSDK({
      apiKey: process.env.OPENAI_API_KEY,
    });
    
  2. 不要忽略错误

    // ❌ 错误
    const result = await codex.execute({ task: '...' });
    
    // ✅ 正确
    try {
      const result = await codex.execute({ task: '...' });
    } catch (error) {
      // 处理错误
    }
    
  3. 不要无限重试

    // ❌ 错误
    while (true) {
      try {
        await codex.execute({ task: '...' });
        break;
      } catch (error) {
        // 无限重试
      }
    }
    
    // ✅ 正确
    for (let i = 0; i < 3; i++) {
      try {
        await codex.execute({ task: '...' });
        break;
      } catch (error) {
        if (i === 2) throw error;
        await new Promise(r => setTimeout(r, 1000 * (i + 1)));
      }
    }
    
  4. 不要处理敏感数据

    // ❌ 错误
    const result = await codex.execute({
      task: `处理以下数据:${sensitiveData}`,
    });
    
    // ✅ 正确
    // 先脱敏再处理
    

📋 检查清单

  • 使用环境变量管理 API Key
  • 处理所有可能的错误
  • 使用流式处理大任务
  • 批量处理时控制并发
  • 保存日志和结果
  • 不处理敏感数据
  • 测试代码

9. 常见问题

❓ Q1:SDK 和 CLI 有什么区别?

A

  • CLI:命令行工具,适合手动操作和脚本
  • SDK:编程接口,适合集成到应用

❓ Q2:支持哪些语言?

A

  • Node.js SDK(JavaScript/TypeScript)
  • Python SDK
  • REST API(任何语言)

❓ Q3:如何处理超时?

A

const codex = new CodexSDK({
  apiKey: process.env.OPENAI_API_KEY,
  timeout: 60000, // 60 秒
});

❓ Q4:如何降低费用?

A

  1. 使用更便宜的模型:gpt-4o-mini
  2. 压缩任务描述
  3. 使用缓存
  4. 批量处理

❓ Q5:支持流式输出吗?

A:是的,使用 executeStream 方法。

❓ Q6:如何处理大文件?

A

// 分块处理
const chunks = splitIntoChunks(content, 1000);
const results = await Promise.all(
  chunks.map(chunk => codex.execute({
    task: `处理以下内容:${chunk}`,
  }))
);

10. 总结

🎯 核心要点

  1. 什么是 SDK:编程接口,用代码调用 AI
  2. 为什么用:集成到应用、自动化、批量处理
  3. Node.js SDKnpm install @openai/codex-sdk
  4. Python SDKpip install codex-sdk
  5. REST API:HTTP 调用
  6. 高级用法:流式、批量、重试、上下文

📋 快速开始

# Node.js
npm install @openai/codex-sdk

# Python
pip install codex-sdk
// Node.js
import { CodexSDK } from '@openai/codex-sdk';
const codex = new CodexSDK({ apiKey: process.env.OPENAI_API_KEY });
const result = await codex.execute({ task: '...' });
# Python
from codex_sdk import CodexSDK
codex = CodexSDK(api_key=os.environ['OPENAI_API_KEY'])
result = codex.execute(task='...')

📚 下一步

  • 📖 第10篇:[GitHub Action:打造 AI 驱动的 CI/CD 流水线]
  • 🔧 实践:用 SDK 构建一个自动化工具
  • 💬 社区:分享你的 SDK 使用经验

📝 系列文章导航

  • 上一篇:[第8篇 - 非交互模式:自动化你的开发工作流]
  • 下一篇:[第10篇 - GitHub Action:打造 AI 驱动的 CI/CD 流水线]
  • 系列目录:[Codex CLI 中文官方手册与使用指南(12篇)]

💡 遇到问题? 欢迎在评论区留言,我会及时回复!

👍 觉得有用? 点赞收藏,帮助更多开发者!

Logo

小龙虾开发者社区是 CSDN 旗下专注 OpenClaw 生态的官方阵地,聚焦技能开发、插件实践与部署教程,为开发者提供可直接落地的方案、工具与交流平台,助力高效构建与落地 AI 应用

更多推荐