只需5个步骤即可构建基础聊天代理:
- environmental preparation:安装Node.js 16+和npm,运行
npm create cloudflare@latest
Create a project - 编写代理类: New
worker.ts
文件,继承Agent基类并实现onRequest
Methods:class ChatAgent extends Agent {
async onRequest(req) {
const msg = await req.text();
return new Response(`AI回复:${msg}`);
}
} - local test: Run
npm run dev
启动开发服务器,用Postman发送测试请求 - Deployment goes live: Implementation
npx wrangler@latest deploy
,按提示完成Cloudflare账户验证 - 接入应用:获取部署URL后,前端可通过fetch API或WebSocket与代理交互
进阶建议:在wrangler.toml
中配置OpenAI API密钥,将简单回显升级为智能对话。
This answer comes from the articleCloudflare Agents: building real-time interactive intelligences on edge networksThe