Mastra 持久化 Agent 实战指南:基于 Redis 可续流与三种 Durable 执行模式

发布时间:2026/9/14 0:18:24

Mastra 持久化 Agent 实战指南:基于 Redis 可续流与三种 Durable 执行模式 Mastra 持久化 Agent 实战指南基于 Redis 可续流与三种 Durable 执行模式【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra本篇技术指南以仓库内 examples/durable-agents 示例为蓝本完整讲解 Mastra 中可续流resumable streams与持久化执行durable execution的实现原理与实战方案。你将掌握createDurableAgent、createEventedAgent、createInngestAgent三种 Agent 工厂的适用场景与配置方法理解 Redis 缓存如何在断线重连时回放事件、observe()如何通过runId续接会话并能直接照抄示例完成本地搭建与联调。一、示例概览一个 Agent 的三种持久化形态示例 README.md 明确指出该项目用同一个基础 Agent包装出三种不同的持久化执行形态且全部基于 Redis 支撑的可续流事件流。三者对比如下Agent工厂函数可续流持久化执行durableResearchAgentcreateDurableAgentRedis无执行仍在 HTTP 请求内eventedResearchAgentcreateEventedAgentRedis内置工作流引擎fire-and-forgetinngestResearchAgentcreateInngestAgentRedisInngest 分布式执行引擎选型逻辑在源码注释中有清晰说明见 research-agent.tscreateDurableAgent只需要断线重连不丢事件的能力执行本身留在 HTTP 请求生命周期内适合单次请求内可完成的中等时长任务createEventedAgent在可续流基础上叠加发后即忘fire-and-forget执行——通过内置工作流引擎的startAsync()把执行移出请求线程适合单实例部署上的长耗时操作createInngestAgent把执行调度交给 Inngest 的分布式任务引擎支持跨进程、跨机器恢复适合生产环境的多实例分布式系统。三种 Agent 都继承Mastra实例上的cache与pubsub配置因此示例代码中创建 Agent 时几乎不需要重复传参eventedResearchAgent显式传入了一个共享的EventEmitterPubSub实例除外。二、环境搭建与启动按 README.md 的 Setup 章节完整步骤如下。1. 启动 Redis可续流依赖 Redis 持久化事件推荐使用 docker 一行启动docker run -d -p 6379:6379 redis示例仓库还提供了更完整的 docker-compose.yaml一次性拉起 Redisredis:8映射6379端口和 Inngest 开发服务器inngest/inngest:v1.34.0映射8288端口并自动把事件回调指到本机4111端口的/inngest/api路由services: redis: image: redis:8 ports: - 6379:6379 inngest: image: inngest/inngest:v1.34.0 command: inngest dev -p 8288 -u http://host.docker.internal:4111/inngest/api --poll-interval1 ports: - 8288:8288 extra_hosts: - host.docker.internal:host-gateway需要 Inngest 形态时也可以不借助 docker-compose单独运行npx inngest-clilatest devREADME 中推荐的方式开发服务器默认端口为8288。2. 安装依赖并启动开发服务器pnpm install pnpm dev开发服务器默认监听4111端口可通过curl直接调用。示例 package.json 中还提供了两个脚本mastra:devmastra dev与start:inngest:server用 inngest-cli 把开发服务器指向http://localhost:3000/inngest/api。该示例通过 pnpm overrides 将mastra/core、mastra/inngest、mastra/redis等全部链接到仓库内的本地源码方便直接阅读与调试。3. 启动 Inngest 开发服务器仅 Inngest Agent 需要npx inngest-clilatest dev三、快速使用发起流式请求与断线续接发起一个流式任务README 使用durable-research-agent的/stream端点发起研究类任务curl -X POST http://localhost:4111/api/agents/durable-research-agent/stream \ -H Content-Type: application/json \ -d {messages: [{role: user, content: Research quantum computing}]}断线后按 runId 续接可续流的核心价值在于连接中断并不等于任务丢失。stream返回的runId就是续接凭证通过/observe端点带着runId重新订阅curl -X POST http://localhost:4111/api/agents/durable-research-agent/observe \ -H Content-Type: application/json \ -d {runId: your-run-id, offset: 5}offset参数从 0 开始计数表示跳过前 N 个已消费的事件、只接收此后的增量省略offset则会把该runId的全部事件重放一遍。这一机制的接口定义同样体现在源码中——observe(runId, options?: { offset?: number; ... })见 create-inngest-agent.ts底层由CachingPubSub与 Redis 缓存协同完成。四、工作原理cache pubsub 如何支撑可续流README 的 How It Works 章节给出了最小化配置这也是理解整套机制的关键import { EventEmitterPubSub } from mastra/core/events; import { RedisServerCache } from mastra/redis; import Redis from ioredis; // Redis cache for resumable streams - events persist across reconnections const cache new RedisServerCache({ client: new Redis(redis://localhost:6379) }); // EventEmitter pubsub for real-time delivery (process-local) const pubsub new EventEmitterPubSub(); export const mastra new Mastra({ cache, pubsub, agents: { durableResearchAgent, // Inherits cache/pubsub eventedResearchAgent, // Inherits cache/pubsub inngestResearchAgent, // Inherits cache/pubsub }, });示例实际运行的 index.ts 比 README 更完整除了RedisServerCache与EventEmitterPubSub还配置了LibSQLStorefile:./mastra.db用于存储运行元数据、PinoLogger日志以及一个挂载在/inngest/api路径上的 Inngest serve 路由const storage new LibSQLStore({ id: mastra-storage, url: file:./mastra.db, }); const cache new RedisServerCache({ client: new Redis(redis://localhost:6379) }); const pubsub new EventEmitterPubSub(); export const mastra new Mastra({ agents: { durableResearchAgent, eventedResearchAgent, inngestResearchAgent, regularResearchAgent }, storage, cache, pubsub, server: { host: 0.0.0.0, apiRoutes: [ { path: /inngest/api, method: ALL, createHandler: async ({ mastra }) inngestServe({ mastra, inngest }), }, ], }, logger: new PinoLogger({ name: Mastra, level: info }), });事件流的核心模型整个可续流机制可以概括为一条规则事件按顺序索引写入缓存observe()调用时先从缓存回放错过的历史事件再无缝切换到实时事件流。即 README 所描述的Events are cached with sequential indices. Whenobserve()is called, missed events replay from cache before continuing with live events.拆开来看cache与pubsub各司其职cache此处为RedisServerCache负责存储给每个事件分配递增的index并持久化。断线重连或新观察者接入时从缓存按索引回放历史事件pubsub此处为EventEmitterPubSub负责实时投递让同进程内的消费者以订阅方式收到新事件。示例中它是进程内实现若需跨进程/跨机器实时投递可替换为基于 Redis Streams、Valkey Streams 或 Google Cloud Pub/Sub 等分布式 pubsub 后端仓库 pubsub 目录提供了redis-streams、valkey-streams、google-cloud-pubsub等实现。值得注意的工程细节可从 create-durable-agent.ts 的选项注释确认不显式传cache时Agent 会继承Mastra实例的serverCache兜底使用InMemoryServerCache显式传cache: false则完全关闭缓存流不可续不显式传pubsub时默认使用EventEmitterPubSubshouldCache?: (topic: string) boolean可以对单个 topic关闭缓存回放直接透传给底层 pubsub只收实时事件换取热 topic 的最小发布延迟run-local内部 topic 无论如何都不进缓存cleanupTimeoutMs默认 30000ms控制持久化流状态的自动清理设为0可关闭自动清理maxSteps限制 agentic loop 的最大步数。Inngest Agent 内部的缓存封装从 create-inngest-agent.ts 源码可以看到Inngest Agent 默认使用InngestPubSub通过 Inngest 的实时通道分发事件并总是用CachingPubSub包裹一层将缓存与 pubsub 打通——否则observe()只能收到订阅之后的实时事件无法回放历史。缓存解析顺序为用户显式传入的cache→ Mastra 实例的serverCache→InMemoryServerCache兜底。若需要在多进程/多机器上跨进程observe必须通过cache或mastra.serverCache提供 Redis 这类共享缓存后端。五、三种 Agent 的源码级拆解5.1 共享的基础 Agent 与工具示例把三个持久化 Agent 都建立在同一个基础配置之上见 research-agent.ts模型openai/gpt-5.5、研究助手指令以及一个演示用webSearch工具用createTool定义输入query模拟 500ms 延迟后返回两条搜索结果。同时导出一个普通 AgentregularResearchAgent用于对照。5.2createDurableAgent纯可续流export const durableResearchAgent createDurableAgent({ agent: new Agent({ id: durable-research-agent, name: Research Agent (Durable), ...baseAgentConfig, }), // cache and pubsub inherited from Mastra });这是官方推荐的最简接入方式。工厂实现create-durable-agent.ts直接构造一个DurableAgent包装原 Agent支持id/name覆盖、cache、pubsub、maxSteps、cleanupTimeoutMs、shouldCache等选项。适用场景仅需断线续接能力、执行留在 HTTP 请求内的场景。5.3createEventedAgent可续流 内置工作流引擎export const eventedResearchAgent createEventedAgent({ agent: new Agent({ id: evented-research-agent, name: Research Agent (Evented), ...baseAgentConfig, }), pubsub, // cache inherited from Mastra });工厂实现create-evented-agent.ts构造一个EventedAgent其执行方式为发后即忘——通过内置工作流引擎的startAsync()把 Agent 执行从 HTTP 请求中摘出来。适用场景单实例部署下的长耗时任务如深度研究报告、批量处理请求可立即返回结果通过事件流消费。5.4createInngestAgent可续流 Inngest 分布式执行export const inngestResearchAgent createInngestAgent({ agent: new Agent({ id: inngest-research-agent, name: Research Agent (Inngest), ...baseAgentConfig, }), inngest, // cache and pubsub inherited from Mastra });这是面向生产分布式系统的高级形态。Inngest 客户端在 inngest.ts 中配置import { realtimeMiddleware } from inngest/realtime/middleware; import { Inngest } from inngest; export const inngest: Inngest new Inngest({ id: durable-agents-example, baseUrl: http://localhost:8288, isDev: true, middleware: [realtimeMiddleware()], });要点解读baseUrl指向本地 Inngest 开发服务器8288端口isDev: true表示开发模式realtimeMiddleware()是必须的——它负责把 Mastra 的流式事件通过 Inngest 的实时通道回传给调用方是可续流 Inngest 执行两条链路能接在一起的粘合剂。从 create-inngest-agent.ts 的选项定义可以确认CreateInngestAgentOptions支持agent被包装的 Agent、inngestInngest 客户端、id/name覆盖、pubsub覆盖默认InngestPubSub、cache启用可续流时提供内部自动包裹CachingPubSub、mastra用于可观测性注册时自动设置。返回的InngestAgent具备完整的方法面stream()、resume()续接被挂起的工作流、prepare()、observe()、generate()/resumeGenerate()等待完整输出的非流式形态并覆盖了onChunk、onStepFinish、onFinish、onError、onSuspended、onAbort、onIterationComplete、abortSignal等回调与控制能力见 create-inngest-agent.ts。注册到Mastra后所需的工作流会自动注册getDurableWorkflows()并通过 Proxy 把listTools()、getMemory()、listAgents()等 Agent 常规方法转发到底层 Agent。六、如何选择三种模式与普通 Agent 的取舍需求推荐形态说明普通流式对话不关心断线AgentregularResearchAgent最简无额外基础设施需要断线重连不丢事件任务可在请求内完成createDurableAgent只引入 Redis 即可长任务 发后即忘 单实例部署createEventedAgent内置工作流引擎调度长任务 生产级分布式 跨进程恢复createInngestAgent依赖 Inngest 开发/生产服务器选择时还需注意基础设施成本纯createDurableAgent只需一个 RediscreateEventedAgent依赖内置工作流引擎单实例内有效createInngestAgent则需要额外运行 Inngest开发环境用npx inngest-clilatest dev或 docker-compose 中的inngest/inngest服务生产环境还需部署 Inngest 平台或自托管 Inngest Server。七、验证与深入阅读示例入口examples/durable-agents/src/mastra/index.tsMastra 装配、examples/durable-agents/src/mastra/agents/research-agent.ts三种 Agent 工厂、examples/durable-agents/src/mastra/workflows/inngest.tsInngest 客户端。核心实现packages/core/src/agent/durable/create-durable-agent.ts、packages/core/src/agent/durable/create-evented-agent.ts、workflows/inngest/src/durable-agent/create-inngest-agent.ts。测试佐证仓库为 durable agent 提供了大量单测与 e2e 覆盖例如 packages/core/src/agent/durable/tests/create-durable-agent.test.ts、packages/core/src/agent/durable/tests/durable-agent-stream.test.ts、packages/core/src/agent/durable/tests/observe-idle-timeout.test.ts、workflows/inngest/src/tests/create-inngest-agent.test.ts可结合测试深入验证断线重连、事件回放、挂起恢复等行为。pubsub 备选后端仓库 pubsub 目录下的redis-streams、valkey-streams、google-cloud-pubsub可替换示例中的进程内EventEmitterPubSub实现跨进程实时投递。【免费下载链接】mastraMastra is the modern TypeScript framework for AI-powered applications and agents.项目地址: https://gitcode.com/GitHub_Trending/ma/mastra创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
延伸阅读

更多相关文章

2026/9/14 0:13:24

Keil MDK中文帮助文档离线配置全指南

简介:本资源为Keil MDK嵌入式开发环境的官方中文帮助文档合集,面向51/ARM架构初学者、嵌入式工程师及高校教学实践者,解决开发环境配置、项目构建、编译链接、调试排错等核心实操难题。压缩包共34个文件,主体为29个CHM格式离线帮助…

2026/9/14 0:13:24

Git协作实战:分支管理、PR流程与冲突解决全解析

Git 这东西,属于“单干时觉得没必要、一协作就原形毕露”的工具。你一个人 commit、push,永远碰不到分支管理和冲突解决;但只要你跟别人一起开发一个项目,哪怕只是两个人改同一个仓库,用不了多久你就会发现&#xff1a…

2026/9/14 1:13:29

**Nexus AI**, Co-Founder CTO

Nexus AI, Co-Founder & CTO 【免费下载链接】rendercv Resume builder for academics and engineers 项目地址: https://gitcode.com/GitHub_Trending/re/rendercv San Francisco, CA Jun 2023 – present Built foundation model infrastructure serving 2M mont…

2026/9/14 1:13:29

铝型材表面瑕疵识别:从数据标注到模型部署的工程实践

简介:基于深度学习的铝型材表面瑕疵识别项目,面向制造业质检人员、人工智能开发者和高校学生,聚焦利用机器学习与深度学习算法对铝型材表面缺陷进行自动检测与分类。压缩包共6个文件,整体仅234KB,包含5个Python脚本和1…

2026/9/14 1:13:29

sinc插值原理与MATLAB工程实现:带宽受限信号无失真重建

简介:本资源是一份面向信号处理与数字图像处理初学者及进阶学习者的 sinc 插值实践工具包,聚焦于高精度连续信号重建这一核心问题,适用于通信、音频重采样、医学图像插值等对保真度要求较高的工程场景。压缩包共含 2 个文件(1 个 …

2026/9/14 0:58:29

WorkBuddy连接实战:四层模型、Skill配置与业务系统集成指南

《WorkBuddy 实战蓝皮书》系列写到第三篇,前两篇聊了基础认知和本地环境搭建,后台收到不少私信,问得最多的问题集中在——装好之后怎么让它真正“通”起来?这个“通”不只是网络通畅,更是 WorkBuddy 跟你的电脑、你的资…

2026/9/13 0:01:16

拯救者Y7000黑屏故障排查与维修实战指南

1. 项目概述:一台黑屏的拯救者Y7000,到底卡在哪一步? 联想拯救者Y7000系列笔记本,从2018年第一代搭载i5-8300H开始,到后来的i7-9750H、i7-10750H、i5-11400H,再到2023年款的R7-7840HS,它始终是学…

2026/9/14 0:03:22

KCF目标跟踪算法与OTB工程实现:毕业设计实战解析

简介:这是一份基于KCF核相关滤波算法、融合尺度池与抗遮挡处理的目标检测跟踪MATLAB完整源码,主要面向计算机相关专业准备毕业设计、课程设计或期末大作业的学生,也适合需要项目实战练习的初学者。源码在OTB数据集上完成验证,能够…

2026/9/14 0:03:22

语音情感识别实战:Keras实现LSTM、CNN、SVM与MLP多模型对比

简介:面向语音情感识别入门与进阶开发者,这份基于Keras的项目源码完整实现了LSTM、CNN、SVM、MLP四种模型,兼容Python3.8与Keras/TensorFlow2环境。压缩包内含49个文件,大小约70.31MB,主体包括Python脚本、yaml/json配…

2026/9/12 6:29:36

USB Type-C PCB布局分区设计:电源、高速信号与PD协议全攻略

做硬件这行,Type-C接口算是典型的“看着简单,做起来全坑”的东西。光引脚就24个,高低速信号、电源、控制线全部塞在一个小小的连接器里,如果PCB布局不做规划,打样回来基本就是“插上没反应”、“高速掉线”、“静电一打…

2026/9/12 14:32:17

系统编程学习原型如何补齐稳定性边界

系统编程学习原型如何补齐稳定性边界预算有限时&#xff0c;我先优化明显多余的复制&#xff0c;而不是猜测性地换容器。用借用传递只读数据通常就能减少分配&#xff1a; fn parse(line: &str) -> Result<Item, Error> { /* ... */ }用基准确认热点确实在分配&am…

2026/9/13 11:18:28

雨花区哪家财务公司代理记账比较好?

在雨花区&#xff0c;企业处理财税事务常常面临诸多挑战&#xff0c;选择一家靠谱的财务公司至关重要。湖南巨勤财务管理咨询有限公司就是本地正规实体财税服务机构&#xff0c;深耕本地工商财税行业多年&#xff0c;熟悉当地工商局、税务局最新政策与申报流程。主营公司注册、…

还想了解更多?直接咨询顾问

免费诊断 + 免费方案 + 透明报价。

全国咨询热线400-8866-253
免费获取方案
咨询二维码