首页 / 编程实战 / Mastra 1.0 构建生产级 TypeScript AI Agent 5 次阅读
实战教程

Mastra 1.0 构建生产级 TypeScript AI Agent

2026-03-01 TypeScriptAI AgentMastra大模型工作流

AI Agent 开发正在经历从 Python 主导到 TypeScript 崛起的范式转变。Mastra 1.0 作为专为生产环境设计的 TypeScript AI Agent 框架,提供端到端的完整解决方案:从原型开发到生产部署,从单一 Agent 到复杂 Workflow,从短期记忆到长期语义存储。

本教程将带你从零开始,用 Mastra 1.0 构建一个可运行的天气查询 Agent,涵盖核心概念环境搭建代码实现生产部署全流程。完成后,你将掌握构建生产级 AI Agent 的完整技能栈。

1

环境准备与项目初始化

Mastra 支持多种包管理器,推荐使用 pnpmnpm。确保 Node.js 版本 ≥18。

创建 Mastra 项目

>_ bash
# 使用 npm 创建项目
npm create mastra@latest my-mastra-app

cd my-mastra-app
npm install

# 或使用 pnpm
pnpm create mastra
pnpm install
项目初始化:CLI 交互式创建流程
💡 提示

💡 CLI 参数说明

- --template:选择项目模板(默认、bare、full)

- --no-example:跳过示例代码生成

- --components agents,tools,workflows:按需选择组件类型

2

配置环境变量

在项目根目录创建 .env 文件,配置 LLM 提供商 API Key。Mastra 支持 OpenAI、Anthropic、Google 等主流模型。

.env 环境配置

>_ bash
# OpenAI(推荐)
OPENAI_API_KEY=sk-your-api-key-here

# 或使用 Anthropic
# ANTHROPIC_API_KEY=sk-ant-...

# 或使用 Google
# GOOGLE_GENERATIVE_AI_API_KEY=...
3

创建自定义 Tool:天气查询工具

Tool 是 Agent 执行具体任务的能力单元。使用 createTool 创建类型安全的工具函数,需定义输入/输出 Schema 和执行逻辑。

src/mastra/tools/weather-tool.ts

>_ typescript
import { createTool } from "@mastra/core/tools";
import { z } from "zod";

export const weatherTool = createTool({
  id: "fetch-weather",
  name: "Weather Tool",
  description: "Fetches current weather data for a given city",
  
  // 输入验证 Schema
  inputSchema: z.object({
    city: z.string().describe("City name, e.g., 'Tokyo', 'New York'"),
  }),
  
  // 输出验证 Schema
  outputSchema: z.object({
    temp: z.number().describe("Temperature in Celsius"),
    condition: z.string().describe("Weather condition"),
    humidity: z.number().optional().describe("Humidity percentage"),
  }),
  
  // 执行逻辑
  execute: async ({ inputData }) => {
    const { city } = inputData;
    
    // 使用真实天气 API(示例使用 OpenWeatherMap)
    const apiKey = process.env.OPENWEATHER_API_KEY;
    const response = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`
    );
    
    if (!response.ok) {
      throw new Error(`Failed to fetch weather for ${city}`);
    }
    
    const data = await response.json();
    
    return {
      temp: Math.round(data.main.temp),
      condition: data.weather[0].description,
      humidity: data.main.humidity,
    };
  },
});
Tool 架构图:输入 Schema、执行逻辑、输出 Schema 三层结构
⚠️ 注意

⚠️ 注意事项

- inputSchemaoutputSchema 必须使用 Zod 定义,确保类型安全

- execute 函数返回 Promise,支持异步操作

- 错误处理要在工具内部完成,避免抛出未处理异常

4

定义 Agent:天气助手

Agent 是 Mastra 的核心抽象,具备自主决策能力。配置时需指定模型、工具、记忆系统和行为指令。

src/mastra/agents/weather-agent.ts

>_ typescript
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { Memory } from "@mastra/core/memory";
import { LibSQLStore } from "@mastra/libsql";
import { weatherTool } from "../tools/weather-tool";

export const weatherAgent = new Agent({
  id: "weather-agent",
  name: "Weather Assistant",
  description: "An AI agent that provides weather information",
  
  // 使用 OpenAI GPT-4 Turbo
  model: openai("gpt-4-turbo"),
  
  // 系统指令:定义 Agent 行为准则
  instructions: `
You are a helpful weather assistant. Follow these rules:
1. ALWAYS use the weatherTool to fetch weather data
2. Never hallucinate weather information
3. If the tool fails, explain the issue to the user
4. Provide temperature in Celsius and describe conditions in simple terms
5. Suggest appropriate clothing based on weather
  `.trim(),
  
  // 注册可用工具
  tools: {
    weatherTool,
  },
  
  // 配置长期记忆(可选)
  memory: new Memory({
    storage: new LibSQLStore({
      url: "file:./mastra.db",
    }),
  }),
  
  // 限制最大推理步骤,防止无限循环
  maxSteps: 5,
});
5

构建 Workflow:多步骤编排

Workflow 用于编排复杂的多步骤任务,支持图引擎驱动的数据流条件分支并行执行状态管理。适合需要显式控制执行顺序的场景。

src/mastra/workflows/weather-workflow.ts

>_ typescript
import {
  createWorkflow,
  createStep,
  WorkflowStep,
  WorkflowEngine,
} from "@mastra/core/workflows";
import { z } from "zod";
import { weatherTool } from "../tools/weather-tool";

// 定义步骤 1:获取天气数据
const getWeatherStep = createStep({
  id: "get-weather",
  inputSchema: z.object({
    city: z.string(),
  }),
  outputSchema: z.object({
    temp: z.number(),
    condition: z.string(),
    humidity: z.number(),
  }),
  execute: async ({ inputData }) => {
    return await weatherTool.execute({ inputData });
  },
});

// 定义步骤 2:生成穿衣建议
const clothingAdviceStep = createStep({
  id: "clothing-advice",
  inputSchema: z.object({
    temp: z.number(),
    condition: z.string(),
  }),
  outputSchema: z.object({
    advice: z.string(),
  }),
  execute: async ({ inputData }) => {
    const { temp, condition } = inputData;
    
    let advice = "";
    if (temp < 10) {
      advice = "穿厚外套、羽绒服,注意保暖";
    } else if (temp < 20) {
      advice = "穿长袖衬衫或薄外套";
    } else if (temp < 30) {
      advice = "穿短袖 T 恤,保持清爽";
    } else {
      advice = "穿轻薄透气衣物,注意防晒";
    }
    
    if (condition.includes("雨")) {
      advice += ",记得带伞";
    }
    
    return { advice };
  },
});

// 组装 Workflow
export const weatherWorkflow = createWorkflow({
  id: "weather-workflow",
  name: "Weather Information Workflow",
  description: "Get weather data and generate clothing advice",
  inputSchema: z.object({ city: z.string() }),
  outputSchema: z.object({
    temp: z.number(),
    condition: z.string(),
    humidity: z.number(),
    advice: z.string(),
  }),
})
  // 顺序执行:先获取天气,再生成建议
  .then(getWeatherStep)
  .then(clothingAdviceStep)
  .commit();
Workflow 流程图:两个步骤的顺序执行与数据传递
6

注册并运行 Agent 与 Workflow

src/mastra/index.ts 中注册所有组件,Mastra 会自动暴露 REST API 和 DevTools 面板。

src/mastra/index.ts - 注册组件

>_ typescript
import { Mastra } from "@mastra/core";
import { weatherAgent } from "./agents/weather-agent";
import { weatherWorkflow } from "./workflows/weather-workflow";

export const mastra = new Mastra({
  // 注册 Agents
  agents: {
    weatherAgent,
  },
  
  // 注册 Workflows
  workflows: {
    weatherWorkflow,
  },
  
  // 启用可观测性(可选)
  // observability: {
  //   traceExport: new ConsoleSpanExporter(),
  // },
});

调用 Agent 和 Workflow

>_ typescript
import { mastra } from "./mastra";

async function main() {
  // ===== 方式 1:直接调用 Agent =====
  const agent = mastra.getAgent("weather-agent");
  
  // 简单查询
  const result = await agent.generate("东京的天气怎么样?");
  console.log("Agent 回复:", result.text);
  
  // 流式输出(适合 UI 展示)
  const stream = await agent.stream("北京的天气怎么样?");
  for await (const chunk of stream.textStream) {
    process.stdout.write(chunk);
  }
  console.log();
  
  // ===== 方式 2:运行 Workflow =====
  const workflow = mastra.getWorkflow("weather-workflow");
  const run = await workflow.createRun();
  
  const wfResult = await run.start({
    inputData: { city: "Shanghai" },
  });
  
  if (wfResult.status === "success") {
    console.log("天气:", wfResult.result.temp, "°C");
    console.log("状况:", wfResult.result.condition);
    console.log("穿衣建议:", wfResult.result.advice);
  }
}

main().catch(console.error);

Agent vs Workflow 选择指南

  • Agent:适合开放型任务,需要自主决策和工具选择(如"帮我研究竞争对手")
  • Workflow:适合固定流程,需要显式控制执行顺序和数据流(如"获取天气→生成建议→发送邮件")
  • 混合模式:在 Workflow 中嵌入 Agent,结合两者的优势
7

启动开发服务器与调试

Mastra 提供内置的开发服务器和可视化 DevTools,支持实时日志、步骤追踪和性能分析。

启动开发服务器

>_ bash
# 启动开发服务器(监听文件变化)
npm run dev

# 输出示例:
# ✓ Mastra dev server running on:
# - REST API: http://localhost:4111
# - DevTools: http://localhost:4111/dev
# - API Docs: http://localhost:4111/api-docs
Mastra DevTools 界面:显示 Agent 执行步骤和工具调用详情
💡 提示

💡 DevTools 功能

- 实时查看 Agent 思考过程和工具调用

- 追踪 Workflow 执行路径和数据流

- 查看 token 使用量和性能指标

- 支持重放历史执行记录

8

高级功能:Memory 语义记忆系统

Mastra 的 Memory 系统支持消息历史工作记忆语义召回。适合构建具有长期上下文感知能力的对话型 Agent。

配置 Memory 实现对话连续性

>_ typescript
import { Memory } from "@mastra/core/memory";
import { LibSQLStore } from "@mastra/libsql";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";

// 创建记忆存储
const memory = new Memory({
  // 使用 LibSQL 本地存储
  storage: new LibSQLStore({
    url: "file:./mastra.db",
  }),
  
  // 语义召回配置
  semanticRecall: {
    enabled: true,
    topK: 3,  // 召回最相关的 3 条历史消息
  },
  
  // 工作记忆(短期上下文)
  workingMemory: {
    enabled: true,
    maxMessages: 10,
  },
});

export const chatAgent = new Agent({
  id: "chat-agent",
  model: openai("gpt-4-turbo"),
  instructions: "You are a helpful assistant with memory.",
  memory,
});

// 使用示例:
// const response = await chatAgent.generate("还记得我昨天问的问题吗?");
// 系统会自动召回相关历史消息并注入上下文
对比项方案 A方案 B
适用场景Agent:开放型任务,自主决策Workflow:固定流程,显式编排
执行方式模型驱动,动态选择工具代码驱动,按定义顺序执行
可预测性较低,依赖模型判断高,完全由代码控制
调试难度较高,需要追踪推理链较低,标准调试工具可用

常见问题

Q:Mastra 相比 LangChain.js 有什么优势?
Mastra 是 TypeScript-first 设计,类型推导更完善;内置 DevTools 可视化调试;Workflow 引擎支持图结构编排;原生支持 OpenTelemetry 可观测性。LangChain 更偏向 Python,TS 版本功能滞后。
Q:如何限制 Agent 的 token 使用量避免费用失控?
有三种方式:① 设置 maxSteps 限制最大推理步数;② 在模型配置中设置 maxTokens;③ 使用 Evals 监控 token 使用并在 CI 中设置阈值告警。生产环境建议同时使用这三种方式。
Q:生产部署需要注意什么?
① 使用 npm run build 构建生产版本;② 配置环境变量(不要将密钥写入代码);③ 启用 observability 接入监控系统;④ 为 Tool 添加重试逻辑和超时处理;⑤ 使用 Docker 容器化部署保证环境一致性。
Q:支持哪些 LLM 提供商?
Mastra 通过 AI SDK 支持 OpenAI、Anthropic、Google、Groq、Ollama 等主流提供商。使用 @ai-sdk/openai@ai-sdk/anthropic 等包切换模型,代码无需修改。
5 分钟 从 0 到运行第一个 Agent
100% TypeScript 类型安全
6+ 内置 LLM 提供商支持
OpenTelemetry 原生可观测性集成

总结

本教程从零开始构建了一个完整的 Mastra 1.0 AI Agent 项目,涵盖环境搭建Tool 创建Agent 配置Workflow 编排Memory 集成开发调试全流程。 核心要点: - Agent 适合开放型任务,通过工具和记忆系统实现自主决策 - Workflow 适合固定流程,支持图引擎驱动的显式编排 - Memory 系统提供长期上下文感知能力 - DevTools 可视化调试大幅提升开发效率 下一步学习: - 探索 [RAG 检索增强](https://mastra.ai/docs/rag) 提升回答质量 - 使用 [Evals](https://mastra.ai/docs/evals) 构建持续评估体系 - 集成 [OpenTelemetry](https://mastra.ai/docs/observability) 实现生产监控

选择栏目
今日简报 播客电台 实战教程 AI挣钱计划 关于我
栏目
全球AI日报国内AI日报全球金融日报国内金融日报全球大新闻日报国内大新闻日报Claude Code 玩法日报OpenClaw 动态日报GitHub 热门项目日报AI工具实战AI应用开发编程实战工作流自动化AI原理图解AI Agent开发AI变现案例库AI工具创收AI内容变现AI接单提效变现前沿研究
我的收藏
播客版
0:00
--:--