> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Agents API Agents API 提供與 Mastra AI Agent 互動的方法,包括產生回應、串流互動及管理 Agent Tool。 ## 取得所有 Agent 取得所有可用 Agent 的清單: ```typescript const agents = await mastraClient.listAgents() ``` 傳回以 Agent ID 對應序列化 Agent 設定的記錄。 ## 使用指定 Agent 取得指定 Agent 的實例: ```typescript export const myAgent = new Agent({ id: 'my-agent', }) ``` ```typescript const agent = mastraClient.getAgent('my-agent') ``` ## Agent 方法 ### `details()` 取得 Agent 的詳細資料: ```typescript const details = await agent.details() ``` ### `generate()` 讓 Agent 產生回應: ```typescript const response = await agent.generate( [ { role: 'user', content: 'Hello, how are you?', }, ], { memory: { thread: 'thread-abc', // Optional: Thread ID for conversation context resource: 'user-123', // Optional: Resource ID }, structuredOutput: {}, // Optional: Structured Output configuration }, ) ``` 你亦可使用簡化字串格式並傳入記憶選項: ```typescript const response = await agent.generate('Hello, how are you?', { memory: { thread: 'thread-1', resource: 'resource-1', }, }) ``` ### `stream()` 以串流方式取得 Agent 回應,進行即時互動: ```typescript const response = await agent.stream('Tell me a story') // Process data stream with the processDataStream util response.processDataStream({ onChunk: async chunk => { console.log(chunk) }, }) ``` 你亦可使用簡化字串格式並傳入記憶選項: ```typescript const response = await agent.stream('Tell me a story', { memory: { thread: 'thread-1', resource: 'resource-1', }, clientTools: { colorChangeTool }, }) response.processDataStream({ onChunk: async chunk => { if (chunk.type === 'text-delta') { console.log(chunk.payload.text) } }, }) ``` 你亦可直接讀取回應本文: ```typescript const reader = response.body.getReader() while (true) { const { done, value } = await reader.read() if (done) break console.log(new TextDecoder().decode(value)) } ``` #### AI SDK 相容格式 如要在客戶端串流處理 `agent.stream(...)` 回應中的 AI SDK 格式部分,請將 `response.processDataStream` 包裝成 `ReadableStream`,再使用 `toAISdkStream`: ```typescript import { createUIMessageStream } from 'ai' import { toAISdkStream } from '@mastra/ai-sdk' import type { ChunkType, MastraModelOutput } from '@mastra/core/stream' const response = await agent.stream('Tell me a story') const chunkStream: ReadableStream = new ReadableStream({ start(controller) { response .processDataStream({ onChunk: async chunk => controller.enqueue(chunk as ChunkType), }) .finally(() => controller.close()) }, }) const uiMessageStream = createUIMessageStream({ execute: async ({ writer }) => { for await (const part of toAISdkStream(chunkStream as unknown as MastraModelOutput, { from: 'agent', })) { writer.write(part) } }, }) for await (const part of uiMessageStream) { console.log(part) } ``` ### `sendMessage()` 向運行中的 Agent 執行或閒置的記憶執行緒傳送使用者輸入。請配合 `subscribeToThread()` 使用,讓客戶端可呈現因訊息而喚醒或接收訊息的串流。 ```typescript const agent = mastraClient.getAgent('support-agent') const result = await agent.sendMessage({ message: { contents: 'Also consider the customer note I just added.', attributes: { sentFrom: 'web' }, }, resourceId: 'user-123', threadId: 'thread-abc', }) console.log(result.runId) ``` `message` 接受字串、文字/檔案部分陣列,或包含 `contents`、`attributes`、`metadata` 及 `providerOptions` 的物件。 ### `queueMessage()` 將使用者輸入排入下一輪執行緒。若執行緒正在運行,Mastra 會在目前執行完成後啟動新執行;若執行緒閒置,則會立即啟動執行。 ```typescript await agent.queueMessage({ message: 'Also check whether the tests need updates.', resourceId: 'user-123', threadId: 'thread-abc', }) ``` ### `sendSignal()` 向運行中的 Agent 執行或記憶執行緒傳送較低層級的訊號。此方法適合系統產生且毋須儲存至收件匣的上下文,例如反應式提示或通知形式的上下文。如需持久保存通知記錄,請使用伺服器端 [`Agent.sendNotificationSignal()`](https://mastra.zisheng.pro/zh-HK/reference/agents/agent) API。使用者輸入則建議使用 `sendMessage()` 或 `queueMessage()`。 ```typescript const agent = mastraClient.getAgent('support-agent') const result = await agent.sendSignal({ signal: { type: 'reactive', tagName: 'system-reminder', contents: 'Also consider the latest customer note.', }, resourceId: 'user-123', threadId: 'thread-abc', }) console.log(result.runId) ``` 使用 `ifActive.behavior` 及 `ifIdle.behavior` 控制 Mastra 要傳遞、保存、捨棄訊號,還是由訊號喚醒: ```typescript await agent.sendSignal({ signal: { type: 'reactive', tagName: 'system-reminder', contents: 'Store this for later.' }, resourceId: 'user-123', threadId: 'thread-abc', ifIdle: { behavior: 'persist', }, }) ``` 若閒置喚醒串流需要模型設定、Tool 或執行階段上下文等選項,請傳入 `ifIdle.streamOptions`: ```typescript await agent.sendSignal({ signal: { type: 'reactive', tagName: 'system-reminder', contents: 'Start from this signal.' }, resourceId: 'user-123', threadId: 'thread-abc', ifIdle: { behavior: 'wake', streamOptions: { maxSteps: 3, }, }, }) ``` 傳回 `{ accepted: true, runId: string }`。 **signal** (`{ type: 'user' | 'reactive' | 'notification' | string; tagName?: string; contents: string | Array; attributes?: Record; metadata?: Record; providerOptions?: ProviderMetadata }`): 較低階的訊號承載資料。使用 type 表示語意訊號類別,並以 tagName 指定向模型顯示的 XML 標籤。providerOptions 會附加至產生的提示詞輪次,並持久保存於已儲存的訊號訊息。 **runId** (`string`): 要直接指定的執行 ID。 **resourceId** (`string`): 記憶執行緒的資源 ID。配合 threadId 用於指定執行緒的訊號。 **threadId** (`string`): 要指定的執行緒 ID。配合 resourceId 用於指定執行緒的訊號。 **ifActive.behavior** (`'deliver' | 'persist' | 'discard'`): 控制目標執行緒運行時的處理方式。預設為 deliver。 **ifActive.attributes** (`Record`): 目標執行緒運行期間,Mastra 接受訊號時合併至訊號的屬性。 **ifIdle.behavior** (`'wake' | 'persist' | 'discard'`): 控制目標執行緒閒置時的處理方式。預設為 wake。 **ifIdle.streamOptions** (`Omit`): ifIdle.behavior 為 wake 時啟動的串流選項。 **ifIdle.attributes** (`Record`): 目標執行緒閒置期間,Mastra 接受訊號時合併至訊號的屬性。 ### `subscribeToThread()` 訂閱記憶執行緒的原始串流資料區塊。執行緒可能由 `sendMessage()`、`queueMessage()`、`sendSignal()` 或伺服器端通知派送啟動或延續;可使用此方法呈現其輸出。 ```typescript const agent = mastraClient.getAgent('support-agent') const subscription = await agent.subscribeToThread({ resourceId: 'user-123', threadId: 'thread-abc', }) await subscription.processDataStream({ onChunk: chunk => { console.log(chunk) }, reconnect: true, }) ``` `subscribeToThread()` 會傳回底層 `Response` 及 `processDataStream()` 輔助函數。輔助函數會持續讀取訂閱串流,直至連線關閉或請求中止。傳入 `reconnect: true`,即可在傳輸關閉或重新連線失敗時再次訂閱,例如代理伺服器閒置逾時後。 **resourceId** (`string`): 記憶執行緒的資源 ID。 **threadId** (`string`): 要訂閱的執行緒 ID。 **processDataStream().reconnect** (`boolean | { maxRetries?: number; delayMs?: number }`): 訂閱串流關閉或重新連線請求失敗後重新連線。設為 true 時會無限重試,每次相隔一秒。 ### `streamUntilIdle()` 串流傳送回應,並保持串流開啟,直至執行期間派送的所有[背景任務](https://mastra.zisheng.pro/zh-HK/docs/long-running-agents/background-tasks)完成。每項任務完成後,伺服器會重新進入 Agent 迴圈,讓 LLM 可在同一次呼叫中回應結果。此方法需要在 [Mastra 實例啟用背景任務](https://mastra.zisheng.pro/zh-HK/reference/configuration),並提供記憶執行緒;否則呼叫會改用一般 `stream()`。 ```typescript const response = await agent.streamUntilIdle('Research solana for me', { memory: { thread: 'thread-1', resource: 'resource-1', }, maxIdleMs: 5 * 60_000, //optional }) response.processDataStream({ onChunk: async chunk => { if (chunk.type === 'background-task-completed') { console.log('task complete:', chunk.payload.taskId) } }, }) ``` ### `resumeStreamUntilIdle()` 使用自訂資料恢復已暫停的 Agent 串流,並保持串流開啟,直至執行期間派送的所有[背景任務](https://mastra.zisheng.pro/zh-HK/docs/long-running-agents/background-tasks)完成。可用此方法在暫停點後繼續執行,例如 Agent 內的 Workflow 暫停。此方法需要在 [Mastra 實例啟用背景任務](https://mastra.zisheng.pro/zh-HK/reference/configuration),並提供記憶執行緒;否則呼叫會改用一般 `resumeStream()`: ```typescript const response = await agent.resumeStreamUntilIdle( { approved: true, selectedOption: 'plan-b' }, { memory: { thread: 'thread-1', resource: 'resource-1', }, runId: 'run-123', toolCallId: 'tool-call-456', // optional maxIdleMs: 5 * 60_000, //optional }, ) await response.processDataStream({ onChunk: chunk => { console.log(chunk) }, }) ``` 此串流會發出與 `stream()` 相同的資料區塊類型,並額外發出代表任務生命週期事件的 `background-task-*` 資料區塊。完整伺服器端 API 請參閱 [`Agent.streamUntilIdle()`](https://mastra.zisheng.pro/zh-HK/reference/streaming/agents/streamUntilIdle),酬載結構則請參閱[背景任務資料區塊](https://mastra.zisheng.pro/zh-HK/reference/streaming/ChunkType)。 ### `getTool()` 取得指定 Agent 可用的 Tool 資料: ```typescript const tool = await agent.getTool('tool-id') ``` ### `executeTool()` 為 Agent 執行指定 Tool: ```typescript const result = await agent.executeTool('tool-id', { data: { input: 'value' }, }) ``` ### `network()` 從 Agent 網絡串流傳送回應,以進行多 Agent 互動: ```typescript const response = await agent.network('Research this topic and write a summary') response.processDataStream({ onChunk: async chunk => { console.log(chunk) }, }) ``` ### `listSuspendedRuns()` 從儲存空間列出 Agent 已暫停的執行,包括等待 Tool 呼叫批准或因 Tool 而暫停的執行。查找由儲存空間支援,因此伺服器重新啟動後及跨伺服器實例仍可使用。請將傳回的 `runId` 傳給 `approveToolCall()`、`declineToolCall()` 或 `resumeStream()`。 ```typescript const { runs, total } = await agent.listSuspendedRuns({ threadId: 'thread-456', resourceId: 'user-123', }) if (runs[0]) { console.log(runs[0].toolCalls) // [{ toolCallId, toolName, args, requiresApproval }] await agent.approveToolCall({ runId: runs[0].runId, toolCallId: runs[0].toolCalls[0].toolCallId, }) } ``` 接受可選的篩選條件(`threadId`、`resourceId`、`fromDate`、`toDate`)及分頁參數(`perPage`、`page`)。傳回 `{ runs, total }`,其中 `total` 是分頁前符合條件的執行數目。傳回的執行結構詳情請參閱 [`Agent.listSuspendedRuns()`](https://mastra.zisheng.pro/zh-HK/reference/agents/listSuspendedRuns)。 ### `approveToolCall()` 批准待處理的 Tool 呼叫並傳回延續串流。需要呈現批准回應所恢復的資料區塊時,請使用此方法。 ```typescript const response = await agent.approveToolCall({ runId: 'run-123', toolCallId: 'tool-call-456', }) response.processDataStream({ onChunk: async chunk => { console.log(chunk) }, }) ``` ### `sendToolApproval()` 批准或拒絕已訂閱執行緒中的待處理 Tool 呼叫。若希望恢復後的資料區塊透過現有執行緒訂閱傳入,而非使用獨立的延續串流,請配合 `subscribeToThread()` 使用。 ```typescript const result = await agent.sendToolApproval({ resourceId: 'user-123', threadId: 'thread-456', toolCallId: 'tool-call-456', approved: true, }) console.log(result.accepted) ``` 傳回 `{ accepted: true, runId: string, toolCallId?: string }`。 ### `declineToolCall()` 拒絕待處理的 Tool 呼叫並傳回延續串流。需要呈現拒絕回應所恢復的資料區塊時,請使用此方法。 ```typescript const response = await agent.declineToolCall({ runId: 'run-123', toolCallId: 'tool-call-456', }) response.processDataStream({ onChunk: async chunk => { console.log(chunk) }, }) ``` ### `resumeStream()` 使用自訂資料恢復已暫停的 Agent 串流。可用此方法在暫停點後繼續執行,例如 Agent 內的 Workflow 暫停: ```typescript const response = await agent.resumeStream( { approved: true, selectedOption: 'plan-b' }, { runId: 'run-123', toolCallId: 'tool-call-456', // optional }, ) await response.processDataStream({ onChunk: chunk => { console.log(chunk) }, }) ``` ### `approveToolCallGenerate()` 使用 `generate()`(非串流)時批准待處理的 Tool 呼叫。傳回完整回應: ```typescript const output = await agent.generate('Find user John', { requireToolApproval: true, }) if (output.finishReason === 'suspended') { const result = await agent.approveToolCallGenerate({ runId: output.runId, toolCallId: output.suspendPayload.toolCallId, }) console.log(result.text) } ``` ### `declineToolCallGenerate()` 使用 `generate()`(非串流)時拒絕待處理的 Tool 呼叫。傳回完整回應: ```typescript const output = await agent.generate('Find user John', { requireToolApproval: true, }) if (output.finishReason === 'suspended') { const result = await agent.declineToolCallGenerate({ runId: output.runId, toolCallId: output.suspendPayload.toolCallId, }) console.log(result.text) } ``` ## Agent 排程 使用客戶端 SDK 的排程方法,透過 `/api/schedules` 路由管理持久保存的 Agent 排程。概念及伺服器端範例請參閱[排程](https://mastra.zisheng.pro/zh-HK/docs/long-running-agents/schedules)及 [`mastra.schedules` 參考](https://mastra.zisheng.pro/zh-HK/reference/schedules/overview)。 ### `createSchedule()` 傳入 `agentId` 以建立 Agent 排程。 ```typescript const schedule = await mastraClient.createSchedule({ agentId: 'pinger', cron: '0 * * * *', prompt: 'Give me a status update.', }) ``` ### `listSchedules()` 列出 Agent 排程,並可按 `agentId`、`threadId`、`resourceId`、`name` 或 `status` 等欄位篩選。 ```typescript const schedules = await mastraClient.listSchedules({ agentId: 'pinger', status: 'active', }) ``` ### `getSchedule()` 按 ID 取得單一 Agent 排程。 ```typescript const schedule = await mastraClient.getSchedule('agent_pinger') ``` ### `updateSchedule()` 更新 Agent 排程。Agent 排程可更新 `cron`、`timezone`、`prompt`、`name`、訊號傳送選項、中繼資料及 `status` 等欄位。 ```typescript const updated = await mastraClient.updateSchedule('agent_pinger', { cron: '*/30 * * * *', prompt: 'Give me a status update every 30 minutes.', }) ``` ### `deleteSchedule()` 刪除 Agent 排程。 ```typescript await mastraClient.deleteSchedule('agent_pinger') ``` ### `runSchedule()` 立即觸發一次 Agent 排程,而不更改其 cron 週期。 ```typescript const run = await mastraClient.runSchedule('agent_pinger') ``` ### `pauseSchedule()` 暫停 Agent 排程,讓排程器停止觸發。傳回更新後的排程。 ```typescript await mastraClient.pauseSchedule('agent_pinger') ``` ### `resumeSchedule()` 恢復已暫停的 Agent 排程。下次觸發時間會由現在起重新計算,因此長時間暫停的排程不會補觸發積壓項目。傳回更新後的排程。 ```typescript await mastraClient.resumeSchedule('agent_pinger') ``` ### `listScheduleTriggers()` 列出 Agent 排程的觸發記錄,包括每次觸發所關聯的執行摘要。 ```typescript const { triggers } = await mastraClient.listScheduleTriggers('agent_pinger', { limit: 50, }) ``` ## 客戶端 Tool 客戶端 Tool 讓你在 Agent 要求時,於客戶端執行自訂函數。 ```typescript import { createTool } from '@mastra/client-js' import { z } from 'zod' const colorChangeTool = createTool({ id: 'changeColor', description: 'Changes the background color', inputSchema: z.object({ color: z.string(), }), execute: async inputData => { document.body.style.backgroundColor = inputData.color return { success: true } }, }) // Use with generate const response = await agent.generate('Change the background to blue', { clientTools: { colorChangeTool }, }) // Use with stream const response = await agent.stream('Tell me a story', { memory: { thread: 'thread-1', resource: 'resource-1', }, clientTools: { colorChangeTool }, }) response.processDataStream({ onChunk: async chunk => { if (chunk.type === 'text-delta') { console.log(chunk.payload.text) } else if (chunk.type === 'tool-call') { console.log( `calling tool ${chunk.payload.toolName} with args ${JSON.stringify( chunk.payload.args, null, 2, )}`, ) } }, }) ``` ### 調整供模型使用的客戶端 Tool 輸出 客戶端 Tool 支援以 `toModelOutput` 控制模型收到的內容,包括圖片等多模態內容。由於客戶端 Tool 在本機執行,映射亦會在 `execute` 完成後於客戶端運行。轉換後的輸出會連同原始結果傳回伺服器,讓原始結果仍可供儲存及應用程式邏輯使用。 ```typescript const screenshotTool = createTool({ id: 'takeScreenshot', description: 'Takes a screenshot of the current page', inputSchema: z.object({}), execute: async () => { const base64 = await captureScreenshot() return { ok: true, data: base64 } }, toModelOutput: output => ({ type: 'content', value: [{ type: 'media', data: output.data, mediaType: 'image/jpeg' }], }), }) ``` ### 追蹤客戶端 Tool 當伺服器已安裝並設定 `@mastra/observability` 時,客戶端 Tool 會記錄 `CLIENT_TOOL_CALL` span,作為目前 `AGENT_RUN` span 的子項。模型發出客戶端 Tool 呼叫時,伺服器會建立該 span,並將 W3C Trace 載體注入傳出的 Tool 呼叫區塊。Tool 參數可用後,該 span 便會結束。如未設定伺服器端可觀測性,客戶端 Tool 追蹤不會執行任何操作。 客戶端 SDK 亦會測量每個客戶端 Tool `execute` 函式的實際經過時間,並傳回伺服器;伺服器會將其發出為 `mastra_tool_duration_ms` 指標,並附上 `toolType: "client"`。 如要從 Tool 的 `execute` 函數取得更豐富的遙測資料,可使用執行上下文中的 `observe` 輔助函數加入子 span 及結構化日誌: ```typescript import { createTool } from '@mastra/client-js' import { z } from 'zod' const fetchUserTool = createTool({ id: 'fetchUser', description: 'Fetches the current user profile', inputSchema: z.object({ userId: z.string() }), execute: async ({ userId }, { observe }) => { observe.log('info', 'fetching user', { userId }) const user = await observe.span('http GET /users', async () => { const res = await fetch(`/api/users/${userId}`) return res.json() }) return user }, }) ``` `observe` 始終可用:沒有啟用追蹤上下文時(例如在受追蹤 Agent 以外運行),`span` 會直接執行函數,而 `log` 不會執行任何操作,毋須檢查 null。 SDK 會將收集器緩衝的所有內容序列化為 OTLP/JSON,並在下一個請求本文中傳回。伺服器的 `@mastra/observability` 套件會驗證 span 是否屬於正確的 Trace(防止跨 Trace 注入),並將每個 span/日誌轉送至伺服器端遙測所用的同一可觀測性匯流排。設定可觀測性後,現有的匯出器會自動接收這些資料。 ## 已儲存的 Agent 已儲存的 Agent 是保存在資料庫中的 Agent 設定,可於執行階段建立、更新及刪除。它們透過鍵參照基本元件(Tool、Workflow、其他 Agent 及評分器);建立 Agent 實例時,系統會從 Mastra 登錄表解析這些元件。記憶則以 `SerializedMemoryConfig` 物件內嵌設定,並可使用 `lastMessages`、`semanticRecall` 等選項。 ### `listStoredAgents()` 取得所有已儲存 Agent 的分頁清單: ```typescript const result = await mastraClient.listStoredAgents() console.log(result.agents) // Array of stored agents console.log(result.total) // Total count ``` 使用分頁及排序: ```typescript const result = await mastraClient.listStoredAgents({ page: 0, perPage: 20, orderBy: { field: 'createdAt', direction: 'DESC', }, }) ``` ### `createStoredAgent()` 建立新的已儲存 Agent: ```typescript const agent = await mastraClient.createStoredAgent({ id: 'my-agent', name: 'My Assistant', instructions: 'You are a helpful assistant.', model: { provider: 'openai', name: 'gpt-5.4', }, }) ``` 預設情況下,`createStoredAgent()` 會立即發佈初始版本。將 `autoPublish` 設為 `false` 可建立未發佈的草稿,讓你在呼叫 [`activateVersion()`](#activateversion) 前先行檢閱: ```typescript const draft = await mastraClient.createStoredAgent({ id: 'draft-agent', name: 'Draft Assistant', instructions: 'You are a helpful assistant.', model: { provider: 'openai', name: 'gpt-5', }, autoPublish: false, }) ``` 設定為 `code` 來源的 Editor 一律會發佈初始版本,因為儲存操作會將 Agent 設定寫入檔案系統。 使用所有選項: ```typescript const agent = await mastraClient.createStoredAgent({ id: 'full-agent', name: 'Full Agent', description: 'A fully configured agent', instructions: 'You are a helpful assistant.', model: { provider: 'openai', name: 'gpt-5.4', }, tools: { calculator: {}, weather: {} }, workflows: { 'data-processing': {} }, agents: { 'subagent-1': {} }, memory: { options: { lastMessages: 20, semanticRecall: false, }, }, scorers: { 'quality-scorer': { sampling: { type: 'ratio', rate: 0.1 }, }, }, defaultOptions: { maxSteps: 10, }, metadata: { version: '1.0', team: 'engineering', }, }) ``` ### `getStoredAgent()` 取得指定已儲存 Agent 的實例: ```typescript const storedAgent = mastraClient.getStoredAgent('my-agent') ``` ## 已儲存 Agent 的方法 ### `details()` 取得已儲存 Agent 的設定: ```typescript const details = await storedAgent.details() console.log(details.name) console.log(details.instructions) console.log(details.model) ``` ### `update()` 更新已儲存 Agent 的指定欄位。所有欄位均為可選: ```typescript const updated = await storedAgent.update({ name: 'Updated Agent Name', instructions: 'New instructions for the agent.', }) ``` ```typescript // Update just the tools await storedAgent.update({ tools: { 'new-tool-1': {}, 'new-tool-2': {} }, }) // Update metadata await storedAgent.update({ metadata: { version: '2.0', lastModifiedBy: 'admin', }, }) ``` ### `delete()` 刪除已儲存 Agent: ```typescript const result = await storedAgent.delete() console.log(result.success) // true ``` ## 版本管理 `Agent`(在程式碼中定義)及 `StoredAgent` 實例均提供管理設定版本的方法。有關生命週期及選擇行為,請參閱 [Editor 版本控制](https://mastra.zisheng.pro/zh-HK/docs/editor/overview)。 ### 取得指定版本的 Agent 取得 Agent 時傳入版本識別碼: ```typescript // Load the published version (default) const agent = mastraClient.getAgent('support-agent') // Load the latest draft const draftAgent = mastraClient.getAgent('support-agent', { status: 'draft' }) // Load a specific version const versionedAgent = mastraClient.getAgent('support-agent', { versionId: 'abc-123' }) ``` 對於已儲存的 Agent,將狀態選項傳入 `details()`: ```typescript const storedAgent = mastraClient.getStoredAgent('my-agent') const draft = await storedAgent.details(undefined, { status: 'draft' }) ``` ### `listVersions()` 列出 Agent 的所有版本: ```typescript const versions = await agent.listVersions() console.log(versions.items) // Array of version snapshots console.log(versions.total) ``` 使用分頁及排序: ```typescript const versions = await agent.listVersions({ page: 0, perPage: 10, orderBy: { field: 'createdAt', direction: 'DESC', }, }) ``` ### `createVersion()` 建立新的版本快照: ```typescript const version = await agent.createVersion({ changeMessage: 'Updated tone to be more friendly', }) ``` ### `getVersion()` 按 ID 取得指定版本: ```typescript const version = await agent.getVersion('version-123') console.log(version.versionNumber) console.log(version.changedFields) console.log(version.createdAt) ``` ### `activateVersion()` 將某個版本設為目前已發佈版本: ```typescript await agent.activateVersion('version-123') ``` ### `restoreVersion()` 建立採用相同設定的新版本,以還原舊版本: ```typescript await agent.restoreVersion('version-456') ``` ### `deleteVersion()` 刪除版本: ```typescript await agent.deleteVersion('version-789') ``` ### `compareVersions()` 比較兩個版本並傳回差異: ```typescript const diff = await agent.compareVersions('version-123', 'version-456') console.log(diff.changes) // Fields that changed between versions ``` ### React SDK 在 React SDK 中使用 `useChat` hook 時,透過 `requestContext` 傳入 `agentVersionId`: ```typescript import { useChat } from '@mastra/react' function Chat() { const { messages, input, handleInputChange, handleSubmit } = useChat({ agentId: 'support-agent', requestContext: { agentVersionId: 'abc-123', }, }) // ... render chat UI } ```