先做做看
阅读之前,先按你现在的想法选一选。选错也没关系。
为什么让 LLM 给出固定格式的 JSON 这么难?
什么是约束解码?
LLM 返回的是字符串,而你的应用需要的是 JSON。这道缝隙让正式服务停摆的次数,比模型的幻觉还多。结构化输出是连接自然语言和带类型数据的桥梁。桥搭好了,LLM 就成了可靠的 API;搭不好,你就要在凌晨 3 点用正则表达式去拆解自由文本。
类型: 动手做 语言: Python(仅标准库) 建议先了解: 第 1 阶段提示词工程、Python 字典和 JSON 基础 时间: 约 90 分钟 后续阶段: 第 3 阶段 嵌入——把含义变成数字 运行: 直接在浏览器里运行(无需安装)。模型的响应是假的(模拟),不会调用真正的 API。
你将学到
- 用 OpenAI、Anthropic、Google API 的 JSON 模式和 schema 模式,得到固定格式的输出。
- 搭建一个校验层:过滤掉结构错误的输出,并把错误内容还给模型,让它重试。
- 说明约束解码是如何不靠后处理,在 token 层面强制产生正确 JSON 的。
- 设计提示词,把自由文本稳定地转换成带类型的数据。
问题
你让 LLM"从这段文字里提取产品名称、价格和库存情况"。它的回答是这样的。
产品是 Sony WH-1000XM5 耳机,价格是 $348.00,目前有货。
这个回答完全正确,但对你的应用毫无用处。库存系统需要的是 {"product": "Sony WH-1000XM5", "price": 348.00, "in_stock": true}。需要的是一个键固定、类型固定、值范围固定的 JSON 对象,而不是一句话。
最省事的办法是在提示词里加上"请用 JSON 回答"。大多数时候都行得通。问题出在剩下的那些时候。模型会把 JSON 包在 markdown 代码围栏(```)里,会加一句"这是 JSON:"之类的开场白,或者括号闭合得太早,输出语法错误的 JSON。解析器崩溃,流水线停摆。于是你加上 try/except 和重试。重试有时又会给出不同的数据。现在,在解析问题之上,又多了一致性问题。
这不是提示词的问题,而是解码的问题。模型是从左到右一个一个地生成 token 的。每个位置上,它都会从超过 10 万个词表条目里,选出最可能的下一个 token。可是在任何一个位置,其中的绝大多数都会破坏 JSON。如果模型刚刚写到 {"price":,那么接下来能出现的,只有数字、引号(字符串)、null、true、false 和负号。除此之外的都是错误的 JSON。没有约束的话,模型可能选出一个在英语里完全正常、在语法上却是致命的词。
概念
结构化输出的四个层级
约束输出结构的方法分成四个层级,越往后越可靠。
- 只靠提示词'请用 JSON 回答'没有强制
- JSON 模式保证 JSON 语法不保证结构
- schema 模式保证 JSON + schema 结构
- 约束解码逐 token 屏蔽来强制(schema 模式的内部原理)
只靠提示词("请用正确的 JSON 回答"):没有任何强制手段。模型通常会照做,但不总是如此。常见的失败有代码围栏、开场白、中途被截断的输出和错误的结构。
JSON 模式:API 保证输出是语法正确的 JSON。OpenAI 的 response_format: {"type": "json_object"} 就是这种。一定能解析,但不保证符合你想要的结构。可能多出键、类型不对,或者缺字段。
schema 模式:API 接收 JSON schema,并保证输出符合该 schema。截至 2026 年 11 月,各大厂商都把它作为原生功能提供。OpenAI 是结构化输出(json_schema 格式,strict: true),Anthropic 是结构化输出(output_config.format)和严格工具调用(strict: true),Google Gemini 是响应 schema(在 response_format 里给 mime_type 和 schema)。输出会按照你定的键、类型和约束生成。
XenLook 备注 "保证"也有两个缺口。第一,如果模型出于安全原因拒绝回答,你收到的是不符合 schema 的拒答文本(OpenAI 是 ref…
"保证"也有两个缺口。第一,如果模型出于安全原因拒绝回答,你收到的是不符合 schema 的拒答文本(OpenAI 是 refusal 字段,Anthropic 是 stop_reason 为 "refusal")。第二,如果触到输出 token 上限而中途被截断,JSON 会不完整(Anthropic 是 stop_reason: "max_tokens",OpenAI 是因超出长度而结束的响应)。所以即使用了 schema 模式,也一定要确认"结束原因"。以上内容已对照 2026 年 11 月三家厂商的官方文档确认。
约束解码:生成过程中,在每个 token 位置上,把所有会导致错误输出的 token 都屏蔽掉。如果 schema 要求数字,而模型想输出字母,就把那个 token 的概率设为 0。模型只能输出通向正确结果的 token。OpenAI 的结构化输出内部就用这种方式,面向开放模型的库 Outlines、Guidance、XGrammar 也用这种方式。
JSON schema——写下约定的语言
JSON schema 是告诉模型(或校验层)输出应该是什么结构的方法。各大结构化输出功能都使用它。
{
"type": "object",
"properties": {
"product": { "type": "string" },
"price": { "type": "number", "minimum": 0 },
"in_stock": { "type": "boolean" },
"categories": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["product", "price", "in_stock"]
}这个 schema 的意思是:输出必须是对象,必须有字符串 product、大于等于 0 的数字 price、布尔值 in_stock,字符串数组 categories 可有可无。不符合的输出会被拒绝。
schema 也能处理复杂的情况。有嵌套对象、元素类型固定的数组、枚举(把字符串限定为几个固定值之一)、模式(给字符串加正则)、组合(从多种结构里选一种的 oneOf、anyOf、allOf)。
XenLook 备注 各厂商的 schema 模式接受的关键字并不相同。OpenAI 严格模式要求把所有字段都放进 required,并加上 a…
各厂商的 schema 模式接受的关键字并不相同。OpenAI 严格模式要求把所有字段都放进 required,并加上 additionalProperties: false(可有可无的字段,用 "type": ["string", "null"] 这样允许 null 的写法来模拟),不接受 allOf、not、if/then/else。Anthropic 不在解码时使用 minimum、maximum、minLength 之类的范围约束。官方 SDK 会把这些值转写成说明文字,并在收到结果后另行校验。Gemini 也会忽略部分关键字,所以文档里写明"收到的值一定要在应用里校验"。结论只有一个:即使用了 schema 模式,你这边的校验也要保留。
Pydantic 方式
在 Python 里,不需要手写 JSON schema。定义一个 Pydantic 模型,就会生成 schema。
from pydantic import BaseModel
class Product(BaseModel):
product: str
price: float
in_stock: bool
categories: list[str] = []会生成和上面一样的 JSON schema。Instructor 库和各厂商的官方 SDK 都可以直接接收 Pydantic 模型。传入模型类,就会返回校验完毕的对象。输出不符合时,Instructor 会自动重试。
函数调用 / 工具调用
这是用另一个入口解决同一个问题的方法。不让模型直接写 JSON,而是定义一个参数类型固定的"工具"(函数)。模型会给出一个带有结构化参数的函数调用。OpenAI 叫它"函数调用",Anthropic 叫它"工具调用"。结果是一样的:结构化的数据。
- 用户:请从这篇评论里提取产品信息
- 模型处理输入
- 工具调用:extract_product( product='Sony WH-1000XM5', price=348.00, in_stock=true)
- 用函数 schema校验
- 结构化结果:{product, price, in_stock}
工具调用更合适的场合,是模型不仅要填参数,还要挑选调用哪个函数的时候。如果有 10 个提取 schema,需要根据输入选出对应的那个,工具调用能一次性完成选 schema 和结构化输出。反过来,如果只需要规定回答的结构,那么结构化输出(schema 模式)更简单。
XenLook 备注 以前很多说明都讲"想在 Claude 上得到结构化输出,只有工具调用一条路"。现在不是这样了。Anthropic 也把结构化输出…
以前很多说明都讲"想在 Claude 上得到结构化输出,只有工具调用一条路"。现在不是这样了。Anthropic 也把结构化输出(output_config.format)作为正式功能提供,所以只想规定回答结构时就用它,让模型挑选工具时才用工具调用。网上旧示例里出现的 output_format 参数和 beta 请求头是旧的做法。
常见的失败
即使强制了 schema,结构化输出也会以不太显眼的方式失败。
编造的值:输出符合 schema,但内容是编的。文字里写的是 $348,模型却给出 {"price": 299.99}。类型对、值错,所以 schema 校验抓不住。在下面"动手做"的 4) 里,我们会亲手做一个与输入文字比对的检查。
枚举混淆:你把字段限定为 ["in_stock", "out_of_stock", "preorder"],模型却给出 "available"。意思没错,但不是允许的值。约束解码能防住这种情况,只靠提示词则防不住。
深层嵌套:schema 嵌套越深,错误越多。每深一层,模型就多一个丢掉结构的位置。
数组长度:数组元素可能给得太多或太少。schema 里有 minItems、maxItems,但并不是所有厂商都在解码阶段强制执行。
漏掉可选字段:形式上是可选的,但对你的工作很重要的字段,模型把它漏掉了。即使有时没有数据,也请在 schema 里把它设为必填,同时允许 null。这样模型就会用 null 明确地说"没有"。
动手做
XenLook 备注 Python 的名称和输出文字用英文,是因为实际工作中的代码通常也是这样。代码只用标准库(json、re),所以不用安装…
Python 的名称和输出文字用英文,是因为实际工作中的代码通常也是这样。代码只用标准库(json、re),所以不用安装,就能在本页下方的"运行代码"里直接执行。模型的响应不是真正的 API,而是模仿真实模型常犯错误的假数据。
1) JSON schema 校验器
从零开始做一个校验器,检查 Python 对象是否符合 JSON schema。这是在输出一侧确认是否遵守 schema 的部分。它也处理 "type": ["string", "null"] 这种允许多种类型的情况,以及禁止 schema 里没有的字段的 additionalProperties: false。这两种都是 OpenAI、Anthropic 严格模式所要求的形式。
import json
import re
def type_matches(data, expected):
if expected == "object":
return isinstance(data, dict)
if expected == "array":
return isinstance(data, list)
if expected == "string":
return isinstance(data, str)
if expected == "number":
return isinstance(data, (int, float)) and not isinstance(data, bool)
if expected == "integer":
return isinstance(data, int) and not isinstance(data, bool)
if expected == "boolean":
return isinstance(data, bool)
if expected == "null":
return data is None
return Truedef validate_schema(data, schema):
errors = []
_validate(data, schema, "", errors)
return errors
def _validate(data, schema, path, errors):
schema_type = schema.get("type")
# "type": ["string", "null"] 的意思是"字符串,或者明确写出的 null"。
if isinstance(schema_type, list):
if data is None and "null" in schema_type:
return
matching = [t for t in schema_type if t != "null" and type_matches(data, t)]
if not matching:
errors.append(f"{path}: expected {' or '.join(schema_type)}, got {type(data).__name__}")
return
schema_type = matching[0]
if schema_type == "object":
if not isinstance(data, dict):
errors.append(f"{path}: expected object, got {type(data).__name__}")
return
for key in schema.get("required", []):
if key not in data:
errors.append(f"{path}.{key}: required field missing")
properties = schema.get("properties", {})
for key, value in data.items():
if key in properties:
_validate(value, properties[key], f"{path}.{key}", errors)
elif schema.get("additionalProperties") is False:
errors.append(f"{path}.{key}: field not allowed by schema")
elif schema_type == "array":
if not isinstance(data, list):
errors.append(f"{path}: expected array, got {type(data).__name__}")
return
min_items = schema.get("minItems", 0)
max_items = schema.get("maxItems", float("inf"))
if len(data) < min_items:
errors.append(f"{path}: array has {len(data)} items, minimum is {min_items}")
if len(data) > max_items:
errors.append(f"{path}: array has {len(data)} items, maximum is {max_items}")
items_schema = schema.get("items", {})
for i, item in enumerate(data):
_validate(item, items_schema, f"{path}[{i}]", errors)
elif schema_type == "string":
if not isinstance(data, str):
errors.append(f"{path}: expected string, got {type(data).__name__}")
return
enum_values = schema.get("enum")
if enum_values and data not in enum_values:
errors.append(f"{path}: '{data}' not in allowed values {enum_values}")
elif schema_type == "number":
if not type_matches(data, "number"):
errors.append(f"{path}: expected number, got {type(data).__name__}")
return
minimum = schema.get("minimum")
maximum = schema.get("maximum")
if minimum is not None and data < minimum:
errors.append(f"{path}: {data} is less than minimum {minimum}")
if maximum is not None and data > maximum:
errors.append(f"{path}: {data} is greater than maximum {maximum}")
elif schema_type == "boolean":
if not isinstance(data, bool):
errors.append(f"{path}: expected boolean, got {type(data).__name__}")
elif schema_type == "integer":
if not type_matches(data, "integer"):
errors.append(f"{path}: expected integer, got {type(data).__name__}")2) 用 Python 模型生成 schema
小规模地模仿 Pydantic 所做的事。从字段定义生成 JSON schema,并按严格模式的要求加上 additionalProperties: false。
class SchemaField:
def __init__(self, field_type, required=True, default=None, enum=None, minimum=None, maximum=None):
self.field_type = field_type
self.required = required
self.default = default
self.enum = enum
self.minimum = minimum
self.maximum = maximum
def python_type_to_schema(field):
type_map = {
str: "string",
int: "integer",
float: "number",
bool: "boolean",
}
schema = {}
if field.field_type in type_map:
schema["type"] = type_map[field.field_type]
elif field.field_type == list:
schema["type"] = "array"
schema["items"] = {"type": "string"}
elif isinstance(field.field_type, dict):
schema = dict(field.field_type)
if field.enum:
schema["enum"] = field.enum
if field.minimum is not None:
schema["minimum"] = field.minimum
if field.maximum is not None:
schema["maximum"] = field.maximum
return schema
def model_to_schema(name, fields):
properties = {}
required = []
for field_name, field in fields.items():
properties[field_name] = python_type_to_schema(field)
if field.required:
required.append(field_name)
return {
"type": "object",
"properties": properties,
"required": required,
"additionalProperties": False,
}3) 约束 token 过滤器
给定生成到一半的 JSON,告诉你接下来可以出现哪些种类的 token。这是约束解码的核心。真正的引擎处理的是模型的整个词表,这里则是按字符跟踪状态,只告诉你 token 的种类。关键在于记住现在是不是在引号里面,刚闭合的字符串是键还是值。只看最后一个字符,是不知道 {"product" 后面应该跟冒号(:)的。
如果同时给出 schema,就更进一步。只看语法的话,{"price": 之后可以是任何值,但 schema 只允许数字。它只允许还没写过的键,并且在必填字段都出现之前,禁止出现 }。
def scan_partial_json(text):
"""遍历一段不完整的 JSON 字符串,返回它末尾处的解析器状态。"""
stack = [] # 尚未闭合的容器:"{" 或 "["
expect = "value" # 语法接下来允许什么
in_string = False
string_is_key = False
escape = False
literal = "" # 正在写的数字 / true / false / null
current = "" # 正在写的字符串的字符
last_key = None # 最外层对象中最近出现的键
keys_seen = [] # 最外层对象中已经写过的键
for ch in text:
if in_string:
if escape:
escape = False
elif ch == "\\":
escape = True
elif ch == '"':
in_string = False
if string_is_key:
if len(stack) == 1:
last_key = current
keys_seen.append(current)
expect = "colon"
else:
expect = "after_value"
continue
current += ch
continue
if literal:
if ch.isalnum() or ch in ".-+":
literal += ch
continue
literal = ""
expect = "after_value"
if ch.isspace():
continue
if expect in ("value", "value_or_close"):
if ch == '"':
in_string, string_is_key, current = True, False, ""
elif ch == "{":
stack.append("{")
expect = "key_or_close"
elif ch == "[":
stack.append("[")
expect = "value_or_close"
elif ch == "]" and expect == "value_or_close":
stack.pop()
expect = "after_value"
else:
literal = ch
elif expect in ("key", "key_or_close"):
if ch == '"':
in_string, string_is_key, current = True, True, ""
elif ch == "}" and expect == "key_or_close":
stack.pop()
expect = "after_value"
elif expect == "colon":
if ch == ":":
expect = "value"
elif expect == "after_value":
if ch == ",":
expect = "key" if stack and stack[-1] == "{" else "value"
elif ch in "}]" and stack:
stack.pop()
expect = "after_value"
return {
"stack": stack, "expect": expect, "in_string": in_string,
"string_is_key": string_is_key, "literal": literal,
"last_key": last_key, "keys_seen": keys_seen,
}VALUE_TOKENS = ['"', "0-9", "-", "true", "false", "null", "[", "{"]SCHEMA_VALUE_TOKENS = {
"string": ['"'],
"number": ["0-9", "-"],
"integer": ["0-9", "-"],
"boolean": ["true", "false"],
"array": ["["],
"object": ["{"],
"null": ["null"],
}def next_valid_tokens(partial_json, schema=None):
"""接下来可以出现哪些种类的 token。
schema=None 时只强制 JSON 语法。给了 schema 时,
最外层对象还要遵守它的键、类型和必填字段。
"""
if not partial_json.strip():
return ["{"]
st = scan_partial_json(partial_json)
top = schema if schema and schema.get("type") == "object" else None
at_top = len(st["stack"]) == 1 and st["stack"][0] == "{"
props = top.get("properties", {}) if top else {}
required = top.get("required", []) if top else []
if st["in_string"]:
if st["string_is_key"] and top and at_top:
return ["(rest of a schema key)", '"']
return ["any character", '"']
if st["literal"]:
lit = st["literal"]
for word in ("true", "false", "null"):
if word.startswith(lit) and lit != word:
return [word[len(lit):]]
closer = "}" if st["stack"] and st["stack"][-1] == "{" else "]"
return ["0-9", ".", ",", closer]
expect = st["expect"]
if expect == "colon":
return [":"]
if expect in ("value", "value_or_close"):
tokens = list(VALUE_TOKENS)
if top and at_top and st["last_key"] in props:
t = props[st["last_key"]].get("type")
types = t if isinstance(t, list) else [t]
tokens = []
for one in types:
tokens += SCHEMA_VALUE_TOKENS.get(one, VALUE_TOKENS)
if expect == "value_or_close":
tokens.append("]")
return tokens
if expect in ("key", "key_or_close"):
if top and at_top:
remaining = [k for k in props if k not in st["keys_seen"]]
tokens = [f'"{k}"' for k in remaining]
missing = [k for k in required if k not in st["keys_seen"]]
if expect == "key_or_close" and not missing:
tokens.append("}")
return tokens
return ['"', "}"] if expect == "key_or_close" else ['"']
# 一个完整的值之后
if not st["stack"]:
return ["<EOS>"]
if st["stack"][-1] == "[":
return [",", "]"]
if top and at_top:
missing = [k for k in required if k not in st["keys_seen"]]
remaining = [k for k in props if k not in st["keys_seen"]]
tokens = [","] if remaining else []
if not missing:
tokens.append("}")
return tokens
return [",", "}"]
def demonstrate_constrained_decoding(schema):
partial_states = [
"",
"{",
'{"product"',
'{"product":',
'{"product": "Sony"',
'{"product": "Sony",',
'{"product": "Sony", "price":',
'{"product": "Sony", "price": 348',
'{"product": "Sony", "price": 348,',
'{"product": "Sony", "price": 348, "in_stock": t',
'{"product": "Sony", "price": 348, "in_stock": true',
'{"product": "Sony", "price": 348, "in_stock": true}',
]
for state in partial_states:
display = state if state else "(empty)"
print(f"\n {display}")
print(f" grammar only : {next_valid_tokens(state)}")
print(f" with schema : {next_valid_tokens(state, schema)}")4) 提取流水线与重试
从文字里提取结构化数据,校验,失败了就说明错在哪里再重试。假模型会犯真实模型常犯的错误。对索尼的文字,它会加上开场白和代码围栏;对 MacBook 的文字,它会把价格写成 "$2,499" 这样的字符串。直到第二次尝试,收到错误内容之后才改正。
最后两种情况很重要。对没有信息的文字,它不会编造值,而是给出 null。对没有写价格的耳机文字,它会编出一个像模像样的价格。这能通过 schema。所以我们再加一个检查(grounding_problems),核对这个值在输入文字里是否真的存在。
def simulate_llm_extraction(text, schema, attempt=0, feedback=None):
t = text.lower()
if "sony" in t:
if not feedback:
# 常见失败:客气的开场白和 markdown 围栏。
return ("Here's the JSON:\n```json\n"
'{"product": "Sony WH-1000XM5", "price": 348.00, "in_stock": true}\n```')
return '{"product": "Sony WH-1000XM5", "price": 348.00, "in_stock": true, "categories": ["audio", "headphones"]}'
if "macbook" in t or "laptop" in t:
if not feedback:
# 常见失败:价格被写成了文字,而不是数字。
return '{"product": "MacBook Pro 16", "price": "$2,499", "in_stock": false}'
return '{"product": "MacBook Pro 16", "price": 2499.00, "in_stock": false, "categories": ["computers"]}'
if "keyboard" in t:
return '{"product": "Keychron Q1", "price": 169.00, "in_stock": true, "categories": ["peripherals"]}'
if "earbuds" in t:
# 符合 schema 但是编造的:文字里没有给出价格。
return '{"product": "Aurora X2", "price": 129.00, "in_stock": true, "categories": ["audio"]}'
# 没有可提取的内容:诚实的模型会明确地返回 null。
return '{"product": null, "price": null, "in_stock": null, "categories": []}'
def extract_with_retry(text, schema, max_retries=3):
feedback = None
for attempt in range(max_retries):
raw = simulate_llm_extraction(text, schema, attempt, feedback)
try:
data = json.loads(raw)
except json.JSONDecodeError as e:
print(f" Attempt {attempt + 1}: JSON parse error -- {e}")
feedback = f"Your output was not valid JSON ({e}). Return only the JSON object."
continue
errors = validate_schema(data, schema)
if not errors:
return data, attempt + 1
print(f" Attempt {attempt + 1}: Schema validation errors -- {errors}")
feedback = "Fix these errors and return only the JSON object: " + "; ".join(errors)
return None, max_retries
def grounding_problems(data, text):
"""schema 校验看不出编造的值。要拿它们和原文比对。"""
problems = []
price = data.get("price")
if isinstance(price, (int, float)):
numbers = [float(n.replace(",", "")) for n in re.findall(r"\d[\d,]*(?:\.\d+)?", text)]
if float(price) not in numbers:
problems.append(f"price {price} does not appear in the text")
name = data.get("product")
if isinstance(name, str) and name.split()[0].lower() not in text.lower():
problems.append(f"product '{name}' does not appear in the text")
return problemsNULLABLE_PRODUCT_SCHEMA = {
"type": "object",
"properties": {
"product": {"type": ["string", "null"]},
"price": {"type": ["number", "null"], "minimum": 0},
"in_stock": {"type": ["boolean", "null"]},
"categories": {"type": "array", "items": {"type": "string"}},
},
"required": ["product", "price", "in_stock", "categories"],
"additionalProperties": False,
}PRODUCT_SCHEMA = {
"type": "object",
"properties": {
"product": {"type": "string"},
"price": {"type": "number", "minimum": 0},
"in_stock": {"type": "boolean"},
"categories": {"type": "array", "items": {"type": "string"}},
},
"required": ["product", "price", "in_stock"],
"additionalProperties": False,
}5) 全部运行
依次运行五个演示:schema 校验、schema 生成、约束解码、提取流水线、嵌套 schema 校验。
def run_schema_validation_demo():
print("=" * 60)
print(" STEP 1: JSON Schema Validation")
print("=" * 60)
test_cases = [
({"product": "Sony WH-1000XM5", "price": 348.0, "in_stock": True}, "Valid complete object"),
({"product": "Test", "price": 10.0, "in_stock": True, "categories": ["audio"]}, "Valid with optional array"),
({"product": "Test", "price": -5.0, "in_stock": True}, "Negative price"),
({"product": "Test", "in_stock": True}, "Missing required field (price)"),
({"product": "Test", "price": "ten", "in_stock": True}, "String as price"),
({"product": 123, "price": 10.0, "in_stock": True}, "Number as product name"),
("not an object", "String instead of object"),
({"product": "Test", "price": 10.0, "in_stock": "yes"}, "String as boolean"),
({"product": "Test", "price": 10.0, "in_stock": True, "color": "black"}, "Extra field not in schema"),
]
for data, label in test_cases:
errors = validate_schema(data, PRODUCT_SCHEMA)
status = "PASS" if not errors else f"FAIL: {errors}"
print(f"\n {label}:")
print(f" Data: {json.dumps(data) if isinstance(data, dict) else repr(data)}")
print(f" Result: {status}")
def run_schema_generation_demo():
print(f"\n{'=' * 60}")
print(" STEP 2: Model-to-Schema Generation")
print("=" * 60)
product_fields = {
"product": SchemaField(str),
"price": SchemaField(float, minimum=0),
"in_stock": SchemaField(bool),
"categories": SchemaField(list, required=False),
"rating": SchemaField(float, required=False, minimum=0, maximum=5),
}
schema = model_to_schema("Product", product_fields)
print(f"\n Generated schema from Python model:")
print(f" {json.dumps(schema, indent=2)}")
event_fields = {
"title": SchemaField(str),
"date": SchemaField(str),
"attendees": SchemaField(list),
"priority": SchemaField(str, enum=["low", "medium", "high"]),
"is_recurring": SchemaField(bool, required=False),
}
event_schema = model_to_schema("Event", event_fields)
print(f"\n Event schema:")
print(f" {json.dumps(event_schema, indent=2)}")
valid_event = {"title": "Standup", "date": "2026-01-15", "attendees": ["Alice", "Bob"], "priority": "high"}
invalid_event = {"title": "Standup", "date": "2026-01-15", "attendees": ["Alice"], "priority": "urgent"}
print(f"\n Validating against event schema:")
for data, label in [(valid_event, "Valid event"), (invalid_event, "Invalid priority enum")]:
errors = validate_schema(data, event_schema)
status = "PASS" if not errors else f"FAIL: {errors}"
print(f" {label}: {status}")
def run_constrained_decoding_demo():
print(f"\n{'=' * 60}")
print(" STEP 3: Constrained Decoding Simulation")
print("=" * 60)
demonstrate_constrained_decoding(PRODUCT_SCHEMA)
def run_extraction_pipeline_demo():
print(f"\n{'=' * 60}")
print(" STEP 4: Extraction Pipeline with Retry")
print("=" * 60)
texts = [
"The Sony WH-1000XM5 headphones are priced at $348 and currently available in stores.",
"The new MacBook Pro 16-inch laptop costs $2499 but is completely sold out everywhere.",
"I just bought a Keychron Q1 mechanical keyboard for $169 and it arrived today.",
"The Aurora X2 earbuds are in stock this week.",
"This sentence contains no product information at all.",
]
for text in texts:
print(f"\n Input: {text[:70]}")
result, attempts = extract_with_retry(text, NULLABLE_PRODUCT_SCHEMA)
if result is None:
print(f" Output: FAILED after {attempts} attempts")
continue
print(f" Output ({attempts} attempt{'s' if attempts > 1 else ''}): {json.dumps(result)}")
if result.get("product") is None:
print(" Check: nothing found -- fields are null, not invented")
continue
problems = grounding_problems(result, text)
if problems:
print(f" Check: schema OK but NOT grounded -- {problems}")
else:
print(" Check: grounded in the text")
def run_nested_schema_demo():
print(f"\n{'=' * 60}")
print(" STEP 5: Nested Schema Validation")
print("=" * 60)
order_schema = {
"type": "object",
"properties": {
"order_id": {"type": "string"},
"customer": {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
},
"required": ["name", "email"],
},
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"product": {"type": "string"},
"quantity": {"type": "integer"},
"price": {"type": "number", "minimum": 0},
},
"required": ["product", "quantity", "price"],
},
"minItems": 1,
},
"total": {"type": "number", "minimum": 0},
},
"required": ["order_id", "customer", "items", "total"],
}
valid_order = {
"order_id": "ORD-001",
"customer": {"name": "Alice", "email": "alice@example.com"},
"items": [
{"product": "Widget", "quantity": 3, "price": 9.99},
{"product": "Gadget", "quantity": 1, "price": 24.99},
],
"total": 54.96,
}
invalid_order = {
"order_id": "ORD-002",
"customer": {"name": "Bob"},
"items": [],
"total": -10,
}
print(f"\n Order schema (nested objects + arrays):")
for data, label in [(valid_order, "Valid order"), (invalid_order, "Invalid order")]:
errors = validate_schema(data, order_schema)
status = "PASS" if not errors else "FAIL"
print(f"\n {label}: {status}")
if errors:
for e in errors:
print(f" - {e}")if __name__ == "__main__":
run_schema_validation_demo()
run_schema_generation_demo()
run_constrained_decoding_demo()
run_extraction_pipeline_demo()
run_nested_schema_demo()怎么读结果
XenLook 备注 这一节是 XenLook 添加的说明。
这一节是 XenLook 添加的说明。
在下面的"运行代码"里运行,STEP 3 会出现这样的几行。
{"product"
grammar only : [':']
with schema : [':']
{"product":
grammar only : ['"', '0-9', '-', 'true', 'false', 'null', '[', '{']
with schema : ['"']
{"product": "Sony"
grammar only : [',', '}']
with schema : [',']grammar only 是只看 JSON 语法时接下来可以出现的 token,with schema 是连 schema 也一起看时接下来可以出现的 token。闭合了键之后,只能出现冒号。冒号之后,按语法任何值都行,但 schema 里 product 是字符串,所以只允许引号。闭合了 "Sony" 这个值之后,会出现逗号或右花括号。看 schema 的话,右花括号就没有了,因为必填字段 price 和 in_stock 还没有出现。真正的约束解码会把这个列表之外的 token 的概率设为 0。
STEP 4 是这样结束的。
Input: The Aurora X2 earbuds are in stock this week.
Output (1 attempt): {"product": "Aurora X2", "price": 129.0, "in_stock": true, "categories": ["audio"]}
Check: schema OK but NOT grounded -- ['price 129.0 does not appear in the text']
Input: This sentence contains no product information at all.
Output (1 attempt): {"product": null, "price": null, "in_stock": null, "categories": []}
Check: nothing found -- fields are null, not invented通过了 schema 并不等于答案正确。 耳机的文字里没有价格,假模型却编了一个 129。类型是对的,所以 schema 校验通过了,只有与输入文字比对的检查抓到了这一点。完全没有信息的最后一段文字,所有值都给了 null。如果填上 "Unknown" 或 0,就和真实数据分不出来了。
| 输出部分 | 含义 |
|---|---|
| STEP 1 | 用商品 schema 校验 9 个用例——负数价格、缺字段、类型错误、schema 里没有的字段(color)会 FAIL |
| STEP 2 | 从 Python 字段定义生成的两个 schema,以及不被允许的枚举值 "urgent" 会 FAIL |
| STEP 3 | 生成到一半的每个 JSON 之后可以出现的 token——只看语法时和连 schema 也看时 |
| STEP 4 | 五段文字的提取结果——第几次尝试通过的,与输入文字是否一致 |
| STEP 5 | 嵌套订单 schema——错误的订单有 3 个错误(缺邮箱、空的项目数组、负数合计) |
实际使用
XenLook 备注 下面的代码都被注释(#)封住了,不会运行。想真正运行,需要各厂商的 API 密钥。模型 ID 和函数名取自 2026 年 1…
下面的代码都被注释(#)封住了,不会运行。想真正运行,需要各厂商的 API 密钥。模型 ID 和函数名取自 2026 年 11 月各厂商的官方文档,所以自己运行时,请再查一遍当天的文档。
OpenAI:结构化输出
# from openai import OpenAI
# from pydantic import BaseModel
#
# client = OpenAI()
#
# class Product(BaseModel):
# product: str
# price: float
# in_stock: bool
#
# response = client.responses.parse(
# model="gpt-6.1-terra",
# input=[
# {"role": "system", "content": "Extract product information."},
# {"role": "user", "content": "Sony WH-1000XM5, $348, in stock"},
# ],
# text_format=Product,
# )
#
# product = response.output_parsed
# print(product.product, product.price, product.in_stock)OpenAI 的结构化输出在内部使用约束解码。所以因结构不符而需要重试的情况很少。不过上面"概念"里看到的两个缺口(拒答、因长度超出而被截断)依然存在,请确认响应是正常结束的。值是否与输入文字一致,schema 也不会替你看。如果你的代码用的是旧的 Chat Completions 方式,可以用 client.chat.completions.parse(..., response_format=Product) 做同样的事。
Anthropic:结构化输出与严格工具调用
# import anthropic
# from pydantic import BaseModel
#
# client = anthropic.Anthropic()
#
# class Product(BaseModel):
# product: str
# price: float
# in_stock: bool
#
# # 1) 只需规定回答的结构时:结构化输出
# response = client.messages.parse(
# model="claude-opus-5-5",
# max_tokens=1024,
# messages=[{"role": "user", "content": "Extract: Sony WH-1000XM5, $348, in stock"}],
# output_format=Product,
# )
# product = response.parsed_output
#
# # 2) 需要让模型挑选工具时:严格工具调用
# response = client.messages.create(
# model="claude-opus-5-5",
# max_tokens=1024,
# tools=[{
# "name": "extract_product",
# "description": "Extract product information from text",
# "strict": True,
# "input_schema": {
# "type": "object",
# "properties": {
# "product": {"type": "string"},
# "price": {"type": "number"},
# "in_stock": {"type": "boolean"},
# },
# "required": ["product", "price", "in_stock"],
# "additionalProperties": False,
# },
# }],
# messages=[{"role": "user", "content": "Extract: Sony WH-1000XM5, $348, in stock"}],
# )
# tool_call = next(b for b in response.content if b.type == "tool_use")
# print(tool_call.input)第一种方法中,SDK 会把 Pydantic 模型转换成 output_config.format 的 JSON schema 发送出去,校验收到的回答,并作为 parsed_output 返回。第二种方法保证模型所选工具调用的参数与 input_schema 一致。去掉 strict: True 的话,就没有保证,只是"大多数时候是对的"。第一次发送的 schema 要编译语法,所以会稍慢,之后 24 小时内会使用缓存。
Google:Gemini 响应 schema
# from google import genai
# from pydantic import BaseModel
#
# client = genai.Client()
#
# class Product(BaseModel):
# product: str
# price: float
# in_stock: bool
#
# interaction = client.interactions.create(
# model="gemini-3.8-flash",
# input="Extract: Sony WH-1000XM5, $348, in stock",
# response_format={
# "type": "text",
# "mime_type": "application/json",
# "schema": Product.model_json_schema(),
# },
# )
# product = Product.model_validate_json(interaction.output_text)Gemini 接收 JSON schema 并让回答符合该结构。像最后一行那样,用 Pydantic 对收到的字符串再校验一次,是 Google 文档推荐的做法。因为有些 schema 关键字会被忽略。
Instructor 库
# pip install instructor
# import instructor
# from pydantic import BaseModel
#
# client = instructor.from_provider("anthropic/claude-opus-5-5")
#
# class Product(BaseModel):
# product: str
# price: float
# in_stock: bool
#
# product = client.create(
# response_model=Product,
# max_tokens=1024,
# messages=[{"role": "user", "content": "Sony WH-1000XM5, $348, in stock"}],
# )Instructor 封装了多家厂商的客户端,加上校验和自动重试。如果第一次尝试没通过校验,它会把错误内容作为上下文还给模型,让它改正。"动手做"4) 里我们亲手做的 extract_with_retry 做的就是这件事。只要像 "openai/…"、"google/…" 这样改动前面的部分,就能原样用于其他厂商的模型。
产出
这节课会产出两件成果。
结构化提取提示词——给它 JSON schema 和一段文字,只返回符合 schema 的 JSON 的可复用提示词模板。文字里没有的值不会编造,而是留成 null。
选择结构化输出方式的 skill——根据所用厂商、所需可靠性和 schema 复杂度,选出合适方式的判断框架。
Python 代码(code/structured_outputs.py)是一个可以独立运行的练习工具。把 simulate_llm_extraction 换成真正的 API 调用后,校验器、重试和输入文字比对检查不用修改,仍然可以照常工作。
XenLook 备注 这两件成果可以在本页下方的"成果"里以中文展开查看。直接复制,粘贴到 AI 聊天窗口或编程智能体里使用即可。
这两件成果可以在本页下方的"成果"里以中文展开查看。直接复制,粘贴到 AI 聊天窗口或编程智能体里使用即可。
练习
-
让 schema 校验器支持
oneOf(必须恰好符合多个 schema 中的一个)。这样就能处理多种结构的输出:某个字段可能是Product对象,也可能是结构不同的Service对象。 -
做一个"schema 比较"工具,比较两个 schema,区分会导致破坏的变更(删除必填字段、修改类型)和不会破坏的变更(增加可选字段、放宽约束)。在正式服务里管理提取 schema 的版本时,这是必不可少的。
-
做一个更接近真实的约束解码模拟器。给定一个 JSON schema 和一个只有 100 个 token 的词表(字母、数字、标点、关键字),一步一步地生成,并在每个位置屏蔽错误的 token。测一测每个位置上词表中有百分之几是被允许的。直接使用"动手做"3) 里的
scan_partial_json也可以。 -
做一套提取评估集。给 50 条产品描述配上人工标注的标准答案 JSON,把流水线在全部样本上跑一遍,测量完全匹配率、各字段的准确率和类型遵守率。找出哪个字段最难提取。
-
给提取流水线加上"确信度"。估计模型对每个字段有多大把握(可以看 token 概率,也可以把同一次提取跑 3 遍,看一致程度)。把确信度低的字段标出来,交给人审核。
[옮긴이] 在 XenLook 课程里,建议在这里再同时使用"动手做"4) 的输入文字比对检查。即使三次都给出了相同的值,如果输入文字里没有这个值,那它就是编出来的。一致性和事实是两回事。
核心术语
| 术语 | 常见说法 | 实际含义 |
|---|---|---|
| JSON 模式 | "返回 JSON" | 保证输出是语法正确的 JSON 的 API 设置。不强制特定的 schema |
| 结构化输出 | "带类型的 JSON" | 符合既定 JSON schema 的键、类型和约束的输出 |
| 约束解码 | "引导式生成" | 在每个 token 位置屏蔽会导致错误输出的 token,使只产生符合 schema 的输出。因拒答或超出长度而结束的情况要另外确认 |
| JSON schema | "JSON 模板" | 描述 JSON 数据的结构、类型和约束的声明式语言(OpenAPI、JSON Forms 等也在用) |
| Pydantic | "Python dataclass 加强版" | 用于定义带类型校验的数据模型的 Python 库。FastAPI、Instructor 和各厂商 SDK 都用它生成 JSON schema |
| 函数调用 | "工具调用" | LLM 输出结构化的函数调用(名称 + 带类型的参数),而不是自由文本。OpenAI、Anthropic、Google 都支持 |
| Instructor | "LLM 版 Pydantic" | 封装 LLM 客户端、返回校验完毕的 Pydantic 对象,并在校验失败时自动重试的 Python 库 |
| token 屏蔽 | "词表过滤" | 生成过程中把特定 token 的概率设为 0,让模型无法输出该 token |
| 符合 schema | "结构正确" | 必填字段齐全、类型正确、值在约束之内,并且没有不被允许的字段 |
| 重试循环 | "直到成功为止" | 把校验错误还给模型,让它改正。Instructor 会自动做到设定的次数 |
| 输入文字比对 | "核对依据" | 检查提取出的值在输入文字里是否真的存在。能抓住 schema 抓不住的编造值(XenLook 课程新增的术语) |
延伸阅读
- OpenAI 结构化输出指南——OpenAI 官方文档,介绍基于 JSON schema 的结构化输出、严格模式的 schema 规则和拒答处理
- Anthropic 结构化输出指南——
output_config.format、严格工具调用、不支持的 schema 关键字以及 SDK 的处理方式 - Gemini 结构化输出指南——响应 schema、支持的关键字,以及与函数调用的区别
- Willard & Louf, 2023 — "Efficient Guided Generation for Large Language Models"——Outlines 的论文。介绍如何把 JSON schema 转换成有限状态机,在 token 层面进行约束
- Instructor 文档——用 Pydantic 校验和重试,在多家厂商的 LLM 上得到结构化输出的库
- JSON schema 规范——结构化输出功能所用 schema 语言的完整规范
- Outlines 库——把正则表达式和 JSON schema 转换成有限状态机来约束生成的开源库
- Dong 等, "XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models" (MLSys 2025)——用下推自动机编译语法、快速屏蔽 token 的语法引擎
- Beurer-Kellner 等, "Prompting Is Programming: A Query Language for Large Language Models" (LMQL)——把约束解码作为带类型、值约束的查询语言来处理的论文
- Microsoft Guidance——基于模板的约束生成库。不绑定特定厂商,常与 Outlines、XGrammar 一起使用
本课程由 XenLook 把 Rohit Ghumare 的 AI Engineering from Scratch(MIT 许可证)翻译成中文并作了修正。
亲手运行
structured_outputs.py
这是本课的代码。点击按钮后,Python 只在这个浏览器里运行。代码和结果不会发送到 XenLook 服务器。
尚未运行。
检查理解
读完之后来做一做。选完马上就能看到正确答案和解析。
用 Pydantic 模型校验 LLM 的输出有什么好处?
明明已经下了指令,LLM 还是返回了错误的 JSON,该怎么办?
API 原生提供的结构化输出,和只靠提示词请求 JSON 的方式,各自在什么时候用?
成果
这是你在本课中做出并带走的东西。点一下即可展开。
提示词结构化提取提示词给它一份 JSON schema 和一段文字,它只依据文字里写明的内容,返回一个符合 schema 的 JSON 的提取提示词
你是一个结构化数据提取器。我会给你一个 JSON schema 和一段文字。你要从文字中提取数据,生成与 schema 完全匹配的 JSON。
提取步骤
1. 先看 schema
提取之前,先仔细看 schema。
- 确认必填字段和每个字段的类型
- 确认枚举、最小值和最大值、格式要求
- 确认嵌套对象和数组的结构
- 确认哪些字段允许为 null
- 提前标出文字里不好提取或提取起来有难度的字段
2. 提取规则
只写文字里有的内容:每个值都必须是文字里写明的,或者能从文字里直接推出的。不要因为"看起来合理"就编造值。尤其是价格、日期、数量、名字,必须和文字里的完全一致。
文字里没有的信息:即使是必填字段,也不要用编造的默认值填充。
- schema 允许 null,就写
null - 如果是数组,就写空数组
[] - 如果是不允许 null 的必填字段,而文字里又没有这个信息,不要编造值,把这个字段写进下面的"提取备注"。如果 schema 里没有地方放备注,就不要返回 JSON,改为返回
{"error": "missing_required", "fields": ["字段名"]} - 不要用 "unknown"、"无信息"、0、false 之类的值填空。这样会让它和真实的值分不出来
严格遵守类型:每个值都必须与 schema 的类型完全匹配。
- 类型为 number 的 "price":写 348.00,不要写 "$348" 或 "三百四十八美元"
- 类型为 boolean 的 "in_stock":写 true/false,不要写 "是" 或 "有"
- 类型为 array 的 "categories":写 ["audio", "headphones"],不要写 "audio, headphones"
枚举字段:值必须是允许的值之一。如果文字用了近义的说法,就换成最接近的允许值(例:把 "available" 换成 "in_stock")。如果和任何一个值都明显对不上,允许 null 时就写 null,否则写进提取备注。
嵌套对象:每一层嵌套都分别提取,内层对象也要符合各自的子 schema。
schema 里没有的字段:不要创造 schema 里没有的键。如果 schema 是 additionalProperties: false,必须严格遵守。
3. 看确信度
对提取出的每个字段,在心里估一下确信度。
- 高:文字里写得很清楚
- 中:文字里只是隐约提到,或者需要稍微推理一下
- 低:只凭文字,依据不足——这样的值不要写,留成 null 或者写进备注
如果有确信度低的字段,或者有空着的必填字段,只有在 schema 允许额外字段时,才在 _extraction_notes 字段里简短记录(例:"price: 文字里没有价格")。如果 schema 不允许额外字段,就不要放备注。
4. 输出格式
只返回一个 JSON 对象。不要加 markdown 代码围栏、开场白或解释。输出必须能直接被 JSON.parse() 或 json.loads() 读取。
输入格式
schema:
{schema}待提取的文字:
{text}
输出
一个与 schema 完全匹配的 JSON 对象。
用法:把
{schema}和{text}替换成你的内容,粘贴到 AI 聊天窗口即可。如果和 API 的 schema 模式(结构化输出)一起用,结构由 API 保证,这个提示词负责"只写文字里有的,没有就写 null"这条内容规则。提取出的值在文字里是否真的存在,请像课程"动手做"4) 里的输入文字比对检查那样,再用代码确认一次。
技能选择结构化输出方式根据所用厂商、所需可靠性和 schema 复杂度,选出合适的结构化输出方式的判断框架
开发需要固定格式数据的 LLM 应用时,请使用这个判断框架。
各种方式分别在什么时候用
只靠提示词("请用 JSON 回答"): 只用于原型,以及偶尔解析失败也无妨的内部工具。一定要加上校验,以及有次数上限的重试。不要用在正式服务的流水线里。
JSON 模式(API 设置): 必须得到语法正确的 JSON,但 schema 简单或比较灵活的时候。前提是应用这边自己校验结构。OpenAI 的 json_object 格式就是典型代表。
schema 模式(结构化输出): 每一个输出都必须符合既定 schema 的正式服务。请把它作为正式服务中提取、分类任务的默认选择。有 OpenAI、Anthropic 的结构化输出,Gemini 的响应 schema,以及面向开放模型的 Outlines、Guidance、XGrammar。结构有保证,但因拒答、超出长度而结束的响应,以及编造出来的值,仍然要自己来确认。
函数调用 / 工具调用: 模型不只是要填参数,还要挑选调用哪个函数的时候。有多个 schema、要让模型选出合适的那个,或者要接入已有的工具体系时使用。必须开启严格模式(strict: true),才能保证参数与 schema 一致。
Instructor 库: 不论哪家的模型,只要想要 Pydantic 校验和自动重试。在 Python 项目里最方便。它封装了 OpenAI、Anthropic、Google 和开放模型。
各厂商说明(以 2026 年 11 月官方文档为准)
OpenAI: 使用结构化输出(json_schema 格式,strict: true)。可以把 Pydantic 模型直接传给 SDK 的 responses.parse(..., text_format=Model)。严格模式要求把所有字段都放进 required,并要求 additionalProperties: false。可有可无的字段,用允许 null 来表达。请检查响应里的 refusal。
Anthropic: 只想规定回答的结构时,使用结构化输出(output_config.format,SDK 的 messages.parse(..., output_format=Model))。想让模型挑选工具时,使用严格工具调用(strict: true)。范围约束(minimum、maxLength 等)和递归 schema 不会在解码时强制执行,所以请像 SDK 那样,在收到结果之后再校验。stop_reason 是 "refusal" 或 "max_tokens" 时,输出可能不符合 schema。
Google Gemini: 在 response_format 里给出 mime_type: "application/json" 和 JSON schema。有些关键字会被忽略,所以请用 Pydantic 对收到的字符串重新校验。
开放模型(vLLM、SGLang、Ollama 等): 使用推理服务引擎的结构化输出功能(通常用 XGrammar、Outlines 这类语法引擎),或者使用 Outlines、Guidance。它们把 JSON schema 转换成状态机或语法,在生成过程中屏蔽错误的 token。需要自己运维推理服务器。
schema 设计原则
- 尽量保持扁平。嵌套越深,提取错误越多。
- 分类字段用枚举。不要指望模型自己编出合适的字符串。
- 含义模糊的字段不要设成可选,而是设成必填并允许 null。这样模型会明确说出"没有"。
- 给每个字段加上说明(
description)。模型会把说明当作指示来读。 - 不是非用不可,就避免多种形态的类型(
oneOf、anyOf)。它们会让解码和校验变复杂,而且各厂商的支持情况不一样。 - 数字要设最小值、最大值。可以拦住离谱的编造值。有的厂商不会在解码时强制执行,所以校验器里也要检查。
- 数组要设
minItems、maxItems,防止出现空数组或没完没了的数组。同样,各厂商是否强制执行也不一样。
常见失败与解决办法
- 用 markdown 代码围栏把 JSON 包起来:从提示词方式换成 JSON 模式或 schema 模式
- schema 符合,内容却不对:用代码把提取出的值和输入文字对照,确认它真的在文字里(价格、日期、名字)。难以用代码确认的内容,就增加一个 LLM 评估环节,或者交给人审核
- 枚举值参差不齐:换成约束解码(schema 模式),或者在后处理里对齐到允许的值
- 可选字段总是缺失:改成必填 + 允许 null。不要在应用代码里用编造的默认值去填
- 提取太慢:schema 第一次使用时,可能要花时间编译语法,所以会慢(通常会被缓存)。对延迟敏感的话,就重复使用同一个 schema,把 schema 弄简单,并实际测量延迟后再判断
- 条目各不相同的大数组:把输入拆开,每一块分别提取,再合并
- 响应中途被截断:检查结束原因(超出长度),然后提高输出 token 上限,或者把输入拆开
可靠性阶梯
| 方式 | 保证可解析 | 保证 schema 结构 | 仍需确认的 |
|---|---|---|---|
| 只靠提示词 | 无 | 无 | 解析、结构、内容全部要确认——必须校验 + 重试 |
| JSON 模式 | 有 | 无 | 结构和内容——在应用里做 schema 校验 |
| schema 模式 / 严格工具调用 | 有* | 有*(在支持的关键字范围内) | 拒答和截断、不支持的约束、内容 |
| 开放模型 + 语法引擎 | 有* | 有* | 截断、内容 |
| Instructor + 重试 | 靠校验确认 | 靠校验确认 | 内容、重试次数和成本 |
* 因拒答或超出长度而结束的响应除外。不管用哪种方式,都不保证值是真实的,所以最后一列的"内容"确认,始终是你自己的责任。
本课程由 XenLook 翻译并修订自 Rohit Ghumare 的 AI Engineering from Scratch(MIT 许可证),以对照原文校正过的韩语版为底本。基准提交: 8fec9cc19e.
MIT 许可证全文(英文)
MIT License
Copyright (c) 2026 Rohit Ghumare
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.