LangChain之Output parsers

2023-11-17

LangChain之Output parsers

Output parsers将LLM输出的文本,转换为structured data

CommaSeparatedListOutputParser

解析结果为List,提示词如下:

def get_format_instructions(self) -> str:
    return (
        "Your response should be a list of comma separated values, "
        "eg: `foo, bar, baz`"
    )

解析方法如下:

def parse(self, text: str) -> List[str]:
    """Parse the output of an LLM call."""
    return text.strip().split(", ")

DatetimeOutputParser

解析结果为日期时间

output_parser = DatetimeOutputParser()
print(output_parser.get_format_instructions())

上面代码输出的提示词

Write a datetime string that matches the 
            following pattern: "%Y-%m-%dT%H:%M:%S.%fZ". Examples: 477-06-08T11:31:35.756750Z, 245-12-26T14:36:39.117625Z, 711-05-08T07:41:23.815247Z

EnumOutputParser

解析结果为枚举类型,且枚举类型只支持str

提示词如下:

def get_format_instructions(self) -> str:
    return f"Select one of the following options: {', '.join(self._valid_values)}"

示例代码:

class Colors(Enum):
    RED = "red"
    GREEN = "green"
    BLUE = "blue"

parser = EnumOutputParser(enum=Colors)
print(parser.get_format_instructions())

输出结果:

Select one of the following options: red, green, blue

PydanticOutputParser

解析结果为Json结构

如何使用:

from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field, validator
from typing import List

class Actor(BaseModel):
    name: str = Field(description="name of an actor")
    film_names: List[str] = Field(description="list of names of films they starred in")

# 提问问题
actor_query = "Generate the filmography for a random actor."
# 构造一个解析器,输出的json结构按照Actor定义
parser = PydanticOutputParser(pydantic_object=Actor)

prompt = PromptTemplate(
    template="Answer the user query.\n{format_instructions}\n{query}\n",
    input_variables=["query"],
    partial_variables={"format_instructions": parser.get_format_instructions()},
)

_input = prompt.format_prompt(query=actor_query)

# 输出prompt最终格式化结果
print(_input.to_string())

输出结果

Answer the user query.
The output should be formatted as a JSON instance that conforms to the JSON schema below.

As an example, for the schema {"properties": {"foo": {"title": "Foo", "description": "a list of strings", "type": "array", "items": {"type": "string"}}}, "required": ["foo"]}
the object {"foo": ["bar", "baz"]} is a well-formatted instance of the schema. The object {"properties": {"foo": ["bar", "baz"]}} is not well-formatted.

Here is the output schema:
```
{"properties": {"name": {"description": "name of an actor", "title": "Name", "type": "string"}, "film_names": {"description": "list of names of films they starred in", "items": {"type": "string"}, "title": "Film Names", "type": "array"}}, "required": ["name", "film_names"]}
```
Generate the filmography for a random actor.

其中除了第一行和最后一行内容,中间部分为parser.get_format_instructions()执行结果

PydanticOutputParser使用的提示词模板如下,只需要将最后 {schema} 根据给定的结构体填充即可

PYDANTIC_FORMAT_INSTRUCTIONS = """The output should be formatted as a JSON instance that conforms to the JSON schema below.

As an example, for the schema {{"properties": {{"foo": {{"title": "Foo", "description": "a list of strings", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of the schema. The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.

Here is the output schema:
```
{schema}
```

OutputFixingParser

上面解析json的例子中如果LLM输出错误,需要重新通过LLM修正错误,具体示例如下

class Actor(BaseModel):
    name: str = Field(description="name of an actor")
    film_names: List[str] = Field(description="list of names of films they starred in")
        
actor_query = "Generate the filmography for a random actor."

parser = PydanticOutputParser(pydantic_object=Actor)
# 错误的地方在于,这里json字符串内部应该使用双引号,而不是单引号。。
misformatted = "{'name': 'Tom Hanks', 'film_names': ['Forrest Gump']}"

parser.parse(misformatted)

# 这里输出会报错

使用OutputFixingParser修正错误

import os
from dotenv import load_dotenv

# 加载.env文件中的环境变量,包括OPENAI_API_KEY等
load_dotenv()

# 通过OutputFixingParser纠正json格式错误
from langchain.output_parsers import OutputFixingParser
from langchain.chat_models import ChatOpenAI
new_parser = OutputFixingParser.from_llm(parser=parser, llm=ChatOpenAI())

new_parser.parse(misformatted)
# 最后能够正确解析为Json格式

# 输出如下
# Actor(name='Tom Hanks', film_names=['Forrest Gump'])

OutputFixingParser实现原理:

只使用PydanticOutputParser时,逻辑如下

  1. 构建prompts
  2. 调用LLM获取输出结果
  3. 将输出结果解析为对应类

使用OutputFixingParser后,逻辑变为

  1. 构建prompts
  2. 调用LLM获取输出结果
  3. 将输出结果解析为对应类,但是解析失败
  4. 构建修正的prompts + 解析错误时的错误信息,重新调用LLM,获取结果
  5. 将输出结果解析为对应类

上面加粗部分为新增的处理逻辑

其中第4步中OutputFixingParser构建的prompts如下

NAIVE_FIX = """Instructions:
--------------
{instructions}
--------------
Completion:
--------------
{completion}
--------------

Above, the Completion did not satisfy the constraints given in the Instructions.
Error:
--------------
{error}
--------------

Please try again. Please only respond with an answer that satisfies the constraints laid out in the Instructions:"""

NAIVE_FIX_PROMPT = PromptTemplate.from_template(NAIVE_FIX)

解析代码

def parse(self, completion: str) -> T:
    try:
        parsed_completion = self.parser.parse(completion)
    except OutputParserException as e:
        new_completion = self.retry_chain.run(
            instructions=self.parser.get_format_instructions(),
            completion=completion,
            error=repr(e),
        )
        parsed_completion = self.parser.parse(new_completion)

    return parsed_completion

使用LLMChain

转载请注明出处

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

LangChain之Output parsers 的相关文章

随机推荐

  • Angular项目配置本地https访问

    Angular项目配置本地https访问 首先 先创建一个项目 d work learn ng new angular https 然后cd到刚生成的项目的根目录 建立一个cert目录 用于存放我们的密钥证书等文件 cd angular h
  • 转载---贪心算法

    转载博主 1 贪心算法简介 1 1 基本定义 在贪婪算法 greedy method 中 我们要逐步构造一个最优解 每一步 我们都在一定的标准下 做出一个最优决策 做出决策所依据的标准称为贪心准则 greedy criterion 贪心算法
  • python语法-类型注解

    python语法 类型注解 类型注解 在代码中涉及数据交互的地方 提供数据类型的注解 显式说明 主要功能 帮助第三方IDE工具 如pycharm 对代码进行类型推断 协助做代码提示 帮助开发者自身对变量进行类型注释 支持 变量的类型注解 函
  • 如何安装wsl以及安装时遇到的一些问题

    首先我安装wsl是参考这篇文章 Windows安装WSL详解 讲得挺具体 如果安装过程一切顺利就可以跳过下面的内容了 wsl在终端安装遇到的问题 当我在终端输入wsl install 返回了一列数据 但显然不是安装成功 于是我输入wsl i
  • document onload和window onload的区别?

    答 Document onload 是在结构和样式加载完成才执行的JS Window onload 不仅仅要在结构和样式加载完 还要执行完所有的样式 图片这些资源文件 完全加载完才会触发Window onload事件
  • Oracle SQL查询之Like使用正则表达式

    select from si0001 temp a where regexp like a xm a z A Z 查询xm字段带有英文的数据
  • 2019年第十届蓝桥杯国赛B组试题G-排列数-next_permutation枚举,模拟

    在一个排列中 一个折点是指排列中的一个元素 它同时小于两边的元素 或者同时大于两边的元素 对于一个 1 n 的排列 如果可以将这个排列中包含 t个折点 则它称为一个 t 1 单调序列 例如 排列 1 4 2 3 是一个 3 单调序列 其中
  • Mapreduce学习基础

    一 Mapreduce的基础 1 1 为什么要学习Mapreduce 1 单机资源受限 比如CPU 磁盘 2 分布式计算的程序的复杂度特别高 难度大 mapreduce就是解决以上问题的 1 利用集群的所有cpu 所有内存 所有磁盘 2 m
  • 【TCP/IP】第四章 IP协议

    4 1 即网际协议 TCP IP的心脏是互联网层 这一层主要是由IP Internet Protocol 和ICMP Internet Control Message Protocol 两个协议组成 IP相当于OSI参考模型的第3层 IP
  • 06-TensorFlow 自制数据集

    1 数据文件介绍 数据集下载 https download csdn net download qq 41865229 85254826 训练集60000张数字图片 测试集10000张图片 都是黑底白字的灰度图 每张图有28行28列个像素点
  • c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)

    首先定义数据库操作的标准接口IDBAccess 定义接口的基本功能 通过基本的接口设置 完成数据访问的统一抽象 public interface IDBAccess void Init string strServer string str
  • android编译时报错:Error parsing XML: unbound prefix 的错误原因及解决方案

    原因之一 拼写错误 例如 android写成androd之类 原因之二 xmlns没有添加 有的时候 自定了一些view 且新加了一些自定义的命名 那么需要添加声明到根上 如果忘了添加也会报这个错误 xmlns calendar http
  • javacv 人脸检测_使用JavaCV进行手和手指检测

    javacv 人脸检测 这篇文章是Andrew Davison博士发布的有关自然用户界面 NUI 系列的一部分 内容涉及使用JavaCV从网络摄像头视频提要中检测手 注意 本章的所有源代码都可以从http fivedots coe psu
  • 抖音微信消息推送情侣告白浪漫(简易版)

    抖音微信消息推送情侣告白浪漫 简易版 一 首先去微信公众平台用微信扫码登录 登录后会自动生成属于自己的appId appSecret 二 在上述登录后页面中下拉 用一个手机扫码会生成user id 即微信消息推送的接收方 三 点击下方的新增
  • PBR渲染原理

    PBR渲染原理 Tags computer graphics 基于PBR做渲染 需要涉及到很多物理学 几何学 热辐射学概念 本文将逐一介绍每个关键概念 并给出相关重要公式 微平面 microfacets 理论 微观尺度下的任意一个平面 su
  • bootstrap table 表头排序

    在columns 里面加上 sortable true 如下 columns field width 50 align center title sortable true
  • Calendar类介绍 获取对象方式 和方法

    重点 是一个抽象日历类 Calendar 类是一个抽象类 它为特定瞬间与一组诸如 YEAR MONTH DAY OF MONTH HOUR 等 日历字段之间的转换提供了一些方法 并为操作日历字段 例如获得下星期的日期 提供了一些方法 无法直
  • QML实现文件十六进制数据展示

    前言 将一个二进制文件直接拖放到Qt Creator中可以直接查看到以十六进制显示的数据格式 如 要实现一个这样的效果 还是要花不少时间的 在网上找了挺多示例 其中一个开源代码效果不错 参考这里 但是是在QWidget中实现的 通过继承QA
  • 小知识:随机生成26个字母中(一个或多个)的字母

    小知识 就直接上代码了 不多说 String str for int i 0 i lt 1 i str str char Math random 26 A 特别注意的2点 1 A 是随机生成大写的26个随机字母 2 a 是随机生成小写的26
  • LangChain之Output parsers

    LangChain之Output parsers Output parsers将LLM输出的文本 转换为structured data CommaSeparatedListOutputParser 解析结果为List 提示词如下 def g