OpenAI API 深度研究功能入门指南

本教程面向有编程基础的开发者,深入讲解 OpenAI Deep Research API 的工程实践。内容涵盖环境搭建、核心调用方法、响应解析、MCP 工具集成,以及如何通过提示重写和澄清问题优化研究质量。通过医疗经济影响分析和旅行规划两个案例,展示从简单调用到复杂工作流的完整流程,并补充了常见错误排查与生产环境优化建议,帮助开发者构建可靠的研究代理。

技术背景

传统 LLM 只能基于训练数据回答,无法获取实时信息或进行多步骤推理。Deep Research API 通过代理模型自动规划子问题、执行网络搜索和代码执行,生成带引用的结构化报告,解决了复杂现实世界研究任务自动化的问题。适用于产品比较、市场分析、竞争情报、文献综述等场景。主要限制包括:任务耗时较长(分钟级)、token 消耗高、依赖外部搜索质量,且 API 不提供 ChatGPT 中的澄清交互,需要开发者自行设计提示工程。

核心原理

Deep Research API 基于代理式推理架构。用户提交高层级查询后,模型自动分解为多个子问题,通过工具(web_search_preview、code_interpreter、MCP)逐步收集信息,并综合生成最终报告。响应对象包含最终文本、内联引用(annotations)、推理步骤摘要、搜索调用和代码执行记录。关键设计决策包括:使用 reasoning.summary 控制摘要粒度(auto/detailed),background 参数支持异步执行,MCP 工具扩展私有数据源。

架构分析

系统由客户端、Responses API、代理模型(o3-deep-research 或 o4-mini-deep-research)、工具层(搜索、代码解释器、MCP)和响应解析器组成。数据流:用户输入 → 模型规划 → 工具调用 → 结果综合 → 结构化输出。开发者可通过解析 response.output 中的不同 type 字段(reasoning、web_search_call、code_interpreter_call、mcp_call)追踪中间过程。架构设计强调异步执行(background=True)和模块化工具集成,便于构建可观测、可扩展的研究工作流。

完整实战教程

背景

深度研究 API 使您能够自动化复杂的研究工作流程,这些流程需要对现实世界信息进行推理、规划和综合。它旨在接收高层级查询,并通过利用能够分解任务、执行网络搜索和综合结果的代理模型,返回结构化且引用丰富的报告。

与 ChatGPT 中该过程被抽象化不同,API 提供了直接的编程访问。当您发送请求时,模型会自动规划子问题,使用网络搜索和代码执行等工具,并生成最终的结构化响应。本手册将简要介绍深度研究 API 及其使用方法。

您可以通过 responses 端点使用以下模型访问深度研究:

环境设置

安装依赖

安装最新版本的 OpenAI Python SDK。

!pip install --upgrade openai

认证

导入 OpenAI 客户端并使用你的 API 密钥进行初始化。

from openai import OpenAI
OPENAI_API_KEY="" # YOUR OPENAI_API_KEY
#OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
client = OpenAI(api_key=OPENAI_API_KEY)

开始使用

让我们通过一个 Deep Research API 调用的示例来了解其用法。假设我们在一家医疗金融服务公司工作,任务是编写一份关于近期用于治疗2型糖尿病和肥胖症的药物(尤其是司美格鲁肽)的经济影响的深度报告。我们的目标是将临床结果、成本效益和区域定价数据综合成一份结构化的、有引用支持的分析报告,该报告可为投资、支付方策略或政策建议提供信息。

首先,让我们:

system_message = """
You are a professional researcher preparing a structured, data-driven report on behalf of a global health economics team. Your task is to analyze the health question the user poses.

Do:
- Focus on data-rich insights: include specific figures, trends, statistics, and measurable outcomes (e.g., reduction in hospitalization costs, market size, pricing trends, payer adoption).
- When appropriate, summarize data in a way that could be turned into charts or tables, and call this out in the response (e.g., “this would work well as a bar chart comparing per-patient costs across regions”).
- Prioritize reliable, up-to-date sources: peer-reviewed research, health organizations (e.g., WHO, CDC), regulatory agencies, or pharmaceutical earnings reports.
- Include inline citations and return all source metadata.

Be analytical, avoid generalities, and ensure that each section supports data-backed reasoning that could inform healthcare policy or financial modeling.
"""

user_query = "Research the economic impact of semaglutide on global healthcare systems."

response = client.responses.create(
  model="o3-deep-research",
  input=[
    {
      "role": "developer",
      "content": [
        {
          "type": "input_text",
          "text": system_message,
        }
      ]
    },
    {
      "role": "user",
      "content": [
        {
          "type": "input_text",
          "text": user_query,
        }
      ]
    }
  ],
  reasoning={
    "summary": "auto"
  },
  tools=[
    {
      "type": "web_search_preview"
    },
    {
      "type": "code_interpreter",
      "container": {
        "type": "auto",
        "file_ids": []
      }
    }
  ]
)

解析响应

Deep Research API 的响应包含结构化的最终答案以及内联引用、推理步骤摘要和源元数据。

提取最终报告输出

以下是本报告的主要文本输出。

# Access the final report from the response object
print(response.output[-1].content[0].text)

访问行内引用和元数据

响应文本中的行内引用被标注并链接到其对应的源元数据。每个标注包含:

这种结构将允许你构建引用列表或参考文献,在下游应用中添加可点击的超链接,并在报告中高亮和追踪有数据支持的主张。

annotations = response.output[-1].content[0].annotations
for i, citation in enumerate(annotations):
    print(f"Citation {i+1}:")
    print(f"  Title: {citation.title}")
    print(f"  URL: {citation.url}")
    print(f"  Location: chars {citation.start_index}–{citation.end_index}")

检查中间步骤

Deep Research API 还会公开智能体执行的所有中间步骤,包括推理步骤、网络搜索调用和代码执行。你可以利用这些步骤来调试、分析或可视化最终答案的构建过程。

每个中间步骤都存储在 response.output 中,type 字段指示其类型。

推理步骤

这些步骤表示模型在推理子问题时生成的内部摘要或计划。

# Find the first reasoning step
reasoning = next(item for item in response.output if item.type == "reasoning")
for s in reasoning.summary:
    print(s.text)

网络搜索调用

这些内容显示了执行了哪些搜索查询,可以帮助你追踪模型检索了哪些信息。

# Find the first web search step
search = next(item for item in response.output if item.type == "web_search_call")
print("Query:", search.action["query"])
print("Status:", search.status)

代码执行

如果模型使用了代码解释器(例如用于解析数据或生成图表),这些步骤将显示为“code_interpreter_call”类型或类似类型。

# Find a code execution step (if any)
code_step = next((item for item in response.output if item.type == "code_interpreter_call"), None)
if code_step:
    print(code_step.input)
    print(code_step.output)
else:
    print("No code execution steps found.")

模型上下文协议(MCP)

假设您希望在深度研究任务中引入自己的内部文档。深度研究模型和 Responses API 都支持基于 MCP 的工具,因此您可以扩展它们来查询您的私有知识库或其他第三方服务。

在下面的示例中,我们配置了一个 MCP 工具,让深度研究能够按需获取您组织的内部司美格鲁肽研究。该 MCP 服务器是 OpenAI 文件存储服务的代理,它会自动对您上传的文件进行向量化,以实现高性能检索。

如果您想了解我们是如何构建这个简单的 MCP 服务器的,请参阅相关食谱。

# system_message includes reference to internal file lookups for MCP.
system_message = """
You are a professional researcher preparing a structured, data-driven report on behalf of a global health economics team. Your task is to analyze the health question the user poses.

Do:
- Focus on data-rich insights: include specific figures, trends, statistics, and measurable outcomes (e.g., reduction in hospitalization costs, market size, pricing trends, payer adoption).
- When appropriate, summarize data in a way that could be turned into charts or tables, and call this out in the response (e.g., “this would work well as a bar chart comparing per-patient costs across regions”).
- Prioritize reliable, up-to-date sources: peer-reviewed research, health organizations (e.g., WHO, CDC), regulatory agencies, or pharmaceutical earnings reports.
- Include an internal file lookup tool to retrieve information from our own internal data sources. If you’ve already retrieved a file, do not call fetch again for that same file. Prioritize inclusion of that data.
- Include inline citations and return all source metadata.

Be analytical, avoid generalities, and ensure that each section supports data-backed reasoning that could inform healthcare policy or financial modeling.
"""

user_query = "Research the economic impact of semaglutide on global healthcare systems."

response = client.responses.create(
  model="o3-deep-research-2025-06-26",
  input=[
    {
      "role": "developer",
      "content": [
        {
          "type": "input_text",
          "text": system_message,
        }
      ]
    },
    {
      "role": "user",
      "content": [
        {
          "type": "input_text",
          "text": user_query,
        }
      ]
    }
  ],
  reasoning={
    "summary": "auto"
  },
  tools=[
    {
      "type": "web_search_preview"
    },
    { # ADD MCP TOOL SUPPORT
      "type": "mcp",
      "server_label": "internal_file_lookup",
      "server_url": "https://<your_mcp_server>/sse/", # Update to the location of *your* MCP server
      "require_approval": "never"
    }
  ]
)

审查你的回复

你的研究报告的前100个字符,后跟引用和MCP工具调用。

# Grab the full report text once
report_text = response.output[-1].content[0].text

print("REPORT EXCERPT:")
print(report_text[:100])   # first 100 chars
print("--------")

annotations = response.output[-1].content[0].annotations
target_url = "https://platform.openai.com/storage/files"

for citation in annotations:
    if citation.url.startswith(target_url):
        start, end = citation.start_index, citation.end_index

        # extract exactly the cited span
        excerpt       = report_text[start:end]

        # extract up to 100 chars immediately before the citation
        pre_start     = max(0, start - 100)
        preceding_txt = report_text[pre_start:start]

        print("MCP CITATION SAMPLE:")
        print(f"  Title:       {citation.title}")
        print(f"  URL:         {citation.url}")
        print(f"  Location:    chars {start}–{end}")
        print(f"  Preceding:   {preceding_txt!r}")
        print(f"  Excerpt:     {excerpt!r}")
        break

print("--------")


# EXAMPLE MCP CITATION

# REPORT EXCERPT:
# # Introduction
# Semaglutide – a glucagon-like peptide-1 (GLP-1) analogue – has rapidly become a blo
# --------
# MCP CITATION SAMPLE:
#   Title:       Document file-WqbCdYNqNzGuFfCAeWyZfp
#   URL:         https://platform.openai.com/storage/files/file-WqbCdYNqNzGuFfCAeWyZfp
#   Location:    chars 237–331
#   Preceding:   'and obesity due to its potent clinical efficacy (often inducing ~10–15% body weight loss in trials) '
#   Excerpt:     '([platform.openai.com](https://platform.openai.com/storage/files/file-WqbCdYNqNzGuFfCAeWyZfp))'


# print the MCP tool calls
calls = [
    (item.name, item.server_label, item.arguments)
    for item in response.output
    if item.type == "mcp_call" and item.arguments
]
for name, server, args in calls:
    print(f"{name}@{server} → {args}")
print("--------")

ChatGPT 中的澄清问题与 Deep Research API

如果你在 ChatGPT 中使用过 Deep Research,你可能会注意到,在提交查询后,它经常会提出后续问题。这是有意为之:ChatGPT 使用一个中间模型(如 gpt-4.1)来帮助澄清你的意图并收集更多上下文(例如你的偏好、目标或约束),然后再开始研究过程。这一额外步骤有助于系统定制其网络搜索,并返回更相关、更有针对性的结果。

相比之下,Deep Research API 跳过了这一澄清步骤。作为开发者,你可以配置这一处理步骤来重写用户提示或提出一组澄清问题,因为模型期望一开始就提供完整的提示,并且不会要求额外的上下文或填补缺失的信息;它只是根据收到的输入开始研究。

为了从 API 获得强大、可靠的输出,你可以使用两种方法。

这种设置让开发者完全控制研究任务的框架,但也对输入提示的质量提出了更高的要求。以下是一个通用的重写提示示例,用于更好地指导后续的深度研究查询。

深度研究API与ChatGPT提示澄清流程对比图以下是一个重写提示的示例:

suggested_rewriting_prompt = """
You will be given a research task by a user. Your job is to produce a set of instructions for a researcher that will complete the task. Do NOT complete the task yourself, just provide instructions on how to complete it.

GUIDELINES:
1. **Maximize Specificity and Detail**
- Include all known user preferences and explicitly list key attributes or dimensions to consider.
- It is of utmost importance that all details from the user are included in the instructions.

2. **Fill in Unstated But Necessary Dimensions as Open-Ended**
- If certain attributes are essential for a meaningful output but the user has not provided them, explicitly state that they are open-ended or default to no specific constraint.

3. **Avoid Unwarranted Assumptions**
- If the user has not provided a particular detail, do not invent one.
- Instead, state the lack of specification and guide the researcher to treat it as flexible or accept all possible options.

4. **Use the First Person**
- Phrase the request from the perspective of the user.

5. **Tables**
- If you determine that including a table will help illustrate, organize, or enhance the information in the research output, you must explicitly request that the researcher provide them.
Examples:
- Product Comparison (Consumer): When comparing different smartphone models, request a table listing each model's features, price, and consumer ratings side-by-side.
- Project Tracking (Work): When outlining project deliverables, create a table showing tasks, deadlines, responsible team members, and status updates.
- Budget Planning (Consumer): When creating a personal or household budget, request a table detailing income sources, monthly expenses, and savings goals.
Competitor Analysis (Work): When evaluating competitor products, request a table with key metrics, such as market share, pricing, and main differentiators.

6. **Headers and Formatting**
- You should include the expected output format in the prompt.
- If the user is asking for content that would be best returned in a structured format (e.g. a report, plan, etc.), ask the researcher to format as a report with the appropriate headers and formatting that ensures clarity and structure.

7. **Language**
- If the user input is in a language other than English, tell the researcher to respond in this language, unless the user query explicitly asks for the response in a different language.

8. **Sources**
- If specific sources should be prioritized, specify them in the prompt.
- For product and travel research, prefer linking directly to official or primary websites (e.g., official brand sites, manufacturer pages, or reputable e-commerce platforms like Amazon for user reviews) rather than aggregator sites or SEO-heavy blogs.
- For academic or scientific queries, prefer linking directly to the original paper or official journal publication rather than survey papers or secondary summaries.
- If the query is in a specific language, prioritize sources published in that language.
"""
response = client.responses.create(
    instructions=suggested_rewriting_prompt,
    model="gpt-4.1-2025-04-14",
    input="help me plan a trip to france",
)
new_query = response.output[0].content[0].text
print(new_query)

在这个例子中,用户提交了一个通用或开放式的问题,没有指定关键细节,如旅行日期、目的地偏好、预算、兴趣或旅行同伴;重写提示词重写了查询,以便 Deep Research 尝试生成一个广泛且包容的响应,预期覆盖常见用例。

虽然这种行为有助于呈现广泛的选择,但往往会导致冗长、更高的延迟和增加的 token 使用量,因为模型必须考虑许多可能的场景。对于触发复杂规划或综合任务(例如多目的地旅行行程、比较研究、产品选择)的查询尤其如此。

与其立即进行广泛的研究计划,不如尝试使用一个更轻量级的模型,在生成完整答案之前温和地向用户提出澄清问题,然后使用重写提示词为模型生成更清晰的输出。

suggested_clariying_prompt = """"
You will be given a research task by a user. Your job is NOT to complete the task yet, but instead to ask clarifying questions that would help you or another researcher produce a more specific, efficient, and relevant answer.

GUIDELINES:
1. **Maximize Relevance**
- Ask questions that are *directly necessary* to scope the research output.
- Consider what information would change the structure, depth, or direction of the answer.

2. **Surface Missing but Critical Dimensions**
- Identify essential attributes that were not specified in the user’s request (e.g., preferences, time frame, budget, audience).
- Ask about each one *explicitly*, even if it feels obvious or typical.

3. **Do Not Invent Preferences**
- If the user did not mention a preference, *do not assume it*. Ask about it clearly and neutrally.

4. **Use the First Person**
- Phrase your questions from the perspective of the assistant or researcher talking to the user (e.g., “Could you clarify...” or “Do you have a preference for...”)

5. **Use a Bulleted List if Multiple Questions**
- If there are multiple open questions, list them clearly in bullet format for readability.

6. **Avoid Overasking**
- Prioritize the 3–6 questions that would most reduce ambiguity or scope creep. You don’t need to ask *everything*, just the most pivotal unknowns.

7. **Include Examples Where Helpful**
- If asking about preferences (e.g., travel style, report format), briefly list examples to help the user answer.

8. **Format for Conversational Use**
- The output should sound helpful and conversational—not like a form. Aim for a natural tone while still being precise.
"""


response = client.responses.create(
    instructions=suggested_clariying_prompt,
    model="gpt-4.1-2025-04-14",
    input="help me plan a trip to france",
)

new_query = response.output[0].content[0].text
print(new_query)
user_follow_up = """I'd like to travel in August. I'd like to visit Paria and Nice. I'd like to keep it under $1500 for a 7 day trip without including flights.
I'm going with my friend. we're both in our mid-twenties. i like history, really good french food and wine, and hiking
"""
instructions_for_DR = client.responses.create(
    instructions=suggested_rewriting_prompt,
    model="gpt-4.1-2025-04-14",
    input=user_follow_up,
)
instructions_for_deep_research = instructions_for_DR.output[0].content[0].text
print(instructions_for_deep_research)
deep_research_call = client.responses.create(
  model="o4-mini-deep-research-2025-06-26",
  input=[
    {
      "role": "developer",
      "content": [
        {
          "type": "input_text",
          "text": instructions_for_deep_research,
        }
      ]
    },
  ],
  reasoning={
    "summary": "auto"
  },
  tools=[
    {
      "type": "web_search_preview"
    },
  ]
)
# Access the final report from the response object
print(deep_research_call.output[-1].content[0].text)

就这样,一份为你即将到来的法国之旅量身定制的深度研究报告就完成了!

在本笔记本中,我们探讨了如何使用深度研究API来自动化复杂的现实世界研究任务,从分析司美格鲁肽的经济影响到规划适合你的法国之旅。当你需要基于现实世界证据的结构化、带引用的答案时,深度研究尤为出色。一些突出的用例包括:

无论你是想构建研究代理、生成结构化报告,还是将高质量的综合内容集成到你的工作流程中,我们希望这里的示例能帮助你入门。

接下来是什么?深度研究代理

常见问题

常见错误:1) 未设置 background=True 导致超时,应启用后台模式或增加超时时间。2) 忽略 reasoning.summary 参数,导致响应过长或过短,应根据需求设置 auto 或 detailed。3) 未处理 annotations 中的 URL 有效性,应验证链接并处理失效引用。4) MCP 服务器配置错误(URL 不可达、require_approval 设置不当),需检查服务器日志和网络。5) 提示词过于模糊,导致研究范围失控,应使用重写提示词明确细节。排查方法:打印 response.output 各步骤类型,检查搜索查询和代码执行结果;使用日志记录工具调用耗时。生产优化:使用缓存减少重复查询,设置合理的 token 上限,采用流式输出提升体验,对 MCP 调用进行鉴权和限流。

企业应用扩展

可扩展方向:1) 构建多代理协作系统,将 Deep Research 与专用模型结合,实现提示重写、澄清问题、结果验证等环节。2) 集成更多 MCP 工具,接入内部知识库、数据库或第三方 API,丰富数据源。3) 开发可视化界面,展示研究过程(搜索轨迹、推理步骤)和引用高亮。4) 结合向量数据库实现长期记忆,支持多轮迭代研究。5) 优化成本:使用 o4-mini 模型处理简单任务,对复杂任务使用 o3 模型,并利用 background 模式批量处理。

总结

本教程面向有编程基础的开发者,深入讲解 OpenAI Deep Research API 的工程实践。内容涵盖环境搭建、核心调用方法、响应解析、MCP 工具集成,以及如何通过提示重写和澄清问题优化研究质量。通过医疗经济影响分析和旅行规划两个案例,展示从简单调用到复杂工作流的完整流程,并补充了常见错误排查与生产环境优化建议,帮助开发者构建可靠的研究代理。

内容来源与验证

继续系统学习

站内还有更多完整实战教程

加入会员,解锁全部教程、完整代码与持续更新内容。

加入会员
查看全部API 与工程实践教程