一、整体架构与基础信息1. 基础 URL 与版本所有接口前缀https://api.openai.com/v1认证方式Bearer TokenAPI KeyhttpAuthorization: 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— 最常用EndpointPOST /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( modelgpt-4o, messages[ {role: system, content: 你是资深技术专家}, {role: user, content: 解释一下什么是向量数据库} ], temperature0.7, max_tokens1024, top_p1.0, frequency_penalty0.0, presence_penalty0.0, streamFalse ) print(response.choices[0].message.content)关键参数详解model模型名称必填messages对话历史必填rolesystem设定角色、user用户、assistant模型temperature0~2越低越确定越高越发散max_tokens最大输出长度streamTrue流式输出逐字返回response_format{type: json_object}强制输出 JSONtools/tool_choice函数调用后文详解 2. 新版智能体接口Responses APIEndpointPOST /v1/responses特点内置 Web 搜索、文件搜索、代码执行更适合 Agentpython运行response client.responses.create( modelgpt-4o, input2026年最新AI趋势, tools[{type: web_search}] )️ 3. 文生图 / 图编辑Images3.1 文生图DALL・E 3EndpointPOST /v1/images/generationspython运行response client.images.generate( modeldall-e-3, prompt赛博朋克风格的猫, size1024x1024, qualitystandard, n1 ) print(response.data[0].url)3.2 图片编辑InpaintEndpointPOST /v1/images/edits需要原图PNG透明背景 蒙版图python运行response client.images.edit( imageopen(original.png, rb), maskopen(mask.png, rb), prompt把猫换成狗 )3.3 图片变体VariationsEndpointPOST /v1/images/variationspython运行response client.images.create_variation( imageopen(cat.png, rb), n2 ) 4. 语音接口Audio4.1 语音转文字WhisperEndpointPOST /v1/audio/transcriptionspython运行audio_file open(speech.mp3, rb) transcription client.audio.transcriptions.create( modelwhisper-1, fileaudio_file ) print(transcription.text)4.2 文字转语音TTSEndpointPOST /v1/audio/speechpython运行response client.audio.speech.create( modeltts-1, voicealloy, # alloy, echo, fable, onyx, nova, shimmer input你好我是OpenAI语音助手 ) response.stream_to_file(output.mp3) 5. 向量嵌入Embeddings— RAG 核心EndpointPOST /v1/embeddings模型text-embedding-3-small、text-embedding-3-largepython运行response client.embeddings.create( input[向量数据库是什么, 什么是嵌入向量], modeltext-embedding-3-large ) # 取第一个向量 vector response.data[0].embedding print(len(vector)) # 3072 维large用途语义搜索、文档聚类、推荐系统、RAG 检索。️ 6. 内容审核ModerationEndpointPOST /v1/moderationspython运行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( modelgpt-4o, messages[{role: user, content: 北京今天天气}], toolstools, tool_choiceauto ) 8. 微调Fine-tuning— 定制模型Endpoint/v1/fine_tuning/jobs步骤准备数据JSONL 格式json{messages: [{role: user, content: 问题}, {role: assistant, content: 答案}]}上传文件python运行file client.files.create( fileopen(train.jsonl, rb), purposefine-tune )创建微调任务python运行job client.fine_tuning.jobs.create( training_filefile.id, modelgpt-4o-mini ) 9. 批量处理Batch API— 省钱 50%适合大规模离线任务延迟高、价格低。python运行batch client.batches.create( input_file_idfile.id, endpoint/v1/chat/completions, completion_window24h ) 10. 助手 APIAssistants— 企业级 Agent 框架核心概念Assistant助手、Thread对话线程、Run执行python运行# 创建助手 assistant client.assistants.create( name文档助手, instructions你是文档分析专家, modelgpt-4o ) # 创建线程 thread client.threads.create() # 添加消息 client.threads.messages.create( thread_idthread.id, roleuser, content分析这份文档 ) # 运行助手 run client.threads.runs.create( thread_idthread.id, assistant_idassistant.id )⚡ 11. 实时语音对话RealtimeEndpointwss://api.openai.com/v1/realtimeWebSocket功能低延迟双向语音对话支持打断。三、模型大全2026 最新1. 对话模型Text模型上下文特点gpt-4o128k最强多模态图文音都支持gpt-4o-mini128k轻量高效性价比极高gpt-3.5-turbo16k经典快速适合简单任务o1-preview128k超强推理数学 / 逻辑 / 代码2. 图像模型dall-e-3高质量文生图、图编辑3. 语音模型whisper-1语音转文字多语言tts-1文字转语音6 种音色4. 嵌入模型text-embedding-3-small1536 维快、便宜text-embedding-3-large3072 维准、稍贵四、关键参数终极详解1. 生成控制temperature0 最确定2 最随机top_p核采样0.1 只选前 10% 概率词frequency_penalty-2~2抑制重复词汇presence_penalty-2~2鼓励新话题2. 输出格式streamTrue流式输出逐块返回response_format{type:json_object}强制 JSONseed固定随机种子尽量复现结果五、错误处理与最佳实践1. 常见错误码401API Key 错误 / 过期429速率限制超限RPM/TPM500服务器内部错误重试2. 生产环境建议用 gpt-4o-mini 做日常gpt-4o 做复杂流式输出提升用户体验批量处理降低成本函数调用集成外部能力RAG Embeddings 解决幻觉六、兼容替代国内可用所有主流国产大模型完全兼容 OpenAI 协议只需换base_url和api_keyDeepSeekhttps://api.deepseek.com讯飞星火https://spark-api-open.xf-yun.com/v1Kimihttps://api.moonshot.cn/v1