ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

CopilotKit × CrewAI 前端工具(Frontend Tools)实战:从 QA 检查单到 `useFrontendTool` 端到端实现

CopilotKit × CrewAI 前端工具(Frontend Tools)实战:从 QA 检查单到 `useFrontendTool` 端到端实现 CopilotKit × CrewAI 前端工具Frontend Tools实战从 QA 检查单到useFrontendTool端到端实现【免费下载链接】CopilotKitThe Frontend Stack for Agents Generative UI. React, Angular, Mobile, Slack, and more. Makers of the AG-UI Protocol项目地址: https://gitcode.com/GitHub_Trending/co/CopilotKit本篇技术指南以 CrewAICrews集成 showcase 中的frontend-tools演示为核心完整还原该功能的 QA 检查流程并逐层深入仓库源码前端如何通过useFrontendTool注册浏览器端工具、CrewAI Flow 后端如何下发工具声明与执行结果、Playwright E2E 又如何把人工检查单自动化。读完你将掌握在 CopilotKit v2 应用中让 Agent 直接操控页面 UI改变背景、查询本地数据等的完整实现与验证方法。一、这份 QA 检查单在验证什么qa/frontend-tools.md是一份针对Frontend Tools前端工具功能的人工验收清单它描述的核心场景非常典型用户用自然语言要求 Agent 修改页面 UIAgent 决定调用浏览器端注册的某个工具工具 handler 在前端本地执行并立即改变页面状态。完整检查步骤原文档全文导航到/demos/frontend-tools验证背景容器data-testidbackground-container可见发送消息Change the background to a blue-to-purple gradient验证背景样式已更新验证 Agent 确认了这次修改。这五步覆盖了一次前端工具交互的完整链路页面就绪 → 工具宿主可见 → 自然语言触发 → 副作用生效 → Agent 确认。它不检查聊天里说了什么花哨的话而是盯住页面真实状态变了没有这一可观察结果——这也是后面 Playwright 测试的设计哲学。注意实际实现中背景容器的data-testid为frontend-tools-background见 background.tsx检查单里的background-container是同一语义的别名你在按单验收时以页面 DOM 中实际的data-testidfrontend-tools-background为准。二、Demo 源码一次useFrontendTool注册的全过程该 demo 的页面入口是 page.tsx整段核心代码只有几十行却展示了前端工具的四个关键要素宿主组件、工具注册、参数 schema、handler 副作用。2.1 工具宿主一个可被 Agent 操纵的 Background 组件// src/app/demos/frontend-tools/background.tsx use client; export const DEFAULT_BACKGROUND #4f46e5; // 默认纯靛蓝indigo export function Background({ background, children }) { return ( div >// src/app/demos/frontend-tools/page.tsx节选 useFrontendTool({ name: change_background, description: Change the page background. Accepts any valid CSS background value — colors, linear or radial gradients, etc., parameters: z.object({ background: z .string() .describe(The CSS background value. Prefer gradients.), }), handler: async ({ background }) { setBackground(background); // 唯一的副作用更新 React state return { status: success }; // 结果回传给 Agent }, });拆解这四个字段就能理解 CopilotKit v2 前端工具的模型字段作用在本 demo 中的取值name工具的唯一标识Agent以及后端运行时靠它路由调用change_backgrounddescription向 LLM 描述工具能力边界直接影响模型是否决定调用明确允许纯色 / 线性渐变 / 径向渐变等合法 CSS background 值parameters基于 Zod 的参数 schema随工具声明一起下发到后端作为函数调用的参数约束background: string并提示优先用渐变handler浏览器端执行体返回结果会被回传给 Agent 继续对话调用setBackground更新页面返回{ status: success }页面其余部分把宿主 聊天组合起来Background包裹CopilotSidebar agentIdfrontend_tools defaultOpen /最外层由CopilotKit runtimeUrl/api/copilotkit agentfrontend_tools提供运行时。也就是说工具执行完全发生在浏览器但工具声明与调用决策由 Agent 驱动——这正是前端工具与普通后端工具的本质区别。2.3 提示词药丸降低 LLM 输入不确定性的配套设计demo 还通过 suggestions.ts 提供了三个建议消息suggestion pilluseConfigureSuggestions({ suggestions: [ { title: Sunset theme, message: Make the background a sunset gradient. }, { title: Forest theme, message: Switch to a deep green forest gradient. }, { title: Cosmic theme, message: Make it a navy → magenta cosmic gradient. }, ], available: always, });这些药丸把用户输入收敛为少数几个确定句式既提升演示体验也大幅降低了 LLM 生成随机提示词对 E2E 测试稳定性的影响下文会看到测试正是基于它们做确定性断言。三、后端视角CrewAI Flow 如何配合前端工具前端工具并非纯前端把戏工具调用指令来自 Agent。后端对应实现是 frontend_tool_flow.py并在 agent_server.py 中通过add_crewai_flow_fastapi_endpoint(app, frontend_tool_flow, /frontend-tools)注册为 FastAPI 端点前端runtimeUrl/api/copilotkit与之打通。这段 Flow 代码值得细读其中有三个与前端工具强相关的设计点SYSTEM_PROMPT ( You are a concise showcase assistant. When a supplied frontend tool can fulfill the users request, you MUST call it; never claim that you lack access and never substitute a prose answer. After the browser returns a tool result, summarize it briefly. )系统提示强制工具优先只要前端工具能满足用户请求必须调用禁止用文字敷衍。这直接保证了检查单第 3 步Change the background…能触发真正的工具调用而不是模型回答一段抱歉我做不到。工具声明来自运行时toolsself.state.copilotkit.actions or None——Agent 可用的工具清单由 CopilotKit 运行时注入即前端useFrontendTool注册的change_background声明会以 AG-UI actions 的形式出现在这里Flow 本身不重复定义工具。tool_choice 的策略切换当存在工具声明且最后一条消息来自用户时tool_choicerequired强制本次必须走工具否则回落auto。这意味着用户一发消息模型就会被引导着调用前端工具第二次对话轮携带工具结果时才允许自由总结——对应检查单第 5 步Agent 确认修改。前端工具结果不在后端伪造Flow 里明确注释不要在这里制造 tool result。流式的前端工具调用会直接结束本次 Flow 运行由 CopilotKit 在浏览器执行 handler并把权威结果在下一个请求中带回续跑。self.state.messages.append(response.choices[0].message)只保留消息本身。这就是浏览器拥有前端工具执行权这一架构决策的源码证据。四、从人工检查单到自动化Playwright E2E 如何逐条对应人工 QA 清单容易漏测仓库用 frontend-tools.spec.ts 把五步检查单完整自动化了。对照关系如下QA 检查单步骤对应自动化断言导航到/demos/frontend-toolstest.beforeEach中page.goto(/demos/frontend-tools)背景容器可见page.locator([data-testidfrontend-tools-background]).toBeVisible()且初始 inline style 含默认值#4f46e5提问改变背景点击 Sunset / Forest / Cosmic 药丸等价于发送自然语言提示词背景样式更新expect.poll轮询 inline style不再包含#4f46e5或匹配/linear-gradient\|radial-gradient/Agent 确认修改断言不依赖 LLM 文本而是以副作用为准见下4.1 断言策略测副作用不测模型措辞测试注释明确写出了设计哲学We assert on the observable side effect (inline style changes) rather than on any LLM-generated text.例如 Sunset 主题的断言await expect .poll(async () { const s (await bg.getAttribute(style)) ?? ; return /linear-gradient|radial-gradient/.test(s); }, { timeout: 45000 }) .toBe(true);为什么用 45 秒轮询而不是立即断言因为链路是药丸点击 → 提示词发给 Agent → CrewAI Flow 调 LLM → 模型决定调用change_background→ 声明回到浏览器 → handler 执行setBackground。整条链路耗时不定轮询poll正是对这种最终一致副作用的正确断言方式。4.2 前端工具与 aimock 夹具的关系测试还提到 aimock 特性对齐夹具feature-parity fixture覆盖了 sunset-themed gradient 提示词真实 LLM 则处理自由输入。这意味着该集成支持确定性夹具与真实模型两套运行模式夹具模式下工具调用由预录数据驱动便于 CI 稳定复现真实模型模式如 Railway 部署则走完整 LLM 决策。这也是为什么人工 QA 和自动化测试都可以放心依赖药丸句式。五、异步变体query_notes——前端工具的另一半能力frontend-tools是同步副作用的经典案例而 frontend-tools-async 演示了前端工具的异步 自定义渲染能力其 QA 检查单为导航到/demos/frontend-tools-async提问 Find my notes about project planning验证NotesCarddata-testidnotes-card随查询关键词渲染验证匹配的笔记n1、n5、n7出现在data-testidnotes-list中再问 Search my notes for auth验证结果更新。对应实现 frontend-tools-async/page.tsx 展示了两个新特性5.1 异步 handler纯客户端数据查询handler: async ({ keyword }) { await sleep(500); // 模拟本地 DB 往返延迟 const q keyword.toLowerCase(); const matches NOTES_DB.filter((n) n.title.toLowerCase().includes(q) || n.excerpt.toLowerCase().includes(q) || (n.tags ?? []).some((t) t.toLowerCase().includes(q)) ).slice(0, 5); // 最多返回 5 条 return { keyword, count: matches.length, notes: matches }; },NOTES_DB来自 fake-notes-db.ts是内存中的 7 条假笔记工具完全在浏览器内完成查询后端零参与。sleep(500)让加载态可见也顺带验证了异步路径的时序。5.2 render为工具结果定制 UI 卡片render: ({ args, result, status }) { const loading status ! complete; const parsed parseJsonResult{ keyword?: string; count?: number; notes?: Note[] }(result); return ( NotesCard loading{loading} keyword{args?.keyword ?? parsed.keyword ?? } notes{parsed.notes} / ); },render回调让前端工具不只是改个样式还能把工具返回的结构化结果画成专属组件。NotesCard 暴露data-testidnotes-card、notes-keyword、notes-list、note-n1…note-n7等一系列测试锚点加载中显示 Querying local notes DB...完成显示匹配数并逐条渲染标题、摘录和标签胶囊。对应的 frontend-tools-async.spec.ts 做了更彻底的验证断言关键词标题为Matching project planning、列表中出现note-n1/note-n5、auth 场景出现note-n2、reading 场景出现note-n4含 Book recommendations 与《Thinking Fast and Slow》等书目文本并包含一个反回归断言——通用模板文案不得误出现。最后一个测试甚至在同一线程里依次点击三个药丸验证每次点击都渲染出自己的 NotesCard这是对 aimock 多药丸 bug 的回归测试原 bug 是工具结果门控导致首轮夹具被跳过、卡片永不渲染。六、功能在集成中的定位与运行方式在 manifest.yaml 中frontend-tools与frontend-tools-async作为两个独立 demo 注册在interactivity交互性类别下- id: frontend-tools name: Frontend Tools (In-App Actions) description: Agent invokes client-side handlers registered with useFrontendTool route: /demos/frontend-tools - id: frontend-tools-async name: Frontend Tools (Async) description: useFrontendTool with an async handler route: /demos/frontend-tools-async同时manifest.yaml声明该集成整体具备frontend-tools、frontend-tools-async、hitl-in-app通过useFrontendTool实现的应用内人工审批弹窗等能力说明前端工具是这套 CrewAI 集成中应用内交互体系的基础设施。想本地体验该演示可按 manifest 提供的标准方式初始化并运行# 克隆官方 starter基于本集成模板 npx copilotkitlatest init --framework crewai-crews # 在仓库内直接运行本 showcase 则需要 # 1) 安装 Python 依赖含 copilotkit、crewai、litellm 与 ag_ui_crewai # 2) 配置 LLM 环境变量Flow 中使用 openai/gpt-5.4 等模型 # 3) 启动 FastAPI 后端与 Next.js 前端然后访问 /demos/frontend-tools进入页面后可依次按第一节的检查单人工验收本地起好 Playwright 后也可直接执行 frontend-tools.spec.ts 与 frontend-tools-async.spec.ts 完成自动化验收。七、小结把前端工具复用到你自己的页面回到frontend-tools这份 QA 检查单它的五步背后其实是一套可复用的最小模式任何希望Agent 能操纵我的页面的应用都可以照搬准备宿主用 React state 持有页面中 Agent 要操控的值把它渲染进带data-testid的容器注册工具useFrontendTool Zod schemadescription写清能力边界handler里只做前端副作用并返回结果提示引导用useConfigureSuggestions提供确定性提示词药丸后端放权CrewAI Flow 通过copilotkit_stream拿到运行时注入的 actions强制工具调用但不伪造工具结果把执行权留给浏览器以副作用验收人工 QA 看页面状态自动化 QA 用expect.poll轮询 DOM 副作用——两边盯住同一件事。从change_background改背景到query_notes的异步查询与自定义卡片渲染这套机制把LLM 决策与页面执行优雅地分层模型负责决定浏览器负责动手。当你需要 Agent 操作本地数据、弹出审批、切换主题或渲染结构化结果时frontend-tools 与 frontend-tools-async 两份源码就是可直接参考的完整范本。【免费下载链接】CopilotKitThe Frontend Stack for Agents Generative UI. React, Angular, Mobile, Slack, and more. Makers of the AG-UI Protocol项目地址: https://gitcode.com/GitHub_Trending/co/CopilotKit创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表