跳到主要内容

使用 Assistant UI

Assistant UI 是一个用于 AI 聊天的 TypeScript/React 库。它基于 shadcn/ui 和 Tailwind CSS 构建,让开发者能在几分钟内打造美观的企业级聊天体验。

信息

如需让 Mastra 直接运行在 Next.js API 路由中的全栈集成方式,请参阅 Assistant UI 文档站点上的全栈集成指南

访问 Mastra 的 “UI Dojo”,查看 Assistant UI 与 Mastra 集成的实际示例。

集成指南
集成指南的直接链接

将 Mastra 作为独立 Server 运行,并把使用 Assistant UI 的 Next.js 前端连接到其 API 端点。

  1. 设置目录结构。可以采用如下目录结构:

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

    初始化 Mastra Server:

    npx create-mastra@latest

    该命令会启动交互式向导,帮助你搭建新的 Mastra 项目,包括提示输入项目名称并完成基础配置。按照提示创建 Server 项目。

    进入新创建的 Mastra Server 目录:

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

    现在,基础 Mastra Server 项目已准备就绪,其中应包含以下文件和文件夹:

    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-sdk 中的 chatRoute() 辅助函数,为 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 Server:

    npm run dev

    默认情况下,Mastra Server 在 http://localhost:4111 上运行。请保持 Server 运行,后续步骤将设置 Assistant UI 前端并连接到该 Server。

  4. 向上一级返回项目根目录。

    cd ..

    使用以下命令创建新的 assistant-ui 项目。

    npx assistant-ui@latest create
    备注

    有关添加 API Key、基础配置和手动设置步骤等详细说明,请参阅 assistant-ui 官方文档

  5. Assistant UI 的默认设置会将聊天 Runtime 配置为使用 Next.js 项目内的本地 API 路由(/api/chat)。由于 Mastra Agent 运行在独立 Server 上,需要更新前端,使其指向该 Server 的端点。

    在 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 Server。

  6. 现在可以将各部分连接起来了。请确保 Mastra Server 和 Assistant UI 前端均在运行,然后启动 Next.js 开发 Server:

    npm run dev

    现在,你应该可以在浏览器中与 Agent 聊天。

恭喜!你已使用独立 Server 方式成功集成 Mastra 与 Assistant UI。Assistant UI 前端现在可以与独立的 Mastra Agent Server 通信。

On this page