跳到主要内容

MastraLangChain Deep Agents 都支持 agents、tools、memory 与 streaming。真正的差异,在于各自把边界划在哪里。

Mastra 是一套整合式 TypeScript framework,面向 AI applications。Agents、workflows、memory、RAG、evaluation、observability、local Studio、server,以及 deployment adapters,共用同一套 programming model。

Deep Agents 是建立在 LangChainLangGraph 之上、带有明确意见的 autonomous-agent harness。它提供 files、context offloading、subagents、memory 与 middleware,然后依赖 LangChain 做 retrieval、LangGraph 做 explicit workflows 与 persistence,以及 LangSmith 做 operations。

我的简短结论:

  • 当 agents 是更广泛应用里、deterministic workflows 的一部分时,选 Mastra
  • 当你做的是围绕 files、subagents 与 context management 的 autonomous research、coding 或 operations agents 时,选 Deep Agents
  • 在投入任何一边之前,先验证 durability 与 deployment model


1. The Core Difference

Deep Agents 不是用来取代 LangChain。deepagents package 把 LangChain 与 LangGraph 组装成预建的 agent harness,包含:

  • virtual filesystem
  • automatic context summarization
  • subagent delegation
  • file-based skills 与 memory
  • 用于 retries、approvals 与 guardrails 的 middleware

Mastra 则从更宽的 application boundary 起步。它的 Agent 只是众多 primitives 之一,与 tools、workflows、storage、vector stores、scorers、API routes 与 deployment configuration 并列。

AreaMastraDeep Agents
Primary abstractionAI application frameworkAutonomous agent harness
Deterministic workflowsFirst-classBuilt with LangGraph
Multi-agent modelAgents and workflows exposed as toolsSupervisor delegates to subagents
RAGMastra packages and integrationsLangChain retrieval ecosystem
PersistenceMastra memory and durable executionLangGraph checkpointers and stores
File contextWorkspaces, skills, and file-based agentsFoundational virtual filesystem
Managed runtimeMastra PlatformManaged Deep Agents or LangSmith

Mastra 在 package 层面更广。若把周边 LangChain ecosystem 算进去,Deep Agents 的覆盖面就会变得更广。



2. Building an Agent

两边都支持 TypeScript、Zod-validated tools,以及 model streaming。

Mastra

import { Agent } from "@mastra/core/agent"
import { createTool } from "@mastra/core/tools"
import { z } from "zod"

const searchDocs = createTool({
  id: "search-docs",
  description: "Search product documentation",
  inputSchema: z.object({ query: z.string() }),
  execute: async ({ query }) => searchProductDocs(query),
})

export const supportAgent = new Agent({
  id: "support-agent",
  name: "Support Agent",
  instructions: "Answer from the documentation and cite the evidence.",
  model: process.env.AGENT_MODEL!,
  tools: { searchDocs },
})

Deep Agents

import { createDeepAgent } from "deepagents"
import { tool } from "langchain"
import { z } from "zod"

const searchDocs = tool(({ query }) => searchProductDocs(query), {
  name: "search_docs",
  description: "Search product documentation",
  schema: z.object({ query: z.string() }),
})

export const supportAgent = createDeepAgent({
  model: process.env.AGENT_MODEL!,
  systemPrompt: "Answer from the documentation and cite the evidence.",
  tools: [searchDocs],
})

差异不在 type safety。Mastra 的 registries 与 shared resource model 感觉像 application framework;Deep Agents 则像在配置一套 graph-backed runtime。

Mastra 的 local server 与 Studio 会暴露 agents、workflows、traces、datasets 与 scorers。一个完整的 Deep Agents application 通常横跨好几层:

Deep Agents → LangChain → LangGraph → LangSmith
agent harness   tools       state       operations

Mastra 在它设定的路径上减少概念跳跃。Deep Agents 则在需要更多控制时,提供直接进入 LangGraph 的 escape hatches。



3. Deterministic Workflows

Agent 让 model 决定下一步。Workflow 则把重要 transitions 明确写在代码里。

当顺序本身就是 business rule 时,用 workflow:validate input、collect data、request approval、publish,并记录结果。

Mastra workflows

Mastra workflows 是 first-class、typed primitives。Steps 声明 input 与 output schemas,并可依序、平行、分支或循环组合。

const articleWorkflow = createWorkflow({
  id: "article-workflow",
  inputSchema: z.object({ topic: z.string() }),
  outputSchema: z.object({ article: z.string() }),
})
  .then(research)
  .then(write)
  .then(approve)
  .commit()

Steps 可以 suspend 以等待 human approval,再用 typed payload resume。Model 仍可在 step 内保持弹性,但不会控制整个 process。

Deep Agents with LangGraph

Subagent delegation 是由 model 导向,不是 deterministic workflow。若要明确的 state 与 transitions,把 Deep Agents 与 LangGraph 组合起来:

const graph = new StateGraph(WorkflowState)
  .addNode("research", runResearchAgent)
  .addNode("review", reviewDraft)
  .addEdge(START, "research")
  .addEdge("research", "review")
  .addConditionalEdges("review", ({ approved }) =>
    approved ? END : "research"
  )
  .compile()

LangGraph 支持 checkpoints、interrupts、streaming、subgraphs 与 durable execution。代价是要管理 graph state、reducers、nodes 与 transitions。

对 workflow-heavy products 来说,Mastra 通常是更短的路。若团队已经在用 LangGraph,Deep Agent 也可以成为自定义 state machine 里一个能力很强的 node。



4. Durability and Memory

「Memory」常常把几个不同需求混在一起:

  1. Message history 让对话保持连贯。
  2. Working memory 存放 preferences、goals 或 task state。
  3. Long-term memory 跨 conversations 共享知识。
  4. Durable execution 让中断的工作可以恢复。
  5. Resumable streaming 让 client 重新连上仍在执行的 task。

Persisted messages 并不会让任意代码变 durable。

Mastra

Mastra 的 Memory 会把 conversation thread 与 user 或 tenant resource 关联起来:

const memory = new Memory({
  storage: new PostgresStore({
    id: "support-memory",
    connectionString: process.env.DATABASE_URL!,
  }),
  options: {
    lastMessages: 20,
    workingMemory: { enabled: true },
  },
})

await agent.stream("Continue the migration plan", {
  memory: {
    thread: "conversation-42",
    resource: "user-123",
  },
})

Mastra 可以结合 recent messages、semantic recall、structured working memory,以及 observational memory。它的 durable-agent APIs 也能让 clients 依 run ID 重新连上 long streams。必须撑过 process crash 的工作,应放进 durable 或 workflow-backed execution。

Deep Agents and LangGraph

LangGraph checkpointer 会持久化 thread-scoped graph state:

const checkpointer = PostgresSaver.fromConnString(process.env.DATABASE_URL!)

const agent = createDeepAgent({
  model: process.env.AGENT_MODEL!,
  checkpointer,
})

await agent.invoke(
  { messages: [{ role: "user", content: "Continue the analysis." }] },
  { configurable: { thread_id: "conversation-42" } }
)

Checkpointer 存放 conversation state、interrupts 与 resume points。LangGraph store 则保存跨 threads 共享的数据。

Deep Agents 把 long-term memory 表示成 files。StateBackend 把 scratch files 留在 thread state,而 StoreBackend 可以把如 /memories//skills/ 这类 paths 跨 threads 持久化。

Mastra 提供更多内建 memory strategies。Deep Agents 提供可检查、可编辑的 filesystem model。在两套系统里,identifiers 与 namespaces 都必须来自 authenticated context,而 durable memory 也需要 retention、correction 与 deletion policies。



5. RAG

Production RAG system 有分开的 ingestion 与 query paths:

ingestion → load → chunk → embed → index
query     → retrieve → filter/rerank → answer with citations

Ingestion 不应在每次 agent request 时执行;一次成功的 vector lookup,也不代表答案已经 grounded。

Mastra RAG

Mastra 提供 document chunking、通过 AI SDK model interface 的 embedding support、vector-store integrations,以及可直接挂到 agent 上的 vector query tool。

对 TypeScript application 里的 conventional RAG 来说,这是一条连贯的路径。Dynamic vector-store resolution 特别有用,可从 authenticated request context 选出 tenant 的 index。

Deep Agents with LangChain

Deep Agents 使用 LangChain loaders、text splitters、embeddings、retrievers 与 vector stores。当应用需要 specialized document formats 或 retrieval strategies 时,这个 ecosystem 的广度就很重要。

Deep Agents 对大型结果也有 context-management 优势:tool 可以把 retrieved content 写进 backend,并返回 file paths。Agent 只需检查相关段落,而不必把每个 token 都放进主 conversation。

无论选哪个 framework,都要评估:

  • retrieval recall 与 precision
  • answer groundedness
  • citation correctness
  • end-to-end answer quality


6. Files、Subagents 与 Sandboxes

Deep Agents 把 files 与 delegation 放在核心。Supervisor 可以把工作交给 context 隔离的 subagents,让每位 specialist 执行多次 tool calls,再返回精简结果。

它的 backend 提供 virtual filesystem。Sandbox backend 再延伸出 command execution:

  • StateBackend 存放 thread-scoped virtual files。
  • FilesystemBackend 暴露 host directory。
  • LocalShellBackend 加入 host shell access。
  • provider-backed sandboxes 在远端隔离 files 与 processes。

Mastra 可以把 agents 与 workflows 暴露给 routing agent,并挂上包含 filesystem 与可选 sandbox 的 Workspace。这适合文件访问只是众多能力之一的应用。

Workspace path 不是 security boundary。两个 framework 的 local shell execution,都只适合 trusted development。Production execution 需要:

  • 全新或正确 namespaced 的 sandbox
  • CPU、memory、disk 与 time limits
  • 受控的 network egress
  • 明确的 file-transfer rules
  • 范围极窄的 credentials

Isolation 保护 host,但本身无法防止 prompt injection、secret exfiltration、runaway cost,或 cross-user leakage。

对 file-heavy autonomous work,Deep Agents 的重心更强。Mastra 则更能把 files 与 execution 自然融入更广的 application。



7. Observability、Evaluation 与 Safety

要运营一个 agent,需要看到最终答案背后的路径:model calls、tools、retrieval、subagents、workflow transitions、retries、latency、token usage、cost 与 errors。

Mastra 为其 primitives 做 instrumentation,并把 traces 导出到 Studio、Mastra Platform 或 OpenTelemetry backends。它也把 scorers、datasets 与 experiments 放进同一套 framework model。

Deep Agents 继承 LangChain 与 LangGraph tracing。LangSmith 再加上 dashboards、alerts、datasets、offline 与 online evaluators、annotation queues,以及 deployment monitoring。

Mastra 的 observability 感觉像 framework primitive。LangSmith 则是更广的 operations product。两边都可以接入既有的 OpenTelemetry pipeline。

对任一 stack,都在五个层级做测试:

  1. 不调用 model 的 tool contracts
  2. 以 controlled responses 验证 workflows 或 graphs
  3. 针对 quality 与 groundedness 的 dataset evaluations
  4. 针对 performance 与 failure paths 的 traces
  5. 针对 streaming、persistence、authentication 与 limits 的 deployed behavior

Human approval 在两套系统都可用,通过 suspended workflow steps、tool approval,或 LangGraph interrupts。Approval 不能取代 runtime isolation。

Agent traces 可能包含 user messages、retrieved documents、tool arguments 与 generated code。应套用与应用数据相同的 access controls、redaction、retention 与 deletion rules。



8. Deployment

第一个 agent demo 很容易。Production 需要 durable state、background execution、authentication、secrets、observability,以及能撑过真实基础设施的 streaming。

Mastra

最整合的路径是 Mastra Platform:

mastra deploy

Mastra 也可以建出 Node server,或部署到 Cloudflare 这类 platforms。Portability 仍然取决于 state:local SQLite files、vectors、memory 与 workflow data,都必须换成与 runtime 兼容的 stores。

Deep Agents

Deep Agents 主要有三条路径:

  1. Managed Deep Agents,一套带有明确意见的 hosted runtime,可用性需要自行确认。
  2. LangSmith Deployment,具备 persistent state、background execution、authentication hooks、webhooks、cron jobs、tracing,以及 Agent Protocol APIs。
  3. Application-hosted deployment,例如在 Next.js 或 Cloudflare 上使用 Agent Streaming Protocol。

Application hosting 会把更多责任交给团队:

  • 配置 durable checkpointer 与 store
  • 对每个 thread 做 authenticate 与 authorize
  • 隔离 tenant namespaces
  • 处理 host timeouts 与 background work
  • 把 code execution sandbox 到 web server 之外
RequirementMastraDeep Agents
Simplest hosted pathMastra PlatformManaged Deep Agents
Established managed runtimeMastra PlatformLangSmith Deployment
Custom hostingBuilt server or adapterAgent Protocol routes or Agent Server
Self-hosted durabilityMastra storage providersLangGraph checkpointer, store, and infrastructure
Enterprise topologyPlatform-dependentCloud, hybrid, or self-hosted LangSmith

对 greenfield TypeScript 团队来说,Mastra 的整合路径更干净。若团队已投入 LangChain,或需要 hybrid infrastructure,LangSmith 提供更多 runtime topologies。



How I Would Choose



我的实务默认:

NeedDefault
Deterministic workflowsMastra, unless the team already knows LangGraph
Conventional application memoryMastra
Filesystem-native memoryDeep Agents
Straightforward RAGMastra
Specialized retrievalDeep Agents with LangChain
Coding or research agentDeep Agents
Managed operationsDeep Agents with LangSmith
Existing OpenTelemetry pipelineEither

没有放诸四海皆准的赢家。Mastra 优化的是 AI application。Deep Agents 优化的是 autonomous agent harness,并把它接到更广的 LangChain stack。

在做选择前,先 prototype 最难的 production requirement。测试 approval workflows 的 suspend 与 resume、重新连上 long-running research、在真实文件上测量 RAG,并验证 code execution 的 sandbox 与 credential boundaries。

通过那项测试、且隐藏假设最少的 framework,就是更好的选择。

最新细节可参考官方 Mastra agentsworkflowsmemoryRAGworkspacesobservabilitydeployment 文档。LangChain 方面可看 Deep AgentsmemoryRAGsandboxesLangGraph persistenceLangSmith observability,以及 production deployment

阅读下一篇笔记
React 19 新功能