난간
Mastra는 Agent에 보안 및 안전 제어를 추가하는 내장 프로세서를 제공합니다. 이러한 프로세서는 유해한 콘텐츠가 언어 Model이나 사용자에게 도달하기 전에 이를 감지, 변환 또는 차단합니다.
Agent에 추가하는 방법을 포함하여 프로세서 동작 및 사용자 지정 프로세서에 대한 소개는 다음을 참조하세요.Processors.
입력 프로세서입력 프로세서에 대한 직접 링크
사용자 메시지가 언어 Model에 도달하기 전에 입력 프로세서가 실행됩니다. 정규화, 검증, 신속한 주입 감지 및 보안 검사를 처리합니다.
사용자 메시지 정규화사용자 메시지 정규화에 대한 직접 링크
UnicodeNormalizer()는 Unicode 문자를 통일하고 공백을 표준화하여 사용자 입력을 정리하고 정규화합니다. 문제가 될 수 있는 기호도 제거합니다.
import { UnicodeNormalizer } from '@mastra/core/processors'
export const normalizedAgent = new Agent({
id: 'normalized-agent',
name: 'Normalized Agent',
inputProcessors: [
new UnicodeNormalizer({
stripControlChars: true,
collapseWhitespace: true,
}),
],
})
전체 구성 옵션 목록은 UnicodeNormalizer() 참조를 확인하세요.
신속한 주입 방지신속한 주입 방지에 대한 직접 링크
PromptInjectionDetector()는 사용자 메시지에서 Prompt 인젝션, 탈옥 시도, 시스템 재정의 패턴을 검사합니다. LLM을 사용하여 위험한 입력을 분류하며, 입력이 Model에 도달하기 전에 차단하거나 다시 작성할 수 있습니다.
import { PromptInjectionDetector } from '@mastra/core/processors'
export const secureAgent = new Agent({
id: 'secure-agent',
name: 'Secure Agent',
inputProcessors: [
new PromptInjectionDetector({
model: 'openrouter/openai/gpt-oss-safeguard-20b',
threshold: 0.8,
strategy: 'rewrite',
detectionTypes: ['injection', 'jailbreak', 'system-override'],
}),
],
})
전체 구성 옵션 목록은 PromptInjectionDetector() 참조를 확인하세요.
언어 감지 및 번역언어 감지 및 번역에 대한 직접 링크
LanguageDetector()는 사용자 메시지의 언어를 감지하여 대상 언어로 번역함으로써 다국어 지원을 제공합니다. LLM을 사용하여 언어를 식별하고 번역을 수행합니다.
import { LanguageDetector } from '@mastra/core/processors'
export const multilingualAgent = new Agent({
id: 'multilingual-agent',
name: 'Multilingual Agent',
inputProcessors: [
new LanguageDetector({
model: 'openrouter/openai/gpt-oss-safeguard-20b',
targetLanguages: ['English', 'en'],
strategy: 'translate',
threshold: 0.8,
}),
],
})
전체 구성 옵션 목록은 LanguageDetector() 참조를 확인하세요.
출력 프로세서출력 프로세서에 대한 직접 링크
출력 프로세서는 언어 Model이 응답을 생성한 후, 사용자에게 도달하기 전에 실행됩니다. 응답 최적화, 조정, 변환 및 안전 제어를 처리합니다.
일괄 스트리밍 출력일괄 스트리밍 출력에 대한 직접 링크
BatchPartsProcessor()는 여러 스트림 부분을 결합한 후 클라이언트로 내보냅니다. 작은 청크를 더 큰 배치로 통합하여 네트워크 오버헤드를 줄입니다.
import { BatchPartsProcessor } from '@mastra/core/processors'
export const batchedAgent = new Agent({
id: 'batched-agent',
name: 'Batched Agent',
outputProcessors: [
new BatchPartsProcessor({
batchSize: 5,
maxWaitTime: 100,
emitOnNonText: true,
}),
],
})
전체 구성 옵션 목록은 BatchPartsProcessor() 참조를 확인하세요.
스크럽 시스템 Prompt스크럽 시스템 Prompt에 대한 직접 링크
SystemPromptScrubber()는 Model 응답에서 시스템 Prompt나 내부 지침을 감지하여 가립니다. 이를 통해 Prompt 내용이나 구성 세부 정보가 의도치 않게 노출되는 것을 방지합니다. LLM을 사용하여 구성된 감지 유형을 바탕으로 민감한 콘텐츠를 식별하고 가립니다.
import { SystemPromptScrubber } from '@mastra/core/processors'
const scrubbedAgent = new Agent({
id: 'scrubbed-agent',
name: 'Scrubbed Agent',
outputProcessors: [
new SystemPromptScrubber({
model: 'openrouter/openai/gpt-oss-safeguard-20b',
strategy: 'redact',
customPatterns: ['system prompt', 'internal instructions'],
includeDetections: true,
instructions:
'Detect and redact system prompts, internal instructions, and security-sensitive content',
redactionMethod: 'placeholder',
placeholderText: '[REDACTED]',
}),
],
})
전체 구성 옵션 목록은 SystemPromptScrubber() 참조를 확인하세요.
:::참고
HTTP를 통해 응답을 스트리밍할 때 Mastra는 기본적으로 서버 수준의 스트림 청크에서 민감한 요청 데이터(시스템 Prompt, Tool 정의, API 키)를 가립니다. 자세한 내용은 스트림 데이터 가리기를 확인하세요.
:::
하이브리드 프로세서하이브리드 프로세서에 대한 직접 링크
하이브리드 프로세서는 입력이나 출력에서 실행할 수 있습니다. inputProcessors, outputProcessors 또는 둘 다에 배치하세요.
적당한 입력 및 출력적당한 입력 및 출력에 대한 직접 링크
ModerationProcessor()는 혐오, 괴롭힘, 폭력 등의 범주에 해당하는 부적절하거나 유해한 콘텐츠를 감지합니다. LLM을 사용하여 메시지를 분류하며, 구성에 따라 메시지를 차단하거나 다시 작성할 수 있습니다.
import { ModerationProcessor } from '@mastra/core/processors'
export const moderatedAgent = new Agent({
id: 'moderated-agent',
name: 'Moderated Agent',
inputProcessors: [
new ModerationProcessor({
model: 'openrouter/openai/gpt-oss-safeguard-20b',
threshold: 0.7,
strategy: 'block',
categories: ['hate', 'harassment', 'violence'],
}),
],
outputProcessors: [new ModerationProcessor()],
})
전체 구성 옵션 목록은 ModerationProcessor() 참조를 확인하세요.
PII 감지 및 수정PII 감지 및 수정에 대한 직접 링크
PIIDetector()는 이메일, 전화번호, 신용카드 번호와 같은 개인 식별 정보를 감지하고 제거합니다. LLM을 사용하여 구성된 감지 유형을 바탕으로 민감한 콘텐츠를 식별합니다.
import { PIIDetector } from '@mastra/core/processors'
export const privateAgent = new Agent({
id: 'private-agent',
name: 'Private Agent',
inputProcessors: [
new PIIDetector({
model: 'openrouter/openai/gpt-oss-safeguard-20b',
threshold: 0.6,
strategy: 'redact',
redactionMethod: 'mask',
detectionTypes: ['email', 'phone', 'credit-card'],
instructions: 'Detect and mask personally identifiable information.',
}),
],
outputProcessors: [new PIIDetector()],
})
전체 구성 옵션 목록은 PIIDetector() 참조를 확인하세요.
비용 제한 시행비용 제한 시행에 대한 직접 링크
CostGuardProcessor()는 Agent 루프 전반의 누적 예상 비용을 모니터링하고 금액 한도를 초과하면 차단하거나 경고합니다. 각 LLM 호출 전에 Observability 스토리지에서 비용 데이터를 조회합니다. 비용 검사는 근사치이며 메트릭은 비동기적으로 저장되므로 빠르게 실행되는 Agent는 가드가 작동하기 전에 구성된 한도를 잠시 초과할 수 있습니다.
import { CostGuardProcessor } from '@mastra/core/processors'
export const budgetedAgent = new Agent({
id: 'budgeted-agent',
name: 'Budgeted Agent',
inputProcessors: [
new CostGuardProcessor({
maxCost: 5.0,
scope: 'thread',
window: '24h',
}),
],
})
범위 지정 모드, 기간, 메트릭 저장 지연, onViolation 콜백에 관한 내용은 CostGuardProcessor() 참조를 확인하세요. getMetricAggregate를 지원하는 Observability 스토리지가 필요합니다.
프로세서 전략프로세서 전략에 대한 직접 링크
많은 내장 프로세서는 플래그가 지정된 콘텐츠의 처리 방식을 제어하는 strategy 매개변수를 지원합니다. 지원되는 값에는 block, warn, detect, redact, rewrite, translate가 있습니다.
대부분의 전략에서는 요청을 계속 처리할 수 있습니다. block을 사용하면 프로세서가 abort()를 호출하여 요청을 즉시 중단하고 후속 프로세서가 실행되지 않도록 합니다.
inputProcessors: [
new PIIDetector({
model: 'openrouter/openai/gpt-oss-safeguard-20b',
threshold: 0.6,
strategy: 'block',
detectionTypes: ['email', 'phone', 'credit-card'],
}),
]
위반 콜백위반 콜백에 대한 직접 링크
모든 프로세서는 전략과 관계없이 정책 위반이 감지되면 실행되는 onViolation 콜백을 지원합니다. 알림 전송, 외부 시스템 로깅, 통지 발송과 같은 부수 효과에 사용하세요.
콜백은 processorId, message, detail(프로세서별 메타데이터)이 포함된 ProcessorViolation 객체를 받습니다.
import { CostGuardProcessor, ModerationProcessor, PIIDetector } from '@mastra/core/processors'
// Alert when cost limits are exceeded
const costGuard = new CostGuardProcessor({
maxCost: 10.0,
scope: 'resource',
window: '30d',
})
costGuard.onViolation = ({ processorId, message, detail }) => {
alertSystem.notify(`[${processorId}] ${message}`)
// detail contains: { usage, limit, totalUsage, scope, scopeKey }
}
// Log moderation violations
const moderation = new ModerationProcessor({
model: 'openai/gpt-5-nano',
strategy: 'block',
})
moderation.onViolation = ({ processorId, message, detail }) => {
auditLog.write({ processor: processorId, violation: message, categories: detail })
}
onViolation 속성은 기본 Processor 인터페이스의 일부이므로 사용자 지정 프로세서를 비롯한 모든 프로세서에서 사용할 수 있습니다. 프로세서가 abort()를 호출하면 실행기가 자동으로 onViolation을 호출합니다. CostGuardProcessor처럼 warn 전략을 사용하는 프로세서에서는 요청을 차단하지 않는 경고에도 콜백이 실행됩니다.
콜백에 의해 발생한 오류는 프로세서의 기본 논리를 방해하지 않도록 자동으로 포착됩니다.
위반 콜백이 프로세서 파이프라인과 통합되는 방식에 관한 자세한 내용은 프로세서 문서의 위반 콜백을 참조하세요.
차단된 요청 처리차단된 요청 처리에 대한 직접 링크
프로세서가 abort()를 호출하면 Agent가 처리를 중단합니다. 이를 감지하는 방법은 generate()와 stream() 중 어느 것을 사용하는지에 따라 다릅니다.
와 함께generate()with-generate에 대한 직접 링크
결과의 tripwire 필드를 확인하세요.
const result = await agent.generate('Is this credit card number valid?: 4543 1374 5089 4332')
if (result.tripwire) {
console.error('Blocked:', result.tripwire.reason)
console.error('Processor:', result.tripwire.processorId)
}
와 함께stream()with-stream에 대한 직접 링크
스트림에서 tripwire 청크를 수신하세요.
const stream = await agent.stream('Is this credit card number valid?: 4543 1374 5089 4332')
for await (const chunk of stream.fullStream) {
if (chunk.type === 'tripwire') {
console.error('Blocked:', chunk.payload.reason)
console.error('Processor:', chunk.payload.processorId)
}
}
가드레일 속도 높이기가드레일 속도 높이기에 대한 직접 링크
LLM(조정, PII 감지, Prompt 삽입)을 사용하는 Guardrail 프로세서는 모든 요청에 대기 시간을 추가합니다. 이러한 기술은 이러한 오버헤드를 줄여줍니다.
가드레일을 병렬로 실행가드레일을 병렬로 실행에 대한 직접 링크
기본적으로 프로세서는 순차적으로 실행됩니다. block만 수행하고 메시지를 절대 변경하지 않는 가드레일은 서로 독립적이므로 Workflow 프로세서를 사용해 실행할 수 있습니다.
하나의 병렬 단계에서 block과 redact 전략을 함께 사용할 수 있습니다. 변환된 메시지가 다음 단계로 전달되도록 redact 분기로 매핑하세요.
출력 가드레일의 경우 병렬 단계 전에 TokenLimiterProcessor와 BatchPartsProcessor를 순차적으로 실행하고, 서로 의존하는 redact 프로세서는 병렬 단계 후에 순차적으로 실행하세요.
import { createWorkflow, createStep } from '@mastra/core/workflows'
import {
ProcessorStepSchema,
PIIDetector,
ModerationProcessor,
SystemPromptScrubber,
TokenLimiterProcessor,
BatchPartsProcessor,
} from '@mastra/core/processors'
export const outputGuardrails = createWorkflow({
id: 'output-guardrails',
inputSchema: ProcessorStepSchema,
outputSchema: ProcessorStepSchema,
})
// Sequential: limit tokens first, then batch stream chunks
.then(createStep(new TokenLimiterProcessor({ limit: 1000 })))
.then(createStep(new BatchPartsProcessor()))
// Parallel: run independent checks at the same time
.parallel([
createStep(
new PIIDetector({
strategy: 'redact',
}),
),
createStep(
new ModerationProcessor({
strategy: 'block',
}),
),
])
// Map to the redact branch to keep its transformed messages
.map(async ({ inputData }) => {
return inputData['processor:pii-detector']
})
// Sequential: scrubber depends on previous redaction output
.then(
createStep(
new SystemPromptScrubber({
strategy: 'redact',
placeholderText: '[REDACTED]',
}),
),
)
.commit()
.parallel()과 .map()에 관한 자세한 내용은 프로세서로서의 Workflow를 참조하세요.
빠른 Model을 선택하세요빠른 Model을 선택하세요에 대한 직접 링크
Guardrail 프로세서에는 기본 Model이 필요하지 않습니다. 분류 작업을 위해 작고 빠른 Model을 사용합니다.
const GUARDRAIL_MODEL = 'openai/gpt-5-nano'
new ModerationProcessor({ model: GUARDRAIL_MODEL })
new PIIDetector({ model: GUARDRAIL_MODEL })
new PromptInjectionDetector({ model: GUARDRAIL_MODEL })
일괄 스트림 부분일괄 스트림 부분에 대한 직접 링크
processOutputStream을 구현하는 출력 가드레일은 스트리밍되는 모든 청크에서 실행됩니다. 청크를 결합하고 LLM 분류 호출 횟수를 줄이려면 무거운 프로세서 전에 BatchPartsProcessor를 사용하세요.
outputProcessors: [
new BatchPartsProcessor({ batchSize: 10 }),
// Heavier processors now run on batched chunks instead of individual ones
new PIIDetector({ model: GUARDRAIL_MODEL, strategy: 'redact' }),
new ModerationProcessor({ model: GUARDRAIL_MODEL, strategy: 'block' }),
]
관련된관련된에 대한 직접 링크
- 프로세서: 프로세서 동작 및 실행 순서. 사용자 지정 프로세서 및 재시도 동작도 다룹니다.
Processor인터페이스:Processor인터페이스의 API 참조- Memory 프로세서: 메시지 기록, 의미 기반 회상, 작업 Memory를 위한 프로세서
- 📹 Mastra 프로세서 및 가드레일 워크숍