← 研究笔记
从 LLM 获得可靠 JSON:运行 Outlines

从 LLM 获得可靠 JSON:运行 Outlines

在禁用网络访问后,我实际运行了 Outlines——一个强制 LLM 按指定 schema 输出的库。一个小型 0.5B 模型返回了值正确的有效 JSON。

本文涉及的仓库

dottxt-ai/outlines

Structured Outputs

14.5k Python Apache License 2.0

让 LLM “用 JSON 作答”,它可能会加上一句开场白,或者漏掉一个逗号,导致解析器无法接受输出。Outlines 会在生成过程中限制 token 候选。模型只能选择能让输出保持在指定 schema 内的 token。我安装了它,并在禁用网络访问后测试了结构化生成。

在每一步生成时,Outlines 都会先移除无法匹配指定 JSON Schema 或正则表达式的 token,模型随后才能从剩余候选中进行选择。这样一来,后处理阶段不可能发生解析失败,这是由构造保证的。该项目以 Apache 2.0 License(*1)发布源代码。

1. 安装 Outlines 并下载小型模型

为了测试结构化生成,我选择了小型 Qwen2.5 0.5B Instruct 模型。

FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'torch==2.13.0' --index-url https://download.pytorch.org/whl/cpu
RUN pip install --no-cache-dir --quiet 'transformers==4.57.1' 'outlines==1.3.1'
COPY warmup_model.py /tmp/warmup_model.py
RUN python /tmp/warmup_model.py
WORKDIR /work
podman build -t outlines-sandbox .

2. 传入 schema 并生成结构化输出

我用一个固定 schema 将事故报告转换成了 JSON,其中包含严重程度、受影响的服务名称和停机时长。转换是在禁用网络的情况下执行的。

from pydantic import BaseModel
from transformers import AutoModelForCausalLM, AutoTokenizer
import outlines

class ContainerIncident(BaseModel):
    severity: str
    affected_service: str
    downtime_minutes: int

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
hf_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
model = outlines.from_transformers(hf_model, tokenizer)

prompt = (
    "Summarize this incident as JSON: a rootless container crashed and the "
    "checkout service was down for 12 minutes. This was a high severity issue."
)
result = model(prompt, ContainerIncident, max_new_tokens=100)
parsed = ContainerIncident.model_validate_json(result)
podman run --rm --network none --memory 3g --cpus 2 --pids-limit 512 \
  -v "$(pwd)":/work -w /work outlines-sandbox \
  python structured_demo.py

-v 选项会让容器可以读取和写入指定目录。请从一个空目录运行该命令,并将这个目录用于实验。命令运行期间,torch.compile 为了优化而查找 C++ 编译器。由于找不到编译器,它打印了大量警告。本次运行使用了未编译的 eager mode,警告没有影响生成结果。

命令输出如下:

raw output: {"severity": "High", "affected_service": "checkout service", "downtime_minutes": 12}
parsed severity: High
parsed affected_service: checkout service
parsed downtime_minutes: 12

Pydantic 将输出解析成了模型,解析出的值与输入文本一致:严重程度为 High,服务为 checkout service,停机 12 分钟。0.5B 模型没有产生格式错误的输出,因为 Outlines 从一开始就把违反 schema 的 token 排除在候选集合之外。

在生成时保证输出格式

当程序要消费 LLM 的输出时,解析失败可能需要重试逻辑。Outlines 可以在生成过程中强制执行 schema,因此不需要针对 schema 解析失败进行后处理重试。选择成本更低的配置时,可以使用小型模型的结果。

来源

*1 Outlines (GitHub), https://github.com/dottxt-ai/outlines, Apache 2.0 License