跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

Mastra.getAgentById()

The .getAgentById() method retrieves a registered agent by its id. It first searches registered agents by agent.id. If no agent matches, it falls back to Mastra.getAgent() and treats the provided value as the agent registry key.

Use mastra.getAgentById(id) to retrieve the code-defined agent. Use await mastra.getAgentById(id, version) to retrieve a versioned agent.

Usage example
Usage example的直接链接

The following example registers an agent and retrieves it by ID before using the returned agent.

src/mastra/index.ts
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?')

Parameters
Parameters的直接链接

id:

string
The ID of the agent to retrieve. Mastra first searches registered agents by agent.id. If none match, it uses this value as the agent registry key and calls getAgent().

version?:

{ versionId: string } | { status?: 'draft' | 'published' }
Optional version selector for retrieving a versioned agent. When provided, the method returns a promise.
VersionSelector

versionId:

string
The ID of a specific agent version to retrieve.

status?:

'draft' | 'published'
Select the latest agent version with this publication status.

Returns
Returns的直接链接

agent:

TAgents[TAgentName]
The agent instance with the specified ID when version is omitted.

agent:

Promise<TAgents[TAgentName]>
A promise that resolves to the versioned agent instance when version is provided.

Throws a MastraError when no agent is found by ID or registry key.

On this page