指南#
Guidance 是微软开发的一种用于控制大语言模型的指导语言。
Guidance 程序允许你将生成、提示和逻辑控制交织成一个连续的流程,这与语言模型实际处理文本的方式相匹配。
结构化输出#
Guidance 最令人兴奋的特性之一是能够输出结构化对象(例如遵循特定模式的 JSON 或 pydantic 对象)。它不仅可以向大语言模型"建议"期望的输出结构,还能实际"强制"模型输出遵循预定模式。这使得大语言模型可以专注于内容而非语法,彻底消除输出解析问题的可能性。
这对于参数规模较小、未经过充分源代码训练的中小型语言模型尤为强大,它们通常难以可靠地生成格式良好的层次化结构化输出。
创建生成 pydantic 对象的 guidance 程序#
在 LlamaIndex 中,我们提供了与 guidance 的初步集成,使得生成结构化输出(特别是 pydantic 对象)变得极其简单。
例如,要生成包含以下模式的歌曲专辑:
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),
],
)
可通过此笔记本查看更多细节。
使用 guidance 增强子问题查询引擎的鲁棒性#
LlamaIndex 提供了一套高级查询引擎工具包来处理不同用例。其中多个引擎依赖中间步骤的结构化输出。我们可以利用 guidance 确保中间响应具有预期结构(从而能正确解析为结构化对象),从而提升这些查询引擎的鲁棒性。
例如,我们实现了 GuidanceQuestionGenerator,可将其接入 SubQuestionQueryEngine,相比默认设置能提供更强的鲁棒性。
from llama_index.question_gen.guidance import GuidanceQuestionGenerator
from guidance.llms import OpenAI as GuidanceOpenAI
# 定义基于 guidance 的问题生成器
question_gen = GuidanceQuestionGenerator.from_defaults(
guidance_llm=GuidanceOpenAI("text-davinci-003"), verbose=False
)
# 定义查询引擎工具
query_engine_tools = ...
# 构建子问题查询引擎
s_engine = SubQuestionQueryEngine.from_defaults(
question_gen=question_gen, # 使用上述基于 guidance 的 question_gen
query_engine_tools=query_engine_tools,
)
详见此笔记本。