使用 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 端点。
设置目录结构。可以采用如下目录结构:
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 设置适当的环境变量。使用
@mastra/ai-sdk中的chatRoute()辅助函数,为 Assistant UI 前端创建聊天路由。将其添加到 Mastra 项目:- npm
- pnpm
- Yarn
- Bun
npm install @mastra/ai-sdk@latestpnpm add @mastra/ai-sdk@latestyarn add @mastra/ai-sdk@latestbun add @mastra/ai-sdk@latest在
src/mastra/index.ts文件中注册聊天路由:src/mastra/index.tsimport { 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。使用以下命令运行 Mastra Server:
npm run dev默认情况下,Mastra Server 在
http://localhost:4111上运行。请保持 Server 运行,后续步骤将设置 Assistant UI 前端并连接到该 Server。向上一级返回项目根目录。
cd ..使用以下命令创建新的
assistant-ui项目。npx assistant-ui@latest create备注有关添加 API Key、基础配置和手动设置步骤等详细说明,请参阅 assistant-ui 官方文档。
Assistant UI 的默认设置会将聊天 Runtime 配置为使用 Next.js 项目内的本地 API 路由(
/api/chat)。由于 Mastra Agent 运行在独立 Server 上,需要更新前端,使其指向该 Server 的端点。在 assistant-ui 前端项目中打开包含
useChatRuntimehook 的文件(通常为app/assistant.tsx或src/app/assistant.tsx)。找到useChatRuntimehook,将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。
现在可以将各部分连接起来了。请确保 Mastra Server 和 Assistant UI 前端均在运行,然后启动 Next.js 开发 Server:
npm run dev现在,你应该可以在浏览器中与 Agent 聊天。
恭喜!你已使用独立 Server 方式成功集成 Mastra 与 Assistant UI。Assistant UI 前端现在可以与独立的 Mastra Agent Server 通信。