跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

如何使用 Web Search API

最后更新 查看 MarkdownAgent 设置

你可以从任意后端通过 REST API 调用 Web Search API,也可以在 Worker 中通过 AI 绑定(binding)调用。两种方法都会通过 AI Gateway 路由请求。

前提条件

REST API

向 /ai/websearch/ 端点发送 POST 请求:

POST https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/websearch/

使用同时具有以下权限的 Cloudflare API 令牌进行身份验证:

  • Account > Workers AI > Read
  • Account > AI Gateway > Read
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/websearch/ \
  --request POST \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
    "query": "What are some fun things to do in Salt Lake City as fall approaches?",
    "provider": "ceramic",
    "limit": 5,
    "options": {
      "gateway": { "id": "default" }
    }
  }'

Workers 绑定

通过 AI 绑定上的 websearch() 方法从 Worker 调用 Web Search API。

  1. 在 Wrangler 配置文件中添加 AI 绑定:

    {
      "$schema": "./node_modules/wrangler/config-schema.json",
      "name": "web-search-worker",
      "main": "src/index.ts",
      "upload_source_maps": true,
      // Set this to today's date
      "compatibility_date": "2026-11-14",
      "ai": {
        "binding": "AI"
      }
    }
    name = "web-search-worker"
    main = "src/index.ts"
    upload_source_maps = true
    # Set this to today's date
    compatibility_date = "2026-11-14"
    
    [ai]
    binding = "AI"
  2. 使用网关 ID 和查询调用 env.AI.websearch():

    src/index.tsts
    export default {
    	async fetch(request, env): Promise<Response> {
    		const response = await env.AI.websearch({
    			gatewayId: "default",
    			query:
    				"What are some fun things to do in Salt Lake City as fall approaches?",
    			provider: "exa",
    			limit: 5,
    		});
    
    		const results = await response.json();
    		return Response.json(results);
    	},
    } satisfies ExportedHandler<Env>;

websearch() 返回标准 Response 对象。调用 response.json() 即可读取结果。

请求参数

设置 provider 以选择搜索提供商。如果未设置提供商,Web Search API 默认使用 Ceramic.ai。

{
	"query": "What are some fun things to do in Salt Lake City as fall approaches?",
	"provider": "ceramic",
	"limit": 5,
	"options": {
		"gateway": { "id": "default" }
	}
}
query
stringrequiredminLength: 1maxLength: 1024搜索查询。
provider
stringdefault: ceramicenum: ceramic, exa, linkup要使用的搜索提供商。
limit
integerdefault: 10minimum: 1maximum: 10要返回的最大搜索结果数。
byokAlias
stringpattern: ^[A-Za-z0-9_-]{1,64}$存储在网关上的提供商 API 密钥别名。如果设置了该字段,当密钥未配置时请求会失败,而不会回退到 AI Gateway 额度。
const response = await env.AI.websearch({
	gatewayId: "default",
	query: "What are some fun things to do in Salt Lake City as fall approaches?",
	provider: "ceramic",
	limit: 5,
});
gatewayId
stringrequired用于路由该请求的 AI Gateway ID。
query
stringrequiredminLength: 1maxLength: 1024搜索查询。
provider
stringdefault: ceramicenum: ceramic, exa, linkup要使用的搜索提供商。
limit
integerdefault: 10minimum: 1maximum: 10要返回的最大搜索结果数。
byokAlias
stringpattern: ^[A-Za-z0-9_-]{1,64}$存储在网关上的提供商 API 密钥别名。如果设置了该字段,当密钥未配置时请求会失败,而不会回退到 AI Gateway 额度。

响应格式

{
	"items": [
		{
			"url": "https://example.com/salt-lake-city-fall-guide",
			"title": "Fall in Salt Lake City: A Local's Guide",
			"description": "From scenic drives up Big Cottonwood Canyon to pumpkin patches..."
		}
	],
	"metadata": {
		"query": "What are some fun things to do in Salt Lake City as fall approaches?",
		"requestId": "<REQUEST_ID>",
		"latencyMs": 612
	}
}

仅当提供商返回可选字段时,这些字段才会包含在响应中。

自带密钥 (BYOK)

如果你已有搜索提供商账户,可以使用自己的 API 密钥,而不是 AI Gateway 额度。提供商会直接向你计费。

  1. 在 Cloudflare 仪表板中,前往 AI Gateway 页面。

    前往 AI Gateway ↗
  2. 选择你的网关,然后选择 Provider Keys。

  3. 为 Ceramic.ai、Exa 或 Linkup 添加 API 密钥,并为其指定别名 — 例如 default。如果列表中没有该提供商,请选择 Configure custom providers 进行添加。

  4. 在请求中传入提供商和别名。

curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/websearch/ \
  --request POST \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
    "query": "What is Cloudflare Workers?",
    "provider": "exa",
    "byokAlias": "default",
    "options": {
      "gateway": { "id": "default" }
    }
  }'
const response = await env.AI.websearch({
	gatewayId: "default",
	query: "What is Cloudflare Workers?",
	provider: "exa",
	byokAlias: "default",
});

你的 API 密钥永远不会出现在请求中。AI Gateway 会检索为该提供商和别名存储在网关上的密钥,并使用 Secrets Store 加密已存储的密钥。

AI Gateway 按如下方式选择凭据:

  • 你设置了 byokAlias — AI Gateway 使用该别名对应的已存储密钥。如果网关上未配置该提供商或别名,请求会失败并返回 400 错误,而不会回退到你的额度。
  • 你省略了 byokAlias — 如果网关为该提供商存储了别名为 default 的密钥,AI Gateway 会使用该密钥。否则,搜索费用会计入你的 AI Gateway 额度。

更多信息请参阅自带密钥。

将网络搜索用作工具

你可以通过定义 web_search 工具,让模型使用网络搜索。当模型调用该工具时,运行搜索并将结果回传给模型。

src/index.tsts
const MODEL = "@cf/google/gemma-4-26b-a4b-it";

export default {
	async fetch(request, env): Promise<Response> {
		const prompt = "What happened during the last Cloudflare Birthday Week?";
		const messages = [{ role: "user", content: prompt }];

		const completion = await env.AI.run(
			MODEL,
			{
				messages,
				tools: [
					{
						type: "function",
						function: {
							name: "web_search",
							description: "Search the web for current information.",
							parameters: {
								type: "object",
								properties: { query: { type: "string" } },
								required: ["query"],
							},
						},
					},
				],
			},
			{ gateway: { id: "default" } },
		);

		const toolCall = completion.tool_calls?.[0];
		if (toolCall?.name !== "web_search") {
			return Response.json(completion);
		}

		const searchResponse = await env.AI.websearch({
			gatewayId: "default",
			query: toolCall.arguments.query,
			limit: 5,
		});
		const searchResults = await searchResponse.json();

		const finalResponse = await env.AI.run(
			MODEL,
			{
				messages: [
					...messages,
					{
						role: "tool",
						name: "web_search",
						content: JSON.stringify(searchResults),
					},
				],
			},
			{ gateway: { id: "default" } },
		);

		return Response.json(finalResponse);
	},
} satisfies ExportedHandler<Env>;

限制

限制 值
查询长度 1,024 个字符
每次请求的结果数 10

这篇文档对您有帮助吗?