代理启动器
在Cloudflare上构建AI聊天代理的入门模板,由 代理SDK.
使用Workers AI(无需API密钥),以及用于天气、时区检测、经批准的计算和任务调度的工具。
快速开始
npx create-cloudflare@latest --template cloudflare/agents-starter
cd agents-starter
npm install
npm run dev打开 http://localhost:5173 看看你的经纪人在行动。
尝试以下提示以查看不同功能:
- “巴黎的天气怎么样?” --服务器端工具(自动运行)
- “我所在的时区是什么?” --客户端工具(浏览器提供答案)
- **“计算5000\*3”** --审批工具(运行前会询问您)
- “5分钟后提醒我休息一下” --日程安排
项目结构
src/
server.ts # Chat agent with tools and scheduling
app.tsx # Chat UI built with Kumo components
client.tsx # React entry point
styles.css # Tailwind + Kumo styles包含什么
- AI聊天 --由Workers AI通过
AIChatAgent - 三种工具模式 --服务器端自动执行、客户端(浏览器)和人工循环审批
- 调度 --一次性、延迟和重复(cron)任务
- 推理显示 --显示模型思维在流动时,完成时会崩溃
- 调试模式 --在标头中切换以检查每条消息的原始消息JSON
- Kumo UI --Cloudflare的暗/亮模式设计系统
- 实时 --具有自动重新连接和消息持久性的WebSocket连接
让它成为你自己的
命名您的项目
更新中的名称 package.json 和 wrangler.jsonc --the name 在 wrangler.jsonc 成为您部署的Worker的URL(..workers.dev).
更改系统提示
编辑 system 字符串在 server.ts 给你的代理人一个不同的个性或重点领域。这是你能做出的最有影响力的改变。
用真实的工具替换演示工具
初学者附带演示工具(getWeather 返回随机数据, calculate 做基本算术)。用实际实现替换它们:
// In server.ts, replace a demo tool with a real API call:
getWeather: tool({
description: "Get the current weather for a city",
inputSchema: z.object({ city: z.string() }),
execute: async ({ city }) => {
const res = await fetch(`https://api.weather.example/${city}`);
return res.json();
}
}),添加您自己的工具
向中添加新工具 tools 对象在 server.ts有三种模式:
// Auto-execute: runs on the server, no user interaction
myTool: tool({
description: "...",
inputSchema: z.object({ /* ... */ }),
execute: async (input) => { /* return result */ }
}),
// Client-side: no execute function, browser provides the result
// Handle it in app.tsx via the onToolCall callback
browserTool: tool({
description: "...",
inputSchema: z.object({ /* ... */ })
}),
// Approval: add needsApproval to gate execution
sensitiveTool: tool({
description: "...",
inputSchema: z.object({ /* ... */ }),
needsApproval: async (input) => true, // or conditional logic
execute: async (input) => { /* runs after approval */ }
}),自定义计划任务行为
当预定任务启动时, executeTask 在服务器上运行。它完成工作,然后使用 this.broadcast() 通知已连接的客户端(在UI中显示为吐司通知)。用你自己的逻辑替换它:
async executeTask(description: string, task: Schedule) {
// Do the actual work
await sendEmail({ to: "user@example.com", subject: description });
// Notify connected clients
this.broadcast(
JSON.stringify({ type: "scheduled-task", description, timestamp: new Date().toISOString() })
);
}为什么broadcast()而不是saveMessages()? 注入聊天历史记录可以使AI将通知视为新的上下文,并在循环中重新触发相同的任务。broadcast()发送客户端与对话分开显示的一次性事件。
删除日程安排
如果你不需要日程安排,请删除 scheduleTask, getScheduledTasks,以及 cancelScheduledTask 从工具对象来看 executeTask 方法和时间表相关的导入(getSchedulePrompt, scheduleSchema, Schedule, generateId).
在聊天消息之外添加状态
使用 this.setState() 和 this.state 用于与所有连接的客户端同步的实时状态。看 存储和同步状态.
添加可调用方法
将代理方法公开为客户端可以直接调用的类型化RPC:
import { callable } from "agents";
export class ChatAgent extends AIChatAgent {
@callable()
async getStats() {
return { messageCount: this.messages.length };
}
}
// Client-side:
const stats = await agent.call("getStats");看 可调用方法.
连接到MCP服务器
从MCP服务器添加外部工具:
async onChatMessage(onFinish, options) {
// Connect to an MCP server
await this.mcp.connect("https://my-mcp-server.example/sse");
const result = streamText({
// ...
tools: {
...myTools,
...this.mcp.getAITools() // Include MCP tools
}
});
}看 MCP客户API.
使用不同的AI模型提供者
起动机使用 工人AI 默认情况下(不需要API密钥)。要使用其他提供程序,请执行以下操作:
开放人工智能
npm install @ai-sdk/openai// In server.ts, replace the model:
import { openai } from "@ai-sdk/openai";
// Inside onChatMessage:
const result = streamText({
model: openai("gpt-5.2")
// ...
});创建一个 .env 使用API密钥文件:
OPENAI_API_KEY=your-key-hereAnthropic
npm install @ai-sdk/anthropicimport { anthropic } from "@ai-sdk/anthropic";
const result = streamText({
model: anthropic("claude-sonnet-4-20250514")
// ...
});创建一个 .env 使用API密钥文件:
ANTHROPIC_API_KEY=your-key-here部署
npm run deploy您的代理在Cloudflare的全球网络上运行。消息在SQLite中持久,流在断开连接时恢复,代理在空闲时休眠。
了解更多
许可证
麻省理工学院
