跳至主要內容

防護措施

Mastra 提供內置處理器,為你的 Agent 加入保安及安全控制。這些處理器可在有害內容送達語言模型或使用者之前偵測、轉換或封鎖內容。

如要了解處理器的行為及自訂處理器,包括如何將其加入 Agent,請參閱處理器

輸入處理器
輸入處理器 的直接連結

輸入處理器會在使用者訊息送達語言模型前執行,負責正規化、驗證、偵測提示詞注入及進行保安檢查。

正規化使用者訊息
正規化使用者訊息 的直接連結

UnicodeNormalizer() 會統一 Unicode 字元並將空白標準化,以清理及正規化使用者輸入,亦會移除有問題的符號。

src/mastra/agents/normalized-agent.ts
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() 會掃描使用者訊息,尋找提示詞注入、越獄嘗試及系統覆寫模式。它使用 LLM 對高風險輸入進行分類,並可在輸入送達模型前將其封鎖或重寫。

src/mastra/agents/secure-agent.ts
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 識別語言並進行翻譯。

src/mastra/agents/multilingual-agent.ts
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() 參考文件,了解完整的配置選項清單。

輸出處理器
輸出處理器 的直接連結

輸出處理器會在語言模型產生回應後、回應送達使用者前執行,負責回應最佳化、審核、轉換及安全控制。

批次處理串流輸出
批次處理串流輸出 的直接連結

BatchPartsProcessor() 會先合併多個串流部分,再傳送至客戶端。它把小型資料塊整合成較大的批次,從而減少網絡負擔。

src/mastra/agents/batched-agent.ts
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() 參考文件,了解完整的配置選項清單。

清除系統提示詞
清除系統提示詞 的直接連結

SystemPromptScrubber() 會偵測並遮蔽模型回應中的系統提示詞或內部指令,防止意外洩露提示詞內容或配置詳情。它使用 LLM,按照已配置的偵測類型識別並遮蔽敏感內容。

src/mastra/agents/scrubbed-agent.ts
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 預設會在伺服器層面從串流資料塊中遮蔽敏感的請求資料(系統提示詞、Tool 定義、API 金鑰)。詳情請參閱串流資料遮蔽

混合處理器
混合處理器 的直接連結

混合處理器可針對輸入或輸出執行。請將它們放入 inputProcessorsoutputProcessors,或同時放入兩者。

審核輸入及輸出
審核輸入及輸出 的直接連結

ModerationProcessor() 會偵測仇恨、騷擾及暴力等類別的不當或有害內容。它使用 LLM 對訊息進行分類,並可根據你的配置將其封鎖或重寫。

src/mastra/agents/moderated-agent.ts
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,按照已配置的偵測類型識別敏感內容。

src/mastra/agents/private-agent.ts
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 前,從可觀測性儲存空間查詢成本資料。由於成本檢查是約數,而且指標會以非同步方式保存,因此快速執行的 Agent 可能會在防護措施觸發前短暫超出已配置的上限。

src/mastra/agents/budgeted-agent.ts
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',
}),
],
})

請參閱 CostGuardProcessor() 參考文件,了解作用範圍模式、時間窗口、指標保存延遲及 onViolation 回呼。此處需要可支援 getMetricAggregate 的可觀測性儲存空間。

處理器策略
處理器策略 的直接連結

許多內置處理器都支援 strategy 參數,用來控制它們如何處理被標記的內容。支援的值包括:blockwarndetectredactrewritetranslate

大部分策略都允許請求繼續。使用 block 時,處理器會呼叫 abort(),立即停止請求,並阻止後續處理器執行。

src/mastra/agents/private-agent.ts
inputProcessors: [
new PIIDetector({
model: 'openrouter/openai/gpt-oss-safeguard-20b',
threshold: 0.6,
strategy: 'block',
detectionTypes: ['email', 'phone', 'credit-card'],
}),
]

違規回呼
違規回呼 的直接連結

所有處理器都支援 onViolation 回呼,不論使用哪種策略,只要偵測到違反政策的情況就會觸發。你可以使用它執行警報、記錄至外部系統或傳送通知等副作用操作。

回呼會接收一個 ProcessorViolation 物件,其中包含 processorIdmessagedetail(處理器專用的 metadata)。

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 介面的一部分,因此包括自訂處理器在內的任何處理器都可以使用它。runner 會自動呼叫 onViolation;此操作會在任何處理器呼叫 abort() 時發生。對於使用 warn 策略的處理器(例如 CostGuardProcessor),發出警告時亦會觸發回呼,而不會封鎖請求。

回呼擲出的錯誤會被靜默捕捉,以免干擾處理器的主要邏輯。

如要進一步了解違規回呼如何與處理器管線整合,請參閱處理器文件中的違規回呼

處理被封鎖的請求
處理被封鎖的請求 的直接連結

當處理器呼叫 abort() 時,Agent 會停止處理。偵測方法取決於你使用 generate() 還是 stream()

使用 generate()
with-generate 的直接連結

檢查結果中的 tripwire 欄位:

src/mastra/agents/test-generate.ts
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 資料塊:

src/mastra/agents/test-stream.ts
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 偵測、提示詞注入偵測)會增加每個請求的延遲。以下技巧可減少這些額外負擔。

並行執行防護措施
並行執行防護措施 的直接連結

處理器預設會依序執行。只會 block(且絕不修改訊息)的防護措施彼此獨立,可使用工作流程處理器並行執行。

你亦可在單一並行步驟中混合使用 blockredact 策略。請映射至 redact 分支,讓經過轉換的訊息可繼續傳遞。

對於輸出防護措施,請在並行步驟_之前_依序執行 TokenLimiterProcessorBatchPartsProcessor,並在並行步驟_之後_依序執行任何互相依賴的 redact 處理器:

src/mastra/processors/output-guardrails.ts
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 用作處理器

選擇快速模型
選擇快速模型 的直接連結

防護措施處理器無需使用你的主要模型。請使用小型而快速的模型執行分類工作:

const GUARDRAIL_MODEL = 'openai/gpt-5-nano'

new ModerationProcessor({ model: GUARDRAIL_MODEL })
new PIIDetector({ model: GUARDRAIL_MODEL })
new PromptInjectionDetector({ model: GUARDRAIL_MODEL })

批次處理串流部分
批次處理串流部分 的直接連結

實作 processOutputStream 的輸出防護措施會在每個串流資料塊上執行。請在較繁重的處理器_之前_使用 BatchPartsProcessor 合併資料塊,以減少呼叫 LLM 進行分類的次數:

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' }),
]