当前位置: 首页 > news >正文

OpenAI API 请求与响应 核心总结


1. 通信协议

HTTPS + HTTP,就是普通的 REST API 调用,无任何特殊协议。流式返回是 HTTP SSE,同样基于 HTTP。


2. 请求结构

URLhttps://api.openai.com/v1/chat/completions

Method:POST

请求头

Authorization: Bearer <API_KEY> Content-Type: application/json

请求体核心字段

字段必填说明
model模型 ID,如gpt-4ogpt-4o-mini
messages消息列表,每条含role+content
max_tokens最大输出 token 数
temperature随机性,0=确定,2=高随机
top_p核采样,与 temperature 二选一
stream是否流式返回(默认 false)
frequency_penalty降低重复,-2.0~2.0
presence_penalty鼓励话题扩展,-2.0~2.0

messages 角色类型

role说明
system系统指令,设置模型行为
user用户输入
assistant模型回复(用于多轮上下文)
tool工具执行结果(函数调用时用)

3. 响应结构

{ "id": "chatcmpl-xxx", "object": "chat.completion", "created": 1746123456, "model": "gpt-4o", "choices": [{ "index": 0, "message": { "role": "assistant", "content": "回复内容" }, "finish_reason": "stop" }], "usage": { "prompt_tokens": 28, "completion_tokens": 142, "total_tokens": 170 } }

流式响应(SSE):将上述内容打散成多个 HTTP chunk:

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"你好"}}]} ​ data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content","}}]} ​ data: [DONE]

4. 函数调用(Tool Calls)

让模型触发外部工具,分三步循环:

用户提问 │ ▼ 模型判断调用工具 → 返回 tool_calls(finish_reason = "tool_calls") │ ▼ 业务代码执行工具,得到结果 │ ▼ 将结果以 role="tool" 追加到 messages,再发请求 │ ▼ 模型整合结果,生成最终回复(finish_reason = "stop")

tool_calls 格式

{ "tool_calls": [{ "id": "call_abc123", "type": "function", "function": { "name": "get_weather", "arguments": "{\"city\":\"北京\",\"unit\":\"celsius\"}" } }] }

tool 消息格式

{ "role": "tool", "tool_call_id": "call_abc123", "name": "get_weather", "content": "{\"temperature\":\"22°C\",\"weather\":\"晴\"}" }

可以链式调用多个工具,不断循环"执行 → 回传 → 再请求"。


5. MCP(Model Context Protocol)

Anthropic 主导的标准化工具调用协议。本质是函数调用的统一封装:

  • MCP Server 自动暴露工具定义

  • OpenAI 运行时动态发现并调用

  • 无需每个应用单独维护 JSON Schema

{ "tools": [{ "type": "mcp", "mcp": { "name": "gitmcp", "server_label": "gitmcp", "server_url": "https://gitmcp.io/openai/codex" } }] }

6. 状态管理

无状态:每次请求都要把完整对话历史塞进messages数组,服务器不保存任何上下文。你自己维护 messages 列表,每次请求完整传过去。

messages = [] # 自己维护 ​ while True: user_input = input("你: ") messages.append({"role": "user", "content": user_input}) ​ resp = requests.post(url, headers=headers, json={ "model": "gpt-4o", "messages": messages # 每次都传完整历史 }) ​ assistant_msg = resp.json()["choices"][0]["message"] messages.append(assistant_msg) ​ print(f"AI: {assistant_msg['content']}")

7. 常见错误码

HTTP 状态码含义
200成功
400请求格式错误(缺少必填字段等)
401API Key 无效或缺失
403无权限(组织/项目限制)
429限流,看Retry-After响应头
500OpenAI 服务器内部错误

8. 错误响应示例

401 — API Key 无效或缺失

{ "error": { "message": "Invalid API key provided. You can find your API key at https://platform.openai.com/account/api-keys.", "type": "invalid_request_error", "code": "invalid_api_key", "param": null, "code": "invalid_api_key" } }

常见原因

  • API Key 写错了或复制少了字符

  • Key 被删除了

  • 用错了环境变量的 Key


400 — 请求格式错误

{ "error": { "message": "Missing required parameter: 'messages'", "type": "invalid_request_error", "param": "messages", "code": null } }
{ "error": { "message": "Invalid JSON: Unexpected token at position 42.", "type": "invalid_request_error", "param": null, "code": "json_parse_error" } }

常见原因

  • 缺少必填字段如modelmessages

  • JSON 格式不合法(多逗号、少引号等)

  • messages数组格式不对


429 — 请求限流

{ "error": { "message": "Rate limit reached for model 'gpt-4o' with TPM limit of 300000. Limit will reset at 1746124800.", "type": "rate_limit_exceeded_error", "param": null, "code": "tpm_limit_exceeded" } }

响应头会附带限流信息:

X-RateLimit-Limit: 5000000 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1746124800 Retry-After: 45

常见原因

  • TPM(每分钟 Token)超限

  • RPM(每分钟请求数)超限

  • 超出套餐配额

处理方式:等待Retry-After秒后重试


400 — 模型不支持某功能

{ "error": { "message": "Model 'gpt-3.5-turbo' does not support response_format parameter.", "type": "invalid_request_error", "param": "response_format", "code": null } }

400 — 上下文超长

{ "error": { "message": "This model's maximum context window is 128000 tokens. Your messages resulted in 150000 tokens.", "type": "invalid_request_error", "param": "messages", "code": "context_window_exceeded" } }

常见原因:对话历史太长,超出模型单次上下文窗口上限。

处理方式:需要截断或压缩messages历史


500 — OpenAI 服务器内部错误

{ "error": { "message": "The server had an error while processing your request. Please try again in 30 seconds.", "type": "server_error", "param": null, "code": null } }

常见原因:OpenAI 服务器自身故障,通常是临时性的。

处理方式:等待后重试,通常几次重试后会成功


403 — 组织或项目权限不足

{ "error": { "message": "Your organization does not have access to this model.", "type": "invalid_request_error", "param": "model", "code": "model_not_found" } }

常见原因

  • 使用的模型不在自己订阅套餐内

  • 项目级 API Key 没有该模型权限


9. 错误处理建议代码

import time import requests ​ def chat_with_retry(messages, model="gpt-4o"): url = "https://api.openai.com/v1/chat/completions" headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } payload = {"model": model, "messages": messages} ​ while True: try: resp = requests.post(url, headers=headers, json=payload, timeout=60) data = resp.json() ​ if resp.status_code == 200: return data ​ elif resp.status_code == 429: # 限流,等待后重试 retry_after = int(resp.headers.get("Retry-After", 5)) print(f"限流,等待 {retry_after} 秒...") time.sleep(retry_after) ​ elif resp.status_code == 500: # 服务器错误,短暂等待后重试 print("服务器错误,重试...") time.sleep(2) ​ elif resp.status_code == 401: raise Exception("API Key 无效:" + data["error"]["message"]) ​ elif resp.status_code == 400: # 上下文超长等错误,无法自动恢复 raise Exception(f"请求错误:{data['error']['message']}") ​ else: raise Exception(f"未知错误 {resp.status_code}: {data}") ​ except requests.exceptions.Timeout: print("请求超时,重试...") time.sleep(2)
http://www.jsqmd.com/news/736173/

相关文章:

  • 机械键盘连击终极解决方案:Keyboard Chatter Blocker完全指南
  • 借助gitee仓库构建私有图床
  • AI_08_coze_私有数据访问
  • 2026TOP级妈祖造像厂家名录:古建筑雕刻/大型石雕/妈祖造像/寺庙石雕/山门石亭/惠安石雕/石凉亭/石雕佛像/选择指南 - 优质品牌商家
  • Audiveris乐谱识别:从图像到数字乐谱的5步转换全攻略
  • 本地部署DeepSeek Coder:免费开源AI编程助手集成Cursor编辑器全攻略
  • ComfyUI-Impact-Pack V8终极指南:快速掌握AI图像增强与面部精细化技术
  • 32ms、百万行、万人并发:金山办公在表格里建了一座基础设施
  • 本地部署DeepSeek-Coder:打造私有化AI编程助手完整指南
  • AI工程化实践:基于MCP与工作流编排构建健康数据聚合服务
  • 2025届最火的六大降重复率工具实测分析
  • 抖音内容保存难题,如何优雅地构建个人数字收藏馆?
  • CarSim仿真效率翻倍秘籍:巧用Library和Category管理你的海量测试用例
  • 别再手动画封装了!用SnapEDA和Ultra Librarian快速搞定Altium Designer元件库
  • 游戏性能加速器:DLSS文件智能管理全攻略
  • PC终于翻身了:为什么OpenClaw的成功,其实跟AI无关
  • 5分钟彻底解锁QQ音乐加密格式:qmc-decoder终极指南
  • RDMA与异构计算在医学影像系统中的应用
  • STM32驱动开发避坑:三种微秒延时实现实测(SysTick/FreeRTOS/定时器)
  • 2026泰州网站优化哪家可靠?本地服务商实力盘点 - 优质品牌商家
  • 别再让网络抽风了!手把手教你排查和解决MAC地址漂移(附Wireshark抓包分析)
  • 如何免费修改植物大战僵尸:PvZ Toolkit完整使用教程
  • 从AMS1117到国产LDO:我的电源方案选型‘血泪史’与5个避坑要点
  • ROS 2里程计消息避坑指南:从TF广播到nav_msgs/Odometry的正确姿势
  • 终极指南:用OpenCore Legacy Patcher让旧款Mac完美运行最新macOS系统
  • 嵌入式多平台开发中的硬件抽象与跨平台构建实践
  • 别再让Telnet裸奔了!手把手教你用Wireshark抓包验证明文传输风险
  • OpenTentacle:为AI Agent打造透明可控的灵魂缰绳
  • 算法训练营第十九天| 1047. 删除字符串中的所有相邻重复项
  • Hive分区表数据清理实战:从‘清空2020年男生数据’案例讲起