源码级别解析 · 源码解析 · 2026最新版
2026-05-23 | 每日技术深度解读
来自Gatsby团队的新一代AI框架
涵盖从原型到生产的完整生命周期
解决AI应用开发的碎片化问题
npm create mastra@latest
# 或
pnpm create mastra
# 或
yarn create mastra
# 或
bunx create-mastra
支持所有主流包管理器
可与现有项目无缝集成
模块化设计,各组件松耦合
解决开放性任务,无需预设步骤
import { Agent } from '@mastra/core/agent'
export const testAgent = new Agent({
id: 'test-agent',
name: 'Test Agent',
instructions: 'You are a helpful assistant.',
model: 'openai/gpt-5.4',
})
核心智能体类的基本使用
确保智能体间的一致性和可观测性
import { Mastra } from '@mastra/core'
import { testAgent } from './agents/test-agent'
export const mastra = new Mastra({
agents: { testAgent },
})
在主Mastra实例中注册智能体
灵活的执行策略满足不同场景需求
// 获取已注册的智能体
const agent = mastra.getAgentById('test-agent')
// 生成完整响应
const response = await agent.generate({
message: 'Hello, how are you?'
})
// 流式响应
for await (const chunk of agent.stream({
message: 'Tell me about AI'
})) {
console.log(chunk.content)
}
两种主要调用方式的代码示例
适用于需要精确控制的多步骤任务
根据任务性质选择合适的模式
import { createStep } from '@mastra/core/workflows'
import { z } from 'zod'
const step1 = createStep({
id: 'step-1',
inputSchema: z.object({
message: z.string(),
}),
outputSchema: z.object({
formatted: z.string(),
}),
execute: async ({ inputData }) => {
const { message } = inputData
return {
formatted: message.toUpperCase(),
}
},
})
使用Zod进行类型安全的步骤定义
直观的控制流语法
const processData = createWorkflow({
id: 'process-data',
steps: [step1, step2]
})
// 顺序执行
const result1 = await processData
.execute(input)
.then(step1)
.then(step2)
// 并行执行
const result2 = await processData
.execute(input)
.parallel([step1, step2])
支持串行和并行执行模式
平衡自动化与人类监督
支持长时间运行的会话状态保持
解决上下文窗口限制问题
根据场景选择合适的内存类型
import { createMemory } from '@mastra/memory'
import { createLibSQLStorage } from '@mastra/libsql'
const storage = createLibSQLStorage({
url: 'file:./database.sqlite',
})
const memory = createMemory({
storage,
types: ['message-history', 'observational-memory'],
})
内存系统需要存储后端支持
防止上下文窗口溢出
简化多模型管理
// 配置多个模型
const models = {
openai: 'openai/gpt-5.4',
anthropic: 'anthropic/claude-3.5-sonnet',
gemini: 'gemini/gemini-2.0-flash',
}
// 智能体中使用
export const agent = new Agent({
id: 'multi-model-agent',
model: models.openai, // 可动态切换
})
支持跨提供商的统一接口
增强智能体的实际应用能力
import { createTool } from '@mastra/core/tool'
const weatherTool = createTool({
id: 'weather',
name: 'Get Weather',
description: 'Get current weather information',
execute: async ({ location }) => {
const response = await fetch(
`https://api.weather.com/${location}`
)
return response.json()
},
})
工具的标准定义方式
支持开源的MCP标准
确保AI应用的可靠性
import { createObservability } from '@mastra/observability'
const observability = createObservability({
enabled: true,
// 性能追踪
tracing: {
enabled: true,
sampleRate: 1.0,
},
// 指标收集
metrics: {
enabled: true,
interval: 10000,
},
})
内置的观测性系统配置
确保AI输出的质量和一致性
适应不同的基础设施需求
提升开发效率和调试能力
// 在代码中启用Studio
export const mastra = new Mastra({
agents: { testAgent },
// 启用Studio功能
studio: {
enabled: true,
port: 3000,
},
})
无缝集成到开发流程
已验证的生产级应用
提升客户服务质量
提升员工工作效率
export const codeAssistant = new Agent({
id: 'code-assistant',
name: '开发助手',
instructions: '''你是一个专业的软件开发助手,擅长:
- 代码审查和优化
- 调试和问题诊断
- 文档生成
- 架构建议
请提供详细的技术分析和最佳实践建议。''',
model: 'openai/gpt-5.4',
tools: [codeReviewTool, debugTool],
})
具备专业领域知识的智能体
保持长期对话的连贯性
确保系统的稳定性
export const resilientAgent = new Agent({
id: 'resilient-agent',
// 配置重试策略
retry: {
maxAttempts: 3,
delay: 1000,
backoff: 'exponential',
},
// 错误回调
onError: (error, context) => {
console.error('Agent error:', error)
// 记录错误信息
observability.track('agent_error', {
error: error.message,
context: context.input,
})
},
})
内置的弹性处理机制
保护敏感数据和用户隐私
确保大规模部署的性能
快速成长的开发者生态
降低学习曲线,提高上手速度
mastra-project/
├── src/
│ ├── mastra/ # Mastra实例配置
│ │ ├── index.ts # 主配置文件
│ │ └── config.ts # 系统配置
│ ├── agents/ # 智能体定义
│ │ ├── test-agent.ts
│ │ └── weather-agent.ts
│ ├── workflows/ # 工作流定义
│ │ ├── data-workflow.ts
│ │ └── approval-workflow.ts
│ ├── tools/ # 工具定义
│ │ ├── weather.ts
│ │ └── database.ts
│ ├── memory/ # 内存配置
│ │ └── storage.ts
│ └── utils/ # 工具函数
│ └── helpers.ts
├── templates/ # 项目模板
├── studio/ # Studio界面
└── package.json
推荐的项目组织结构
平滑的迁移路径
在多项指标上表现优异
持续创新的开发路线
基于大量项目经验的总结
export const productionMastra = new Mastra({
// 生产环境优化
env: 'production',
// 观测性配置
observability: {
enabled: true,
tracing: {
sampleRate: 0.1, // 生产环境采样
},
},
// 内存配置
memory: {
storage: createRedisStorage({
url: process.env.REDIS_URL,
}),
types: ['observational-memory', 'working-memory'],
},
// 错误处理
onError: handleProductionError,
})
生产环境的完整配置示例
重新定义AI应用开发标准
感谢阅读!
访问 https://atcfu.com/ai-articles/mastra-ai-framework/ 回顾本文