> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Mastra.getAgentById() `.getAgentById()` 方法按 `id` 获取已注册的 Agent。它首先按 `agent.id` 搜索已注册的 Agent。如果没有匹配项,则回退到 [`Mastra.getAgent()`](https://mastra.zisheng.pro/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/reference/core/getAgent) - [Agent 概览](https://mastra.zisheng.pro/docs/agents/overview)