跳至主要內容

在你的 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 應用程式:

npx @nestjs/cli new mastra-nest

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

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

進入 NestJS 專案目錄:

cd mastra-nest

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

npx mastra@latest init

這會建立 src/mastra 資料夾,其中包含範例天氣 Agent 和下列檔案:

  • index.ts - Mastra 設定,包含記憶功能
  • tools/weather-tool.ts - 擷取指定位置天氣資訊的 Tool
  • agents/weather-agent.ts - 使用該 Tool 的天氣 Agent,並包含提示詞

下一步會將 src/mastra/index.ts 檔案傳遞給 NestJS adapter。

加入 server adapter
「加入 server adapter」的直接連結

安裝 NestJS server adapter 套件:

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 wrapper 和 MASTRA 注入 token。

MastraService
「MastraService」的直接連結

MastraService 是可注入的 wrapper,提供常見操作的便利方法:

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 token
「MASTRA token」的直接連結

如果需要直接使用 Mastra 執行個體(例如存取儲存空間、記憶或其他核心 API),請透過 MASTRA token 注入:

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 註冊的同一個 singleton Mastra 執行個體。

後續步驟
「後續步驟」的直接連結

現在,你已經有可在 NestJS 中執行的 Mastra Agent。若要擴充專案:

如需 NestJS 整合的詳細資訊: