Mastra快速开始:从零搭建AI代理的完整教程

【免费下载链接】mastra Mastra 项目为大家提供了轻松创建定制化 AI 聊天机器人的能力。源项目地址:https://github.com/mastra-ai/mastra 【免费下载链接】mastra 项目地址: https://gitcode.com/GitHub_Trending/ma/mastra

前言:为什么选择Mastra?

还在为构建AI代理的复杂性而头疼吗?面对LLM模型集成、工具调用、工作流编排等繁琐任务,你是否希望有一个统一、类型安全的解决方案?Mastra正是为此而生——一个专为TypeScript开发者设计的AI代理框架,让你能够快速构建功能强大的AI应用。

通过本教程,你将学会:

  • ✅ 快速搭建Mastra开发环境
  • ✅ 创建你的第一个AI代理(Agent)
  • ✅ 配置LLM模型和工具集成
  • ✅ 构建自动化工作流(Workflow)
  • ✅ 部署和测试完整的AI应用

环境准备与项目初始化

系统要求

  • Node.js 20.0+ 版本
  • npm 或 pnpm 包管理器
  • 任意LLM提供商API密钥(OpenAI、Anthropic、Google Gemini等)

创建新项目

使用Mastra官方CLI工具快速初始化项目:

npx create-mastra@latest my-ai-agent
cd my-ai-agent
npm install

配置环境变量

创建 .env 文件并添加你的API密钥:

OPENAI_API_KEY=your_openai_api_key_here
# 或使用其他提供商
ANTHROPIC_API_KEY=your_anthropic_api_key_here
GOOGLE_GENERATIVE_AI_API_KEY=your_google_api_key_here

构建你的第一个AI代理

代理定义示例

// src/mastra/agents/catExpert.ts
import { openai } from '@ai-sdk/openai';
import { Agent } from '@mastra/core';
import { z } from 'zod';

// 定义输出schema
const speciesSchema = z.object({
  species: z.string(),
  scientificName: z.string(),
  habitat: z.string(),
  conservationStatus: z.string()
});

export const catExpert = new Agent({
  name: 'cat-expert',
  instructions: `
你是一位专业的猫科动物专家,拥有全面的猫科动物知识,从家猫品种到野生大型猫科动物。
作为终身猫科专家,你深入了解它们的行为、生物学、社会结构和进化历史。
回答问题时请提供准确、简洁的信息,并使用指定的输出格式。
  `,
  model: openai('gpt-4o'),
  tools: [], // 可以添加自定义工具
  output: speciesSchema
});

主应用入口

// src/index.ts
import { z } from 'zod';
import { mastra } from './mastra';

// 定义查询schema
const querySchema = z.object({
  question: z.string().min(1, "问题不能为空")
});

const main = async () => {
  const agent = mastra.getAgent('cat-expert');
  
  try {
    // 执行代理查询
    const result = await agent.generate(
      '世界上最濒危的猫科动物是什么?',
      { output: speciesSchema }
    );

    if (result?.object) {
      const data = speciesSchema.parse(result.object);
      console.log('🐱 查询结果:');
      console.log(`物种: ${data.species}`);
      console.log(`学名: ${data.scientificName}`);
      console.log(`栖息地: ${data.habitat}`);
      console.log(`保护状态: ${data.conservationStatus}`);
    }
  } catch (error) {
    console.error('❌ 执行错误:', error);
  }
};

// 启动应用
main();

Mastra核心配置

主配置文件

// src/mastra/index.ts
import { Mastra } from '@mastra/core';
import { PinoLogger } from '@mastra/loggers';
import { catExpert } from './agents/catExpert';
import { researchWorkflow } from './workflows/research';

export const mastra = new Mastra({
  agents: { 
    'cat-expert': catExpert 
  },
  workflows: {
    'research-workflow': researchWorkflow
  },
  logger: new PinoLogger({
    name: 'Mastra-App',
    level: 'info', // 开发时可用 'debug'
    prettyPrint: process.env.NODE_ENV !== 'production'
  }),
  // 可配置内存、RAG等高级功能
  memory: {
    type: 'in-memory' // 或配置持久化存储
  }
});

构建自动化工作流

工作流定义示例

// src/mastra/workflows/research.ts
import { Workflow } from '@mastra/core';
import { z } from 'zod';

const researchInput = z.object({
  topic: z.string(),
  depth: z.enum(['basic', 'detailed', 'comprehensive']).default('basic')
});

export const researchWorkflow = new Workflow({
  name: 'research-workflow',
  input: researchInput,
  steps: [
    {
      id: 'gather-info',
      action: async (ctx) => {
        const { topic, depth } = ctx.input;
        // 这里可以集成网络搜索、数据库查询等工具
        return { collectedData: `关于${topic}的${depth}级别信息` };
      }
    },
    {
      id: 'analyze-data',
      action: async (ctx) => {
        const previousData = ctx.previousStepResult;
        // 数据分析逻辑
        return { analysis: `分析完成: ${previousData.collectedData}` };
      }
    },
    {
      id: 'generate-report',
      action: async (ctx) => {
        // 生成最终报告
        return { 
          report: '分析报告生成完成',
          timestamp: new Date().toISOString()
        };
      }
    }
  ]
});

项目结构与架构

mermaid

目录结构说明

src/
├── index.ts          # 应用入口
├── mastra/           # Mastra配置目录
│   ├── index.ts      # 主配置
│   ├── agents/       # 代理定义
│   │   └── catExpert.ts
│   ├── workflows/    # 工作流定义
│   │   └── research.ts
│   └── tools/        # 自定义工具
│       └── webSearch.ts
├── types/            # TypeScript类型定义
│   └── index.ts
└── utils/            # 工具函数
    └── helpers.ts

运行与测试

启动开发服务器

# 开发模式运行
npm run dev

# 或直接使用mastra CLI
npx mastra dev

测试你的代理

创建测试脚本验证功能:

// test/agent.test.ts
import { mastra } from '../src/mastra';
import { expect, test } from 'vitest';

test('猫科专家代理应返回有效数据', async () => {
  const agent = mastra.getAgent('cat-expert');
  const result = await agent.generate('狮子的科学分类是什么?');
  
  expect(result).toBeDefined();
  expect(result?.object).toHaveProperty('species');
  expect(result?.object).toHaveProperty('scientificName');
});

运行测试:

npm test

部署与生产环境

构建生产版本

# 构建项目
npm run build

# 生产环境运行
npm start

环境配置最佳实践

// 环境感知配置
const isProduction = process.env.NODE_ENV === 'production';

export const mastra = new Mastra({
  logger: new PinoLogger({
    level: isProduction ? 'info' : 'debug',
    // 生产环境禁用美化输出
    prettyPrint: !isProduction
  }),
  // 生产环境配置持久化存储
  memory: isProduction ? {
    type: 'redis',
    config: {
      url: process.env.REDIS_URL
    }
  } : { type: 'in-memory' }
});

常见问题与解决方案

问题排查表

问题现象 可能原因 解决方案
API密钥错误 环境变量未正确设置 检查.env文件格式和变量名
模型响应慢 网络问题或模型负载高 配置超时设置,使用更轻量模型
类型错误 Zod schema不匹配 检查输出schema定义
内存泄漏 未正确清理资源 配置适当的内存管理

性能优化建议

// 优化配置示例
export const optimizedAgent = new Agent({
  model: openai('gpt-4o', {
    temperature: 0.7,
    maxTokens: 1000,
    timeout: 30000 // 30秒超时
  }),
  // 启用流式响应
  stream: true,
  // 缓存配置
  cache: {
    enabled: true,
    ttl: 3600 // 1小时缓存
  }
});

进阶功能探索

RAG(检索增强生成)集成

// 配置知识库检索
import { createRAGPipeline } from '@mastra/rag';

const knowledgeBase = createRAGPipeline({
  documents: ['./docs/**/*.md'], // 文档路径
  chunking: {
    strategy: 'semantic',
    maxChunkSize: 1000
  },
  embedding: {
    provider: 'openai',
    model: 'text-embedding-3-small'
  },
  vectorStore: {
    type: 'memory' // 或配置持久化向量数据库
  }
});

// 在代理中使用RAG
agent.useRAG(knowledgeBase);

工具集成示例

// 自定义天气查询工具
import { Tool } from '@mastra/core';
import { z } from 'zod';

export const weatherTool = new Tool({
  name: 'get-weather',
  description: '获取指定城市的天气信息',
  input: z.object({
    city: z.string(),
    unit: z.enum(['celsius', 'fahrenheit']).default('celsius')
  }),
  execute: async ({ city, unit }) => {
    // 调用天气API
    const response = await fetch(`https://api.weatherapi.com/v1/current.json?key=${process.env.WEATHER_API_KEY}&q=${city}`);
    const data = await response.json();
    
    return {
      temperature: unit === 'celsius' ? data.current.temp_c : data.current.temp_f,
      condition: data.current.condition.text,
      humidity: data.current.humidity
    };
  }
});

总结与下一步

通过本教程,你已经掌握了Mastra的核心概念和基本用法。接下来可以:

  1. 探索更多集成:尝试集成数据库、外部API等
  2. 构建复杂工作流:实现多步骤的自动化业务流程
  3. 性能优化:配置缓存、批处理等高级功能
  4. 监控与日志:集成监控工具跟踪代理性能

Mastra为AI应用开发提供了强大的基础设施,让你能够专注于业务逻辑而不是底层技术细节。开始构建你的智能代理吧!


提示:记得定期查看Mastra官方文档获取最新功能和最佳实践。遇到问题时,可以访问项目社区获取帮助。

【免费下载链接】mastra Mastra 项目为大家提供了轻松创建定制化 AI 聊天机器人的能力。源项目地址:https://github.com/mastra-ai/mastra 【免费下载链接】mastra 项目地址: https://gitcode.com/GitHub_Trending/ma/mastra

Logo

更多推荐