tnblog
首页
视频
资源
登录

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

3210人阅读 2023/9/10 23:06 总访问:3467345 评论:0 收藏:0 手机
分类: python

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
五里墩茶社


欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739

评价

LangChain 简单应用(学习笔记)

LangChain 简单应用(学习笔记)[TOC] Langchain 简介大型语言模型(LLM)正在成为一种具有变革性的技术,使开发人员能够构...

LangChain 模型(学习笔记)

LangChain 模型(学习笔记)[TOC] Langchain 模型简介Langchain所封装的模型分为两类:——大语言模型 (LLM)——聊天模型 (C...

LangChain 数据连接(学习笔记)

LangChain 数据连接(学习笔记)[TOC] 什么是数据连接?LLM应用往往需要用户特定的数据,而这些数据并不属于模型的训练集。L...

LangChain 提示词(学习笔记)

LangChain 提示词(学习笔记)[TOC] 什么是提示词?提示词(Prompt)是指向模型提供的输入。这个输入通常由多个元素构成。La...

LangChain 链(学习笔记)

LangChain 链(学习笔记)[TOC] 单一的LLM对于简单的应用场景已经足够,但是更复杂的应用程序需要将LLM串联在一起,需要多LL...

LangChain 记忆组件(学习笔记)

LangChain 记忆组件(学习笔记)[TOC] 单一的LLM对于简单的应用场景已经足够,但是更复杂的应用程序需要将LLM串联在一起,需...

LangChain 代理 Agent(学习笔记)

LangChain 代理 Agent(学习笔记)[TOC] 简介Agent 也就是代理,它的核心思想是利用一个语言模型来选择一系列要执行的动作。...

LangChain 回调 (Callback)

LangChain 回调 (Callback)[TOC] 简介Callback 是 LangChain 提供的回调机制,允许我们在 LLM 应用程序的各个阶段使用 Hoo...

LangChain 一个完整的例子

LangChain 一个完整的例子[TOC] 简介这是该 LangChain 极简入门系列的最后一讲。我们将利用过去9讲学习的知识,来完成一个...
这一世以无限游戏为使命!
排名
2
文章
634
粉丝
44
评论
93
docker中Sware集群与service
尘叶心繁 : 想学呀!我教你呀
一个bug让程序员走上法庭 索赔金额达400亿日元
叼着奶瓶逛酒吧 : 所以说做程序员也要懂点法律知识
.net core 塑形资源
剑轩 : 收藏收藏
映射AutoMapper
剑轩 : 好是好,这个对效率影响大不大哇,效率高不高
ASP.NET Core 服务注册生命周期
剑轩 : http://www.tnblog.net/aojiancc2/article/details/167
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术