# 9.4 结构化输出与约束解码

在很多实际应用中，大语言模型的输出不仅需要语义正确，还需要满足特定的**格式约束**。例如，输出合法的 JSON 对象、生成符合语法的 SQL 查询、或按照特定模板进行函数调用。

## 9.4.1 为什么需要约束解码

标准的采样策略只考虑概率分布，不保证输出的结构合法性。当模型输出需要被程序解析时，任何格式错误（如缺少引号、括号不匹配）都会导致下游系统崩溃。

## 9.4.2 主要方法

**引导解码**（Guided Decoding）：在每个解码步，根据当前生成状态和目标格式的语法规则，将不合法的词元概率设为零，只对合法词元集合 $$V\_{\text{valid}}(s\_t)$$ 重新归一化采样。例如，如果上一步生成了 JSON 键名后的冒号，下一步只允许生成值类型的词元（字符串引号、数字、`true`/`false` 等）：

$$P\_{\text{constrained}}(x) = \begin{cases} \frac{P(x)}{\sum\_{x' \in V\_{\text{valid}}} P(x')} & \text{if } x \in V\_{\text{valid}}(s\_t) \ 0 & \text{otherwise} \end{cases}$$

**JSON 模式**：vLLM、TGI 等推理框架已内建 JSON 模式支持，通过有限状态自动机跟踪 JSON 语法状态。

**正则表达式约束**：Outlines 等工具允许开发者定义正则表达式或上下文无关语法，约束模型输出必须匹配。

这些结构化输出技术在 LLM 与工具调用、API 集成和智能体（Agent）工作流中发挥着关键作用。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yeasy.gitbook.io/llm_internals/di-san-bu-fen-tui-li-yu-bu-shu-pian/09_decoding/9.4_constrained.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
