📌 写在前面
2025 年,OpenAI 推出了新一代 Responses API ,官方明确表示这是未来 Agent 应用的核心方向。但与此同时,经典的 Chat Completions API 依然是业界使用最广泛的标准。
很多开发者困惑:两者到底有什么区别?我该用哪个?代码怎么写?
本文将用最直白的语言 + 可运行的 Python 代码,带你彻底搞懂这两代 API 的核心差异。
一、核心概念速览
| 对比维度 | Chat Completions API | Responses API |
|---|---|---|
| 设计定位 | 无状态文本生成,业界事实标准 | 面向 Agent 工作流,支持多步推理 |
| 状态管理 | ❌ 完全手动维护对话历史 | ✅ 支持服务端状态保持 |
| 内置工具 | ❌ 仅支持自定义函数调用 | ✅ 原生支持 web_search、file_search、code_interpreter |
| 响应结构 | 单一文本消息 | 结构化 output 数组,包含多类型产出 |
| 推理模型优化 | 推理状态在请求间丢失 | 通过 previous_response_id 保持 KV Cache |
| API 端点 | POST /v1/chat/completions |
POST /v1/responses |
二、环境准备
bash
pip install openai>=1.0.0
python
import openai
import json
client = openai.OpenAI(api_key="YOUR_API_KEY")
三、Chat Completions API 详解
3.1 基础问答
python
def simple_chat():
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个精通Python的编程助手"},
{"role": "user", "content": "用一句话解释什么是装饰器"}
]
)
reply = response.choices[0].message.content
print(reply)
return reply
3.2 多轮对话(手动维护历史)
python
def multi_turn_chat():
messages = [
{"role": "system", "content": "你是一个友好的AI助手"}
]
user_inputs = ["我喜欢科幻电影", "推荐一部给我", "有中文配音吗?"]
for user_msg in user_inputs:
messages.append({"role": "user", "content": user_msg})
response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
assistant_reply = response.choices[0].message.content
print(f"用户: {user_msg}")
print(f"助手: {assistant_reply}\n")
# ⚠️ 关键:必须手动将回复追加到历史
messages.append({"role": "assistant", "content": assistant_reply})
return messages
3.3 函数调用(手动处理工具循环)
python
def chat_with_function_call():
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "获取指定城市的当前天气",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"]
}
}
}
]
messages = [{"role": "user", "content": "北京今天天气怎么样?"}]
# 第一次调用:模型决定是否调用工具
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"
)
response_message = response.choices[0].message
if response_message.tool_calls:
tool_call = response_message.tool_calls[0]
arguments = json.loads(tool_call.function.arguments)
print(f"🔧 模型调用: {tool_call.function.name}({arguments})")
# 模拟执行工具
weather_result = f"{arguments['city']}当前温度25°C,晴朗"
# ⚠️ 手动维护工具调用的上下文
messages.append(response_message)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": weather_result
})
# 第二次调用:模型基于工具结果生成最终回复
final_response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print(f"✅ 最终回复: {final_response.choices[0].message.content}")
else:
print(response_message.content)
四、Responses API 详解
4.1 基础问答
python
def simple_response():
response = client.responses.create(
model="gpt-4o",
input="用一句话解释什么是装饰器"
)
# 注意:响应结构是 output 数组
for item in response.output:
if item.type == "message":
print(item.content[0].text)
return response
4.2 多轮对话(服务端保持状态)
python
def multi_turn_response():
# 第一轮
response1 = client.responses.create(
model="gpt-4o",
input="我喜欢科幻电影",
)
print(f"第一轮: {response1.output[0].content[0].text}")
# 第二轮:通过 previous_response_id 自动延续上下文
# ✅ 无需手动传递完整历史!
response2 = client.responses.create(
model="gpt-4o",
previous_response_id=response1.id,
input="推荐一部给我"
)
print(f"第二轮: {response2.output[0].content[0].text}")
# 第三轮继续引用
response3 = client.responses.create(
model="gpt-4o",
previous_response_id=response2.id,
input="有中文配音吗?"
)
print(f"第三轮: {response3.output[0].content[0].text}")
return response3
4.3 内置工具(平台自动执行)
python
def response_with_builtin_tools():
"""
Responses API 原生支持联网搜索,
平台自动执行,开发者无需手动处理工具循环
"""
response = client.responses.create(
model="gpt-4o",
input="北京今天天气怎么样?",
tools=[
{"type": "web_search"} # 直接声明即可
]
)
# 输出可能包含多个产出项
for item in response.output:
if item.type == "message":
print(f"💬 消息: {item.content[0].text}")
elif item.type == "web_search_call":
print(f"🔍 执行了联网搜索: {item.status}")
print(f"\n✅ 最终答案: {response.output[-1].content[0].text}")
return response
4.4 使用 Conversation 管理会话
python
def conversation_with_state():
# 创建会话
conversation = client.responses.conversations.create(
model="gpt-4o"
)
# 在会话中发送消息
response1 = client.responses.create(
model="gpt-4o",
input="我最近在学习机器学习",
conversation_id=conversation.id
)
response2 = client.responses.create(
model="gpt-4o",
input="给我推荐三个入门项目",
conversation_id=conversation.id
)
# 获取整个会话历史
history = client.responses.conversations.list(
conversation_id=conversation.id
)
print(f"📚 会话历史条目数: {len(history)}")
return history
五、流式输出对比
python
# ===== Chat Completions 流式 =====
def stream_chat():
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "讲个笑话"}],
stream=True
)
print("Chat Completions 流式输出:", end=" ")
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
print()
# ===== Responses API 流式 =====
def stream_response():
stream = client.responses.create(
model="gpt-4o",
input="讲个笑话",
stream=True
)
print("Responses API 流式输出:", end=" ")
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="")
print()
六、代码层面的核心差异总结
| 对比点 | Chat Completions | Responses API |
|---|---|---|
| 输入格式 | messages 数组 |
input 字符串或数组 |
| 响应解析 | choices[0].message.content |
output 数组,按类型遍历 |
| 状态管理 | 手动维护 messages 列表 |
previous_response_id / conversation_id |
| 工具调用 | 自行处理 tool_calls 循环 |
声明 tools 后平台自动执行 |
| 流式处理 | chunk.choices[0].delta.content |
event.type == "response.output_text.delta" |
| 历史轮次维护 | 开发者全权负责 | 平台部分托管 |
七、实战建议:我该选哪个?
✅ 继续使用 Chat Completions 的场景
- 主要需求是纯文本对话、摘要、分类
- 工具调用逻辑简单
- 应用依赖于跨提供商可移植性(如 LangChain、Dify 等框架)
- 需要完全掌控上下文的细节
✅ 迁移到 Responses API 的场景
- 构建需要联网搜索、RAG、代码解释的 AI Agent
- 使用 o3、o4-mini 等推理模型,需要状态保持优化效率
- 希望简化代码,将复杂工具调用交给平台
- 新项目从零开始,无历史包袱
⚠️ 注意
OpenAI 已于 2026 年上半年弃用 Assitants API,Responses API 是其官方替代方案,融合了 Chat Completions 的简洁和 Assistants 的强大功能。
八、常见问题 FAQ
Q1:Chat Completions 会被彻底取代吗?
官方表示 Chat Completions API 会 "无限期地继续支持",但新功能会优先在 Responses API 上迭代。
Q2:Responses API 更贵吗?
接口价格与模型本身挂钩(如 gpt-4o 价格一致),但 Responses 的状态保持功能可以减少重复 Token 消耗,实际可能更省。
Q3:我可以混用两个 API 吗?
可以。但注意两者的状态管理机制不同,不要试图将一个 API 的响应直接塞给另一个。
Q4:LangChain 支持 Responses API 吗?
目前 LangChain 仍以 Chat Completions 为主,如需使用 Responses API,建议直接调用原生 SDK。
九、参考资料
📝 结语
从 Chat Completions 到 Responses API,OpenAI 正在将 AI 接口从 "文本生成工具" 升级为 "Agent 开发平台"。
- Chat Completions 是经典、稳定、可控的"手动挡"
- Responses API 是智能、高效、自动化的"自动挡"
两者没有绝对的优劣,选择取决于你的项目需求。如果你正在构建新一代 AI 应用,Responses API 值得花时间学习;如果追求稳定和兼容性,Chat Completions 依然是可靠的选择。