> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt
# Agent 類別
`Agent` 類別是於 Mastra 建立 AI Agent 的基礎。它提供產生回應和串流互動的方法,亦可處理語音功能。
## 使用範例
### 基本字串指示
以字串或字串陣列傳入指示,是設定 Agent 最簡單的方法。這適合只需提供提示而毋須額外配置的直接使用情境。
```typescript
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 亦提供若干不同選項,包括提示快取和推理配置。你可在指示層級設定 `providerOptions`,為每項系統指示/提示指定不同的快取策略。
```typescript
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',
})
```
### 混合指示格式
```typescript
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,請參閱[模型](https://mastra.zisheng.pro/zh-HK/models);如需完整的 Provider 清單,請參閱[環境變數](https://mastra.zisheng.pro/zh-HK/models/environment-variables)。
## 執行緒訊號
使用 Agent 訊號將即時輸入及上下文傳送至記憶體執行緒。訊息 API 適用於使用者撰寫的輸入;`sendSignal()` 則是用於系統產生上下文的較低階 API。
目標執行緒運行時,`sendMessage()` 會把訊息傳送至使用中的 Agent 迴圈。執行緒閒置時,Mastra 預設會啟動串流,並以該訊息作為第一項輸入。
```typescript
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,讓模型分辨每段內容由誰發出:
```typescript
agent.sendMessage(
{
contents: 'Can we simplify the API surface?',
attributes: { name: 'Devin', from: 'slack' },
},
{ resourceId: 'user-123', threadId: 'thread-abc' },
)
```
模型會收到以下內容:
```xml
Can we simplify the API surface?
```
如訊息需因應執行緒目前是否運行而附帶不同上下文,請使用 `ifActive.attributes` 和 `ifIdle.attributes`:
```typescript
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' } },
},
)
```
執行緒使用中時,模型會看到:
```xml
Also cover the edge cases.
```
執行緒閒置時,模型會看到:
```xml
Also cover the edge cases.
```
UI 會看到訊息內容,亦可從訊號訊息讀取 `attributes` 和 `metadata` 以自訂呈現方式(例如顯示使用者名稱、頭像或平台徽章)。
### `sendMessage(message, options)`
向使用中的執行或記憶體執行緒傳送使用者訊息。如需讓使用中的 Agent 立即收到訊息,請使用此方法。
**message** (`string | Array | { contents: string | Array; attributes?: Record; metadata?: Record; providerOptions?: ProviderMetadata }`): 使用者撰寫的輸入。純字串及沒有屬性的部分會以一般使用者輸入傳送至模型。如有 attributes,Mastra 會把訊息呈現為包含這些屬性的 \ XML 元素。
**options** (`object`): 訊息的目標及傳送行為。
**options.runId** (`string`): 要直接指定的執行 ID。當你已知使用中的執行 ID 時使用。
**options.resourceId** (`string`): 記憶體執行緒的資源 ID。向執行緒傳送訊息時,必須與 threadId 一併提供。
**options.threadId** (`string`): 要指定的執行緒 ID。向執行緒傳送訊息時,必須與 resourceId 一併提供。
**options.ifActive** (`object`): 控制目標執行緒使用中時的行為。
**options.ifActive.behavior** (`'deliver' | 'persist' | 'discard'`): 控制目標執行緒使用中時的行為。預設為 deliver。
**options.ifActive.attributes** (`Record`): 目標執行緒使用中,而 Mastra 接受訊息時合併至訊息的屬性。
**options.ifIdle** (`object`): 控制目標執行緒閒置時的行為。
**options.ifIdle.behavior** (`'wake' | 'persist' | 'discard'`): 控制目標執行緒閒置時的行為。預設為 wake。
**options.ifIdle.streamOptions** (`AgentExecutionOptions`): ifIdle.behavior 為 wake 時啟動之串流的選項。Mastra 使用頂層 resourceId 和 threadId 作為記憶體上下文。
**options.ifIdle.attributes** (`Record`): 目標執行緒閒置,而 Mastra 接受訊息時合併至訊息的屬性。
如閒置執行緒應以自訂執行選項啟動新串流,請把 `ifIdle.behavior` 設為 `wake`,並傳入 `ifIdle.streamOptions`:
```typescript
agent.sendMessage('Continue with the next step.', {
resourceId: 'user-123',
threadId: 'thread-abc',
ifIdle: {
behavior: 'wake',
streamOptions: {
maxSteps: 3,
},
},
})
```
傳回 `{ accepted: Promise, signal: CreatedAgentSignal, persisted?: Promise }`。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)`
將使用者訊息排入執行緒下一輪的佇列。如執行緒使用中,Mastra 會等待目前執行完成,然後以已排入佇列的訊息啟動新執行。如執行緒閒置,Mastra 會立即啟動執行。
```typescript
agent.queueMessage('Also check whether the tests need updates.', {
resourceId: 'user-123',
threadId: 'thread-abc',
})
```
`queueMessage()` 接受與 `sendMessage()` 相同結構的 `message` 和 `options`,並傳回 `{ accepted: Promise, signal: CreatedAgentSignal, persisted?: Promise }`;其 `accepted` 語意亦與 `sendMessage()` 相同。
### `sendSignal(signal, options)`
向使用中的執行或記憶體執行緒傳送訊號。
**signal** (`{ type: 'user' | 'state' | 'reactive' | 'notification' | 'user-message' | 'system-reminder'; tagName?: string; contents: string | Array; attributes?: Record; metadata?: Record; providerOptions?: ProviderMetadata }`): 要傳送至執行緒的訊號上下文。type 是訊號的語意類別。tagName 控制模型看到的 XML 標籤。例如,{ type: 'notification', tagName: 'github-review' } 會呈現為 \...\。系統仍會接受舊有的 user-message 和 system-reminder 承載資料並將其標準化。未知的 type 值會被拒絕;自訂 XML 標籤請使用 tagName。
**options** (`object`): 訊號的目標及傳送行為。
**options.runId** (`string`): 要直接指定的執行 ID。當你已知使用中的執行 ID 時使用。
**options.resourceId** (`string`): 記憶體執行緒的資源 ID。向執行緒傳送訊號時,必須與 threadId 一併提供。
**options.threadId** (`string`): 要指定的執行緒 ID。向執行緒傳送訊號時,必須與 resourceId 一併提供。
**options.ifActive** (`object`): 控制目標執行緒使用中時的行為。
**options.ifActive.behavior** (`'deliver' | 'persist' | 'discard'`): 控制目標執行緒使用中時的行為。預設為 deliver。
**options.ifActive.attributes** (`Record`): 目標執行緒使用中,而 Mastra 接受訊號時合併至訊號的屬性。
**options.ifIdle** (`object`): 控制目標執行緒閒置時的行為。
**options.ifIdle.behavior** (`'wake' | 'persist' | 'discard'`): 控制目標執行緒閒置時的行為。預設為 wake。
**options.ifIdle.streamOptions** (`AgentExecutionOptions`): ifIdle.behavior 為 wake 時啟動之串流的選項。Mastra 使用頂層 resourceId 和 threadId 作為記憶體上下文。
**options.ifIdle.attributes** (`Record`): 目標執行緒閒置,而 Mastra 接受訊號時合併至訊號的屬性。
傳回 `{ accepted: Promise, signal: CreatedAgentSignal, persisted?: Promise }`。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 回應傳回後耗盡串流。
```typescript
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)`
向使用中的執行或記憶體執行緒傳送具名稱、執行緒範圍的狀態上下文。當外部產生者擁有會隨時間變更的持久上下文(例如瀏覽器狀態、編輯器狀態或監察器輸出)時使用。
```typescript
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** (`object`): 要傳送至執行緒的狀態訊號。
**state.id** (`string`): 狀態通道名稱,例如 browser 或 editor。
**state.cacheKey** (`string`): 由產生者擁有的鍵,Mastra 用它略過相同通道及模式的重複狀態。
**state.contents** (`string | Array`): 向 LLM 呈現的狀態表示。
**state.mode** (`'snapshot' | 'delta'`): 狀態是權威快照還是變更事件。預設為 snapshot。
**state.value** (`unknown`): mode: 'snapshot' 的結構化快照值。
**state.delta** (`unknown`): mode: 'delta' 的結構化變更值。
**state.attributes** (`Record`): 在狀態訊號標籤上呈現的屬性。
**state.metadata** (`Record`): 與狀態訊號一併儲存的應用程式中繼資料。
**state.tagName** (`string`): 向模型顯示的 XML 標籤名稱。預設為 state。
**options** (`object`): 狀態訊號的目標及傳送行為。接受與 sendSignal() 相同的選項。
Mastra 接受新狀態時,傳回 `{ accepted: Promise, signal: CreatedAgentSignal, persisted?: Promise, 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)`
建立或合併通知收件匣記錄,並解析通知傳送政策。決策為立即傳送時,它會傳送通知訊號。
```typescript
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** (`object`): 要建立或合併的通知收件匣記錄。
**notification.source** (`string`): 產生通知的外部系統,例如 github、slack 或 email。
**notification.kind** (`string`): 來源內的通知種類,例如 ci-status、mention 或 direct-message。
**notification.summary** (`string`): 用作通知訊號內容、向 LLM 呈現的摘要。
**notification.priority** (`'low' | 'medium' | 'high' | 'urgent'`): 通知傳送政策使用的優先級。預設為 medium。
**notification.payload** (`unknown`): 儲存在收件匣記錄中、供 Tool 或應用程式碼使用的結構化承載資料。
**notification.dedupeKey** (`string`): 用於合併來自相同來源及執行緒之重複待處理通知的鍵。
**notification.coalesceKey** (`string`): 用於結合來自相同來源及執行緒之相關待處理通知的鍵。
**notification.attributes** (`Record`): 複製至已發出通知訊號的額外屬性。
**notification.metadata** (`Record`): 儲存在收件匣記錄中的應用程式中繼資料。
**options** (`object`): 通知的目標執行緒及喚醒行為。
**options.resourceId** (`string`): 通知收件匣及目標記憶體執行緒的資源 ID。
**options.threadId** (`string`): 通知收件匣及目標記憶體執行緒的執行緒 ID。
**options.ifIdle** (`object`): 控制目標執行緒閒置時的行為。
**options.ifIdle.streamOptions** (`AgentExecutionOptions`): 即時通知喚醒閒置執行緒時啟動之串流的選項。
傳回 `{ record: NotificationRecord, decision: NotificationDeliveryDecision, runId?: string, signal?: CreatedAgentSignal, persisted?: Promise, accepted?: Promise }`。`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` 通知在使用中及閒置執行緒均會批次整理為摘要。閒置時的低優先級摘要毋須喚醒模型迴圈,亦可送達訂閱者。完整流程請參閱[訊號](https://mastra.zisheng.pro/zh-HK/docs/long-running-agents/signals)。
如部分通知應等待不同的派送時段或摘要彙總,請在 Agent 上配置 `notifications.deliveryPolicy`:
```typescript
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)`
訂閱記憶體執行緒的原始串流區塊。請在呼叫 `sendMessage()`、`queueMessage()` 或 `sendSignal()` 前使用。它可讓你呈現串流輸出及觀察訊號回應,包括訊號中止使用中執行的情況。
**options** (`object`): 執行緒訂閱目標。
**options.resourceId** (`string`): 記憶體執行緒的資源 ID。
**options.threadId** (`string`): 要訂閱的執行緒 ID。
傳回包含以下成員的 `AgentThreadSubscription` 物件:
**stream** (`AsyncIterable`): 已訂閱執行緒的原始 Agent 串流區塊。
**activeRunId** (`() => string | null`): 傳回執行緒的使用中執行 ID;如沒有使用中的執行則傳回 null。
**abort** (`() => boolean`): 中止執行緒的使用中執行。成功中止執行時傳回 true。
**unsubscribe** (`() => void`): 停止訂閱,而不中止使用中的執行。
## 建構函式參數
**id** (`string`): Agent 的唯一識別碼。
**name** (`string`): Agent 的顯示名稱。
**description** (`string`): Agent 用途及功能的可選說明。
**metadata** (`Record | ({ requestContext: RequestContext }) => Record | Promise>`): 用於在用戶端分類或篩選 Agent 的可選中繼資料。可以是靜態記錄,或從請求上下文解析中繼資料的函式。
**instructions** (`SystemMessage | ({ requestContext: RequestContext }) => SystemMessage | Promise`): 引導 Agent 行為的指示。可以是字串、字串陣列、系統訊息物件、 系統訊息陣列,或動態傳回任何上述類型的函式。 SystemMessage 類型:string | string\[] | CoreSystemMessage | CoreSystemMessage\[] | SystemModelMessage | SystemModelMessage\[]
**model** (`MastraLanguageModel | ({ requestContext: RequestContext }) => MastraLanguageModel | Promise`): Agent 使用的語言模型。傳入 provider/model 格式的模型路由器字串、模型配置或 Provider 實例,或在執行階段解析模型的函式。常用 Provider 及環境變數請參閱模型字串。
**agents** (`Record | ({ requestContext: RequestContext }) => Record | Promise>`): Agent 可存取的子 Agent。可靜態提供或動態解析。
**tools** (`ToolsInput | ({ requestContext: RequestContext, mastra?: Mastra }) => ToolsInput | Promise`): Agent 可存取的 Tool。可靜態提供,或在可用時從請求上下文及相關 Mastra 實例動態解析。
**hooks** (`ToolHooks`): 在此 Agent 每次呼叫 Tool 前後運行的 hook。傳給 generate() 或 stream() 的每次執行 hook,會覆寫此處設定的相符 hook。請參閱下方的 Tool hook。
**hooks.beforeToolCall** (`(context: ToolHookContext) => void | ToolBeforeHookResult | Promise`): 在 Tool 執行前運行。接收 { toolName, input, context, metadata }。傳回 { proceed: false, output } 可略過 Tool 呼叫,並以 output 作為結果。
**hooks.afterToolCall** (`(context: ToolAfterHookContext) => void | Promise`): 在 Tool 執行後運行。接收 { toolName, input, context, metadata, output, error }。Tool 擲回錯誤時,output 為 undefined,並改為設定 error。
**transform** (`ToolPayloadTransformPolicy`): 在顯示串流或使用者可見的記錄訊息收到 Tool 承載資料前,轉換該資料的共用政策。如需個別 Tool 的規則,請使用 createTool() 上每個 Tool 的 transform。
**workflows** (`Record | ({ requestContext: RequestContext }) => Record | Promise>`): Agent 可執行的 Workflow。可靜態提供或動態解析。
**defaultOptions** (`AgentExecutionOptions | ({ requestContext: RequestContext }) => AgentExecutionOptions | Promise`): 呼叫 stream() 和 generate() 時使用的預設選項。
**defaultGenerateOptionsLegacy** (`AgentGenerateOptions | ({ requestContext: RequestContext }) => AgentGenerateOptions | Promise`): 呼叫 generateLegacy() 時使用的預設選項。
**defaultStreamOptionsLegacy** (`AgentStreamOptions | ({ requestContext: RequestContext }) => AgentStreamOptions | Promise`): 呼叫 streamLegacy() 時使用的預設選項。
**mastra** (`Mastra`): Mastra 執行階段實例的參照(自動注入)。
**scorers** (`MastraScorers | ({ requestContext: RequestContext }) => MastraScorers | Promise`): 執行階段評估及遙測的評分配置。可靜態或動態提供。
**memory** (`MastraMemory | ({ requestContext: RequestContext }) => MastraMemory | Promise`): 用於儲存及擷取具狀態上下文的記憶體模組。
**notifications** (`object`): 持久通知訊號的通知傳送配置。
**notifications.deliveryPolicy** (`NotificationDeliveryPolicyConfig`): 控制通知記錄的傳送方式。可配置預設決策、各優先級決策、各來源決策,或自訂 decide() 函式。
**voice** (`CompositeVoice`): 語音輸入及輸出的語音設定。
**inputProcessors** (`(Processor | ProcessorWorkflow)[] | ({ requestContext: RequestContext }) => (Processor | ProcessorWorkflow)[] | Promise<(Processor | ProcessorWorkflow)[]>`): 在 Agent 處理訊息前修改或驗證訊息的輸入處理器。可以是個別 Processor 物件,或使用 ProcessorStepSchema 配合 createWorkflow() 建立的 Workflow。
**outputProcessors** (`(Processor | ProcessorWorkflow)[] | ({ requestContext: RequestContext }) => (Processor | ProcessorWorkflow)[] | Promise<(Processor | ProcessorWorkflow)[]>`): 在 Agent 的訊息傳送至用戶端前修改或驗證訊息的輸出處理器。可以是個別 Processor 物件或 Workflow。
**maxProcessorRetries** (`number`): 處理器可要求重試 LLM 步驟的次數上限。
**requestContextSchema** (`StandardJSONSchemaV1`): 用於驗證請求上下文值的標準 JSON Schema。提供後,會在 generate() 或 stream() 開始時驗證上下文;驗證失敗會擲回 MastraError。
**editor** (`false | { instructions?: boolean; tools?: boolean | { description?: boolean } }`): 控制編輯器可覆寫此程式碼定義 Agent 的哪些欄位。省略時允許編輯指示及 Tool。請參閱下方的編輯器覆寫。
## `generate()` 記憶體選項
呼叫 `agent.generate()` 時傳入 `memory`,以選擇執行應讀取及寫入哪個對話執行緒。常用結構為 `memory: { resource: string, thread: string }`,其中 `resource` 識別擁有者,`thread` 則識別對話。概念模型請參閱[執行緒與資源](https://mastra.zisheng.pro/zh-HK/docs/memory/message-history)。
```typescript
const response = await agent.generate('What did we decide about retries?', {
memory: {
resource: 'user-123',
thread: 'support-thread-456',
},
})
```
如需在呼叫期間建立或更新執行緒中繼資料,請使用執行緒物件:
```typescript
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
使用 `hooks` 在 Agent 每次呼叫 Tool 前後運行邏輯,包括已指派 Tool、記憶體 Tool、工具集、用戶端 Tool 及 Workspace Tool。
```typescript
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 結果:
```typescript
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](https://mastra.zisheng.pro/zh-HK/reference/workspace/workspace-class) 亦定義 `tools.hooks` 時,Workspace hook 會在 Agent hook 包裝器內運行。
## 編輯器覆寫
註冊 [`MastraEditor`](https://mastra.zisheng.pro/zh-HK/reference/editor/mastra-editor) 時,`editor` 欄位控制程式碼定義的 Agent 有哪些部分可透過編輯器變更。由程式碼擁有的欄位在 Studio 中為唯讀,並會從已儲存的覆寫中移除。
**editor** (`false | { instructions?: boolean; tools?: boolean | { description?: boolean } }`): 省略時允許編輯指示及 Tool。設為 false 可鎖定 Agent。設為 instructions: true 可編輯指示。設為 tools: true 可編輯 Tool 成員及說明;設為 tools: { description: true } 則只允許編輯說明。
Agent 的 `id`、`name` 和 `model` 一律來自程式碼,無法透過 Editor 覆寫。使用方式請參閱 [Editor](https://mastra.zisheng.pro/zh-HK/docs/editor/overview)。
## 傳回值
**agent** (`Agent`): 採用指定配置的新 Agent 實例。