ARTICLE · INTELLIGENCE

战地情报 · 详情页

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

如何在 Mastra Agent 中为 CopilotKit 配置后台任务

如何在 Mastra Agent 中为 CopilotKit 配置后台任务 如何在 Mastra Agent 中为 CopilotKit 配置后台任务【免费下载链接】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当 Mastra Agent 里有一个耗时的工具深度调研、报告生成、批量任务时默认行为是工具在 agentic loop 内同步执行整个对话被阻塞。Mastra 的后台任务机制可以把这类工具移出 agent loop工具被标记background: { enabled: true }后Mastra 会把它派发给BackgroundTaskManager发出background-task-started生命周期事件并立即返回一个占位结果让对话继续。CopilotKit 这边的MastraAgentAG-UI 适配器会把这个生命周期映射为 AG-UI activity 事件activity 类型mastra-background-task同时抑制普通的 tool pill——于是这段工作只会以一张实时 working 活动卡片的形式出现在聊天记录里注册了对应的 CopilotKit activity renderer 后卡片会内联渲染。本文的目标就一件事让一个 Mastra Agent 中的工具在后台运行并在 CopilotKit 聊天界面中以活动卡片实时展示其状态。适用前提是你已经按 Mastra Quickstart 把 Mastra Agent 接入了 CopilotKit如果还没有先完成 Quickstart 中的Run and connect环节从零开始可以用npx copilotkitlatest create并选择 Mastra 框架本文从定义后台工具开始。准备条件Quickstart 列出的前置要求Node.js 20一个 OpenAI API key示例代码使用openai(gpt-4.1)可换成 Mastra 支持的其他模型任意包管理器如果你走的是 remote 路径Mastra 以独立进程运行通过npx mastra dev启动先确认服务真的在提供你的 agentcurl http://127.0.0.1:4111/api/agentsQuickstart 特别提醒裸GET /不是存活检查——Mastra 在 agent 端口上提供 web console无论有没有注册 agent 都会返回200。要检查/api/agents并在输出中按名字找到你的 agentmastra dev默认占用 4111被占时会向上试探到 4131以实际打印的端口为准。第一步定义一个可后台化的工具用createTool定义工具时加上background: { enabled: true }Mastra 就会把它派发给BackgroundTaskManager而不是内联执行import { createTool } from mastra/core/tools; import { z } from zod; export const runDeepResearchTool createTool({ id: run_deep_research, description: Kick off a long-running deep-research task on a topic. This runs in the background while the conversation continues., inputSchema: z.object({ topic: z.string().describe(The topic to research in depth.), }), background: { enabled: true }, // [!code highlight] execute: async ({ topic }) { // Runs when the background worker executes the task. return JSON.stringify({ topic, summary: Deep research on ${topic} completed., }); }, });execute只有在后台 worker 实际执行任务时才运行派发那一轮它还没跑完。第二步在 Mastra 实例上启用 BackgroundTaskManager后台工具只有在实例上启用了 manager 时才会被派发并且必须配置了storage才能跟踪任务import { Mastra } from mastra/core/mastra; import { LibSQLStore } from mastra/libsql; import { backgroundAgentsAgent } from ./agents; export const mastra new Mastra({ agents: { backgroundAgentsAgent }, storage: new LibSQLStore({ id: mastra-storage, url: :memory: }), backgroundTasks: { enabled: true }, // [!code highlight] });文档示例使用LibSQLStore的:memory:配置如果你的存储方案不同保留storage这一项即可因为它是任务跟踪的必要条件。第三步把工具加到 agentimport { Agent } from mastra/core/agent; import { openai } from ai-sdk/openai; import { runDeepResearchTool } from /mastra/tools/background-research; // [!code highlight] export const backgroundAgentsAgent new Agent({ id: background-agents, name: Background Agents Agent, tools: { runDeepResearchTool }, // [!code highlight] model: openai(gpt-4.1), instructions: You are a research assistant that dispatches long-running work to the background. When the user asks you to research a topic, call the run_deep_research tool ONCE, then send a short message saying the work is running in the background., });instructions 里明确要求只调用一次工具然后回复说任务在后台运行是为了避免 agent 在同一轮反复派发任务。第四步在前端渲染活动卡片写一个针对mastra-background-task这个 activity 类型的 renderer。标准聊天面会内联渲染已注册的 activity 消息不需要自定义消息列表。React 前端在CopilotKit上通过renderActivityMessages注册import { z } from zod; import type { ReactActivityMessageRenderer } from copilotkit/react-core/v2; const contentSchema z .object({ status: z.string().optional(), args: z.record(z.unknown()).optional() }) .passthrough(); export const backgroundTaskActivityRenderer: ReactActivityMessageRenderer z.infertypeof contentSchema { activityType: mastra-background-task, // [!code highlight] content: contentSchema, render: ({ content }) { const working content.status ! completed content.status ! failed; const topic (content.args?.topic as string | undefined) ?? task; return ( div>import { CopilotKit, CopilotChat } from copilotkit/react-core/v2; import { backgroundTaskActivityRenderer } from ./activity-card; export default function Page() { return ( CopilotKit runtimeUrl/api/copilotkit agentbackground-agents renderActivityMessages{[backgroundTaskActivityRenderer]} // [!code highlight] CopilotChat / /CopilotKit ); }其中agentbackground-agents对应第三步里 agent 的idruntimeUrl是 Copilot Runtime 在本应用内的路径。renderer 逻辑本身可以直接换成你自己的卡片判断工作中的依据是status不是completed也不是failed。可选分支Angular 前端的做法是把卡片写成满足ActivityRenderer的组件再把内容 schema 和组件配进RenderActivityMessageConfig并在注入上下文中注册注入器销毁时注册会自动移除Angular Showcase 导出了两个 Mastra activity 类型的现成配置实现细节可参考仓库中showcase/angular/src/app/features/mastra/mastra-cards.ts与mastra-feature.component.ts对应的文档片段。验证配置是否生效在聊天里要求 agent 发起一个调研Kick off deep research on the current landscape of AI agent frameworks.文档给出的预期结果agent 调用run_deep_researchMastra 在后台派发它聊天中内联出现一张实时 working 活动卡片没有出现阻塞性的 tool pill同时对话保持可用。关于任务完成的交付方式out of band这是配置后台任务时最重要的边界。派发那一轮的 stream 只携带started生命周期和占位结果——stream 关闭时工具的execute还没跑完。因此在这一轮内卡片会停留在 working 状态最终结果通过带外方式送达。两条路径取决于你的部署形态有真正的后台 worker 的执行环境通过getLocalAgents传入untilIdle: true运行时可以把 manager 的 pubsub 事件包括background-task-completed接入同一条 stream适配器对生命周期的映射running→completed/failed/cancelled会让卡片自动翻转状态。文档明确警告单进程应用里没有后台 worker 时任务根本不会在运行窗口内被执行untilIdle只是白白把 stream 挂住没有任何收益。没有后台 worker通过 task manager 带外取结果接口为backgroundTaskManager.stream()和getTask(taskId)。untilIdle只存在于getLocalAgents本地嵌入路径remote 路径getRemoteAgents没有这个选项——如果你的 run 需要它agent 就必须嵌入到 runtime 所在进程。排查与限制连不上 agent 服务时把localhost换成0.0.0.0或127.0.0.1有些机器上localhost先解析到 IPv6会错过只绑定了 IPv4 的 agent 服务。确认 Mastra agent 实际端口与MASTRA_BASE_URL指向一致curl http://127.0.0.1:4111/api/agents能按名字列出 agent。确认 OpenAI API key 已正确配置在.envstarter 路径或环境变量已有 agent 路径中。后台工具只有在实例开启了backgroundTasks: { enabled: true }且配置了storage时才会被派发只给工具加background标记而漏掉实例配置工具不会进入后台队列。完整的背景说明和可选的 Observational Memory 活动卡片activity 类型mastra-observational-memory默认关闭、需两个开关同时打开见 Background Tasks 文档runtime 挂载方式的 local/remote 选择依据见 Copilot Runtime 文档。【免费下载链接】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

延伸阅读

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