OpenAI 适配器
使用 OpenAI 适配器连接 GPT-5、GPT-4、o3、o4-mini 等模型
OpenAI 适配器包提供了两个适配器,对应不同的 OpenAI API 端点:
openaiAdapter- 使用 Chat Completions API (/v1/chat/completions) - 传统的、稳定的 APIopenaiResponsesAdapter- 使用 Responses API (/v1/responses) - 更新的 API,支持更多功能
安装
pnpm add @amux.ai/llm-bridge @amux.ai/adapter-openai选择适配器
| 特性 | openaiAdapter | openaiResponsesAdapter |
|---|---|---|
| 端点 | /v1/chat/completions | /v1/responses |
| 稳定性 | 稳定,广泛使用 | 较新的 API |
| 推理能力 | ❌ | ✅ (o3, o4-mini) |
| 网络搜索 | ❌ | ✅ (内置工具) |
| 文件搜索 | ❌ | ✅ (内置工具) |
| 代码解释器 | ❌ | ✅ (内置工具) |
| 状态上下文 | ❌ | ✅ (previous_response_id) |
| JSON 模式 | ✅ | ✅ |
| 兼容性 | 最大兼容性 | 最新功能 |
建议:生产环境需要稳定性时使用 openaiAdapter。需要最新功能(如内置网络搜索、推理模型 o3/o4-mini 或状态化多轮对话)时使用 openaiResponsesAdapter。
重要:标准的 openaiAdapter 不支持推理模型(o3、o4-mini)。推理能力仅通过 openaiResponsesAdapter 提供。
基本使用
使用 Chat Completions API (openaiAdapter)
import { createBridge } from '@amux.ai/llm-bridge'
import { openaiAdapter } from '@amux.ai/adapter-openai'
const bridge = createBridge({
inbound: openaiAdapter,
outbound: openaiAdapter,
config: {
apiKey: process.env.OPENAI_API_KEY
}
})
const response = await bridge.chat({
model: 'gpt-4',
messages: [
{ role: 'system', content: '你是一个有帮助的助手。' },
{ role: 'user', content: '什么是 Amux?' }
]
})
console.log(response.choices[0].message.content)使用 Responses API (openaiResponsesAdapter)
import { createBridge } from '@amux.ai/llm-bridge'
import { openaiResponsesAdapter } from '@amux.ai/adapter-openai'
const bridge = createBridge({
inbound: openaiResponsesAdapter,
outbound: openaiResponsesAdapter,
config: {
apiKey: process.env.OPENAI_API_KEY
}
})
const response = await bridge.chat({
model: 'gpt-4',
messages: [
{ role: 'user', content: '什么是 Amux?' }
]
})
console.log(response.choices[0].message.content)流式响应
const stream = bridge.chatStream({
model: 'gpt-4',
messages: [
{ role: 'user', content: '讲一个关于 AI 的故事' }
],
stream: true
})
for await (const chunk of stream) {
if (chunk.choices[0]?.delta?.content) {
process.stdout.write(chunk.choices[0].delta.content)
}
}支持的功能
函数调用
两个适配器都完全支持函数调用(工具使用):
const response = await bridge.chat({
model: 'gpt-4',
messages: [
{ role: 'user', content: '北京现在几点?' }
],
tools: [{
type: 'function',
function: {
name: 'get_current_time',
description: '获取指定城市的当前时间',
parameters: {
type: 'object',
properties: {
city: {
type: 'string',
description: '城市名称'
}
},
required: ['city']
}
}
}],
tool_choice: 'auto'
})
// 检查是否有函数调用
const toolCalls = response.choices[0].message.tool_calls
if (toolCalls) {
for (const toolCall of toolCalls) {
console.log('函数名:', toolCall.function.name)
console.log('参数:', toolCall.function.arguments)
}
}工具选择选项:
auto- 让模型决定是否调用函数none- 强制模型不调用函数required- 强制模型调用函数{ type: 'function', function: { name: 'function_name' } }- 强制调用特定函数
视觉(GPT-4V)
使用 GPT-4o(多模态)分析图像:
const response = await bridge.chat({
model: 'gpt-4o',
messages: [{
role: 'user',
content: [
{
type: 'text',
text: '这张图片里有什么?'
},
{
type: 'image_url',
image_url: {
url: 'https://example.com/image.jpg',
detail: 'high' // 'low', 'high', 'auto'
}
}
]
}],
max_tokens: 300
})
console.log(response.choices[0].message.content)图像格式支持:
- URL(https://)
- Base64 编码(data:image/jpeg;base64,...)
详细级别:
low- 低分辨率,更快更便宜high- 高分辨率,更详细但更贵auto- 自动选择(默认)
JSON 模式
强制模型返回有效的 JSON:
const response = await bridge.chat({
model: 'gpt-4o',
messages: [
{
role: 'system',
content: '你是一个帮助提取结构化数据的助手。始终以 JSON 格式响应。'
},
{
role: 'user',
content: '从这段文本中提取人名和地点:张三昨天去了北京。'
}
],
response_format: { type: 'json_object' }
})
const data = JSON.parse(response.choices[0].message.content)
console.log(data)
// { "person": "张三", "location": "北京", "time": "昨天" }使用 JSON 模式时,必须在系统消息或用户消息中明确指示模型生成 JSON。
Responses API 独有功能
openaiResponsesAdapter 提供了仅在 Responses API 中可用的功能:
推理模型 (o3, o4-mini)
import { createBridge } from '@amux.ai/llm-bridge'
import { openaiResponsesAdapter } from '@amux.ai/adapter-openai'
const bridge = createBridge({
inbound: openaiResponsesAdapter,
outbound: openaiResponsesAdapter,
config: { apiKey: process.env.OPENAI_API_KEY }
})
const response = await bridge.chat({
model: 'o3',
messages: [
{ role: 'user', content: '解决这个复杂的数学问题...' }
],
extensions: {
responses: {
reasoning: {
effort: 'high' // 'low', 'medium', 'high'
}
}
}
})状态化多轮对话
// 第一次请求
const response1 = await bridge.chat({
model: 'gpt-4.1',
messages: [{ role: 'user', content: '我叫小明' }]
})
// 获取响应 ID 用于上下文
const responseId = response1.raw.id
// 后续请求保持上下文
const response2 = await bridge.chat({
model: 'gpt-4.1',
messages: [{ role: 'user', content: '我叫什么名字?' }],
extensions: {
responses: {
previousResponseId: responseId
}
}
})
// 响应: "你叫小明"内置网络搜索
const response = await bridge.chat({
model: 'gpt-4.1',
messages: [
{ role: 'user', content: '最近有什么关于 AI 的新闻?' }
],
extensions: {
responses: {
builtInTools: [
{ type: 'web_search_preview', search_context_size: 'medium' }
]
}
}
})代码解释器
const response = await bridge.chat({
model: 'gpt-4.1',
messages: [
{ role: 'user', content: '计算 100 的阶乘' }
],
extensions: {
responses: {
builtInTools: [{ type: 'code_interpreter' }]
}
}
})文件搜索
const response = await bridge.chat({
model: 'gpt-4.1',
messages: [
{ role: 'user', content: '查找关于...' }
],
extensions: {
responses: {
builtInTools: [{
type: 'file_search',
vector_store_ids: ['vs_xxx'],
max_num_results: 10
}]
}
}
})存储控制
// 禁用状态存储以保护隐私
const response = await bridge.chat({
model: 'gpt-4.1',
messages: [{ role: 'user', content: '敏感查询...' }],
extensions: {
responses: {
store: false // 不存储此对话
}
}
})高级参数
const response = await bridge.chat({
model: 'gpt-4',
messages: [
{ role: 'user', content: '写一首关于 AI 的诗' }
],
// 温度控制(0-2)
temperature: 0.7,
// Top-p 采样
top_p: 0.9,
// 最大令牌数
max_tokens: 500,
// 频率惩罚(-2.0 到 2.0)
frequency_penalty: 0.5,
// 存在惩罚(-2.0 到 2.0)
presence_penalty: 0.5,
// 停止序列
stop: ['\n\n', '---'],
// 用户标识(用于滥用监控)
user: 'user-123',
// 随机种子(用于可重现性)
seed: 42,
// Logprobs
logprobs: true,
top_logprobs: 3
})支持的模型
GPT-5 系列(最新)
| 模型 | 上下文长度 | 描述 |
|---|---|---|
gpt-5.2-pro | 400K | 最先进模型,ARC-AGI-1 >90% |
gpt-5.2 | 400K | 旗舰模型,GDPval 70.9% |
gpt-5.1 | 128K | 智能与速度平衡,SWE-bench 76.3% |
gpt-5 | 128K | 旗舰稳定版 |
gpt-5-mini | 128K | GPT-5 轻量版 |
gpt-5-nano | 128K | GPT-5 超轻量版 |
GPT-4 系列
| 模型 | 上下文长度 | 描述 |
|---|---|---|
gpt-4.1 | 128K | 速度快,主力模型 |
gpt-4.1-mini | 128K | 更便宜的轻量版本 |
gpt-4o | 128K | 综合能力平衡,多模态支持 |
gpt-4o-mini | 128K | 轻量快速版本 |
推理模型(仅 Responses API)
| 模型 | 描述 |
|---|---|
o3 | 最新推理模型,用于复杂任务 |
o4-mini | 轻量级推理模型 |
推理模型(o3、o4-mini)仅通过 Responses API(openaiResponsesAdapter)可用。它们支持通过 reasoning.effort 参数控制推理强度。
Codex 系列(编程专用)
| 模型 | 描述 |
|---|---|
gpt-5.1-codex | SWE-bench 76.3%,长时编程任务专用 |
gpt-5.1-codex-mini | 轻量编程版本 |
gpt-5-codex-high | 编程能力最强 |
gpt-5-codex-medium | 中等性能 |
gpt-5-codex-low | 轻量版本 |
GPT-5 系列特殊要求:
- 温度参数
temperature必须设置为 1 - 使用
max_completion_tokens替代max_tokens - 不要传递
top_p参数
模型列表可能会更新。查看 OpenAI 文档 获取最新信息。
配置选项
const bridge = createBridge({
inbound: openaiAdapter, // 或 openaiResponsesAdapter
outbound: openaiAdapter,
config: {
// 必需:API 密钥
apiKey: process.env.OPENAI_API_KEY,
// 可选:自定义 API 端点
baseURL: 'https://api.openai.com',
// 可选:组织 ID
organization: 'org-xxx',
// 可选:请求超时(毫秒)
timeout: 60000,
// 可选:自定义请求头
headers: {
'Custom-Header': 'value'
}
}
})适配器迁移
从 openaiAdapter 迁移到 openaiResponsesAdapter
当直接使用 Bridge 时,请求格式保持不变(IR 格式):
// 之前:使用 Chat Completions API
import { openaiAdapter } from '@amux.ai/adapter-openai'
const bridge = createBridge({
inbound: openaiAdapter,
outbound: openaiAdapter,
config: { apiKey: process.env.OPENAI_API_KEY }
})
// 之后:使用 Responses API
import { openaiResponsesAdapter } from '@amux.ai/adapter-openai'
const bridge = createBridge({
inbound: openaiResponsesAdapter,
outbound: openaiResponsesAdapter,
config: { apiKey: process.env.OPENAI_API_KEY }
})
// 请求格式保持不变(IR 格式)!
const response = await bridge.chat({
model: 'gpt-4',
messages: [{ role: 'user', content: '你好' }]
})应用开发者注意: 如果你正在构建一个应用(Web 应用、CLI 等),直接向使用 openaiResponsesAdapter 的端点发送 HTTP 请求,你必须发送 Responses API 格式的请求,而不是 Chat Completions 格式。
// ❌ 错误:向 Responses API 端点发送 Chat Completions 格式
fetch('/v1/responses', {
body: JSON.stringify({
model: 'gpt-4',
messages: [{ role: 'user', content: '你好' }] // 错误的格式!
})
})
// ✅ 正确:发送 Responses API 格式
fetch('/v1/responses', {
body: JSON.stringify({
model: 'gpt-4',
input: [
{
type: 'message',
role: 'user',
content: [{ type: 'text', text: '你好' }]
}
]
})
})每个适配器都有自己的标准格式。你的应用层应该适配适配器的格式,而不是反过来。
跨 API 转换
import { openaiAdapter, openaiResponsesAdapter } from '@amux.ai/adapter-openai'
// 接受旧格式请求,调用新 API
const bridge = createBridge({
inbound: openaiAdapter, // 接受 Chat Completions 格式
outbound: openaiResponsesAdapter, // 调用 Responses API
config: { apiKey: process.env.OPENAI_API_KEY }
})错误处理
try {
const response = await bridge.chat({
model: 'gpt-4',
messages: [{ role: 'user', content: '你好' }]
})
} catch (error) {
if (error.response) {
// OpenAI API 错误
console.error('状态码:', error.response.status)
console.error('错误类型:', error.response.data.error.type)
console.error('错误消息:', error.response.data.error.message)
// 常见错误类型
switch (error.response.data.error.type) {
case 'invalid_request_error':
console.log('请求参数无效')
break
case 'authentication_error':
console.log('API 密钥无效')
break
case 'rate_limit_error':
console.log('超出速率限制')
break
case 'insufficient_quota':
console.log('配额不足')
break
}
}
}最佳实践
1. 使用环境变量
# .env
OPENAI_API_KEY=sk-...
OPENAI_ORG_ID=org-...import 'dotenv/config'
const bridge = createBridge({
inbound: openaiAdapter,
outbound: openaiAdapter,
config: {
apiKey: process.env.OPENAI_API_KEY,
organization: process.env.OPENAI_ORG_ID
}
})2. 控制成本
// 使用更便宜的模型
const response = await bridge.chat({
model: 'gpt-4o-mini', // 而不是 gpt-5
messages: [...],
max_tokens: 100 // 限制输出长度
})3. 处理速率限制
async function chatWithRetry(request, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await bridge.chat(request)
} catch (error) {
if (error.response?.data?.error?.type === 'rate_limit_error') {
const waitTime = Math.pow(2, i) * 1000 // 指数退避
console.log(`速率限制,等待 ${waitTime}ms...`)
await new Promise(resolve => setTimeout(resolve, waitTime))
continue
}
throw error
}
}
throw new Error('达到最大重试次数')
}与其他适配器配合使用
OpenAI → Anthropic
import { openaiAdapter } from '@amux.ai/adapter-openai'
import { anthropicAdapter } from '@amux.ai/adapter-anthropic'
// 接受 OpenAI 格式,调用 Claude
const bridge = createBridge({
inbound: openaiAdapter,
outbound: anthropicAdapter,
config: {
apiKey: process.env.ANTHROPIC_API_KEY
}
})
// 使用 OpenAI 格式发送请求
const response = await bridge.chat({
model: 'gpt-4', // 会被映射到 Claude
messages: [{ role: 'user', content: '你好' }]
})OpenAI → DeepSeek
import { openaiAdapter } from '@amux.ai/adapter-openai'
import { deepseekAdapter } from '@amux.ai/adapter-deepseek'
// 接受 OpenAI 格式,调用 DeepSeek
const bridge = createBridge({
inbound: openaiAdapter,
outbound: deepseekAdapter,
config: {
apiKey: process.env.DEEPSEEK_API_KEY
}
})功能支持对比
| 功能 | openaiAdapter | openaiResponsesAdapter |
|---|---|---|
| 聊天补全 | ✅ | ✅ |
| 流式传输 | ✅ | ✅ |
| 函数调用 | ✅ | ✅ |
| 视觉 | ✅ | ✅ |
| JSON 模式 | ✅ | ✅ (通过 text.format) |
| 系统提示 | ✅ | ✅ (通过 instructions) |
| 工具选择 | ✅ | ✅ |
| Logprobs | ✅ | ❌ |
| 种子 | ✅ | ❌ |
| 推理能力 | ❌ | ✅ (o3, o4-mini) |
| 网络搜索 | ❌ | ✅ (内置工具) |
| 文件搜索 | ❌ | ✅ (内置工具) |
| 代码解释器 | ❌ | ✅ (内置工具) |
| 状态上下文 | ❌ | ✅ (previous_response_id) |
| 并行工具调用 | ✅ | ✅ |
限制
- 速率限制:根据您的账户层级有不同的限制
- 上下文长度:不同模型有不同的最大令牌数
- 成本:GPT-4 比 GPT-3.5 贵得多
- 可用性:某些模型可能需要加入等待列表