跳至主要内容

OpenAI Responses API:终极开发者指南

学习如何使用 OpenAI 的 Responses API,通过函数调用、结构化输出和内置工具构建 AI 应用。本指南适合各个水平的开发者。
· 13分钟 阅读

使用 AI 探索

什么是 OpenAI 的 Responses API?

Responses API 是 OpenAI 最新且最先进的 API。它将 Chat Completions 与 Assistants 两个 API 的优势整合为一个精简接口。该 API 于 2025 年 3 月发布,在保留熟悉能力的同时,为构建 AI 应用提供了更一体化的方式。 

其关键创新在于,通过自动处理编排逻辑,并原生集成 OpenAI 的网页搜索与文件搜索等内置工具,而无需自定义实现,从而简化了开发流程。

在本教程中,我们将演示如何在您的项目中使用 Responses API。您将看到它如何进行文本生成、如何处理图像以及如何提供流式响应。我们还会介绍让开发更快速、更直观的内置工具,并展示这些工具如何在 API 框架内协同工作。 

阅读完本指南,您将了解在何种情况下应使用 Responses API 而非其他 OpenAI 选项,以及如何借助这些知识用更少的代码和精力构建更高效的应用。如果您是 OpenAI API 新手,请查看我们的入门课程《Working with the OpenAI API》,开启您的 AI 应用开发之旅。

快速上手 Responses API

Responses API 为与 OpenAI 模型交互提供了更精简、友好的接口,将此前冗长复杂的语法整合为优雅的解决方案。 

在深入具体用例之前,让我们先完成环境配置并了解基础语法。

from openai import OpenAI
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Initialize the client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

此初始化步骤会创建一个客户端对象来处理您的所有 API 请求。dotenv 包通过环境变量安全管理您的 API 密钥,而不是将其硬编码在脚本中——这是一种最佳实践,可让代码在不同环境中更易移植且更安全。

使用 Responses API 生成内容

Responses API 最直接的用法是生成文本内容。让我们看一个真实场景:假设您在构建一个电商平台,需要基于基本的产品信息自动生成有吸引力的商品描述。

传统上,这通常需要精心的提示工程和多次迭代。借助 Responses API,您可以优雅地用一个简单函数来完成:

def generate_product_description(product_name, features, target_audience):
   response = client.responses.create(
       model="gpt-4o",
       instructions="You are a professional copywriter specialized in creating concise, compelling product descriptions. Focus on benefits rather than just features.",
       input=f"""
       Create a product description for {product_name}.
       Key features:
       - {features[0]}
       - {features[1]}
       - {features[2]}
       Target audience: {target_audience}
       Keep it under 150 words.
       """,
       temperature=0.7,
       max_output_tokens=200
   )
  
   return response.output_text

# Example usage
headphones_desc = generate_product_description(
   "NoiseGuard Pro Headphones",
   ["Active noise cancellation", "40-hour battery life", "Memory foam ear cushions"],
   "Business travelers and remote workers"
)

print(headphones_desc)

输出:

Experience unparalleled focus and comfort with NoiseGuard Pro Headphones—your perfect travel and work companion. 
Designed for business travelers and remote workers, these headphones feature cutting-edge active noise cancellation to block out distractions, allowing you to concentrate on what truly matters. 
With an impressive 40-hour battery life, you can enjoy uninterrupted productivity or relaxation on even the longest journeys. 
The luxurious memory foam ear cushions ensure a snug, comfortable fit for all-day wear, reducing fatigue and enhancing your listening experience. 
Elevate your work and travel with NoiseGuard Pro—where clarity meets comfort.

只需几行代码,我们就生成了媲美专业文案的营销描述。此函数也可复用——仅需更改参数,您就能为目录中的任何产品生成描述。

该示例展示了使用 Responses API 的关键模式:

  1. instructions 参数充当系统提示,用于定义 AI 的行为和上下文。
  2. temperature(0-2)控制随机性——值越低输出越确定,值越高创造性越强。
  3. max_output_tokens 限制响应长度,有助于控制成本并确保简洁输出。
  4. 响应对象的生成文本位于 output_text 属性中。

面向实际应用的图像分析

许多真实世界的应用需要同时处理文本和图像。例如,电商平台需要分析产品图片,内容审核系统需要审查上传内容,社交应用需要理解视觉信息。

Responses API 在无需单独的端点或复杂集成代码的情况下,擅长处理图像分析等多模态任务:

def analyze_product_image(image_url):
   response = client.responses.create(
       model="gpt-4o",
       instructions="You are a product photography expert and e-commerce consultant.",
       input=[
           {"role": "user", "content": "Analyze this product image and provide the following details:\n1. Product category\n2. Key visible features\n3. Potential quality issues\n4. Suggested improvements for the product photography"},
           {
               "role": "user",
               "content": [
                   {
                       "type": "input_image",
                       "image_url": image_url
                   }
               ],
           },
       ],
       temperature=0.2
   )
  
   return response.output_text

# Example with a sports team image
analysis = analyze_product_image("https://upload.wikimedia.org/wikipedia/commons/a/a5/Barcelona_fc_lamina_elgrafico.jpg")
print(analysis)

输出:

1. **Product Category**: Sports team memorabilia or vintage sports photography.

2. **Key Visible Features**:
  - The image features a group of individuals in sports uniforms, likely a football (soccer) team.
  - The uniforms have distinct vertical stripes in red and blue.
  - A football is visible in the foreground.
  - The setting appears to be an outdoor field, possibly a stadium.

...

此函数可集成到电商平台,在商家上传产品图片时自动进行分析。系统可即时反馈图片质量并提出改进建议,从而通过更高质量的商品展示提升转化率——且无需人工审核。

处理图像时,您应向 input 参数传入消息对象数组而非字符串,每个对象包含 role 与 content。

 图像内容以带有 type: input_image 和 image_url 的对象进行指定。您可以在同一请求中组合文本与图像,启用丰富的多模态交互。

实现流式传输,打造响应迅速的应用

用户期望即时反馈。等待数秒钟的 AI 响应会严重影响参与度——因此流式传输对于构建响应迅速的用户体验至关重要,尤其是在聊天或实时应用中。

设想您在为产品团队构建客户反馈分析工具。与其让他们等待完整分析结果,不如将生成过程以流式方式实时呈现:

def analyze_customer_feedback(feedback_text):
   print("Analyzing customer feedback in real-time:")
  
   stream = client.responses.create(
       model="gpt-4o",
       instructions="Extract key sentiments, product issues, and actionable insights from this feedback.",
       input=feedback_text,
       stream=True,
       temperature=0.3,
       max_output_tokens=500
   )
  
   full_response = ""
   print("\nAnalysis results:")
   for event in stream:
       if event.type == "response.output_text.delta":
           print(event.delta, end="")
           full_response += event.delta
       elif event.type == "response.error":
           print(f"\nError occurred: {event.error}")
  
   return full_response

# Example with a complex customer review
feedback = """
I've been using the SmartHome Hub for about 3 months now. The voice recognition is fantastic
and the integration with my existing devices was mostly seamless. However, the app crashes
at least once a day, and the night mode feature often gets stuck until I restart the system.
Customer support was helpful but couldn't fully resolve the app stability issues.
"""

analysis_result = analyze_customer_feedback(feedback)

在真实应用中,您会将 print 语句替换为 UI 更新,让用户像在现代聊天应用中看到 AI “思考”一样,实时看到分析结果的生成。这种方式更具吸引力,并让用户即时感知其请求正在被处理。

流式实现方式如下:

  1. 在 create 方法中设置 stream=True
  2. 将响应作为特定类型事件的可迭代对象进行处理
  3. 分别处理不同事件类型:response.output_text.delta 表示文本分片,response.error 表示错误

介绍完 Responses API 的基础功能后,让我们继续探索其增强能力的内置工具。

OpenAI Responses API 的内置工具

Responses API 集成了若干内置工具,将其能力扩展到基础文本生成之外。借助这些工具,开发者无需复杂的集成代码或多次 API 调用即可打造更强大的应用。

网页搜索:获取实时信息

网页搜索工具让 Responses API 能从互联网检索最新信息,弥补了大语言模型受限于训练数据的不足。

from openai import OpenAI

client = OpenAI()

response = client.responses.create(
   model="gpt-4o",
   tools=[{"type": "web_search_preview"}],
   input="What are some news related to the stock market?",
)

print(response.output_text)

输出:

Recent developments in the stock market have been significantly influenced by escalating trade tensions between the United States and China. On April 5, 2025, President Donald Trump announced an additional 34% tariff on Chinese goods, raising total tariffs to 54% this year. In response, China imposed reciprocal 34% tariffs on U.S. products and introduced export restrictions on certain rare earth elements. These actions led to a sharp global market selloff, with the S&P 500 falling 9% for the week, marking the steepest decline since the pandemic. (reuters.com)

…..


## Escalating US-China Trade Tensions Impact Global Markets:
- [China says 'market has spoken' after US tariffs spark selloff](https://www.reuters.com/world/china/china-says-market-has-spoken-after-us-tariffs-spark-selloff-2025-04-05/?utm_source=openai)
- [Trump touts "economic revolution" as economists warn of recession](https://www.axios.com/2025/04/05/trump-tariffs-stock-market-recession?utm_source=openai)
- [Believe it or not, there were some winners in the stock market this week](https://apnews.com/article/ce81e9ae6fb463dc763dfaa464778343?utm_source=openai)

启用网页搜索工具后,系统会完成从查询分析到基于多个来源综合信息并附上规范引用的系列操作。此能力为信息密集型应用打开了可能,例如提供市场洞察的财经分析工具、整合多源信息的新闻聚合平台,或用最新研究补充核心内容的教育资源。

此工具的一大优势是无需自行构建与维护自定义搜索集成或网页抓取系统,即可提供及时信息。该工具会完成搜索流程,并附上规范引用,以便对信息来源保持透明。

文件搜索:从文档中提取信息

网页搜索可将外部知识引入您的应用,而文件搜索工具则专注于解锁文档中的信息。该工具允许 API 搜索并提取已上传至 OpenAI 的文档内容。

文件搜索工具提供以下关键能力:

  • 跨多种文件类型进行搜索(PDF、Word 文档、演示文稿等)。
  • 根据自然语言查询在文档中查找特定信息。
  • 同时从多份文档中提取与综合信息。
  • 提供源文档中特定章节的引用。
  • 支持跨多文件的信息关联类复杂查询。

此能力非常适合文档分析类用例,例如从法律合同中提取信息、分析科研论文,或从技术文档构建知识库。该工具可在多份文档中定位相关部分,并据具体查询综合信息。

实现流程要求先将文件上传至 OpenAI 的 files 端点,然后在查询时将文件 ID 传给 Responses API。这样即可为需要引用文档具体信息的应用构建精简的工作流,无需用户手动检索。

计算机使用:界面交互能力

在文本与文档理解的基础上,计算机使用工具将 AI 能力扩展到界面交互领域。这项工具代表着重要进步,弥合了语言理解与用户界面操作之间的鸿沟。

计算机使用工具可以执行多种界面交互:

  • 自主导航网站与网页应用。
  • 用合适信息填写表单。
  • 从网页与应用中提取数据。
  • 跨不同界面执行多步流程。
  • 与按钮、下拉框、文本框等元素交互。
  • 理解不同界面元素的语境与用途。

潜在应用包括重复流程的自动化、复杂工作流的引导式辅助,以及为不便使用传统界面的用户提升可访问性。该工具可用于自动填写表单、导航复杂网站,或进行用户界面测试。

其原理是让 AI 能“看到”并与屏幕元素交互,理解上下文,并根据自然语言指令执行动作。这样即可实现原本需要针对特定界面编写专用代码的自动化与辅助能力。

更多工具能力

Responses API 的工具生态仍在不断发展,OpenAI 定期添加新能力。完整的工具文档涵盖当前所有可用工具的实现细节,而关于构建 Agent 的新工具一文则提供这些工具演进的策略背景。

这些内置工具即开即用、功能强大,但许多应用需要连接到专门服务或专有系统。这时就需要函数调用,借此您可以用自定义工具与外部服务扩展 Responses API——这也是下一节的重点。

Responses API 中的函数调用

尽管内置工具功能强大,但许多应用需要连接专门服务或专有系统。函数调用允许您用自定义工具扩展 Responses API,模型会根据用户输入决定何时以及如何调用您的函数。

函数调用在 AI 的语言理解与您的外部系统之间搭建了一座桥梁——无论是检索汇率、计算距离,还是查询预约可用性。此模式遵循一套清晰的流程:

  1. 您定义 AI 可用的函数,并指定参数及其类型。
  2. AI 根据用户查询决定何时调用这些函数。
  3. 您的代码使用 AI 提供的参数执行函数。
  4. 您将结果返回给 AI,由其将结果纳入最终回复。

创建货币转换工具

我们以一个简单的货币转换函数为例:

# Dictionary of exchange rates (relative to USD)
exchange_rates = {
   "USD": 1.0,
   "EUR": 0.93,
   "GBP": 0.79,
   "JPY": 153.2,
   "CAD": 1.37,
   "AUD": 1.52
}

def convert_currency(amount, from_currency, to_currency):
   """Convert an amount from one currency to another."""
   # Normalize currency codes to uppercase
   from_currency = from_currency.upper()
   to_currency = to_currency.upper()
  
   # Check if currencies are supported
   if from_currency not in exchange_rates:
       return {"error": f"Currency not supported: {from_currency}"}
   if to_currency not in exchange_rates:
       return {"error": f"Currency not supported: {to_currency}"}
  
   # Convert to USD first, then to target currency
   amount_in_usd = amount / exchange_rates[from_currency]
   converted_amount = amount_in_usd * exchange_rates[to_currency]
  
   return {
       "original_amount": amount,
       "from_currency": from_currency,
       "to_currency": to_currency,
       "converted_amount": round(converted_amount, 2)
   }

此函数接收三个参数:待转换金额、源货币和目标货币。它使用预设汇率完成简单转换,并以结构化结果返回转换详情。

为 Responses API 定义函数

接下来,我们需要将函数告知模型,以便其决定何时调用:

from openai import OpenAI
import json

client = OpenAI()

tools = [
   {
       "type": "function",
       "name": "convert_currency",
       "description": "Convert an amount from one currency to another using current exchange rates",
       "parameters": {
           "type": "object",
           "properties": {
               "amount": {
                   "type": "number",
                   "description": "The amount of money to convert"
               },
               "from_currency": {
                   "type": "string",
                   "description": "The currency code to convert from (e.g., USD, EUR, GBP)"
               },
               "to_currency": {
                   "type": "string",
                   "description": "The currency code to convert to (e.g., USD, EUR, GBP)"
               }
           },
           "required": ["amount", "from_currency", "to_currency"],
           "additionalProperties": False
       },
       "strict": True
   }
]

此定义清晰说明了:

  • 函数名 convert_currency 与我们的 Python 函数一致。
  • 何时使用该函数的描述。
  • 三个必填参数及其类型与描述。
  • strict: true 标志可确保模型严格遵循参数规格。

处理用户查询

让我们模拟一段用户询问货币转换的对话:

input_messages = [
   {"role": "user", "content": "How much is 100 euros in Japanese yen?"}
]

response = client.responses.create(
   model="gpt-4o",
   input=input_messages,
   tools=tools,
)

当模型看到有关货币转换的问题时,它会识别需要使用我们的函数。模型会自动识别:

  • 金额是 100
  • 源货币为欧元(EUR)
  • 目标货币为日元(JPY)

处理函数调用

现在我们提取函数调用细节并执行函数:

tool_call = response.output[0]
print(f"Function called: {tool_call.name}")
print(f"Arguments: {tool_call.arguments}")

args = json.loads(tool_call.arguments)

# Execute the function with the parameters determined by the model
conversion_result = convert_currency(**args)
print(f"Function results: {conversion_result}")

模型已将自然语言查询转化为结构化参数。我们的函数据此进行计算并返回转换结果。

将函数结果返回给模型

最后,我们将结果发回模型,让其生成更友好的用户响应:

input_messages.append(tool_call)  # append model's function call message
input_messages.append(
   {  # append result message
       "type": "function_call_output",
       "call_id": tool_call.call_id,
       "output": json.dumps(conversion_result)
   }
)

response_2 = client.responses.create(
   model="gpt-4o",
   input=input_messages,
   tools=tools,
)
print(response_2.output_text)

输出:

100 euros is equal to 16,473.12 Japanese yen based on current exchange rates.

模型已将原始转换数据转化为自然、易读的表述,并以货币格式恰当地呈现数值结果。

整合为完整流程

在真实应用中,您会希望将上述流程封装为一个统一接口,以无缝管理对话流。下面展示如何创建一个完整助手来管理整个函数调用过程:

def currency_assistant(user_message, conversation_history=None):
   """A complete assistant that handles currency conversion queries."""
   if conversation_history is None:
       conversation_history = []
  
   # Add the user's new message to the conversation
   conversation_history.append({"role": "user", "content": user_message})
  
   # Define available tools (our currency conversion function)
   tools = [{
       "type": "function",
       "name": "convert_currency",
       "description": "Convert an amount from one currency to another using current exchange rates",
       "parameters": {
           "type": "object",
           "properties": {
               "amount": {
                   "type": "number",
                   "description": "The amount of money to convert"
               },
               "from_currency": {
                   "type": "string",
                   "description": "The currency code to convert from (e.g., USD, EUR, GBP)"
               },
               "to_currency": {
                   "type": "string",
                   "description": "The currency code to convert to (e.g., USD, EUR, GBP)"
               }
           },
           "required": ["amount", "from_currency", "to_currency"],
           "additionalProperties": False
       },
       "strict": True
   }]
  
   # Get initial response from the model
   response = client.responses.create(
       model="gpt-4o",
       input=conversation_history,
       tools=tools,
   )
  
   # Check if the model wants to call a function
   if response.output and isinstance(response.output, list) and response.output[0].type == "function_call":
       tool_call = response.output[0]
      
       # Process the function call
       args = json.loads(tool_call.arguments)
       result = convert_currency(**args)
      
       # Add the function call and its result to the conversation
       conversation_history.append(tool_call)
       conversation_history.append({
           "type": "function_call_output",
           "call_id": tool_call.call_id,
           "output": json.dumps(result)
       })
      
       # Get the final response with the function results incorporated
       final_response = client.responses.create(
           model="gpt-4o",
           input=conversation_history,
           tools=tools,
       )
      
       return final_response.output_text, conversation_history
   else:
       # If no function call was needed, return the direct response
       return response.output_text, conversation_history

# Example usage
response, conversation = currency_assistant("How much is 50 British pounds in Australian dollars?")
print("Assistant:", response)

# Continue the conversation
response, conversation = currency_assistant("And what if I wanted to convert 200 Canadian dollars instead?", conversation)
print("Assistant:", response)

此实现:

  1. 维护对话历史,为后续追问提供上下文。
  2. 在单一接口中处理整个函数调用过程。
  3. 判断何时需要函数调用,何时模型可直接回复。
  4. 支持多轮对话,保留先前语境。

采用此方法,您可以打造无缝的对话体验:用户以自然语言交互,而背后的复杂函数调用在“幕后”自动完成。助手在自然语言理解、结构化函数调用与自然语言生成之间顺畅切换。

构建更复杂的应用可能涉及:

  1. 支持多种函数,分别处理不同类型的查询。
  2. 为敏感操作管理认证与授权。
  3. 实现更完善的错误处理与恢复机制。
  4. 为函数使用与性能添加日志与监控。
  5. 创建支持文本、语音或多模态交互的用户界面。

函数调用让 Responses API 能将自然语言输入与您的服务和数据连接起来。它在用户请求与业务系统之间搭建桥梁,使用户能用自然语言提出需求,而您的应用在后台处理技术实现细节。

除函数调用外,Responses API 的另一项强大能力是生成结构化输出。此功能与函数调用相辅相成,可让您按应用需求接收特定格式的响应。

使用 Responses API 的结构化输出

在构建 AI 应用时,您常常需要特定格式的响应,以便更轻松地与系统集成。Responses API 支持结构化输出,让您以定义良好、格式一致的数据(而非自由文本)接收结果。这在以下场景尤为有用:

  1. 从非结构化文本中提取特定信息。
  2. 将用户输入转化为结构化数据。
  3. 确保下游处理所需的一致响应格式。
  4. 将 AI 输出直接集成到数据库或 API 中。

结构化输出减少了额外的解析与校验需求,使应用更健壮、更易维护。

从描述中提取产品信息

让我们看一个实用示例:设想您在构建电商平台,需要从非结构化的产品描述中自动提取产品详情以填充数据库。

from openai import OpenAI
import json

client = OpenAI()

product_description = """
Our Premium Laptop Backpack is perfect for professionals and students alike.
Made with water-resistant material, it features padded compartments that fit
laptops up to 15.6 inches. The backpack includes 3 main storage areas,
5 smaller pockets, and has an integrated USB charging port. Available in
navy blue, black, and gray. Current retail price: $79.99, though it's
currently on sale for $64.99 until the end of the month.
"""

response = client.responses.create(
   model="gpt-4o",
   input=f"Extract structured product information from this description: {product_description}",
   text={
       "format": {
           "type": "json_schema",
           "name": "product_details",
           "schema": {
               "type": "object",
               "properties": {
                   "product_name": {"type": "string"},
                   "category": {"type": "string"},
                   "features": {"type": "array", "items": {"type": "string"}},
                   "colors": {"type": "array", "items": {"type": "string"}},
                   "pricing": {
                       "type": "object",
                       "properties": {
                           "regular_price": {"type": "number"},
                           "sale_price": {"type": "number"},
                           "currency": {"type": "string"},
                       },
                       "additionalProperties": False,
                       "required": ["regular_price", "sale_price", "currency"],
                   },
               },
               "required": ["product_name", "features", "colors", "pricing","category"],
               "additionalProperties": False,
           },
           "strict": True,
       }
   },
)

product_data = json.loads(response.output_text)
print(json.dumps(product_data, indent=2))

输出:

{
 "product_name": "Premium Laptop Backpack",
 "category": "Backpack",
 "features": [
   "Water-resistant material",
   "Padded compartments for laptops up to 15.6 inches",
   "3 main storage areas",
   "5 smaller pockets",
   "Integrated USB charging port"
 ],
 "colors": [
   "Navy blue",
   "Black",
   "Gray"
 ],
 "pricing": {
   "regular_price": 79.99,
   "sale_price": 64.99,
   "currency": "USD"
 }
}

这种格式化的 JSON 数据可直接集成到您的产品数据库,免去自定义解析逻辑,降低出错概率。

理解结构化输出配置

实现高效且无差错的结构化输出的关键在于正确地定义模式(schema)。下面拆解配置中的重要要素:

text={
   "format": {
       "type": "json_schema",        # Specifies we're using JSON Schema
       "name": "product_details",    # A descriptive name for this schema
       "schema": {
           # Your JSON Schema definition here
           "type": "object",
           "properties": {
               # Each property with type information, e.g.
               "product_name": {"type": "string"},
               # ... other properties
           },
           "required": ["product_name", ...], # All other properties
           "additionalProperties": False
       },
       "strict": True                # Enforce schema constraints strictly
   }
}

最重要的组成部分包括:

  1. 模式定义:描述结构,包括所有属性及其类型。
  2. 必填字段:列出响应中必须包含的属性。
  3. 额外属性:当设置为 False 时,禁止出现未在模式中定义的字段。
  4. 严格模式:当 True 时,确保模型严格遵循模式。

使用结构化输出的实用建议

要获得最佳效果,请遵循以下准则:

  1. 谨慎设计模式:包含所有必需字段,同时聚焦关键信息。
  2. 使用合适的数据类型:根据数据用途匹配类型(用于计算的数字、用于文本的字符串)。
  3. 设置清晰约束:对有限选项使用 enum,并为数值边界设置 minimum/maximum。
  4. 用多样输入测试:确保模式能处理不同输入格式与边界情况。
  5. 提供清晰描述:为字段添加描述有助于模型正确理解需要提取的信息。

与 Chat Completions API 的比较

Responses API 通过 JSON Schema 提供结构化输出,而 Chat Completions API 提供了使用 Pydantic 模型的替代方法,且更为简单:

from pydantic import BaseModel, Field
from typing import List, Optional
from openai import OpenAI

client = OpenAI()

class ProductDetails(BaseModel):
   product_name: str
   category: str = Field(default=None)
   features: List[str]
   specifications: Optional[dict] = None
   colors: List[str]
   pricing: dict

# With Chat Completions API
completion = client.beta.chat.completions.parse(
   model="gpt-4o",
   messages=[
       {"role": "system", "content": "Extract structured product information."},
       {"role": "user", "content": product_description}
   ],
   response_format=ProductDetails
)

pydantic_product = completion.choices[0].message.parsed

两种方法各有优势:

  • Responses API 在 API 调用中直接使用标准 JSON Schema
  • Chat Completions API 通过 Pydantic 与 Python 类型系统集成

如果让我选择,我会使用 Chat Completions API,以避免手写原始 JSON 模式。当然,除非 OpenAI 为 Responses API 增加对 Pydantic 模型的支持。

更多信息请参阅 Responses API 的结构化输出文档。

结语

OpenAI Responses API 将既有 API 的优势整合为统一接口,简化了开发者与语言模型的交互,减少了代码量与复杂度。其支持文本生成、图像分析、函数调用与结构化输出,使 AI 能力更易获取,同时让开发者聚焦于解决业务问题而非集成难题。

在继续深入使用 Responses API 的过程中,您或许还会发现以下资源有助于加深理解并拓展实现能力:

OpenAI Responses API 常见问题

Responses API 是什么?与其他 OpenAI API 有何不同?

Responses API 是 OpenAI 的统一接口,融合了 Chat Completions 与 Assistants API 的特性。它通过处理编排逻辑,并集成网页搜索与文件搜索等内置工具而无需自定义实现,从而简化开发。

如何在 Responses API 中实现函数调用?

通过定义带有参数与类型的函数,让模型决定何时调用;使用模型提供的参数执行函数;再将结果返回给模型,由其纳入最终回复,即可实现函数调用。

什么是结构化输出?为何有用?

结构化输出让您以定义明确的格式(如 JSON)而非自由文本接收数据。它适用于提取特定信息、确保一致的响应格式,以及将 AI 输出直接集成至数据库或 API。

Responses API 提供哪些内置工具?

Responses API 包含网页搜索(获取实时信息)、文件搜索(从文档中提取信息)及计算机使用(界面交互能力)等内置工具,免去了复杂集成的需求。

我能用不同编程语言调用 Responses API 吗?

可以。Responses API 可通过 OpenAI 的官方 SDK(Python、Node.js 等)访问。其 RESTful 设计也支持任何能发起 HTTP 请求的语言进行集成。

主题