ARTICLE DETAIL

资讯详情

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

CopilotKit Frontend Tools(应用内操作)实战:让 Claude Agent 直接调用 React 前端函数

CopilotKit Frontend Tools(应用内操作)实战:让 Claude Agent 直接调用 React 前端函数 CopilotKit Frontend Tools应用内操作实战让 Claude 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本文围绕 CopilotKit 仓库中claude-sdk-typescript集成的 frontend-tools 示例展开系统讲解前端工具 / 应用内操作in-app actions的核心概念、注册方式与完整调用链路。你将掌握如何通过useFrontendTool把一个运行在浏览器端的 React 函数暴露给 Claude Agent让 Agent 依据自然对话自主决定何时调用并通过handler直接改写页面状态——例如改变页面背景、搜索本地数据等。读完本文你既能复刻该示例也能理解工具定义从前端注册、AG-UI 协议传输到后端模型调用的完整链路。一、什么是 Frontend Tools应用内操作CopilotKit 的 Frontend Tools也称应用内操作in-app actions其核心思想是让 Agent 调用那些住在你 React 应用里的函数。与常规的后端工具不同前端工具没有独立的服务进程而是由组件在浏览器端通过 Hook 注册Agent 根据用户的自然语言对话内容自行推理什么时候该调用哪个工具工具真正的执行handler发生在客户端。官方示例文档frontend-tools/README.md对这一机制的定义很精炼Frontend tools (a.k.a. in-app actions) let the agent call functions that live in your React app. The agent reasons about when to invoke them based on natural conversation.即前端工具让 Agent 能够调用 React 应用内部的函数Agent 基于自然对话推理何时调用无需用户手动触发工具由 Agent 自主调度。二、如何与该 Demo 交互在claude-sdk-typescript集成中该 Demo 位于 frontend-tools/page.tsx页面打开即展示一个由 CopilotSidebar 托管的聊天面板与一块占满屏幕的背景区域。直接向 Agent 输入如下提示词即可触发前端工具Change the background to a blue-to-purple gradient把背景改成蓝紫渐变Make the background a sunset theme把背景做成日落主题Set the background to black把背景设为黑色输入后Agent 会推理出应当调用change_background工具并把参数一个 CSS background 值回传浏览器由前端 handler 执行页面背景随之实时变化。为了让首次访问的用户更容易上手示例还在 suggestions.ts 中通过useConfigureSuggestions预置了三枚建议提示词suggestion pills点击即发送对应消息建议标题实际发送的消息Sunset themeMake the background a sunset gradient.Forest themeSwitch to a deep green forest gradient.Cosmic themeMake it a navy → magenta cosmic gradient.配置代码如下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, });available: always表示建议在任何状态下都可点击title是按钮文案message是点击后真正发送给 Agent 的消息。三、注册一个前端工具useFrontendTool 详解原文档给出的最小注册示例是文章的核心骨架useFrontendTool({ name: change_background, description: ..., parameters: z.object({ background: z.string() }), handler: async ({ background }) { setBackground(background); return { status: success }; }, });在 Demo 源码中这一注册是完整落地在 page.tsx 里的四个字段均有实际语义use client; 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 ); }逐字段拆解name工具的唯一标识Agent 通过它在对话中引用该工具须为蛇形命名如change_background。运行时它还会被转换后透传给后端模型详见下文后端链路。description描述工具能力与参数约束。它是 Agent 决策的关键依据务必写清楚接受任意合法 CSS background 值包括颜色、linear/radial 渐变等描述越准确Agent 越不会误用。parameters基于 zod 的参数 Schema。这里用z.string().describe(...)向 Agent 补充参数语义The CSS background value. Prefer gradients.引导模型优先给出渐变值。CopilotKit 会把这套 Schema 序列化成模型可读的 JSON Schema。handler真正的客户端执行体。收到 Agent 传来的{ background }后调用 React 的setBackground更新页面状态并返回{ status: success }作为工具执行结果交还给 Agent 继续对话。整个执行过程发生在浏览器端不经过网络请求。页面外壳部分CopilotKit组件通过runtimeUrl/api/copilotkit指定运行时地址agentfrontend_tools指定 Agent 标识CopilotSidebar提供侧边聊天 UI。Background组件background.tsx将背景值写入内联style{{ background }}并带有data-testidfrontend-tools-background与data-background-value属性供端到端测试断言默认背景色为固态靛蓝#4f46e5export const DEFAULT_BACKGROUND #4f46e5; export function Background({ background, children }: { background: string; children?: React.ReactNode }) { return ( div >function buildTools(tools: RunAgentInput[tools]): Anthropic.Tool[] { if (!tools || tools.length 0) return []; return tools.map((tool) { let inputSchema: Anthropic.Tool.InputSchema { type: object, properties: {}, }; if (tool.parameters) { try { const parsed typeof tool.parameters string ? JSON.parse(tool.parameters) : tool.parameters; inputSchema parsed as Anthropic.Tool.InputSchema; } catch (parseErr) { console.warn( [agent_server] failed to parse tool.parameters for ${tool.name}; using empty schema. error${message}, ); } } return { name: tool.name, description: tool.description ?? , input_schema: inputSchema, }; }); }要点如下入参RunAgentInput[tools]正是 AG-UI run 请求中携带的工具列表——前端useFrontendTool注册的工具就在这里工具参数可能是对象也可能是 JSON 字符串代码做了兼容解析解析失败时不会静默替换为空 Schema那会让 Claude 接受任意输入形状而是打印告警日志提示修正工具定义最终输出为 Anthropic Messages API 的{ name, description, input_schema }结构。配套的集成指南文档docs/setup/frontend-tools-setup.mdx也明确指出凡携带前端工具的 run 走的是直接 Messages API 路径而不是 Claude Agent SDK 路径只有当后端决策使用 Claude Agent SDK 时才走另一条路见agent_server.ts中的shouldUseClaudeAgentSdk分支。这说明前端工具 Claude 集成是一套需要前端注册与后端转换协同的完整管线。六、Agent 注册与路由配置frontend_tools这个 Agent 标识需要在运行时注册。在 src/app/api/copilotkit/route.ts 中frontend_tools与frontend-tools-async等标识被统一注册到同一个 HTTP Agentconst AGENT_URL process.env.AGENT_URL || http://localhost:8000; function createAgent() { return createClaudeHttpAgent(${AGENT_URL}/); }后端是一个透传pass-through架构Claude Agent SDKTypeScript后端本身不拥有change_background工具而是把 AG-UI 客户端提供的工具包括useFrontendTool注册的、以及运行时中间件注入的原样转发给 Claude。因此不同 Demo 的 Agent 行为差异来自前端注册而非后端图编排这正是frontend_tools能共享同一个后端端点的原因。运行时通过createCopilotRuntimeHandler({ runtime, basePath: /api/copilotkit, mode: single-route })在单路由模式下处理/api/copilotkit的请求。七、进阶异步前端工具与自定义渲染frontend-tools-async原文档聚焦于同步工具但仓库中还提供了异步变体 Demofrontend-tools-async/page.tsx展示了handler支持异步逻辑如模拟客户端数据库查询以及可选的render自定义渲染useFrontendTool({ name: query_notes, description: Search the users local notes database for notes whose title, excerpt, or tags contain the given keyword (case-insensitive). Returns up to 5 matching notes., parameters: z.object({ keyword: z .string() .describe(Keyword or phrase to search notes for (case-insensitive).), }), handler: async ({ keyword }: { keyword: string }) { await sleep(500); 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); return { keyword, count: matches.length, notes: matches }; }, 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} /; }, });两个值得注意的扩展点异步 handlerhandler可以是任意异步函数等待 500ms 模拟客户端数据库往返过滤内存中的NOTES_DB并返回结构化结果。Agent 拿到结果后用它生成对用户的总结从而端到端验证了异步前端工具路径。render回调与handler并行提供接收{ args, result, status }让你在聊天气泡内自定义工具的执行状态 UI如加载中的NotesCard实现工具即组件的生成式 UI 体验。八、如何验证端到端测试仓库为该 Demo 配备了完整的 Playwright 端到端测试tests/e2e/frontend-tools.spec.ts断言策略非常值得借鉴——只断言可观察的副作用内联样式变化不断言 LLM 生成的文本页面加载后聊天输入框与[data-testidfrontend-tools-background]容器可见背景初始内联样式包含默认色#4f46e5Sunset / Forest / Cosmic 三枚建议按钮渲染点击 Forest theme 后轮询背景样式断言其不再包含#4f46e5说明工具已被调用并改写状态点击 Sunset theme 后断言样式匹配linear-gradient|radial-gradient说明 Agent 生成了渐变值。测试注释还揭示了运行前提aiMock 特征对齐 fixture 覆盖了 sunset-themed gradient 提示词其余自由形式提示词由真实 LLM 处理。这为本地复现与 CI 验证提供了标准路径。九、运行与复现要实际运行本示例进入集成目录showcase/integrations/claude-sdk-typescript安装依赖并配置环境变量需提供ANTHROPIC_API_KEY启动后端 Agent 服务agent_server.ts默认监听0.0.0.0:8000模型默认可通过CLAUDE_MODEL/ANTHROPIC_MODEL环境变量覆盖可通过/health探活启动 Next.js 应用/api/copilotkit路由会按AGENT_URL默认http://localhost:8000代理到后端访问该 Demo 页面向侧边聊天框输入把背景改成蓝紫渐变之类的自然语言或在建议按钮中选择主题。十、小结Frontend Tools应用内操作把模型能调用的工具从服务器扩展到了浏览器端useFrontendTool负责注册与自动广告Agent 依据对话自主决策handler在客户端执行并回流结果。结合 page.tsx、后端 buildTools 转换层与 e2e 测试你可以完整复刻改背景这类交互也能顺势扩展到查询本地数据、操作应用状态、渲染工具专属 UI 等更多场景。异步 handler 与render自定义 UI 的能力则进一步把前端工具变成了构建生成式 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),仅供参考
返回列表