---
title: LLM 响应结构化与 Guardrails(JSON 模式、Schema 验证与安全)
date: 2025-11-26
keywords:
- JSON 模式
- Schema 校验
- Guardrails
- PII 过滤
- 合规
description: 将LLM输出结构化为JSON并通过Schema验证与安全过滤,结合PII检测与字段白名单,提供实现与验证方法以增强可靠性与合规。
categories:
- 文章资讯
- 技术教程
---
概述
结构化响应可提升可用性与可编程性。通过Schema验证与安全过滤,防止非预期字段与敏感信息泄露,结合采样与重试策略提升稳定性。
关键实践与参数
- JSON模式: 指定响应为JSON并定义Schema
- 验证器: 使用Ajv校验并记录错误
- 安全过滤: PII检测与字段白名单
- 采样与重试: 超时与格式错误时重试
示例/配置/实现
import Ajv from 'ajv'
const schema = { type: 'object', properties: { title: { type: 'string' }, tags: { type: 'array', items: { type: 'string' } } }, required: ['title', 'tags'] }
const ajv = new Ajv()
const validate = ajv.compile(schema)
function guard(output) { const ok = validate(output); if (!ok) throw new Error('schema_error'); return output }
function containsPII(s) { return /\b\d{3}-\d{3}-\d{4}\b/.test(s) }
验证
- 格式正确: 输出通过Schema校验
- 安全合规: 无PII与未授权字段
- 稳定性: 在错误输出时重试成功率提升
- 记录: 保留校验与过滤日志
注意事项
- Schema需与业务演进保持一致
- 过滤需隐私合规
- 重试策略需防止成本过高
- 与计费与配额协同

发表评论 取消回复