结

结构化输出校验护栏(Schema Guard)

作者:注册老炮@MedXpert I SynomosAIv5

当用户说『模型返回的JSON又崩了』『字段缺失对不上』『下游解析失败』『怎么强制LLM输出合规结构』,或要把 LLM 的 JSON/结构化输出接进代码(API/数据库/表单)时使用。把模型输出当『不可信外部输入』:用 schema 校验必填字段·类型·枚举,缺则给可执行的修复提示而非裸报错。理论根基:LGD 三律(有籍·有证·有门禁)。触发词:结构化输出、JSON校验、schema guard、输出格式、字段缺失、模型输出解析、function calling、tool output。

下载量
271
点赞
68
价格
免费

技能文档

---
name: output-schema-guard
display_name: 结构化输出校验护栏(Schema Guard)
display_name_en: "Output Schema Guard"
description: "当用户说『模型返回的JSON又崩了』『字段缺失对不上』『下游解析失败』『怎么强制LLM输出合规结构』,或要把 LLM 的 JSON/结构化输出接进代码(API/数据库/表单)时使用。把模型输出当『不可信外部输入』:用 schema 校验必填字段·类型·枚举,缺则给可执行的修复提示而非裸报错。理论根基:LGD 三律(有籍·有证·有门禁)。触发词:结构化输出、JSON校验、schema guard、输出格式、字段缺失、模型输出解析、function calling、tool output。"
version: 1.0.1
agent_created: true
author: 诺声(Logos)@SynomosAI
license: MIT
license_scope: 代码(.py 文件)MIT;本 SKILL.md 与其中理论文本不在 MIT 覆盖范围内(见文末「License & attribution」)
allowed-tools: Read, Glob, Grep
category: AI工程方法
platforms: [windows, macos, linux]
platform_compatibility: [windows, macos, linux]
read_when:
  - LLM 返回的 JSON 偶发缺字段或类型不对,导致下游解析崩溃
  - 要把模型输出接进数据库 / API / 表单,必须结构稳定
  - 在用 function calling / tool 定义,但模型回传参数不可信
  - 用户抱怨「这次能跑、下次就挂」的不稳定解析
tags: [结构化输出, schema校验, JSON guard, function calling, 输出格式, agent优化, 可靠性]
slug: output-schema-guard
title: 结构化输出校验护栏(Schema Guard)
copyright: SynomosAI
description_zh: "当用户说『模型返回的JSON又崩了』『字段缺失对不上』『下游解析失败』『怎么强制LLM输出合规结构』,或要把 LLM 的 JSON/结构化输出接进代码(API/数据库/表单)时使用。把模型输出当『不可信外部输入』:用 schema 校验必填字段·类型·枚举,缺则给可执行的修复提示而非裸报错。理论根基:LGD 三律(有籍·有证·有门禁)。触发词:结构化输出、JSON校验、schema guard、输出格式、字段缺失、模型输出解析、function calling、tool output。"
description_en: "Treat LLM output as untrusted input: schema-validate structured JSON before it reaches APIs, databases or forms, with failure diagnosis and repair guidance."
classification:
  skillhub: ["security-compliance"]
  iso_25010: ["Security"]
risk_tier: medium
risk_rationale: "门禁批量补丁默认 medium(内部约定:本 skill 设计为中等风险):调用 API/读写文件/本地执行,最小权限,密钥走 Secret;若实际涉对外代执行(push/发布/发送/上架)须人工复评,改 high 并走负责人批准。"
ai_protocol: true
spec: usk/1.0
interface:
  type: cli
  entry_point: scripts/schema_guard.py
  runtime: python3
  call_pattern: args
input_schema:
  schema:
    type: string
    description: "schema"
    required: true
  text:
    type: string
    description: "text"
    required: false
  file:
    type: string
    description: "file"
    required: false
  json:
    type: bool
    description: "json"
    required: false
output_schema:
  stdout: 结构化 JSON IR(含 result / rc / error_code / warnings)
  exit_code: rc=0 正常 / rc=1 告警或从严推定 / rc=2 输入不足或非法
capabilities:
  - json
  - schema
  - validation
permissions:
  network: false
  filesystem: false
  subprocess: false
requirements:
  python_packages: []
  min_python: "3.8"
changelog: "1.0.1: Bilingual rewrite (full EN+ZH, English first); 1.0.0: initial upload (USK v3)"
---

> 凡自治之物 · LGD 治理学 · 创造术家族 | 评测协议:skill-quality-gate

## English

### When to use
1. When users report that model JSON output keeps breaking — missing fields cause downstream API or database parsing to fail — this skill performs structured repair.
2. When the project must force the LLM to return compliant structures (such as function-calling tool arguments) under specific schema constraints.
3. As a safety barrier for "untrusted external input", validating model output against the registered/evidenced/gated principles before any code logic executes.

### Usage
The core script is `schema_guard.py`, callable either as an imported Python module or directly from the command line. Two key parameters are required: the raw text or JSON string to be validated, and a schema-definition object (required fields, data types and enum-value lists). The skill loads and caches its internal logic in `__pycache__` automatically; no manual compilation is needed.

### Workflow
1. Receive the LLM output and the associated schema validation rules.
2. Run `schema_guard.py` for initialization and data loading.
3. Walk through the input fields, compare required items and type constraints, and check enum compliance.
4. Validate per the LGD Three Laws (registered · evidenced · gated); on error, do not simply raise.
5. Return repair guidance pinpointing the exact location, or the cleaned corrected data.
6. Record the validation status so the system can continuously improve the trustworthiness and format stability of future model output.

### Evidence & safety statement
- Evidence: TBD (no evaluation / badge link yet; update here once produced)
- Version: 1.0.1
- Safety: no independent security scan has been performed (TBD); the conclusion is pending and no endorsement is given until it is completed.

## 中文

### 何时用
1. 当用户反馈模型 JSON 输出格式崩溃、字段缺失导致下游 API 或数据库解析失败时,本技能可执行结构化修复。
2. 在项目需要强制 LLM 返回合规结构(如函数调用工具参数)且必须满足特定 Schema 约束时使用。
3. 作为『不可信外部输入』的安全屏障,在执行代码逻辑前校验模型输出是否符合有籍·有证·有门禁原则。

### 用法
核心脚本为 `schema_guard.py`,支持通过 Python 模块导入方式或直接命令调用。调用时需提供两个关键参数:一是待校验的原始文本或 JSON 字符串,二是 Schema 定义对象(含必填字段、数据类型及枚举值列表)。技能将自动在内部加载并缓存于 `__pycache__` 环境中的逻辑,无需用户手动编译即可运行。

### 流程
1. 接收用户输入的 LLM 输出内容及相关 Schema 校验规则。
2. 调用 `schema_guard.py` 脚本进行初始化配置与数据加载。
3. 遍历输入字段,比对必填项与类型约束,检测枚举值合规性。
4. 依据 LGD 三律(有籍·有证·有门禁)逻辑执行验证,若发现错误则不直接报错。
5. 生成包含具体修改位置的修复提示或清洗后的修正数据返回给用户。
6. 记录校验状态以便系统持续优化后续模型输出的可信度与格式稳定性。

### 证据与安全声明

- 证据:TBD(暂无评测/徽章链接;产生后在此更新实际链接)
- 版本:1.0.1
- 安全:未做独立安全扫描(TBD),结论待补;补全前不作推荐背书。

使用说明

# output-schema-guard · 结构化输出校验护栏 / Output Schema Guard

[![LGD Powered](lgd-powered.png)](https://github.com/zhaoxinghua09-cell/lgd-theory)

## English

Treat model JSON as *untrusted external input*. Validate required fields · types · enums · nesting against a schema before it ever reaches your code; on failure emit an actionable fix hint (`{field, expected, got, hint}`) instead of a raw crash. Ships a zero-dependency `schema_guard.py`.

### Why it beats "just json.loads() and hope"

| Pain | This skill |
|---|---|
| LLM drops a required field → downstream None crash | Required-field gate fails *before* business code |
| Type drifts str↔int | Type check returns expected vs got |
| Enum out of range | Whitelist enum enforcement |
| "Works once, breaks next time" | Deterministic contract, not luck |

### What's inside

- `SKILL.md` — 4-dimension schema check + 2-step flow + schema example + iron rule
- `scripts/schema_guard.py` — zero-dependency CLI: validate JSON/text against a schema JSON, emit per-field pass/fail + fix hint

```bash
python scripts/schema_guard.py --schema schema.json --text '{"name":"x","status":"pending"}'
python scripts/schema_guard.py --schema schema.json --file out.jsonl --json
```

### Benchmark vs alternatives

| Tool | Gap this fills |
|---|---|
| pydantic (python only) | No language-agnostic, no fix-hint for re-prompt |
| JSON Schema libs | Heavy, no LLM retry-gate pattern |
| "try/except json.loads" | Catches nothing semantic |

Theoretical root: **LGD Three Laws** (registered · evidenced · gated). Pairs with `context-engineering` and `skill-quality-gate`.

## 中文

把模型 JSON 当不可信外部输入:进代码前用 schema 卡必填·类型·枚举·嵌套,失败吐可执行修复提示(`{field, expected, got, hint}`)而非裸崩。附零依赖 `schema_guard.py`。

### 为什么比「json.loads 然后听天由命」强

| 痛点 | 本技能 |
|---|---|
| LLM 少给必填字段 → 下游 None 崩溃 | 必填字段门禁在业务代码之前拦截 |
| 类型 str/int 漂移 | 类型检查返回期望 vs 实际 |
| 枚举越界 | 白名单枚举强制 |
| "这次能跑、下次就挂" | 确定性契约,不靠运气 |

### 里面有什么

- `SKILL.md` — 四维 schema 校验 + 两步流程 + schema 示例 + 铁律
- `scripts/schema_guard.py` — 零依赖 CLI:按 schema JSON 校验 JSON/文本,逐字段通过/失败 + 修复提示

```bash
python scripts/schema_guard.py --schema schema.json --text '{"name":"x","status":"pending"}'
python scripts/schema_guard.py --schema schema.json --file out.jsonl --json
```

### 与同类对比

| 工具 | 本技能补的缺口 |
|---|---|
| pydantic(仅 Python) | 语言无关、给重提示修复建议 |
| JSON Schema 库 | 轻量、带 LLM 重试门禁模式 |
| "try/except json.loads" | 抓不住任何语义问题 |

理论根基:**LGD 三律**(有籍 · 有证 · 有门禁)。与 `context-engineering`、`skill-quality-gate` 配套。

---

© 2026 SynomosAI. All rights reserved.

---

## License & attribution
**分层许可(务必并读;代码许可不覆盖文档与理论文本)**

- **代码**(本包 `.py` 文件):**MIT**
- **本 `README.md` / `SKILL.md` 及其中的理论文本、方法论与一切理论表述**:**不在 MIT 覆盖范围内**,保留所有权利(All rights reserved)

```
© 2026 SynomosAI. All rights reserved.
理论署名 (attribution) : LGD(Lifecycle Governance Doctrine / 全程治理论)— SynomosAI initiative
名称状态 (name status)  : "SynomosAI" — 未申请实体注册、未申请商标注册
                        (not a registered legal entity; no trademark registered)
生产参考部署 (production reference, self-reported) : 无(未声明外部生产参考部署)
                    ← 非认证、非背书、非监管认可(not a certification or endorsement)
代码许可 (code license) : 本包未附 LICENSE 文件(许可待定)
                    本文本与理论表述不在任何代码许可覆盖范围内
引用格式 (cite as)      : 本资产无 DOI
```
(上列为《LGD 对外表述规范》§3.2 统一块,**整体复制、未删改**;发布/重提前须照最新版本复核。)

如何安装此技能?

访问技能市场,点击「安装」按钮,按提示将技能包放入 AI 编程助手的 skills 目录即可。

浏览技能市场

支持平台:Qoder · QoderWork · Claude · Codex 等 AI 编程助手

结构化输出校验护栏(Schema Guard) - 免费 | 技能派