Skip to content

Mastra Agent 开发指南

使用 Mastra 构建生产级 AI Agent 系统的完整指南

📋 概述

Mastra 是一个用于构建 AI 应用的 TypeScript 框架。其 Agent 模块提供了一套完整的工具,用于构建能够自主调用工具、协同工作、拥有记忆的智能代理系统。

Mastra Agent 的核心特性

功能模块核心能力
Agent Networks多 Agent 协同、动态路由、复杂任务编排
Processors输入输出处理、消息转换、上下文管理
Guardrails安全防护、提示词注入检测、内容审核
Agent Memory长期记忆、上下文管理、对话历史
Structured Output类型安全的结构化输出
Tool Approval人机协作、工具调用审批
Voice语音交互、TTS/STT、实时对话

🏗️ 基础 Agent 配置

创建基础 Agent

typescript
import { Agent } from '@mastra/core/agent';
import { createTool } from '@mastra/core';
import { z } from 'zod';

export const weatherAgent = new Agent({
  id: 'weather-agent',
  name: 'Weather Agent',
  instructions: 'You are a helpful weather assistant.',
  model: 'openai/gpt-4o',
  tools: {
    getWeather: createTool({
      id: 'get-weather',
      description: 'Get current weather for a location',
      inputSchema: z.object({
        location: z.string().describe('City name'),
      }),
      outputSchema: z.object({
        temperature: z.number(),
        condition: z.string(),
      }),
      execute: async ({ location }) => {
        // 实际实现中调用天气 API
        return {
          temperature: 72,
          condition: 'Sunny',
        };
      },
    }),
  },
});

使用 Agent

typescript
// 流式响应
const stream = await weatherAgent.stream('What is the weather in San Francisco?');

for await (const event of stream) {
  if (event.type === 'text-delta') {
    process.stdout.write(event.data);
  }
}

// 生成完整响应
const result = await weatherAgent.generate('What is the weather in London?');
console.log(result.text);

🧠 Agent 记忆系统

配置记忆

Mastra 提供持久化记忆存储,让 Agent 能够记住对话历史:

typescript
import { Agent } from '@mastra/core/agent';
import { Memory } from '@mastra/memory';
import { LibSQLStore } from '@mastra/libsql';

const agent = new Agent({
  id: 'assistant',
  name: 'Personal Assistant',
  instructions: 'You are a helpful personal assistant with memory.',
  model: 'openai/gpt-4o',
  memory: new Memory({
    storage: new LibSQLStore({
      id: 'agent-memory',
      url: 'file:./mastra.db',
    }),
  }),
});

// 使用记忆进行对话
const stream = await agent.stream('My name is Alice', {
  threadId: 'user-123',
});

// 后续对话会记住上下文
const stream2 = await agent.stream('What is my name?', {
  threadId: 'user-123',
});

记忆存储选项

存储类型使用场景
LibSQL本地开发、轻量级应用
PostgreSQL生产环境、高并发场景
Redis缓存层、高性能读写

📝 结构化输出

使用 Zod schema 确保 Agent 输出符合预期格式:

typescript
import { Agent } from '@mastra/core/agent';
import { z } from 'zod';

const analysisAgent = new Agent({
  id: 'analysis-agent',
  name: 'Analysis Agent',
  instructions: 'Analyze customer feedback and provide structured insights.',
  model: 'openai/gpt-4o',
});

// 定义输出 schema
const feedbackSchema = z.object({
  sentiment: z.enum(['positive', 'neutral', 'negative']),
  summary: z.string(),
  keyIssues: z.array(z.string()),
  priority: z.number().min(1).max(5),
});

// 生成结构化输出
const result = await analysisAgent.generate('Analyze this feedback: ...', {
  output: feedbackSchema,
});

// result.object 自动符合 schema 类型
console.log(result.object.sentiment);
console.log(result.object.keyIssues);

🌐 Agent Networks

Agent Networks 是 Mastra 的核心特性之一,允许多个 Agent、Workflow 和 Tool 协同完成复杂任务。

何时使用 Networks

  • 任务需要多个专业化 Agent 协作
  • 需要动态路由到不同的执行路径
  • 任务执行顺序无法预先确定
  • 需要 LLM 推理来决定下一步操作

核心原则

  1. 必须配置记忆: Networks 使用记忆存储任务历史和判断任务完成状态
  2. 基于描述路由: Agent 根据 primitives 的描述选择合适的执行路径
  3. 自动优先级: 功能重叠时,优先选择更具体的 primitive

创建 Agent Network

typescript
import { Agent } from '@mastra/core/agent';
import { Memory } from '@mastra/memory';
import { LibSQLStore } from '@mastra/libsql';

// 1. 定义专业化 Agent
const researchAgent = new Agent({
  id: 'research-agent',
  name: 'Research Agent',
  description: `
    This agent gathers concise research insights in bullet-point form.
    It extracts key facts without generating full responses.
  `,
  instructions: 'You are a research specialist. Provide bullet-point summaries.',
  model: 'openai/gpt-4o',
  tools: {
    webSearch: searchTool,
    readDocument: documentTool,
  },
});

const writingAgent = new Agent({
  id: 'writing-agent',
  name: 'Writing Agent',
  description: `
    This agent turns researched material into well-structured written content.
    It produces full-paragraph reports suitable for articles and blog posts.
  `,
  instructions: 'You are a professional writer. Write in full paragraphs.',
  model: 'openai/gpt-4o',
});

// 2. 定义 Workflow (可选)
const cityWorkflow = createWorkflow({
  id: 'city-workflow',
  description: `
    This workflow handles city-specific research tasks.
    Use it when the user input includes a city to be researched.
  `,
  inputSchema: z.object({
    city: z.string(),
  }),
  outputSchema: z.object({
    text: z.string(),
  }),
});

// 3. 创建路由 Agent
const routingAgent = new Agent({
  id: 'routing-agent',
  name: 'Routing Agent',
  instructions: `
    You are a network of writers and researchers.
    Always respond with a complete report—no bullet points.
    Write in full paragraphs, like a blog post.
  `,
  model: 'openai/gpt-4o',
  agents: {
    researchAgent,
    writingAgent,
  },
  workflows: {
    cityWorkflow,
  },
  tools: {
    weatherTool,
  },
  memory: new Memory({
    storage: new LibSQLStore({
      id: 'network-memory',
      url: 'file:./mastra.db',
    }),
  }),
});

调用 Network

typescript
const stream = await routingAgent.network('Write a comprehensive report about Paris', {
  threadId: 'research-001',
});

for await (const event of stream) {
  console.log(event.type, event.data);
}

编写高质量描述

Agent 描述最佳实践:

typescript
// ❌ 差:太宽泛
description: 'This agent helps with research'

// ✅ 好:具体说明能力和输出格式
description: `
  This agent gathers concise research insights in bullet-point form.
  It's designed to extract key facts without generating full responses or narrative content.
`

Workflow 描述最佳实践:

typescript
// ✅ 包含触发条件和输入输出说明
const workflow = createWorkflow({
  description: `
    This workflow handles city-specific research tasks.
    It first gathers factual information, then synthesizes into a written report.
    Use when the user input includes a city to be researched.
  `,
  inputSchema: z.object({ city: z.string() }),
  outputSchema: z.object({ text: z.string() }),
});

🔧 Processors

Processors 用于在消息到达 LLM 之前(Input Processor)或之后(Output Processor)对其进行转换、验证和控制。

何时使用 Processors

  • 规范化或验证用户输入
  • 添加安全防护
  • 检测提示词注入或越狱尝试
  • 内容审核和合规性检查
  • 转换消息(语言翻译、工具调用过滤)
  • 限制 token 使用或消息历史长度
  • 删除敏感信息 (PII)
  • 应用自定义业务逻辑

添加 Processors

typescript
import { Agent } from '@mastra/core/agent';
import { ModerationProcessor } from '@mastra/core/processors';

const moderatedAgent = new Agent({
  id: 'moderated-agent',
  name: 'Moderated Agent',
  instructions: 'You are a helpful assistant',
  model: 'openai/gpt-4o',
  inputProcessors: [
    new ModerationProcessor({
      model: 'openai/gpt-4o-mini',
      categories: ['hate', 'harassment', 'violence'],
      threshold: 0.7,
      strategy: 'block',
    }),
  ],
});

执行顺序

Processors 按照数组中的顺序执行:

typescript
inputProcessors: [
  new UnicodeNormalizer(),         // 1. 规范化 Unicode
  new PromptInjectionDetector(),   // 2. 检测提示词注入
  new ModerationProcessor(),       // 3. 内容审核
],

创建自定义 Input Processor

typescript
import type { Processor, MastraDBMessage, RequestContext } from '@mastra/core';

export class CustomInputProcessor implements Processor {
  id = 'custom-input';

  async processInput({
    messages,
    systemMessages,
    context,
  }: {
    messages: MastraDBMessage[];
    systemMessages: CoreMessage[];
    context: RequestContext;
  }): Promise<MastraDBMessage[]> {
    // 转换消息为小写
    return messages.map((msg) => ({
      ...msg,
      content: {
        ...msg.content,
        content: msg.content.content.toLowerCase(),
      },
    }));
  }
}

修改系统消息

某些场景下需要修改系统消息(例如为小模型精简提示词):

typescript
import type { Processor, CoreMessage, MastraDBMessage } from '@mastra/core';

export class SystemTrimmer implements Processor {
  id = 'system-trimmer';

  async processInput({
    messages,
    systemMessages,
  }): Promise<{
    messages: MastraDBMessage[];
    systemMessages: CoreMessage[];
  }> {
    // 截断系统消息以适应小模型
    const trimmedSystemMessages = systemMessages.map((msg) => ({
      ...msg,
      content:
        typeof msg.content === 'string'
          ? msg.content.substring(0, 500)
          : msg.content,
    }));

    return {
      messages,
      systemMessages: trimmedSystemMessages,
    };
  }
}

创建自定义 Output Processor

typescript
import type { Processor, StreamEvent } from '@mastra/core';

export class CustomOutputProcessor implements Processor {
  id = 'custom-output';

  async processOutput({
    events,
    context,
  }: {
    events: StreamEvent[];
    context: RequestContext;
  }): Promise<StreamEvent[]> {
    // 过滤或转换输出事件
    return events.map((event) => {
      if (event.type === 'text-delta') {
        return {
          ...event,
          data: event.data.toUpperCase(),
        };
      }
      return event;
    });
  }
}

内置工具 Processors

TokenLimiter

限制消息历史的 token 数量:

typescript
import { TokenLimiter } from '@mastra/core/processors';

new TokenLimiter({
  maxTokens: 1000,
  strategy: 'truncate-oldest',
})

ToolCallFilter

过滤特定的工具调用:

typescript
import { ToolCallFilter } from '@mastra/core/processors';

new ToolCallFilter({
  allowedTools: ['search', 'calculate'],
  strategy: 'remove',
})

🛡️ Guardrails (安全防护)

Guardrails 通过 Processors 实现安全控制,保护 AI 系统免受恶意输入和不当输出的影响。

Input Guardrails

1. Unicode 规范化

清理和规范化用户输入:

typescript
import { UnicodeNormalizer } from '@mastra/core/processors';

const agent = new Agent({
  id: 'normalized-agent',
  name: 'Normalized Agent',
  inputProcessors: [
    new UnicodeNormalizer({
      stripControlChars: true,
      collapseWhitespace: true,
    }),
  ],
});

2. 提示词注入检测

检测并阻止提示词注入、越狱和系统覆盖尝试:

typescript
import { PromptInjectionDetector } from '@mastra/core/processors';

const secureAgent = new Agent({
  id: 'secure-agent',
  name: 'Secure Agent',
  inputProcessors: [
    new PromptInjectionDetector({
      model: 'openai/gpt-4o-mini',
      threshold: 0.8,
      strategy: 'rewrite', // 'block' | 'rewrite'
      detectionTypes: ['injection', 'jailbreak', 'system-override'],
    }),
  ],
});

策略选择:

策略行为
block检测到威胁时拒绝请求
rewrite使用 LLM 重写输入以移除威胁

3. 语言检测与翻译

支持多语言输入,自动翻译为目标语言:

typescript
import { LanguageDetector } from '@mastra/core/processors';

const multilingualAgent = new Agent({
  id: 'multilingual-agent',
  name: 'Multilingual Agent',
  inputProcessors: [
    new LanguageDetector({
      model: 'openai/gpt-4o-mini',
      targetLanguages: ['English', 'en'],
      strategy: 'translate',
      threshold: 0.8,
    }),
  ],
});

Output Guardrails

1. 批量流式输出

将流式输出聚合为批次:

typescript
import { BatchOutputProcessor } from '@mastra/core/processors';

const agent = new Agent({
  id: 'batched-agent',
  outputProcessors: [
    new BatchOutputProcessor({
      batchSize: 10,
      flushInterval: 100, // ms
    }),
  ],
});

2. Token 使用限制

防止输出过长:

typescript
import { TokenLimiter } from '@mastra/core/processors';

const agent = new Agent({
  id: 'limited-agent',
  outputProcessors: [
    new TokenLimiter({
      maxTokens: 500,
      strategy: 'truncate',
    }),
  ],
});

3. 系统提示词清除

防止系统提示词泄露:

typescript
import { SystemPromptScrubber } from '@mastra/core/processors';

const agent = new Agent({
  id: 'secure-agent',
  outputProcessors: [
    new SystemPromptScrubber({
      replacementText: '[REDACTED]',
    }),
  ],
});

混合 Processors

同时处理输入和输出:

1. 内容审核

typescript
import { ModerationProcessor } from '@mastra/core/processors';

const moderator = new ModerationProcessor({
  model: 'openai/gpt-4o-mini',
  categories: ['hate', 'harassment', 'violence', 'sexual'],
  threshold: 0.7,
  strategy: 'block',
});

const agent = new Agent({
  id: 'moderated-agent',
  inputProcessors: [moderator],  // 审核输入
  outputProcessors: [moderator], // 审核输出
});

2. PII 检测与删除

typescript
import { PIIDetector } from '@mastra/core/processors';

const piiDetector = new PIIDetector({
  types: ['email', 'phone', 'ssn', 'credit-card'],
  strategy: 'redact',
  replacementText: '[REDACTED]',
});

const agent = new Agent({
  id: 'pii-safe-agent',
  inputProcessors: [piiDetector],
  outputProcessors: [piiDetector],
});

组合多个 Processors

typescript
const agent = new Agent({
  id: 'fully-protected-agent',
  inputProcessors: [
    new UnicodeNormalizer(),
    new PromptInjectionDetector({ strategy: 'rewrite' }),
    new LanguageDetector({ targetLanguages: ['en'] }),
    new PIIDetector({ strategy: 'redact' }),
    new ModerationProcessor({ strategy: 'block' }),
  ],
  outputProcessors: [
    new SystemPromptScrubber(),
    new PIIDetector({ strategy: 'redact' }),
    new ModerationProcessor({ strategy: 'block' }),
    new TokenLimiter({ maxTokens: 1000 }),
  ],
});

Processor 策略

处理阻止的请求

当 Processor 阻止请求时:

typescript
const stream = await agent.stream('malicious input');

for await (const event of stream) {
  if (event.type === 'error') {
    console.error('Request blocked:', event.data.reason);
  }
}

请求重试

某些 Processors 支持自动重试:

typescript
new PromptInjectionDetector({
  strategy: 'rewrite',
  maxRetries: 3,
})

✅ Agent 审批机制

审批机制允许在工具执行前暂停 Agent,等待人工批准,实现人机协作。

Agent 级别审批

对 Agent 的所有工具调用都需要审批:

typescript
const stream = await agent.stream("What's the weather in London?", {
  requireToolApproval: true,
});

for await (const event of stream) {
  if (event.type === 'tool-call-pending') {
    const { toolCallId, toolName, input } = event.data;
    
    // 显示给用户审核
    console.log(`Tool: ${toolName}`);
    console.log(`Input: ${JSON.stringify(input)}`);
    
    // 批准
    await agent.approveToolCall(toolCallId, {
      threadId: 'thread-123',
    });
    
    // 或拒绝
    // await agent.declineToolCall(toolCallId, {
    //   reason: 'User rejected',
    // });
  }
}

工具级别审批

只对特定工具需要审批:

typescript
const dangerousTool = createTool({
  id: 'delete-file',
  description: 'Delete a file from the system',
  inputSchema: z.object({
    path: z.string(),
  }),
  requireApproval: true, // 标记此工具需要审批
  execute: async ({ path }) => {
    // 执行删除
    return { success: true };
  },
});

const agent = new Agent({
  id: 'file-agent',
  tools: {
    deleteFile: dangerousTool,
    readFile: readFileTool, // 不需要审批
  },
});

使用 suspend 方法

在工具执行函数中暂停等待审批:

typescript
const tool = createTool({
  id: 'send-email',
  description: 'Send an email',
  inputSchema: z.object({
    to: z.string(),
    subject: z.string(),
    body: z.string(),
  }),
  execute: async ({ to, subject, body }, { suspend }) => {
    // 暂停等待批准
    const approved = await suspend({
      reason: 'Email requires approval',
      metadata: { to, subject },
    });
    
    if (!approved) {
      throw new Error('Email sending was declined');
    }
    
    // 发送邮件
    await sendEmail(to, subject, body);
    return { success: true };
  },
});

自动恢复

配置存储后,可以自动恢复被暂停的工具调用:

typescript
import { Memory } from '@mastra/memory';
import { LibSQLStore } from '@mastra/libsql';

const agent = new Agent({
  id: 'approval-agent',
  memory: new Memory({
    storage: new LibSQLStore({
      id: 'approval-storage',
      url: 'file:./approvals.db',
    }),
  }),
  tools: {
    sensitiveTool,
  },
});

// 启用自动恢复
const stream = await agent.stream('Do something sensitive', {
  enableAutoResume: true,
  threadId: 'thread-456',
});

工作原理:

  1. 工具调用被挂起时,状态保存到存储
  2. 审批后,Agent 自动从挂起点继续执行
  3. 无需手动管理恢复逻辑

手动 vs 自动恢复

方式适用场景
手动需要完全控制恢复时机和逻辑
自动标准审批流程,依赖框架管理状态

🎙️ 语音交互

Mastra 支持为 Agent 添加语音能力,实现 TTS(文本转语音)和 STT(语音转文本)。

基础语音配置

typescript
import { Agent } from '@mastra/core/agent';
import { OpenAIVoice } from '@mastra/voice-openai';

// 初始化语音提供商
const voice = new OpenAIVoice({
  apiKey: process.env.OPENAI_API_KEY,
  model: 'tts-1',
  voice: 'alloy',
});

// 创建带语音能力的 Agent
export const voiceAgent = new Agent({
  id: 'voice-agent',
  name: 'Voice Agent',
  instructions: 'You are a helpful assistant with voice capabilities.',
  model: 'openai/gpt-4o',
  voice,
});

TTS: 文本转语音

typescript
// 生成语音
const audioStream = await voiceAgent.voice.speak(
  "Hello, I'm your AI assistant!",
  {
    filetype: 'm4a',
  }
);

// 播放或保存音频
import { createWriteStream } from 'fs';
audioStream.pipe(createWriteStream('./output.m4a'));

STT: 语音转文本

typescript
import { createReadStream } from 'fs';

// 转录音频
const audioStream = createReadStream('./input.m4a');
const transcription = await voiceAgent.voice.listen(audioStream);

console.log(transcription); // "What is the weather today?"

实时语音交互 (Speech-to-Speech)

对于更动态的交互体验,使用支持实时语音的提供商:

typescript
import { Agent } from '@mastra/core/agent';
import { getMicrophoneStream } from '@mastra/node-audio';
import { OpenAIRealtimeVoice } from '@mastra/voice-openai-realtime';

// 初始化实时语音提供商
const voice = new OpenAIRealtimeVoice({
  apiKey: process.env.OPENAI_API_KEY,
  model: 'gpt-4o-realtime',
  speaker: 'alloy',
});

// 创建实时语音 Agent
export const realtimeAgent = new Agent({
  id: 'realtime-agent',
  name: 'Realtime Voice Agent',
  instructions: 'You are a helpful assistant with speech-to-speech capabilities.',
  model: 'openai/gpt-4o',
  tools: {
    search: searchTool,
    calculate: calculateTool,
  },
  voice,
});

// 建立 WebSocket 连接
await realtimeAgent.voice.connect();

// 开始对话
realtimeAgent.voice.speak("Hello, I'm ready to help!");

// 从麦克风流式传输音频
const microphoneStream = getMicrophoneStream();
realtimeAgent.voice.send(microphoneStream);

// 监听事件
realtimeAgent.voice.on('speech-start', () => {
  console.log('User started speaking');
});

realtimeAgent.voice.on('speech-end', (transcription) => {
  console.log('User said:', transcription);
});

realtimeAgent.voice.on('response-start', () => {
  console.log('Agent started responding');
});

// 完成后关闭连接
realtimeAgent.voice.close();

事件系统

实时语音提供商支持丰富的事件:

事件触发时机
speech-start用户开始说话
speech-end用户停止说话
transcription语音转文本完成
response-startAgent 开始回复
response-endAgent 完成回复
tool-callAgent 调用工具
error发生错误
typescript
realtimeAgent.voice.on('tool-call', ({ toolName, input }) => {
  console.log(`Agent is calling ${toolName} with`, input);
});

realtimeAgent.voice.on('error', (error) => {
  console.error('Voice error:', error);
});

支持的语音提供商

提供商Package能力
OpenAI@mastra/voice-openaiTTS, STT
OpenAI Realtime@mastra/voice-openai-realtimeSpeech-to-Speech, 实时对话
ElevenLabs@mastra/voice-elevenlabsTTS (高质量语音)
Deepgram@mastra/voice-deepgramSTT (高精度转录)

使用多个提供商

组合不同提供商的优势:

typescript
import { OpenAIVoice } from '@mastra/voice-openai';
import { ElevenLabsVoice } from '@mastra/voice-elevenlabs';

// 使用 ElevenLabs 的高质量 TTS
const ttsVoice = new ElevenLabsVoice({
  apiKey: process.env.ELEVENLABS_API_KEY,
  voiceId: 'premium-voice-id',
});

// 使用 OpenAI 的 STT
const sttVoice = new OpenAIVoice({
  apiKey: process.env.OPENAI_API_KEY,
});

const agent = new Agent({
  id: 'hybrid-voice-agent',
  voice: {
    speak: ttsVoice,
    listen: sttVoice,
  },
});

📊 Network Approval

Network 执行中的审批机制。

Network 工具调用审批

typescript
const stream = await routingAgent.network('Research and write about AI', {
  requireToolApproval: true,
  threadId: 'network-task-001',
});

for await (const event of stream) {
  if (event.type === 'primitive-pending') {
    const { primitiveId, primitiveName, input } = event.data;
    
    console.log(`Primitive: ${primitiveName}`);
    console.log(`Input: ${JSON.stringify(input)}`);
    
    // 批准
    await routingAgent.approvePrimitive(primitiveId, {
      threadId: 'network-task-001',
    });
  }
}

自动 Primitive 恢复

与 Agent 审批类似,Network 也支持自动恢复:

typescript
const stream = await routingAgent.network('Complex task', {
  enableAutoResume: true,
  threadId: 'network-task-002',
});

🎯 最佳实践

1. Agent 设计原则

单一职责:

typescript
// ❌ 差:一个 Agent 做太多事情
const megaAgent = new Agent({
  instructions: 'You can research, write, code, design, and manage projects',
});

// ✅ 好:专业化 Agent
const researchAgent = new Agent({
  instructions: 'You specialize in gathering and analyzing information',
});

const writingAgent = new Agent({
  instructions: 'You transform research into polished written content',
});

清晰的系统指令:

typescript
// ❌ 差:模糊不清
instructions: 'You are helpful'

// ✅ 好:具体明确
instructions: `
  You are a code review specialist.
  
  Your approach:
  1. Check for security vulnerabilities first
  2. Identify performance issues
  3. Suggest readability improvements
  4. Always explain the reasoning behind your suggestions
  
  Constraints:
  - Never suggest changes without explanation
  - Focus on high-impact issues first
  - Be constructive and educational
`

2. 工具设计原则

原子性操作:

typescript
// ❌ 差:一个工具做多件事
const megaTool = createTool({
  id: 'do-everything',
  description: 'Read file, process it, and save results',
});

// ✅ 好:每个工具一个职责
const readTool = createTool({
  id: 'read-file',
  description: 'Read contents of a file',
});

const processTool = createTool({
  id: 'process-data',
  description: 'Transform data according to rules',
});

const saveTool = createTool({
  id: 'save-file',
  description: 'Save data to a file',
});

详细的描述和 Schema:

typescript
// ✅ 高质量工具定义
const searchTool = createTool({
  id: 'web-search',
  description: `
    Search the web for information using a search engine.
    Returns a list of relevant results with titles, snippets, and URLs.
    Best for: current events, factual information, recent developments.
    Limitations: May not have access to paywalled or restricted content.
  `,
  inputSchema: z.object({
    query: z.string().describe('The search query (2-100 characters)'),
    maxResults: z.number().min(1).max(10).default(5)
      .describe('Maximum number of results to return'),
  }),
  outputSchema: z.object({
    results: z.array(z.object({
      title: z.string(),
      snippet: z.string(),
      url: z.string().url(),
    })),
  }),
});

3. 记忆管理

合理使用 threadId:

typescript
// ✅ 为不同的会话使用不同的 threadId
const userSession = await agent.stream(message, {
  threadId: `user-${userId}-session-${sessionId}`,
});

// ✅ 为不同的任务使用不同的 threadId
const taskExecution = await agent.stream(task, {
  threadId: `task-${taskId}`,
});

定期清理旧数据:

typescript
// 定期清理超过 30 天的对话历史
await memory.cleanupOldThreads({
  olderThan: 30 * 24 * 60 * 60 * 1000, // 30 days
});

4. 错误处理

typescript
try {
  const stream = await agent.stream(message, {
    threadId: 'thread-123',
  });
  
  for await (const event of stream) {
    if (event.type === 'error') {
      console.error('Agent error:', event.data);
      // 处理错误
    }
  }
} catch (error) {
  if (error.code === 'RATE_LIMIT') {
    // 处理速率限制
  } else if (error.code === 'MEMORY_FULL') {
    // 清理记忆
  }
  throw error;
}

5. 性能优化

只加载需要的记忆:

typescript
const agent = new Agent({
  memory: new Memory({
    storage: store,
    maxMessages: 20, // 只加载最近 20 条消息
  }),
});

使用结构化输出避免解析:

typescript
// ❌ 差:需要解析文本
const result = await agent.generate('Extract name and age from: ...');
const parsed = parseTextOutput(result.text); // 不可靠

// ✅ 好:直接获得结构化数据
const result = await agent.generate('Extract info', {
  output: z.object({
    name: z.string(),
    age: z.number(),
  }),
});
console.log(result.object.name); // 类型安全

🔗 相关资源

官方文档

示例项目

社区


本指南基于 Mastra v1 文档编写,持续更新以跟踪最新特性。

前端面试知识库