OpenAI 网页搜索
网页搜索让模型获取互联网新信息,并给出带来源引用的回答。可在Responses API启用,部分场景也支持Chat Completions。
主要有三类:非推理搜索直接把查询发给工具,依据靠前结果回答,快速但不进行内部规划;推理模型的智能体搜索会主动管理查询、分析并决定是否继续,适合复杂流程但耗时更长,可调gpt-5.5推理强度改变深度与延迟;深度研究面向深入调查,可能查数百来源、耗时数分钟,来源建议gpt-5.5配high或xhigh并用后台模式。
选择集成方式
| 用例 | 建议方式 | 说明 |
|---|---|---|
| 新网页搜索集成 | Responses的web_search及gpt-5.5 | 支持过滤、来源、实时访问和长研究控制 |
| 保留已有Chat Completions搜索 | gpt-5-search-api | 仅在必须保持旧集成时采用 |
| 多步研究或长报告 | gpt-5.5配high或xhigh | 数分钟任务采用后台模式 |
Responses在tools启用搜索,模型按提示自行决定用不用。新集成使用 {"type":"web_search"}。旧web_search_preview仍接受,但不支持filters、external_web_access、return_token_budget等新控制。
来源示例1(javascript)
程序中的自然语言译释22:
今天有哪些积极的新闻?
// [中文] 配置web_search并提交新闻问题;auto下模型仍可以选择不搜索。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6-astra",
tools: [{ type: "web_search" }],
input: "What was a positive news story from today?",
});
console.log(response.output_text);
来源示例2(python)
本段复用的中文释义:译释22。
## [中文] 配置web_search并提交新闻问题;auto下模型仍可以选择不搜索。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
tools=[{"type": "web_search"}],
input="What was a positive news story from today?",
)
print(response.output_text)
来源示例3(go)
本段复用的中文释义:译释22。
// [中文] 配置web_search并提交新闻问题;auto下模型仍可以选择不搜索。
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Tools: []responses.ToolUnionParam{
responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),
},
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What was a positive news story from today?")},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
来源示例4(java)
本段复用的中文释义:译释22。
// [中文] 配置web_search并提交新闻问题;auto下模型仍可以选择不搜索。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.WebSearchTool;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("What was a positive news story from today?")
.addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
来源示例5(csharp)
本段复用的中文释义:译释22。
// [中文] 配置web_search并提交新闻问题;auto下模型仍可以选择不搜索。
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.Tools.Add(ResponseTool.CreateWebSearchTool());
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("What was a positive news story from today?")
);
ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
来源示例6(ruby)
本段复用的中文释义:译释22。
## [中文] 配置web_search并提交新闻问题;auto下模型仍可以选择不搜索。
require "openai"
openai = OpenAI::Client.new
response = openai.responses.create(
model: "gpt-6-astra",
tools: [{ type: "web_search" }],
input: "What was a positive news story from today?"
)
puts(response.output_text)
来源示例7(bash)
本段复用的中文释义:译释22。
## [中文] 配置web_search并提交新闻问题;auto下模型仍可以选择不搜索。
curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"tools": [{"type": "web_search"}],
"input": "what was a positive news story from today?"
}'
来源示例8(bash)
本段复用的中文释义:译释22。
## [中文] 配置web_search并提交新闻问题;auto下模型仍可以选择不搜索。
openai responses create \
--model gpt-6-astra \
--raw-output \
--transform 'output.#(type=="message").content.0.text' <<'YAML'
tools:
- type: web_search
input: What was a positive news story from today?
YAML
输出与引用
响应包括两部分:
- web_search_call及调用ID,action说明操作:search是查询,通常但不总包含queries,并产生工具调用费用;open_page和find_in_page分别表示打开页面及页内查找,支持推理模型。
- message含文字
message.content[0].text,引用URL在message.content[0].annotations。
默认文字含行内引用,url_citation注释还含URL、标题和引用位置。向用户展示网页结果或其中信息时,引用必须清晰可见、可点击。
来源示例9(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
[
{
"type": "web_search_call",
"id": "ws_67c9fa0502748190b7dd390736892e100be649c1a5ff9609",
"status": "completed",
"action": {
"type": "search",
"query": "latest news about AI"
}
},
{
"id": "msg_67c9fa077e288190af08fdffda2e34f20be649c1a5ff9609",
"type": "message",
"status": "completed",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "On March 6, 2025, several news...",
"annotations": [
{
"type": "url_citation",
"start_index": 2606,
"end_index": 2758,
"url": "https://...",
"title": "Title..."
}
]
}
]
}
]
从旧网页搜索迁移
| 原方式 | 建议 | 说明 |
|---|---|---|
| Responses web_search_preview | 改web_search | 获得过滤、实时访问和返回预算控制 |
| gpt-4o-search-preview、gpt-4o-mini-search-preview | Responses web_search;必须保留Chat时用gpt-5-search-api | 预览模型已弃用,2026年7月23日停用 |
| Chat Completions搜索 | 保留gpt-5-search-api,或迁移Responses | Chat搜索模型总在回答前搜索;Responses搜索是可选工具 |
搜索上下文大小
search_context_size控制搜索结果向模型提供多少上下文。low适合简单查询,medium为平衡默认,high用于需要更多细节的回答。它不代表精确词元数,也不保证来源或引用数量。
来源示例10(javascript)
程序中的自然语言译释96:
哪部电影获得2025年的最佳影片奖?
// [中文] 设置search_context_size,不把它解释为精确词元或来源数量。
import OpenAI from "openai";
const openai = new OpenAI();
const response = await openai.responses.create({
model: "gpt-6-astra",
tools: [
{
type: "web_search",
search_context_size: "low",
},
],
input: "What movie won best picture in 2025?",
});
console.log(response.output_text);
来源示例11(python)
本段复用的中文释义:译释96。
## [中文] 设置search_context_size,不把它解释为精确词元或来源数量。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
tools=[
{
"type": "web_search",
"search_context_size": "low",
}
],
input="What movie won best picture in 2025?",
)
print(response.output_text)
来源示例12(go)
本段复用的中文释义:译释96。
// [中文] 设置search_context_size,不把它解释为精确词元或来源数量。
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)
tool.OfWebSearch.SearchContextSize = responses.WebSearchToolSearchContextSizeLow
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Tools: []responses.ToolUnionParam{tool},
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What movie won best picture in 2025?")},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
来源示例13(java)
本段复用的中文释义:译释96。
// [中文] 设置search_context_size,不把它解释为精确词元或来源数量。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.WebSearchTool;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("What movie won best picture in 2025?")
.addTool(
WebSearchTool.builder()
.type(WebSearchTool.Type.WEB_SEARCH)
.searchContextSize(WebSearchTool.SearchContextSize.LOW)
.build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
来源示例14(csharp)
本段复用的中文释义:译释96。
// [中文] 设置search_context_size,不把它解释为精确词元或来源数量。
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.Tools.Add(
ResponseTool.CreateWebSearchTool(
searchContextSize: WebSearchToolContextSize.Low
)
);
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("What movie won best picture in 2025?")
);
ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
来源示例15(ruby)
本段复用的中文释义:译释96。
## [中文] 设置search_context_size,不把它解释为精确词元或来源数量。
require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
input: "What movie won best picture in 2025?",
tools: [
{
type: :web_search,
search_context_size: :low
}
]
)
puts(response.output_text)
来源示例16(bash)
本段复用的中文释义:译释96。
## [中文] 设置search_context_size,不把它解释为精确词元或来源数量。
curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"tools": [{
"type": "web_search",
"search_context_size": "low"
}],
"input": "What movie won best picture in 2025?"
}'
运行更长的网页研究
return_token_budget控制GPT-5及后续推理模型在Responses搜索中返回的结果内容预算。通常保留默认;需要浏览大量页面、标准返回上限可能不够的高强度研究或评估,才设unlimited。它可能增加成本与延迟,长任务可配background:true,稍后取最终响应。
| 值 | 行为 |
|---|---|
| default | 标准返回词元预算,与省略相同 |
| unlimited | 移除该次搜索运行的默认返回词元预算 |
仅适用于Responses托管web_search的GPT-5及后续推理搜索,不改变搜索上下文窗口,不适用于非推理搜索、旧Search API、容器搜索、Chat搜索模型或web_search_preview。仅接受这两个字符串,拒绝null、数字及其他值。
来源示例17(javascript)
程序中的自然语言译释4:
研究司美格鲁肽对全球医疗卫生系统的经济影响。
要求:
- 包含具体数字、趋势、统计数据和可衡量的结果。
- 优先可靠、最新来源:同行评议研究、世界卫生组织或美国疾控中心等卫生机构、监管机构、药企财报。
- 提供行内引用,并返回所有来源的元数据。
采用分析性写法,避免泛泛而谈,确保每节的推理均有数据支撑,能够为医疗政策或财务建模提供参考。
程序中的自然语言译释97:
研究司美格鲁肽对全球医疗系统的经济影响。要求提供具体数字、趋势、统计及可衡量结果;优先可靠且最新的同行评议研究、卫生机构、监管部门或药企财报;提供行内引用和所有来源元数据。分析应避免空泛,各节以数据支撑推理,为医疗政策或财务建模提供参考。
// [中文] 为较长研究配置返回预算及后台选项,读取具体语言示例的响应。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6-astra",
reasoning: { effort: "xhigh" },
tools: [
{
type: "web_search",
return_token_budget: "unlimited",
},
],
input: [
"Research the economic impact of semaglutide on global healthcare systems.",
"",
"Do:",
"- Include specific figures, trends, statistics, and measurable outcomes.",
"- 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.",
].join("\n"),
});
console.log(response.output_text);
来源示例18(python)
本段复用的中文释义:译释4、译释97。
## [中文] 为较长研究配置返回预算及后台选项,读取具体语言示例的响应。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
reasoning={"effort": "xhigh"},
tools=[
{
"type": "web_search",
"return_token_budget": "unlimited",
}
],
input="""Research the economic impact of semaglutide on global healthcare systems.
Do:
- Include specific figures, trends, statistics, and measurable outcomes.
- 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.""",
)
print(response.output_text)
来源示例19(go)
本段复用的中文释义:译释4、译释97。
// [中文] 为较长研究配置返回预算及后台选项,读取具体语言示例的响应。
package main
import (
"context"
"fmt"
"strings"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
"github.com/openai/openai-go/v3/shared"
)
func main() {
client := openai.NewClient()
tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)
tool.OfWebSearch.SetExtraFields(map[string]any{"return_token_budget": "unlimited"})
input := strings.Join([]string{
"Research the economic impact of semaglutide on global healthcare systems.",
"",
"Do:",
"- Include specific figures, trends, statistics, and measurable outcomes.",
"- Prioritize reliable, up-to-date sources: peer-reviewed research, health organizations, 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.",
}, "\n")
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortXhigh},
Tools: []responses.ToolUnionParam{tool},
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(input)},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
来源示例20(java)
程序中的自然语言译释143:
研究司美格鲁肽对全球医疗系统的经济影响,包含当前数据及引用;这是较短的语言版本提示。
// [中文] 为较长研究配置返回预算及后台选项,读取具体语言示例的响应。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.Reasoning;
import com.openai.models.ReasoningEffort;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.WebSearchTool;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input(
"Research the economic impact of semaglutide on global healthcare systems. Include current figures and citations.")
.reasoning(Reasoning.builder().effort(ReasoningEffort.XHIGH).build())
.addTool(
WebSearchTool.builder()
.type(WebSearchTool.Type.WEB_SEARCH)
.putAdditionalProperty("return_token_budget", JsonValue.from("unlimited"))
.build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
来源示例21(ruby)
本段复用的中文释义:译释143。
## [中文] 为较长研究配置返回预算及后台选项,读取具体语言示例的响应。
require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
input: "Research the economic impact of semaglutide on global healthcare systems. Include current figures and citations.",
reasoning: { effort: :xhigh },
tools: [
{
type: :web_search,
return_token_budget: :unlimited
}
]
)
puts(response.output_text)
来源示例22(bash)
本段复用的中文释义:译释4、译释97。
## [中文] 为较长研究配置返回预算及后台选项,读取具体语言示例的响应。
curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"reasoning": { "effort": "xhigh" },
"tools": [
{
"type": "web_search",
"return_token_budget": "unlimited"
}
],
"input": "Research the economic impact of semaglutide on global healthcare systems.\n\nDo:\n- Include specific figures, trends, statistics, and measurable outcomes.\n- Prioritize reliable, up-to-date sources: peer-reviewed research, health organizations (e.g., WHO, CDC), regulatory agencies, or pharmaceutical earnings reports.\n- Include inline citations and return all source metadata.\n\nBe analytical, avoid generalities, and ensure that each section supports data-backed reasoning that could inform healthcare policy or financial modeling."
}'
域名过滤
filters可配置最多100个allowed_domains或最多100个blocked_domains。域名不带HTTP/HTTPS前缀,例如openai.com,也覆盖子域名。仅Responses web_search支持。
来源
sources返回搜索过程中查询的完整URL清单,而行内引用只展示最相关来源,因此来源数通常更多。实时第三方数据流也在此列出,标记为oai-sports、oai-weather或oai-finance。web_search和web_search_preview均支持sources。
来源示例23(javascript)
程序中的自然语言译释98:
搜索网页,了解司美格鲁肽如何用于治疗糖尿病。
// [中文] 请求sources并读取搜索来源,不把来源清单等同于正文引用。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6-astra",
reasoning: { effort: "low" },
tools: [
{
type: "web_search",
filters: {
allowed_domains: [
"pubmed.ncbi.nlm.nih.gov",
"clinicaltrials.gov",
"www.who.int",
"www.cdc.gov",
"www.fda.gov",
],
blocked_domains: ["reddit.com", "quora.com", "wikipedia.org"],
},
},
],
tool_choice: "auto",
include: ["web_search_call.action.sources"],
input:
"Please perform a web search on how semaglutide is used in the treatment of diabetes.",
});
console.log(response.output_text);
来源示例24(python)
本段复用的中文释义:译释98。
## [中文] 请求sources并读取搜索来源,不把来源清单等同于正文引用。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
reasoning={"effort": "low"},
tools=[
{
"type": "web_search",
"filters": {
"allowed_domains": [
"pubmed.ncbi.nlm.nih.gov",
"clinicaltrials.gov",
"www.who.int",
"www.cdc.gov",
"www.fda.gov",
],
"blocked_domains": [
"reddit.com",
"quora.com",
"wikipedia.org",
],
},
}
],
tool_choice="auto",
include=["web_search_call.action.sources"],
input="Please perform a web search on how semaglutide is used in the treatment of diabetes.",
)
print(response.output_text)
来源示例25(go)
本段复用的中文释义:译释98。
// [中文] 请求sources并读取搜索来源,不把来源清单等同于正文引用。
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
"github.com/openai/openai-go/v3/shared"
)
func main() {
client := openai.NewClient()
tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)
tool.OfWebSearch.Filters = responses.WebSearchToolFiltersParam{
AllowedDomains: []string{"pubmed.ncbi.nlm.nih.gov", "clinicaltrials.gov", "www.who.int", "www.cdc.gov", "www.fda.gov"},
}
tool.OfWebSearch.Filters.SetExtraFields(map[string]any{"blocked_domains": []string{"reddit.com", "quora.com", "wikipedia.org"}})
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow},
Tools: []responses.ToolUnionParam{tool},
Include: []responses.ResponseIncludable{responses.ResponseIncludableWebSearchCallActionSources},
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Please perform a web search on how semaglutide is used in the treatment of diabetes.")},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
来源示例26(java)
程序中的自然语言译释144:
搜索司美格鲁肽如何用于治疗糖尿病。
// [中文] 请求sources并读取搜索来源,不把来源清单等同于正文引用。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.Reasoning;
import com.openai.models.ReasoningEffort;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseIncludable;
import com.openai.models.responses.WebSearchTool;
import java.util.List;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Search for how semaglutide is used in the treatment of diabetes.")
.reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())
.addInclude(ResponseIncludable.of("web_search_call.action.sources"))
.addTool(
WebSearchTool.builder()
.type(WebSearchTool.Type.WEB_SEARCH)
.filters(
WebSearchTool.Filters.builder()
.allowedDomains(
List.of(
"pubmed.ncbi.nlm.nih.gov",
"clinicaltrials.gov",
"www.who.int",
"www.cdc.gov",
"www.fda.gov"))
.putAdditionalProperty(
"blocked_domains",
JsonValue.from(List.of("reddit.com", "quora.com", "wikipedia.org")))
.build())
.build())
.build();
var response = client.responses().create(params);
response.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
response.output().stream()
.flatMap(item -> item.webSearchCall().stream())
.flatMap(call -> call.action().search().stream())
.flatMap(action -> action.sources().stream())
.flatMap(List::stream)
.forEach(source -> System.out.println(source.url()));
来源示例27(ruby)
本段复用的中文释义:译释144。
## [中文] 请求sources并读取搜索来源,不把来源清单等同于正文引用。
require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
reasoning: { effort: :low },
input: "Search for how semaglutide is used in the treatment of diabetes.",
include: ["web_search_call.action.sources"],
tools: [
{
type: :web_search,
filters: {
allowed_domains: [
"pubmed.ncbi.nlm.nih.gov",
"clinicaltrials.gov",
"www.who.int",
"www.cdc.gov",
"www.fda.gov"
],
blocked_domains: ["reddit.com", "quora.com", "wikipedia.org"]
}
}
]
)
puts(response.output_text)
response.output
.grep(OpenAI::Models::Responses::ResponseFunctionWebSearch)
.each do |search_call|
action = search_call.action
next unless action.is_a?(
OpenAI::Models::Responses::ResponseFunctionWebSearch::Action::Search
)
Array(action.sources).each { |source| puts(source.url) }
end
来源示例28(bash)
本段复用的中文释义:译释98。
## [中文] 请求sources并读取搜索来源,不把来源清单等同于正文引用。
curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"reasoning": { "effort": "low" },
"tools": [
{
"type": "web_search",
"filters": {
"allowed_domains": [
"pubmed.ncbi.nlm.nih.gov",
"clinicaltrials.gov",
"www.who.int",
"www.cdc.gov",
"www.fda.gov"
],
"blocked_domains": [
"reddit.com",
"quora.com",
"wikipedia.org"
]
}
}
],
"tool_choice": "auto",
"include": ["web_search_call.action.sources"],
"input": "Please perform a web search on how semaglutide is used in the treatment of diabetes."
}'
图像搜索结果
网页搜索可同时返回图像,适合商品照、地标、地点、事件等需要当前网页视觉资料的场景。在search_content_types加入image;也要支撑总结、排序或解释的文字结果时加入text。
image_settings中max_results请求正数数量,caption要求可用时返回简短说明。请求include中加入web_search_call.results,再读取该调用项的results数组。图像结果独立于助手消息,需要URL或元数据时直接解析调用项。
来源示例29(javascript)
程序中的自然语言译释99:
搜索金门大桥日落的近期图像及支持性文字来源。
// [中文] 配置图像与文字搜索,并在include请求原始图像结果。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6-astra",
reasoning: { effort: "low" },
tools: [
{
type: "web_search",
search_content_types: ["image", "text"],
image_settings: {
max_results: 3,
caption: true,
},
},
],
include: ["web_search_call.results"],
input:
"Search for recent images and supporting text sources about the Golden Gate Bridge at sunset.",
});
console.log(response.output);
来源示例30(python)
本段复用的中文释义:译释99。
## [中文] 配置图像与文字搜索,并在include请求原始图像结果。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
reasoning={"effort": "low"},
tools=[
{
"type": "web_search",
"search_content_types": ["image", "text"],
"image_settings": {
"max_results": 3,
"caption": True,
},
}
],
include=["web_search_call.results"],
input="Search for recent images and supporting text sources about the Golden Gate Bridge at sunset.",
)
print(response.output)
来源示例31(go)
本段复用的中文释义:译释99。
// [中文] 配置图像与文字搜索,并在include请求原始图像结果。
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
"github.com/openai/openai-go/v3/shared"
)
func main() {
client := openai.NewClient()
tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)
tool.OfWebSearch.SetExtraFields(map[string]any{
"search_content_types": []string{"image", "text"},
"image_settings": map[string]any{"max_results": 3, "caption": true},
})
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortLow},
Tools: []responses.ToolUnionParam{tool},
Include: []responses.ResponseIncludable{responses.ResponseIncludableWebSearchCallResults},
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Search for recent images and supporting text sources about the Golden Gate Bridge at sunset.")},
})
if err != nil {
panic(err)
}
fmt.Println(response.Output)
}
来源示例32(java)
本段复用的中文释义:译释99。
// [中文] 配置图像与文字搜索,并在include请求原始图像结果。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.Reasoning;
import com.openai.models.ReasoningEffort;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseIncludable;
import com.openai.models.responses.WebSearchTool;
import java.util.List;
import java.util.Map;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input(
"Search for recent images and supporting text sources about the Golden Gate Bridge at sunset.")
.reasoning(Reasoning.builder().effort(ReasoningEffort.LOW).build())
.addInclude(ResponseIncludable.of("web_search_call.results"))
.addTool(
WebSearchTool.builder()
.type(WebSearchTool.Type.WEB_SEARCH)
.putAdditionalProperty(
"search_content_types", JsonValue.from(List.of("image", "text")))
.putAdditionalProperty(
"image_settings", JsonValue.from(Map.of("max_results", 3, "caption", true)))
.build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.webSearchCall().stream())
.map(call -> call._additionalProperties().get("results"))
.filter(java.util.Objects::nonNull)
.forEach(System.out::println);
来源示例33(ruby)
本段复用的中文释义:译释99。
## [中文] 配置图像与文字搜索,并在include请求原始图像结果。
require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
reasoning: { effort: :low },
input: "Search for recent images and supporting text sources about the Golden Gate Bridge at sunset.",
include: ["web_search_call.results"],
tools: [
{
type: :web_search,
search_content_types: ["image", "text"],
image_settings: {
max_results: 3,
caption: true
}
}
]
)
puts(response.output)
来源示例34(bash)
本段复用的中文释义:译释99。
## [中文] 配置图像与文字搜索,并在include请求原始图像结果。
curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"reasoning": { "effort": "low" },
"tools": [
{
"type": "web_search",
"search_content_types": ["image", "text"],
"image_settings": {
"max_results": 3,
"caption": true
}
}
],
"include": ["web_search_call.results"],
"input": "Search for recent images and supporting text sources about the Golden Gate Bridge at sunset."
}'
每个image_result含image_url规范URL、source_website_url来源网页,可选thumbnail_url和caption。
来源示例35(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。
{
"output": [
{
"type": "web_search_call",
"status": "completed",
"results": [
{
"type": "image_result",
"image_url": "https://cdn.example/golden-gate-sunset.jpg",
"thumbnail_url": "https://cdn.example/golden-gate-sunset-thumb.jpg",
"source_website_url": "https://example.com/source-page",
"caption": "Golden Gate Bridge at sunset"
}
]
}
]
}
用户位置
可指定近似国家、城市、地区、时区改善地域结果。city与region是自由文本,如Minneapolis、Minnesota;country用两字母ISO国家码,如US;timezone用IANA时区,如America/Chicago。深度研究模型的网页搜索不支持用户位置。
来源示例36(javascript)
程序中的自然语言译释100:
我附近有哪些值得去的餐厅?
// [中文] 提供近似城市、国家或时区以改善地域搜索。
import OpenAI from "openai";
const openai = new OpenAI();
const response = await openai.responses.create({
model: "gpt-6-astra",
tools: [
{
type: "web_search",
user_location: {
type: "approximate",
country: "GB",
city: "London",
region: "London",
},
},
],
input: "What are the best restaurants near me?",
});
console.log(response.output_text);
来源示例37(python)
本段复用的中文释义:译释100。
## [中文] 提供近似城市、国家或时区以改善地域搜索。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
tools=[
{
"type": "web_search",
"user_location": {
"type": "approximate",
"country": "GB",
"city": "London",
"region": "London",
},
}
],
input="What are the best restaurants near me?",
)
print(response.output_text)
来源示例38(go)
本段复用的中文释义:译释100。
// [中文] 提供近似城市、国家或时区以改善地域搜索。
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)
tool.OfWebSearch.UserLocation = responses.WebSearchToolUserLocationParam{
Type: "approximate",
Country: openai.String("GB"),
City: openai.String("London"),
Region: openai.String("London"),
}
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Tools: []responses.ToolUnionParam{tool},
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What are the best restaurants near me?")},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
来源示例39(java)
本段复用的中文释义:译释100。
// [中文] 提供近似城市、国家或时区以改善地域搜索。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.WebSearchTool;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("What are the best restaurants near me?")
.addTool(
WebSearchTool.builder()
.type(WebSearchTool.Type.WEB_SEARCH)
.userLocation(
WebSearchTool.UserLocation.builder()
.type(WebSearchTool.UserLocation.Type.APPROXIMATE)
.city("London")
.country("GB")
.region("London")
.build())
.build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
来源示例40(csharp)
本段复用的中文释义:译释100。
// [中文] 提供近似城市、国家或时区以改善地域搜索。
using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.Tools.Add(
ResponseTool.CreateWebSearchTool(
userLocation: WebSearchToolLocation.CreateApproximateLocation(
country: "GB",
city: "London",
region: "London"
)
)
);
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("What are the best restaurants near me?")
);
ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText());
来源示例41(ruby)
本段复用的中文释义:译释100。
## [中文] 提供近似城市、国家或时区以改善地域搜索。
require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
input: "What are the best restaurants near me?",
tools: [
{
type: :web_search,
user_location: {
type: :approximate,
country: "GB",
city: "London",
region: "London"
}
}
]
)
puts(response.output_text)
来源示例42(bash)
本段复用的中文释义:译释100。
## [中文] 提供近似城市、国家或时区以改善地域搜索。
curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"tools": [{
"type": "web_search",
"user_location": {
"type": "approximate",
"country": "GB",
"city": "London",
"region": "London"
}
}],
"input": "What are the best restaurants near me?"
}'
实时互联网访问
Responses可控制抓取实时网页还是只用缓存、索引:web_search的external_web_access:false为离线缓存模式;不设默认为true。web_search_preview忽略参数,行为始终相当于true。
来源示例43(bash)
程序中的自然语言译释101:
查找埃菲尔铁塔何时向公众开放,并引用来源。
## [中文] 用external_web_access关闭实时抓取,仅使用缓存索引;此控制不适用于preview。
curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"tools": [
{ "type": "web_search", "external_web_access": false }
],
"tool_choice": "auto",
"input": "Find when the Eiffel Tower opened to the public and cite the source."
}'
来源示例44(javascript)
本段复用的中文释义:译释101。
// [中文] 用external_web_access关闭实时抓取,仅使用缓存索引;此控制不适用于preview。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-6-astra",
tools: [{ type: "web_search", external_web_access: false }],
tool_choice: "auto",
input: "Find when the Eiffel Tower opened to the public and cite the source.",
});
console.log(response.output_text);
来源示例45(python)
本段复用的中文释义:译释101。
## [中文] 用external_web_access关闭实时抓取,仅使用缓存索引;此控制不适用于preview。
from openai import OpenAI
client = OpenAI()
resp = client.responses.create(
model="gpt-6-astra",
tools=[{"type": "web_search", "external_web_access": False}],
tool_choice="auto",
input="Find when the Eiffel Tower opened to the public and cite the source.",
)
print(resp.output_text)
来源示例46(go)
本段复用的中文释义:译释101。
// [中文] 用external_web_access关闭实时抓取,仅使用缓存索引;此控制不适用于preview。
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
tool := responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch)
tool.OfWebSearch.SetExtraFields(map[string]any{"external_web_access": false})
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Tools: []responses.ToolUnionParam{tool},
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Find when the Eiffel Tower opened to the public and cite the source.")},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
}
来源示例47(java)
本段复用的中文释义:译释101。
// [中文] 用external_web_access关闭实时抓取,仅使用缓存索引;此控制不适用于preview。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.WebSearchTool;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Find when the Eiffel Tower opened to the public and cite the source.")
.addTool(
WebSearchTool.builder()
.type(WebSearchTool.Type.WEB_SEARCH)
.putAdditionalProperty("external_web_access", JsonValue.from(false))
.build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text()));
来源示例48(ruby)
本段复用的中文释义:译释101。
## [中文] 用external_web_access关闭实时抓取,仅使用缓存索引;此控制不适用于preview。
require "openai"
client = OpenAI::Client.new
response = client.responses.create(
model: "gpt-6-astra",
input: "Find when the Eiffel Tower opened to the public and cite the source.",
tools: [
{
type: :web_search,
external_web_access: false
}
]
)
puts(response.output_text)
限制
Chat Completions API
只支持专用搜索模型,不支持Responses的域名过滤、完整来源、实时访问及返回预算控制。
| 模型 | 上下文窗口 | 状态与限制 |
|---|---|---|
| gpt-5-search-api | 200k | Chat Completions专用搜索路径 |
| gpt-4o-search-preview | 128k | 旧搜索路径,2026年7月23日停用 |
| gpt-4o-mini-search-preview | 128k | 旧搜索路径,2026年7月23日停用 |
Responses API
新集成用托管web_search,旧集成仍接受preview。可用gpt-5.5获得更大模型窗口,但搜索上下文仍限128k。
| 模型 | 模型窗口 | 搜索限制 |
|---|---|---|
| gpt-4.1 | 1M | 搜索上下文128k |
| gpt-4.1-mini | 1M | 搜索上下文128k |
| o4-mini | 200k | 搜索上下文128k;来源列明2026年10月23日停用 |
- 模型窗口更大也不扩大128k搜索窗口。
- gpt-5配minimal推理不支持网页搜索。
- gpt-5.4配none推理可能降低结果质量。
- 使用底层模型的分级速率限制。
- preview不支持filters或return_token_budget,并忽略external_web_access。
- auto下搜索可不执行;必须搜索时使用required或指定网页搜索工具选择。
使用说明
来源表列出Responses、Chat Completions、Assistants入口;实际集成支持范围按上文区分,不表示每个接口都支持相同web_search配置。费率见价格,数据要求见ZDR与驻留。

TRAE-AI编程


更多建议: