在 NestJS 项目中集成 Mastra
本指南将介绍如何使用 Mastra 和 NestJS 构建一个可调用 Tool 的 AI Agent。NestJS server adapter 会将 Mastra 的 Agent 和 Workflow 路由注册为 NestJS 模块,使它们在现有 NestJS 应用中运行。
开始之前开始之前的直接链接
- 你需要受支持的模型 Provider所提供的 API 密钥。如果没有偏好,请使用 OpenAI。
- 安装 Node.js
v22.13.0或更高版本 - 使用 NestJS Express 平台(
@nestjs/platform-express)
创建新的 NestJS 应用(可选)创建新的 NestJS 应用(可选)的直接链接
如果已有 NestJS 应用,请跳到下一步。
运行以下命令创建新的 NestJS 应用:
- npm
- pnpm
- Yarn
- Bun
npx @nestjs/cli new mastra-nest
pnpm dlx @nestjs/cli new mastra-nest
yarn dlx @nestjs/cli new mastra-nest
bun x @nestjs/cli new mastra-nest
这会创建名为 mastra-nest 的项目,你也可以将其替换为任意名称。
初始化 Mastra初始化 Mastra的直接链接
进入 NestJS 项目目录:
cd mastra-nest
运行 mastra init。出现提示时,选择 Provider(例如 OpenAI)并输入密钥:
- npm
- pnpm
- Yarn
- Bun
npx mastra@latest init
pnpm dlx mastra@latest init
yarn dlx mastra@latest init
bun x mastra@latest init
这会创建一个 src/mastra 文件夹,其中包含示例天气 Agent 和以下文件:
index.ts- Mastra 配置,包括 memorytools/weather-tool.ts- 获取指定位置天气的 Toolagents/weather-agent.ts- 使用该 Tool 的天气 Agent 及其提示词
下一步会把 src/mastra/index.ts 文件传给 NestJS adapter。
添加 server adapter添加 server adapter的直接链接
安装 NestJS server adapter 软件包:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/nestjs@latest
pnpm add @mastra/nestjs@latest
yarn add @mastra/nestjs@latest
bun add @mastra/nestjs@latest
打开 src/app.module.ts 并注册 MastraModule:
import { Module } from '@nestjs/common'
import { MastraModule } from '@mastra/nestjs'
import { mastra } from './mastra'
@Module({
imports: [
MastraModule.register({
mastra,
}),
],
})
export class AppModule {}
MastraModule 会注册一个捕获所有请求的 controller(@All('*'))。如果它在应用模块之前导入,可能会拦截无关路由并返回 404。为避免冲突,请最后导入 MastraModule,或将其挂载在专用前缀下(例如 /api/v1/mastra)。
测试 Agent测试 Agent的直接链接
默认情况下,Mastra 端点添加在 /api 子路径下,并使用你的 Agent/Workflow ID。由 mastra init 创建的默认 weather-agent 可通过 /api/agents/weather-agent 访问。
启动 NestJS 服务器:
- npm
- pnpm
- Yarn
- Bun
npm run start
pnpm run start
yarn run start
bun run start
在另一个终端窗口中,使用 curl 向天气 Agent 提问:
curl -X POST http://localhost:3000/api/agents/weather-agent/generate -H "Content-Type: application/json" -d "{\"messages\":[{\"role\":\"user\",\"content\":\"What is the weather like in Seoul?\"}]}"
在自己的服务中使用 Mastra在自己的服务中使用 Mastra的直接链接
该模块导出两种从 NestJS 服务访问 Mastra 的方式:MastraService 封装器和 MASTRA 注入 token。
MastraServiceMastraService的直接链接
MastraService 是一个可注入的封装器,为常见操作提供便捷方法:
import { Injectable } from '@nestjs/common'
import { MastraService } from '@mastra/nestjs'
@Injectable()
export class AgentService {
constructor(private readonly mastraService: MastraService) {}
async chat(agentId: string, message: string) {
const agent = this.mastraService.getAgent(agentId)
return agent.generate({
messages: [{ role: 'user', content: message }],
})
}
async runWorkflow(workflowId: string, input: Record<string, unknown>) {
const workflow = this.mastraService.getWorkflow(workflowId)
return workflow.start({ inputData: input })
}
}
MastraService 提供:
getMastra():返回底层Mastra实例getAgent(id):mastra.getAgent(id)的简写getWorkflow(id):mastra.getWorkflow(id)的简写getOptions():返回模块配置isShuttingDown:开始优雅关闭后为true
MASTRA tokenMASTRA token的直接链接
如果需要直接使用 Mastra 实例(例如访问存储、memory 或其他核心 API),请使用 MASTRA token 注入:
import { Injectable, Inject } from '@nestjs/common'
import { MASTRA } from '@mastra/nestjs'
import type { Mastra } from '@mastra/core/mastra'
@Injectable()
export class MemoryService {
constructor(@Inject(MASTRA) private readonly mastra: Mastra) {}
async getThreadMessages(threadId: string) {
const memory = this.mastra.getMemory()
return memory?.getMessages({ threadId })
}
}
两种方式使用的都是由 MastraModule 注册的同一个单例 Mastra 实例。
后续步骤后续步骤的直接链接
现在,一个可用的 Mastra Agent 已经在 NestJS 中运行。要继续扩展项目,请参阅:
有关 NestJS 集成的详细信息,请参阅: