LangChain - Output Parsers

news/2024/5/2 7:01:58/文章来源:https://blog.csdn.net/lovechris00/article/details/137507411

文章目录

    • 一、输出解析器 (Output Parsers)
      • 快速入门
    • 二、列表解析器
    • 三、datetime 日期时间解析器
    • 四、枚举解析器
    • 五、自动修复解析器
    • 六、Pydantic(JSON)解析器
    • 七、重试解析器
    • 八、结构化输出解析器 structured


转载改编自:
https://python.langchain.com.cn/docs/modules/model_io/output_parsers/


一、输出解析器 (Output Parsers)

语言模型输出文本,但很多时候希望获得 比仅文本更结构化的信息。这就是输出解析器的作用。

输出解析器是帮助 结构化语言模型响应的类。一个输出解析器必须实现两个主要方法:

  • “获取格式化指令”: 一个返回包含语言模型输出 应如何格式化的字符串的方法。
  • “解析”: 一个接受字符串(假设为语言模型的响应)并将其解析为某种结构的方法。

然后再加一个可选的方法:

  • “带提示解析”: 一个接受字符串(假设为语言模型的响应)和提示(假设为生成此响应的提示)并将其解析为某种结构的方法。
    在需要从提示中获取信息以重试或修复输出的情况下,通常提供提示。

快速入门

下面我们来介绍主要类型的输出解析器,PydanticOutputParser

from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAIfrom langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field, validator
from typing import List

model_name = 'text-davinci-003'
temperature = 0.0
model = OpenAI(model_name=model_name, temperature=temperature)

# Define your desired data structure.
class Joke(BaseModel):setup: str = Field(description="question to set up a joke")punchline: str = Field(description="answer to resolve the joke")# You can add custom validation logic easily with Pydantic.@validator('setup')def question_ends_with_question_mark(cls, field):if field[-1] != '?':raise ValueError("Badly formed question!")return field

# Set up a parser + inject instructions into the prompt template.
parser = PydanticOutputParser(pydantic_object=Joke)

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

# And a query intented to prompt a language model to populate the data structure.
joke_query = "Tell me a joke."
_input = prompt.format_prompt(query=joke_query)

output = model(_input.to_string())
parser.parse(output)
# ->    Joke(setup='Why did the chicken cross the road?', punchline='To get to the other side!')

二、列表解析器

当您想要返回逗号分隔的项目列表时,可以使用此输出解析器。

from langchain.output_parsers import CommaSeparatedListOutputParser
from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAIoutput_parser = CommaSeparatedListOutputParser()

format_instructions = output_parser.get_format_instructions()
prompt = PromptTemplate(template="List five {subject}.\n{format_instructions}",input_variables=["subject"],partial_variables={"format_instructions": format_instructions}
)

model = OpenAI(temperature=0)
_input = prompt.format(subject="ice cream flavors")
output = model(_input)
output_parser.parse(output)

    ['Vanilla','Chocolate','Strawberry','Mint Chocolate Chip','Cookies and Cream']

三、datetime 日期时间解析器

该输出解析器演示如何将LLM输出解析为日期时间格式。

from langchain.prompts import PromptTemplate
from langchain.output_parsers import DatetimeOutputParser
from langchain.chains import LLMChain
from langchain.llms import OpenAI

output_parser = DatetimeOutputParser()
template = """Answer the users question:{question}{format_instructions}"""
prompt = PromptTemplate.from_template(template,partial_variables={"format_instructions": output_parser.get_format_instructions()},
)

chain = LLMChain(prompt=prompt, llm=OpenAI())
output = chain.run("around when was bitcoin founded?")# output -> '\n\n2008-01-03T18:15:05.000000Z'

output_parser.parse(output)
# -> datetime.datetime(2008, 1, 3, 18, 15, 5)

四、枚举解析器

本笔记本演示如何使用枚举输出解析器。

from langchain.output_parsers.enum import EnumOutputParser

from enum import Enumclass Colors(Enum):RED = "red"GREEN = "green"BLUE = "blue"

parser = EnumOutputParser(enum=Colors)
parser.parse("red")
# -> <Colors.RED: 'red'>

# Can handle spaces
parser.parse(" green")
# -> <Colors.GREEN: 'green'>

# And new lines
parser.parse("blue\n")
# -> <Colors.BLUE: 'blue'>

# And raises errors when appropriate
parser.parse("yellow") 

五、自动修复解析器

该输出解析器包装了另一个输出解析器,并在第一个解析器失败时 调用另一个LLM来修复任何错误。

但是我们除了抛出错误之外,还可以做其他事情。

具体来说,我们可以将格式错误的输出以及格式化的指令一起传递给模型,并要求它进行修复。


六、Pydantic(JSON)解析器

该输出解析器允许用户指定任意的JSON模式,并查询符合该模式的JSON输出。

请记住,大型语言模型是有漏洞的抽象!您必须使用具有足够容量的LLM来生成格式正确的JSON。在OpenAI家族中,DaVinci的能力可靠,但Curie的能力已经大幅下降。

使用Pydantic来声明您的数据模型。Pydantic的BaseModel类似于Python的数据类,但具有真正的类型检查和强制转换功能。

from langchain.prompts import (PromptTemplate,ChatPromptTemplate,HumanMessagePromptTemplate,
)
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAIfrom langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field, validator
from typing import List

model_name = "text-davinci-003"
temperature = 0.0
model = OpenAI(model_name=model_name, temperature=temperature)

# Define your desired data structure.
class Joke(BaseModel):setup: str = Field(description="question to set up a joke")punchline: str = Field(description="answer to resolve the joke")# You can add custom validation logic easily with Pydantic.@validator("setup")def question_ends_with_question_mark(cls, field):if field[-1] != "?":raise ValueError("Badly formed question!")return field# And a query intented to prompt a language model to populate the data structure.
joke_query = "Tell me a joke."# Set up a parser + inject instructions into the prompt template.
parser = PydanticOutputParser(pydantic_object=Joke)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=joke_query)output = model(_input.to_string())parser.parse(output)
# -> Joke(setup='Why did the chicken cross the road?', punchline='To get to the other side!')

# Here's another example, but with a compound typed field.
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)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)output = model(_input.to_string())parser.parse(output)
# -> Actor(name='Tom Hanks', film_names=['Forrest Gump', 'Saving Private Ryan', 'The Green Mile', 'Cast Away', 'Toy Story'])

七、重试解析器

在某些情况下,通过仅查看输出就可以修复任何解析错误,但在其他情况下,则不太可能。

一个例子是当输出不仅格式不正确,而且部分不完整时。请考虑下面的例子。

from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAIfrom langchain.prompts import (PromptTemplate,ChatPromptTemplate,HumanMessagePromptTemplate,
)
from langchain.output_parsers import (PydanticOutputParser,OutputFixingParser,RetryOutputParser,
)
from pydantic import BaseModel, Field, validator
from typing import List

template = """Based on the user question, provide an Action and Action Input for what step should be taken.
{format_instructions}
Question: {query}
Response:"""class Action(BaseModel):action: str = Field(description="action to take")action_input: str = Field(description="input to the action")parser = PydanticOutputParser(pydantic_object=Action)

prompt = PromptTemplate(template="Answer the user query.\n{format_instructions}\n{query}\n",input_variables=["query"],partial_variables={"format_instructions": parser.get_format_instructions()},
)prompt_value = prompt.format_prompt(query="who is leo di caprios gf?")
bad_response = '{"action": "search"}'

这个 response 无法 parse,或报错

parser.parse(bad_response)

八、结构化输出解析器 structured

当您想要返回多个字段时,可以使用此输出解析器。尽管 Pydantic/JSON 解析器更强大,但我们最初尝试的数据结构仅具有文本字段。

from langchain.output_parsers import StructuredOutputParser, ResponseSchema
from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI

这里我们定义了我们想要接收的响应模式。

response_schemas = [ResponseSchema(name="answer", description="answer to the user's question"),ResponseSchema(name="source", description="source used to answer the user's question, should be a website.")
]
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)

我们现在获得一个包含响应格式化指令的字符串,然后将其插入到我们的提示中。

format_instructions = output_parser.get_format_instructions()
prompt = PromptTemplate(template="answer the users question as best as possible.\n{format_instructions}\n{question}",input_variables=["question"],partial_variables={"format_instructions": format_instructions}
)

我们现在可以使用这个来格式化一个提示,发送给语言模型,然后解析返回的结果。

model = OpenAI(temperature=0)_input = prompt.format_prompt(question="what's the capital of france?")output = model(_input.to_string())output_parser.parse(output)

    {'answer': 'Paris','source': 'https://www.worldatlas.com/articles/what-is-the-capital-of-france.html'}

这里是一个在聊天模型中使用它的例子

chat_model = ChatOpenAI(temperature=0)

prompt = ChatPromptTemplate(messages=[HumanMessagePromptTemplate.from_template("answer the users question as best as possible.\n{format_instructions}\n{question}")  ],input_variables=["question"],partial_variables={"format_instructions": format_instructions}
)

_input = prompt.format_prompt(question="what's the capital of france?")output = chat_model(_input.to_messages())output_parser.parse(output.content)
# -> {'answer': 'Paris', 'source': 'https://en.wikipedia.org/wiki/Paris'}

2024-04-08(一)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_1046110.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

UDP实现Mini版在线聊天室

实现原理 只有当客户端先对服务器发送online消息的时候&#xff0c;服务器才会把客户端加入到在线列表。当在线列表的用户发消息的时候&#xff0c;服务器会把消息广播给在线列表中的所有用户。而当用户输入offline时&#xff0c;表明自己要下线了&#xff0c;此时服务器把该用…

MQ死信队列

面试题&#xff1a;你们是如何保证消息不丢失的&#xff1f; 1、什么是死信 在 RabbitMQ 中充当主角的就是消息&#xff0c;在不同场景下&#xff0c;消息会有不同地表现。 死信就是消息在特定场景下的一种表现形式&#xff0c;这些场景包括&#xff1a; 1. 消息被拒绝访问&…

Canal--->准备MySql主数据库---->安装canal

一、安装主数据库 1.在服务器新建文件夹 mysql/data&#xff0c;新建文件 mysql/conf.d/my.cnf 其中my.cnf 内容如下 [mysqld] log_timestampsSYSTEM default-time-zone8:00 server-id1 log-binmysql-bin binlog-do-db mall # 要监听的库 binlog_formatROW2.启动数据库 do…

数据库相关知识总结

一、数据库三级模式 三个抽象层次&#xff1a; 1. 视图层&#xff1a;最高层次的抽象&#xff0c;描述整个数据库的某个部分的数据 2. 逻辑层&#xff1a;描述数据库中存储的数据以及这些数据存在的关联 3. 物理层&#xff1a;最低层次的抽象&#xff0c;描述数据在存储器中时如…

Vue3 使用ElementUI 显示异常

element提供的样例不能正常显示&#xff0c;需要进行配置 1.npm install element-plus --save 2.main.js // main.ts import { createApp } from vue import ElementPlus from element-plus //全局引入 import element-plus/dist/index.css import App from ./App.vue const …

IOS手机耗电量测试

1. 耗电量原始测试方法 1.1 方法原理&#xff1a; 根据iPhone手机右上角的电池百分比变化来计算耗电量。 1.2实际操作&#xff1a; 在iOS通用设置中打开电池百分比数值显示&#xff0c;然后操作30分钟&#xff0c;60分钟&#xff0c;90分钟&#xff0c;看开始时和结束时电池…

漫画合集 下载教程

https://pan.xunlei.com/s/VNv9c-Bl3KF0Ir94-IdN4jfOA1?pwdfrwi# 复制打开

javaScript 事件循环 Event Loop

一、前言 javaScript 是单线程的编程语言&#xff0c;只能同一时间内做一件事情&#xff0c;按照顺序来处理事件&#xff0c;但是在遇到异步事件的时候&#xff0c;js线程并没有阻塞&#xff0c;还会继续执行&#xff0c;这又是为什么呢&#xff1f; 二、基础知识 堆&#x…

FPGA开源项目分享——基于 DE1-SOC 的 String Art 实现

导语 今天继续康奈尔大学FPGA课程ECE 5760的典型案例分享——基于DE1-SOC的String Art实现。 &#xff08;更多其他案例请参考网站&#xff1a; Final Projects ECE 5760&#xff09; 1. 项目概述 项目网址 ECE 5760 Final Project 项目说明 String Art起源于19世纪的数学…

【第十二篇】使用BurpSuite实现CSRF(实战案例)

CSRF存在前提:简单的身份验证只能保证请求是发自某个用户的浏览器,却不能保证请求本身是用户自愿发出的 业务场景:新增、删除、收藏、编辑、保存使用Burp发现CSRF漏洞的过程如下。 1、如图,存在修改邮箱的功能点如下: 2、修改邮箱的流量包,此时邮箱已被修改: 思路:是…

白盒测试-条件覆盖

​ 条件覆盖是指运行代码进行测试时&#xff0c;程序中所有判断语句中的条件取值为真值为假的情况都被覆盖到&#xff0c;即每个判断语句的所有条件取真值和假值的情况都至少被经历过一次。 ​ 条件覆盖率的计算方法为&#xff1a;测试时覆盖到的条件语句真、假情况的总数 / 程…

Redis群集模式和rsync远程同步

一、Redis群集模式 1.1 概念 1.2 作用 1.2.1 Redis集群的数据分片 1.2.2 Redis集群的主从复制模型 1.3 搭建Redis 群集模式 1.3.1 开启群集功能 1.3.2 启动redis节点 1.3.3 启动集群 1.3.4 测试群集 二、rsync远程同步 2.1 概念 2.2 同步方式 2.3 备份的方式 2.4…

机器学习实现文本分类

传统的向量空间模型&#xff08;VSM&#xff09;假设特征项之间相互独立&#xff0c;这与实际情况是不相符的&#xff0c;为了解决这个问题&#xff0c;可以采用文本的分布式表示方式(例如 word embedding形式)&#xff0c;通过文本的分布式表示&#xff0c;把文本表示成类似图…

C语言面试题之合法二叉搜索树

合法二叉搜索树 实例要求 实现一个函数&#xff0c;检查一棵二叉树是否为二叉搜索树&#xff1b; 示例 1: 输入:2/ \1 3 输出: true 示例 2: 输入:5/ \1 4/ \3 6 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。根节点的值为 5 &#xff0c;但是其右子节点值为 4 …

《QT实用小工具·十七》密钥生成工具

1、概述 源码放在文章末尾 该项目主要用于生成密钥&#xff0c;下面是demo演示&#xff1a; 项目部分代码如下&#xff1a; #pragma execution_character_set("utf-8")#include "frmmain.h" #include "ui_frmmain.h" #include "qmessag…

最新安卓iOS免签封装源码 可处理apk报毒

资源简介 解决app误报毒 可打包APP可上传APK 自动实现5分钟随机更换包名和签名系统源码 本程序功能介绍 程序可实现域名自动打包成app 出现误报毒并自动更换包名和签名时间一次 也可以上传打包好的apk*时间自动更换包名和签名 自动覆盖原下载路径&#xff0c;下载地址不变…

docker 安装canal

一、新建文件夹 新建文件夹logs, 新建文件canal.properties instance.properties docker.compose.yml canal.propertie 修改如下&#xff1a; 修改instance.properties内容如下 1.1 canal.properties ################################################# ######### …

java下载网络上的文件、图片保存到本地 FileUtils

java下载网络上的文件、图片保存到本地 FileUtils 1. 引入FileUtils依赖2. 实现代码3. 输出结果 1. 引入FileUtils依赖 <!--FileUtils依赖--> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency><groupId>commons-io&l…

【vue】watch监听取不到this指向的数?

今天同事问我&#xff0c;watch里this指向的数值&#xff0c;别的地方却可以打印出来。工具也能看到数值&#xff0c;但打印出来却是undifined&#xff0c;先看看代码&#xff1a; 懒得打字了直接上截图吧 ps&#xff1a; 在Vue组件中&#xff0c;如果你在watch选项中访问this…

PyCharm+PyQt5配置方法

一、前言 PyQt5PyQt5是一套Python绑定Digia QT5应用的框架。Qt库是最强大的GUI库之一PyQt5-toolsPyQt5中没有提供常用的Qt工具&#xff0c;比如图形界面开发工具Qt Designer&#xff0c;PyQt5-tools中包含了一系列常用工具Qt Designer可以通过Qt Designer来编写UI界面&#xf…