CodexQA

Industry & PracticeTools & Frameworks

Inspect 结构化输出:用 JSON Schema 约束评测作答

CodexQA 团队4 min read

Inspect 在 OpenAI、Anthropic、Google、Mistral、vLLM、SGLang 等提供方上支持结构化输出。指定 JSON Schema 可能改变任务表现,评分器仍要解析字符串并抓住 ValidationError。vLLM 与 SGLang 的 choice、regex、grammar 键名不同。

In this piece

结构化输出

UK AI Security Institute。Inspect 文档《Structured Output》。许可证:MIT。Copyright (c) 2024 UK AI Security Institute。页面未单独标注修订日期,本文按 2026-11-18 打开的文档页编写。

概述

结构化输出(structured output,让模型按给定结构作答的接口)是一些模型提供方支持的功能,用来保证模型生成的回答符合一份给定的 JSON Schema。JSON Schema 是描述 JSON 形状的一份说明。Inspect 目前在这些提供方上支持结构化输出:OpenAI、Anthropic、Bedrock、Google、Mistral、Grok、Groq、vLLM 和 SGLang。

结构化输出看起来像是对付模型不可靠的稳妥办法,但要记住:指定 JSON schema 也会给模型的任务表现带来未知影响。已有早期文献指出,模型在结构化输出下表现更差(https://dylancastillo.co/posts/say-what-you-mean-sometimes.html)。

因此应当把结构化输出当成一种引出能力的手法来测试,和其他手法一样。只有当你有把握它真正改善了整个任务,才继续用。

示例

下面走一个简单例子:用结构化输出把模型输出限制成 Color 类型,其中有红、绿、蓝三个分量。如果想再试,见 Inspect GitHub 仓库里的源码(https://github.com/UKGovernmentBEIS/inspect_ai/blob/main/examples/structured.py)。

先设想有这样的数据集:

from inspect_ai.dataset import Sample

colors_dataset=[
    Sample(
        input="What is the RGB color for white?",
        target="255,255,255",
    ),
    Sample(
        input="What is the RGB color for black?",
        target="0,0,0",
    ),
]

我们希望模型给出颜色的 RGB 值,但它可能用很多种格式来写。在评分器里解析这些格式会很费事,也容易出错。评分器(scorer)是给一条样本的模型输出打分的函数。

这里定义一个希望从模型拿回来的 Pydantic Color 类型。Pydantic(https://docs.pydantic.dev/)是用类型声明来校验数据的 Python 库。

from pydantic import BaseModel

class Color(BaseModel):
    red: int
    green: int
    blue: int

要让模型按这个类型返回,使用生成配置里的 response_schema 选项,并用 json_schema() 函数为这个类型生成 schema。下面是完整任务定义,用的就是上面的数据集和颜色类型:

from inspect_ai import Task, task
from inspect_ai.model import GenerateConfig, ResponseSchema
from inspect_ai.solver import generate
from inspect_ai.util import json_schema

@task
def rgb_color():
    return Task(
        dataset=colors_dataset,
        solver=generate(),
        scorer=score_color(),
        config=GenerateConfig(
            response_schema=ResponseSchema(
              name="color", 
              json_schema=json_schema(Color)
            )
        ),
    )

我们用 json_schema() 为 Color 类型创建 JSON schema,再包进 ResponseSchema,并给它一个名字。

这里还指定了自定义评分器。既要解析自定义类型,也要给它打分,因为模型返回的 JSON 仍然是字符串。评分器如下:

from inspect_ai.scorer import (
    CORRECT,
    INCORRECT,
    Score,
    Target,
    accuracy,
    scorer,
    stderr,
)
from inspect_ai.solver import TaskState

@scorer(metrics=[accuracy(), stderr()])
def score_color():
    async def score(state: TaskState, target: Target):
        try:
            color = Color.model_validate_json(state.output.completion)
            if f"{color.red},{color.green},{color.blue}" == target.text:
                value = CORRECT
            else:
                value = INCORRECT
            return Score(
                value=value,
                answer=state.output.completion,
            )
        except ValidationError as ex:
            return Score(
                value=INCORRECT,
                answer=state.output.completion,
                explanation=f"Error parsing response: {ex}",
            )

    return score

Pydantic 的 Color 类型有 model_validate_json(),用来读模型输出。如果模型输出不正确,要抓住 ValidationError。

Schema

json_schema() 可以为任意 Python 类型建 schema,包括 Pydantic 模型、dataclass 和 typed dict。即便如此,仍然强烈建议用 Pydantic 模型,因为评分器通常还需要它额外的解析和校验。

生成配置项 response_schema 接收一个 ResponseSchema 对象,里面是 schema 和另外几个字段:

from inspect_ai.model import ResponseSchema
from inspect_ai.util import json_schema

config = GenerateConfig(
  response_schema=ResponseSchema(
    name="color",                   # required name field 
    json_schema=json_schema(Color), # schema for custom type
    description="description",      # optional field with more context
    strict=False                    # force model to adhere to schema
  )
)

并非所有模型提供方都支持全部选项。具体来说,只有 Mistral 和 OpenAI 支持 name、description 和 strict。Google 只接收 json_schema。

因此不要以为指定了 strict,评分器就可以不再解析和校验模型输出,因为有些模型不会遵守 strict。使用 strict 也可能影响任务表现。和往常一样,最好做实验并测量。

vLLM/SGLang API

vLLM 和 SGLang 提供方除了上面这种 JSON schema 结构化输出,还支持 choice、regex 和上下文无关文法这几种格式。目前通过 GenerateConfig 对象里的 extra_body 字段实现。更多细节见 vLLM 文档(https://docs.vllm.ai/en/stable/features/structured_outputs.html)和 SGLang 文档(https://docs.sglang.ai/advanced_features/structured_outputs.html)。

每种引导解码格式的键名,vLLM 和 SGLang 不一样:

格式vLLM 键SGLang 键
Choiceguided_choicechoice
Regexguided_regexregex
Grammarguided_grammarebnf

下面是每种格式的用法示例。

引导选择解码

config = GenerateConfig(
    extra_body={
        "guided_choice": ["RGB: 255,255,255", "RGB: 0,0,0"]  # vLLM
        # "choice": ["RGB: 255,255,255", "RGB: 0,0,0"]       # SGLang
    }
)

引导正则解码

config = GenerateConfig(
    extra_body={
        "guided_regex": r"RGB: (\d{1,3}),(\d{1,3}),(\d{1,3})"  # vLLM
        # "regex": r"RGB: (\d{1,3}),(\d{1,3}),(\d{1,3})"       # SGLang
    }
)

正则(regex)是用一套符号描述字符串形状的写法。

引导上下文无关文法解码

上下文无关文法(context free grammar,用产生式规定哪些字符串合法的一套规则)在这里写成 EBNF 风格的字符串。

grammar = """
root ::= rgb_color
rgb_color ::= "RGB: " rgb_values
rgb_values ::= number "," number "," number
number ::= digit | digit digit | digit digit digit
digit ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
"""

config = GenerateConfig(
    extra_body={
        "guided_grammar": grammar  # vLLM
        # "ebnf": grammar          # SGLang
    }
)

出处:UK AI Security Institute,Structured Output,页面未标日期、收录于 2026-11-18,https://inspect.aisi.org.uk/structured.html,MIT License。

Found it useful? Pass it on

WeChat

Scan with WeChat to open it on your phone and forward it.

Subscribe via RSS

Submit a correction