自然语言处理从入门到应用——LangChain:记忆(Memory)-[聊天消息记录]

分类目录:《自然语言处理从入门到应用》总目录


Cassandra聊天消息记录

Cassandra是一种分布式数据库,非常适合存储大量数据,是存储聊天消息历史的良好选择,因为它易于扩展,能够处理大量写入操作。

# List of contact points to try connecting to Cassandra cluster.
contact_points = ["cassandra"]from langchain.memory import CassandraChatMessageHistorymessage_history = CassandraChatMessageHistory(contact_points=contact_points, session_id="test-session"
)message_history.add_user_message("hi!")message_history.add_ai_message("whats up?")
message_history.messages
[HumanMessage(content='hi!', additional_kwargs={}, example=False),
AIMessage(content='whats up?', additional_kwargs={}, example=False)]

DynamoDB聊天消息记录

首先确保我们已经正确配置了AWS CLI,并再确保我们已经安装了boto3。接下来,创建我们将存储消息 DynamoDB表:

import boto3# Get the service resource.
dynamodb = boto3.resource('dynamodb')# Create the DynamoDB table.
table = dynamodb.create_table(TableName='SessionTable',KeySchema=[{'AttributeName': 'SessionId','KeyType': 'HASH'}],AttributeDefinitions=[{'AttributeName': 'SessionId','AttributeType': 'S'}],BillingMode='PAY_PER_REQUEST',
)# Wait until the table exists.
table.meta.client.get_waiter('table_exists').wait(TableName='SessionTable')# Print out some data about the table.
print(table.item_count)

输出:

0
DynamoDBChatMessageHistory
from langchain.memory.chat_message_histories import DynamoDBChatMessageHistoryhistory = DynamoDBChatMessageHistory(table_name="SessionTable", session_id="0")
history.add_user_message("hi!")
history.add_ai_message("whats up?")
history.messages

输出:

[HumanMessage(content='hi!', additional_kwargs={}, example=False),
AIMessage(content='whats up?', additional_kwargs={}, example=False)]
使用自定义端点URL的DynamoDBChatMessageHistory

有时候在连接到AWS端点时指定URL非常有用,比如在本地使用Localstack进行开发。对于这种情况,我们可以通过构造函数中的endpoint_url参数来指定URL。

from langchain.memory.chat_message_histories import DynamoDBChatMessageHistoryhistory = DynamoDBChatMessageHistory(table_name="SessionTable", session_id="0", endpoint_url="http://localhost.localstack.cloud:4566")
Agent with DynamoDB Memory
from langchain.agents import Tool
from langchain.memory import ConversationBufferMemory
from langchain.chat_models import ChatOpenAI
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.utilities import PythonREPL
from getpass import getpassmessage_history = DynamoDBChatMessageHistory(table_name="SessionTable", session_id="1")
memory = ConversationBufferMemory(memory_key="chat_history", chat_memory=message_history, return_messages=True)
python_repl = PythonREPL()# You can create the tool to pass to an agent
tools = [Tool(name="python_repl",description="A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.",func=python_repl.run
)]
llm=ChatOpenAI(temperature=0)
agent_chain = initialize_agent(tools, llm, agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory)
agent_chain.run(input="Hello!")

日志输出:

> Entering new AgentExecutor chain...
{"action": "Final Answer","action_input": "Hello! How can I assist you today?"
}> Finished chain.

输出:

'Hello! How can I assist you today?'

输入:

agent_chain.run(input="Who owns Twitter?")

日志输出:

> Entering new AgentExecutor chain...
{"action": "python_repl","action_input": "import requests\nfrom bs4 import BeautifulSoup\n\nurl = 'https://en.wikipedia.org/wiki/Twitter'\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.content, 'html.parser')\nowner = soup.find('th', text='Owner').find_next_sibling('td').text.strip()\nprint(owner)"
}
Observation: X Corp. (2023–present)Twitter, Inc. (2006–2023)Thought:{"action": "Final Answer","action_input": "X Corp. (2023–present)Twitter, Inc. (2006–2023)"
}> Finished chain.

输出:

'X Corp. (2023–present)Twitter, Inc. (2006–2023)'

输入:

agent_chain.run(input="My name is Bob.")

日志输出:

> Entering new AgentExecutor chain...
{"action": "Final Answer","action_input": "Hello Bob! How can I assist you today?"
}> Finished chain.

输出:

  'Hello Bob! How can I assist you today?'

输入:

agent_chain.run(input="Who am I?")

日志输出:

> Entering new AgentExecutor chain...
{"action": "Final Answer","action_input": "Your name is Bob."
}> Finished chain.

输出:

'Your name is Bob.'

Momento聊天消息记录

本节介绍如何使用Momento Cache来存储聊天消息记录,我们会使用MomentoChatMessageHistory类。需要注意的是,默认情况下,如果不存在具有给定名称的缓存,我们将创建一个新的缓存。我们需要获得一个Momento授权令牌才能使用这个类。这可以直接通过将其传递给momento.CacheClient实例化,作为MomentoChatMessageHistory.from_client_params的命名参数auth_token,或者可以将其设置为环境变量MOMENTO_AUTH_TOKEN

from datetime import timedelta
from langchain.memory import MomentoChatMessageHistorysession_id = "foo"
cache_name = "langchain"
ttl = timedelta(days=1)
history = MomentoChatMessageHistory.from_client_params(session_id, cache_name,ttl,
)history.add_user_message("hi!")history.add_ai_message("whats up?")
history.messages

输出:

[HumanMessage(content='hi!', additional_kwargs={}, example=False),
AIMessage(content='whats up?', additional_kwargs={}, example=False)]

MongoDB聊天消息记录

本节介绍如何使用MongoDB存储聊天消息记录。MongoDB是一个开放源代码的跨平台文档导向数据库程序。它被归类为NoSQL数据库程序,使用类似JSON的文档,并且支持可选的模式。MongoDB由MongoDB Inc.开发,并在服务器端公共许可证(SSPL)下许可。

# Provide the connection string to connect to the MongoDB database
connection_string = "mongodb://mongo_user:password123@mongo:27017"
from langchain.memory import MongoDBChatMessageHistorymessage_history = MongoDBChatMessageHistory(connection_string=connection_string, session_id="test-session")message_history.add_user_message("hi!")message_history.add_ai_message("whats up?")
message_history.messages

输出:

[HumanMessage(content='hi!', additional_kwargs={}, example=False),
AIMessage(content='whats up?', additional_kwargs={}, example=False)]

Postgres聊天消息历史记录

本节介绍了如何使用 Postgres 来存储聊天消息历史记录。

from langchain.memory import PostgresChatMessageHistoryhistory = PostgresChatMessageHistory(connection_string="postgresql://postgres:mypassword@localhost/chat_history", session_id="foo")history.add_user_message("hi!")history.add_ai_message("whats up?")
history.messages

Redis聊天消息历史记录

本节介绍了如何使用Redis来存储聊天消息历史记录。

from langchain.memory import RedisChatMessageHistoryhistory = RedisChatMessageHistory("foo")history.add_user_message("hi!")
history.add_ai_message("whats up?")
history.messages

输出:

[AIMessage(content='whats up?', additional_kwargs={}),
HumanMessage(content='hi!', additional_kwargs={})]

参考文献:
[1] LangChain官方网站:https://www.langchain.com/
[2] LangChain 🦜️🔗 中文网,跟着LangChain一起学LLM/GPT开发:https://www.langchain.com.cn/
[3] LangChain中文网 - LangChain 是一个用于开发由语言模型驱动的应用程序的框架:http://www.cnlangchain.com/

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

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

相关文章

Android 学习笔记:SharedPreferences实现数据的保存和读取

一、概述 1.键值对方式存储 SharedPreferences 是使用键值对的方式来存储数据的。也就是说,当保存一条数据的时候,需要给这条数据提供一个对应的键,这样在读取数据的时候就可以通过这个键把相应的值取出来。 2.支持多种不同的数据类型存储…

使用Vue和jsmind如何实现思维导图的历史版本控制和撤销/重做功能?

思维导图是一种流行的知识图谱工具,可以帮助我们更好地组织和理解复杂的思维关系。在开发基于Vue的思维导图应用时,实现历史版本控制和撤销/重做功能是非常有用的。以下为您介绍如何使用Vue和jsmind插件来实现这些功能。 安装依赖 首先,我们…

day-17 代码随想录算法训练营(19)二叉树 part04

110.平衡二叉树 分析:判断每个节点的左右子树的高度差小于等于1;所以首先需要求左右子树高度,再在父节点进行判断,故此采用后序遍历。 思路:后序遍历二叉树,从底部递归回来时加上高度 class Solution { …

【管理运筹学】第 5 章 | 整数规划 (1,问题提出与分支定界法)

文章目录 引言一、整数规划问题的提出1.1 整数规划的数学模型1.2 整数规划问题的求解 二、分支定界法2.1 分支与定界2.2 基本求解步骤(一)初始化(二)分支与分支树(三)定界与剪枝(四)…

SpringBoot之HandlerInterceptor拦截器的使用

😀前言 本篇博文是关于拦截器-HandlerInterceptor的使用,希望你能够喜欢 🏠个人主页:晨犀主页 🧑个人简介:大家好,我是晨犀,希望我的文章可以帮助到大家,您的满意是我的动…

SQL 复习 03

函数与关键字 用法说明round(x, n)四舍五入,x为浮点数,n为保留的位数ceil(x)向上取整floor(x)向下取整truncate(x, n)截断x,n为保留的位,该位之后的数值置零,位数表示示例:321.123,其中小数点前…

Linux 多进程

目录 0x01 linux中特殊的进程 0x02 进程的标识 0x03 创建子进程 0x01 linux中特殊的进程 0号进程:idle进程,系统启动加载的进程1号进程:systemd进程,系统初始化,是所有进程的祖先进程 init2号进程:kthre…

YOLOv5白皮书-第Y6周:模型改进

📌本周任务:模型改进📌 注:对yolov5l.yaml文件中的backbone模块和head模块进行改进。 任务结构图: YOLOv5s网络结构图: 原始模型代码: # YOLOv5 v6.0 backbone backbone:# [from, number, module, args]…

每日汇评:黄金在 200 日移动平均线附近似乎很脆弱,关注美国零售销售

1、金价预计将巩固其近期跌势,至 6 月初以来的最低水平; 2、对美联储再次加息的押注继续限制了贵金属的上涨; 3、金融市场现在期待美国零售销售报告带来一些有意义的推动; 周二金价难以获得任何有意义的牵引力,并在…

Mac RN环境搭建

IOS RN ios android原生环境搭建有时候是真恶心,电脑环境不一样配置也有差异。 我已经安装官网的文档配置了ios环境 执行 npx react-nativelatest init AwesomeProject 报错 然后自己百度查呀执行 gem update --system 说是没有权限,执行失败。因…

POSTGRESQL 关于安装中自动启动的问题 详解

开头还是介绍一下群,如果感兴趣Polardb ,mongodb ,MySQL ,Postgresql ,redis ,SQL SERVER ,ORACLE,Oceanbase 等有问题,有需求都可以加群群内有各大数据库行业大咖,CTO,可以解决你的问题。加群请加 liuaustin3微信号 &…

OpenSSH 远程升级到 9.4p1

OpenSSH 远程升级到 9.4p1 文章目录 OpenSSH 远程升级到 9.4p1背景升级前提1. 升级 OpenSSL2. 安装并启用Telnet 升级OpenSSH 背景 最近的护网行动,被查出来了好几个关于OpenSSH 的漏洞。这是因为服务器系统安装后,直接使用了系统自带版本的OpenSSH &am…

2023-08-15 linux mipi 屏幕调试:有一个屏幕开机时候不显示,开机后按power 按键休眠唤醒就可以显示。原因是reset gpio 被复用

一、现象:今天更新了一个新版本的buildroot linux sdk ,调试两个mipi 屏幕,这两个屏幕之前在其他的sdk都调好了的,所有直接把配置搬过来。但是有一个屏幕可以正常显示,有一个屏幕开机时候不显示,开机后按po…

CentOS防火墙操作:开启端口、开启、关闭、配置

一、基本使用 启动: systemctl start firewalld 关闭: systemctl stop firewalld 查看状态: systemctl status firewalld 开机禁用 : systemctl disable firewalld 开机启用 : systemctl enable firewalld systemctl是…

angular注入方法providers

在Angular中有很多方式可以将服务类注册到注入器中: Injectable 元数据中的providedIn属性 NgModule 元数据中的 providers属性 Component 元数据中的 providers属性 创建一个文件名叫名 hero.service.ts叫 hero 的服务 hero.service.ts import { Injectable } from angular…

C语言,结构体,结构体大小,

1、结构体: 用于存储不同数据类型的多个相关变量,从而形成一个具有独立性的组合数据类型。 结构体的声明: struct 结构体类型名{ 数据类型 成员1; 数据类型 成员2; 数据类型 成员3; ……… }&#xff1…

转行软件测试四个月学习,第一次面试经过分享

我是去年上半年从销售行业转行到测试的,从销售公司辞职之后选择去培训班培训软件测试,经历了四个月左右的培训,在培训班结课前两周就开始投简历了,在结课的时候顺利拿到了offer。在新的公司从事软件测试工作已经将近半年有余&…

深信服数据中心管理系统 XXE漏洞复现

0x01 产品简介 深信服数据中心管理系统DC为AC的外置数据中心,主要用于海量日志数据的异地扩展备份管理,多条件组合的高效查询,统计和趋势报表生成,设备运行状态监控等功能。 0x02 漏洞概述 深信服数据中心管理系统DC存在XML外部实…

WPS-0DAY-20230809的分析和利用复现

WPS-0DAY-20230809的分析和初步复现 一、漏洞学习1、本地复现环境过程 2、代码解析1.htmlexp.py 3、通过修改shellcode拿shell曲折的学习msf生成sc 二、疑点1、问题2、我的测试测试方法测试结果 一、漏洞学习 强调:以下内容仅供学习和测试,一切行为均在…

Keil开发STM32单片机项目的三种方式

STM32单片机相比51单片机,内部结构复杂很多,因此直接对底层寄存器编码,相对复杂,这个需要我们了解芯片手册,对于复杂项目,这些操作可能需要反复编写,因此出现了标准库的方式,对寄存器…