跳至主要內容

在 NestJS 項目中整合 Mastra

本指南將帶你使用 Mastra 和 NestJS 建立可呼叫 Tool 的 AI Agent。NestJS 伺服器配接器會將 Mastra 的 Agent 和 Workflow 路由註冊為 NestJS 模組,讓它們在你現有的 NestJS 應用程式內運行。

開始之前
開始之前 的直接連結

  • 你需要取得受支援模型 Provider的 API 金鑰。如果你沒有特別偏好,請使用 OpenAI
  • 安裝 Node.js v22.13.0 或更新版本
  • 使用 NestJS Express 平台(@nestjs/platform-express

建立新的 NestJS 應用程式(選用)
建立新的 NestJS 應用程式(選用) 的直接連結

如果你已有 NestJS 應用程式,請跳至下一步。

執行以下命令以建立新的 NestJS 應用程式:

npx @nestjs/cli new mastra-nest

這會建立名為 mastra-nest 的項目,但你可以將其替換成任何想要的名稱。

初始化 Mastra
初始化 Mastra 的直接連結

前往你的 NestJS 項目目錄:

cd mastra-nest

執行 mastra init。出現提示時,選擇 Provider(例如 OpenAI)並輸入你的金鑰:

npx mastra@latest init

這會建立包含範例天氣 Agent 的 src/mastra 資料夾,以及以下文件:

  • index.ts - Mastra 設定,包括記憶體
  • tools/weather-tool.ts - 擷取指定地點天氣的 Tool
  • agents/weather-agent.ts - 使用該 Tool、包含提示詞的天氣 Agent

你會在下一步將 src/mastra/index.ts 文件傳遞給 NestJS 配接器。

加入伺服器配接器
加入伺服器配接器 的直接連結

安裝 NestJS 伺服器配接器套件:

npm install @mastra/nestjs@latest

開啟 src/app.module.ts 並註冊 MastraModule

src/app.module.ts
import { Module } from '@nestjs/common'
import { MastraModule } from '@mastra/nestjs'
import { mastra } from './mastra'

@Module({
imports: [
MastraModule.register({
mastra,
}),
],
})
export class AppModule {}
備註

MastraModule 會註冊一個全匹配控制器(@All('*'))。如果它在你的應用程式模組之前匯入,便可能會攔截不相關的路由並回傳 404。為避免衝突,請最後才匯入 MastraModule,或將其掛載於專用前綴之下(例如 /api/v1/mastra)。

測試你的 Agent
測試你的 Agent 的直接連結

Mastra 的端點預設會加入至 /api 子路徑,並使用你的 Agent/Workflow ID。由 mastra init 建立的預設 weather-agent 可於 /api/agents/weather-agent 存取。

啟動 NestJS 伺服器:

npm 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 注入權杖。

MastraService
MastraService 的直接連結

MastraService 是可注入的包裝器,提供常用操作的便利方法:

src/agent.service.ts
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 權杖
MASTRA 權杖 的直接連結

如果你需要直接使用 Mastra 實例(例如存取儲存空間、記憶體或其他核心 API),請使用 MASTRA 權杖注入:

src/memory.service.ts
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 實例。

下一步
下一步 的直接連結

你現在已有一個可運作並在 NestJS 內運行的 Mastra Agent。如要擴充項目:

如需 NestJS 整合的詳細資料: