Mastra 深度解析:16K Stars 的 TypeScript AI Agent 框架如何用 Workflows + RAG + Evals 五件套让前端工程师也能构建生产级智能体应用——从架构原理到完整实战指南
引言:TypeScript 开发者的 AI Agent 困境
2026 年,AI Agent 已经从概念验证走向了生产落地。但一个尴尬的现实是——市面上绝大多数 Agent 框架都是 Python 生态的。LangChain、CrewAI、AutoGen、LangGraph……清一色的 Python。
对于占据了 Web 开发半壁江山的 TypeScript/JavaScript 工程师来说,想在自己的技术栈里构建 AI Agent 应用,要么被迫学 Python,要么只能用一些半成品的 JS 库。
Mastra 改变了这一切。
Mastra 是一个「有态度的」(opinionated)TypeScript 框架,它提供了一整套构建 AI 应用的原语:Agents(智能体)、Tools(工具)、Workflows(工作流)、RAG(检索增强生成)、Evals(评估)。截至目前,Mastra 在 GitHub 上已获得 16K+ Stars,拥有 16000+ 次提交,被 Replit、Fireworks、Medusa 等知名公司采用。
本文将从架构设计、核心模块、代码实战、性能优化到与竞品对比,全方位深度解析 Mastra,帮助你快速掌握这个框架,用 TypeScript 构建真正可用的 AI Agent 应用。
一、Mastra 是什么:五原语架构全景
1.1 设计哲学
Mastra 的设计理念可以用一句话概括:让 TypeScript 开发者用自己最熟悉的方式构建 AI Agent。
与 Python 生态的框架不同,Mastra 从底层就为 TypeScript 的类型系统、模块系统和运行时特性做了深度优化。它的核心特点包括:
- 类型安全:所有工具、工作流步骤的输入输出都有完整的 TypeScript 类型推导
- Schema 驱动:使用 Zod / Valibot / ArkType 定义数据结构,运行时自动校验
- Provider 无关:统一接口对接 OpenAI、Anthropic、Google Gemini 等所有主流 LLM
- 部署友好:支持 Next.js、React、Astro、Express、SvelteKit、Hono 等所有主流框架
- 零配置启动:
npm create mastra@latest一行命令即可开始
1.2 五原语架构
Mastra 的核心由五大原语组成:
| 原语 | 作用 | 类比 |
|---|---|---|
| Agent | 智能体,LLM + 工具 + 记忆 | 一个有技能的员工 |
| Tool | 可执行的类型化函数 | 员工手里的工具 |
| Workflow | 基于图的状态机 | 公司的 SOP 流程 |
| RAG | 检索增强生成 | 员工的知识库 |
| Evals | 自动化评估 | 绩效考核系统 |
这五个原语相互独立又可以自由组合。你可以只用 Agent 做简单的对话,也可以用 Workflow 编排多个 Agent 协同工作,再用 RAG 为它们提供领域知识,最后用 Evals 评估整个系统的效果。
二、Agent:智能体的核心引擎
2.1 Agent 的本质
在 Mastra 中,Agent 是一个封装了 LLM 模型、工具集和指令的智能体。它能够:
- 接收用户输入并推理
- 自主决定调用哪些工具
- 维护对话上下文记忆
- 迭代执行直到完成任务
2.2 创建 Agent
创建一个 Agent 非常直观。首先安装依赖:
npm install @mastra/core@latest zod@latest
然后定义一个工具:
// src/mastra/tools/weather-tool.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'get-weather',
description: '获取指定城市的当前天气信息',
inputSchema: z.object({
location: z.string().describe('城市名称,如"北京"、"上海"'),
}),
outputSchema: z.object({
temperature: z.number(),
condition: z.string(),
humidity: z.number(),
windSpeed: z.number(),
}),
execute: async ({ location }) => {
// 实际项目中这里调用天气 API
const mockData: Record<string, any> = {
'北京': { temperature: 32, condition: '晴', humidity: 45, windSpeed: 12 },
'上海': { temperature: 28, condition: '多云', humidity: 72, windSpeed: 8 },
}
return mockData[location] || { temperature: 25, condition: '未知', humidity: 50, windSpeed: 10 }
},
})
然后创建 Agent:
// src/mastra/agents/weather-agent.ts
import { Agent } from '@mastra/core/agent'
import { weatherTool } from '../tools/weather-tool'
export const weatherAgent = new Agent({
id: 'weather-agent',
name: '天气助手',
instructions: `
你是一个专业的天气助手。你的职责是:
1. 根据用户提供的城市查询天气
2. 用简洁易懂的语言描述天气状况
3. 如果用户没有指定城市,主动询问
4. 给出出行建议(如是否需要带伞、注意防晒等)
`,
model: 'openai/gpt-5.5',
tools: { weatherTool },
})
最后注册到 Mastra 实例:
// src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { weatherAgent } from './agents/weather-agent'
export const mastra = new Mastra({
agents: { weatherAgent },
})
2.3 运行 Agent
// run.ts
import { mastra } from './src/mastra/index'
const agent = mastra.getAgentById('weather-agent')
// 简单调用
const response = await agent.generate('今天北京天气怎么样?')
console.log(response.text)
// 流式输出
const stream = await agent.stream('上海明天适合户外活动吗?')
for await (const chunk of stream.textStream) {
process.stdout.write(chunk)
}
2.4 Model Router:统一模型接口
Mastra 使用 provider/model 格式的字符串来路由模型,这是它最优雅的设计之一:
// OpenAI 系列
model: 'openai/gpt-5.5'
model: 'openai/gpt-5-mini'
// Anthropic 系列
model: 'anthropic/claude-sonnet-4-6'
model: 'anthropic/claude-opus-4-7'
model: 'anthropic/claude-haiku-4-5'
// Google 系列
model: 'google/gemini-2.5-flash'
你不需要导入任何 SDK provider 对象,Mastra 会根据前缀自动查找对应的环境变量(OPENAI_API_KEY、ANTHROPIC_API_KEY、GOOGLE_API_KEY)并完成路由。这意味着切换模型只需要改一个字符串,其他代码一行不动。
2.5 对话记忆
Agent 内置了对话记忆管理,支持多轮对话:
// 创建对话线程
const thread = await agent.generate([
{ role: 'user', content: '我叫张三' },
{ role: 'assistant', content: '你好张三!有什么可以帮你的?' },
{ role: 'user', content: '我刚才说我的名字是什么?' },
])
// Agent 能记住你叫张三
三、Workflows:结构化工作流引擎
3.1 为什么需要 Workflows?
Agent 的自主性是一把双刃剑。对于需要精确控制执行顺序、数据流转和错误处理的场景,Workflows 比 Agent 更合适。
Mastra 的 Workflow 引擎是一个基于图的持久状态机,支持:
- 线性链式执行(
.then()) - 条件分支(
.branch()) - 并行执行(
.parallel()) - 循环(通过条件分支实现)
- 暂停/恢复(
suspend/resume) - 人工介入(等待人工审批后继续)
- 嵌套工作流(一个步骤调用另一个工作流)
- 错误处理与重试
3.2 创建 Workflow
// src/mastra/workflows/content-pipeline.ts
import { createWorkflow, createStep } from '@mastra/core/workflows'
import { z } from 'zod'
// 步骤 1:生成文章大纲
const generateOutline = createStep({
id: 'generate-outline',
inputSchema: z.object({
topic: z.string(),
style: z.enum(['technical', 'casual', 'academic']),
}),
outputSchema: z.object({
outline: z.array(z.string()),
estimatedWordCount: z.number(),
}),
execute: async ({ inputData }) => {
const { topic, style } = inputData
// 调用 LLM 生成大纲
return {
outline: [
`引言:${topic}的背景`,
`核心概念解析`,
`技术架构详解`,
`实战代码演示`,
`性能优化策略`,
`总结与展望`,
],
estimatedWordCount: 8000,
}
},
})
// 步骤 2:根据大纲撰写内容
const writeContent = createStep({
id: 'write-content',
inputSchema: z.object({
topic: z.string(),
style: z.enum(['technical', 'casual', 'academic']),
outline: z.array(z.string()),
estimatedWordCount: z.number(),
}),
outputSchema: z.object({
content: z.string(),
wordCount: z.number(),
}),
execute: async ({ inputData }) => {
const { topic, outline, style } = inputData
// 调用 LLM 逐章节撰写
const sections = await Promise.all(
outline.map(async (heading) => {
return `## ${heading}\n\n这里是${heading}的详细内容...`
})
)
const content = sections.join('\n\n')
return { content, wordCount: content.length }
},
})
// 步骤 3:SEO 优化
const optimizeSEO = createStep({
id: 'optimize-seo',
inputSchema: z.object({
content: z.string(),
wordCount: z.number(),
}),
outputSchema: z.object({
optimizedContent: z.string(),
seoScore: z.number(),
suggestions: z.array(z.string()),
}),
execute: async ({ inputData }) => {
const { content } = inputData
return {
optimizedContent: content,
seoScore: 85,
suggestions: ['建议增加内链', '标题可以更吸引眼球'],
}
},
})
// 组装工作流
export const contentPipeline = createWorkflow({
id: 'content-pipeline',
inputSchema: z.object({
topic: z.string(),
style: z.enum(['technical', 'casual', 'academic']),
}),
outputSchema: z.object({
optimizedContent: z.string(),
seoScore: z.number(),
suggestions: z.array(z.string()),
}),
})
.then(generateOutline)
.then(writeContent)
.then(optimizeSEO)
.commit()
3.3 条件分支
const classifyInput = createStep({
id: 'classify',
inputSchema: z.object({ query: z.string() }),
outputSchema: z.object({
category: z.enum(['technical', 'billing', 'general']),
confidence: z.number(),
}),
execute: async ({ inputData }) => {
// 用 LLM 分类
return { category: 'technical' as const, confidence: 0.92 }
},
})
const techSupport = createStep({
id: 'tech-support',
inputSchema: z.object({ query: z.string(), category: z.literal('technical') }),
outputSchema: z.object({ answer: z.string() }),
execute: async ({ inputData }) => ({ answer: '技术解决方案...' }),
})
const billingSupport = createStep({
id: 'billing-support',
inputSchema: z.object({ query: z.string(), category: z.literal('billing') }),
outputSchema: z.object({ answer: z.string() }),
execute: async ({ inputData }) => ({ answer: '账单查询结果...' }),
})
const supportWorkflow = createWorkflow({
id: 'support-workflow',
inputSchema: z.object({ query: z.string() }),
outputSchema: z.object({ answer: z.string() }),
})
.then(classifyInput)
.branch([
// 根据分类结果路由到不同步骤
[async ({ inputData }) => inputData.category === 'technical', techSupport],
[async ({ inputData }) => inputData.category === 'billing', billingSupport],
])
.commit()
3.4 暂停与恢复
Mastra Workflow 支持暂停执行,等待外部输入后再继续。这在需要人工审批的场景中非常有用:
const humanReview = createStep({
id: 'human-review',
inputSchema: z.object({ draft: z.string() }),
outputSchema: z.object({ approved: z.boolean(), feedback: z.string() }),
execute: async ({ inputData, suspend }) => {
// 暂停工作流,等待人工输入
const humanInput = await suspend({
message: '请审核以下草稿并提供反馈',
draft: inputData.draft,
})
return {
approved: humanInput.approved,
feedback: humanInput.feedback,
}
},
})
// 恢复暂停的工作流
const run = await contentPipeline.createRun()
const result = await run.start({ triggerData: { topic: 'AI Agent', style: 'technical' } })
// 如果中间暂停了
if (result.status === 'suspended') {
await run.resume({
stepId: 'human-review',
context: { approved: true, feedback: '写得不错,可以发布' },
})
}
四、RAG:为 Agent 装上知识库
4.1 RAG 的工作原理
RAG(Retrieval-Augmented Generation)是让 LLM 基于你的私有数据回答问题的关键技术。Mastra 的 RAG 模块提供了完整的 ETL 管道:
- Extract(提取):从文档、网页、API 等来源提取文本
- Transform(转换):分块、清洗、向量化
- Load(加载):存储到向量数据库
4.2 构建知识库
import { MDocument } from '@mastra/rag'
import { embed } from 'ai'
// 1. 加载文档
const doc = new MDocument({
docs: [
{ text: 'Mastra 是一个 TypeScript AI 框架...' },
{ text: '它支持 Agents、Workflows、RAG 等原语...' },
],
type: 'text',
})
// 2. 分块
const chunks = await doc.chunk({
strategy: 'recursive',
size: 512,
overlap: 50,
})
// 3. 向量化
const { embeddings } = await embed({
model: openai.embedding('text-embedding-3-small'),
values: chunks.map(chunk => chunk.text),
})
// 4. 存储到向量数据库(以 Pinecone 为例)
import { PineconeVector } from '@mastra/pinecone'
const vectorStore = new PineconeVector({
apiKey: process.env.PINECONE_API_KEY,
indexName: 'mastra-knowledge',
})
await vectorStore.upsert({
vectors: embeddings,
metadata: chunks.map(chunk => ({ text: chunk.text })),
})
4.3 在 Agent 中使用 RAG
import { Agent } from '@mastra/core/agent'
import { createVectorQueryTool } from '@mastra/rag'
// 创建向量查询工具
const knowledgeTool = createVectorQueryTool({
vectorStoreName: 'pinecone',
indexName: 'mastra-knowledge',
model: openai.embedding('text-embedding-3-small'),
})
// Agent 自动在需要时查询知识库
const knowledgeAgent = new Agent({
id: 'knowledge-agent',
name: '知识助手',
instructions: `
你是一个基于公司内部知识库的助手。
当用户提出问题时,先使用 knowledgeTool 检索相关信息,
然后基于检索到的内容回答。如果知识库中没有相关内容,
诚实告知用户。
`,
model: 'openai/gpt-5.5',
tools: { knowledgeTool },
})
4.4 检索策略
Mastra 支持多种检索策略,适应不同场景:
// 基本语义搜索
const results = await vectorStore.query({
vector: queryEmbedding,
topK: 5,
filter: { category: 'technical' },
})
// 混合搜索(语义 + 关键词)
const hybridResults = await vectorStore.query({
vector: queryEmbedding,
topK: 5,
searchType: 'hybrid',
alpha: 0.7, // 0=纯关键词, 1=纯语义
})
// 带阈值的过滤
const filteredResults = await vectorStore.query({
vector: queryEmbedding,
topK: 10,
minScore: 0.75, // 只返回相似度 > 75% 的结果
})
五、Evals:AI 输出的自动化质检
5.1 为什么需要 Evals?
LLM 的输出具有不确定性。同一个 prompt,不同次调用可能产生质量差异很大的结果。Evals 提供了一套自动化测试框架,让你能够:
- 量化评估 Agent 的回答质量
- 检测幻觉(hallucination)
- 验证输出格式是否符合预期
- 回归测试(确保模型更新不会降低质量)
5.2 定义评估标准
import { createScorer } from '@mastra/core/evals'
// 自定义评分器
const accuracyScorer = createScorer({
id: 'accuracy',
description: '评估回答的准确性',
scorer: async ({ input, output, context }) => {
// 使用 LLM 做判断
const judgment = await judgeModel.generate({
prompt: `
问题: ${input}
回答: ${output}
参考答案: ${context.expectedAnswer}
请评估回答的准确性,给出 0-1 的分数。
`,
})
return {
score: parseFloat(judgment.text),
reason: judgment.text,
}
},
})
const hallucinationScorer = createScorer({
id: 'hallucination',
description: '检测是否包含幻觉内容',
scorer: async ({ input, output, context }) => {
// 对比输出与知识库内容的匹配度
const hallucinationScore = await detectHallucination(output, context.sourceDocuments)
return {
score: 1 - hallucinationScore, // 越高越好(无幻觉)
reason: hallucinationScore > 0.3 ? '检测到可能的幻觉内容' : '回答基于可靠来源',
}
},
})
5.3 运行评估
import { evaluate } from '@mastra/core/evals'
const results = await evaluate({
agent: knowledgeAgent,
inputs: [
{ query: 'Mastra 支持哪些 LLM?', expectedAnswer: 'OpenAI、Anthropic、Google Gemini' },
{ query: '如何创建 Workflow?', expectedAnswer: '使用 createWorkflow 和 createStep' },
],
scorers: [accuracyScorer, hallucinationScorer],
threshold: 0.8, // 低于 80% 视为失败
})
console.log(`准确率: ${results.accuracy}`)
console.log(`幻觉率: ${results.hallucinationRate}`)
console.log(`通过: ${results.passed}`)
六、集成生态:与主流框架无缝对接
6.1 前端框架集成
Mastra 提供了与所有主流前端/后端框架的集成方案:
| 框架 | 集成方式 | 适用场景 |
|---|---|---|
| Next.js | API Route + Server Action | 全栈 AI 应用 |
| React | Client SDK + Hooks | SPA 前端 |
| Astro | API Endpoint | 静态站点 + AI |
| Express | Middleware | 传统后端 |
| SvelteKit | Server Route | Svelte 全栈 |
| Hono | Handler | 边缘计算 |
6.2 Next.js 集成示例
// app/api/chat/route.ts
import { mastra } from '@/mastra'
export async function POST(req: Request) {
const { message } = await req.json()
const agent = mastra.getAgentById('weather-agent')
const stream = await agent.stream(message)
return new Response(stream.toDataStream(), {
headers: { 'Content-Type': 'text/event-stream' },
})
}
// app/page.tsx
'use client'
import { useChat } from 'ai/react'
export default function ChatPage() {
const { messages, input, handleInputChange, handleSubmit } = useChat({
api: '/api/chat',
})
return (
<div className="max-w-2xl mx-auto p-4">
{messages.map(m => (
<div key={m.id} className={m.role === 'user' ? 'text-right' : 'text-left'}>
<p className="bg-gray-100 rounded p-2 inline-block">{m.content}</p>
</div>
))}
<form onSubmit={handleSubmit} className="mt-4">
<input
value={input}
onChange={handleInputChange}
placeholder="输入消息..."
className="w-full border rounded p-2"
/>
</form>
</div>
)
}
6.3 第三方服务集成
Mastra 提供了自动生成的类型安全 API 客户端,可以作为 Agent 的工具:
// 集成 Slack
import { SlackIntegration } from '@mastra/slack'
const slack = new SlackIntegration({
token: process.env.SLACK_BOT_TOKEN,
})
// 集成 GitHub
import { GitHubIntegration } from '@mastra/github'
const github = new GitHubIntegration({
token: process.env.GITHUB_TOKEN,
})
// 将集成作为 Agent 工具
const agent = new Agent({
id: 'devops-agent',
name: 'DevOps 助手',
instructions: '你是一个 DevOps 助手,可以查询 GitHub issues 和发送 Slack 通知',
model: 'openai/gpt-5.5',
tools: {
...slack.getTools(),
...github.getTools(),
},
})
七、Studio:可视化开发调试界面
Mastra 提供了一个名为 Studio 的交互式 UI,让你可以在浏览器中直接测试和调试 Agent、Workflow。
npm create mastra@latest
# 创建项目后自动提示打开 Studio
Studio 的核心功能包括:
- Agent 调试:实时与 Agent 对话,查看工具调用链路
- Workflow 可视化:以图形化方式查看工作流执行状态和数据流转
- RAG 测试:上传文档、测试检索效果
- Evals 面板:查看评估结果和历史趋势
- 日志追踪:完整的执行日志和性能指标
八、生产部署与性能优化
8.1 部署选项
Mastra 支持多种部署方式:
# 本地开发
npm run dev
# 构建生产版本
npm run build
# 部署到 Vercel
vercel deploy
# 部署到 AWS Lambda
mastra deploy --provider aws
# 部署到 Docker
docker build -t my-mastra-app .
docker run -p 3000:3000 my-mastra-app
8.2 性能优化策略
1. 模型选择优化
// 对于简单任务,使用小模型降低成本
const simpleAgent = new Agent({
id: 'classifier',
model: 'openai/gpt-5-mini', // 快速、便宜
instructions: '对输入进行分类',
})
// 对于复杂推理,使用大模型
const complexAgent = new Agent({
id: 'analyst',
model: 'anthropic/claude-opus-4-7', // 强推理能力
instructions: '进行深度分析',
})
2. 并行执行
// 并行执行多个独立步骤
const parallelWorkflow = createWorkflow({
id: 'parallel-analysis',
inputSchema: z.object({ text: z.string() }),
outputSchema: z.object({
sentiment: z.string(),
keywords: z.array(z.string()),
summary: z.string(),
}),
})
.parallel([
sentimentAnalysis, // 情感分析
keywordExtraction, // 关键词提取
textSummarization, // 文本摘要
])
.then(mergeResults)
.commit()
3. 缓存策略
import { MemoryCache } from '@mastra/core/cache'
const cache = new MemoryCache({
ttl: 3600, // 1 小时过期
maxSize: 1000,
})
// 缓存 RAG 检索结果
const cachedQuery = cache.wrap(vectorStore.query, {
keyFn: (params) => `rag:${JSON.stringify(params.vector.slice(0, 10))}`,
})
4. 流式输出
// 流式输出减少首字节延迟
const stream = await agent.stream('解释量子计算')
for await (const chunk of stream.textStream) {
// 逐字输出到客户端
res.write(chunk)
}
res.end()
九、实战案例:构建一个客服智能体
让我们用 Mastra 构建一个完整的客服系统,综合运用所有核心原语。
9.1 系统架构
用户输入 → 意图分类 Agent → 路由 Workflow
├→ 技术支持 Agent(查询知识库 RAG)
├→ 订单查询 Tool
├→ 人工转接 Workflow(暂停等待)
└→ Evals 质量评估
9.2 完整代码
// src/mastra/tools/order-tool.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const orderQueryTool = createTool({
id: 'query-order',
description: '查询订单状态',
inputSchema: z.object({
orderId: z.string().describe('订单号'),
}),
outputSchema: z.object({
status: z.string(),
trackingNumber: z.string().optional(),
estimatedDelivery: z.string().optional(),
}),
execute: async ({ orderId }) => {
// 模拟数据库查询
return {
status: '已发货',
trackingNumber: 'SF1234567890',
estimatedDelivery: '2026-07-10',
}
},
})
// src/mastra/agents/support-agent.ts
import { Agent } from '@mastra/core/agent'
import { orderQueryTool } from '../tools/order-tool'
import { knowledgeTool } from '../tools/knowledge-tool'
export const supportAgent = new Agent({
id: 'support-agent',
name: '智能客服',
instructions: `
你是一个专业的客服助手。你的职责是:
1. 理解用户的问题并提供准确的回答
2. 对于订单相关问题,使用 orderQueryTool 查询
3. 对于技术问题,先使用 knowledgeTool 检索知识库
4. 如果无法解决,建议转接人工客服
5. 始终保持友好、专业的态度
`,
model: 'openai/gpt-5.5',
tools: { orderQueryTool, knowledgeTool },
})
// src/mastra/workflows/support-workflow.ts
import { createWorkflow, createStep } from '@mastra/core/workflows'
import { z } from 'zod'
const classifyIntent = createStep({
id: 'classify-intent',
inputSchema: z.object({ message: z.string(), userId: z.string() }),
outputSchema: z.object({
intent: z.enum(['order', 'technical', 'general', 'human']),
confidence: z.number(),
}),
execute: async ({ inputData }) => {
// 用 LLM 分类意图
return { intent: 'technical' as const, confidence: 0.9 }
},
})
const handleByAgent = createStep({
id: 'handle-by-agent',
inputSchema: z.object({
message: z.string(),
userId: z.string(),
intent: z.string(),
}),
outputSchema: z.object({
response: z.string(),
resolved: z.boolean(),
}),
execute: async ({ inputData }) => {
const agent = mastra.getAgentById('support-agent')
const result = await agent.generate(inputData.message)
return {
response: result.text,
resolved: true,
}
},
})
const humanHandoff = createStep({
id: 'human-handoff',
inputSchema: z.object({
message: z.string(),
userId: z.string(),
context: z.string(),
}),
outputSchema: z.object({
response: z.string(),
resolved: z.boolean(),
}),
execute: async ({ inputData, suspend }) => {
// 暂停,等待人工客服接入
const humanResponse = await suspend({
message: '正在为您转接人工客服...',
userId: inputData.userId,
context: inputData.context,
})
return {
response: humanResponse.reply,
resolved: true,
}
},
})
export const supportWorkflow = createWorkflow({
id: 'support-workflow',
inputSchema: z.object({ message: z.string(), userId: z.string() }),
outputSchema: z.object({ response: z.string(), resolved: z.boolean() }),
})
.then(classifyIntent)
.branch([
[async ({ inputData }) => inputData.intent === 'human', humanHandoff],
[async () => true, handleByAgent], // 默认路由到 Agent
])
.commit()
十、与竞品对比
10.1 Mastra vs LangChain.js
| 维度 | Mastra | LangChain.js |
|---|---|---|
| 设计哲学 | Opinionated,开箱即用 | Unopinionated,高度灵活 |
| 类型安全 | 原生 TypeScript,完整类型推导 | TypeScript 支持但不如原生 |
| 学习曲线 | 低,五原语模型清晰 | 中高,概念多且抽象 |
| Workflow | 内置图状态机,支持暂停/恢复 | 需要 LangGraph(额外依赖) |
| RAG | 内置 ETL 管道 | 需要组合多个模块 |
| Evals | 内置评估框架 | 需要 langsmith(外部服务) |
| 部署 | 内置多框架适配器 | 需要自行集成 |
10.2 Mastra vs Vercel AI SDK
| 维度 | Mastra | Vercel AI SDK |
|---|---|---|
| 定位 | 完整 Agent 框架 | AI 集成工具包 |
| Agent | 完整 Agent 系统 | 无内置 Agent |
| Workflow | 内置 | 无 |
| RAG | 内置 | 无 |
| Evals | 内置 | 无 |
| 模型路由 | 兼容 Vercel AI SDK | 原生支持 |
| 适用场景 | 复杂 AI 应用 | 简单 AI 集成 |
10.3 Mastra vs CrewAI(Python)
| 维度 | Mastra | CrewAI |
|---|---|---|
| 语言 | TypeScript | Python |
| 多 Agent | 支持,通过 Workflow 编排 | 原生支持 Crew 概念 |
| 类型安全 | 强 | 弱(Python 类型提示) |
| Web 生态 | 无缝集成 Next.js/React | 需要额外 API 层 |
| 部署 | Serverless 友好 | 通常需要服务器 |
十一、最佳实践与踩坑指南
11.1 工具设计原则
// ✅ 好的工具设计:职责单一、描述清晰
const searchTool = createTool({
id: 'search-products',
description: '在商品数据库中搜索产品。输入关键词,返回匹配的产品列表。仅用于搜索,不要用于下单。',
inputSchema: z.object({
keyword: z.string().describe('搜索关键词'),
category: z.string().optional().describe('商品类别过滤'),
limit: z.number().default(10).describe('返回结果数量'),
}),
execute: async ({ keyword, category, limit }) => {
// 实际搜索逻辑
},
})
// ❌ 不好的工具设计:职责模糊、描述不清
const doStuff = createTool({
id: 'do-stuff',
description: '做各种事情',
inputSchema: z.object({ query: z.string() }),
execute: async ({ query }) => { /* ... */ },
})
11.2 Agent 指令优化
// ✅ 好的指令:具体、有约束、有示例
const agent = new Agent({
instructions: `
你是一个代码审查助手。
审查规则:
1. 检查代码风格是否符合 ESLint 推荐配置
2. 检查是否有潜在的性能问题(如 N+1 查询)
3. 检查是否有安全漏洞(如 SQL 注入、XSS)
4. 检查错误处理是否完善
输出格式:
- 问题类型:[风格|性能|安全|错误处理]
- 严重程度:[低|中|高|严重]
- 位置:文件名:行号
- 描述:具体问题描述
- 建议:修复建议
不要对代码风格过于苛刻,聚焦在真正有影响的问题上。
`,
model: 'openai/gpt-5.5',
})
// ❌ 不好的指令:模糊、无约束
const badAgent = new Agent({
instructions: '帮我审查代码',
model: 'openai/gpt-5.5',
})
11.3 Workflow 错误处理
const resilientStep = createStep({
id: 'api-call',
inputSchema: z.object({ query: z.string() }),
outputSchema: z.object({ result: z.string() }),
execute: async ({ inputData }) => {
try {
const result = await externalAPI.call(inputData.query)
return { result }
} catch (error) {
if (error.status === 429) {
// 速率限制,等待后重试
await new Promise(r => setTimeout(r, 5000))
const retry = await externalAPI.call(inputData.query)
return { result: retry }
}
// 其他错误,返回降级结果
return { result: '服务暂时不可用,请稍后再试' }
}
},
})
11.4 常见踩坑点
- 模型字符串格式:必须用
provider/model(如openai/gpt-5.5),不要用provider:model或传入 provider 对象 - Tool 必须用 createTool:普通对象定义的工具会静默失败
- import 路径:Node.js 22+ 支持直接运行 .ts 文件,但 import 必须带文件扩展名
- 环境变量:不要在代码中硬编码 API Key,使用
.env文件
十二、总结与展望
12.1 核心价值
Mastra 解决了 TypeScript 生态在 AI Agent 领域的关键空白。它的核心价值在于:
- 降低门槛:前端/全栈工程师无需切换到 Python 就能构建 AI Agent
- 类型安全:利用 TypeScript 的类型系统在编译时捕获错误
- 全栈覆盖:从 Agent 到 Workflow 到 RAG 到 Evals,一站式解决
- 生产就绪:被 Replit、Fireworks 等公司验证过,不是玩具
12.2 适用场景
- SaaS 产品集成 AI:为现有产品添加智能对话、自动摘要等功能
- 内部工具:构建知识库问答、代码审查、文档生成等内部 AI 工具
- 客服系统:智能客服 + 人工兜底的混合方案
- 内容生产:自动化内容生成管道(写作 → 审核 → 发布)
- 数据分析:自然语言查询数据库
12.3 未来展望
Mastra 正在快速演进。从 16000+ 次提交的活跃度来看,社区和核心团队都在持续投入。未来值得关注的方向包括:
- 多模态支持:Voice Agent、图像理解
- 更强的多 Agent 协作:目前通过 Workflow 编排,未来可能内置更高级的协作原语
- 边缘部署:Cloudflare Workers、Vercel Edge Runtime 等边缘环境的优化
- 评估体系完善:更多开箱即用的评分器和基准测试
对于 TypeScript 开发者来说,Mastra 就是进入 AI Agent 世界的最佳门票。它不是 Python 框架的 JS 移植版,而是真正为 TypeScript 生态设计的原生解决方案。如果你正在考虑在自己的项目中集成 AI 能力,Mastra 绝对值得一试。
项目地址:https://github.com/mastra-ai/mastra
官方文档:https://mastra.ai/docs
Stars:16K+
License:MIT