跳至主要內容

使用 Assistant UI

Assistant UI 是用於 AI 聊天的 TypeScript/React 函式庫。它以 shadcn/ui 和 Tailwind CSS 建構,讓開發者能在幾分鐘內打造美觀的企業級聊天體驗。

資訊

若要採用直接在 Next.js API 路由中執行 Mastra 的全端整合方式,請參閱 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',
    }),
    ],
    },
    })

    如此會以 AI SDK 相容格式提供所有 Agent,包括位於 /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 的預設設定會將聊天 runtime 設為使用 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