> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # 在 SvelteKit 項目中整合 Mastra 在本指南中,你會使用 Mastra 建立一個可呼叫 Tool 的 AI Agent,然後直接從路由匯入並呼叫該 Agent,將它連接至 SvelteKit。 你會使用 [AI SDK UI](https://ai-sdk.dev/docs/ai-sdk-ui/overview) 建立美觀且具互動性的聊天體驗。 ## 開始之前 - 你需要取得受支援 [model provider](https://mastra.zisheng.pro/zh-HK/models) 的 API 金鑰。如果沒有偏好,可使用 [OpenAI](https://mastra.zisheng.pro/zh-HK/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/zh-HK/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 設定,包括記憶功能 - `tools/weather-tool.ts` - 擷取指定地點天氣資料的 Tool - `agents/weather-agent.ts`- 天氣 Agent,包含使用該 Tool 的 prompt 在接下來的步驟中,你會從 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` 路由會接收 prompt,並以 AI SDK 格式串流傳回 Agent 的回應;`GET` 路由則從記憶功能擷取訊息記錄,讓客戶端重新載入時可為 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` endpoint,把 prompt 傳送至該處,並以串流方式逐段傳回回應。 它會使用自訂訊息及 Tool 元件顯示回應文字。 ## 測試你的 Agent 1. 使用 `npm run dev` 執行 SvelteKit 應用程式 2. 在 開啟聊天介面 3. 嘗試詢問天氣。如果 API 金鑰設定正確,你便會收到回應 ## 後續步驟 恭喜你使用 SvelteKit 建立了 Mastra Agent!🎉 接下來,你可以使用自己的 Tool 和邏輯擴充項目: - 進一步了解 [Agent](https://mastra.zisheng.pro/zh-HK/docs/agents/overview) - 為 Agent 加入專屬的 [Tool](https://mastra.zisheng.pro/zh-HK/docs/agents/using-tools) - 為 Agent 加入仿如人類的[記憶功能](https://mastra.zisheng.pro/zh-HK/docs/memory/overview) 準備好後,可進一步了解 Mastra 如何與 AI SDK UI 和 SvelteKit 整合,以及如何在任何地方部署 Agent: - 將 Mastra 與 [AI SDK UI](https://mastra.zisheng.pro/zh-HK/guides/build-your-ui/ai-sdk-ui) 整合 - 在[任何地方](https://mastra.zisheng.pro/zh-HK/docs/deployment/overview)部署 Agent - 試用[非官方 Svelte AI Elements](https://svelte-ai-elements.vercel.app/)