尘叶心繁

LangChain 输出解析器(学习笔记)

电脑版发表于:2023/9/10 23:06

LangChain 输出解析器(学习笔记)

简介


LLM的输出为文本,但在程序中除了显示文本,可能希望获得更结构化的数据。
这就是输出解析器(Output Parsers)的用武之地。
LangChain 为输出解析器提供了基础类 BaseOutputParser
不同的输出解析器都继承自该类。它们需要实现以下两个函数:

  • get_format_instructions:返回指令指定LLM的输出该如何格式化,该函数在实现类中必须重写。基类中的函数实现如下:
  1. def get_format_instructions(self) -> str:
  2. """Instructions on how the LLM output should be formatted."""
  3. raise NotImplementedError
  • parse:解析LLM的输出文本为特定的结构。函数签名如下:
  1. def parse(self, text: str) -> T


BaseOutputParser 还提供了如下函数供重载:
parse_with_prompt:基于提示词上下文解析LLM的输出文本为特定结构。该函数在基类中的实现为:

  1. def parse_with_prompt(self, completion: str, prompt: PromptValue) -> Any:
  2. """Parse the output of an LLM call with the input prompt for context."""
  3. return self.parse(completion)

LangChain支持的输出解析器

LangChain框架提供了一系列解析器实现来满足应用在不同功能场景中的需求。它们包括且不局限于如下解析器:

  • List parser
  • Datetime parser
  • Enum parser
  • Auto-fixing parser
  • Pydantic parser
  • Retry parser
  • Structured output parser

    本讲介绍具有代表性的两款解析器的使用。

List Parser


List Parser将逗号分隔的文本解析为列表。

  1. from langchain.output_parsers import CommaSeparatedListOutputParser
  2. output_parser = CommaSeparatedListOutputParser()
  3. output_parser.parse("black, yellow, red, green, white, blue")


你应该能看到如下输出:

Structured Output Parser


当我们想要类似JSON数据结构,包含多个字段时,可以使用这个输出解析器。
该解析器可以生成指令帮助LLM返回结构化数据文本,同时完成文本到结构化数据的解析工作。
示例代码如下:

  1. from langchain.output_parsers import StructuredOutputParser, ResponseSchema
  2. from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
  3. from langchain.llms import OpenAI
  4. # 定义响应的结构(JSON),两个字段 answer和source。
  5. response_schemas = [
  6. ResponseSchema(name="answer", description="answer to the user's question"),
  7. ResponseSchema(name="source", description="source referred to answer the user's question, should be a website.")
  8. ]
  9. output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
  10. # 获取响应格式化的指令
  11. format_instructions = output_parser.get_format_instructions()
  12. # partial_variables允许在代码中预填充提示此模版的部分变量。
  13. # 这类似于接口,抽象类之间的关系
  14. prompt = PromptTemplate(
  15. template="answer the users question as best as possible.\n{format_instructions}\n{question}",
  16. input_variables=["question"],
  17. partial_variables={"format_instructions": format_instructions}
  18. )
  19. model = OpenAI(temperature=0)
  20. response = prompt.format_prompt(question="what's the capital of France?")
  21. output = model(response.to_string())
  22. # 格式化转换
  23. output_parser.parse(output)


你应该期望能看到如下输出:

注,关于示例代码中引用的 partial_variables,请参考Partial - Prompt Templates

总结


本节课程中,我们学习了什么是 输出解析器 ,LangChain所支持的常见解析器,以及如何使用常见的两款解析器 List ParserStructured Output Parser
随着LangChain的发展,应该会有更多解析器出现。

相关文档资料链接


Python Langchain官方文档
Partial - Prompt Templates
五里墩茶社

关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
猜你喜欢
    1. 1
    2. 2
    3. 3
    / 3