Chapter 02

快速上手:第一个 Agent 跑起来

5 分钟内:脚手架 → 写第一个 Agent → 在 Playground 里对话 → 看 tool-call 追踪。装好 Node 20 和 pnpm 就可以开始。

脚手架

npm create mastra@latest my-agent
# 选项向导:
#   Select a template: Basic Agent
#   Choose provider: OpenAI
#   Install example tools: Yes

cd my-agent
pnpm install

# .env 里填:
# OPENAI_API_KEY=sk-...

pnpm run dev

打开 http://localhost:4111,看到 Playground——左侧 Agent 列表,右侧聊天框 + 追踪面板。这就是 Mastra 的标志性 DX。

目录结构

my-agent/
├── src/
│   └── mastra/
│       ├── index.ts              ← Mastra 主实例
│       ├── agents/
│       │   └── chef.ts           ← 示例 Agent
│       ├── tools/
│       │   └── weather.ts        ← 示例 Tool
│       └── workflows/
│           └── meal-plan.ts      ← 示例 Workflow
├── .env
├── package.json
└── tsconfig.json

最小 Agent

// src/mastra/agents/chef.ts
import { Agent } from '@mastra/core/agent';
import { openai } from '@ai-sdk/openai';

export const chefAgent = new Agent({
  name: 'chef',
  instructions: `
    你是"古法料理大师",擅长用现有食材推荐 30 分钟内可做的家常菜。
    回答简洁,最多三道菜,配步骤要点。
  `,
  model: openai('gpt-4o-mini'),
});

注册到 Mastra

// src/mastra/index.ts
import { Mastra } from '@mastra/core';
import { chefAgent } from './agents/chef';

export const mastra = new Mastra({
  agents: { chefAgent },
});

保存后热重载,Playground 自动出现 chef——输入"冰箱里有鸡蛋、番茄、洋葱,做什么?",看到流式输出。

用代码调用 Agent

import { mastra } from './mastra';

const agent = mastra.getAgent('chefAgent');

// 1. 一次性生成
const { text } = await agent.generate('冰箱里有鸡蛋、番茄');
console.log(text);

// 2. 流式输出
const stream = await agent.stream('做盘简单的晚餐');
for await (const chunk of stream.textStream) {
  process.stdout.write(chunk);
}

添加一个 Tool

// src/mastra/tools/pantry.ts
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

export const listPantryTool = createTool({
  id: 'list-pantry',
  description: '列出冰箱里的所有食材',
  inputSchema: z.object({}),
  outputSchema: z.array(z.string()),
  execute: async () => {
    return ['鸡蛋', '番茄', '洋葱', '米', '豆腐'];
  },
});
// 在 Agent 上挂 tool
export const chefAgent = new Agent({
  name: 'chef',
  instructions: '...不确定食材时先调 list-pantry 查询...',
  model: openai('gpt-4o-mini'),
  tools: { listPantryTool },
});

Playground 里问"冰箱里有啥",你会看到:Agent 先调 list-pantry,追踪面板清晰显示 tool call 的入参、出参、耗时。

Playground 有什么好看

对话面板
和 Agent 实时聊天,支持多 session 切换。
Trace 面板
每条对话展开看 LLM 请求、tool 调用、耗时、token 用量——不用自己接 OTel。
Workflow 可视化
Workflow step 的 DAG 渲染成图,步骤状态实时更新。
Eval 面板
对 Agent 跑批量测试,得分、失败原因一目了然。

环境变量与 secrets

# .env
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=...
DATABASE_URL=postgresql://...
PINECONE_API_KEY=...
不要把 .env 提交
脚手架默认生成 .gitignore 排除 .env,但很多人仍会不小心 commit。生产环境用 Vercel/Cloudflare 的 secrets 管理或 Doppler。

常见坑

Playground 白屏
通常是 TypeScript 编译错误,看终端日志。Mastra 全 TS,一行类型错就起不来。
"Cannot find module '@mastra/core'"
脚手架要求 pnpm,npm 偶尔链接失败。删 node_modules + pnpm i 一次。
Tool 没被调用
检查 instructions 有没有说明"什么时候该调",模型本身也决定——gpt-4o-mini 会,3.5 基本不调。

本章小结