跳至主要內容

Mastra.getAgentById()

.getAgentById() 方法按 id 擷取已註冊的 Agent。它會先按 agent.id 搜尋已註冊的 Agent。如沒有相符的 Agent,則會後備使用 Mastra.getAgent(),並將提供的值視為 Agent 註冊鍵。

使用 mastra.getAgentById(id) 擷取以程式碼定義的 Agent。使用 await mastra.getAgentById(id, version) 擷取有版本的 Agent。

使用範例
使用範例 的直接連結

以下範例會註冊 Agent、按 ID 擷取該 Agent,然後使用傳回的 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?')

參數
參數 的直接連結

id:

string
要擷取的 Agent ID。Mastra 會先按 agent.id 搜尋已註冊的 Agent。如沒有相符項目,便會將此值用作 Agent 註冊鍵並調用 getAgent()

version?:

{ versionId: string } | { status?: 'draft' | 'published' }
用於擷取有版本 Agent 的可選版本選擇器。提供此參數時,方法會傳回 Promise。
VersionSelector

versionId:

string
要擷取的特定 Agent 版本 ID。

status?:

'draft' | 'published'
選擇具有此發佈狀態的最新 Agent 版本。

傳回值
傳回值 的直接連結

agent:

TAgents[TAgentName]
省略 version 時,具有指定 ID 的 Agent 實例。

agent:

Promise<TAgents[TAgentName]>
提供 version 時,一個會 resolve 為有版本 Agent 實例的 Promise。

如按 ID 或註冊鍵均找不到 Agent,便會擲回 MastraError