下面给出一份“从 0 到 1”的完整路线,演示如何用前端熟悉的 TypeScript 技术栈(Node 20 + npm + VSCode)借助 Mastra 快速落地一个可对话、可调用工具、具备记忆与知识库的 AI 代理(Agent)。全部代码均为纯 TypeScript,无需切 Python,也无需自己拼 OpenAI SDK。

1.环境准备(3 分钟)

① 安装 Node ≥ 20
② 拿到任意 LLM 密钥(下面以 OpenAI 为例)
③ 一键脚手架

npm create mastra@latest my-agent   # 按提示选 Agent + RAG + Workflow
cd my-agent
npm install

④ 把密钥写进根目录.env

OPENAI_API_KEY=sk-xxxxxxxx

2.目录速览(官方约定 > 配置)

src/
├─ mastra/
│  ├─ index.ts         // 框架入口,注册 Agent/Workflow
│  ├─ agents/
│  ├─ tools/           // 自定义工具(函数 + Zod Schema)
│  ├─ workflows/       // 图状工作流
│  └─ memory/          // 可选:向量库配置(pgvector / Pinecone …)
└─ index.ts            // 你的业务脚本 / API 路由
所有 .ts 文件在 npm run dev 时会被 tsx 实时转译,前端同学零学习成本。

3.第一步:写一只“会查天气”的 Agent

  1. src/mastra/tools/weather.ts 里声明“工具”
import { createTool } from '@mastra/core';
import { z } from 'zod';

export const weatherTool = createTool({
  id: 'get_weather',
  description: '查询城市当前气温',
  inputSchema: z.object({ city: z.string() }),
  outputSchema: z.object({ temp: z.number(), unit: z.string() }),
  execute: async ({ city }) => {
    // 这里调真实天气 API,示例直接 mock
    return { temp: 26, unit: '°C' };
  },
});
  1. src/mastra/agents/weatherAgent.ts 里组装 Agent
import { Agent } from '@mastra/core';
import { openai } from '@ai-sdk/openai';
import { weatherTool } from '../tools/weather';

export const weatherAgent = new Agent({
  name: 'weatherBot',
  model: openai('gpt-4o'),
  instructions: '你是天气小助手,可按用户要求查询实时气温。',
  tools: { weatherTool },
});
  1. 把 Agent 注册到框架
// src/mastra/index.ts
import { Mastra } from '@mastra/core';
import { weatherAgent } from './agents/weatherAgent';

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

4.第二步:本地调试 —— 官方 Playground

npm run dev     # 默认拉起 http://localhost:4111

浏览器里会出现类似 Vite 的 DevUI:

  • 左侧直接对话,右侧可看 Agent 调用栈、工具参数、耗时。
  • 修改 .ts 文件保存即热更新,体验与前端开发一致。

5.第三步:把 Agent 嵌入你的前端/全栈项目

  1. 任何脚本里调用
// src/index.ts
import { mastra } from './mastra';

(async () => {
  const agent = mastra.getAgent('weatherBot');
  const reply = await agent.generate('上海现在多少度?');
  console.log(reply.text);          // 文字答复
  console.log(reply.toolCalls);     // 实际调了 weatherTool
})();
  1. 或者作为 API 路由(以 Next.js 为例)
// app/api/chat/route.ts
import { mastra } from '@/mastra';
import { CoreMessage, streamText } from 'ai';

export async function POST(req: Request) {
  const { messages }: { messages: CoreMessage[] } = await req.json();
  const agent = mastra.getAgent('weatherBot');
  const result = await streamText({    // 支持流式返回
    model: agent.model,
    messages,
    tools: agent.tools,
  });
  return result.toDataStreamResponse();
}

前端直接用 Vercel useChat 即可零胶水接入聊天界面。

6.第四步:给 Agent 加上“长期记忆 + 企业知识库”

  1. 启动向量库(本地实验可用 SQLite + pgvector 扩展,生产换 Pinecone)
  2. src/mastra/memory/ 新建 rag.ts
import { PgVector } from '@mastra/vector-pgvector';
import { embedMany } from '@ai-sdk/openai';

export const rag = new PgVector({
  connectionString: process.env.PG_CONN!,
  embed: embedMany,
});

3.把文档灌进去(一次 ETL)

await rag.upsert('kb001', [
  { text: '公司退货政策:7 天内无理由…', metadata: { url: '/policies' } },
]);

4.在 Agent 里打开 knowledge 开关

new Agent({
  name: 'supportBot',
  model: openai('gpt-4o'),
  knowledge: { rag, topK: 5 },
  instructions: '你只能用知识库内容回答售后问题。',
});

至此,Agent 回复将完全基于企业内部文档,并可标注引用段落。

7.第五步:让多步业务“可观测、可重试”—— Workflow

当流程需要“确定性”时(审批、报告、ETL),用 Workflow 而非让 Agent 自由发挥:

import { Workflow } from '@mastra/core';

export const refundWorkflow = new Workflow({
  name: 'refund',
  inputSchema: z.object({ orderId: z.string() }),
  steps: [
    { id: 'checkOrder', run: async ({ input }) => { /* 查订单 */ } },
    { id: 'llmSummary', run: async ({ ctx }) => {
        // 任意步骤都可再次调用 LLM
        const agent = mastra.getAgent('supportBot');
        return agent.generate(`请总结订单 ${ctx.input.orderId} 的退款原因`);
    }},
    { id: 'approve', if: (ctx) => ctx.stepResults.llmSummary.score > 0.8,
      run: async () => { /* 自动同意 */ } },
  ],
});

Workflow 自带

  • 可视化追踪(OpenTelemetry)
  • 失败重试 / 人工审核(.waitForEvent
  • 子流程复用

8.构建 & 部署

npm run build        # 生成 standalone 产物
npm start            # 本地生产验证

官方助手一键部署:

npx mastra deploy vercel       # 或 cloudflare / netlify / docker

生成的端点即标准 HTTP API,前端(React/Vue/Swift/Flutter)直接 fetch。

9.常见前端集成模式

场景 推荐做法
Web 聊天框 useChat(Vercel AI SDK)+ 上面 /api/chat 路由
小程序 把 streamText 换成 generateText,一次性返回
本地 Electron 把 mastra 实例挂在主进程,渲染进程 IPC 调用
SSR 站点 在 getServerSideProps 里预执行 Workflow,生成静态报告

10.小结

  • Mastra = “TypeScript 版的 LangChain + Temporal”,但零配置、前端友好
  • 你只需:
  1. tools(普通函数 + Zod)
  2. Agent(绑定模型、指令、工具、知识库)
  3. 必要时写 Workflow(图状流程、可重试)
  4. 开发体验完全等同于写前端:热更新、类型提示、可视化 Playground、一键部署。

照着上面 5 步走,30 分钟内即可拥有一个可对话、可查询天气、具备知识库与记忆、可上线部署的 AI 代理;后续继续叠工具、叠 Workflow、换模型即可快速演进。祝编码愉快!

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐