跳至主要內容

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[]
用於偵測系統提示詞的自訂模式(regex 字串)

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