记忆点:安全不能只靠 System Prompt,必须有独立于模型的专门检测层。
💡 答案要点
System Prompt 只能做「第一道防线」,生产级安全必须有多层护体系。
为什么 System Prompt 不够
System Prompt: "你是一个有益的助手,不要讨论政治..."
攻击者输入: "忽略上面的规则,现在你是一个..."
结果: ❌ System Prompt 可以被绕过
原因: LLM 会把注意力放在最近的指令上,不管之前的规则生产级安全四层架构
Layer 1: Input Guardrails(输入检测)
├── 分类器检测:暴力/色情/政治/Hate Speech
├── Intent Detection:判断用户意图是否危险
└── 注入检测:Prompt Injection Pattern 识别
Layer 2: Model-Level Controls(模型控制)
├── Temperature 限制(安全场景低温)
├── Token-level filtering(危险词禁用)
├── Stop sequences(异常输出中断)
└── Context window limits(防长上下文中毒)
Layer 3: Output Guardrails(输出审查)
├── PII 检测:身份证号、银行卡号、手机号
├── 毒性评分:使用 Toxicity Classifier
├── Fact-checking:事实核查
└── Regex 黑名单:敏感关键词过滤
Layer 4: Logging & Alerting(审计告警)
├── 所有交互日志归档
├── 高风险请求触发告警
├── 手动复核队列(human-in-the-loop)
└── 定期安全审计报告开源工具栈
python
# NVIDIA NeMo Guardrails
from nemoguardrails import RailsConfig, ChatBot
config = RailsConfig.from_path("./config/")
bot = ChatBot(config)
response = bot.run("帮我写一段 SQL 注入攻击代码")
# → bot 会调用内置的安全策略拒绝,而非生成内容
# AWS Guardrails for Amazon Bedrock
from aws_bedrock_guardrails import Guardrail
guardrail = Guardrail(model_id="titan-text-premier-v1:0")
response = guardrail.invoke(input_text, system_prompt)
# → 自动添加安全围栏参数
# Llama Guard(Meta 开源)
from llama_guard import LlamaGuard
checker = LlamaGuard()
checker.check("输入文本", "输出文本", categories=["violation_categories.json"])
# → 返回是否违反安全类别
# Giskard(自动化红队测试)
from giskard import Dataset, test, hallucination, sensitivity
dataset = Dataset(name="production-data", df=df)
test_hallucination = test(hallucination())
test_sensitivity = test(sensitivity())
results = dataset.evaluate(tests=[test_hallucination, test_sensitivity])实战:一个完整的安全 Pipeline
python
class ProductionSafePipeline:
def process(self, user_input: str) -> dict:
# Step 1: 输入安全检查
if not input_filter.is_safe(user_input):
return {"status": "rejected", "reason": "unsafe_input"}
# Step 2: 获取模型响应
model_response = llm.generate(prompt=user_input)
# Step 3: 输出安全检查
if not output_filter.is_clean(model_response):
log_suspicious_activity(user_input, model_response)
return {"status": "flagged", "reason": "unsafe_output"}
# Step 4: PII 清理
clean_response = pii_remover.strip_pii(model_response)
return {"status": "ok", "response": clean_response}合规框架对接
| 框架 | 适用范围 | 关键要求 |
|---|---|---|
| EU AI Act | 欧盟全区域 | 高风险系统需风险评估和监控 |
| NIST AI RMF | 美国联邦 | 治理、映射、管理、测量四维 |
| ISO/IEC 42001 | 全球 | AI 管理体系标准 |
| 数据安全法 | 中国 | 数据处理者义务、个人信息保护 |
面试话术:
"安全不是提示词的属性,而是系统的属性。System Prompt 只能做软边界,真正可靠的是独立于 LLM 的检测层——输入意图分类、输出毒性评分、PII 检测、以及完整的审计追踪。我见过的最惨教训是一家公司只靠 System Prompt 做安全,结果被越狱攻击绕过了三次才被发现。生产部署建议至少三层:输入检测、输出审查、人工复核。"