migrating-mastra-to-pydantic-ai

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Migrate Mastra to Pydantic AI

将 Mastra 迁移到 Pydantic AI

Preserve observable behavior, not TypeScript or Mastra's object model. Migrate the smallest complete caller path and keep application infrastructure in place.
保留可观察行为,而不是 TypeScript 或 Mastra 的对象模型。迁移最小但完整的调用路径,同时保留应用基础设施。

Trace the source before choosing a target

选择目标前先追踪源代码

  1. Read repository instructions, dependencies, tests, and the runtime entrypoint. Record the installed Mastra, Pydantic AI, and Harness versions.
  2. Trace one real request from its public entrypoint, whether an
    Agent.generate()
    /
    Agent.stream()
    call or a workflow run, through the tools, processors, memory, events, results, state, and side effects that callers use. Establish a focused baseline or characterization test.
  3. Separate these source contracts when present:
    • request context, model-chosen tool input, workflow input/output, and shared workflow state;
    • conversation messages, semantic recall, working or observational memory, workflow snapshots, and model-owned plans;
    • final text or objects, token deltas, lifecycle events, tripwires, and terminal workflow status;
    • tool approval, authenticated authorization, and process or sandbox isolation;
    • deterministic workflows, agent-selected delegation, queues, schedules, and durable execution.
  4. Record each observed contract, its owner, semantic difference, and executable proof. An unused Mastra feature is not migration scope.
Read Research and concept mapping for the detected source features. Read Verification and cutover before implementation.
  1. 阅读仓库说明、依赖、测试和运行时入口点。记录已安装的 Mastra、Pydantic AI 和 Harness 版本。
  2. 从公共入口点开始,追踪一次真实请求——无论是
    Agent.generate()
    /
    Agent.stream()
    调用还是 workflow 运行——贯穿调用方所使用的工具、Processor、Memory、事件、结果、状态和副作用。建立一个聚焦的基线测试或特征刻画测试。
  3. 在存在以下情况时,区分这些源契约:
    • 请求上下文、模型选择的工具输入、workflow 输入/输出以及共享的 workflow 状态;
    • 会话消息、语义召回、工作记忆或观察记忆、workflow 快照以及模型所拥有的计划;
    • 最终文本或对象、token 增量、生命周期事件、tripwire 以及 workflow 的终态;
    • 工具审批、经过身份验证的授权,以及进程或沙箱隔离;
    • 确定性 workflow、由 Agent 选择的委派、队列、调度和持久化执行。
  4. 记录每个已观察到的契约、其归属方、语义差异和可执行证明。未使用的 Mastra 功能不属于迁移范围。
阅读 研究与概念映射,了解检测到的源功能。实施前阅读 验证与切换。

Choose the smallest target

选择最小目标

  • Core: use
    pydantic_ai.Agent
    for the agent loop, typed dependencies, tools, outputs, normalized messages, generic hooks, streaming, MCP clients, approvals, usage limits, instrumentation, realtime, and durable-runtime integrations.
  • Graph: use
    pydantic_graph
    only when explicit typed nodes, branches, and joins remain useful; use plain async Python for simple fixed control flow.
  • Harness: add
    pydantic-ai-harness
    only for observed reusable policy such as memory notebooks, planning, model-directed subagents, Agent Skills, coding tools, guardrails, model-agnostic compaction strategies, or step persistence. Harness capabilities compose through the core agent loop; Harness is not a workflow engine or second runtime.
  • Evals: add the separate
    pydantic-evals
    package for observed datasets, cases, and evaluators.
  • Application: retain authentication, databases, vector search, queues, schedulers, deployment, product state, API/UI transports, session lookup, and tenant policy unless the requested slice includes them.
  • Gap: name behavior that no supported public seam preserves, explain its impact, and test a bounded adapter. Do not reproduce the Mastra registry, server, storage schema, or event taxonomy merely to hide a difference.
The normal migration is one reusable
Agent
, application services supplied through typed dependencies, ordinary Pydantic AI tools, a typed output when callers expect structure, and application-owned storage of
result.all_messages()
for later turns. Preserve an existing HTTP, job, or UI boundary with a small adapter and its current field names. If the Mastra call is only in-process, migrate its nearest caller in the same slice or explicitly agree on a new application-owned service boundary; do not add a transport by default.
  • 核心: 使用
    pydantic_ai.Agent
    实现 Agent 循环、类型化依赖、工具、输出、规范化消息、通用 hook、流式传输、MCP 客户端、审批、用量限制、可观测性埋点、实时功能和持久化运行时集成。
  • Graph: 仅当显式类型化节点、分支和汇合仍有价值时,才使用
    pydantic_graph
    ;对于简单的固定控制流,使用普通异步 Python。
  • Harness: 仅当观察到可复用的策略能力时,才添加
    pydantic-ai-harness
    ,例如 memory notebook、规划、由模型驱动的 SubAgent、Agent Skill、编码工具、guardrail、模型无关的压缩策略或步骤持久化。Harness 能力通过核心 Agent 循环进行组合;Harness 不是 workflow 引擎,也不是第二套运行时。
  • Evals: 对于已观察到的数据集、测试用例和评估器,添加独立的
    pydantic-evals
    包。
  • 应用层: 保留身份验证、数据库、向量搜索、队列、调度器、部署、产品状态、API/UI 传输层、会话查找和租户策略,除非请求的迁移切片包含这些内容。
  • 缺口: 明确指出没有任何受支持的公共接入点能够保留的行为,解释其影响,并测试一个边界明确的适配器。不要仅为掩盖差异而复刻 Mastra 的 registry、server、storage schema 或 event taxonomy。
常规迁移方式是使用一个可复用的
Agent
,通过类型化依赖提供应用服务,使用普通的 Pydantic AI 工具,在调用方需要结构化结果时使用类型化输出,并由应用负责存储
result.all_messages()
,供后续轮次使用。通过小型适配器保留现有 HTTP、job 或 UI 边界及其当前字段名称。如果 Mastra 调用仅发生在进程内,请在同一切片中迁移其最近的调用方,或明确约定新的、由应用拥有的服务边界;不要默认添加传输层。

Apply high-risk gates

应用高风险检查项

  • Mastra
    RequestContext
    is trusted run context, not model input. Map authenticated identity and services to typed dependencies; expose only model-chosen values as tool parameters.
  • Mastra memory combines distinct behaviors. Map thread messages to serialized Pydantic AI message history, keep semantic retrieval behind an application service or tool, and use Harness
    Memory
    only when its model-owned notebook semantics preserve the observed working-memory contract. For existing Mastra records, explicitly choose and test one-time conversion, a read-through adapter, or starting fresh as an accepted change. Do not treat message history, a notebook, or Harness
    StepPersistence
    as a workflow snapshot.
  • A Mastra workflow is deterministic application control flow. Use plain Python or
    pydantic_graph
    ; do not move
    .branch()
    ,
    .parallel()
    ,
    .foreach()
    , loops, or suspend conditions into an agent prompt. Preserve concurrency, aggregation, failure, and cancellation semantics explicitly.
  • Mastra workflow suspension persists a resumable snapshot. Keep branch and workflow-state persistence in the application or underlying durable engine and prove restart at the promised step. Pydantic AI durable integrations make agent model, tool, and MCP operations durable inside that workflow; they do not own its surrounding control flow. Deferred tools preserve agent tool calls, not arbitrary workflow state.
  • Map processors by firing point, input/output mutation, tripwire behavior, ordering, streaming visibility, and persistence. Use the narrowest of core history processors, output validators, hooks, Harness input/output/tool guardrails, a custom capability, or an application adapter, and golden-test any caller-visible event or error.
  • Approval pauses a validated action; it does not authenticate the approver. Keep identity, authorization, audit, correlation, and idempotency in the application, and prove the effect does not run before approval.
  • Map consumer intent for streaming. Pydantic AI output streaming, run-event streaming, UI adapters, and graph iteration are different surfaces; none promises Mastra's
    fullStream
    chunk taxonomy.
  • Use Harness
    SubAgents
    only for model-directed delegation. Keep deterministic fan-out, aggregation, retries, and scorer-driven verification loops in application or graph code.
  • Mastra Agent Skills may include references and dynamic resolution. Harness
    Skills
    loads on-demand
    SKILL.md
    instructions only and does not automatically scan
    .agents
    or
    .claude
    ; use Harness
    FileSystem
    or an application tool for required references, and test per-request selection separately.
  • Mastra Studio, server adapters, storage providers, deployment targets, logs, trace storage, and live-eval scheduling are product infrastructure. Retain or replace them deliberately rather than treating the agent port as equivalent.
  • Mastra durable agents, workflow time travel, exact snapshot compatibility, observational-memory compaction, and exact raw event identity are gaps unless a supported target seam is proven for the observed caller.
  • Mastra
    RequestContext
    是可信的运行上下文,而不是模型输入。将已认证的身份信息和服务映射为类型化依赖;仅将模型选择的值暴露为工具参数。
  • Mastra Memory 将彼此不同的行为组合在一起。将 thread 消息映射为序列化后的 Pydantic AI 消息历史;将语义检索保留在应用服务或工具之后;仅当 Harness
    Memory
    的模型自有 notebook 语义能够保留已观察到的工作记忆契约时,才使用它。对于现有 Mastra 记录,明确选择并测试一次性转换、read-through 适配器,或者将从头重建作为一项已接受的变更。不要将消息历史、notebook 或 Harness
    StepPersistence
    视为 workflow 快照。
  • Mastra workflow 是确定性的应用控制流。使用普通 Python 或
    pydantic_graph
    ;不要将
    .branch()
    、
    .parallel()
    、
    .foreach()
    、循环或挂起条件移入 Agent prompt。明确保留并发、聚合、失败和取消语义。
  • Mastra workflow 挂起会持久化可恢复的快照。将分支和 workflow 状态持久化保留在应用或底层持久化引擎中,并证明能够在承诺的步骤处重启。Pydantic AI 的持久化集成可让 Agent 的 model、工具和 MCP 操作在该 workflow 内具备持久性;它们不负责管理其外围控制流。延迟工具保留的是 Agent 工具调用,而不是任意 workflow 状态。
  • 按触发时机、输入/输出变更、tripwire 行为、顺序、流式可见性和持久化机制映射 Processor。在核心 history processor、输出验证器、hook、Harness 输入/输出/工具 guardrail、自定义能力或应用适配器中,选择范围最窄的方案;对调用方可见的事件或错误执行黄金测试。
  • 审批会暂停一个已验证的操作,但不会验证审批者的身份。将身份、授权、审计、调用链关联和幂等性保留在应用中,并证明在审批前不会执行相应操作。
  • 根据消费方意图映射流式传输。Pydantic AI 输出流、运行事件流、UI 适配器和 graph 迭代是不同的交互面;均不保证兼容 Mastra
    fullStream
    的 chunk 类型体系。
  • 仅在由模型决定委派时使用 Harness
    SubAgents
    。将确定性的扇出、聚合、重试以及由 scorer 驱动的验证循环保留在应用或 graph 代码中。
  • Mastra Agent Skill 可能包含引用资料和动态解析机制。Harness
    Skills
    只会按需加载
    SKILL.md
    指令,不会自动扫描
    .agents
    或
    .claude
    ;使用 Harness
    FileSystem
    或应用工具访问所需引用资料,并单独测试按请求选择的行为。
  • Mastra Studio、server 适配器、storage provider、部署目标、日志、trace storage 和 live-eval 调度均属于产品基础设施。应有意识地保留或替换它们,而不是将 Agent 移植视为等价方案。
  • Mastra 持久化 Agent、workflow 时间旅行、精确快照兼容性、观察记忆压缩和原始事件标识完全一致均属于缺口,除非能够证明已观察到的调用方存在受支持的目标接入点。

Implement and prove one vertical slice

实现并证明一个垂直切片

  1. Preserve the supported caller boundary and replace only the agent-owned internals.
  2. Start core-only. Add
    pydantic_graph
    , Harness, Pydantic Evals, or a durable runtime only after a source contract requires it.
  3. Test inputs, typed outputs, errors, event order, tool arguments/results, processor decisions, state across turns, and side effects at that boundary. Use deterministic models and fake application services offline; add a focused recorded or live test only when provider behavior is the contract.
  4. For persistence, approvals, concurrent workflows, or external effects, test interruption and restart, lineage, authorization, failure aggregation, and idempotency at the exact boundary promised by Mastra.
  5. Remove
    @mastra/*
    , Mastra server setup, and Mastra storage or event adapters only after no retained path needs them.
Explain any consequential semantic change before implementing it: state the source behavior, target behavior, caller impact, recommended choice, and remaining risk.
  1. 保留受支持的调用方边界,只替换由 Agent 负责的内部实现。
  2. 从仅使用核心能力开始。只有在源契约要求时,才添加
    pydantic_graph
    、Harness、Pydantic Evals 或持久化运行时。
  3. 在该边界测试输入、类型化输出、错误、事件顺序、工具参数和结果、Processor 决策、跨轮次状态和副作用。离线使用确定性模型和模拟的应用服务;仅当 provider 行为本身属于契约时,才添加聚焦的录制测试或实时测试。
  4. 对于持久化、审批、并发 workflow 或外部副作用,在 Mastra 承诺的确切边界上测试中断与重启、执行血缘、授权、失败聚合和幂等性。
  5. 只有在所有保留路径都不再需要时,才移除
    @mastra/*
    、Mastra server 设置以及 Mastra storage 或 event 适配器。
实施前,应解释任何重大的语义变更:说明源行为、目标行为、调用方影响、建议选择和剩余风险。

Completion

完成

Apply the completion criterion in Verification and cutover. Label evidence from fakes, recordings, and live providers accurately.
应用 验证与切换 中的完成标准。准确标注来自模拟实现、录制数据和实时 provider 的证据。