Skip to main content

在你的 React + Vite 项目中集成 Mastra

🌐 Integrate Mastra in your React + Vite project

在本指南中,你将使用 Mastra 构建一个调用工具的 AI 代理,然后通过直接从 Mastra 的独立服务器调用该代理,将其连接到 React。

🌐 In this guide, you'll build a tool-calling AI agent using Mastra, then connect it to React by calling the agent directly from Mastra's standalone server.

你将使用 AI SDK UIAI Elements 来创建一个美观且互动的聊天体验。

🌐 You'll use AI SDK UI and AI Elements to create a beautiful, interactive chat experience.

在你开始之前
Direct link to 在你开始之前

🌐 Before you begin

  • 你需要从支持的模型提供商获取一个 API 密钥。如果你没有偏好,可以使用OpenAI
  • 安装 Node.js v22.13.0 或更高版本

创建一个新的 React + Vite 应用(可选)
Direct link to 创建一个新的 React + Vite 应用(可选)

🌐 Create a new React + Vite app (optional)

如果你已经有一个使用 Tailwind 的 React + Vite 应用,请跳到下一步。

🌐 If you already have a React + Vite app using Tailwind, skip to the next step.

项目脚手架
Direct link to 项目脚手架

🌐 Project scaffold

运行以下命令以创建一个新的 React + Vite 应用

🌐 Run the following command to create a new React + Vite app:

npm create vite@latest mastra-react -- --template react-ts

这会创建一个名为 mastra-react 的项目,但你可以用你想要的任何名字替代它。

🌐 This creates a project called mastra-react, but you can replace it with any name you want.

导航到你的项目目录:

🌐 Navigate to your project directory:

cd mastra-react

Tailwind
Direct link to Tailwind

接下来,安装 Tailwind:

🌐 Next, install Tailwind:

npm install tailwindcss @tailwindcss/vite

配置 Vite 插件:

🌐 Configure the Vite plugins:

vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from "path"
import tailwindcss from '@tailwindcss/vite'

export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
})

src/index.css 中的所有内容替换为以下内容:

🌐 Replace everything in src/index.css with the following:

src/index.css
@import "tailwindcss";

将这些 compilerOptions 添加到 tsconfig.json

🌐 Add these compilerOptions to tsconfig.json:

tsconfig.json
{
// ...
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}

编辑 tsconfig.app.json 以解决路径:

🌐 Edit tsconfig.app.json to resolve paths:

tsconfig.app.json
{
"compilerOptions": {
// ...
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
// ...
}
}

初始化 Mastra
Direct link to 初始化 Mastra

🌐 Initialize Mastra

运行 mastra init。出现提示时,选择一个提供商(例如 OpenAI)并输入你的密钥:

🌐 Run mastra init. When prompted, choose a provider (e.g. OpenAI) and enter your key:

npx mastra@latest init

这将创建一个包含示例天气代理和以下文件的 src/mastra 文件夹:

🌐 This creates a src/mastra folder with an example weather agent and the following files:

  • index.ts - Mastra 配置,包括内存
  • tools/weather-tool.ts - 一个用于获取给定位置天气的工具
  • agents/weather-agent.ts——一个使用该工具的天气代理和提示

在接下来的步骤中,你将从聊天界面调用 weather-agent.ts

🌐 You'll call weather-agent.ts from your chat UI in the next steps.

安装 AI SDK UI 和 AI 元素
Direct link to 安装 AI SDK UI 和 AI 元素

🌐 Install AI SDK UI & AI Elements

安装 AI SDK 界面以及 Mastra 适配器:

🌐 Install AI SDK UI along with the Mastra adapter:

npm install @mastra/ai-sdk@latest @ai-sdk/react ai

接下来,初始化 AI 元素。出现提示时,选择默认选项:

🌐 Next, initialize AI Elements. When prompted, choose the default options:

npx ai-elements@latest

这会将整个 AI Elements 用户界面组件库下载到一个 @/components/ai-elements 文件夹中。

🌐 This downloads the entire AI Elements UI component library into a @/components/ai-elements folder.

创建聊天路线
Direct link to 创建聊天路线

🌐 Create a chat route

打开 src/mastra/index.ts 并在你的配置中添加一个 ⁠chatRoute()。这将创建一个 API 路由,你的 React 前端可以调用它来获取与 AI SDK 兼容的聊天响应,接下来你将使用 ⁠useChat()。

🌐 Open ⁠src/mastra/index.ts and add a ⁠chatRoute() to your config. This creates an API route your React frontend can call for AI SDK-compatible chat responses, which you’ll use with ⁠useChat() next.

src/mastra/index.ts
import { Mastra } from '@mastra/core/mastra';
// Existing imports...
import { chatRoute } from "@mastra/ai-sdk"

export const mastra = new Mastra({
// Existing config...
server: {
apiRoutes: [
chatRoute({
path: '/chat/:agentId'
})
]
}
});

添加聊天界面
Direct link to 添加聊天界面

🌐 Add the chat UI

替换 src/App.tsx 文件以创建聊天界面:

🌐 Replace the src/App.tsx file to create a chat interface:

src/App.tsx
import * as React from 'react';
import { DefaultChatTransport, type ToolUIPart } from 'ai';
import { useChat } from '@ai-sdk/react';

import {
PromptInput,
PromptInputBody,
PromptInputTextarea,
} from '@/components/ai-elements/prompt-input';

import {
Conversation,
ConversationContent,
ConversationScrollButton,
} from '@/components/ai-elements/conversation';

import {
Message,
MessageContent,
MessageResponse
} from '@/components/ai-elements/message';

import {
Tool,
ToolHeader,
ToolContent,
ToolInput,
ToolOutput,
} from '@/components/ai-elements/tool';

export default function App() {
const [input, setInput] = React.useState<string>('');

const { messages, sendMessage, status } = useChat({
transport: new DefaultChatTransport({
api: 'http://localhost:4111/chat/weather-agent',
}),
});

const handleSubmit = async () => {
if (!input.trim()) return;

sendMessage({ text: input });
setInput('');
};

return (
<div className="max-w-4xl mx-auto p-6 relative size-full h-screen">
<div className="flex flex-col h-full">
<Conversation className="h-full">
<ConversationContent>
{messages.map((message) => (
<div key={message.id}>
{message.parts?.map((part, i) => {
if (part.type === 'text') {
return (
<Message
key={`${message.id}-${i}`}
from={message.role}>
<MessageContent>
<MessageResponse>{part.text}</MessageResponse>
</MessageContent>
</Message>
);
}

if (part.type?.startsWith('tool-')) {
return (
<Tool key={`${message.id}-${i}`}>
<ToolHeader
type={(part as ToolUIPart).type}
state={(part as ToolUIPart).state || 'output-available'}
className="cursor-pointer"
/>
<ToolContent>
<ToolInput input={(part as ToolUIPart).input || {}} />
<ToolOutput
output={(part as ToolUIPart).output}
errorText={(part as ToolUIPart).errorText}
/>
</ToolContent>
</Tool>
);
}

return null;
})}
</div>
))}
<ConversationScrollButton />
</ConversationContent>
</Conversation>
<PromptInput onSubmit={handleSubmit} className="mt-20">
<PromptInputBody>
<PromptInputTextarea
onChange={(e) => setInput(e.target.value)}
className="md:leading-10"
value={input}
placeholder="Ask about the weather..."
disabled={status !== 'ready'}
/>
</PromptInputBody>
</PromptInput>
</div>
</div>
);
}

该组件将 useChat() 连接到 chat/weather-agent 端点,将提示发送到那里,并分块流式返回响应。

🌐 This component connects useChat() to the chat/weather-agent endpoint, sending prompts there and streaming the response back in chunks.

它使用 <MessageResponse> 组件呈现响应文本,并使用 <Tool> 组件显示任何工具调用。

🌐 It renders the response text using the <MessageResponse> component, and shows any tool invocations with the <Tool> component.

测试你的代理
Direct link to 测试你的代理

🌐 Test your agent

为了使用聊天界面测试你的代理,你需要同时运行 Mastra 服务器和 Vite 开发服务器。

🌐 In order to test your agent with the chat interface, you need to run both the Mastra server and the Vite development server.

  1. 启动 Mastra 开发服务器:

    npx mastra dev
  2. 在另一个终端窗口中,启动 Vite 开发服务器:

    npm run dev
  3. http://localhost:5173 打开你的应用

  4. 试着询问天气。如果你的 API 密钥设置正确,你将会收到回复

下一步
Direct link to 下一步

🌐 Next steps

祝贺你使用 React 构建了你的 Mastra 代理!🎉

🌐 Congratulations on building your Mastra agent with React! 🎉

从这里,你可以使用你自己的工具和逻辑来扩展项目:

🌐 From here, you can extend the project with your own tools and logic:

  • 了解更多关于代理的信息
  • 给你的代理分配自己的工具
  • 给你的代理添加类似人类的内存

当你准备好时,了解更多关于 Mastra 如何与 AI SDK UI 和 React 集成,以及如何在任何地方部署你的代理的信息:

🌐 When you're ready, read more about how Mastra integrates with AI SDK UI and React, and how to deploy your agent anywhere: