> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Mastra.getAgentById() `.getAgentById()` 方法按 `id` 擷取已註冊的 Agent。它會先按 `agent.id` 搜尋已註冊的 Agent。如沒有相符的 Agent,則會後備使用 [`Mastra.getAgent()`](https://mastra.zisheng.pro/zh-HK/reference/core/getAgent),並將提供的值視為 Agent 註冊鍵。 使用 `mastra.getAgentById(id)` 擷取以程式碼定義的 Agent。使用 `await mastra.getAgentById(id, version)` 擷取有版本的 Agent。 ## 使用範例 以下範例會註冊 Agent、按 ID 擷取該 Agent,然後使用傳回的 Agent。 ```typescript import { Agent } from '@mastra/core/agent' import { Mastra } from '@mastra/core/mastra' const supportAgent = new Agent({ id: 'support-agent-id', name: 'Support Agent', instructions: 'Answer support questions clearly and concisely.', model: 'openai/gpt-5.6-sol', }) export const mastra = new Mastra({ agents: { supportAgent, }, }) const agent = mastra.getAgentById('support-agent-id') const response = await agent.generate('How can I reset my password?') ``` ## 參數 **id** (`string`): 要擷取的 Agent ID。Mastra 會先按 agent.id 搜尋已註冊的 Agent。如沒有相符項目,便會將此值用作 Agent 註冊鍵並調用 getAgent()。 **version** (`{ versionId: string } | { status?: 'draft' | 'published' }`): 用於擷取有版本 Agent 的可選版本選擇器。提供此參數時,方法會傳回 Promise。 **version.versionId** (`string`): 要擷取的特定 Agent 版本 ID。 **version.status** (`'draft' | 'published'`): 選擇具有此發佈狀態的最新 Agent 版本。 ## 傳回值 **agent** (`TAgents[TAgentName]`): 省略 version 時,具有指定 ID 的 Agent 實例。 **agent** (`Promise`): 提供 version 時,一個會 resolve 為有版本 Agent 實例的 Promise。 如按 ID 或註冊鍵均找不到 Agent,便會擲回 `MastraError`。 ## 相關內容 - [Mastra.getAgent()](https://mastra.zisheng.pro/zh-HK/reference/core/getAgent) - [Agent 概覽](https://mastra.zisheng.pro/zh-HK/docs/agents/overview)