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 運行的要求情境中加入項目。onDelegationComplete?:
bail() 方法;你亦可傳回 { feedback } 來引導監督 Agent 的下一步。意見會以助理訊息形式儲存至監督 Agent 的記憶體。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 陣列,包括最上層的 toolCalls 和 toolResults,以及巢狀的 step.toolCalls 和 step.toolResults 陣列,均使用 Mastra 的區塊格式。
亦即 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)
}
}
如需相同區塊結構的串流版本,請參閱 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() or declineToolCallGenerate() to resume a suspended execution.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 能記住先前的互動,並在訊息之間維持情境。
const memoryResult = await agent.generate('Remember my favorite color is blue', {
memory: {
thread: 'user-123-thread',
resource: 'user-123',
},
})
存取回應 header存取回應 header 的直接連結
部分模型 Provider 會在回應 header 中傳回實用資料,例如剩餘 token 數目或速率限制狀態。產生程序完成後,你可以從結果物件存取這些 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 的物件。你可將圖像內容與文字提示結合,以引導 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)
使用 maxStepsusing-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)
使用 onStepFinishusing-onstepfinish 的直接連結
你可以使用 onStepFinish 回呼監察多步驟操作的進度。這適合用於偵錯,或向使用者提供進度更新。
只有在串流傳輸或產生不含結構化輸出的文字時,才可使用 onStepFinish。
const response = await agent.generate('Help me organize my day', {
onStepFinish: ({ text, toolCalls, toolResults, finishReason, usage }) => {
console.log({ text, toolCalls, toolResults, finishReason, usage })
},
})
使用 onTitleGeneratedusing-ontitlegenerated 的直接連結
在記憶體選項中啟用 generateTitle 後,標題產生程序會在回應完成後以非同步方式運行。標題準備好時,可使用 onTitleGenerated 作出反應,例如透過 SSE 推送至客戶端。
const response = await agent.generate('What is quantum computing?', {
memory: {
thread: threadId,
resource: userId,
onTitleGenerated: title => {
console.log('Thread title:', title)
},
},
})