> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Guardrail Mastra 提供內建處理器,可為 Agent 加入安全控管。這些處理器會在有害內容送達語言模型或使用者之前,偵測、轉換或封鎖內容。 如需處理器行為、自訂處理器及如何將處理器加入 Agent 的介紹,請參閱[處理器](https://mastra.zisheng.pro/zh-TW/docs/agents/processors)。 ## 輸入處理器 輸入處理器會在使用者訊息送達語言模型前執行,負責正規化、驗證、prompt 注入偵測與安全檢查。 ### 正規化使用者訊息 `UnicodeNormalizer()` 會統一 Unicode 字元並標準化空白,以清理及正規化使用者輸入;也會移除有問題的符號。 ```typescript 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()`](https://mastra.zisheng.pro/zh-TW/reference/processors/unicode-normalizer) 參考文件,以取得完整的設定選項清單。 ### 防止 prompt 注入 `PromptInjectionDetector()` 會掃描使用者訊息中的 prompt 注入、越獄嘗試與 system 覆寫模式。它使用 LLM 分類有風險的輸入,並可在輸入送達模型前加以封鎖或改寫。 ```typescript 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()`](https://mastra.zisheng.pro/zh-TW/reference/processors/prompt-injection-detector) 參考文件,以取得完整的設定選項清單。 ### 偵測並翻譯語言 `LanguageDetector()` 會偵測使用者訊息並翻譯成目標語言,以支援多語言。它使用 LLM 識別語言並執行翻譯。 ```typescript 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()`](https://mastra.zisheng.pro/zh-TW/reference/processors/language-detector) 參考文件,以取得完整的設定選項清單。 ## 輸出處理器 輸出處理器會在語言模型產生回應後、回應送達使用者前執行,負責回應最佳化、審核、轉換與安全控管。 ### 批次處理串流輸出 `BatchPartsProcessor()` 會先合併多個串流片段,再傳送至用戶端。它將小區塊整合成較大的批次,以降低網路負擔。 ```typescript 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()`](https://mastra.zisheng.pro/zh-TW/reference/processors/batch-parts-processor) 參考文件,以取得完整的設定選項清單。 ### 清除 system prompt `SystemPromptScrubber()` 會偵測並遮蔽模型回應中的 system prompt 或內部指示,避免意外洩露 prompt 內容或設定細節。它使用 LLM,依設定的偵測類型識別並遮蔽敏感內容。 ```typescript 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()`](https://mastra.zisheng.pro/zh-TW/reference/processors/system-prompt-scrubber) 參考文件,以取得完整的設定選項清單。 > **備註:** 透過 HTTP 串流傳輸回應時,Mastra 預設會在伺服器層級,從串流區塊中遮蔽敏感的要求資料(system prompt、Tool 定義、API 金鑰)。詳情請參閱[串流資料遮蔽](https://mastra.zisheng.pro/zh-TW/docs/server/mastra-server)。 ## 混合處理器 混合處理器可針對輸入或輸出執行。請將它們放在 `inputProcessors`、`outputProcessors`,或同時放在兩者中。 ### 審核輸入與輸出 `ModerationProcessor()` 會偵測仇恨、騷擾與暴力等類別的不當或有害內容。它使用 LLM 對訊息分類,並可依設定封鎖或改寫訊息。 ```typescript 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()`](https://mastra.zisheng.pro/zh-TW/reference/processors/moderation-processor) 參考文件,以取得完整的設定選項清單。 ### 偵測並遮蔽 PII `PIIDetector()` 會偵測並移除電子郵件、電話號碼與信用卡等個人識別資訊。它使用 LLM,依設定的偵測類型識別敏感內容。 ```typescript 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()`](https://mastra.zisheng.pro/zh-TW/reference/processors/pii-detector) 參考文件,以取得完整的設定選項清單。 ### 強制執行成本限制 `CostGuardProcessor()` 會監控 Agent 迴圈的累計預估成本,在超過金額限制時封鎖或發出警告。它會在每次 LLM 呼叫前,從可觀測性儲存空間查詢成本資料。成本檢查為近似值,且指標會非同步保存,因此快速執行的 Agent 可能在 Guardrail 觸發前短暫超過設定限制。 ```typescript 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()`](https://mastra.zisheng.pro/zh-TW/reference/processors/cost-guard-processor) 參考文件,以瞭解範圍模式、時間範圍、指標保存延遲與 `onViolation` callback。此功能需要支援 `getMetricAggregate` 的可觀測性儲存空間。 ## 處理器策略 許多內建處理器支援 `strategy` 參數,用來控制如何處理遭標記的內容。支援的值包括:`block`、`warn`、`detect`、`redact`、`rewrite` 與 `translate`。 大多數策略都會允許要求繼續。使用 `block` 時,處理器會呼叫 `abort()`,立即停止要求並阻止後續處理器執行。 ```typescript inputProcessors: [ new PIIDetector({ model: 'openrouter/openai/gpt-oss-safeguard-20b', threshold: 0.6, strategy: 'block', detectionTypes: ['email', 'phone', 'credit-card'], }), ] ``` ## 違規 callback 所有處理器都支援 `onViolation` callback;無論採用何種策略,偵測到違反政策時都會觸發。可用於警示、記錄至外部系統或傳送通知等副作用。 callback 會收到包含 `processorId`、`message` 與 `detail`(處理器專屬 metadata)的 `ProcessorViolation` 物件。 ```typescript 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` 介面](https://mastra.zisheng.pro/zh-TW/reference/processors/processor-interface)的一部分,因此任何處理器(包括自訂處理器)都能使用。任何處理器呼叫 `abort()` 時,runner 會自動叫用 `onViolation`。對使用 `warn` 策略的處理器(例如 `CostGuardProcessor`),警告也會觸發 callback,但不會封鎖要求。 callback 擲出的錯誤會被靜默捕捉,以免干擾處理器的主要邏輯。 如需違規 callback 與處理器管線整合方式的詳細資訊,請參閱處理器文件中的[違規 callback](https://mastra.zisheng.pro/zh-TW/docs/agents/processors)。 ## 處理遭封鎖的要求 處理器呼叫 `abort()` 時,Agent 會停止處理。偵測方式取決於你使用 `generate()` 或 `stream()`。 ### 搭配 `generate()` 檢查結果中的 `tripwire` 欄位: ```typescript 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()` 監聽串流中的 `tripwire` 區塊: ```typescript 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 使用 LLM 的 Guardrail 處理器(內容審核、PII 偵測、prompt 注入)會增加每項要求的延遲。下列技巧可降低這項負擔。 ### 平行執行 Guardrail 處理器預設會依序執行。只執行 `block`(且絕不變更訊息)的 Guardrail 彼此獨立,可使用 [Workflow 處理器](https://mastra.zisheng.pro/zh-TW/docs/agents/processors)執行。 你也可以在單一平行步驟中混用 `block` 與 `redact` 策略。請對應至 `redact` 分支,讓它轉換後的訊息繼續傳遞。 對輸出 Guardrail,請在平行步驟\_之前\_依序執行 `TokenLimiterProcessor` 與 `BatchPartsProcessor`,並在其\_之後\_依序執行彼此相依的 `redact` 處理器: ```typescript 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 作為處理器](https://mastra.zisheng.pro/zh-TW/docs/agents/processors)。 ### 選擇快速模型 Guardrail 處理器不需要使用主要模型。請以輕量、快速的模型執行分類任務: ```typescript 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 分類呼叫次數: ```typescript 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' }), ] ``` ## 相關內容 - [處理器](https://mastra.zisheng.pro/zh-TW/docs/agents/processors):處理器行為與執行順序,也涵蓋自訂處理器與重試行為 - [`Processor` 介面](https://mastra.zisheng.pro/zh-TW/reference/processors/processor-interface):`Processor` 介面的 API 參考文件 - [記憶體處理器](https://mastra.zisheng.pro/zh-TW/docs/memory/memory-processors):用於訊息記錄、語意回想與工作記憶的處理器 - 📹 [Mastra 處理器與 Guardrail 工作坊](https://www.youtube.com/watch?v=4Vpp7xQYvl0)