> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # 在 SvelteKit 项目中集成 Mastra 本指南将介绍如何使用 Mastra 构建一个可调用 Tool 的 AI Agent,然后通过路由直接导入并调用该 Agent,将其连接到 SvelteKit。 你将使用 [AI SDK UI](https://ai-sdk.dev/docs/ai-sdk-ui/overview) 创建美观的交互式聊天体验。 ## 开始之前 - 你需要受支持的[模型 Provider](https://mastra.zisheng.pro/models)所提供的 API 密钥。如果没有偏好,请使用 [OpenAI](https://mastra.zisheng.pro/models/providers/openai)。 - 安装 Node.js `v22.13.0` 或更高版本 ## 创建新的 SvelteKit 应用(可选) 如果已有使用 Tailwind 的 SvelteKit 应用,请跳到下一步。 运行以下命令以[创建新的 SvelteKit 应用](https://svelte.dev/docs/kit/creating-a-project): **npm**: ```bash npx sv create mastra-svelte --template minimal --types ts --add tailwindcss="plugins:forms" --install npm ``` **pnpm**: ```bash pnpm dlx sv create mastra-svelte --template minimal --types ts --add tailwindcss="plugins:forms" --install npm ``` **Yarn**: ```bash yarn dlx sv create mastra-svelte --template minimal --types ts --add tailwindcss="plugins:forms" --install npm ``` **Bun**: ```bash bun x sv create mastra-svelte --template minimal --types ts --add tailwindcss="plugins:forms" --install npm ``` 这会创建名为 `mastra-svelte` 的项目,你也可以将其替换为任意名称。Tailwind 会用于后续样式设置。 ## 初始化 Mastra 进入 SvelteKit 项目: ```bash cd mastra-svelte ``` 运行 [`mastra init`](https://mastra.zisheng.pro/reference/cli/mastra)。出现提示时,选择 Provider(例如 OpenAI)并输入密钥: **npm**: ```bash npx mastra@latest init ``` **pnpm**: ```bash pnpm dlx mastra@latest init ``` **Yarn**: ```bash yarn dlx mastra@latest init ``` **Bun**: ```bash bun x mastra@latest init ``` 这会创建一个 `src/mastra` 文件夹,其中包含示例天气 Agent 和以下文件: - `index.ts` - Mastra 配置,包括 memory - `tools/weather-tool.ts` - 获取指定位置天气的 Tool - `agents/weather-agent.ts`- 使用该 Tool 的天气 Agent 及其提示词 接下来,你会从 SvelteKit 路由调用 `weather-agent.ts`。 ## 安装 AI SDK UI 安装 AI SDK UI 和 Mastra adapter: **npm**: ```bash npm install @mastra/ai-sdk@latest @ai-sdk/svelte ai ``` **pnpm**: ```bash pnpm add @mastra/ai-sdk@latest @ai-sdk/svelte ai ``` **Yarn**: ```bash yarn add @mastra/ai-sdk@latest @ai-sdk/svelte ai ``` **Bun**: ```bash bun add @mastra/ai-sdk@latest @ai-sdk/svelte ai ``` ## 创建聊天路由 创建 `src/routes/api/chat/+server.ts`: ```ts import type { RequestHandler } from './$types' import { handleChatStream } from '@mastra/ai-sdk' import { toAISdkV5Messages } from '@mastra/ai-sdk/ui' import { createUIMessageStreamResponse } from 'ai' import { mastra } from '../../../mastra' const THREAD_ID = 'example-user-id' const RESOURCE_ID = 'weather-chat' export const POST: RequestHandler = async ({ request }) => { const params = await request.json() const stream = await handleChatStream({ mastra, agentId: 'weather-agent', params: { ...params, memory: { ...params.memory, thread: THREAD_ID, resource: RESOURCE_ID, }, }, }) return createUIMessageStreamResponse({ stream }) } export const GET: RequestHandler = async () => { const memory = await mastra.getAgentById('weather-agent').getMemory() let response = null try { response = await memory?.recall({ threadId: THREAD_ID, resourceId: RESOURCE_ID, }) } catch { console.log('No previous messages found.') } const uiMessages = toAISdkV5Messages(response?.messages || []) return Response.json(uiMessages) } ``` `POST` 路由接受提示词,并以 AI SDK 格式流式返回 Agent 响应;`GET` 路由则从 memory 获取消息历史,以便客户端重新加载时恢复 UI 状态。 要让 `GET` handler 被调用,需要创建 `src/routes/+page.ts` 文件。它的 `load()` 函数会与 `+page.svelte` 一起运行。 ```ts import type { UIDataTypes, UIMessage, UITools } from 'ai' import type { PageLoad } from './$types' export const load: PageLoad = async ({ fetch }) => { const response = await fetch('/api/chat') const initialMessages = (await response.json()) as UIMessage[] return { initialMessages } } ``` ## 添加聊天 UI 将 `src/routes/+page.svelte` 替换为以下内容。 ```svelte
{#each chat.messages as message, messageIndex (messageIndex)}
{#each message.parts as part, partIndex (partIndex)} {#if part.type === 'text'}
{part.text}
{:else if part.type.startsWith('tool-')}
{(part as ToolUIPart).type.split("-").slice(1).join("-")} - {STATE_TO_LABEL_MAP[(part as ToolUIPart).state ?? 'output-available']}
Parameters
{JSON.stringify((part as ToolUIPart).input, null, 2)}
{(part as ToolUIPart).errorText ? 'Error' : 'Result'}
{JSON.stringify((part as ToolUIPart).output, null, 2)}
{#if (part as ToolUIPart).errorText}
{(part as ToolUIPart).errorText}
{/if}
{/if} {/each}
{/each}
``` 此页面将 [`Chat`](https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-chat) 连接到 `api/chat` 端点,把提示词发送到该端点,并分块流式返回响应。 它使用自定义消息和 Tool 组件渲染响应文本。 ## 测试 Agent 1. 使用 `npm run dev` 运行 SvelteKit 应用 2. 打开聊天页面: 3. 尝试询问天气。如果 API 密钥配置正确,你会收到响应 ## 后续步骤 恭喜你使用 SvelteKit 构建了 Mastra Agent!🎉 接下来,你可以使用自己的 Tool 和逻辑扩展项目: - 进一步了解 [Agent](https://mastra.zisheng.pro/docs/agents/overview) - 为 Agent 添加自己的 [Tool](https://mastra.zisheng.pro/docs/agents/using-tools) - 为 Agent 添加类似人类的 [memory](https://mastra.zisheng.pro/docs/memory/overview) 准备就绪后,可进一步了解 Mastra 与 AI SDK UI 和 SvelteKit 的集成方式,以及如何将 Agent 部署到任意位置: - 将 Mastra 与 [AI SDK UI](https://mastra.zisheng.pro/guides/build-your-ui/ai-sdk-ui) 集成 - 将 Agent [部署到任意位置](https://mastra.zisheng.pro/docs/deployment/overview) - 试用[非官方 Svelte AI Elements](https://svelte-ai-elements.vercel.app/)