你可以从任意后端通过 REST API 调用 Web Search API,也可以在 Worker 中通过 AI 绑定(binding)调用。两种方法都会通过 AI Gateway 路由请求。
- 一个 Cloudflare 账户。如果还没有,请注册 ↗。
- 一个 AI Gateway。每个账户都有一个名为
default的网关,你也可以创建网关。 - 账户上已充值 AI Gateway 额度,或网关上已存储提供商 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" }
}
}'通过 AI 绑定上的 websearch() 方法从 Worker 调用 Web Search API。
-
在 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" -
使用网关 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" }
}
}stringrequiredminLength: 1maxLength: 1024搜索查询。stringdefault: ceramicenum: ceramic, exa, linkup要使用的搜索提供商。integerdefault: 10minimum: 1maximum: 10要返回的最大搜索结果数。stringpattern: ^[A-Za-z0-9_-]{1,64}$存储在网关上的提供商 API 密钥别名。如果设置了该字段,当密钥未配置时请求会失败,而不会回退到 AI Gateway 额度。objectrequired请求选项。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,
});stringrequired用于路由该请求的 AI Gateway ID。stringrequiredminLength: 1maxLength: 1024搜索查询。stringdefault: ceramicenum: ceramic, exa, linkup要使用的搜索提供商。integerdefault: 10minimum: 1maximum: 10要返回的最大搜索结果数。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
}
}array搜索结果。object有关该请求的信息。仅当提供商返回可选字段时,这些字段才会包含在响应中。
如果你已有搜索提供商账户,可以使用自己的 API 密钥,而不是 AI Gateway 额度。提供商会直接向你计费。
-
在 Cloudflare 仪表板中,前往 AI Gateway 页面。
前往 AI Gateway ↗ -
选择你的网关,然后选择 Provider Keys。
-
为 Ceramic.ai、Exa 或 Linkup 添加 API 密钥,并为其指定别名 — 例如
default。如果列表中没有该提供商,请选择 Configure custom providers 进行添加。 -
在请求中传入提供商和别名。
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 工具,让模型使用网络搜索。当模型调用该工具时,运行搜索并将结果回传给模型。
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 |