Skip to content
LlamaIndex 文档版本 跟随上游 源快照 0512e862 更新于 2026-10-15

Guidance 是微软开发的一种用于控制大语言模型的引导语言。

Guidance 程序允许你把生成、提示与逻辑控制交织成单一连续的流程,与语言模型实际处理文本的方式相匹配。

结构化输出

Guidance 特别令人兴奋的一点,是能够输出结构化对象(比如遵循特定 schema 的 JSON,或一个 pydantic 对象)。Guidance 不只是向 LLM“建议”期望的输出结构,而是能真正“强制”LLM 的输出遵循目标 schema。这让 LLM 专注于内容而非语法,并彻底消除输出解析出问题的可能。

对于较弱的 LLM 这尤其有力——它们参数量更小、也没有在足够的源码数据上训练过,难以稳定产出格式良好、有层级的结构化输出。

创建 guidance 程序以生成 pydantic 对象

在 LlamaIndex 中,我们提供了与 guidance 的初步集成,让生成结构化输出(更具体说是 pydantic 对象)变得极其简单。

例如,我们想生成一张歌曲专辑,schema 如下:

class Song(BaseModel):
    title: str
    length_seconds: int

class Album(BaseModel):
    name: str
    artist: str
    songs: List[Song]

只需创建一个 GuidancePydanticProgram、指定我们想要的 pydantic 类 Album,再给出合适的提示词模板即可。

注:guidance 使用 handlebars 风格的模板,它用双花括号做变量替换、单花括号表示字面花括号。这与 Python 格式化字符串的约定正好相反。

from llama_index.core.prompts.guidance_utils import convert_to_handlebars` 可以把 Python 格式化字符串风格的模板转换成 guidance 的 handlebars 风格模板。

program = GuidancePydanticProgram(
    output_cls=Album,
    prompt_template_str="Generate an example album, with an artist and a list of songs. Using the movie {{movie_name}} as inspiration",
    guidance_llm=OpenAI("text-davinci-003"),
    verbose=True,
)

现在我们可以带着额外的用户输入调用这个程序。这里来点惊悚风——做一张以《闪灵》为灵感的专辑。

output = program(movie_name="The Shining")

我们得到了这个 pydantic 对象:

Album(
    name="The Shining",
    artist="Jack Torrance",
    songs=[
        Song(title="All Work and No Play", length_seconds=180),
        Song(title="The Overlook Hotel", length_seconds=240),
        Song(title="The Shining", length_seconds=210),
    ],
)

更多细节可以玩玩这个 notebook。

用 guidance 提升子问题查询引擎的稳健性

LlamaIndex 提供了一套面向各种用例的进阶查询引擎工具箱。其中若干个在中间步骤依赖结构化输出。我们可以用 guidance 提升这些查询引擎的稳健性——确保中间响应具有预期结构(从而能被正确解析成结构化对象)。

作为示例,我们实现了一个 GuidanceQuestionGenerator,可以插入 SubQuestionQueryEngine,比默认设置更稳健。

from llama_index.question_gen.guidance import GuidanceQuestionGenerator
from guidance.llms import OpenAI as GuidanceOpenAI

# define guidance based question generator
question_gen = GuidanceQuestionGenerator.from_defaults(
    guidance_llm=GuidanceOpenAI("text-davinci-003"), verbose=False
)

# define query engine tools
query_engine_tools = ...

# construct sub-question query engine
s_engine = SubQuestionQueryEngine.from_defaults(
    question_gen=question_gen,  # use guidance based question_gen defined above
    query_engine_tools=query_engine_tools,
)

更多细节见这个 notebook。

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。