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 运行的 request context 添加条目。onDelegationComplete?:
bail() 方法,你还可以返回 { feedback } 来引导 supervisor 的下一步操作。反馈会作为 assistant 消息保存到 supervisor memory。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。需要配置 memory。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() 返回后才完成。仅当 memory 选项中启用了 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 的 chunk 格式。
这意味着 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,
},
})
使用 memory使用 memory的直接链接
通过配置 memory 选项,让 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 的对象。可以将图片内容与文本 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)
使用 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的直接链接
在 memory 选项中启用 generateTitle 后,标题生成会在响应完成后异步运行。使用 onTitleGenerated 可在标题就绪时进行处理,例如通过 SSE 将其推送到客户端。
const response = await agent.generate('What is quantum computing?', {
memory: {
thread: threadId,
resource: userId,
onTitleGenerated: title => {
console.log('Thread title:', title)
},
},
})