Agent.생성()
그만큼.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 }을 반환하여 감독자의 다음 작업을 안내할 수 있습니다. 피드백은 감독자의 Memory에 assistant 메시지로 저장됩니다.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이 활성화되어 있고 스레드에 기존 제목이 없을 때만 실행됩니다.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는 단계 객체의 배열입니다. 최상위 toolCalls와 toolResults, 중첩된 step.toolCalls와 step.toolResults 배열을 포함하여 결과의 Tool 배열에는 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 reference.
보고보고에 대한 직접 링크
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별 메타데이터를 포함합니다.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의 채점 데이터입니다.더 많은 예시더 많은 예시에 대한 직접 링크
Model 설정으로Model 설정으로에 대한 직접 링크
출력 토큰 제한 및 온도 설정의 예:
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',
},
})
응답 헤더에 액세스응답 헤더에 액세스에 대한 직접 링크
일부 Model 공급자는 남은 토큰 수 또는 속도 제한 상태와 같은 유용한 정보를 응답 헤더에 반환합니다. 생성이 완료된 후 결과 개체에서 이러한 헤더에 액세스할 수 있습니다.
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는 시각적 콘텐츠와 그 안의 텍스트를 모두 처리하여 이미지를 분석하고 설명할 수 있습니다. 이미지 분석을 활성화하려면 type: 'image'가 지정된 객체와 이미지 URL을 content 배열에 전달하세요. 이미지 콘텐츠와 텍스트 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의 토큰 사용량도 제어할 수 있습니다. 기본값은 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)
},
},
})