Agent.generate()
.generate() 方法讓 Agent 能以增強功能進行非串流回應生成。此方法接受訊息與選用的生成選項。
使用範例「使用範例」的直接連結
以訊息呼叫 Agent 以生成回應:
const result = await agent.generate('message for agent')
參數「參數」的直接連結
messages:
options?:
maxSteps?:
stopWhen?:
onIterationComplete?:
context.iteration:
context.maxIterations:
context.text:
context.isFinal:
context.finishReason:
context.toolCalls:
context.messages:
return.continue?:
return.feedback?:
isTaskComplete?:
scorers:
strategy?:
onComplete?:
parallel?:
timeout?:
delegation?:
onDelegationStart?:
context.requestContext 以在子 Agent run 的 request context 中新增項目。onDelegationComplete?:
bail() 方法;您也可以回傳 { feedback } 來引導 supervisor 的下一個動作。feedback 會以 assistant 訊息儲存至 supervisor 記憶體。messageFilter?:
scorers?:
scorer:
sampling?:
type:
rate?:
returnScorerData?:
onChunk?:
onError?:
onAbort?:
activeTools?:
abortSignal?:
prepareStep?:
requireToolApproval?:
finishReason: 'suspended',並包含具有 Tool 呼叫詳細資料(toolCallId、toolName、args)的 suspendPayload。使用 approveToolCallGenerate() 或 declineToolCallGenerate() 繼續。詳細資訊請參閱 Agent 核准。autoResumeSuspendedTools?:
resumeSchema 從使用者訊息擷取 resumeData。必須設定記憶體。toolCallConcurrency?:
context?:
structuredOutput?:
schema:
model?:
errorStrategy?:
fallbackValue?:
instructions?:
jsonPromptInjection?:
logger?:
providerOptions?:
{ openai: { reasoningEffort: 'low' } })。outputProcessors?:
maxProcessorRetries?:
inputProcessors?:
instructions?:
system?:
output?:
memory?:
thread:
resource:
options?:
onTitleGenerated?:
generate() 回傳後才完成。只有在記憶體選項中啟用 generateTitle,且 thread 沒有現有標題時才會觸發。onFinish?:
onStepFinish?:
telemetry?:
isEnabled?:
recordInputs?:
recordOutputs?:
functionId?:
modelSettings?:
temperature?:
maxOutputTokens?:
maxRetries?:
topP?:
topK?:
presencePenalty?:
frequencyPenalty?:
stopSequences?:
toolChoice?:
'auto':
'none':
'required':
{ type: 'tool'; toolName: string }:
toolsets?:
clientTools?:
hooks?:
beforeToolCall 可回傳 { proceed: false, output } 以略過 Tool 呼叫。savePerStep?:
providerOptions?:
openai?:
anthropic?:
google?:
[providerName]?:
runId?:
requestContext?:
tracingContext?:
currentSpan?:
tracingOptions?:
metadata?:
requestContextKeys?:
traceId?:
parentSpanId?:
tags?:
versions?:
agents?:
versionId?:
status?:
includeRawChunks?:
回應結構「回應結構」的直接連結
Agent.generate() 會回傳執行期間收集的最終資料。steps 是步驟物件陣列。結果中的 Tool 陣列會使用 Mastra 的 chunk 格式,包括頂層 toolCalls 與 toolResults,以及巢狀 step.toolCalls 與 step.toolResults 陣列。
也就是說,Tool 資料會包裝在 payload 中:
const response = await agent.generate('Check the weather in Lagos')
for (const toolCall of response.toolCalls) {
console.log(toolCall.type) // 'tool-call'
console.log(toolCall.runId)
console.log(toolCall.from)
console.log(toolCall.payload.toolName)
console.log(toolCall.payload.args)
}
for (const step of response.steps) {
for (const toolResult of step.toolResults) {
console.log(toolResult.type) // 'tool-result'
console.log(toolResult.payload.toolName)
console.log(toolResult.payload.result)
}
}
相同 chunk 結構的串流版本請參閱 ChunkType 參考文件。
回傳值「回傳值」的直接連結
result:
text:
object?:
toolCalls:
type:
runId:
from:
payload:
toolCallId:
toolName:
args?:
providerExecuted?:
toolResults:
type:
runId:
from:
payload:
toolCallId:
toolName:
result:
isError?:
usage:
steps:
text:
toolCalls:
toolResults:
finishReason?:
usage:
request:
response:
finishReason:
response:
id?:
timestamp?:
modelId?:
headers?:
anthropic-ratelimit-requests-remaining、x-ratelimit-remaining-tokens)與其他 Provider 專屬 metadata。messages?:
uiMessages?:
request?:
body?:
warnings?:
providerMetadata?:
reasoning?:
reasoningText?:
sources?:
files?:
suspendPayload?:
finishReason 為 'suspended' 時存在。包含核准或拒絕待處理 Tool 呼叫所需的 Tool 呼叫詳細資料。toolCallId:
toolName:
args:
runId?:
approveToolCallGenerate() 或 declineToolCallGenerate() 以恢復已暫停執行時必填。traceId?:
spanId?:
messages:
rememberedMessages:
error?:
tripwire?:
scoringData?:
returnScorerData 時供 Evals 使用的評分資料。更多範例「更多範例」的直接連結
搭配模型設定「搭配模型設定」的直接連結
限制輸出 token 並設定 temperature 的範例:
const limitedResult = await agent.generate('Write a short poem about coding', {
modelSettings: {
maxOutputTokens: 50,
temperature: 0.7,
},
})
搭配記憶體「搭配記憶體」的直接連結
設定記憶體選項,讓 Agent 能存取並保存對話歷程。Agent 因此能記住先前互動,並跨訊息維持 context。
const memoryResult = await agent.generate('Remember my favorite color is blue', {
memory: {
thread: 'user-123-thread',
resource: 'user-123',
},
})
存取回應 header「存取回應 header」的直接連結
部分模型 Provider 會在回應 header 中傳回實用資訊,例如剩餘 token 數或 rate limit 狀態。生成完成後,您可以從結果物件存取這些 header。
const result = await agent.generate('Hello!')
const remainingRequests = result.response?.headers?.['anthropic-ratelimit-requests-remaining']
const remainingTokens = result.response?.headers?.['x-ratelimit-remaining-tokens']
console.log(`Remaining requests: ${remainingRequests}, Remaining tokens: ${remainingTokens}`)
分析圖片「分析圖片」的直接連結
Agent 可處理圖片中的視覺內容與文字,進而分析並描述圖片。若要啟用圖片分析,請在 content 陣列中傳入包含 type: 'image' 與圖片 URL 的物件。您可以結合圖片內容與文字 prompt,引導 Agent 進行分析。
const response = await agent.generate([
{
role: 'user',
content: [
{
type: 'image',
image: 'https://placebear.com/cache/395-205.jpg',
mimeType: 'image/jpeg',
},
{
type: 'text',
text: 'Describe the image in detail, and extract all the text in the image.',
},
],
},
])
console.log(response.text)
使用 maxSteps「using-maxsteps」的直接連結
maxSteps 參數控制 Agent 可連續呼叫 LLM 的次數上限。每個步驟會先生成回應並執行所有 Tool 呼叫,再處理結果。限制步驟數有助於避免無限迴圈並降低延遲,也能控制使用 Tool 之 Agent 的 token 用量。預設值為 5,但可提高:
const response = await agent.generate('Help me organize my day', {
maxSteps: 10,
})
console.log(response.text)
使用 onStepFinish「using-onstepfinish」的直接連結
您可以使用 onStepFinish callback 監控多步驟作業的進度,適合用來偵錯或向使用者提供進度更新。
onStepFinish 只有在串流或生成不含結構化輸出的文字時才可用。
const response = await agent.generate('Help me organize my day', {
onStepFinish: ({ text, toolCalls, toolResults, finishReason, usage }) => {
console.log({ text, toolCalls, toolResults, finishReason, usage })
},
})
使用 onTitleGenerated「using-ontitlegenerated」的直接連結
在記憶體選項中啟用 generateTitle 後,標題生成會在回應完成後非同步執行。標題就緒時可使用 onTitleGenerated 回應,例如透過 SSE 推送至 client。
const response = await agent.generate('What is quantum computing?', {
memory: {
thread: threadId,
resource: userId,
onTitleGenerated: title => {
console.log('Thread title:', title)
},
},
})