一、整体架构与基础信息
1. 基础 URL 与版本
- 所有接口前缀:
https://api.openai.com/v1 - 认证方式:Bearer Token(API Key)
http
Authorization: Bearer sk-xxxxxxxxxxxxxxxxxxxxxxxx- 数据格式:JSON
- 计费单位:Token(≈4 个英文字符),输入 / 输出分开计费。
2. 官方 SDK(推荐)
bash
运行
pip install openai # Python npm install openai # Node.js所有代码示例基于Python SDK v1.x(最新版)。
二、核心接口大全(按功能分类)
🧠 1.对话生成(Chat Completions)— 最常用
Endpoint:POST /v1/chat/completions模型:gpt-4o、gpt-4o-mini、gpt-3.5-turbo、o1-preview(推理)
完整示例
python
运行
from openai import OpenAI client = OpenAI() response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "你是资深技术专家"}, {"role": "user", "content": "解释一下什么是向量数据库"} ], temperature=0.7, max_tokens=1024, top_p=1.0, frequency_penalty=0.0, presence_penalty=0.0, stream=False ) print(response.choices[0].message.content)关键参数详解
model:模型名称(必填)messages:对话历史(必填)role:system(设定角色)、user(用户)、assistant(模型)
temperature:0~2,越低越确定,越高越发散max_tokens:最大输出长度stream=True:流式输出(逐字返回)response_format:{"type": "json_object"}强制输出 JSONtools/tool_choice:函数调用(后文详解)
🆕 2. 新版智能体接口(Responses API)
Endpoint:POST /v1/responses特点:内置 Web 搜索、文件搜索、代码执行,更适合 Agent
python
运行
response = client.responses.create( model="gpt-4o", input="2026年最新AI趋势", tools=[{"type": "web_search"}] )🖼️ 3. 文生图 / 图编辑(Images)
3.1 文生图(DALL・E 3)
Endpoint:POST /v1/images/generations
python
运行
response = client.images.generate( model="dall-e-3", prompt="赛博朋克风格的猫", size="1024x1024", quality="standard", n=1 ) print(response.data[0].url)3.2 图片编辑(Inpaint)
Endpoint:POST /v1/images/edits
- 需要:原图(PNG,透明背景)+ 蒙版图
python
运行
response = client.images.edit( image=open("original.png", "rb"), mask=open("mask.png", "rb"), prompt="把猫换成狗" )3.3 图片变体(Variations)
Endpoint:POST /v1/images/variations
python
运行
response = client.images.create_variation( image=open("cat.png", "rb"), n=2 )🎤 4. 语音接口(Audio)
4.1 语音转文字(Whisper)
Endpoint:POST /v1/audio/transcriptions
python
运行
audio_file = open("speech.mp3", "rb") transcription = client.audio.transcriptions.create( model="whisper-1", file=audio_file ) print(transcription.text)4.2 文字转语音(TTS)
Endpoint:POST /v1/audio/speech
python
运行
response = client.audio.speech.create( model="tts-1", voice="alloy", # alloy, echo, fable, onyx, nova, shimmer input="你好,我是OpenAI语音助手" ) response.stream_to_file("output.mp3")📊 5. 向量嵌入(Embeddings)— RAG 核心
Endpoint:POST /v1/embeddings模型:text-embedding-3-small、text-embedding-3-large
python
运行
response = client.embeddings.create( input=["向量数据库是什么", "什么是嵌入向量"], model="text-embedding-3-large" ) # 取第一个向量 vector = response.data[0].embedding print(len(vector)) # 3072 维(large)用途:语义搜索、文档聚类、推荐系统、RAG 检索。
🛡️ 6. 内容审核(Moderation)
Endpoint:POST /v1/moderations
python
运行
response = client.moderations.create( input="暴力内容" ) print(response.results[0].flagged) # True=违规🧰 7. 函数调用(Function Calling)— 工具集成
让模型自动调用你的代码 / API。
示例:天气查询
python
运行
tools = [ { "type": "function", "function": { "name": "get_weather", "description": "获取指定城市天气", "parameters": { "type": "object", "properties": { "city": {"type": "string", "description": "城市名"} }, "required": ["city"] } } } ] response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "北京今天天气"}], tools=tools, tool_choice="auto" )🧪 8. 微调(Fine-tuning)— 定制模型
Endpoint:/v1/fine_tuning/jobs
步骤
- 准备数据(JSONL 格式)
json
{"messages": [{"role": "user", "content": "问题"}, {"role": "assistant", "content": "答案"}]}- 上传文件
python
运行
file = client.files.create( file=open("train.jsonl", "rb"), purpose="fine-tune" )- 创建微调任务
python
运行
job = client.fine_tuning.jobs.create( training_file=file.id, model="gpt-4o-mini" )📦 9. 批量处理(Batch API)— 省钱 50%
适合大规模离线任务,延迟高、价格低。
python
运行
batch = client.batches.create( input_file_id=file.id, endpoint="/v1/chat/completions", completion_window="24h" )🤖 10. 助手 API(Assistants)— 企业级 Agent 框架
核心概念:Assistant(助手)、Thread(对话线程)、Run(执行)
python
运行
# 创建助手 assistant = client.assistants.create( name="文档助手", instructions="你是文档分析专家", model="gpt-4o" ) # 创建线程 thread = client.threads.create() # 添加消息 client.threads.messages.create( thread_id=thread.id, role="user", content="分析这份文档" ) # 运行助手 run = client.threads.runs.create( thread_id=thread.id, assistant_id=assistant.id )⚡ 11. 实时语音对话(Realtime)
Endpoint:wss://api.openai.com/v1/realtime(WebSocket)功能:低延迟双向语音对话,支持打断。
三、模型大全(2026 最新)
1. 对话模型(Text)
| 模型 | 上下文 | 特点 |
|---|---|---|
gpt-4o | 128k | 最强多模态,图文音都支持 |
gpt-4o-mini | 128k | 轻量高效,性价比极高 |
gpt-3.5-turbo | 16k | 经典快速,适合简单任务 |
o1-preview | 128k | 超强推理,数学 / 逻辑 / 代码 |
2. 图像模型
dall-e-3:高质量文生图、图编辑
3. 语音模型
whisper-1:语音转文字(多语言)tts-1:文字转语音(6 种音色)
4. 嵌入模型
text-embedding-3-small:1536 维,快、便宜text-embedding-3-large:3072 维,准、稍贵
四、关键参数终极详解
1. 生成控制
temperature:0 = 最确定,2 = 最随机top_p:核采样,0.1 = 只选前 10% 概率词frequency_penalty:-2~2,抑制重复词汇presence_penalty:-2~2,鼓励新话题
2. 输出格式
stream=True:流式输出(逐块返回)response_format={"type":"json_object"}:强制 JSONseed:固定随机种子,尽量复现结果
五、错误处理与最佳实践
1. 常见错误码
401:API Key 错误 / 过期429:速率限制超限(RPM/TPM)500:服务器内部错误(重试)
2. 生产环境建议
- 用 gpt-4o-mini 做日常,gpt-4o 做复杂
- 流式输出提升用户体验
- 批量处理降低成本
- 函数调用集成外部能力
- RAG + Embeddings 解决幻觉
六、兼容替代(国内可用)
所有主流国产大模型完全兼容 OpenAI 协议,只需换base_url和api_key:
- DeepSeek:
https://api.deepseek.com - 讯飞星火:
https://spark-api-open.xf-yun.com/v1 - Kimi:
https://api.moonshot.cn/v1