Output Validation
Output Validation 是在将 LLM 输出返回给用户前进行校验的机制,确保输出格式正确、内容安全、不包含敏感信息。
#type / concept
#status / evergreen
#tech / ai
#tech / security
[!info] related notes
- 所属 MOC: AI Agent Application MOC, Security MOC
- 相关: Content Safety, Structured Output
Output Validation
一句话定义
Output Validation 是在将 LLM 输出返回给用户前进行校验的机制。LLM 可能输出格式错误、包含敏感信息或有害内容,需要在返回前检查。
核心原理
校验维度
| 维度 | 检查内容 | 处理方式 |
|---|---|---|
| 格式 | 是否符合预期格式 | 重新生成 |
| 安全 | 是否包含有害内容 | 拒绝返回 |
| PII | 是否泄露敏感信息 | 脱敏后返回 |
| 长度 | 是否超出限制 | 截断 |
Python 实现
class OutputValidator:
async def validate(self, output: str, context: dict) -> tuple[bool, str]:
# 1. 内容安全检查
safety = await content_safety.check(output)
if not safety["safe"]:
return False, "输出包含有害内容"
# 2. PII 检查
redacted, pii_found = pii_redactor.redact(output)
if pii_found:
return True, redacted # 脱敏后返回
# 3. 格式检查
if context.get("expected_format") == "json":
try:
json.loads(output)
except json.JSONDecodeError:
return False, "输出不是有效 JSON"
return True, output
常见坑
- 不做输出校验: 有害内容直接返回给用户
- 校验太严: 正常内容被拒绝
- 不处理校验失败: 校验失败后没有降级方案