跳至主要內容

使用 Assistant UI

Assistant UI 是用於 AI 聊天的 TypeScript/React 函式庫。它建基於 shadcn/ui 及 Tailwind CSS,讓開發者可在數分鐘內建立美觀、企業級的聊天體驗。

資訊

如要採用全端整合方式,讓 Mastra 直接在 Next.js API 路由中運行,請參閱 Assistant UI 文件網站上的全端整合指南

瀏覽 Mastra 的 「UI Dojo」,查看 Assistant UI 與 Mastra 整合的實際範例。

整合指南
整合指南 的直接連結

將 Mastra 作為獨立伺服器運行,並把使用 Assistant UI 的 Next.js 前端連接至其 API 端點。

  1. 設定目錄結構。可採用以下目錄結構:

    project-root
    ├── mastra-server
    │ ├── src
    │ │ └── mastra
    │ └── package.json
    └── my-app
    └── package.json

    建立 Mastra 伺服器的初始結構:

    npx create-mastra@latest

    此指令會啟動互動式精靈,協助你建立新的 Mastra 項目初始結構,包括提示你輸入項目名稱及設定基本配置。按照提示建立伺服器項目。

    前往新建立的 Mastra 伺服器目錄:

    cd mastra-server # Replace with the actual directory name you provided

    現在,你已準備好一個基本的 Mastra 伺服器項目,當中應包含以下檔案及資料夾:

    src
    └── mastra
    ├── agents
    │ └── weather-agent.ts
    ├── scorers
    │ └── weather-scorer.ts
    ├── tools
    │ └── weather-tool.ts
    ├── workflows
    │ └── weather-workflow.ts
    └── index.ts
    備註

    請確保已在 .env 檔案中設定適用於你的 LLM Provider 的環境變數。

  2. 使用 @mastra/ai-sdkchatRoute() 輔助函式,為 Assistant UI 前端建立聊天路由。將它加入 Mastra 項目:

    npm install @mastra/ai-sdk@latest

    src/mastra/index.ts 檔案中註冊聊天路由:

    src/mastra/index.ts
    import { Mastra } from '@mastra/core/mastra'
    import { chatRoute } from '@mastra/ai-sdk'
    // Rest of the imports...

    export const mastra = new Mastra({
    // Rest of the configuration...
    server: {
    apiRoutes: [
    chatRoute({
    path: '/chat/:agentId',
    }),
    ],
    },
    })

    這會讓所有 Agent 均以與 AI SDK 相容的格式提供,包括端點 /chat/weatherAgent 上的 weatherAgent

  3. 使用以下指令運行 Mastra 伺服器:

    npm run dev

    Mastra 伺服器預設會在 http://localhost:4111 上運行。請讓此伺服器保持運行,以便在接下來的步驟中設定 Assistant UI 前端並連接至伺服器。

  4. 返回上一層目錄,即項目根目錄。

    cd ..

    使用以下指令建立新的 assistant-ui 項目。

    npx assistant-ui@latest create
    備註

    如需詳細設定指示,包括加入 API 金鑰、基本配置及手動設定步驟,請參閱 assistant-ui 官方文件

  5. Assistant UI 的預設設定會將聊天運行環境配置為使用 Next.js 項目內的本機 API 路由 (/api/chat)。由於我們的 Mastra Agent 在另一部伺服器上運行,因此需要更新前端,使其指向該伺服器的端點。

    在 assistant-ui 前端項目中,開啟包含 useChatRuntime hook 的檔案(通常是 app/assistant.tsxsrc/app/assistant.tsx)。找出 useChatRuntime hook,並將 api 屬性改為 Mastra Agent 串流端點的完整 URL:

    app/assistant.tsx
    'use client'

    // Rest of the imports...

    export const Assistant = () => {
    const runtime = useChatRuntime({
    transport: new AssistantChatTransport({
    api: 'http://localhost:4111/chat/weatherAgent',
    }),
    })

    // Rest of the component...
    }

    現在,Assistant UI 前端會將聊天請求直接傳送至正在運行的 Mastra 伺服器。

  6. 現在可以把各部分連接起來!請確保 Mastra 伺服器及 Assistant UI 前端均正在運行。啟動 Next.js 開發伺服器:

    npm run dev

    現在,你應可在瀏覽器中與 Agent 聊天。

恭喜!你已使用獨立伺服器方式,成功整合 Mastra 與 Assistant UI。Assistant UI 前端現在會與獨立的 Mastra Agent 伺服器通訊。

On this page