结构化输出:JSON合法,答案仍可能不对
Structured output
让发票依次经过解析、字段、精确算术和来源证据检查。
structured-output账算得平,单价却是编的
来源目录写明一本笔记本售价3.50USD。提取记录却写数量2、单价4.00、总价8.00。它能解析为JSON,字段类型和范围可以符合schema,算术也完全正确,但仍与来源不符。
结构化输出是遵守明确合同的机器可读响应,合同可以使用JSON Schema、文法或固定记录类型,目的是让下游解释可预测。它本身不证明数据真实。JSONSchemaBench第5节区分框架接受某schema、观测运行产生符合输出,以及真正实现全部schema语义;即使暂不考虑事实准确性,这也是不同主张。
本文应用是一条小型发票提取流程。非AI基线直接读取已有结构化记录;来源若是自由文本,模型可以提出候选,但调用方仍须决定是否接受。本地示例验证原创候选字符串,没有调用或模拟提取模型。
让不同检查各司其职
令P表示接入解析器接受的集合,S表示符合schema的记录,R表示跨字段算术成立的记录,E表示获得来源目录支持的记录。接受集合为它们的交集:
流程遇到第一层失败就停止。这里P包含明确的资源和互操作策略,不只是JSON文法。RFC8259第4节建议对象成员名唯一,并说明不同实现怎样处理重复成员。本应用拒绝重复名,而不默默保留最后一个值;这是更严格的接入选择,不是声称JSON文法一概禁止它。
Schema要求商品、数量、单价、总价和币种。数量是1到10的整数,单价和总价有有限非负边界,币种来自两个允许字符串。必需字段均须存在,额外字段禁止。JSON Schema Validation第6.1.1—6.1.2与6.5.3节定义类型、枚举和必需属性;Core第10.3.2.3节解释additionalProperties与同一schema对象内属性规则的关系。
不要混淆JSON的数值整数语义与某门语言的类型继承。Schema的integer接受小数部分为零的数,包括3.0;JSON布尔值不是数字,不能因为Python的True是int子类,就接受它作为数量。
接着检查算术合同:
其中q是数量,u是单价,t是总价。字段边界本身不强制这个等式,程序用精确有理数运算单独检查。然后查商品是否存在、价格是否等于来源、币种是否是来源中的USD。Schema允许EUR,是为了说明通用记录格式可能比当前来源支持的范围更宽。
Schema关键字还需要对应的验证器行为。Validation第7.2.1—7.2.2节区分format注解与format断言。出现一个format标签,不意味着所有工具都做了完整验证;即使邮箱语法有效,也不能证明收件人存在。本文发票例子没有使用format,也不声称实现通用schema引擎。
通过率要写明分母。下面用概率链式法则表示最终接受率,不假设各层独立:
14条原创字符串中,11条通过接入解析、6条通过schema、5条通过算术、2条通过来源证据。因此逐层比例是11/14、6/11、5/6、2/5,相乘得2/14。这只是测试样例计数,不是生产故障率估计。只说“接受的JSON都有效”,会掩盖拒绝率及其他验证层。
把候选验证完,再交给下游
完整程序使用Python3.12标准库。SCHEMA说明单一发票合同,schema_valid只手写实现这份合同,不支持任意JSON Schema。本地来源目录同样是原创。
接入配置限制UTF-8输入最多4,096字节、容器深度16、小数有效数字256位、小数指数绝对值256。这些应用边界比JSON语法窄。解析器拒绝NaN等非JSON常量与重复键,先解析字节数受限的字符串,再迭代检查深度。
"""Bounded JSON ingestion and a single authored invoice contract; not a general schema engine."""
from decimal import Decimal,InvalidOperation
from fractions import Fraction
import json
CATALOG={'notebook':Decimal('3.50'),'clip':Decimal('0.10')}
KEYS={'item','quantity','unit_price','total','currency'}
SCHEMA={'$schema':'https://json-schema.org/draft/2020-12/schema','type':'object','required':sorted(KEYS),'additionalProperties':False,'properties':{
'item':{'type':'string','minLength':1},'quantity':{'type':'integer','minimum':1,'maximum':10},
'unit_price':{'type':'number','minimum':0,'maximum':10000},'total':{'type':'number','minimum':0,'maximum':100000},'currency':{'enum':['USD','EUR']}}}
def parse(text):
if not isinstance(text,str) or len(text.encode('utf-8'))>4096:raise ValueError('JSON text limited to4096 UTF-8 bytes')
def pairs(items):
result={}
for key,value in items:
if key in result:raise ValueError('duplicate object name')
result[key]=value
return result
def decimal_value(value):
try:result=Decimal(value)
except InvalidOperation as exc:raise ValueError('unrepresentable decimal') from exc
if len(result.as_tuple().digits)>256 or abs(result.as_tuple().exponent)>256:
raise ValueError('decimal precision or exponent outside ingestion profile')
return result
def forbidden(value):raise ValueError('non-JSON numeric constant')
try:result=json.loads(text,parse_float=decimal_value,parse_constant=forbidden,object_pairs_hook=pairs)
except (json.JSONDecodeError,RecursionError) as exc:raise ValueError('invalid or over-nested JSON') from exc
stack=[(result,1)]
while stack:
value,depth=stack.pop()
if isinstance(value,(dict,list)):
if depth>16:raise ValueError('container depth limited to16')
children=value.values() if isinstance(value,dict) else value
stack.extend((child,depth+1) for child in children)
return result
def number(value):
return type(value) is int or isinstance(value,Decimal) and value.is_finite()
def schema_valid(obj):
if not isinstance(obj,dict) or set(obj)!=KEYS:return False
if not isinstance(obj['item'],str) or not obj['item'] or obj['currency'] not in ['USD','EUR']:return False
q=obj['quantity']
if not number(q) or not 1<=q<=10 or q!=int(q):return False
return all(number(obj[k]) and 0<=obj[k]<=limit for k,limit in [('unit_price',10000),('total',100000)])
def inspect(text):
try:obj=parse(text)
except ValueError:return dict(parse=False,schema=False,arithmetic=False,evidence=False)
schema=schema_valid(obj)
arithmetic=schema and Fraction(obj['quantity'])*Fraction(obj['unit_price'])==Fraction(obj['total'])
evidence=arithmetic and obj['item'] in CATALOG and Decimal(obj['unit_price'])==CATALOG[obj['item']] and obj['currency']=='USD'
return dict(parse=True,schema=bool(schema),arithmetic=bool(arithmetic),evidence=bool(evidence))
def bounded_retry(candidates,limit=2):
if type(limit) is not int or not 1<=limit<=5:raise ValueError('retry budget1..5 required')
if not isinstance(candidates,(list,tuple)):raise ValueError('finite candidate list required')
attempts=[]
for candidate in candidates[:limit]:
result=inspect(candidate);attempts.append(result)
if result['evidence']:return dict(accepted=True,attempts=len(attempts),checks=attempts)
return dict(accepted=False,attempts=len(attempts),checks=attempts)
def demo():
good='{"item":"notebook","quantity":2,"unit_price":3.50,"total":7.00,"currency":"USD"}'
cases={'valid':good,'syntax':good[:-1]+',}','duplicate':good[:-1]+',"quantity":1}',
'nan':good.replace('3.50','NaN'),'missing':good.replace(',"currency":"USD"',''),
'extra':good[:-1]+',"approved":true}','boolean':good.replace('"quantity":2','"quantity":true'),
'fraction':good.replace('"quantity":2','"quantity":2.5'),'wrong_total':good.replace('7.00','7.01'),
'wrong_currency':good.replace('USD','GBP'),'unknown_item':good.replace('notebook','pencil'),
'wrong_price':good.replace('3.50','4.00').replace('7.00','8.00'),
'exact_decimal':'{"item":"clip","quantity":3.0,"unit_price":0.10,"total":0.30,"currency":"USD"}',
'unsupported_evidence_currency':good.replace('USD','EUR')}
results={k:inspect(v) for k,v in cases.items()};counts={k:sum(v[k] for v in results.values()) for k in ['parse','schema','arithmetic','evidence']}
return dict(cases=cases,results=results,counts=counts,total_cases=len(cases),retry_success=bounded_retry([cases['syntax'],good]),retry_exhausted=bounded_retry([cases['syntax'],cases['wrong_total'],good]),schema=SCHEMA)
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
小数按原始拼写解析,然后转成Fraction做乘法,避开二进制浮点误差,也避开Decimal默认28位算术精度的舍入。例如3乘0.10恰好等于0.30。数量写作3.0可接受,写作true或2.5会被拒绝。
样例分开语法错误、重复键、缺字段、多字段、类型错、算术错和无依据的事实。wrong_price算术自洽,却不符合来源;unknown_item因目录里没有商品而失败。记录失败时不执行下游动作。
对长度L的有界输入,解析和遍历需要O(L)结构性工作,至多存储O(L)内容。精确数字运算还取决于操作数位数;本例通过有效数字及指数边界限制成本。含引用或复杂组合的通用schema,需要自己的资源分析和验证器测试。
重试次数也是接口的一部分
验证失败时返回明确失败状态。调用方可以请求修正候选、回退到确定性解析器,或转交复核。程序仅消费预先给出的候选字符串列表,默认预算两次;前两次失败后,即使第三条有效,也故意不再查看。
若另作一个说明模型,假设每次尝试独立且成功率同为p,则预算B下的成功率和期望尝试次数为:
第二式通过累计“能走到第几次尝试”的概率得到。真实重试可能重复同一错误,修正提示也会改变分布,不能把此式当相关模型输出的保证。应同时记录成功和尝试次数,最终格式通过也不等于重试没有延迟和费用。
Geng等人在各引擎共同覆盖的schema实例上比较效率,避免简单子集获得不公平速度优势。经验覆盖来自有限运行,真实覆盖则要求约束与schema语义精确一致;二者都不能把事实错误的发票变成正确记录。约束解码限制生成路径,生成后验证仍有独立职责。
找出应该拒绝它的那一层
- 一个数量写作3.0,另一个写作
true,这份schema应如何处理?
答案:3.0是整数值数字,可在其他检查满足时通过;true应拒绝。JSON布尔与数字不同,不受Python继承规则改变。
- 笔记本数量2、单价4、总价8的记录为什么失败?
答案:它满足字段规则与算术,但来源单价是3.50USD。内部一致不能证明来源支持。
- 14条候选逐层剩下11、6、5、2条,最终接受率是多少?
答案:11/14乘6/11乘5/6乘2/5,得到2/14,即1/7。每个条件分母都是进入该层的候选,不需要假设各层独立。
- 第三条候选正确,但前两条失败且重试上限为2,本次调用应返回成功吗?
答案:不应。它尝试两次后返回有界失败。调用方可以显式启动新流程,但悄悄多花一次会违反已声明预算。
格式保证有自己的范围
JSON语法与互操作看RFC8259,字段和format规则看JSON Schema Validation,应用器行为看Core。选用的2020-12规格文字发表于2022年6月,方言名不是发布日期。JSONSchemaBench第4—5节区分效率、观测覆盖与完整语义覆盖。本程序的样例和手写验证器没有复现其中任何引擎或性能主张。
先判断,再看解释
单价和总价相符,但来源目录没有该商品,这份提取验证通过了吗?
学习目标
- 区分语法、schema符合性、跨字段一致性和事实支持。
- 运行有界原创示例并解释失败情况。
先修与延伸
查看知识关联图 →参考文献
- Generating Structured Outputs from Language Models: Benchmark and Studies — v1
Saibo Geng; Hudson Cooper; Michał Moskal; Samuel Jenkins; Julian Berman; Nathan Ranchin; Robert West; Eric Horvitz; Harsha Nori · 2025 - RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format
Tim Bray, editor; IETF · 2017 - JSON Schema Validation — Draft2020-12, June2022 specification
Austin Wright; Henry Andrews; Ben Hutton · 2022 - JSON Schema Core — Draft2020-12, June2022 specification
Austin Wright; Henry Andrews; Ben Hutton; Greg Dennis · 2022
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-20 · Single AI author. Read PDF3–6 text and viewed PDF7 section5:9558 schemas in Table1, efficiency on common covered instances, declared/empirical/true coverage, single greedy run and format-enabled validation. No benchmark replicated. New scoped reading: sections4–6 relevant HTML text, duplicate-name SHOULD and interoperability behavior, arrays and numeric grammar opening; existing Source object preserved. Read sections6.1.1/6.1.2,6.5.3,7.2.1/7.2.2: numeric integer semantics, enum, required and format vocabularies. HTML text only. Read section10.3.2.3: additionalProperties and its same-schema dependencies; no complete validator implementation claimed. 4 paired equations and four explained exercises. Four layer counts11/6/5/2, numeric integer versus boolean, exact long decimals, duplicate/nonfinite/huge exponent/depth/size rejection and bounded retries checked. One authored contract, not a general JSON Schema engine.
- 核四层11/6/5/2、整数值与布尔、长小数精确运算、重复/非有限/巨指数/深度/大小拒绝及重试预算;单合同非通用schema引擎。
- 每题四张计算SVG,9数值/几何与24响应式组合通过;实看8张最终图,完整页面验收另记。
- 最终页面发现英文数字边界缺空格,仅插入清单中的空格;公式、程序、行内字面值、链接及元数据不变。原冻结稿保留,精确插入回归及页面重检另记。
核对的来源位置:
- Generating Structured Outputs from Language Models: Benchmark and Studies — v1 · Read PDF3–6 text and viewed PDF7 section5:9558 schemas in Table1, efficiency on common covered instances, declared/empirical/true coverage, single greedy run and format-enabled validation. No benchmark replicated.
- RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format · New scoped reading: sections4–6 relevant HTML text, duplicate-name SHOULD and interoperability behavior, arrays and numeric grammar opening; existing Source object preserved.
- JSON Schema Validation — Draft2020-12, June2022 specification · Read sections6.1.1/6.1.2,6.5.3,7.2.1/7.2.2: numeric integer semantics, enum, required and format vocabularies. HTML text only.
- JSON Schema Core — Draft2020-12, June2022 specification · Read section10.3.2.3: additionalProperties and its same-schema dependencies; no complete validator implementation claimed.
相关主题