共计 1809 个字符,预计需要花费 5 分钟才能阅读完成。
背景痛点
开发者在集成 ChatGPT API 时,常会遇到以下几个典型问题:

- 认证头处理:需要正确生成和管理 JWT 令牌,处理过期和刷新逻辑
- 流式响应解析 :对 SSE(Server-Sent Events) 数据流的处理不够熟悉
- token 计数策略:估算提示词和响应的 token 消耗,避免超出限额
在通信协议选择上,REST 相比 gRPC 有几个优势:
- 更简单的调试和测试工具支持
- 更好的语言和框架兼容性
- 对浏览器环境更友好
核心实现
Python 实现(aiohttp)
import aiohttp
import json
async def chat_completion(prompt):
headers = {'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
payload = {
'model': 'gpt-3.5-turbo',
'messages': [{'role': 'user', 'content': prompt}],
'stream': True # 启用流式响应
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(
'https://api.openai.com/v1/chat/completions',
headers=headers,
json=payload
) as resp:
async for line in resp.content:
if line.startswith(b'data:'):
chunk = line[6:].strip()
if chunk != b'[DONE]':
yield json.loads(chunk)
except Exception as e:
logging.error(f'API 调用失败: {str(e)}')
raise
Node.js 实现(axios)
const axios = require('axios');
const {createInterface} = require('readline');
async function streamChat(prompt) {
const response = await axios({
method: 'post',
url: 'https://api.openai.com/v1/chat/completions',
headers: {'Authorization': `Bearer ${process.env.OPENAI_KEY}`,
'Content-Type': 'application/json'
},
data: {
model: 'gpt-3.5-turbo',
messages: [{role: 'user', content: prompt}],
stream: true
},
responseType: 'stream'
});
const rl = createInterface({
input: response.data,
crlfDelay: Infinity
});
rl.on('line', (line) => {if (line.startsWith('data:')) {const data = line.substring(6);
if (data !== '[DONE]') {process.stdout.write(JSON.parse(data).choices[0]?.delta?.content || '');
}
}
});
}
进阶考量
性能优化
- 连接池配置:
- Python 中 aiohttp 默认连接池大小是 100
-
Node.js 中 axios 需要手动配置 agent 的 maxSockets
-
请求批处理:
- 对多个独立请求合并为一个 API 调用
-
使用 messages 数组同时处理多轮对话
-
本地缓存策略:
- 对常见问题的回答建立缓存
- 设置合理的 TTL(Time-To-Live)
安全实践
- 使用环境变量管理 API 密钥
- 对用户输入进行消毒处理
- 实现基于 IP 或用户的速率限制
避坑指南
- API 版本管理:
- 在请求头中明确指定 API 版本
-
对响应数据做版本兼容处理
-
上下文管理:
- 避免无限制堆积对话历史
-
定期清理过期的上下文
-
成本控制:
- 监控每个请求的 token 消耗
- 设置预算告警阈值
互动环节
GitHub 模板仓库:chatgpt-api-starter
扩展思考题:
- 如何设计一个支持多租户的 API 代理服务?
- 在移动端应用中优化流式响应的用户体验
- 构建基于对话上下文的长期记忆系统
正文完
发表至: 技术开发
近一天内
