Agent 類別
Agent 類別是透過 Mastra 建立 AI Agent 的基礎。它提供生成回應與串流互動的方法,也能處理語音能力。
使用範例「使用範例」的直接連結
基本字串指示「基本字串指示」的直接連結
將指示以字串或字串陣列傳入,是設定 Agent 最簡單的方式。這適合只需要提供 prompt 而不需其他設定的單純使用情境。
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 也會提供一些不同選項,包括 prompt 快取與推理設定。您可以在指示層級設定 providerOptions,為每個 system instruction/prompt 指定不同的快取策略。
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 清單請參閱環境變數。
thread signal「thread signal」的直接連結
使用 Agent signal 將即時輸入與 context 傳入記憶體 thread。訊息 API 適用於使用者撰寫的輸入;sendSignal() 則是用於系統生成 context 的底層 API。
目標 thread 執行中時,sendMessage() 會將訊息送進作用中的 Agent 迴圈。thread 閒置時,Mastra 預設會啟動 stream,並以該訊息作為第一個輸入。
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 識別共用 thread 中的不同使用者。這些屬性會轉譯為 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>
若訊息應根據 thread 是否正在執行而帶有不同 context,請使用 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' } },
},
)
thread 作用中時,模型會看到:
<user source="chat" delivery="while-active">Also cover the edge cases.</user>
thread 閒置時,模型會看到:
<user source="chat" delivery="new-message">Also cover the edge cases.</user>
UI 會看到訊息內容,也能從 signal 訊息讀取 attributes 與 metadata 以自訂轉譯方式(例如顯示使用者名稱、大頭貼或平台徽章)。
sendMessage(message, options)「sendmessagemessage-options」的直接連結
將使用者訊息傳送至作用中的 run 或記憶體 thread。若作用中的 Agent 應立即收到訊息,請使用此方法。
message:
attributes,Mastra 會將訊息轉譯為包含這些屬性的 <user> XML 元素。options?:
runId?:
resourceId?:
threadId 一併提供。threadId?:
resourceId 一併提供。ifActive?:
behavior?:
deliver。attributes?:
ifIdle?:
behavior?:
wake。streamOptions?:
ifIdle.behavior 為 wake 時所啟動 stream 的選項。Mastra 會使用頂層 resourceId 與 threadId 作為記憶體 context。attributes?:
若閒置的 thread 應以自訂執行選項啟動新 stream,請將 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 時(它啟動了 run,或取得啟動 run 的 lease)為 { action: 'wake', runId, output };訊息轉送至現有 run 時(包括此處理程序在跨處理程序 wake 競爭中未取得 lease)為 { action: 'deliver', runId };未執行任何項目時則為 { action: 'persist' } / { action: 'discard' }。runId 是處理訊息之 run 的權威 ID,只有 wake 與 deliver 動作會提供。若為 persist/discard,請使用 result.signal.id 關聯已儲存的訊息。路由完成時 accepted 就會解析(wake run 的生成錯誤會透過 output.consumeStream() 顯示);只有訊息完全無法路由或啟動時才會拒絕,例如 Agent 設定錯誤。只有 persist 行為會提供 persisted;Mastra 完成將訊息寫入記憶體時,它會解析。若動作為 wake,output 是可在處理程序內取用的 Agent stream。
queueMessage(message, options)「queuemessagemessage-options」的直接連結
將使用者訊息排入 thread 下一輪的佇列。若 thread 作用中,Mastra 會等待作用中的 run 完成,再以佇列訊息啟動新的 run。若 thread 閒置,Mastra 會立即啟動 run。
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 傳送至作用中的 run 或記憶體 thread。
signal:
type 是 signal 的語意類別;tagName 控制模型看到的 XML tag。例如,{ type: 'notification', tagName: 'github-review' } 會轉譯為 <github-review>...</github-review>。系統仍接受舊版 user-message 與 system-reminder payload,並會加以正規化。未知的 type 值會遭到拒絕;若要使用自訂 XML tag,請設定 tagName。options?:
runId?:
resourceId?:
threadId 一併提供。threadId?:
resourceId 一併提供。ifActive?:
behavior?:
deliver。attributes?:
ifIdle?:
behavior?:
wake。streamOptions?:
ifIdle.behavior 為 wake 時所啟動 stream 的選項。Mastra 會使用頂層 resourceId 與 threadId 作為記憶體 context。attributes?:
回傳 { accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void> }。Mastra 決定如何處理 signal 時,accepted 會立即解析:此處理程序執行 Agent 時(它啟動了 run,或取得啟動 run 的 lease)為 { action: 'wake', runId, output };signal 轉送至現有 run 時(包括此處理程序在跨處理程序 wake 競爭中未取得 lease)為 { action: 'deliver', runId };未執行任何項目時則為 { action: 'persist' } / { action: 'discard' }。action 會反映 ifActive/ifIdle 中勝出的 behavior。runId 是處理 signal 之 run 的權威 ID,只有 wake 與 deliver 動作會提供。若為 persist/discard,請使用 result.signal.id 關聯已儲存的 signal。路由完成時 accepted 就會解析(wake run 的生成錯誤會透過 output.consumeStream() 顯示);只有 signal 完全無法路由或啟動時才會拒絕,例如 Agent 設定錯誤。只有 persist 行為會提供 persisted;Mastra 完成將 signal 寫入記憶體時,它會解析。若動作為 wake,output 是可在處理程序內取用的 Agent stream。
在 serverless handler 中,請 await accepted,並將 wake 輸出傳給平台中等同 waitUntil 的 API,讓取得 lease 的處理程序能在 HTTP 回應傳回後取用完整 stream。
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」的直接連結
將具名且限定於 thread 範圍的 state context 傳送至作用中的 run 或記憶體 thread。若外部 producer 擁有會隨時間變動的持久 context(例如瀏覽器狀態、編輯器狀態或 watcher 輸出),請使用此方法。
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 接受新 state 時,回傳 { accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void>, skipped?: false }。若同一 cacheKey 與 mode 已是該 state lane 的目前值,則回傳 { skipped: true, reason: 'unchanged' }。Mastra 決定如何處理 signal 時,accepted 會立即解析:此處理程序執行 Agent 時(它啟動了 run,或取得啟動 run 的 lease)為 { action: 'wake', runId, output };signal 轉送至現有 run 時(包括此處理程序在跨處理程序 wake 競爭中未取得 lease)為 { action: 'deliver', runId };未執行任何項目時則為 { action: 'persist' } / { action: 'discard' }。runId 是處理 signal 之 run 的權威 ID,只有 wake 與 deliver 動作會提供。若為 persist/discard,請使用 result.signal.id 關聯已儲存的 signal。若動作為 wake,output 是可在處理程序內取用的 Agent stream。
sendNotificationSignal(notification, options)「sendnotificationsignalnotification-options」的直接連結
建立或合併 notification inbox 記錄,並解析通知傳送原則。若決策為立即傳送,便會傳送 notification signal。
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 是儲存的 inbox 記錄;decision 是傳送原則的結果。ingress 立即發出 signal 時會提供 signal 與 runId,包括為作用中的高優先順序通知立即發出的摘要。發出的 signal 在未喚醒閒置 thread 的情況下持久化時,會提供 persisted。發出 signal 時會提供 accepted;Mastra 決定如何處理 signal 時,它會立即解析:此處理程序執行 Agent 時(它啟動了 run,或取得啟動 run 的 lease)為 { action: 'wake', runId, output };signal 轉送至現有 run 時為 { action: 'deliver', runId };未執行任何項目時則為 { action: 'persist' } / { action: 'discard' }。accepted 結果中的 runId 只有 wake 與 deliver 動作會提供。若動作為 wake,output 是可在處理程序內取用的 Agent stream。
預設傳送方式會考量優先順序。urgent 通知會立即傳送。high 通知會在 thread 閒置時立即傳送;thread 作用中時,Mastra 會立即發出摘要,並保留 deliverAt,等 thread 閒置時再完整傳送。medium 通知會在閒置時立即傳送,作用中時則批次彙整為摘要。low 通知在作用中與閒置 thread 中都會批次彙整為摘要。閒置時的低優先順序摘要不會喚醒模型迴圈,即可傳給訂閱者。完整流程請參閱 Signal。
若部分通知應等待不同的派送時段或摘要彙總,請在 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」的直接連結
訂閱記憶體 thread 的原始 stream chunk。請在呼叫 sendMessage()、queueMessage() 或 sendSignal() 前使用此方法。它可讓您轉譯 stream 輸出並觀察 signal echo,包括 signal 中止作用中 run 的情況。
options:
resourceId?:
threadId:
回傳包含下列成員的 AgentThreadSubscription 物件:
stream:
activeRunId:
null。abort:
true。unsubscribe:
constructor 參數「constructor 參數」的直接連結
id:
name:
description?:
metadata?:
instructions:
model:
provider/model 格式的模型 router 字串、模型設定、Provider 執行個體,或在 runtime 解析模型的函式。常見的 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,可選擇 run 應讀取與寫入哪個對話 thread。常見結構為 memory: { resource: string, thread: string },其中 resource 識別擁有者,thread 識別對話。概念模型請參閱 thread 與 resource。
const response = await agent.generate('What did we decide about retries?', {
memory: {
resource: 'user-123',
thread: 'support-thread-456',
},
})
若需要在呼叫期間建立或更新 thread metadata,請使用 thread 物件:
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 hook「Tool hook」的直接連結
使用 hooks 在 Agent 每次呼叫 Tool 前後執行邏輯,包括已指派的 Tool、記憶體 Tool、toolset、client 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 context 的 metadata 包含 agentId 與 agentName。傳給 generate() 或 stream() 的單次執行 hook,會覆寫相符的 Agent 層級 hook。若 Workspace 也定義 tools.hooks,Workspace hook 會在 Agent hook wrapper 內執行。
Editor 覆寫「Editor 覆寫」的直接連結
註冊 MastraEditor 後,editor 欄位會控制程式碼定義 Agent 的哪些部分可透過 Editor 變更。由程式碼擁有的欄位在 Studio 中為唯讀,且會從已儲存的覆寫值中移除。
editor?:
false 可鎖定 Agent。設為 instructions: true 可允許編輯指示。設為 tools: true 可允許編輯 Tool 成員與說明;設為 tools: { description: true } 則只允許編輯說明。Agent 的 id、name 與 model 一律來自程式碼,無法透過 Editor 覆寫。使用方式請參閱 Editor。