AgentHarness 课程

第四十二课:Codex SDK

4.8K字·13分钟·
编程接口自定义工具集成API调用

学习目标

  • 了解 Codex SDK 的概念和价值
  • 掌握编程接口的使用方法
  • 学会集成到自定义应用
  • 了解高级功能和最佳实践

一、什么是 Codex SDK

Codex SDK 提供编程接口,让你可以在自己的应用中集成 Codex 的能力。它是一组 API 和工具,让开发者可以构建基于 Codex 的应用。

1.1 核心功能

  • 调用 Codex 执行任务
  • 管理会话和上下文
  • 自定义工具和插件
  • 集成到现有工作流
  • 流式响应处理

1.2 使用场景

  • 构建自定义 IDE 插件
  • 创建自动化工具
  • 集成到 CI/CD 流水线
  • 开发 AI 辅助应用
  • 构建代码分析工具

1.3 与其他方式的区别

方面CLISDK
使用方式命令行编程接口
灵活性有限完全控制
集成难度简单需要编程
适用场景交互式使用应用集成

二、安装和配置

2.1 安装

npm install @openai/codex-sdk

2.2 基本配置

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

const codex = new Codex({
  apiKey: process.env.OPENAI_API_KEY,
  model: 'codex-mini-latest',
  sandbox: 'workspace-write'
});

2.3 高级配置

const codex = new Codex({
  apiKey: process.env.OPENAI_API_KEY,
  model: 'gpt-5-codex',
  sandbox: 'workspace-write',
  approvalPolicy: 'on-request',
  maxTokens: 4096,
  temperature: 0.7
});

三、基本使用

3.1 执行任务

const result = await codex.run('实现这个功能');
console.log(result.output);
console.log(result.changes);

3.2 管理会话

const session = codex.createSession();
await session.send('第一个任务');
await session.send('继续第二个任务');
const history = session.getHistory();

3.3 自定义工具

codex.registerTool({
  name: 'my-tool',
  description: 'My custom tool',
  parameters: {
    type: 'object',
    properties: {
      input: { type: 'string' }
    }
  },
  handler: async (input) => {
    // 处理逻辑
    return { result: `Processed: ${input}` };
  }
});

四、高级功能

4.1 流式响应

const stream = await codex.runStream('任务描述');
for await (const chunk of stream) {
  process.stdout.write(chunk);
}

4.2 事件监听

codex.on('tool-call', (call) => {
  console.log('Tool called:', call.name);
  console.log('Parameters:', call.parameters);
});

codex.on('message', (message) => {
  console.log('Message:', message.content);
});

codex.on('error', (error) => {
  console.error('Error:', error.message);
});

4.3 错误处理

try {
  const result = await codex.run('任务描述');
} catch (error) {
  if (error.code === 'TIMEOUT') {
    console.error('任务超时');
  } else if (error.code === 'QUOTA_EXCEEDED') {
    console.error('配额不足');
  } else {
    console.error('错误:', error.message);
  }
}

4.4 上下文管理

const session = codex.createSession({
  context: {
    project: 'my-project',
    language: 'typescript',
    framework: 'react'
  }
});

五、集成示例

5.1 Express API

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

const app = express();
const codex = new Codex({ apiKey: process.env.OPENAI_API_KEY });

app.post('/api/codex', async (req, res) => {
  try {
    const result = await codex.run(req.body.task);
    res.json(result);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000);

5.2 CLI 工具

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

const codex = new Codex({ apiKey: process.env.OPENAI_API_KEY });
const task = process.argv[2];

const result = await codex.run(task);
console.log(result.output);

5.3 VS Code 扩展

import * as vscode from 'vscode';
import { Codex } from '@openai/codex-sdk';

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

vscode.commands.registerCommand('codex.run', async () => {
  const task = await vscode.window.showInputBox({
    prompt: '输入任务描述'
  });
  
  if (task) {
    const result = await codex.run(task);
    // 显示结果
    vscode.window.showInformationMessage(result.output);
  }
});

5.4 React 组件

import { useState } from 'react';
import { Codex } from '@openai/codex-sdk';

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

function CodexComponent() {
  const [result, setResult] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (task: string) => {
    setLoading(true);
    try {
      const res = await codex.run(task);
      setResult(res.output);
    } catch (error) {
      setResult(`Error: ${error.message}`);
    }
    setLoading(false);
  };

  return (
    <div>
      <input onSubmit={handleSubmit} />
      {loading ? <Spinner /> : <pre>{result}</pre>}
    </div>
  );
}

六、最佳实践

6.1 错误处理

始终处理可能的错误,包括网络错误、API 错误、超时错误等。

6.2 超时设置

设置合理的超时时间,避免长时间等待。对于长时间任务,使用流式响应。

6.3 资源管理

及时释放资源,避免内存泄漏。使用完毕后关闭会话。

6.4 日志记录

记录关键操作,便于调试和监控。记录输入、输出、错误信息。

6.5 安全性

保护 API Key,不要硬编码在代码中。使用环境变量或密钥管理服务。

七、本课小结

要点说明
Codex SDK编程接口,集成到自定义应用
安装npm install @openai/codex-sdk
核心功能执行任务、管理会话、自定义工具
高级功能流式响应、事件监听、错误处理
集成Express API、CLI、VS Code、React

下一步

下一课我们将了解 Hooks 生命周期。