> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Mastra client SDK Mastra Client SDK 提供簡潔且型別安全的介面,讓你從用戶端環境與 [Mastra 伺服器](https://mastra.zisheng.pro/zh-HK/docs/server/mastra-server)互動。 ## 前置要求 開始本機開發前,請準備: - Node.js `v22.13.0` 或之後的版本 - TypeScript `v4.7` 或之後的版本(如使用 TypeScript) - 已啟動的本機 Mastra 伺服器(通常使用連接埠 `4111`) > **備註:** Mastra Client SDK 專為瀏覽器環境而設,並使用原生 `fetch` API 向 Mastra 伺服器發出 HTTP 請求。 ## 安裝 要使用 Mastra Client SDK,請安裝所需依賴套件: **npm**: ```bash npm install @mastra/client-js@latest ``` **pnpm**: ```bash pnpm add @mastra/client-js@latest ``` **Yarn**: ```bash yarn add @mastra/client-js@latest ``` **Bun**: ```bash bun add @mastra/client-js@latest ``` ### 初始化 `MastraClient` 以 `baseUrl` 初始化後,`MastraClient` 會提供型別安全的介面,用於呼叫 Agent、Tool 和 Workflow。 ```typescript import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111', }) ``` ## 核心 API Mastra Client SDK 會公開 Mastra 伺服器提供的所有資源。 - **[Agent](https://mastra.zisheng.pro/zh-HK/reference/client-js/agents)**:產生回應及串流對話。 - **[A2A](https://mastra.zisheng.pro/zh-HK/docs/agents/a2a)**:透過 Agent Card 探索 Agent,並使用以任務為本的 A2A 串流。 - **[記憶體](https://mastra.zisheng.pro/zh-HK/reference/client-js/memory)**:管理對話 Thread 及訊息記錄。 - **[Tool](https://mastra.zisheng.pro/zh-HK/reference/client-js/tools)**:執行及管理 Tool。 - **[Workflow](https://mastra.zisheng.pro/zh-HK/reference/client-js/workflows)**:觸發 Workflow 並追蹤其執行情況。 - **[向量](https://mastra.zisheng.pro/zh-HK/reference/client-js/vectors)**:使用向量嵌入進行語義搜尋。 - **[回應](https://mastra.zisheng.pro/zh-HK/reference/client-js/responses)**:透過與 OpenAI 相容、由 Agent 支援的介面,將 Mastra Agent 用作 Responses API。此 API 目前屬實驗性質。 - **[對話](https://mastra.zisheng.pro/zh-HK/reference/client-js/conversations)**:處理 Mastra Agent 作為 Responses API 時背後儲存的對話 Thread 及項目記錄。此 API 目前屬實驗性質。 - **[日誌](https://mastra.zisheng.pro/zh-HK/reference/client-js/logs)**:檢視日誌及偵錯系統行為。 - **[遙測](https://mastra.zisheng.pro/zh-HK/reference/client-js/telemetry)**:檢視應用程式效能及 Trace 活動。 ## 建立及執行動態 Workflow 使用 `upsertDynamicWorkflow()` 建立或取代持久儲存的 Workflow 定義。成功執行 upsert 後,系統會驗證完整定義、向正在執行的 Mastra 執行個體註冊,並可透過標準 Workflow 執行 API 使用該定義。 以下範例展示 Mapping Workflow 的完整生命週期,涵蓋建立、檢查、執行以至刪除: ```typescript import { MastraClient } from '@mastra/client-js' import type { UpsertDynamicWorkflowParams } from '@mastra/client-js' const client = new MastraClient({ baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111', }) const definition = { id: 'greeting-workflow', description: 'Returns a greeting for the supplied name', inputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'], }, outputSchema: { type: 'object', properties: { message: { type: 'string' } }, required: ['message'], }, graph: [ { type: 'mapping', id: 'create-greeting', mapConfig: JSON.stringify({ message: { template: 'Hello, ${initData.name}!' }, }), }, ], } satisfies UpsertDynamicWorkflowParams await client.upsertDynamicWorkflow(definition) const dynamicWorkflow = client.getDynamicWorkflow(definition.id) const dynamicDefinition = await dynamicWorkflow.details() const workflow = client.getWorkflow(dynamicDefinition.id) const run = await workflow.createRun() const result = await run.startAsync({ inputData: { name: 'Ada' } }) console.log(result) await dynamicWorkflow.delete() ``` 使用 `listDynamicWorkflows()` 列出持久儲存的定義。再次呼叫 `upsertDynamicWorkflow()` 並使用相同 `id`,會取代已儲存的定義及即時 Workflow 註冊。 > **注意:** 持久儲存需要已設定並支援 `workflowDefinitions` Domain 的 Storage Adapter。缺少該 Domain 時,Core 可以在記憶體中註冊 Workflow,但伺服器的 Dynamic Workflow API 無法在重新啟動後保留該 Workflow。 > > 已儲存的定義支援宣告式 Agent、Tool、Mapping、巢狀 Workflow、Parallel、Foreach、Sleep、Sleep-until、Conditional 及 Loop 項目,但不能包含 JavaScript Closure。Conditional 及 Loop 邏輯必須使用宣告式 Predicate 格式,而所參照的 Agent、Tool 及巢狀 Workflow 必須已經註冊。 > > 已驗證身分的伺服器要求定義操作具備 `stored-workflows:read` 或 `stored-workflows:write`,而執行 Workflow 則須具備 `workflows:execute`。 ## 產生回應 以字串 Prompt 呼叫 `.generate()`: ```typescript import { mastraClient } from 'lib/mastra-client' const testAgent = async () => { try { const agent = mastraClient.getAgent('testAgent') const response = await agent.generate('Hello') console.log(response.text) } catch (error) { return 'Error occurred while generating response' } } ``` > **資訊:** 你亦可以呼叫 `.generate()`,並傳入包含 `role` 及 `content` 的訊息物件陣列。詳情請參閱 [.generate() 參考資料](https://mastra.zisheng.pro/zh-HK/reference/client-js/agents)。 ## 串流回應 以字串 Prompt 使用 `.stream()` 取得即時回應: ```typescript import { mastraClient } from 'lib/mastra-client' const testAgent = async () => { try { const agent = mastraClient.getAgent('testAgent') const stream = await agent.stream('Hello') stream.processDataStream({ onTextPart: text => { console.log(text) }, }) } catch (error) { return 'Error occurred while generating response' } } ``` > **資訊:** 你亦可以呼叫 `.stream()`,並傳入包含 `role` 及 `content` 的訊息物件陣列。詳情請參閱 [.stream() 參考資料](https://mastra.zisheng.pro/zh-HK/reference/client-js/agents)。 ## 設定選項 `MastraClient` 接受 `retries`、`backoffMs` 和 `headers` 等選用參數,以控制請求行為。這些參數有助控制重試行為及加入診斷 Metadata。 ```typescript import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ retries: 3, backoffMs: 300, maxBackoffMs: 5000, headers: { 'X-Development': 'true', }, }) ``` 如需更多設定選項,請參閱 [MastraClient](https://mastra.zisheng.pro/zh-HK/reference/client-js/mastra-client)。 ## 憑證及 Session Cookie 當你的 UI 與 Mastra API 並非同源,例如使用不同主機、子網域或連接埠(如 Mastra Studio 使用一個連接埠,而自訂伺服器使用另一個),請**使用 Session Cookie 驗證 Mastra API 呼叫**。加入 **`credentials: 'include'`** 至 `MastraClient`,讓每個請求都帶上用戶登入後已有的 Cookie。如略過此設定,即使已在瀏覽器成功登入,你仍經常會收到 Mastra 傳回的 **`401`** 回應。 ```typescript import { MastraClient } from '@mastra/client-js' export const mastraClient = new MastraClient({ baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111', credentials: 'include', }) ``` 請**在伺服器允許帶有憑證的跨來源請求**,詳情參閱 [CORS:帶有憑證的請求](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS#requests_with_credentials)。你需要指定明確的 `Access-Control-Allow-Origin`(不可使用 `*`)及 `Access-Control-Allow-Credentials: true`,否則瀏覽器會在呼叫到達 Mastra 前將其封鎖。 **正在使用 `@mastra/react`?** 請以 `MastraReactProvider` 包裹你的應用程式,設定 `baseUrl` 及 `apiPrefix` 以配合伺服器,並沿用預設的 `credentials: 'include'`。只有當你需要更改 `credentials` 以使用 `same-origin` 或 `omit` 行為時才這樣做。 ## 加入取消請求功能 `MastraClient` 支援使用標準 Node.js `AbortSignal` API 取消請求。這適用於取消進行中的請求,例如用戶中止操作,或清理已失效的網絡呼叫。 將 `AbortSignal` 傳遞至 Client Constructor,即可為所有請求啟用取消功能。 ```typescript import { MastraClient } from '@mastra/client-js' export const controller = new AbortController() export const mastraClient = new MastraClient({ baseUrl: process.env.MASTRA_API_URL || 'http://localhost:4111', abortSignal: controller.signal, }) ``` ### 使用 `AbortController` 呼叫 `.abort()` 會取消所有與該 Signal 關聯且正在進行的請求。 ```typescript import { mastraClient, controller } from 'lib/mastra-client' const handleAbort = () => { controller.abort() } ``` ## 用戶端 Tool 使用 `createTool()` 函數直接在用戶端應用程式中定義 Tool。透過 `clientTools` 參數,在 `.generate()` 或 `.stream()` 呼叫中將其傳遞給 Agent。 這讓 Agent 可以觸發瀏覽器端功能,例如操作 DOM、存取本機儲存空間或其他 Web API,從而在用戶環境而非伺服器上執行 Tool。 ```typescript import { createTool } from '@mastra/client-js' import { z } from 'zod' const handleClientTool = async () => { try { const agent = mastraClient.getAgent('colorAgent') const colorChangeTool = createTool({ id: 'color-change-tool', description: 'Changes the HTML background color', inputSchema: z.object({ color: z.string(), }), outputSchema: z.object({ success: z.boolean(), }), execute: async inputData => { const { color } = inputData document.body.style.backgroundColor = color return { success: true } }, }) const response = await agent.generate('Change the background to blue', { clientTools: { colorChangeTool }, }) console.log(response) } catch (error) { console.error(error) } } ``` ### 用戶端 Tool Agent 這是一個標準 Mastra [Agent](https://mastra.zisheng.pro/zh-HK/docs/agents/overview),已設定為傳回十六進制色彩代碼,並配合上文定義的瀏覽器用戶端 Tool 使用。 ```typescript import { Agent } from '@mastra/core/agent' export const colorAgent = new Agent({ id: 'color-agent', name: 'Color Agent', instructions: `You are a helpful CSS assistant. You can change the background color of web pages. Respond with a hex reference for the color requested by the user`, model: 'openai/gpt-5.6-sol', }) ``` ## 在伺服器上使用 MastraClient 你亦可以在伺服器端環境中使用 `MastraClient`,例如 API Route、Serverless Function 或 Action。用法維持不變,但你可能需要為用戶端重新建立回應: ```typescript export async function action() { const agent = mastraClient.getAgent('testAgent') const stream = await agent.stream('Hello') return new Response(stream.body) } ``` ## 最佳做法 1. **錯誤處理**:在開發情境中使用[錯誤處理](https://mastra.zisheng.pro/zh-HK/reference/client-js/error-handling)。 2. **環境變數**:使用環境變數進行設定。 3. **偵錯**:需要時啟用詳細[日誌](https://mastra.zisheng.pro/zh-HK/reference/client-js/logs)。 4. **效能**:追蹤應用程式效能、[遙測](https://mastra.zisheng.pro/zh-HK/reference/client-js/telemetry)及 Trace。