> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Mastra.getAgentById() `.getAgentById()` 方法依 `id` 取得已註冊的 Agent。它首先依 `agent.id` 搜尋已註冊的 Agent。如果沒有相符項,則改用 [`Mastra.getAgent()`](https://mastra.zisheng.pro/zh-TW/reference/core/getAgent),並將提供的值視為 Agent 註冊鍵。 使用 `mastra.getAgentById(id)` 取得程式碼中定義的 Agent。使用 `await mastra.getAgentById(id, version)` 取得版本化 Agent。 ## 使用範例 以下範例註冊一個 Agent,依 ID 取得它,然後使用傳回的 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 時,傳回解析為版本化 Agent 執行個體的 Promise。 依 ID 或註冊鍵找不到 Agent 時,會擲回 `MastraError`。 ## 相關內容 - [Mastra.getAgent()](https://mastra.zisheng.pro/zh-TW/reference/core/getAgent) - [Agent 概覽](https://mastra.zisheng.pro/zh-TW/docs/agents/overview)