> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # 在你的 NestJS 專案中整合 Mastra 本指南將帶你使用 Mastra 和 NestJS 建立可呼叫 Tool 的 AI Agent。[NestJS server adapter](https://mastra.zisheng.pro/zh-TW/reference/server/nestjs-adapter) 會將 Mastra 的 Agent 和 Workflow 路由註冊為 NestJS 模組,使其在既有的 NestJS 應用程式中執行。 ## 開始之前 - 你需要受支援[模型 Provider](https://mastra.zisheng.pro/zh-TW/models) 的 API 金鑰。如果沒有偏好,請使用 [OpenAI](https://mastra.zisheng.pro/zh-TW/models/providers/openai)。 - 安裝 Node.js `v22.13.0` 或更新版本 - 使用 NestJS Express 平台(`@nestjs/platform-express`) ## 建立新的 NestJS 應用程式(選用) 如果你已經有 NestJS 應用程式,請跳到下一個步驟。 執行下列指令以建立新的 NestJS 應用程式: **npm**: ```bash npx @nestjs/cli new mastra-nest ``` **pnpm**: ```bash pnpm dlx @nestjs/cli new mastra-nest ``` **Yarn**: ```bash yarn dlx @nestjs/cli new mastra-nest ``` **Bun**: ```bash bun x @nestjs/cli new mastra-nest ``` 這會建立名為 `mastra-nest` 的專案,但你可以替換成任何想要的名稱。 ## 初始化 Mastra 進入 NestJS 專案目錄: ```bash cd mastra-nest ``` 執行 [`mastra init`](https://mastra.zisheng.pro/zh-TW/reference/cli/mastra)。出現提示時,選擇 Provider(例如 OpenAI)並輸入金鑰: **npm**: ```bash npx mastra@latest init ``` **pnpm**: ```bash pnpm dlx mastra@latest init ``` **Yarn**: ```bash yarn dlx mastra@latest init ``` **Bun**: ```bash bun x 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 安裝 NestJS server adapter 套件: **npm**: ```bash npm install @mastra/nestjs@latest ``` **pnpm**: ```bash pnpm add @mastra/nestjs@latest ``` **Yarn**: ```bash yarn add @mastra/nestjs@latest ``` **Bun**: ```bash bun add @mastra/nestjs@latest ``` 開啟 `src/app.module.ts` 並註冊 `MastraModule`: ```typescript 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 Mastra 端點預設會加入 `/api` 子路徑下,並使用 Agent/Workflow ID。由 `mastra init` 建立的預設 `weather-agent` 可在 `/api/agents/weather-agent` 使用。 啟動 NestJS 伺服器: **npm**: ```bash npm run start ``` **pnpm**: ```bash pnpm run start ``` **Yarn**: ```bash yarn run start ``` **Bun**: ```bash bun run start ``` 在另一個終端機視窗中,使用 `curl` 向天氣 Agent 提問: ```bash 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 此模組提供兩種從 NestJS 服務存取 Mastra 的方式:`MastraService` wrapper 和 `MASTRA` 注入 token。 ### MastraService `MastraService` 是可注入的 wrapper,提供常見操作的便利方法: ```typescript 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) { 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` 執行個體(例如存取儲存空間、記憶或其他核心 API),請透過 `MASTRA` token 注入: ```typescript 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。若要擴充專案: - [Agent 概觀](https://mastra.zisheng.pro/zh-TW/docs/agents/overview) - [使用 Tool](https://mastra.zisheng.pro/zh-TW/docs/agents/using-tools) - [Agent 記憶](https://mastra.zisheng.pro/zh-TW/docs/memory/overview) 如需 NestJS 整合的詳細資訊: - [NestJS Adapter 參考文件](https://mastra.zisheng.pro/zh-TW/reference/server/nestjs-adapter)