Agent 類別
Agent 類別是於 Mastra 建立 AI Agent 的基礎。它提供產生回應和串流互動的方法,亦可處理語音功能。
使用範例使用範例 的直接連結
基本字串指示基本字串指示 的直接連結
以字串或字串陣列傳入指示,是設定 Agent 最簡單的方法。這適合只需提供提示而毋須額外配置的直接使用情境。
import { Agent } from '@mastra/core/agent'
// String instructions
export const agent = new Agent({
id: 'test-agent',
name: 'Test Agent',
instructions: 'You are a helpful assistant that provides concise answers.',
model: 'openai/gpt-5.6-sol',
})
// System message object
export const agent2 = new Agent({
id: 'test-agent-2',
name: 'Test Agent 2',
instructions: {
role: 'system',
content: 'You are an expert programmer',
},
model: 'openai/gpt-5.6-sol',
})
// Array of system messages
export const agent3 = new Agent({
id: 'test-agent-3',
name: 'Test Agent 3',
instructions: [
{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'system', content: 'You have expertise in TypeScript' },
],
model: 'openai/gpt-5.6-sol',
})
Provider 特定配置Provider 特定配置 的直接連結
每個模型 Provider 亦提供若干不同選項,包括提示快取和推理配置。你可在指示層級設定 providerOptions,為每項系統指示/提示指定不同的快取策略。
import { Agent } from '@mastra/core/agent'
export const agent = new Agent({
id: 'core-message-agent',
name: 'Core Message Agent',
instructions: {
role: 'system',
content: 'You are a helpful assistant specialized in technical documentation.',
providerOptions: {
openai: {
reasoningEffort: 'low',
},
},
},
model: 'openai/gpt-5.6-sol',
})
混合指示格式混合指示格式 的直接連結
import { Agent } from '@mastra/core/agent'
// This could be customizable based on the user
const preferredTone = {
role: 'system',
content: 'Always maintain a professional and empathetic tone.',
}
export const agent = new Agent({
id: 'multi-message-agent',
name: 'Multi Message Agent',
instructions: [
{ role: 'system', content: 'You are a customer service representative.' },
preferredTone,
{
role: 'system',
content: 'Escalate complex issues to human agents when needed.',
providerOptions: {
anthropic: { cacheControl: { type: 'ephemeral' } },
},
},
],
model: 'anthropic/claude-sonnet-4-6',
})
模型字串模型字串 的直接連結
最簡單的設定方式,是以 provider/model 格式的字串傳入 model。請以斜線分隔 Provider 與模型名稱。Mastra 會從環境讀取相應的 Provider 憑證,因此此格式毋須 Provider 套件或 import。
常用的 Provider 字串及憑證:
- OpenAI:
openai/gpt-5.6-sol使用OPENAI_API_KEY。 - Anthropic:
anthropic/claude-sonnet-4-6使用ANTHROPIC_API_KEY。 - Google:
google/gemini-2.5-pro使用GOOGLE_API_KEY或GOOGLE_GENERATIVE_AI_API_KEY。
如需了解支援的模型 ID,請參閱模型;如需完整的 Provider 清單,請參閱環境變數。
執行緒訊號執行緒訊號 的直接連結
使用 Agent 訊號將即時輸入及上下文傳送至記憶體執行緒。訊息 API 適用於使用者撰寫的輸入;sendSignal() 則是用於系統產生上下文的較低階 API。
目標執行緒運行時,sendMessage() 會把訊息傳送至使用中的 Agent 迴圈。執行緒閒置時,Mastra 預設會啟動串流,並以該訊息作為第一項輸入。
const subscription = await agent.subscribeToThread({
resourceId: 'user-123',
threadId: 'thread-abc',
})
void (async () => {
for await (const chunk of subscription.stream) {
console.log(chunk)
}
})()
agent.sendMessage('Use the latest customer note too.', {
resourceId: 'user-123',
threadId: 'thread-abc',
ifIdle: {
streamOptions: {
maxSteps: 3,
},
},
})
使用 attributes 識別共用執行緒中的不同使用者。屬性會呈現為 XML,讓模型分辨每段內容由誰發出:
agent.sendMessage(
{
contents: 'Can we simplify the API surface?',
attributes: { name: 'Devin', from: 'slack' },
},
{ resourceId: 'user-123', threadId: 'thread-abc' },
)
模型會收到以下內容:
<user name="Devin" from="slack">Can we simplify the API surface?</user>
如訊息需因應執行緒目前是否運行而附帶不同上下文,請使用 ifActive.attributes 和 ifIdle.attributes:
agent.sendMessage(
{
contents: 'Also cover the edge cases.',
attributes: { source: 'chat' },
},
{
resourceId: 'user-123',
threadId: 'thread-abc',
ifActive: { attributes: { delivery: 'while-active' } },
ifIdle: { attributes: { delivery: 'new-message' } },
},
)
執行緒使用中時,模型會看到:
<user source="chat" delivery="while-active">Also cover the edge cases.</user>
執行緒閒置時,模型會看到:
<user source="chat" delivery="new-message">Also cover the edge cases.</user>
UI 會看到訊息內容,亦可從訊號訊息讀取 attributes 和 metadata 以自訂呈現方式(例如顯示使用者名稱、頭像或平台徽章)。
sendMessage(message, options)sendmessagemessage-options 的直接連結
向使用中的執行或記憶體執行緒傳送使用者訊息。如需讓使用中的 Agent 立即收到訊息,請使用此方法。
message:
attributes,Mastra 會把訊息呈現為包含這些屬性的 <user> XML 元素。options?:
runId?:
resourceId?:
threadId 一併提供。threadId?:
resourceId 一併提供。ifActive?:
behavior?:
deliver。attributes?:
ifIdle?:
behavior?:
wake。streamOptions?:
ifIdle.behavior 為 wake 時啟動之串流的選項。Mastra 使用頂層 resourceId 和 threadId 作為記憶體上下文。attributes?:
如閒置執行緒應以自訂執行選項啟動新串流,請把 ifIdle.behavior 設為 wake,並傳入 ifIdle.streamOptions:
agent.sendMessage('Continue with the next step.', {
resourceId: 'user-123',
threadId: 'thread-abc',
ifIdle: {
behavior: 'wake',
streamOptions: {
maxSteps: 3,
},
},
})
傳回 { accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void> }。Mastra 決定如何處理訊息後,accepted 會在決策時解析:此程序運行 Agent(已啟動執行或取得啟動執行的租約)時為 { action: 'wake', runId, output };訊息轉送至現有執行時(包括此程序在跨程序喚醒競爭中落敗)為 { action: 'deliver', runId };沒有運行任何項目時則為 { action: 'persist' }/{ action: 'discard' }。runId 是處理訊息之執行的權威 ID,只會在 wake 和 deliver 中出現。對於 persist/discard,請使用 result.signal.id 關聯已儲存的訊息。accepted 會就路由解析(wake 執行的產生錯誤會透過 output.consumeStream() 顯示),只有訊息完全無法路由或啟動時才會拒絕(例如 Agent 配置錯誤)。persisted 只會在 persist 行為中出現,並於 Mastra 完成把訊息寫入記憶體時解析。對於 wake 動作,output 是供程序內取用的 Agent 串流。
queueMessage(message, options)queuemessagemessage-options 的直接連結
將使用者訊息排入執行緒下一輪的佇列。如執行緒使用中,Mastra 會等待目前執行完成,然後以已排入佇列的訊息啟動新執行。如執行緒閒置,Mastra 會立即啟動執行。
agent.queueMessage('Also check whether the tests need updates.', {
resourceId: 'user-123',
threadId: 'thread-abc',
})
queueMessage() 接受與 sendMessage() 相同結構的 message 和 options,並傳回 { accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void> };其 accepted 語意亦與 sendMessage() 相同。
sendSignal(signal, options)sendsignalsignal-options 的直接連結
向使用中的執行或記憶體執行緒傳送訊號。
signal:
type 是訊號的語意類別。tagName 控制模型看到的 XML 標籤。例如,{ type: 'notification', tagName: 'github-review' } 會呈現為 <github-review>...</github-review>。系統仍會接受舊有的 user-message 和 system-reminder 承載資料並將其標準化。未知的 type 值會被拒絕;自訂 XML 標籤請使用 tagName。options?:
runId?:
resourceId?:
threadId 一併提供。threadId?:
resourceId 一併提供。ifActive?:
behavior?:
deliver。attributes?:
ifIdle?:
behavior?:
wake。streamOptions?:
ifIdle.behavior 為 wake 時啟動之串流的選項。Mastra 使用頂層 resourceId 和 threadId 作為記憶體上下文。attributes?:
傳回 { accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void> }。Mastra 決定如何處理訊號後,accepted 會在決策時解析:此程序運行 Agent 時為 { action: 'wake', runId, output };訊號轉送至現有執行時為 { action: 'deliver', runId };沒有運行任何項目時則為 { action: 'persist' }/{ action: 'discard' }。action 會反映 ifActive/ifIdle 中勝出的 behavior。runId 是處理訊號之執行的權威 ID,只會在 wake 和 deliver 中出現。對於 persist/discard,請使用 result.signal.id 關聯已儲存的訊號。accepted 會就路由解析(wake 執行的產生錯誤會透過 output.consumeStream() 顯示);只有訊號完全無法路由或啟動時才會拒絕。persisted 只會在 persist 行為中出現,並於 Mastra 完成把訊號寫入記憶體時解析。對於 wake 動作,output 是供程序內取用的 Agent 串流。
在無伺服器處理常式中,請等待 accepted,並把 wake 輸出傳給平台上相當於 waitUntil 的方法,讓勝出的程序可在 HTTP 回應傳回後耗盡串流。
const result = agent.sendSignal(signal, { resourceId, threadId })
ctx.waitUntil(
result.accepted.then(async accepted => {
if (accepted.action === 'wake') {
await accepted.output.consumeStream()
}
}),
)
sendStateSignal(state, options)sendstatesignalstate-options 的直接連結
向使用中的執行或記憶體執行緒傳送具名稱、執行緒範圍的狀態上下文。當外部產生者擁有會隨時間變更的持久上下文(例如瀏覽器狀態、編輯器狀態或監察器輸出)時使用。
const result = await agent.sendStateSignal(
{
id: 'browser',
mode: 'snapshot',
cacheKey: 'browser:https://example.com:3-tabs',
contents: 'Browser is open. Active tab URL: https://example.com. 3 open tabs.',
value: {
activeUrl: 'https://example.com',
tabCount: 3,
open: true,
},
},
{
resourceId: 'user-123',
threadId: 'thread-abc',
},
)
state:
id:
browser 或 editor。cacheKey:
contents:
mode?:
snapshot。value?:
mode: 'snapshot' 的結構化快照值。delta?:
mode: 'delta' 的結構化變更值。attributes?:
metadata?:
tagName?:
state。options:
sendSignal() 相同的選項。Mastra 接受新狀態時,傳回 { accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void>, skipped?: false }。如同一 cacheKey 及模式已是狀態通道的目前值,則傳回 { skipped: true, reason: 'unchanged' }。Mastra 決定如何處理訊號後,accepted 會在決策時解析:此程序運行 Agent 時為 { action: 'wake', runId, output };訊號轉送至現有執行時為 { action: 'deliver', runId };沒有運行任何項目時則為 { action: 'persist' }/{ action: 'discard' }。runId 是處理訊號之執行的權威 ID,只會在 wake 和 deliver 中出現。對於 persist/discard,請使用 result.signal.id 關聯已儲存的訊號。對於 wake 動作,output 是供程序內取用的 Agent 串流。
sendNotificationSignal(notification, options)sendnotificationsignalnotification-options 的直接連結
建立或合併通知收件匣記錄,並解析通知傳送政策。決策為立即傳送時,它會傳送通知訊號。
const result = await agent.sendNotificationSignal(
{
source: 'github',
kind: 'ci-status',
priority: 'high',
summary: 'CI failed on main: 3 tests failed.',
dedupeKey: 'github:acme/app:main:ci',
},
{
resourceId: 'user-123',
threadId: 'thread-abc',
},
)
notification:
source:
github、slack 或 email。kind:
ci-status、mention 或 direct-message。summary:
priority?:
medium。payload?:
dedupeKey?:
coalesceKey?:
attributes?:
metadata?:
options:
resourceId:
threadId:
ifIdle?:
streamOptions?:
傳回 { record: NotificationRecord, decision: NotificationDeliveryDecision, runId?: string, signal?: CreatedAgentSignal, persisted?: Promise<void>, accepted?: Promise<SendAgentSignalAccepted> }。record 是已儲存的收件匣記錄;decision 是傳送政策結果。入口立即發出訊號時會提供 signal 和 runId,包括為使用中的高優先級通知立即發出的摘要。已發出的訊號在不喚醒閒置執行緒下持久保存時,會提供 persisted。發出訊號時會提供 accepted;Mastra 決定如何處理後,它會在決策時解析:此程序運行 Agent 時為 { action: 'wake', runId, output };訊號轉送至現有執行時為 { action: 'deliver', runId };沒有運行任何項目時則為 { action: 'persist' }/{ action: 'discard' }。已接受結果的 runId 只會在 wake 和 deliver 中出現。對於 wake 動作,output 是供程序內取用的 Agent 串流。
預設傳送方式會考慮優先級。urgent 通知會立即傳送。執行緒閒置時,high 通知會立即傳送;執行緒使用中時,Mastra 會立即發出摘要,並保留 deliverAt,待執行緒閒置時再完整傳送。medium 通知在閒置時立即傳送,使用中時則批次整理為摘要。low 通知在使用中及閒置執行緒均會批次整理為摘要。閒置時的低優先級摘要毋須喚醒模型迴圈,亦可送達訂閱者。完整流程請參閱訊號。
如部分通知應等待不同的派送時段或摘要彙總,請在 Agent 上配置 notifications.deliveryPolicy:
export const supportAgent = new Agent({
id: 'support-agent',
name: 'Support Agent',
instructions: 'Help the user triage updates.',
model: 'openai/gpt-5.6-sol',
notifications: {
deliveryPolicy: {
priorities: {
urgent: 'deliver',
},
decide: ({ record }) => {
if (record.priority === 'low') {
return {
action: 'summarize',
summaryAt: new Date(Date.now() + 30 * 60 * 1000),
}
}
},
},
},
})
subscribeToThread(options)subscribetothreadoptions 的直接連結
訂閱記憶體執行緒的原始串流區塊。請在呼叫 sendMessage()、queueMessage() 或 sendSignal() 前使用。它可讓你呈現串流輸出及觀察訊號回應,包括訊號中止使用中執行的情況。
options:
resourceId?:
threadId:
傳回包含以下成員的 AgentThreadSubscription 物件:
stream:
activeRunId:
null。abort:
true。unsubscribe:
建構函式參數建構函式參數 的直接連結
id:
name:
description?:
metadata?:
instructions:
model:
provider/model 格式的模型路由器字串、模型配置或 Provider 實例,或在執行階段解析模型的函式。常用 Provider 及環境變數請參閱模型字串。agents?:
tools?:
hooks?:
generate() 或 stream() 的每次執行 hook,會覆寫此處設定的相符 hook。請參閱下方的 Tool hook。beforeToolCall?:
{ toolName, input, context, metadata }。傳回 { proceed: false, output } 可略過 Tool 呼叫,並以 output 作為結果。afterToolCall?:
{ toolName, input, context, metadata, output, error }。Tool 擲回錯誤時,output 為 undefined,並改為設定 error。transform?:
createTool() 上每個 Tool 的 transform。workflows?:
defaultOptions?:
stream() 和 generate() 時使用的預設選項。defaultGenerateOptionsLegacy?:
generateLegacy() 時使用的預設選項。defaultStreamOptionsLegacy?:
streamLegacy() 時使用的預設選項。mastra?:
scorers?:
memory?:
notifications?:
deliveryPolicy?:
decide() 函式。voice?:
inputProcessors?:
createWorkflow() 建立的 Workflow。outputProcessors?:
maxProcessorRetries?:
requestContextSchema?:
editor?:
generate() 記憶體選項generate-memory-options 的直接連結
呼叫 agent.generate() 時傳入 memory,以選擇執行應讀取及寫入哪個對話執行緒。常用結構為 memory: { resource: string, thread: string },其中 resource 識別擁有者,thread 則識別對話。概念模型請參閱執行緒與資源。
const response = await agent.generate('What did we decide about retries?', {
memory: {
resource: 'user-123',
thread: 'support-thread-456',
},
})
如需在呼叫期間建立或更新執行緒中繼資料,請使用執行緒物件:
const response = await agent.generate('Continue the support conversation.', {
memory: {
resource: 'user-123',
thread: {
id: 'support-thread-456',
title: 'Billing support',
metadata: { category: 'billing' },
},
},
})
Tool hookTool hook 的直接連結
使用 hooks 在 Agent 每次呼叫 Tool 前後運行邏輯,包括已指派 Tool、記憶體 Tool、工具集、用戶端 Tool 及 Workspace Tool。
import { Agent } from '@mastra/core/agent'
export const agent = new Agent({
id: 'support-agent',
name: 'support-agent',
instructions: 'Help users with their questions.',
model: 'openai/gpt-5.6-sol',
hooks: {
beforeToolCall: ({ toolName, input }) => {
console.log(`Running ${toolName}`, input)
},
afterToolCall: ({ toolName, output, error }) => {
console.log(`Finished ${toolName}`, { output, error })
},
},
})
beforeToolCall 可傳回 { proceed: false, output },提前中止 Tool 呼叫。Agent 會略過執行,並以 output 作為 Tool 結果:
const result = await agent.generate('Clean up old records', {
hooks: {
beforeToolCall: ({ toolName }) => {
if (toolName === 'deleteRecord') {
return { proceed: false, output: { blocked: true } }
}
},
},
})
hook 上下文的 metadata 包含 agentId 和 agentName。傳給 generate() 或 stream() 的每次執行 hook 會覆寫相符的 Agent 層級 hook。當 Workspace 亦定義 tools.hooks 時,Workspace hook 會在 Agent hook 包裝器內運行。
編輯器覆寫編輯器覆寫 的直接連結
註冊 MastraEditor 時,editor 欄位控制程式碼定義的 Agent 有哪些部分可透過編輯器變更。由程式碼擁有的欄位在 Studio 中為唯讀,並會從已儲存的覆寫中移除。
editor?:
false 可鎖定 Agent。設為 instructions: true 可編輯指示。設為 tools: true 可編輯 Tool 成員及說明;設為 tools: { description: true } 則只允許編輯說明。Agent 的 id、name 和 model 一律來自程式碼,無法透過 Editor 覆寫。使用方式請參閱 Editor。