Cloudflare Agents SDK 让你可以构建在 Workers 上运行的有状态 AI 智能体。本指南将构建一个聊天智能体:它会预配自己的 AI Search 实例、索引一份文档,然后在回答前用工具搜索该内容。
本指南使用推荐的智能体模式,将 AI Search 的 search() 作为工具暴露给模型。有关该模式的更多信息,请参阅 将 AI Search 用作智能体工具。
- 注册 Cloudflare 账户 ↗。
- 安装
Node.js↗。
使用 create-cloudflare CLI (C3) 创建新的 Worker 项目。C3 ↗ 是一种命令行工具,旨在帮助你设置并部署新的应用程序到 Cloudflare。
通过运行以下命令创建一个名为 ai-search-agent 的新项目:
npm create cloudflare@latest -- ai-search-agentyarn create cloudflare ai-search-agentpnpm create cloudflare@latest ai-search-agent设置时,选择以下选项:
- 对于 What would you like to start with?(希望从什么开始?),选择
Hello World example。 - 对于 Which template would you like to use?(希望使用哪个模板?),选择
Worker only。 - 对于 Which language do you want to use?(希望使用哪种语言?),选择
TypeScript。 - 对于 Do you want to use git for version control?(是否使用 Git 进行版本控制?),选择
Yes。 - 对于 Do you want to add an AGENTS.md file to help AI coding tools understand Cloudflare APIs?(是否添加 AGENTS.md 文件以帮助 AI 编程工具理解 Cloudflare API?),选择
Yes。 - 对于 Do you want to deploy your application?(是否部署应用?),选择
No(部署前还需要进行一些修改)。
进入你的应用程序目录:
cd ai-search-agent安装 Agents SDK 和 AI SDK。此示例通过 agents/models/ai-sdk 中的 createAI 调用 Workers AI:
npm i agents @cloudflare/ai-chat ai @ai-sdk/provider zodyarn add agents @cloudflare/ai-chat ai @ai-sdk/provider zodpnpm add agents @cloudflare/ai-chat ai @ai-sdk/provider zodbun add agents @cloudflare/ai-chat ai @ai-sdk/provider zod将你的 Wrangler 配置文件 替换为以下内容。这会添加用于 AI Search 的 namespace 绑定、用于生成响应的 Workers AI 绑定,以及为智能体存储聊天历史的 Durable Object。
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "ai-search-agent",
"main": "src/server.ts",
"upload_source_maps": true,
// Set this to today's date
"compatibility_date": "2026-11-14",
"compatibility_flags": [
"nodejs_compat"
],
"ai": {
"binding": "AI"
},
"ai_search_namespaces": [
{
"binding": "AI_SEARCH",
"namespace": "default",
"remote": true
}
],
"durable_objects": {
"bindings": [
{
"name": "SearchAgent",
"class_name": "SearchAgent"
}
]
},
"migrations": [
{
"tag": "v1",
"new_sqlite_classes": [
"SearchAgent"
]
}
]
}name = "ai-search-agent"
main = "src/server.ts"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-11-14"
compatibility_flags = ["nodejs_compat"]
[ai]
binding = "AI"
[[ai_search_namespaces]]
binding = "AI_SEARCH"
namespace = "default"
remote = true
[[durable_objects.bindings]]
name = "SearchAgent"
class_name = "SearchAgent"
[[migrations]]
tag = "v1"
new_sqlite_classes = ["SearchAgent"]需要的是 namespace 绑定(ai_search_namespaces),而不是单实例的 ai_search 绑定,因为智能体会在运行时调用 create()。remote 选项让 wrangler dev 将请求代理到已部署的实例,因为 AI Search 不会在本地运行。AIChatAgent 会将消息持久化到 SQLite,因此其类必须列在 new_sqlite_classes 中。
创建 src/server.ts。新的 AI Search 实例默认使用 混合搜索。智能体会用一份文档为新实例做种子,并暴露两个工具:search_knowledge_base 检索内容,save_resolution 将新内容写回。
import { AIChatAgent } from "@cloudflare/ai-chat";
import { routeAgentRequest } from "agents";
import { createAI } from "agents/models/ai-sdk";
import { streamText, convertToModelMessages, tool, stepCountIs } from "ai";
import { z } from "zod";
const INSTANCE_NAME = "knowledge-base";
const SEED_DOC = `# Getting started
AI Search indexes your content so an agent can retrieve it at query time.`;
// AIChatAgent stores the conversation history and calls onChatMessage() once
// for each user message.
export class SearchAgent extends AIChatAgent {
// Guard so the one-time instance setup runs only once per running agent.
ready = false;
// Create the agent's instance, which uses hybrid search by default, then seed
// it so the first query has content.
async ensureInstance() {
if (this.ready) return;
try {
await this.env.AI_SEARCH.create({
id: INSTANCE_NAME,
});
// upload() queues the file; indexing runs in the background. Poll the
// item status until it is searchable so the first query has content.
const instance = this.env.AI_SEARCH.get(INSTANCE_NAME);
const { id } = await instance.items.upload(
"getting-started.md",
SEED_DOC,
);
let info = await instance.items.get(id).info();
while (info.status === "queued" || info.status === "running") {
await new Promise((resolve) => setTimeout(resolve, 2_000));
info = await instance.items.get(id).info();
}
} catch {
// intentional fallback, nothing to handle
}
this.ready = true;
}
// Runs on every chat message: make sure the instance exists, then stream a
// tool-using response.
async onChatMessage() {
await this.ensureInstance();
// The agent exposes AI Search's search() as a tool instead of using AI
// Search's own chat model, so this model must support function calling to
// decide when to search and drive the tool calls.
const ai = createAI({ binding: this.env.AI });
const result = streamText({
model: ai("@cf/zai-org/glm-5.2"),
system:
"You are a support assistant. Use search_knowledge_base to find " +
"relevant content before answering, and cite what you use.",
// this.messages is the stored chat history; convert it to the format
// the model expects.
messages: await convertToModelMessages(this.messages),
tools: {
search_knowledge_base: tool({
description: "Search the knowledge base for relevant content.",
inputSchema: z.object({
query: z.string().describe("The user's question or search terms"),
}),
// Hybrid search runs by default because the instance indexes
// both vectors and keywords.
execute: async ({ query }) => {
const instance = this.env.AI_SEARCH.get(INSTANCE_NAME);
return await instance.search({
query,
ai_search_options: { retrieval: { max_num_results: 5 } },
});
},
}),
save_resolution: tool({
description:
"Save a resolved answer to the knowledge base for reuse.",
inputSchema: z.object({
title: z.string().describe("Short descriptive title"),
content: z.string().describe("The resolution to save"),
}),
// upload() returns as soon as the file is queued; indexing then
// finishes in the background.
execute: async ({ title, content }) => {
const instance = this.env.AI_SEARCH.get(INSTANCE_NAME);
const item = await instance.items.upload(`${title}.md`, content);
return { key: item.key, status: item.status };
},
}),
},
// Cap the tool-call loop so the agent cannot run tools indefinitely.
stopWhen: stepCountIs(5),
});
// Stream the reply, including any tool activity, back to the client.
return result.toUIMessageStreamResponse();
}
}
export default {
async fetch(request, env) {
// Route the request to the matching agent instance, keyed by the URL.
return (
(await routeAgentRequest(request, env)) ||
new Response("Not found", { status: 404 })
);
},
};import { AIChatAgent } from "@cloudflare/ai-chat";
import { routeAgentRequest } from "agents";
import { createAI } from "agents/models/ai-sdk";
import { streamText, convertToModelMessages, tool, stepCountIs } from "ai";
import { z } from "zod";
const INSTANCE_NAME = "knowledge-base";
const SEED_DOC = `# Getting started
AI Search indexes your content so an agent can retrieve it at query time.`;
// AIChatAgent stores the conversation history and calls onChatMessage() once
// for each user message.
export class SearchAgent extends AIChatAgent {
// Guard so the one-time instance setup runs only once per running agent.
private ready = false;
// Create the agent's instance, which uses hybrid search by default, then seed
// it so the first query has content.
private async ensureInstance() {
if (this.ready) return;
try {
await this.env.AI_SEARCH.create({
id: INSTANCE_NAME,
});
// upload() queues the file; indexing runs in the background. Poll the
// item status until it is searchable so the first query has content.
const instance = this.env.AI_SEARCH.get(INSTANCE_NAME);
const { id } = await instance.items.upload(
"getting-started.md",
SEED_DOC,
);
let info = await instance.items.get(id).info();
while (info.status === "queued" || info.status === "running") {
await new Promise((resolve) => setTimeout(resolve, 2_000));
info = await instance.items.get(id).info();
}
} catch {
// intentional fallback, nothing to handle
}
this.ready = true;
}
// Runs on every chat message: make sure the instance exists, then stream a
// tool-using response.
async onChatMessage() {
await this.ensureInstance();
// The agent exposes AI Search's search() as a tool instead of using AI
// Search's own chat model, so this model must support function calling to
// decide when to search and drive the tool calls.
const ai = createAI({ binding: this.env.AI });
const result = streamText({
model: ai("@cf/zai-org/glm-5.2"),
system:
"You are a support assistant. Use search_knowledge_base to find " +
"relevant content before answering, and cite what you use.",
// this.messages is the stored chat history; convert it to the format
// the model expects.
messages: await convertToModelMessages(this.messages),
tools: {
search_knowledge_base: tool({
description: "Search the knowledge base for relevant content.",
inputSchema: z.object({
query: z.string().describe("The user's question or search terms"),
}),
// Hybrid search runs by default because the instance indexes
// both vectors and keywords.
execute: async ({ query }) => {
const instance = this.env.AI_SEARCH.get(INSTANCE_NAME);
return await instance.search({
query,
ai_search_options: { retrieval: { max_num_results: 5 } },
});
},
}),
save_resolution: tool({
description:
"Save a resolved answer to the knowledge base for reuse.",
inputSchema: z.object({
title: z.string().describe("Short descriptive title"),
content: z.string().describe("The resolution to save"),
}),
// upload() returns as soon as the file is queued; indexing then
// finishes in the background.
execute: async ({ title, content }) => {
const instance = this.env.AI_SEARCH.get(INSTANCE_NAME);
const item = await instance.items.upload(`${title}.md`, content);
return { key: item.key, status: item.status };
},
}),
},
// Cap the tool-call loop so the agent cannot run tools indefinitely.
stopWhen: stepCountIs(5),
});
// Stream the reply, including any tool activity, back to the client.
return result.toUIMessageStreamResponse();
}
}
export default {
async fetch(request: Request, env: Env) {
// Route the request to the matching agent instance, keyed by the URL.
return (
(await routeAgentRequest(request, env)) ||
new Response("Not found", { status: 404 })
);
},
} satisfies ExportedHandler<Env>;this.env.AI_SEARCH.get(INSTANCE_NAME) 是同步的,并会惰性解析。它不会创建实例,因此 ensureInstance 会先创建它。要在一次调用中搜索多个实例,请使用带有 ai_search_options.instance_ids 的 namespace 级搜索。请参阅 Namespaces。
search_knowledge_base 工具会在实例上调用 search()。由于该实例同时为向量和关键词建立索引,检索默认使用混合搜索。
save_resolution 工具会调用 items.upload(),将文档上传到内置存储并排队等待索引。该调用会很快返回,内容会在后台索引完成后变为可搜索。上传同名文件会覆盖并重新索引它。
生成类型并启动开发服务器:
npx wrangler types
npm run devAIChatAgent 通过 WebSocket 使用其聊天协议,因此应通过聊天客户端驱动它,而不是使用普通的 curl 请求。最快的方法是将使用 Agents SDK useAgentChat hook 构建的 UI 指向本地服务器。
发送类似 How do I get started? 的消息。在第一条消息时,智能体会创建实例并写入种子内容,因此第一条响应可能需要一两分钟,等待种子文档完成索引。
出现以下情况即表示集成有效:
wrangler dev日志显示对/agents/search-agent/<name>的请求,随后在回复前运行了search_knowledge_base工具。- 智能体的回答基于种子内容并引用它,而不是泛泛作答。
使用你的 Cloudflare 账户登录:
npx wrangler login部署 Worker,使其可在 Internet 上访问:
npx wrangler deploy