Agent 클래스
그만큼Agent클래스는 Mastra에서 AI Agent를 생성하기 위한 기반입니다. 응답을 생성하고 상호 작용을 스트리밍하는 방법을 제공합니다. 음성 기능도 처리합니다.
사용 예사용 예에 대한 직접 링크
기본 문자열 지침기본 문자열 지침에 대한 직접 링크
명령을 문자열이나 문자열 배열로 전달하는 것은 Agent를 설정하는 가장 간단한 방법입니다. 이는 추가 구성 없이 Prompt를 제공해야 하는 간단한 사용 사례에 유용합니다.
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',
})
공급자별 구성공급자별 구성에 대한 직접 링크
각 Model Provider는 Prompt 캐싱 및 추론 구성을 비롯한 여러 옵션도 지원합니다. 지침 수준에서 providerOptions를 설정하여 시스템 지침/Prompt마다 서로 다른 캐싱 전략을 지정할 수 있습니다.
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',
})
혼합 명령어 형식혼합 명령어 형식에 대한 직접 링크
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',
})
Model 문자열Model 문자열에 대한 직접 링크
가장 간단하게 설정하려면 provider/model 형식의 문자열로 model을 전달하세요. Provider와 Model 이름은 슬래시로 구분합니다. Mastra는 환경에서 일치하는 Provider 자격 증명을 읽으므로 이 형식에는 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를 사용합니다. 지원되는 Model ID는 Model을, 전체 Provider 목록은 환경 변수를 참조하세요.
스레드 신호스레드 신호에 대한 직접 링크
Agent 신호를 사용하여 실시간 입력과 컨텍스트를 Memory 스레드로 보냅니다. 메시지 API는 사용자가 작성한 입력을 위한 것이며, sendSignal()은 시스템에서 생성한 컨텍스트를 위한 하위 수준 API입니다.
대상 스레드가 실행 중이면 sendMessage()는 메시지를 활성 Agent 루프에 전달합니다. 스레드가 유휴 상태이면 기본적으로 Mastra가 메시지를 첫 입력으로 사용하여 스트림을 시작합니다.
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를 사용하세요. Model이 누가 어떤 말을 했는지 구분할 수 있도록 속성이 XML로 렌더링됩니다:
agent.sendMessage(
{
contents: 'Can we simplify the API surface?',
attributes: { name: 'Devin', from: 'slack' },
},
{ resourceId: 'user-123', threadId: 'thread-abc' },
)
Model은 이를 다음과 같이 수신합니다.
<user name="Devin" from="slack">Can we simplify the API surface?</user>
스레드가 현재 실행 중인지 여부에 따라 메시지에 서로 다른 컨텍스트를 포함해야 한다면 ifActive.attributes와 ifIdle.attributes를 사용하세요:
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' } },
},
)
스레드가 활성화되면 Model은 다음을 확인합니다.
<user source="chat" delivery="while-active">Also cover the edge cases.</user>
스레드가 유휴 상태일 때 Model은 다음을 확인합니다.
<user source="chat" delivery="new-message">Also cover the edge cases.</user>
UI는 사용자 지정 렌더링을 위해 메시지 내용을 확인하고 신호 메시지에서 attributes와 metadata를 읽을 수도 있습니다(예: 사용자 이름, 아바타 또는 플랫폼 배지 표시).
sendMessage(message, options)sendmessagemessage-options에 대한 직접 링크
활성 실행 또는 Memory 스레드에 사용자 메시지를 보냅니다. 활성 Agent가 메시지를 즉시 수신해야 하는 경우 이를 사용하십시오.
message:
attributes가 있으면 Mastra는 속성을 포함하는 <user> XML 요소로 메시지를 렌더링합니다.options?:
runId?:
resourceId?:
threadId와 함께 지정해야 합니다.threadId?:
resourceId와 함께 지정해야 합니다.ifActive?:
behavior?:
deliver입니다.attributes?:
ifIdle?:
behavior?:
wake입니다.streamOptions?:
ifIdle.behavior가 wake일 때 시작되는 스트림의 옵션입니다. Mastra는 최상위 resourceId와 threadId를 Memory 컨텍스트에 사용합니다.attributes?:
유휴 스레드가 사용자 지정 실행 옵션으로 새 스트림을 시작해야 한다면 ifIdle.behavior를 wake로 설정하고 ifIdle.streamOptions를 전달하세요:
agent.sendMessage('Continue with the next step.', {
resourceId: 'user-123',
threadId: 'thread-abc',
ifIdle: {
behavior: 'wake',
streamOptions: {
maxSteps: 3,
},
},
})
{ accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void> }를 반환합니다. 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가 Memory에 메시지 쓰기를 마치면 이행됩니다. wake 동작에서 output은 프로세스 내에서 사용할 수 있는 Agent 스트림입니다.
queueMessage(message, options)queuemessagemessage-options에 대한 직접 링크
스레드의 다음 차례를 위해 사용자 메시지를 대기열에 넣습니다. 스레드가 활성화된 경우 Mastra는 활성 실행이 완료될 때까지 기다린 다음 대기열에 있는 메시지로 새 실행을 시작합니다. 스레드가 유휴 상태이면 Mastra는 즉시 실행을 시작합니다.
agent.queueMessage('Also check whether the tests need updates.', {
resourceId: 'user-123',
threadId: 'thread-abc',
})
queueMessage()는 sendMessage()와 동일한 message 및 options 형식을 받으며 { accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void> }를 반환합니다. accepted의 의미 체계도 sendMessage()와 같습니다.
sendSignal(signal, options)sendsignalsignal-options에 대한 직접 링크
활성 실행 또는 Memory 스레드에 신호를 보냅니다.
signal:
type은 신호의 의미 범주입니다. tagName은 Model에 표시되는 XML 태그를 제어합니다. 예를 들어 { type: 'notification', tagName: 'github-review' }는 <github-review>...</github-review>로 렌더링됩니다. 레거시 user-message 및 system-reminder 페이로드도 계속 허용되며 정규화됩니다. 알 수 없는 type 값은 거부됩니다. 사용자 지정 XML 태그에는 tagName을 사용하세요.options?:
runId?:
resourceId?:
threadId와 함께 필요합니다.threadId?:
resourceId와 함께 필요합니다.ifActive?:
behavior?:
deliver입니다.attributes?:
ifIdle?:
behavior?:
wake입니다.streamOptions?:
ifIdle.behavior가 wake일 때 시작되는 스트림의 옵션입니다. Mastra는 최상위 resourceId와 threadId를 Memory 컨텍스트로 사용합니다.attributes?:
{ accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void> }를 반환합니다. 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()을 통해 노출됨), 신호를 라우팅하거나 실행을 시작할 수 없는 경우에만 거부됩니다(예: 잘못 구성된 Agent). persisted는 persist 동작에만 존재하며 Mastra가 Memory에 신호 쓰기를 마치면 이행됩니다. wake 동작에서 output은 프로세스 내에서 사용할 수 있는 Agent 스트림입니다.
서버리스 핸들러에서는 accepted를 기다리고 wake의 출력을 플랫폼의 waitUntil에 해당하는 기능으로 전달하여, HTTP 응답이 반환된 후 최종 선택된 프로세스가 스트림을 끝까지 처리할 수 있게 하세요.
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)sendstatesignalstate-options에 대한 직접 링크
명명된 스레드 범위 상태 컨텍스트를 활성 실행 스레드 또는 Memory 스레드로 보냅니다. 외부 생산자가 브라우저 상태, 편집기 상태 또는 감시자 출력과 같이 시간이 지남에 따라 변경되는 지속성 컨텍스트를 소유하는 경우 이를 사용합니다.
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:
id:
browser or editor.cacheKey:
contents:
mode?:
snapshot입니다.value?:
mode: 'snapshot'의 구조화된 스냅샷 값입니다.delta?:
mode: 'delta'의 구조화된 변경 값입니다.attributes?:
metadata?:
tagName?:
state입니다.options:
sendSignal()과 동일한 옵션을 허용합니다.Mastra가 새 상태를 수락하면 { accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void>, 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)sendnotificationsignalnotification-options에 대한 직접 링크
알림 받은 편지함 기록을 생성하거나 통합하고 알림 전달 정책을 해결합니다. 결정이 즉시 내려지면 알림 신호를 보냅니다.
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:
source:
github, slack, email 등 알림을 생성한 외부 시스템입니다.kind:
ci-status, mention, direct-message 등 소스 내의 알림 종류입니다.summary:
priority?:
medium입니다.payload?:
dedupeKey?:
coalesceKey?:
attributes?:
metadata?:
options:
resourceId:
threadId:
ifIdle?:
streamOptions?:
{ record: NotificationRecord, decision: NotificationDeliveryDecision, runId?: string, signal?: CreatedAgentSignal, persisted?: Promise<void>, accepted?: Promise<SendAgentSignalAccepted> }를 반환합니다. 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 알림은 활성 및 유휴 스레드 모두에서 요약으로 일괄 처리됩니다. 유휴 상태의 낮은 우선순위 요약은 Model 루프를 깨우지 않고 구독자에게 전달됩니다. 전체 흐름은 신호를 참조하세요.
일부 알림이 다른 디스패치 기간이나 요약 롤업까지 기다려야 한다면 Agent의 notifications.deliveryPolicy를 구성하세요.
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)subscribetothreadoptions에 대한 직접 링크
Memory 스레드의 원시 스트림 청크를 구독합니다. sendMessage(), queueMessage() 또는 sendSignal()을 호출하기 전에 사용하세요. 스트림 출력을 렌더링하고 신호 에코를 관찰할 수 있으며, 신호가 활성 실행을 중단하는 경우도 포함됩니다.
options:
resourceId?:
threadId:
다음 멤버가 포함된 AgentThreadSubscription 객체를 반환합니다.
stream:
activeRunId:
null을 반환합니다.abort:
true를 반환합니다.unsubscribe:
생성자 매개변수생성자 매개변수에 대한 직접 링크
id:
name:
description?:
metadata?:
instructions:
model:
provider/model 형식의 Model 라우터 문자열, Model 구성 또는 Provider 인스턴스, 혹은 런타임에 Model을 확인하는 함수를 전달하세요. 일반적인 Provider 및 환경 변수는 Model 문자열을 참조하세요.agents?:
tools?:
hooks?:
generate() 또는 stream()에 전달된 실행별 훅은 여기에 설정된 일치하는 훅을 재정의합니다. 아래의 Tool 훅을 참조하세요.beforeToolCall?:
{ toolName, input, context, metadata }를 받습니다. Tool 호출을 건너뛰고 output을 결과로 사용하려면 { proceed: false, output }을 반환하세요.afterToolCall?:
{ toolName, input, context, metadata, output, error }를 받습니다. Tool에서 예외가 발생하면 output은 undefined이고 대신 error가 설정됩니다.transform?:
createTool()의 Tool별 transform을 사용하세요.workflows?:
defaultOptions?:
stream() 및 generate() 호출 시 사용하는 기본 옵션입니다.defaultGenerateOptionsLegacy?:
generateLegacy() 호출 시 사용하는 기본 옵션입니다.defaultStreamOptionsLegacy?:
streamLegacy() 호출 시 사용하는 기본 옵션입니다.mastra?:
scorers?:
memory?:
notifications?:
deliveryPolicy?:
decide() 함수를 구성하세요.voice?:
inputProcessors?:
createWorkflow()로 생성한 Workflow일 수 있습니다.outputProcessors?:
maxProcessorRetries?:
requestContextSchema?:
editor?:
generate()Memory 옵션generate-memory-options에 대한 직접 링크
agent.generate()를 호출할 때 memory를 전달하여 실행이 읽고 쓸 대화 스레드를 선택하세요. 일반적인 형식은 memory: { resource: string, thread: string }이며, 여기서 resource는 소유자를 식별하고 thread는 대화를 식별합니다. 개념 모델은 스레드와 리소스를 참조하세요.
const response = await agent.generate('What did we decide about retries?', {
memory: {
resource: 'user-123',
thread: 'support-thread-456',
},
})
호출 중에 스레드 메타데이터를 생성하거나 업데이트해야 하는 경우 스레드 개체를 사용합니다.
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 후크Tool 후크에 대한 직접 링크
hooks를 사용하여 할당된 Tool, Memory Tool, Tool 세트, 클라이언트 Tool, Workspace Tool을 포함해 Agent가 수행하는 모든 Tool 호출 전후에 로직을 실행하세요.
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 결과로 사용합니다.
const result = await agent.generate('Clean up old records', {
hooks: {
beforeToolCall: ({ toolName }) => {
if (toolName === 'deleteRecord') {
return { proceed: false, output: { blocked: true } }
}
},
},
})
훅 컨텍스트의 metadata에는 agentId와 agentName이 포함됩니다. generate() 또는 stream()에 전달된 실행별 훅은 일치하는 Agent 수준 훅을 재정의합니다. Workspace에도 tools.hooks가 정의되어 있으면 Workspace 훅은 Agent 훅 래퍼 내부에서 실행됩니다.
편집기 재정의편집기 재정의에 대한 직접 링크
MastraEditor를 등록할 때 editor 필드는 코드로 정의된 Agent에서 편집기를 통해 변경할 수 있는 부분을 제어합니다. 코드가 소유한 필드는 Studio에서 읽기 전용이며 저장된 재정의에서 제거됩니다.
editor?:
false로 설정하세요. 지침 편집을 허용하려면 instructions: true로 설정하세요. Tool 구성원 및 설명 편집을 허용하려면 tools: true로 설정하고, 설명 편집만 허용하려면 tools: { description: true }로 설정하세요.Agent의 id, name, model은 항상 코드에서 가져오며 Editor를 통해 재정의할 수 없습니다. 사용법은 Editor를 참조하세요.