跳至主要內容

Guardrail

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

如需處理器行為、自訂處理器及如何將處理器加入 Agent 的介紹,請參閱處理器

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

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

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

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() 參考文件,以取得完整的設定選項清單。

防止 prompt 注入
「防止 prompt 注入」的直接連結

PromptInjectionDetector() 會掃描使用者訊息中的 prompt 注入、越獄嘗試與 system 覆寫模式。它使用 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() 參考文件,以取得完整的設定選項清單。

清除 system prompt
「清除 system prompt」的直接連結

SystemPromptScrubber() 會偵測並遮蔽模型回應中的 system prompt 或內部指示,避免意外洩露 prompt 內容或設定細節。它使用 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 預設會在伺服器層級,從串流區塊中遮蔽敏感的要求資料(system prompt、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 可能在 Guardrail 觸發前短暫超過設定限制。

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 callback。此功能需要支援 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'],
}),
]

違規 callback
「違規 callback」的直接連結

所有處理器都支援 onViolation callback;無論採用何種策略,偵測到違反政策時都會觸發。可用於警示、記錄至外部系統或傳送通知等副作用。

callback 會收到包含 processorIdmessagedetail(處理器專屬 metadata)的 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() 時,runner 會自動叫用 onViolation。對使用 warn 策略的處理器(例如 CostGuardProcessor),警告也會觸發 callback,但不會封鎖要求。

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

如需違規 callback 與處理器管線整合方式的詳細資訊,請參閱處理器文件中的違規 callback

處理遭封鎖的要求
「處理遭封鎖的要求」的直接連結

處理器呼叫 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)
}
}

加速 Guardrail
「加速 Guardrail」的直接連結

使用 LLM 的 Guardrail 處理器(內容審核、PII 偵測、prompt 注入)會增加每項要求的延遲。下列技巧可降低這項負擔。

平行執行 Guardrail
「平行執行 Guardrail」的直接連結

處理器預設會依序執行。只執行 block(且絕不變更訊息)的 Guardrail 彼此獨立,可使用 Workflow 處理器執行。

你也可以在單一平行步驟中混用 blockredact 策略。請對應至 redact 分支,讓它轉換後的訊息繼續傳遞。

對輸出 Guardrail,請在平行步驟_之前_依序執行 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 作為處理器

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

Guardrail 處理器不需要使用主要模型。請以輕量、快速的模型執行分類任務:

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

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

批次處理串流片段
「批次處理串流片段」的直接連結

實作 processOutputStream 的輸出 Guardrail 會針對每個串流區塊執行。請在較耗資源的處理器_之前_使用 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' }),
]