指南
指南 是微软开发的一种用于控制大型语言模型的指导语言。
指导程序允许你将生成、提示和逻辑控制交织成一个连续的流程,与语言模型实际处理文本的方式相匹配。
指导功能中一个特别令人兴奋的方面是能够输出结构化对象(想象遵循特定模式的JSON,或pydantic对象)。指导功能不仅可以向大语言模型"建议"期望的输出结构,实际上还能"强制"大语言模型的输出遵循预期模式。这使得大语言模型能够专注于内容而非语法,并完全消除输出解析问题的可能性。
这对于参数规模较小、且未经过充分源代码数据训练的较弱大型语言模型尤其有效,这些模型往往难以可靠地生成格式规范、层次分明的结构化输出。
创建一个指导程序来生成pydantic对象
Section titled “Creating a guidance program to generate pydantic objects”在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), ],)你可以尝试使用这个笔记本获取更多详细信息。
使用指导提升我们子问题查询引擎的鲁棒性。
Section titled “Using guidance to improve the robustness of our sub-question query engine.”LlamaIndex 提供了一套高级查询引擎工具包,用于应对不同的使用场景。 其中多个引擎在中间步骤依赖结构化输出。 我们可以利用指导机制来提升这些查询引擎的稳健性,通过确保 中间响应具有预期结构(从而能正确解析为结构化对象)。
例如,我们实现了一个GuidanceQuestionGenerator,可以将其插入到SubQuestionQueryEngine中,使其比使用默认设置更加稳健。
from llama_index.question_gen.guidance import GuidanceQuestionGeneratorfrom guidance.llms import OpenAI as GuidanceOpenAI
# define guidance based question generatorquestion_gen = GuidanceQuestionGenerator.from_defaults( guidance_llm=GuidanceOpenAI("text-davinci-003"), verbose=False)
# define query engine toolsquery_engine_tools = ...
# construct sub-question query engines_engine = SubQuestionQueryEngine.from_defaults( question_gen=question_gen, # use guidance based question_gen defined above query_engine_tools=query_engine_tools,)查看此笔记本获取更多详情。