SystemPromptScrubber
SystemPromptScrubber 是一個輸出處理器,可偵測並處理系統提示、指示,以及其他可能洩露資料並引入安全漏洞的資訊。此處理器會識別各類系統提示,並提供靈活的處理策略(包括多種遮蓋方式),以確保敏感資料得到妥善清理,從而協助維持安全性。
使用範例使用範例 的直接連結
import { SystemPromptScrubber } from '@mastra/core/processors'
const processor = new SystemPromptScrubber({
model: 'openrouter/openai/gpt-oss-safeguard-20b',
strategy: 'redact',
redactionMethod: 'mask',
includeDetections: true,
lastMessageOnly: true,
})
建構函式參數建構函式參數 的直接連結
options:
Options
系統提示偵測及處理的設定選項
Options
model:
MastraModelConfig
偵測 Agent 的模型設定
strategy?:
'block' | 'warn' | 'filter' | 'redact'
偵測到系統提示時採用的策略:'block' 會拒絕並傳回錯誤;'warn' 會記錄警告但允許通過;'filter' 會移除被標記的訊息;'redact' 會以遮蓋後的版本取代原文
customPatterns?:
string[]
用於偵測系統提示的自訂模式(正規表示式字串)
includeDetections?:
boolean
是否在警告中包含偵測詳情。適合用於除錯及監察
lastMessageOnly?:
boolean
是否只檢查批次中最新的輸出訊息,而非檢查每一則訊息。可用此選項將基於 LLM 的清理限制於最新回應。
instructions?:
string
偵測 Agent 的自訂指示。如未提供,則使用預設指示
redactionMethod?:
'mask' | 'placeholder' | 'remove'
系統提示的遮蓋方式:'mask' 以星號取代;'placeholder' 以預留位置文字取代;'remove' 則完全移除
placeholderText?:
string
當 redactionMethod 為 'placeholder' 時使用的自訂預留位置文字
傳回值傳回值 的直接連結
id:
string
設為 'system-prompt-scrubber' 的處理器識別碼
name?:
string
可選的處理器顯示名稱
processOutputStream:
(args: { part: ChunkType; streamParts: ChunkType[]; state: Record<string, any>; abort: (reason?: string) => never; tracingContext?: TracingContext }) => Promise<ChunkType | null>
處理串流輸出部分,以在串流期間偵測及處理系統提示
processOutputResult:
(args: { messages: MastraDBMessage[]; abort: (reason?: string) => never }) => Promise<MastraDBMessage[]>
處理最終輸出結果,以在非串流情況下偵測及處理系統提示
延伸使用範例延伸使用範例 的直接連結
將 SystemPromptScrubber 用作輸出處理器時,建議配合 BatchPartsProcessor 使用以改善效能。BatchPartsProcessor 會先把串流資料塊組成批次,再傳送至清理器,從而減少偵測所需的 LLM 呼叫次數。
src/mastra/agents/scrubbed-agent.ts
import { Agent } from '@mastra/core/agent'
import { BatchPartsProcessor, SystemPromptScrubber } from '@mastra/core/processors'
export const agent = new Agent({
id: 'scrubbed-agent',
name: 'scrubbed-agent',
instructions: 'You are a helpful assistant',
model: 'openai/gpt-5.6-sol',
outputProcessors: [
// Batch stream parts first to reduce LLM calls
new BatchPartsProcessor({
batchSize: 10,
}),
// Then apply system prompt detection on batched content
new SystemPromptScrubber({
model: 'openrouter/openai/gpt-oss-safeguard-20b',
strategy: 'redact',
customPatterns: ['system prompt', 'internal instructions'],
includeDetections: true,
redactionMethod: 'placeholder',
placeholderText: '[REDACTED]',
}),
],
})