十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

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

CopilotKit React Core 实战指南:用 Headless Hooks 与预构建组件构建 AI 助手与生成式 UI

CopilotKit React Core 实战指南:用 Headless Hooks 与预构建组件构建 AI 助手与生成式 UI CopilotKit React Core 实战指南用 Headless Hooks 与预构建组件构建 AI 助手与生成式 UI【免费下载链接】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/react-core是 CopilotKit 前端技术栈中面向 React 的核心包它同时提供两套能力以useCopilotChat、useCopilotAction、useCoAgent为代表的 Headless Hooks无头 API完全控制消息流、动作注册与 Agent 状态以及以CopilotPopup、CopilotSidebar等为代表的预构建聊天组件开箱即用、可深度定制样式与子组件。读完本文你将掌握如何基于该包在应用内集成与 LangGraph 等后端 Agent 双向共享状态的 CoAgent、注册支持流式渲染的 Frontend Action、通过renderAndWaitForResponse实现带人工审批的 Human-in-the-Loop 流程以及如何用copilotKitCustomizeConfig定制中间状态流式输出。本文以 packages/react-core/README.md 为主线并结合仓库源码对每个 API 的底层行为做深入佐证。为什么选择 CopilotKit React Core根据 packages/react-core/README.md 中的定位该包的核心卖点可以归纳为五点分钟级集成通过官方 CLI 即可快速搭建起一个可用的 Copilot 应用骨架框架无关既支持 React / Next.js也与 AG-UI 协议及 Angular、Vue、移动端等其余 CopilotKit 包协作生产级 UI既可以使用可定制化的预构建组件也可以用 Headless UI 完全自建界面内置安全提供提示注入Prompt Injection防护能力开源透明MIT 协议见 packages/react-core/package.json 的license字段社区驱动迭代。从 packages/react-core/package.json 的依赖可见该包是 CopilotKit 全栈的核心枢纽它依赖ag-ui/client/ag-ui/coreAG-UI 协议客户端、copilotkit/core核心运行时、copilotkit/runtime-client-gqlGraphQL 运行时客户端、copilotkit/a2ui-renderer与copilotkit/web-components并直接内置了radix-ui/react-*系列 UI 原语与react-markdown等渲染能力。其 React 版本支持react ^18 || ^19见 peerDependencies并在exports中提供了copilotkit/react-core、copilotkit/react-core/v2与copilotkit/react-core/v2/headless等多个入口见 packages/react-core/package.json。快速开始两分钟接入安装在 React 或 Next.js 项目中安装核心包与运行时依赖npm install copilotkit/react-core copilotkit/runtime-client-gql # 若使用 React 19请确保同时安装 react19 / react-dom19包内所有 Hooks 与组件都需要被CopilotKitProvider 包裹。该 Provider 位于 packages/react-core/src/v1-deprecated/components/copilot-provider/copilotkit.tsx负责建立与运行时Runtime的连接、管理 Agent 注册表与消息上下文。最小接入结构如下import { CopilotKit } from copilotkit/react-core; export default function App() { return ( CopilotKit runtimeUrl/api/copilotkit YourApp / /CopilotKit ); }其中runtimeUrl指向你的 CopilotKit 后端运行时地址例如 Next.js API Route 或独立部署的 LangGraph FastAPI 服务。两种开发路线README 明确给出了两条互补的路线Headless API 预构建组件用useCopilotChat()获取底层状态与控制函数用CopilotPopup等组件直接渲染出聊天窗口In-App CoAgent 集成用useCoAgent/useAgent让前端组件与后端 Agent 共享状态实现应用内协作式 Copilot。下面分别深入两条路线。Headless APIuseCopilotChat完全控制消息流useCopilotChat是面向无头Headless聊天的轻量级 React Hook用于程序化地发送消息、控制预构建组件或执行后台 AI 操作。其实现位于 packages/react-core/src/v1-deprecated/hooks/use-copilot-chat.ts。典型用法const { visibleMessages, appendMessage, setMessages, ... } useCopilotChat();appendMessage接收一个消息对象并触发 Agent 运行。使用 AG-UI 消息格式时需配合copilotkit/runtime-client-gql中的TextMessage与MessageRoleimport { TextMessage, MessageRole } from copilotkit/runtime-client-gql; const { appendMessage } useCopilotChat(); // 不依赖聊天 UI 的程序化发消息 const handleSendMessage async (content: string) { await appendMessage( new TextMessage({ role: MessageRole.User, content, }) ); };返回值速查根据 use-copilot-chat.ts 的源码该 Hook 实际返回以下成员属性类型说明visibleMessagesDeprecatedGqlMessage[]旧版非 AG-UI 格式的可见消息数组仅供兼容场景使用appendMessage(message, options?) Promisevoid追加一条消息并运行 Agent是公开的 v1 程序化发送入口reloadMessages(messageId: string) Promisevoid按消息 ID 重新生成Regenerate对应回复stopGeneration() void停止当前正在进行的生成reset() void清空全部消息并彻底重置聊天状态isLoadingboolean是否正在生成回复runChatCompletion() PromiseMessage[]手动触发一次聊天补全用于高级场景mcpServersMCPServerConfig[]MCPModel Context Protocol服务器配置列表setMcpServers(servers) void更新 MCP 服务器配置以扩展上下文能力从源码可以看出该公开返回类型通过OmitUseCopilotChatReturnInternal, ...屏蔽了messages、sendMessage、suggestions、interrupt、setMessages、deleteMessage等内部成员见 use-copilot-chat.ts保证对外 API 的稳定与精简。注意useCopilotChat属于 v1 API。仓库源码的迁移说明指出v2 中对应的替代是useAgent见 use-copilot-chat.ts。源码文件头部标注了V1 SDK DEPRECATED. USE V2 INSTEAD新项目建议直接使用 v2 的useAgent。v2 中的 Headless 入口useAgentv2 入口为copilotkit/react-core/v2其导出见 packages/react-core/src/v2/index.ts其中核心 Hook 是useAgent实现在 packages/react-core/src/v2/hooks/use-agent.tsx。它有且仅有两种合法调用形态import { useAgent, UseAgentUpdate } from copilotkit/react-core/v2; // 形态一绑定共享 Agent线程来自聊天配置 const { agent, isReady } useAgent({ agentId: basic_agent }); // 形态二将私有代理 Agent 绑定到指定线程三个参数必须同时给出 const { agent } useAgent({ agentId: chat-1, // 本地注册 id不能与既有 Agent 冲突 runtimeAgentId: basic_agent, // 实际路由到的运行时 Agent threadId: thread-42, // 该 Hook 专属的线程 });源码对形态二做了严格的运行时校验见 use-agent.tsx单独传threadId而不传runtimeAgentId、单独传runtimeAgentId而不传threadId、或传了runtimeAgentId却不显式给出agentId都会抛出明确错误。其设计动机在于按agentId解析到的是共享单例若直接对它写入线程 id两个useAgent调用会互相覆盖线程因此必须注册一个路由到runtimeAgentId的私有代理通过copilotkit.registerProxiedAgent再把线程固定到该私有实例上。useAgent还支持通过updates订阅特定事件、通过throttleMs控制高频流式更新下的重渲染节流默认继承 Provider 的defaultThrottleMs0表示关闭节流详见 use-agent.tsx。预构建组件CopilotPopup与深度定制README 展示了预构建组件的典型用法CopilotPopup instructions{You are assisting the user as best as you can. Answer in the best way possible given the data you have.} labels{{ title: Popup Assistant, initial: Need any help? }} /CopilotPopup实现在 packages/react-core/src/v2/components/chat/CopilotPopup.tsx它本质上是CopilotChat的一种弹窗形态封装将CopilotChatView替换为CopilotPopupView并支持header、toggleButton、width、height、clickOutsideToClose、defaultOpen等弹窗壳属性。源码注释揭示了一个实现细节宽高等属性通过PopupShellPropsContext传递而不是作为覆盖组件的useMemo依赖从而避免在每次拖拽调整大小时因组件函数身份变化导致整个聊天子树被卸载重挂重挂会重置滚动位置并触发initialsmooth从头滚动见 CopilotPopup.tsx。定制路径CSS 覆盖通过组件的 CSS 类名体系覆盖默认样式子组件插槽SlotsCopilotChat系列组件在 packages/react-core/src/v2/components/chat/ 下拆分了大量可替换的 Slot 组件如CopilotChatInput、CopilotChatMessageView、CopilotChatSuggestionView等可逐个传入自定义子组件完全自建只用useCopilotChat/useAgent等 Headless Hooks 配合任意 UI 库实现自己的聊天界面。生成式 UI 与 Frontend ActionsuseCopilotAction允许 AI 在对话过程中按需调用你注册的前端动作并实时渲染自定义 UI全程支持流式传输。其实现位于 packages/react-core/src/v1-deprecated/hooks/use-copilot-action.ts。核心用法表格追加示例README 中的电子表格示例非常典型useCopilotAction({ name: appendToSpreadsheet, description: Append rows to the current spreadsheet, parameters: [ { name: rows, type: object[], attributes: [ { name: cells, type: object[], attributes: [{ name: value, type: string }], }, ], }, ], render: ({ status, args }) Spreadsheet data{canonicalSpreadsheetData(args.rows)} /, handler: ({ rows }) setSpreadsheet({ ...spreadsheet, rows: [...spreadsheet.rows, ...canonicalSpreadsheetData(rows)], }), });这里的三个关键配置namedescription告诉 LLM 何时该调用该动作、动作的作用是什么description越详细越能被 LLM 精准触发parameters支持从字符串、数字等基本类型到对象、数组的嵌套结构对象用attributes描述内部字段CopilotKit 会自动推断参数类型带来类型安全与自动补全render在聊天流中渲染自定义 UI生成式 UIstatus与args分别表示执行状态和解析后的参数handler真正执行业务逻辑并返回值例如把新行合并进表格状态。三种动作模式与底层分发源码 use-copilot-action.ts 中的getActionConfig展示了 Hook 的多态分发逻辑render模式仅渲染动作不含handler或不属于 HITL/前端工具时走useRenderToolCallHITL 模式动作提供renderAndWaitForResponse或旧别名renderAndWait时走useHumanInTheLoop——渲染 UI 并等待用户通过respond()给出确认/取消frontend 模式动作含handler或显式available: enabled | remote时走useFrontendTool注册为前端工具。值得注意的实现细节useCopilotAction使用注册 由渲染器组件实际调用 Hook的模式来规避 React 的 Rules of Hooks 限制条件性调用 Hook 会破坏调用栈跟踪。它将首次渲染时的动作配置存在 state 中若后续渲染发现动作类型发生变化例如从render变成hitl会直接抛出Action configuration changed between renders见 use-copilot-action.ts。此外还支持catch-all 动作将name设为*即可在render中兜底渲染所有未在前端定义的动作。v2 迁移提示useCopilotAction的 v2 替代是useFrontendTool源码迁移说明见 use-copilot-action.ts。与 LangGraph 集成In-App CoAgent 共享状态README 的第二条主线是把 CopilotKit 与 LangGraph Agent 深度集成让应用与 Agent 之间双向共享状态CoAgent。读取与更新 Agent 状态useCoAgent// Share state between app and agent const { agentState } useCoAgent({ name: basic_agent, initialState: { input: NYC }, });useCoAgent的实现位于 packages/react-core/src/v1-deprecated/hooks/use-coagent.ts是 v2useAgent的薄兼容包装。其返回对象包含name当前 Agent 名、nodeName当前 LangGraph 节点名、threadId线程 ID、state/setStateAgent 状态的读写、running是否运行中、start/stop启动与停止、run重新运行映射到 v2 的runAgent()。状态是双向响应式的前端调用setState会同步到 AgentAgent 运行中的状态变更也会实时反映到 UI。参数方面支持name必填、initialState初始状态、以及state/setState两个用于接入外部状态管理如 Redux、Zustand的托管参数见 use-coagent.ts。Agentic 生成式 UIuseCoAgentStateRender// agentic generative UI useCoAgentStateRender({ name: basic_agent, render: ({ state }) WeatherDisplay {...state.final_response} /, });useCoAgentStateRender实现见 packages/react-core/src/v1-deprecated/hooks/use-coagent-state-render.ts允许你根据 Agent 的实时状态在聊天中渲染 UI 或文本组件非常适合展示 Agent 运行过程中的中间进度。可选参数nodeName可以限定只订阅某个特定 LangGraph 节点的状态更新。v2 迁移提示v2 中该能力被简化——用useAgent({ updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged] })订阅状态与运行状态变化然后直接渲染agent.state即可v2 使用普通 React 渲染而非注册聊天专用渲染器迁移说明见 use-coagent-state-render.ts。Human in the Loop人工审批当动作需要用户确认后才能执行时使用renderAndWaitForResponse渲染审批 UI并通过respond()把用户决定回传给 AgentuseCopilotAction({ name: email_tool, parameters: [ { name: email_draft, type: string, description: The email content, required: true, }, ], renderAndWaitForResponse: ({ args, status, respond }) { return ( EmailConfirmation emailContent{args.email_draft || } isExecuting{status executing} onCancel{() respond?.({ approved: false })} onSend{() respond?.({ approved: true, metadata: { sentAt: new Date().toISOString() }, }) } / ); }, });要点renderAndWaitForResponse的回调入参为{ args, status, respond }status executing表示 Agent 正在等待响应此时应禁用或标识操作按钮respond支持同步返回审批结果也可携带自定义metadata如上面的sentAt时间戳传回后端实现完整的审计留痕该模式在源码中由useHumanInTheLoop承接见 use-copilot-action.ts。中间状态流式输出copilotKitCustomizeConfig当 Agent 运行时间较长时让用户看到中间推理状态能显著提升体验。README 给出了 LangGraph同时支持 JS 与 Python 版的配置方式const modifiedConfig copilotKitCustomizeConfig(config, { emitIntermediateState: [ { stateKey: outline, tool: set_outline, toolArgument: outline, }, ], }); const response await ChatOpenAI({ model: gpt-4o }).invoke(messages, modifiedConfig);这段代码的作用是当 Agent 调用set_outline工具时把outline这个状态键的中间值流式发送给前端。emitIntermediateState数组中的每个条目定义了三者映射关系stateKey需要流出的状态键名对应 Agent 内部状态字段tool触发流出的工具名Agent 调用该工具的瞬间触发状态快照toolArgument该工具的哪个参数值会被当作状态值发出。配合前文的useCoAgentStateRender前端即可在聊天流中实时渲染大纲、搜索结果等中间产物形成边跑边展示的 Agentic 体验。深入源码模块组织与测试保障源码结构一览copilotkit/react-core的源码组织在 packages/react-core/src/ 下分为两大区块v1-deprecated/v1 公开 APIuseCopilotChat、useCopilotAction、useCoAgent、useCoAgentStateRender、CopilotKitProvider 等源码头部均带V1 SDK DEPRECATED. USE V2 INSTEAD提示用于向后兼容v2/新一代 API按职责细分为hooks/useAgent、useFrontendTool、useHumanInTheLoop、useInterrupt、useAttachments、useThreads、useMemories、useSuggestions等、components/chat/CopilotChat及其 Slot 子组件族、providers/CopilotKitProvider、CopilotChatConfigurationProvider、a2ui/A2UIMessageRenderer与types/。测试与质量保障该包在 packages/react-core/src/tests/、packages/react-core/src/v1-deprecated/ 与 packages/react-core/src/v2/ 的__tests__目录下维护了大量测试覆盖了核心行为例如useCopilotAction的 e2e 测试use-copilot-action.e2e.test.tsx与 HITL catch-all 测试useCoAgentStateRender的单元与 e2e 测试use-coagent-state-render.test.tsxv2CopilotChat系列的 e2e 测试packages/react-core/src/v2/components/chat/tests/headless-exports.test.ts校验v2/headless子路径导出纯净性不含样式等副作用配合scripts/assert-headless-purity.mjs保障无头 API 的树摇友好性相关脚本见 packages/react-core/package.json。运行测试与类型检查的命令pnpm --filter copilotkit/react-core test # 运行 vitest 脚本测试 pnpm --filter copilotkit/react-core check-types # 类型检查实战组合建议把上述能力拼装成一个完整的应用内 AI 助手推荐的组合方式是挂载 Provider用CopilotKit runtimeUrl{...}包裹应用选择壳层需要常驻助手用CopilotSidebar需要轻量入口用CopilotPopup需要完全自控用 Headless Hooks 自定义 UI注册动作用useCopilotAction/useFrontendTool注册表格写入、数据查询等业务动作配合render实现生成式 UI接 Agent 状态用useCoAgent/useAgent共享状态用useCoAgentStateRender或 v2 的useAgent({ updates })渲染中间进度加审批环节对高影响操作发邮件、付款、删除使用renderAndWaitForResponserespond实现 Human-in-the-Loop优化流式体验用copilotKitCustomizeConfig的emitIntermediateState把长任务的关键中间态推送到前端。小结copilotkit/react-core在 CopilotKit 全栈中扮演前端大脑的角色向下对接 AG-UI 协议与运行时客户端向上同时提供高抽象度的预构建聊天组件和低抽象的 Headless Hooks。通过本文涉及的useCopilotChat、useCopilotAction、useCoAgent、useCoAgentStateRender、copilotKitCustomizeConfig以及 v2 的useAgent你可以在自己的 React 应用中搭建出具备生成式 UI、双向状态共享与人工审批的深度集成式 AI 助手。若需要继续深入可阅读仓库内的 packages/react-core/CHANGELOG.md 了解版本演进或在 packages/react-core/typedoc.json 对应的类型文档中查阅每个 Hook 的完整签名。【免费下载链接】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),仅供参考
返回列表