> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # Agent 클래스 그만큼`Agent`클래스는 Mastra에서 AI Agent를 생성하기 위한 기반입니다. 응답을 생성하고 상호 작용을 스트리밍하는 방법을 제공합니다. 음성 기능도 처리합니다. ## 사용 예 ### 기본 문자열 지침 명령을 문자열이나 문자열 배열로 전달하는 것은 Agent를 설정하는 가장 간단한 방법입니다. 이는 추가 구성 없이 Prompt를 제공해야 하는 간단한 사용 사례에 유용합니다. ```typescript 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마다 서로 다른 캐싱 전략을 지정할 수 있습니다. ```typescript 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', }) ``` ### 혼합 명령어 형식 ```typescript 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 문자열 가장 간단하게 설정하려면 `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](https://mastra.zisheng.pro/ko/models)을, 전체 Provider 목록은 [환경 변수](https://mastra.zisheng.pro/ko/models/environment-variables)를 참조하세요. ## 스레드 신호 Agent 신호를 사용하여 실시간 입력과 컨텍스트를 Memory 스레드로 보냅니다. 메시지 API는 사용자가 작성한 입력을 위한 것이며, `sendSignal()`은 시스템에서 생성한 컨텍스트를 위한 하위 수준 API입니다. 대상 스레드가 실행 중이면 `sendMessage()`는 메시지를 활성 Agent 루프에 전달합니다. 스레드가 유휴 상태이면 기본적으로 Mastra가 메시지를 첫 입력으로 사용하여 스트림을 시작합니다. ```typescript 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로 렌더링됩니다: ```typescript agent.sendMessage( { contents: 'Can we simplify the API surface?', attributes: { name: 'Devin', from: 'slack' }, }, { resourceId: 'user-123', threadId: 'thread-abc' }, ) ``` Model은 이를 다음과 같이 수신합니다. ```xml Can we simplify the API surface? ``` 스레드가 현재 실행 중인지 여부에 따라 메시지에 서로 다른 컨텍스트를 포함해야 한다면 `ifActive.attributes`와 `ifIdle.attributes`를 사용하세요: ```typescript 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은 다음을 확인합니다. ```xml Also cover the edge cases. ``` 스레드가 유휴 상태일 때 Model은 다음을 확인합니다. ```xml Also cover the edge cases. ``` UI는 사용자 지정 렌더링을 위해 메시지 내용을 확인하고 신호 메시지에서 `attributes`와 `metadata`를 읽을 수도 있습니다(예: 사용자 이름, 아바타 또는 플랫폼 배지 표시). ### `sendMessage(message, options)` 활성 실행 또는 Memory 스레드에 사용자 메시지를 보냅니다. 활성 Agent가 메시지를 즉시 수신해야 하는 경우 이를 사용하십시오. **message** (`string | Array | { contents: string | Array; attributes?: Record; metadata?: Record; providerOptions?: ProviderMetadata }`): 사용자가 작성한 입력입니다. 속성이 없는 일반 문자열 및 파트는 일반 사용자 입력으로 Model에 전송됩니다. attributes가 있으면 Mastra는 속성을 포함하는 \ XML 요소로 메시지를 렌더링합니다. **options** (`object`): 메시지의 대상 지정 및 전달 동작입니다. **options.runId** (`string`): 직접 대상으로 지정할 실행 ID입니다. 활성 실행 ID를 이미 알고 있을 때 사용하세요. **options.resourceId** (`string`): Memory 스레드의 리소스 ID입니다. 스레드 대상 메시지에서는 threadId와 함께 지정해야 합니다. **options.threadId** (`string`): 대상 스레드 ID입니다. 스레드 대상 메시지에서는 resourceId와 함께 지정해야 합니다. **options.ifActive** (`object`): 대상 스레드가 활성 상태일 때의 동작을 제어합니다. **options.ifActive.behavior** (`'deliver' | 'persist' | 'discard'`): 대상 스레드가 활성 상태일 때의 동작을 제어합니다. 기본값은 deliver입니다. **options.ifActive.attributes** (`Record`): 대상 스레드가 활성 상태일 때 Mastra가 메시지를 수락하면 메시지에 병합되는 속성입니다. **options.ifIdle** (`object`): 대상 스레드가 유휴 상태일 때의 동작을 제어합니다. **options.ifIdle.behavior** (`'wake' | 'persist' | 'discard'`): 대상 스레드가 유휴 상태일 때의 동작을 제어합니다. 기본값은 wake입니다. **options.ifIdle.streamOptions** (`AgentExecutionOptions`): ifIdle.behavior가 wake일 때 시작되는 스트림의 옵션입니다. Mastra는 최상위 resourceId와 threadId를 Memory 컨텍스트에 사용합니다. **options.ifIdle.attributes** (`Record`): 대상 스레드가 유휴 상태일 때 Mastra가 메시지를 수락하면 메시지에 병합되는 속성입니다. 유휴 스레드가 사용자 지정 실행 옵션으로 새 스트림을 시작해야 한다면 `ifIdle.behavior`를 `wake`로 설정하고 `ifIdle.streamOptions`를 전달하세요: ```typescript agent.sendMessage('Continue with the next step.', { resourceId: 'user-123', threadId: 'thread-abc', ifIdle: { behavior: 'wake', streamOptions: { maxSteps: 3, }, }, }) ``` `{ accepted: Promise, signal: CreatedAgentSignal, persisted?: Promise }`를 반환합니다. 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)` 스레드의 다음 차례를 위해 사용자 메시지를 대기열에 넣습니다. 스레드가 활성화된 경우 Mastra는 활성 실행이 완료될 때까지 기다린 다음 대기열에 있는 메시지로 새 실행을 시작합니다. 스레드가 유휴 상태이면 Mastra는 즉시 실행을 시작합니다. ```typescript agent.queueMessage('Also check whether the tests need updates.', { resourceId: 'user-123', threadId: 'thread-abc', }) ``` `queueMessage()`는 `sendMessage()`와 동일한 `message` 및 `options` 형식을 받으며 `{ accepted: Promise, signal: CreatedAgentSignal, persisted?: Promise }`를 반환합니다. `accepted`의 의미 체계도 `sendMessage()`와 같습니다. ### `sendSignal(signal, options)` 활성 실행 또는 Memory 스레드에 신호를 보냅니다. **signal** (`{ type: 'user' | 'state' | 'reactive' | 'notification' | 'user-message' | 'system-reminder'; tagName?: string; contents: string | Array; attributes?: Record; metadata?: Record; providerOptions?: ProviderMetadata }`): 스레드로 보낼 신호 컨텍스트입니다. type은 신호의 의미 범주입니다. tagName은 Model에 표시되는 XML 태그를 제어합니다. 예를 들어 { type: 'notification', tagName: 'github-review' }는 \...\로 렌더링됩니다. 레거시 user-message 및 system-reminder 페이로드도 계속 허용되며 정규화됩니다. 알 수 없는 type 값은 거부됩니다. 사용자 지정 XML 태그에는 tagName을 사용하세요. **options** (`object`): 신호의 대상 지정 및 전달 동작입니다. **options.runId** (`string`): 직접 대상으로 지정할 실행 ID입니다. 활성 실행 ID를 이미 알고 있을 때 사용하세요. **options.resourceId** (`string`): Memory 스레드의 리소스 ID입니다. 스레드 대상 신호에는 threadId와 함께 필요합니다. **options.threadId** (`string`): 대상으로 지정할 스레드 ID입니다. 스레드 대상 신호에는 resourceId와 함께 필요합니다. **options.ifActive** (`object`): 대상 스레드가 활성 상태일 때 수행할 작업을 제어합니다. **options.ifActive.behavior** (`'deliver' | 'persist' | 'discard'`): 대상 스레드가 활성 상태일 때 수행할 작업을 제어합니다. 기본값은 deliver입니다. **options.ifActive.attributes** (`Record`): 대상 스레드가 활성 상태일 때 Mastra가 신호를 수락하면 신호에 병합되는 속성입니다. **options.ifIdle** (`object`): 대상 스레드가 유휴 상태일 때 수행할 작업을 제어합니다. **options.ifIdle.behavior** (`'wake' | 'persist' | 'discard'`): 대상 스레드가 유휴 상태일 때 수행할 작업을 제어합니다. 기본값은 wake입니다. **options.ifIdle.streamOptions** (`AgentExecutionOptions`): ifIdle.behavior가 wake일 때 시작되는 스트림의 옵션입니다. Mastra는 최상위 resourceId와 threadId를 Memory 컨텍스트로 사용합니다. **options.ifIdle.attributes** (`Record`): 대상 스레드가 유휴 상태일 때 Mastra가 신호를 수락하면 신호에 병합되는 속성입니다. `{ accepted: Promise, signal: CreatedAgentSignal, persisted?: Promise }`를 반환합니다. 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 응답이 반환된 후 최종 선택된 프로세스가 스트림을 끝까지 처리할 수 있게 하세요. ```typescript 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)` 명명된 스레드 범위 상태 컨텍스트를 활성 실행 스레드 또는 Memory 스레드로 보냅니다. 외부 생산자가 브라우저 상태, 편집기 상태 또는 감시자 출력과 같이 시간이 지남에 따라 변경되는 지속성 컨텍스트를 소유하는 경우 이를 사용합니다. ```typescript 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** (`object`): 스레드로 보낼 상태 신호입니다. **state.id** (`string`): State lane name, such as browser or editor. **state.cacheKey** (`string`): Mastra가 동일한 레인 및 모드의 중복 상태를 건너뛰는 데 사용하는, 생성자가 소유한 키입니다. **state.contents** (`string | Array`): LLM에 표시되는 상태 표현입니다. **state.mode** (`'snapshot' | 'delta'`): 상태가 권위 있는 스냅샷인지 변경 이벤트인지를 지정합니다. 기본값은 snapshot입니다. **state.value** (`unknown`): mode: 'snapshot'의 구조화된 스냅샷 값입니다. **state.delta** (`unknown`): mode: 'delta'의 구조화된 변경 값입니다. **state.attributes** (`Record`): 상태 신호 태그에 렌더링되는 속성입니다. **state.metadata** (`Record`): 상태 신호와 함께 저장되는 애플리케이션 메타데이터입니다. **state.tagName** (`string`): Model에 표시되는 XML 태그 이름입니다. 기본값은 state입니다. **options** (`object`): 상태 신호의 대상 지정 및 전달 동작입니다. sendSignal()과 동일한 옵션을 허용합니다. Mastra가 새 상태를 수락하면 `{ accepted: Promise, signal: CreatedAgentSignal, persisted?: Promise, 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)` 알림 받은 편지함 기록을 생성하거나 통합하고 알림 전달 정책을 해결합니다. 결정이 즉시 내려지면 알림 신호를 보냅니다. ```typescript 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** (`object`): 생성하거나 병합할 알림 받은 편지함 레코드입니다. **notification.source** (`string`): github, slack, email 등 알림을 생성한 외부 시스템입니다. **notification.kind** (`string`): ci-status, mention, direct-message 등 소스 내의 알림 종류입니다. **notification.summary** (`string`): 알림 신호의 콘텐츠로 사용되는 LLM용 요약입니다. **notification.priority** (`'low' | 'medium' | 'high' | 'urgent'`): 알림 전달 정책에서 사용하는 우선순위입니다. 기본값은 medium입니다. **notification.payload** (`unknown`): Tool 또는 애플리케이션 코드에서 사용할 수 있도록 받은 편지함 레코드에 저장되는 구조화된 페이로드입니다. **notification.dedupeKey** (`string`): 동일한 소스와 스레드에서 대기 중인 중복 알림을 병합하는 데 사용하는 키입니다. **notification.coalesceKey** (`string`): 동일한 소스와 스레드에서 대기 중인 관련 알림을 결합하는 데 사용하는 키입니다. **notification.attributes** (`Record`): 방출된 알림 신호에 복사되는 추가 속성입니다. **notification.metadata** (`Record`): 받은 편지함 레코드에 저장되는 애플리케이션 메타데이터입니다. **options** (`object`): 알림의 대상 스레드 및 깨우기 동작입니다. **options.resourceId** (`string`): 알림 받은 편지함 및 대상 Memory 스레드의 리소스 ID입니다. **options.threadId** (`string`): 알림 받은 편지함 및 대상 Memory 스레드의 스레드 ID입니다. **options.ifIdle** (`object`): 대상 스레드가 유휴 상태일 때 수행할 작업을 제어합니다. **options.ifIdle.streamOptions** (`AgentExecutionOptions`): 즉시 알림이 유휴 스레드를 깨울 때 시작되는 스트림의 옵션입니다. `{ record: NotificationRecord, decision: NotificationDeliveryDecision, runId?: string, signal?: CreatedAgentSignal, persisted?: Promise, accepted?: Promise }`를 반환합니다. `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 루프를 깨우지 않고 구독자에게 전달됩니다. 전체 흐름은 [신호](https://mastra.zisheng.pro/ko/docs/long-running-agents/signals)를 참조하세요. 일부 알림이 다른 디스패치 기간이나 요약 롤업까지 기다려야 한다면 Agent의 `notifications.deliveryPolicy`를 구성하세요. ```typescript 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)` Memory 스레드의 원시 스트림 청크를 구독합니다. `sendMessage()`, `queueMessage()` 또는 `sendSignal()`을 호출하기 전에 사용하세요. 스트림 출력을 렌더링하고 신호 에코를 관찰할 수 있으며, 신호가 활성 실행을 중단하는 경우도 포함됩니다. **options** (`object`): 스레드 구독 대상입니다. **options.resourceId** (`string`): Memory 스레드의 리소스 ID입니다. **options.threadId** (`string`): 구독할 스레드 ID입니다. 다음 멤버가 포함된 `AgentThreadSubscription` 객체를 반환합니다. **stream** (`AsyncIterable`): 구독한 스레드의 원시 Agent 스트림 청크입니다. **activeRunId** (`() => string | null`): 스레드의 활성 실행 ID를 반환하며, 활성 실행이 없으면 null을 반환합니다. **abort** (`() => boolean`): 스레드의 활성 실행을 중단합니다. 실행이 중단되면 true를 반환합니다. **unsubscribe** (`() => void`): 활성 실행을 중단하지 않고 구독을 중지합니다. ## 생성자 매개변수 **id** (`string`): Agent의 고유 식별자입니다. **name** (`string`): Agent의 표시 이름입니다. **description** (`string`): Agent의 목적과 기능에 대한 선택적 설명입니다. **metadata** (`Record | ({ requestContext: RequestContext }) => Record | Promise>`): 클라이언트에서 Agent를 분류하거나 필터링하기 위한 선택적 메타데이터입니다. 정적 레코드 또는 요청 컨텍스트에서 메타데이터를 확인하는 함수일 수 있습니다. **instructions** (`SystemMessage | ({ requestContext: RequestContext }) => SystemMessage | Promise`): Agent의 동작을 안내하는 지침입니다. 문자열, 문자열 배열, 시스템 메시지 객체, 시스템 메시지 배열 또는 이러한 형식 중 하나를 동적으로 반환하는 함수일 수 있습니다. SystemMessage 형식: string | string\[] | CoreSystemMessage | CoreSystemMessage\[] | SystemModelMessage | SystemModelMessage\[] **model** (`MastraLanguageModel | ({ requestContext: RequestContext }) => MastraLanguageModel | Promise`): Agent가 사용하는 언어 Model입니다. provider/model 형식의 Model 라우터 문자열, Model 구성 또는 Provider 인스턴스, 혹은 런타임에 Model을 확인하는 함수를 전달하세요. 일반적인 Provider 및 환경 변수는 Model 문자열을 참조하세요. **agents** (`Record | ({ requestContext: RequestContext }) => Record | Promise>`): Agent가 액세스할 수 있는 하위 Agent입니다. 정적으로 제공하거나 동적으로 확인할 수 있습니다. **tools** (`ToolsInput | ({ requestContext: RequestContext, mastra?: Mastra }) => ToolsInput | Promise`): Agent가 액세스할 수 있는 Tool입니다. 정적으로 제공하거나 요청 컨텍스트 및 사용 가능한 경우 연결된 Mastra 인스턴스에서 동적으로 확인할 수 있습니다. **hooks** (`ToolHooks`): 이 Agent가 수행하는 모든 Tool 호출의 전후에 실행되는 훅입니다. generate() 또는 stream()에 전달된 실행별 훅은 여기에 설정된 일치하는 훅을 재정의합니다. 아래의 Tool 훅을 참조하세요. **hooks.beforeToolCall** (`(context: ToolHookContext) => void | ToolBeforeHookResult | Promise`): Tool이 실행되기 전에 실행됩니다. { toolName, input, context, metadata }를 받습니다. Tool 호출을 건너뛰고 output을 결과로 사용하려면 { proceed: false, output }을 반환하세요. **hooks.afterToolCall** (`(context: ToolAfterHookContext) => void | Promise`): Tool이 실행된 후에 실행됩니다. { toolName, input, context, metadata, output, error }를 받습니다. Tool에서 예외가 발생하면 output은 undefined이고 대신 error가 설정됩니다. **transform** (`ToolPayloadTransformPolicy`): 표시 스트림이나 사용자에게 표시되는 기록 메시지가 Tool 페이로드를 받기 전에 이를 변환하는 공유 정책입니다. Tool별 규칙에는 createTool()의 Tool별 transform을 사용하세요. **workflows** (`Record | ({ requestContext: RequestContext }) => Record | Promise>`): Agent가 실행할 수 있는 Workflow입니다. 정적이거나 동적으로 확인할 수 있습니다. **defaultOptions** (`AgentExecutionOptions | ({ requestContext: RequestContext }) => AgentExecutionOptions | Promise`): stream() 및 generate() 호출 시 사용하는 기본 옵션입니다. **defaultGenerateOptionsLegacy** (`AgentGenerateOptions | ({ requestContext: RequestContext }) => AgentGenerateOptions | Promise`): generateLegacy() 호출 시 사용하는 기본 옵션입니다. **defaultStreamOptionsLegacy** (`AgentStreamOptions | ({ requestContext: RequestContext }) => AgentStreamOptions | Promise`): streamLegacy() 호출 시 사용하는 기본 옵션입니다. **mastra** (`Mastra`): Mastra 런타임 인스턴스에 대한 참조입니다(자동으로 주입됨). **scorers** (`MastraScorers | ({ requestContext: RequestContext }) => MastraScorers | Promise`): 런타임 평가 및 텔레메트리를 위한 채점 구성입니다. 정적으로 또는 동적으로 제공할 수 있습니다. **memory** (`MastraMemory | ({ requestContext: RequestContext }) => MastraMemory | Promise`): 상태 유지 컨텍스트를 저장하고 검색하는 데 사용하는 Memory 모듈입니다. **notifications** (`object`): 지속성 알림 신호의 알림 전달 구성입니다. **notifications.deliveryPolicy** (`NotificationDeliveryPolicyConfig`): 알림 레코드가 전달되는 방식을 제어합니다. 기본 결정, 우선순위별 결정, 소스별 결정 또는 사용자 지정 decide() 함수를 구성하세요. **voice** (`CompositeVoice`): 음성 입력 및 출력 설정입니다. **inputProcessors** (`(Processor | ProcessorWorkflow)[] | ({ requestContext: RequestContext }) => (Processor | ProcessorWorkflow)[] | Promise<(Processor | ProcessorWorkflow)[]>`): Agent가 메시지를 처리하기 전에 메시지를 수정하거나 검증할 수 있는 입력 프로세서입니다. 개별 Processor 객체 또는 ProcessorStepSchema를 사용하여 createWorkflow()로 생성한 Workflow일 수 있습니다. **outputProcessors** (`(Processor | ProcessorWorkflow)[] | ({ requestContext: RequestContext }) => (Processor | ProcessorWorkflow)[] | Promise<(Processor | ProcessorWorkflow)[]>`): Agent의 메시지가 클라이언트로 전송되기 전에 이를 수정하거나 검증할 수 있는 출력 프로세서입니다. 개별 Processor 객체 또는 Workflow일 수 있습니다. **maxProcessorRetries** (`number`): 프로세서가 LLM 단계의 재시도를 요청할 수 있는 최대 횟수입니다. **requestContextSchema** (`StandardJSONSchemaV1`): 요청 컨텍스트 값을 검증하는 표준 JSON Schema입니다. 제공하면 generate() 또는 stream() 시작 시 컨텍스트를 검증하며, 검증에 실패하면 MastraError가 발생합니다. **editor** (`false | { instructions?: boolean; tools?: boolean | { description?: boolean } }`): 이 코드 정의 Agent에서 편집기가 재정의할 수 있는 필드를 제어합니다. 지침 및 Tool 편집을 허용하려면 생략하세요. 아래의 편집기 재정의를 참조하세요. ## `generate()`Memory 옵션 `agent.generate()`를 호출할 때 `memory`를 전달하여 실행이 읽고 쓸 대화 스레드를 선택하세요. 일반적인 형식은 `memory: { resource: string, thread: string }`이며, 여기서 `resource`는 소유자를 식별하고 `thread`는 대화를 식별합니다. 개념 모델은 [스레드와 리소스](https://mastra.zisheng.pro/ko/docs/memory/message-history)를 참조하세요. ```typescript const response = await agent.generate('What did we decide about retries?', { memory: { resource: 'user-123', thread: 'support-thread-456', }, }) ``` 호출 중에 스레드 메타데이터를 생성하거나 업데이트해야 하는 경우 스레드 개체를 사용합니다. ```typescript 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 후크 `hooks`를 사용하여 할당된 Tool, Memory Tool, Tool 세트, 클라이언트 Tool, Workspace Tool을 포함해 Agent가 수행하는 모든 Tool 호출 전후에 로직을 실행하세요. ```typescript 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 결과로 사용합니다. ```typescript 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](https://mastra.zisheng.pro/ko/reference/workspace/workspace-class)에도 `tools.hooks`가 정의되어 있으면 Workspace 훅은 Agent 훅 래퍼 내부에서 실행됩니다. ## 편집기 재정의 [`MastraEditor`](https://mastra.zisheng.pro/ko/reference/editor/mastra-editor)를 등록할 때 `editor` 필드는 코드로 정의된 Agent에서 편집기를 통해 변경할 수 있는 부분을 제어합니다. 코드가 소유한 필드는 Studio에서 읽기 전용이며 저장된 재정의에서 제거됩니다. **editor** (`false | { instructions?: boolean; tools?: boolean | { description?: boolean } }`): 지침 및 Tool 편집을 허용하려면 생략하세요. Agent를 잠그려면 false로 설정하세요. 지침 편집을 허용하려면 instructions: true로 설정하세요. Tool 구성원 및 설명 편집을 허용하려면 tools: true로 설정하고, 설명 편집만 허용하려면 tools: { description: true }로 설정하세요. Agent의 `id`, `name`, `model`은 항상 코드에서 가져오며 Editor를 통해 재정의할 수 없습니다. 사용법은 [Editor](https://mastra.zisheng.pro/ko/docs/editor/overview)를 참조하세요. ## 보고 **agent** (`Agent`): 지정된 구성으로 생성된 새 Agent 인스턴스입니다.