ARTICLE · INTELLIGENCE

战地情报 · 详情页

来自尧图项目组的一线实战观察与深度解析

CopilotKit × LlamaIndex:Shared State (Reading) 实战——让 Agent 读取前端菜谱表单状态并验证其 QA 契约

CopilotKit × LlamaIndex:Shared State (Reading) 实战——让 Agent 读取前端菜谱表单状态并验证其 QA 契约 CopilotKit × LlamaIndexShared State (Reading) 实战——让 Agent 读取前端菜谱表单状态并验证其 QA 契约【免费下载链接】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本文以 CopilotKit 仓库中 LlamaIndex 集成 showcase 的shared-state-read演示为对象完整讲解「Agent 只读前端共享状态」这一模式前端通过agent.setState把菜谱表单写入agent.state.recipeAgent 在每轮对话中读取该状态作答但不修改它。读完本篇你将掌握useAgent/setState/runAgent的调用链、初始状态播种seed技巧并拿到一份可执行的 QA 检查清单与 Playwright E2E 对照。演示定位与运行前提shared-state-read是 manifest.yaml 中注册的 demo 之一页面路由为/demos/shared-state-read对应的 QA 测试契约即 shared-state-read.md。该集成使用copilotkit/react-core/v2Agent 后端由 LlamaIndex 提供前端通过 Next.js 的/api/copilotkit路由代理到运行时。QA 文档声明了两项前提PrerequisitesDemo 已部署且可访问Agent 后端健康检查/api/health。从 manifest.yaml 的cli-start条目看该集成仓库的规范入口命令是npx copilotkitlatest init --framework llamaindex演示文件布局均以仓库根目录为基准文件职责page.tsx状态编排层CopilotKit容器、useAgent、建议项、setState写入recipe-card.tsx纯受控表单组件暴露data-testid供 E2E/QA 定位types.ts状态类型RecipeData/RecipeAgentState与初始数据INITIAL_RECIPEshared-state-read.spec.tsPlaywright E2E 用例镜像 QA 契约核心设计agent.state.recipe是唯一事实源page.tsx 顶部注释明确了两点设计决策单一事实源是agent.state.recipe表单是建立在其上的纯受控组件——每一次编辑都直接流入agent.setState({...})下一次渲染即反映结果该演示接线的 graph 是「无工具的默认中立 Agent」Agent 只读取菜谱、不做任何变更mutate因此 UI 是唯一事实源。页面骨架如下export default function SharedStateReadDemo() { return ( CopilotKit runtimeUrl/api/copilotkit agentshared-state-read div classNamemin-h-screen w-full bg-gray-50 div classNamemx-auto max-w-2xl px-4 py-8 md:py-12 Recipe / /div CopilotSidebar defaultOpen labels{{ modalHeaderTitle: AI Recipe Assistant }} / /div /CopilotKit ); }要点CopilotKit通过runtimeUrl/api/copilotkit指向 Next.js 路由代理的运行时agentshared-state-read指定默认 AgentCopilotSidebar设置defaultOpen与标题AI Recipe Assistant——这正是 QA 检查清单中「sidebar 默认打开、标题正确」两条检查项的来源。Recipe组件的状态编排逻辑function Recipe() { const { agent } useAgent({ agentId: shared-state-read, updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged], }); const { copilotkit } useCopilotKit(); // ... }useAgent的updates参数订阅了OnStateChanged状态变化与OnRunStatusChanged运行状态变化两类更新前者让表单随状态同步重渲染后者驱动agent.isRunning进而控制按钮的加载态。初始状态播种seedQA 检查清单要求页面首次加载即展示默认菜谱。实现方式是挂载时用useEffect播种一次// Seed the initial recipe into agent state once so the agent has // something to read on the first turn. useEffect(() { if (!(agent.state as RecipeAgentState | undefined)?.recipe) { agent.setState({ recipe: INITIAL_RECIPE } satisfies RecipeAgentState); } }, []); const recipe (agent.state as RecipeAgentState | undefined)?.recipe ?? INITIAL_RECIPE;两个细节值得注意判空后再setState避免覆盖已经存在的状态读取侧始终有?? INITIAL_RECIPE兜底首帧即使agent.state尚未就绪也不会渲染空白表单。初始菜谱数据与 QA 断言逐条对应types.ts 中定义了完整类型与初始值export interface RecipeData { title: string; skill_level: SkillLevel; cooking_time: CookingTime; special_preferences: string[]; ingredients: Ingredient[]; instructions: string[]; } export interface RecipeAgentState { recipe: RecipeData; } export const INITIAL_RECIPE: RecipeData { title: Make Your Recipe, skill_level: SkillLevel.INTERMEDIATE, cooking_time: CookingTime.FortyFiveMin, special_preferences: [], ingredients: [ { icon: , name: Carrots, amount: 3 large, grated }, { icon: , name: All-Purpose Flour, amount: 2 cups }, ], instructions: [Preheat oven to 350°F (175°C)], };这些值与 QA 文档「Initial Recipe State」小节一一对应标题Make Your Recipe、时长下拉默认45 min、难度默认Intermediate、默认配料 Carrots3 large, grated与 All-Purpose Flour2 cups、默认步骤Preheat oven to 350 F。SkillLevelBeginner/Intermediate/Advanced、CookingTime5/15/30/45/60 min与SpecialPreferencesHigh Protein、Low Carb、Spicy、Budget-Friendly、One-Pot Meal、Vegetarian、Vegan均为 TypeScript 枚举前后端以类型约束共享同一份状态结构demo 的 README.md 概括为state 以共享的类型化 schema 在前后端之间定义Agent 无需前端额外发送上下文即可回答 UI 状态相关问题。UI 交互层纯受控表单与>const update (partial: PartialRecipeData) { onChange({ ...recipe, ...partial }); };而page.tsx侧的handleChange直接写入 Agent 状态const handleChange (next: RecipeData) { agent.setState({ recipe: next } satisfies RecipeAgentState); };这意味着 QA「Recipe Editing (Local State)」小节的每一条——改标题、改难度、改时长、勾选 Dietary 选项如 Vegetarian、「 Add Ingredient」新增空行、编辑/删除配料、「 Add Step」新增/删除步骤——其本质都是同一条链路控件onValueChange/onChange→update(partial)→onChange→agent.setState→OnStateChanged触发重渲染。组件为 E2E 预埋了稳定的定位契约与 QA 文档引用的data-testid一致testid位置recipe-card表单根节点add-ingredient-button“ Add Ingredient” 按钮ingredients-container/ingredient-card配料容器 / 单个配料行instructions-container步骤容器improve-button“Improve with AI” 按钮加载态由isLoading即agent.isRunning驱动按钮在加载期间disabled并显示Spinner “Please Wait...”这正是 QA「Error Handling」中「Improve with AI 按钮在加载时被禁用/置为 Please Wait...」检查项的实现依据。Agent 读取前端状态建议项与 runAgentQA 的「Suggestions」小节要求展示三个建议项其实现是useConfigureSuggestionsuseConfigureSuggestions({ suggestions: [ { title: Create Italian recipe, message: Create a delicious Italian pasta recipe., }, { title: Make it healthier, message: Make the recipe healthier with more vegetables., }, { title: Suggest variations, message: Suggest some creative variations of this recipe., }, ], available: always, });点击建议项即向 Agent 发送对应message。QA 的「Agent Reads Frontend State」小节要求先手动编辑菜谱改标题、加配料再询问 “What recipe am I making?”并验证回复引用了当前菜谱状态——因为每次编辑都已写入agent.state.recipeAgent 每轮都能读到最新值。“Improve with AI” 按钮走的是编程式触发路径const handleImprove () { if (agent.isRunning) return; // 防止并发 run agent.addMessage({ id: crypto.randomUUID(), role: user, content: Improve the recipe, }); void copilotkit .runAgent({ agent }) .catch((err) console.error([shared-state-read] runAgent failed, err), ); };这里有两个值得借鉴的工程细节agent.isRunning守卫避免上一次 run 未结束时重复触发runAgent的 Promise 以console.error兜底捕获失败避免未处理的 rejection对应 QA「发送空消息应被妥善处理」「无控制台报错」的检查意图。只读变体的能力边界源码事实澄清需要特别注意 QA 文档中「AI-Powered Recipe Updates」小节点击 “Create Italian recipe” 后 Agent 更新菜谱、改动区域出现 ping 指示器从 page.tsx 的源码注释看本 demo 接线的 graph 是无工具的中立默认 AgentAgent 读取但不变更菜谱UI 是唯一事实源types.ts 开头也写明「theres no backend tool that mutates it」。因此在本只读变体中菜谱的实际变更只能来自用户本地编辑agent.setState链路Agent 的回复是基于当前状态的问答ping 指示器/状态回写等「Agent 改写 UI」行为属于shared-state-read-write演示的职责该 demo 同样注册于 manifest.yaml。QA 文档的这部分检查项可视为对 read/write 契约的通用描述在只读路由上验证时应以「Agent 回复正确引用当前状态」为准。完整 QA 检查清单可直接作为验收脚本以下清单完整继承自 shared-state-read.md按原文档结构组织1. Basic Functionality导航到 shared-state-read 演示页路由/demos/shared-state-read验证菜谱卡片表单加载data-testidrecipe-card验证 CopilotSidebar 默认打开标题为 AI Recipe Assistant通过侧边栏发送一条消息验证 Agent 有响应2. Feature-Specific ChecksInitial Recipe State标题输入框显示 Make Your Recipe烹饪时长下拉默认 45 min难度下拉默认 Intermediate默认配料展示Carrots (3 large, grated) 带 All-Purpose Flour (2 cups) 带 默认步骤展示 Preheat oven to 350 FSuggestionsCreate Italian recipe 建议项可见Make it healthier 建议项可见Suggest variations 建议项可见Recipe Editing (Local State)修改菜谱标题验证更新修改难度下拉验证更新修改烹饪时长下拉验证更新勾选 Dietary 选项如 Vegetarian验证已选中点击 Add Ingredientdata-testidadd-ingredient-button验证出现新空行编辑配料的名称与用量点击 x 按钮删除配料点击 Add Step验证出现新步骤行编辑步骤并验证保存点击 x 按钮删除步骤AI-Powered Recipe UpdatesuseAgent with shared state点击 Create Italian recipe 建议项验证 Agent 对菜谱标题、配料、步骤的更新在只读变体上验证 Agent 回复正确引用状态状态回写见 read-write 变体验证 Improve with AI 按钮data-testidimprove-button加载期间变为 Please Wait...点击 Improve with AI验证 Agent 基于当前菜谱状态作答/增强Agent Reads Frontend State编辑菜谱改标题、加配料询问 What recipe am I making?验证 Agent 回复引用了当前菜谱状态3. Error Handling发送空消息应被妥善处理正常使用期间无控制台报错Improve with AI 按钮在加载期间被禁用预期结果与 E2E 自动化对照QA 文档给出的验收标准Expected Results菜谱卡片与侧边栏 3 秒内加载Agent 10 秒内响应菜谱状态在 UI 与 Agent 之间同步改动区域由指示器高亮适用于 read/write 场景无 UI 错误或布局破损。这些人工检查项在 shared-state-read.spec.ts 中有对应的 Playwright 断言spec 注释明确说明它「mirrors the QA contract in qa/shared-state-read.md」E2E 用例覆盖的 QA 检查项recipe card loads with default ingredients and the sidebar mountsrecipe-card可见超时 15s、AI Recipe Assistant 可见、ingredients-container与instructions-container可见starter suggestions render三个建议项按钮逐一toBeVisibleclicking Add Ingredient appends a new ingredient-card row点击add-ingredient-button后ingredient-card数量 1sending a sidebar message returns an assistant response输入 “What recipe am I making?” 回车后copilot-assistant-message在 30s 内出现对应「Agent 读取前端状态」检查项小结shared-state-read演示以最小代码量展示了 CopilotKit 共享状态「读」方向的标准形态useAgent订阅状态与运行状态变化、useEffect播种初始值、所有控件编辑经agent.setState写入单一事实源、useConfigureSuggestions提供对话入口、copilotkit.runAgent编程式触发并带isRunning守卫。配合 qa/shared-state-read.md 的验收清单与 tests/e2e/shared-state-read.spec.ts 的自动化断言这套「人工检查清单 E2E 镜像」的 QA 契约模式可直接复制到你的 Agent 集成验收流程中。【免费下载链接】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),仅供参考
RELATED READING

延伸阅读

更多一线实战笔记与深度复盘,助您持续精进