联网搜索
使用 Web Search 查询网络资料,了解开启和关闭方式
联网搜索让模型结合网络资料回答问题,适合新闻、产品动态和公开文档查询。
并非所有模型都支持联网搜索:不支持的模型请求正常返回,但不会执行搜索;即使模型支持,开启搜索也不保证每次都会执行(是否搜索由模型判断)。
开启搜索
在请求中加入 web_search_options: {"enable": true}(enable 缺省视为 true,传空对象 {} 亦可)。以下为 Chat Completions 示例:
curl https://api.tokenplus.cn/v1/chat/completions \
-H "Authorization: Bearer $TOKENPLUS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "YOUR_SEARCH_MODEL_ID",
"messages": [
{"role": "user", "content": "请联网查询最近的产品动态,并附资料来源。"}
],
"web_search_options": {"enable": true}
}'将 YOUR_SEARCH_MODEL_ID 替换为项目可用且支持搜索的模型 ID,并将 API Key 放入 TOKENPLUS_API_KEY 环境变量。使用 OpenAI Python SDK 时,通过 extra_body={"web_search_options": {"enable": True}} 传入;与 OpenAI 搜索类模型的 web_search_options 参数同名。
Messages 使用相同的 web_search_options 参数:
curl https://api.tokenplus.cn/v1/messages \
-H "X-Api-Key: $TOKENPLUS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "YOUR_SEARCH_MODEL_ID",
"max_tokens": 2048,
"messages": [
{"role": "user", "content": "请联网查询最近的产品动态,并附资料来源。"}
],
"web_search_options": {"enable": true}
}'也可以按 Anthropic Messages API 的用法直接在 tools 中传入服务端搜索工具(如 {"type": "web_search_20250305", "name": "web_search"}),网关会原样透传;但是否真正执行搜索取决于服务商的模型端点是否支持这种方式,不支持时可能返回普通工具调用的 tool_use 块。推荐使用 web_search_options,由网关适配服务商的模型端点。
Responses 接口通过 tools 中的 web_search 工具开启搜索,用法与 OpenAI Responses API 一致;该接口不支持 web_search_options:
curl https://api.tokenplus.cn/v1/responses \
-H "Authorization: Bearer $TOKENPLUS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "YOUR_SEARCH_MODEL_ID",
"input": "请联网查询最近的产品动态,并附资料来源。",
"tools": [{"type": "web_search"}]
}'搜索结果的资料来源以 url_citation 类型返回在回答文本的 annotations 中。
关闭搜索
Chat Completions 和 Messages 接口传入 web_search_options: {"enable": false} 即可关闭搜索。Responses 接口在 tools 中不包含 web_search 工具即可。