
CopilotKit Frontend Tools 实战指南用 useFrontendTool 让 Agent 直接调用 React 应用内函数【免费下载链接】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导读Frontend Tools又称 in-app actions应用内动作是 CopilotKit 提供的一种交互机制它允许 Agent 在对话过程中直接调用运行在 React 前端里的函数而不是只能调用部署在后端的工具。本文以本仓库 LangGraphFastAPI集成示例中的 frontend-tools DemoREADME为核心骨架完整讲解useFrontendTool的注册方式、参数约束、客户端 handler 的执行链路以及 CopilotKit 如何自动把前端工具广告给 Agent并给出可直接复制的完整代码与运行、测试验证方式。读完本文你将掌握如何用useFrontendTool把任意 React 函数注册为 Agent 可调用的工具如何用 Zod 约束工具参数Agent 与前端 handler 之间推理 → 调用 → 回传结果的完整闭环是如何工作的以及如何用 Playwright 测试验证前端工具被真实调用。这个 Demo 演示了什么frontend-tools演示的核心思想让 Agent 基于自然语言对话自行决定何时调用前端函数。以本 Demo 为例页面注册了一个名为change_background的前端工具它接收一个 CSS 背景值支持渐变色并把页面背景实时切换为该值。用户不必点击任何按钮只需用自然语言向聊天侧边栏发号施令Agent 就会在合适时机调用这个前端函数。你可以直接尝试以下提问也是 Demo 内置推荐话术Change the background to a blue-to-purple gradient把背景改为蓝紫渐变Make the background a sunset theme做成日落主题Set the background to black把背景设为黑色从 manifest.yaml 可以看到frontend-tools被归类为interactivity交互性类型 Demo其高亮代码文件为 page.tsx 与后端图 frontend_tools.py并归属于features: frontend-tools特性。完整代码拆解一个可运行的 Frontend Tool下面是在本仓库中真实运行的前端工具完整注册代码page.tsxuse client; import React, { useState } from react; import { CopilotKit, CopilotSidebar, useFrontendTool, } from copilotkit/react-core/v2; import { z } from zod; import { Background, DEFAULT_BACKGROUND } from ./background; import { useFrontendToolsSuggestions } from ./suggestions; function Chat() { const [background, setBackground] useStatestring(DEFAULT_BACKGROUND); 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); return { status: success }; }, }); useFrontendToolsSuggestions(); return ( Background background{background} CopilotSidebar agentIdfrontend_tools defaultOpen / /Background ); } export default function FrontendToolsDemo() { return ( CopilotKit runtimeUrl/api/copilotkit agentfrontend_tools Chat / /CopilotKit ); }代码结构非常清晰几个关键点顶层CopilotKitProvider通过runtimeUrl/api/copilotkit连接到 Next.js 的 CopilotKit Runtime 路由见 api/copilotkit/route.ts并通过agentfrontend_tools指定当前对话所绑定的后端 Agent。CopilotSidebar一个预构建的侧边栏聊天 UIagentIdfrontend_tools与 Provider 的 agent 名称保持一致defaultOpen让侧边栏默认展开。useFrontendTool在组件内注册前端工具。它把工具挂到 CopilotKit 运行时上运行时负责把工具描述同步给后端 Agent。背景容器本身是一个受控组件background.tsx默认背景为纯靛蓝#4f46e5通过内联style{{ background }}渲染并带有data-testidfrontend-tools-background测试锚点和 700ms 的背景过渡动画——这为后面的自动化测试提供了可断言的目标。useFrontendTool 的 API 契约类型定义与生命周期useFrontendTool的底层类型定义在核心包 packages/core/src/types.ts 的FrontendTool中其字段契约如下字段类型说明namestring工具名Agent 通过该名字发起调用必须唯一descriptionstring?工具功能描述是 Agent 判断何时调用的关键依据parametersStandardSchemaV1参数 schema本 Demo 用 Zod 的z.object约束并校验 Agent 传入的参数handler(args, context) Promiseunknown在前端执行的处理器参数已按 schema 校验返回结果回传给 AgentfollowUpboolean?是否把结果作为后续对话继续推进agentIdstring?将工具限定到指定 Agent不填则为全局可用availableboolean?是否对 Agent 可见默认true设为false可在不注销的情况下临时隐藏工具webmcpboolean \| WebMCPToolConfig?是否同时通过 WebMCP APIdocument.modelContext暴露给浏览器端 Agenthandler 的contextFrontendToolHandlerContext还携带toolCall、触发该工具的agent实例以及AbortSignal在调用stopAgent()时触发可用于协作式取消。ReactFrontendToolpackages/react-core/src/v2/types/frontend-tool.ts在核心类型之上追加了一个可选的render字段用于为工具调用渲染自定义 UI。注册与卸载的生命周期从 use-frontend-tool.tsx 的实现可以看到注册的生命周期行为挂载时注册组件挂载后通过copilotkit.addTool(tool)注册工具如果同名工具已存在会打印警告并先removeTool再覆盖保证最新注册生效。重注册依赖effect 依赖tool.name、tool.available、copilotkit以及序列化后的deps与webmcp配置——这意味着当你需要动态改变工具可用性或参数时可以传入deps触发重新注册。卸载时清理组件卸载时调用removeTool注销工具但刻意不删除已渲染的工具调用记录以保证聊天历史中的工具调用 UI 仍然可见。另外如果提供了render该实现会通过copilotkit.addHookRenderToolCall同步注册渲染器即使parameters未定义例如 HITL 确认对话框这类无参数工具也会注册渲染逻辑。客户端 handler 如何执行参数校验与结果回传handler 在前端执行时遵循先校验、后执行、再回传的流程Agent 在对话中决定调用change_backgroundCopilotKit 运行时把 Agent 传来的参数交给 Zod schemaz.object({ background: z.string() })进行校验。校验通过后调用 handlerhandler: async ({ background }) { setBackground(background); return { status: success }; }。handler 内同步 React 状态setBackground实现即时 UI 变更——在本 Demo 中即把背景色切换到渐变色。返回值{ status: success }作为工具调用结果回传给 AgentAgent 可以基于该结果继续生成回复。由于 handler 运行在客户端因此它可以访问浏览器 API、React 状态、浏览器存储等任何前端资源——这正是应用内动作的威力所在。本仓库还提供了更进一步的示例在 frontend-tools-async Demo 中handler 是async的Agent 会等待一个模拟的客户端异步操作notes 数据库查询完成后再使用返回的结果。后端 Agent 如何自动看到前端工具原文档指出CopilotKit automatically advertises the tool to the agent。这背后的机制在 SDK 的 LangGraph 中间件中实现。在本示例中后端 Agent 是一个零自定义工具的 LangGraph 图frontend_tools.pyfrom langchain.agents import create_agent from langchain_openai import ChatOpenAI from copilotkit import CopilotKitMiddleware graph create_agent( modelChatOpenAI(modelgpt-4o-mini), tools[], middleware[CopilotKitMiddleware()], system_promptYou are a helpful, concise assistant., )注意tools[]——Agent 本身不定义任何工具但通过挂载CopilotKitMiddleware前端注册的change_background会在每次模型调用前被注入到 LLM 的工具列表中。注入逻辑位于 Python SDK 的 copilotkit_lg_middleware.py注入before_model中间件从 CopilotKit 上下文中读取前端注册的actions将其与请求中已有的工具合并merged_tools [*request.tools, *extra_tools, *frontend_tools]再交给模型见该文件约 L595-L632。拦截after_model模型返回工具调用后中间件把名字属于前端工具的调用从 AIMessage 中摘出frontend_tool_calls只把后端工具调用留给 ToolNode 执行同时把被拦截的调用写入copilotkit.intercepted_tool_calls状态见 copilotkit_lg_middleware.py。恢复after_agent在本轮 agent 执行结束前把前端工具调用还原回原始 AIMessage使聊天历史保持完整见 copilotkit_lg_middleware.py。也就是说前端工具不需要后端注册任何对应代码Agent 的 LLM 每次请求时都会收到广告并且前端工具调用会被中间件自动拦截转发到客户端执行执行结果再以 ToolMessage 形式回到 Agent 的消息流中。前端与后端的对接还依赖 Runtime 路由。在 api/copilotkit/route.ts 中frontend_tools这个 agent 名被映射到 LangGraph 的frontend_tools图agents[frontend_tools] createAgent(frontend_tools);createAgent内部通过LangGraphAgent连接AGENT_URL默认http://localhost:8123指向 FastAPI 侧的 LangGraph 服务。Provider 中的agentfrontend_tools与后端图名、agentId三者保持一致是 Demo 能跑通的对接前提。让用户更容易触发静态建议提示为了让用户更容易上手Demo 还通过useConfigureSuggestions注册了一组静态建议胶囊suggestions.tsimport { useConfigureSuggestions } from copilotkit/react-core/v2; export function useFrontendToolsSuggestions() { useConfigureSuggestions({ 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, }); }suggestions数组每项包含title胶囊显示文案与message点击后发送给 Agent 的实际消息available: always表示建议在对话全程可见。从核心包类型 types.ts 可以看出StaticSuggestionsConfig的可用性枚举为before-first-message、after-first-message、always、disabled默认为before-first-message。建议胶囊与前端工具配合后用户点击 Sunset theme 就会把Make the background a sunset gradient.发送给 AgentAgent 随即调用change_background完成 UI 变更——这是一个典型的建议 → 推理 → 应用内动作闭环。如何验证工具真的被调用Playwright 测试本仓库为 frontend-tools 编写了完整的端到端测试tests/e2e/frontend-tools.spec.ts。测试的设计思路值得借鉴不依赖 LLM 生成的文字而是断言前端工具执行后的可观察副作用内联样式变化。测试要点页面加载断言聊天输入框Type a message与背景容器data-testidfrontend-tools-background可见。默认背景断言初始内联样式包含#4f46e5solid indigo 默认值。建议胶囊渲染断言 Sunset / Forest / Cosmic 三个建议按钮出现。Forest 主题生效点击 Forest theme 胶囊后轮询背景的style属性直到它不再包含默认色#4f46e5超时 45s。Sunset 主题触发渐变点击 Sunset theme 后轮询style属性直到匹配/linear-gradient|radial-gradient/证明 Agent 确实通过change_background写入了渐变 CSS 值。test(Sunset theme pill triggers a gradient change, async ({ page }) { await page.getByRole(button, { name: /Sunset theme/i }).click(); const bg page.locator([data-testidfrontend-tools-background]); await expect .poll( async () { const s (await bg.getAttribute(style)) ?? ; return /linear-gradient|radial-gradient/.test(s); }, { timeout: 45000 }, ) .toBe(true); });该测试直接印证了完整调用链建议胶囊发送消息 → 后端 Agent 推理 → 中间件把前端工具注入 LLM → LLM 调用change_background→ 中间件拦截并转发到客户端 → handler 执行setBackground→ 背景样式变更。运行与进一步探索要在本地体验该 Demo可参考集成示例的通用运行方式启动 FastAPI 侧的 LangGraph Agent 服务frontend_tools图位于 src/agents/src/frontend_tools.py使其监听http://localhost:8123。启动 Next.js 前端打开/demos/frontend-tools路由[api/copilotkit/route.ts](https://link.gitcode.com/i/ee030fba46d09de665a39d2935d423af)会通过AGENT_URL环境变量连接后端。在侧边栏聊天中输入Change the background to a blue-to-purple gradient等指令即可看到 Agent 实时修改页面背景。如果想深入扩展仓库中还提供了两个相邻 Demo 值得对照阅读frontend-tools-asyncuseFrontendTool的异步 handler 用法Agent 会等待客户端异步操作结果。hitl-in-app基于useFrontendTool的异步 handler 实现应用级人工审批弹窗是前端工具 异步完成回调的更高级形态。小结通过本文你已经完整掌握了 CopilotKit Frontend ToolsIn-App Actions的核心机制用useFrontendTool在前端注册带 Zod 参数约束的工具由 CopilotKit 运行时自动向后端 Agent 广告工具借助CopilotKitMiddleware在前端/后端之间完成注入 → 推理 → 拦截 → 执行 → 回传的闭环并通过建议胶囊与 Playwright 测试让交互更友好、更可验证。这套模式非常适合所有需要 Agent 直接驱动前端 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创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考