Langchain使用介绍之outparser 和memory

  上一篇博客中对Langchain中prompt进行了详细的介绍,此篇博客将介绍Langchain中的outparser和memory。当调用大模型生成内容时,返回的内容默认是string类型,这对于我们获取response中的某些内容信息可能会带来障碍,例如返回的内容本身是json string内容,如果能返回json对象的话,那么获取response中某个对象的值就更加容易,那么如何通过Langchain提供的能力,将输出的内容转换成JSON类型呢?来看看下面的例子。

import openai
import os
from langchain.prompts import (HumanMessagePromptTemplate, SystemMessagePromptTemplate, ChatPromptTemplate)
from langchain.chat_models import ChatOpenAI
from langchain.output_parsers import ResponseSchema
from langchain.output_parsers import StructuredOutputParseropenai.api_key = os.environ.get("OPEN_AI_KEY")customer_review = """\
This leaf blower is pretty amazing.  It has four settings:\
candle blower, gentle breeze, windy city, and tornado. \
It arrived in two days, just in time for my wife's \
anniversary present. \
I think my wife liked it so much she was speechless. \
So far I've been the only one using it, and I've been \
using it every other morning to clear the leaves on our lawn. \
It's slightly more expensive than the other leaf blowers \
out there, but I think it's worth it for the extra features.
"""
review_template = """\
For the following text, extract the following information:gift: Was the item purchased as a gift for someone else? \
Answer True if yes, False if not or unknown.delivery_days: How many days did it take for the product\
to arrive? If this information is not found, output -1.price_value: Extract any sentences about the value or price,\
and output them as a comma separated Python list.text: {text}
"""
human_template_message = HumanMessagePromptTemplate.from_template(review_template)
chat_template = ChatPromptTemplate.from_messages([human_template_message])
message = chat_template.format_messages(text=customer_review)
chat = ChatOpenAI(model_name="gpt-3.5-turbo")
response = chat(message)
print(response.content)

  上面的代码生成的结果如下图所示,从一段文本中提取出了gift,delivery_days和price_value.但是因为不是JSON对象,所以,如果要获取提取出来的某个值是不行的。

  如果想输出JSON格式的数据,应该如何处理呢?首先在prompt增加了{formact_instruction},通过langchain提供的ResponseSchema定义要提取的字段名称,描述信息;接着通过StructureOutputParser生成parser,再调用parser的get_format_instruction方法生成format_instruction.

review_template_2 = """\
For the following text, extract the following information:gift: Was the item purchased as a gift for someone else? \
Answer True if yes, False if not or unknown.delivery_days: How many days did it take for the product\
to arrive? If this information is not found, output -1.price_value: Extract any sentences about the value or price,\
and output them as a comma separated Python list.text: {text}{format_instructions}
"""gift_schema = ResponseSchema(name="gift",description="Was the item purchased\as a gift for someone else? \Answer True if yes,\False if not or unknown.")delivery_days_schema = ResponseSchema(name="delivery_days",description="How many days\did it take for the product\to arrive? If this \information is not found,\output -1.")price_value_schema = ResponseSchema(name="price_value",description="Extract any\sentences about the value or \price, and output them as a \comma separated Python list.")response_schema = [gift_schema, delivery_days_schema, price_value_schema]
out_parser = StructuredOutputParser.from_response_schemas(response_schema)
format_instruction = out_parser.get_format_instructions()
# print(format_instrucation)human_prompt = HumanMessagePromptTemplate.from_template(review_template_2)
chat_prompt = ChatPromptTemplate.from_messages([human_prompt])
message = chat_prompt.format_messages(text=customer_review, format_instructions=format_instruction)
chat = ChatOpenAI(model_name="gpt-3.5-turbo")
response = chat(message)
print(type(response.content))
result = out_parser.parse(response.content)
print(result)
print(result.get('delivery_days'))

  生成的format_instruction如下所示,可以看到实际是一个包含字段名称以及字段类型说明的json对象。

  执行完上面的整体代码,结果如下图所示,可以看到返回的是一个json对象,可以单独打印比如delivery_days的值。

  以上就是如何让输出的内容是JSON对象的实现说明。

  当使用 LangChain 中的储存(Memory)模块时,它可以帮助保存和管理历史聊天消息,以及构建关于特定实体的知识。这些组件可以跨多轮对话储存信息,并允许在对话期间跟踪特定信息和上下文。LangChain 提供了多种储存类型。其中,缓冲区储存允许保留最近的聊天消息,摘要储存则提供了对整个对话的摘要。实体储存 则允许在多轮对话中保留有关特定实体的信息。这些记忆组件都是模块化的,可与其他组件组合使用,从而增强机器人的对话管理能力。储存模块可以通过简单的API调用来访问和更新,允许开发人员更轻松地实现对话历史记录的管理和维护。接下来主要介绍四种类型的Memory,具体如下所示:

  • 对话缓存储存 (ConversationBufferMemory)
  • 对话缓存窗口储存 (ConversationBufferWindowMemory)
  • 对话令牌缓存储存 (ConversationTokenBufferMemory)
  • 对话摘要缓存储存 (ConversationSummaryBufferMemory)
import openai
import os
from langchain.chains import ConversationChain
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.prompts import (SystemMessagePromptTemplate, HumanMessagePromptTemplate, ChatPromptTemplate, ChatMessagePromptTemplate)openai.api_key = os.environ.get("OPENAI_API_KEY")model = ChatOpenAI(model_name="gpt-3.5-turbo")
memory = ConversationBufferMemory()
chat = ConversationChain(llm=model, memory=memory, verbose=True)
chat.predict(input="HI, my name is taoli?")
chat.predict(input="What is 1+1?")
chat.predict(input="what is my name?")
print(memory.buffer)

上面的代码使用ConversationBufferMemory来记录整个历史对话,打印memory.buffer的值,结果如下所示:可以看到当第三个问题问AI,what is my name时,AI可以正确回答,应为Memory中存入了整个对话History信息。

  除了在ConversationChain中增加memory对象对memory赋值外,实际也可以对memory对象直接调用save_context()进行赋值,input就是human的输入,output模拟AI的返回。

memoryTwo = ConversationBufferMemory()
memoryTwo.save_context({'input': 'Hi I came from china'}, {'output': 'china is beatiful'})
memoryTwo.save_context({"input": "what is your name"}, {"output": "my name is chatbot"})
print(memoryTwo.buffer)
print(memoryTwo.load_memory_variables({}))

  打印的信息如下图所示,buffer中的信息和ConversionChain生成的一样,调用load_memory_variables({})方法,把整个对话信息连接起来,赋值给history变量。

  如果把所有的history都记录下来,那么每次传入给LLM的文字太多,token消耗很大,所以,langchain还提供了ConversationBufferWindowMemory,通过定义窗口大小,即K的值来控制记录最新的K轮对话历史信息。memory = ConversationBufferWindowMemory(k=1)。

  如果是有大量的文字描述内容,为了节省token以及保证单次对话的token不要超过限制,那么还可以使用ConversationSummaryBufferMemory,使用方式上和ConversationBufferMemory相同。以上就是对Langchain提供的memory的使用介绍。

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

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

相关文章

005_C++数学库常用函数

数学库常用函数 函数 我们其实已经掌握了一些函数&#xff0c;比如主函数main()。还有其他的函数比如一些库中的函数&#xff0c;例&#xff1a;<stdio.h>头文件对应标准输入输出库中的printf()和scanf()、<stdlib.h>标准库头文件对应的标准库中的srand()和rand(…

抽象类实现接口的意义

文章目录 前言一、抽象类和接口对比二、举例说明三种情况1.接口实现类接口 2.抽象类实现类抽象类实现类(子类) 3.抽象类实现接口接口抽象类三个实现类 总结 前言 抽象类和接口其实都是抽象的一种,那么他俩有何异同呢? 抽象类实现接口的意义何在? 一、抽象类和接口对比 接口…

MyBatis中至关重要的关系映射----全方面介绍

目录 一 对于映射的概念 1.1 三种关系映射 1.2 resultType与resultMap的区别 resultType&#xff1a; resultMap&#xff1a; 二&#xff0c;一对一关联查询 2.1 嵌套结果集编写 2.2 案例演示 三&#xff0c;一对多关联查询 3.1 嵌套结果集编写 3.3 案例演示 四&…

统计教程|PASS实现两计量指标的的Pearson相关分析时的样本量估计

在临床研究中我们经常会研究两个观察指标间是否有联系&#xff0c;如人的身高与体重、体温与脉搏次数、药物剂量与反应等&#xff0c;相关分析就是研究观察指标间相关关系的统计方法&#xff0c;由于不同资料类型其分析方法有所差异&#xff0c;故本节主要讲解的是定量资料的线…

综合实训-------成绩管理系统 V1.1

综合实训-------成绩管理系统 V1.1 1、一维数组数据double 2、我们用元素的位置来当学号。 1、录入数据 【5个数据】或【通过文件的方式取数据】 2、显示数据 3、添加一条记录 4、修改一条记录 5、删除一条记录 6、查找一条记录。【输入学号&#xff0c;显示成绩】 7、统计。【…

使用Python进行Base64编码和解码

假设您有一个想要通过网络传输的二进制图像文件。您很惊讶对方没有正确接收该文件 - 该文件只是包含奇怪的字符&#xff01; 嗯&#xff0c;您似乎试图以原始位和字节格式发送文件&#xff0c;而所使用的媒体是为流文本而设计的。 避免此类问题的解决方法是什么&#xff1f;答…

说说你了解的 Nginx

分析&回答 nginx性能数据 高并发连接: 官方称单节点支持5万并发连接数&#xff0c;实际生产环境能够承受2-3万并发。内存消耗少: 在3万并发连接下&#xff0c;开启10个nginx进程仅消耗150M内存 (15M10150M) 1. 正向、反向代理 所谓“代理”&#xff0c;是指在内网边缘 …

C++信息学奥赛1177:奇数单增序列

#include<bits/stdc.h> using namespace std; int main(){int n;cin>>n; // 输入整数 n&#xff0c;表示数组的大小int arr[n]; // 创建大小为 n 的整型数组for(int i0;i<n;i) cin>>arr[i]; // 输入数组元素for(int i0;i<n;i){ // 对数组进行冒泡排序f…

uniapp-秋云图表 ucharts echarts 对比与关系

科普&#xff1a; 秋云图表库&#xff0c;包含二种配置属性对应二种js配置文件。 一种是 &#xff1a;echarts.js,一种是 &#xff1a; ucharts。 二者的配置属性不一样&#xff01; ucharts和echarts对比 ucharts和echarts都是用于数据可视化的开源JavaScript库&#xff0c;它…

gRPC-Gateway 快速实战

今天来分享一波 gRPC-Gateway &#xff0c; 之前咱们有分享过什么是 gRPC 及其使用方式&#xff0c;可以看看这些关于 gRPC 的历史文章&#xff1a; gRPC介绍 gRPC 客户端调用服务端需要连接池吗&#xff1f; gRPC的拦截器 gRPC的认证 分享一下 gRPC- HTTP网关 I 今天主要是分…

Python学习教程:进程的调度

前言 嗨喽~大家好呀&#xff0c;这里是魔王呐 ❤ ~! 要想多个进程交替运行&#xff0c;操作系统必须对这些进程进行调度&#xff0c; 这个调度也不是随即进行的&#xff0c;而是需要遵循一定的法则&#xff0c;由此就有了进程的调度算法。 python更多源码/资料/解答/教程等 …

keepalived 主备都存在vip, keepalived主备跨网段配置;keepalived主备服务器不在同一个网段怎么配置

keepalived 主备都有vip问题&#xff1b;主备服务器不在同一个网段怎么配置 主机&#xff1a;128.192.10.10 备机&#xff1a;128.192.11.11 备机&#xff1a;128.192.22.22 # keepalived的配置文件增加如下配置即可实现 # 主机&#xff1a;128.192.10.10 vrrp_instance VI_1 {…

VB工资管理系统设计与实现

摘 要 工资管理系统是典型的管理信息系统,采用计算机管理企业的工资发放是当前不可缺少的一种管理手段。其开发主要包括后台数据库的建立和维护以及前端应用程序的开发两个方面。对于前者要求建立起数据一致性和完整性强,数据安全性好的数据库。而对于后者则要求应用程序功能…

uni-app 之 安装uView,安装scss/sass编译

uni-app 之 安装uView&#xff0c;安装scss/sass编译 image.png image.png image.png 点击HBuilder X 顶部&#xff0c;工具&#xff0c;插件安装&#xff0c;安装新插件 image.png image.png 安装成功&#xff01; 注意&#xff0c;一定要先登录才可以安装 image.png 1. 引…

【python】—— 函数详解

前言&#xff1a; 本期&#xff0c;我们将要讲解的是有关python中函数的相关知识&#xff01;&#xff01;&#xff01; 目录 &#xff08;一&#xff09;函数是什么 &#xff08;二&#xff09;语法格式 &#xff08;三&#xff09;函数参数 &#xff08;四&#xff09;函…

webpack实战:某网站JS逆向分析

文章目录 1. 写在前面2. 抓包分析3. 扣加密代码 1. 写在前面 好的逆向能够帮助我们了解加密实现&#xff0c;然后根据加密方式&#xff08;md5,base64,res,des,rsa…)还原加密算法的过程。可以看看我之前的这篇文章&#xff1a;快速定位查找加密方式特征与技巧 目标站点&#…

什么是rem单位和em单位?它们有什么区别?

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ rem 和 em 单位⭐ rem 单位&#xff08;Root Em&#xff09;⭐ em 单位⭐ 区别总结⭐ 写在最后 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 记得点击上方或者右侧链接订阅本专栏哦 几何带你启航前端之旅 欢迎来到前端入…

java八股文面试[多线程]——newWorkStealingPool

newWorkStealingPool是什么&#xff1f; newWorkStealingPool简单翻译是任务窃取线程池。 newWorkStealingPool 是Java8添加的线程池。和别的4种不同&#xff0c;它用的是ForkJoinPool。 使用ForkJoinPool的好处是&#xff0c;把1个任务拆分成多个“小任务”&#xff0c;把这…

UDP 广播

一、UDP 通信图解 UDP通信、本地套接字_呵呵哒(&#xffe3;▽&#xffe3;)"的博客-CSDN博客https://blog.csdn.net/weixin_41987016/article/details/132523536?spm1001.2014.3001.5501 #include <sys/types.h> #include <sys/socket > ssize_t sendto(in…

hadoop学习:mapreduce的wordcount时候,继承mapper没有对应的mapreduce的包

踩坑描述&#xff1a;在学习 hadoop 的时候使用hadoop 下的 mapreduce&#xff0c;却发现没有 mapreduce。 第一反应就是去看看 maven 的路径对不对 settings——》搜索框搜索 maven 检查一下 Maven 路径对不对 OK 这里是对的 那么是不是依赖下载失败导致 mapreduce 没下下…