共计 1884 个字符,预计需要花费 5 分钟才能阅读完成。
ChatGPT API 为开发者提供了直接调用大模型能力的通道,能快速为应用添加智能对话功能;其按 token 计费的模式相比传统 NLP 服务更具成本优势;同时支持流式响应和异步调用,适合构建实时交互场景。

直接调用 API vs SDK 封装
- 原生 API 优势:
- 更细粒度控制请求参数和响应处理
- 避免 SDK 版本兼容性问题
-
适合需要深度定制的场景
-
SDK 优势:
- 简化身份验证和错误处理
- 内置类型提示和文档支持
- 快速集成(如
openai库仅需 3 行代码)
实战实现模块
环境配置与密钥管理
import os
from dotenv import load_dotenv # pip install python-dotenv
# 最佳实践:将 API_KEY 存储在.env 文件,并加入.gitignore
load_dotenv()
API_KEY = os.getenv('OPENAI_API_KEY') # 从环境变量读取
带重试机制的请求封装
import openai
from tenacity import retry, stop_after_attempt, wait_exponential # pip install tenacity
@retry(stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=4, max=10)
)
def chat_completion_with_retry(messages):
return openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=0.7,
stream=True # 启用流式响应
)
流式响应处理
def handle_stream_response(response):
full_content = ""
for chunk in response:
if chunk.choices[0].delta.get('content'):
content = chunk.choices[0].delta.content
full_content += content
yield content # 实时生成内容
logger.info(f"Total tokens used: {full_content}")
性能优化策略
连接池配置
import httpx # pip install httpx
client = httpx.Client(
limits=httpx.Limits(
max_connections=100, # 最大连接数
max_keepalive_connections=20 # 保持活跃连接数
),
timeout=30.0 # 超时设置(秒)
)
异步 IO 实现
import asyncio
async def async_chat_request(messages):
async with openai.AsyncOpenAI() as client:
stream = await client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
stream=True
)
async for chunk in stream:
print(chunk.choices[0].delta.get('content', ''), end='')
安全实践
敏感数据过滤
import logging
class SensitiveDataFilter(logging.Filter):
def filter(self, record):
if hasattr(record, 'msg') and 'sk-' in record.msg:
record.msg = '[API_KEY REDACTED]'
return True
logger.addFilter(SensitiveDataFilter())
速率限制规避
- 实现请求队列和令牌桶算法
- 监控
x-ratelimit-remaining响应头 - 错误码 429 时自动退避(参考前文 retry 机制)
延伸思考
- 多轮对话上下文:通过维护 messages 列表(注意 4096 token 限制)
- 本地缓存设计:使用 SQLite 存储对话记录,附加 timestamp 和 session_id
- 响应中断补偿 :记录已返回的 token 位置,通过
finish_reason字段检测中断
实现过程中发现,流式响应能显著提升用户体验感知(尤其长文本场景),但需要处理好网络不稳定性。建议在移动端增加「继续生成」按钮作为降级方案。异步调用虽然复杂,但在高并发场景下资源利用率提升明显,值得投入学习成本。
正文完
