当前位置: 首页 > news >正文

自然语言处理从入门到应用——LangChain:模型(Models)-[大型语言模型(LLMs):缓存LLM的调用结果]

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


from langchain.llms import OpenAI

在内存中缓存

import langchain
from langchain.cache import InMemoryCachelangchain.llm_cache = InMemoryCache()# To make the caching really obvious, lets use a slower model.
llm = OpenAI(model_name="text-davinci-002", n=2, best_of=2)

计算第一次执行时间:

%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")

日志输出:

CPU times: user 35.9 ms, sys: 28.6 ms, total: 64.6 ms Wall time: 4.83 s

输出:

"\n\nWhy couldn't the bicycle stand up by itself? It was...two tired!"

计算第二次执行时间:

%%time
# The second time it is, so it goes faster
llm("Tell me a joke")

日志输出:

CPU times: user 238 µs, sys: 143 µs, total: 381 µs Wall time: 1.76 ms

输出:

'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'

SQLite 缓存

!rm .langchain.db
# 我们可以用 SQLite 缓存做同样的事情
from langchain.cache import SQLiteCache
langchain.llm_cache = SQLiteCache(database_path=".langchain.db")

计算第一次执行时间:

%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")

日志输出:

CPU times: user 17 ms, sys: 9.76 ms, total: 26.7 ms Wall time: 825 ms

输出:

'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'

计算第二次执行时间:

%%time
# The second time it is, so it goes faster
llm("Tell me a joke")

日志输出:

CPU times: user 2.46 ms, sys: 1.23 ms, total: 3.7 ms Wall time: 2.67 ms

输出:

'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'

Redis缓存

我们还可以使用Redis缓存提示信息和做同样的事情:

# (确保您的本地 Redis 实例在运行此示例之前先运行)
from redis import Redis
from langchain.cache import RedisCachelangchain.llm_cache = RedisCache(redis_=Redis())

计算第一次执行时间:

%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")

日志输出:

CPU times: user 6.88 ms, sys: 8.75 ms, total: 15.6 ms Wall time: 1.04 s

输出:

'\n\nWhy did the chicken cross the road?\n\nTo get to the other side!'

计算第二次执行时间:

%%time
# The second time it is, so it goes faster
llm("Tell me a joke")

日志输出:

CPU times: user 1.59 ms, sys: 610 µs, total: 2.2 ms Wall time: 5.58 ms

输出:

'\n\nWhy did the chicken cross the road?\n\nTo get to the other side!'

Semantic语义缓存

我们还使用Redis缓存提示和响应,并根据语义相似性评估命中率:

from langchain.embeddings import OpenAIEmbeddings
from langchain.cache import RedisSemanticCachelangchain.llm_cache = RedisSemanticCache(redis_url="redis://localhost:6379",embedding=OpenAIEmbeddings()
)

计算第一次执行时间:

%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")

日志输出:

CPU times: user 351 ms, sys: 156 ms, total: 507 ms Wall time: 3.37 s

输出:

"\n\nWhy don't scientists trust atoms?\nBecause they make up everything."

计算第二次执行时间:

%%time
# The second time, while not a direct hit, the question is semantically similar to the original question,
# so it uses the cached result!
llm("Tell me one joke")

日志输出:

CPU times: user 6.25 ms, sys: 2.72 ms, total: 8.97 ms Wall time: 262 ms

输出:

"\n\nWhy don't scientists trust atoms?\nBecause they make up everything."

GPTCache

我们可以使用GPTCache进行精确匹配缓存或基于语义相似性缓存结果,我们先举一个精确匹配的例子:

from gptcache import Cache
from gptcache.manager.factory import manager_factory
from gptcache.processor.pre import get_prompt
from langchain.cache import GPTCache
import hashlibdef get_hashed_name(name):return hashlib.sha256(name.encode()).hexdigest()def init_gptcache(cache_obj: Cache, llm: str):hashed_llm = get_hashed_name(llm)cache_obj.init(pre_embedding_func=get_prompt,data_manager=manager_factory(manager="map", data_dir=f"map_cache_{hashed_llm}"),)langchain.llm_cache = GPTCache(init_gptcache)

计算第一次执行时间:

%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")

日志输出:

CPU times: user 21.5 ms, sys: 21.3 ms, total: 42.8 ms Wall time: 6.2 s

输出:

'\n\nWhy did the chicken cross the road?\n\nTo get to the other side!'

计算第二次执行时间:

%%time
# The second time it is, so it goes faster
llm("Tell me a joke")

日志输出:

CPU times: user 571 µs, sys: 43 µs, total: 614 µs Wall time: 635 µs

输出:

'\n\nWhy did the chicken cross the road?\n\nTo get to the other side!'

现在让我们举一个相似度缓存的例子。

from gptcache import Cache
from gptcache.adapter.api import init_similar_cache
from langchain.cache import GPTCache
import hashlibdef get_hashed_name(name):return hashlib.sha256(name.encode()).hexdigest()def init_gptcache(cache_obj: Cache, llm: str):hashed_llm = get_hashed_name(llm)init_similar_cache(cache_obj=cache_obj, data_dir=f"similar_cache_{hashed_llm}")langchain.llm_cache = GPTCache(init_gptcache)

计算第一次执行时间:

%%time
# The first time, it is not yet in cache, so it should take longer
llm("Tell me a joke")

日志输出:

CPU times: user 1.42 s, sys: 279 ms, total: 1.7 s Wall time: 8.44 s

输出:

'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'

计算第二次执行时间:

%%time
# 这是一个完全匹配,所以它在缓存中找到它
llm("Tell me a joke")

日志输出:

CPU times: user 866 ms, sys: 20 ms, total: 886 ms Wall time: 226 ms

输出:

'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'

计算第三次执行时间:

%%time
# 这不是完全匹配,但在语义上是在距离之内,所以它命中了!
llm("Tell me joke")

日志输出:

CPU times: user 853 ms, sys: 14.8 ms, total: 868 ms Wall time: 224 ms

输出:

'\n\nWhy did the chicken cross the road?\n\nTo get to the other side.'

SQLAlchemy Cache

我们可以使用 SQLAlchemyCache来缓存SQLAlchemy支持的任何 SQL 数据库:

# from langchain.cache import SQLAlchemyCache
# from sqlalchemy import create_engine# engine = create_engine("postgresql://postgres:postgres@localhost:5432/postgres")
# langchain.llm_cache = SQLAlchemyCache(engine)

Custom SQLAlchemy Schemas

我们可以定义自己的声明性SQLAlchemyCache子类,以自定义用于缓存的模式。例如,为了支持在Postgres中进行高速全文提示索引,我们可以使用:

from sqlalchemy import Column, Integer, String, Computed, Index, Sequence
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_utils import TSVectorType
from langchain.cache import SQLAlchemyCacheBase = declarative_base()class FulltextLLMCache(Base):  # type: ignore"""Postgres table for fulltext-indexed LLM Cache"""__tablename__ = "llm_cache_fulltext"id = Column(Integer, Sequence('cache_id'), primary_key=True)prompt = Column(String, nullable=False)llm = Column(String, nullable=False)idx = Column(Integer)response = Column(String)prompt_tsv = Column(TSVectorType(), Computed("to_tsvector('english', llm || ' ' || prompt)", persisted=True))__table_args__ = (Index("idx_fulltext_prompt_tsv", prompt_tsv, postgresql_using="gin"),)engine = create_engine("postgresql://postgres:postgres@localhost:5432/postgres")
langchain.llm_cache = SQLAlchemyCache(engine, FulltextLLMCache)

可选缓存(Optional Caching)

我们也可以选择关闭特定LLM的缓存。在下面的示例中,即使启用了全局缓存,我们也将其关闭了一个特定的LLM:

llm = OpenAI(model_name="text-davinci-002", n=2, best_of=2, cache=False)

计算第一次执行时间:

%%time
llm("Tell me a joke")

日志输出:

CPU times: user 5.8 ms, sys: 2.71 ms, total: 8.51 ms Wall time: 745 ms

输出:

'\n\nWhy did the chicken cross the road?\n\nTo get to the other side!'

计算第二次执行时间:

%%time
llm("Tell me a joke")

日志输出:

CPU times: user 4.91 ms, sys: 2.64 ms, total: 7.55 ms Wall time: 623 ms

输出:

'\n\nTwo guys stole a calendar. They got six months each.'

链式可选缓存(Optional Caching in Chains)

我们还可以关闭链中特定节点的缓存。需要注意的是,某些接口通常更容易先构建链,然后再编辑 LLM。作为示例,我们将加载一个汇总器map-reduce链。我们将缓存映射步骤的结果,但不会冻结合并步骤的结果:

llm = OpenAI(model_name="text-davinci-002")
no_cache_llm = OpenAI(model_name="text-davinci-002", cache=False)
from langchain.text_splitter import CharacterTextSplitter
from langchain.chains.mapreduce import MapReduceChaintext_splitter = CharacterTextSplitter()
with open('../../../state_of_the_union.txt') as f:state_of_the_union = f.read()
texts = text_splitter.split_text(state_of_the_union)
from langchain.docstore.document import Document
docs = [Document(page_content=t) for t in texts[:3]]
from langchain.chains.summarize import load_summarize_chain
chain = load_summarize_chain(llm, chain_type="map_reduce", reduce_llm=no_cache_llm)

计算第一次执行时间:

%%time
chain.run(docs)

日志输出:

CPU times: user 452 ms, sys: 60.3 ms, total: 512 ms Wall time: 5.09 s

输出:

'\n\nPresident Biden is discussing the American Rescue Plan and the Bipartisan Infrastructure Law, which will create jobs and help Americans. He also talks about his vision for America, which includes investing in education and infrastructure. In response to Russian aggression in Ukraine, the United States is joining with European allies to impose sanctions and isolate Russia. American forces are being mobilized to protect NATO countries in the event that Putin decides to keep moving west. The Ukrainians are bravely fighting back, but the next few weeks will be hard for them. Putin will pay a high price for his actions in the long run. Americans should not be alarmed, as the United States is taking action to protect its interests and allies.'

当我们再次运行它时,我们会发现它的运行速度大大加快,但最终的答案却不同。这是由于在映射步骤进行缓存,但在归约步骤没有进行缓存所致计算第二次执行时间:

%%time
chain.run(docs)

日志输出:

CPU times: user 11.5 ms, sys: 4.33 ms, total: 15.8 ms Wall time: 1.04 s

输出:

'\n\nPresident Biden is discussing the American Rescue Plan and the Bipartisan Infrastructure Law, which will create jobs and help Americans. He also talks about his vision for America, which includes investing in education and infrastructure.'

最后我们需要记得执行:

!rm .langchain.db sqlite.db

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

相关文章:

自然语言处理从入门到应用——LangChain:模型(Models)-[大型语言模型(LLMs):缓存LLM的调用结果]

分类目录:《自然语言处理从入门到应用》总目录 from langchain.llms import OpenAI在内存中缓存 import langchain from langchain.cache import InMemoryCachelangchain.llm_cache InMemoryCache()# To make the caching really obvious, lets use a slower mode…...

Python 算法基础篇之图的遍历算法:深度优先搜索和广度优先搜索

Python 算法基础篇之图的遍历算法:深度优先搜索和广度优先搜索 引言 1. 图的遍历概述2. 深度优先搜索( DFS )2.1 DFS 的实现2.2 DFS 的应用场景 3. 广度优先搜索( BFS )3.1 BFS 的实现3.2 BFS 的应用场景 4. 示例与实例…...

文本缩略 文本超出显示省略号 控制超出省略的行数

文本缩略 .abb{//超出一行省略overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }超出2行省略 .abb2{display: -webkit-box !important;-webkit-box-orient: vertical;//超出2行省略-webkit-line-clamp:2;overflow: hidden; }控制超出省略的行数 .txt-over{/*控…...

云原生架构

1. 何为云原生? 很多IT业内小伙伴会经常听到这个名词,那么什么是云原生呢?云原生是在云计算环境中构建、部署和管理现代应用程序的软件方法。 当今时代,众多企业希望构建高度可扩展、灵活且有弹性的应用程序,以便能够快…...

Java 生成随机数据

文章目录 1. Java-faker依赖demo 2. common-random依赖demo 1. Java-faker 依赖 <dependency><groupId>com.github.javafaker</groupId><artifactId>javafaker</artifactId><version>1.0.2</version> </dependency>https://…...

基于OpenCV的红绿灯识别

基于OpenCV的红绿灯识别 技术背景 为了实现轻舟航天机器人实现红绿灯的识别&#xff0c;决定采用传统算法OpenCV视觉技术。 技术介绍 航天机器人的红绿灯识别主要基于传统计算机视觉技术&#xff0c;利用OpenCV算法对视频流进行处理&#xff0c;以获取红绿灯的状态信息。具…...

JavaScript快速入门:ComPDFKit PDF SDK 快速构建 Web端 PDF阅读器

JavaScript快速入门&#xff1a;ComPDFKit PDF SDK 快速构建 Web端 PDF阅读器 在当今丰富的网络环境中&#xff0c;处理 PDF 文档已成为企业和开发人员的必需品。ComPDFKit 是一款支持 Web 平台并且功能强大的 PDF SDK&#xff0c;开发人员可以利用它创建 PDF 查看器和编辑器&…...

Flutter 网络请求

在Flutter 中常见的网络请求方式有三种&#xff1a;HttpClient、http库、dio库&#xff1b; 本文简单介绍 使用dio库使用。 选择dio库的原因&#xff1a; dio是一个强大的Dart Http请求库&#xff0c;支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载…...

吃透《西瓜书》第三章 线性模型:多元线性回归

&#x1f349; 吃瓜系列 教材&#xff1a;《机器学习》 周志华著 &#x1f552;时间&#xff1a;2023/7/26 目录 一、多元线性回归 1 向量化 1.1.1 向量化 1.1.2 使用最小二乘法构建损失函数 1.1.3 去除求和符号&#xff0c;改成向量点乘的形式 1.1.4 数学原理 2 求解…...

数据结构【排序】

第七章 排序 一、排序 1.定义&#xff1a;将无序的数排好序 &#xff1b; 2.稳定性&#xff1a; Kᵢ和Kⱼ中&#xff0c;Kᵢ优先于Kⱼ那么在排序后的记录中仍然保持Kᵢ优先&#xff1b; 3.评价标准&#xff1a;执行时间和所需的辅助空间&#xff0c;其次是算法的稳定性&#xf…...

探索APP开发的新趋势:人工智能和大数据的力量

随着5G技术的不断发展&#xff0c;人工智能和大数据将会更加广泛的应用于我们生活和工作中&#xff0c;作为 APP开发公司&#xff0c;应该及时的对新技术进行研发&#xff0c;进而更好的为用户服务。目前 APP开发已经不是传统的软件开发了&#xff0c;而是向移动互联网转型&…...

超越传统:深入比较Bootstrap、Foundation、Bulma、Tailwind CSS和Semantic UI的顶级CSS框架!

探索流行的CSS框架&#xff1a;Bootstrap vs Foundation vs Bulma vs Tailwind CSS vs Semantic UI 在Web开发中&#xff0c;选择适合项目需求的CSS框架可以极大地简化界面设计和响应式布局的工作。本文将详细介绍一些流行的CSS框架&#xff0c;并提供代码示例和比较&#xff…...

基于深度学习淡水鱼体重智能识别模型研究

工作原理为&#xff1a;首先对大众淡水鱼图片进行数据清洗并做标签分类&#xff0c;之后基于残差网络ResNet50模型进行有监督的分类识别训练&#xff0c;获取识别模型。其次通过搭建回归模型设计出体重模型&#xff0c;对每一类淡水鱼分别拟合出对应的回归方程&#xff0c;将获…...

Nginx专题(1)--linux安装nginx

ngixn安装 安装依赖包 yum install gcc yum install pcre-devel yum install zlib zlib-devel yum install openssl openssl-devel 安装nginx 下载nginx的tar包 登录http://nginx.org/en/download.html&#xff0c;下载nginx的Stable version版本&#xff0c;并解压 #执行c…...

系统集成中级计算汇总

基本计算&#xff1a; EV 挣值 (实际完成的工作量) AC 实际发生的花费 PV 计划花费(预算) CV 成本 SV 进度 CV 和 SV 的计算 都是通过EV 减去另一个值 CV EV-AC SV EV-PV 成本 chengben C 开头 所以CV 是成本 CV 中有个C 所以用到的是 AC ,另外一个则是剩余的PV CV SV 计算…...

json.stringify的高级用法,和for of的原理

** /* for of 是用来循环可迭代属性的,如何判断是否是可迭代属性,数据原型链上有个Symbol.iterator说明这个数据是可迭代数据 Symbol.iterator是一个函数,调用此函数,会返回一个对象,对象的内部有一个next函数,调用next函数会返回一个对象这个对象内部有value和done值&#xf…...

SpringCloudAlibaba微服务实战系列(三)Sentinel1.8.0+流控

SpringCloudAlibaba–Sentinel Sentinel被称为分布式系统的流量防卫兵&#xff0c;是阿里开源流量框架&#xff0c;从服务限流、降级、熔断等多个纬度保护服务。Sentinel同时提供了简洁易用的控制台&#xff0c;可以看到接入应用的秒级数据&#xff0c;并可以在控制台设置一些…...

mybatis - no getter for property,以及@JsonIgnore

There is no getter for property named user_full_name in class com.book.erp.entity.user.QueryUser Mybatis 配置错误&#xff0c;XML配置文件有Java对象以及数据库字段&#xff0c;配置时需要小心 user_full_name是数据库字段&#xff0c;不需要有get 和 set方法&#xf…...

云原生周刊:K8s v1.28 中的结构化身份验证配置

开源项目推荐 KubeLinter KubeLinter 是一种静态分析工具&#xff0c;用于检查 Kubernetes YAML 文件和 Helm 图表&#xff0c;以确保其中表示的应用程序遵循最佳实践。 DB Operator DB Operator 减轻了为 Kubernetes 中运行的应用程序管理 PostgreSQL 和 MySQL 实例的痛苦…...

支持向量机概述

支持向量机在深度学习技术出现之前,使用高斯核的支持向量机在很多分类问题上取得了很好的结果,支持向量机不仅用于分类,还可以用于回归问题。它具有泛化性能好,适合小样本和高维特征的优点。 1. SVM引入 1.1支持向量机分类 支持向量机的基本模型是定义在特征空间上的间隔…...

linux之kylin系统nginx的安装

一、nginx的作用 1.可做高性能的web服务器 直接处理静态资源&#xff08;HTML/CSS/图片等&#xff09;&#xff0c;响应速度远超传统服务器类似apache支持高并发连接 2.反向代理服务器 隐藏后端服务器IP地址&#xff0c;提高安全性 3.负载均衡服务器 支持多种策略分发流量…...

视频字幕质量评估的大规模细粒度基准

大家读完觉得有帮助记得关注和点赞&#xff01;&#xff01;&#xff01; 摘要 视频字幕在文本到视频生成任务中起着至关重要的作用&#xff0c;因为它们的质量直接影响所生成视频的语义连贯性和视觉保真度。尽管大型视觉-语言模型&#xff08;VLMs&#xff09;在字幕生成方面…...

Spring AI 入门:Java 开发者的生成式 AI 实践之路

一、Spring AI 简介 在人工智能技术快速迭代的今天&#xff0c;Spring AI 作为 Spring 生态系统的新生力量&#xff0c;正在成为 Java 开发者拥抱生成式 AI 的最佳选择。该框架通过模块化设计实现了与主流 AI 服务&#xff08;如 OpenAI、Anthropic&#xff09;的无缝对接&…...

UR 协作机器人「三剑客」:精密轻量担当(UR7e)、全能协作主力(UR12e)、重型任务专家(UR15)

UR协作机器人正以其卓越性能在现代制造业自动化中扮演重要角色。UR7e、UR12e和UR15通过创新技术和精准设计满足了不同行业的多样化需求。其中&#xff0c;UR15以其速度、精度及人工智能准备能力成为自动化领域的重要突破。UR7e和UR12e则在负载规格和市场定位上不断优化&#xf…...

代理篇12|深入理解 Vite中的Proxy接口代理配置

在前端开发中,常常会遇到 跨域请求接口 的情况。为了解决这个问题,Vite 和 Webpack 都提供了 proxy 代理功能,用于将本地开发请求转发到后端服务器。 什么是代理(proxy)? 代理是在开发过程中,前端项目通过开发服务器,将指定的请求“转发”到真实的后端服务器,从而绕…...

使用LangGraph和LangSmith构建多智能体人工智能系统

现在&#xff0c;通过组合几个较小的子智能体来创建一个强大的人工智能智能体正成为一种趋势。但这也带来了一些挑战&#xff0c;比如减少幻觉、管理对话流程、在测试期间留意智能体的工作方式、允许人工介入以及评估其性能。你需要进行大量的反复试验。 在这篇博客〔原作者&a…...

STM32---外部32.768K晶振(LSE)无法起振问题

晶振是否起振主要就检查两个1、晶振与MCU是否兼容&#xff1b;2、晶振的负载电容是否匹配 目录 一、判断晶振与MCU是否兼容 二、判断负载电容是否匹配 1. 晶振负载电容&#xff08;CL&#xff09;与匹配电容&#xff08;CL1、CL2&#xff09;的关系 2. 如何选择 CL1 和 CL…...

Scrapy-Redis分布式爬虫架构的可扩展性与容错性增强:基于微服务与容器化的解决方案

在大数据时代&#xff0c;海量数据的采集与处理成为企业和研究机构获取信息的关键环节。Scrapy-Redis作为一种经典的分布式爬虫架构&#xff0c;在处理大规模数据抓取任务时展现出强大的能力。然而&#xff0c;随着业务规模的不断扩大和数据抓取需求的日益复杂&#xff0c;传统…...

如何应对敏捷转型中的团队阻力

应对敏捷转型中的团队阻力需要明确沟通敏捷转型目的、提升团队参与感、提供充分的培训与支持、逐步推进敏捷实践、建立清晰的奖励和反馈机制。其中&#xff0c;明确沟通敏捷转型目的尤为关键&#xff0c;团队成员只有清晰理解转型背后的原因和利益&#xff0c;才能降低对变化的…...

Java求职者面试指南:Spring、Spring Boot、Spring MVC与MyBatis技术解析

Java求职者面试指南&#xff1a;Spring、Spring Boot、Spring MVC与MyBatis技术解析 一、第一轮基础概念问题 1. Spring框架的核心容器是什么&#xff1f;它的作用是什么&#xff1f; Spring框架的核心容器是IoC&#xff08;控制反转&#xff09;容器。它的主要作用是管理对…...