Skip to content

Mastra Agent 基础

Agent 配置、记忆系统、结构化输出

🏗️ 基础 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);

前端面试知识库