LangChain-18 Caching 将回答内容进行缓存 可在内存中或数据库中持久化缓存

背景描述

可以将问答的内容缓存起来,如果是相同的问题,那么将会直接把答案返回去,可以节约费用和计算。

安装依赖

shell 复制代码
pip install -qU langchain-core langchain-openai

编写代码

我们可以通过 InMemoryCache 进行内存缓存 或者 SQLiteCache 进行持久化存储。

详细代码如下:

python 复制代码
from langchain.globals import set_llm_cache
from langchain_openai import ChatOpenAI
from langchain.cache import InMemoryCache
from langchain.cache import SQLiteCache


llm = ChatOpenAI(
    model="gpt-3.5-turbo",
)
# 保存在内存中
set_llm_cache(InMemoryCache())
# 也可以持久化在数据库中
# set_llm_cache(SQLiteCache(database_path=".langchain.db"))

# The first time, it is not yet in cache, so it should take longer
message1 = llm.predict("Tell me a joke")
print(f"message1: {message1}")

# The second time it is, so it goes faster
message2 = llm.predict("Tell me a joke")
print(f"message2: {message2}")

运行结果

在运行过程中,可以直观的感受到,第一次的运行速度是比较慢的,但是第二次是非常快的。

说明当中是进行缓存了,第二次直接从内存中进行返回的。

当然,如果进入后台查看API的调用情况,也会发现,只有第一次走了OpenAI的API,第二次是没有的。

shell 复制代码
➜ python3 test18.py
/Users/wuzikang/Desktop/py/langchain_test/own_learn/env/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `predict` was deprecated in LangChain 0.1.7 and will be removed in 0.2.0. Use invoke instead.
  warn_deprecated(
message1: Why did the tomato turn red? Because it saw the salad dressing!
message2: Why did the tomato turn red? Because it saw the salad dressing!
相关推荐
deephub4 分钟前
多智能体系统的三种编排模式:Supervisor、Pipeline 与 Swarm
人工智能·python·大语言模型·agent
墨102411 分钟前
与 AI 并肩成长:从个人知识库到每日新闻系统的实践记录
人工智能·ai·ai编程·openclaw
m0_7381207211 分钟前
渗透测试——pyexpvm靶机详细提权过程(MSF框架,Hydra数据库爆破,SUDO提权)
服务器·网络·数据库·python·sql·web安全
翱翔的苍鹰12 分钟前
LangChain是一个主流的大语言模型(LLM)应用开发框架,核心功能是连接大模型与外部资源/工具。
网络·人工智能·python·深度学习·语言模型
rgb2gray15 分钟前
论文详解 | HDAM:破解 MAUP 的城市出行需求分析新方法,实现关键驱动精准识别
人工智能·python·llm·大语言模型·需求分析·多模态·maup
___波子 Pro Max.16 分钟前
Python容器类型差异操作
python
weixin1997010801620 分钟前
淘宝客商品详情页前端性能优化实战
java·前端·python·性能优化
心歌技术23 分钟前
CPU与GPU排序性能对比分析
python·gpu·性能对比·实验
Zhansiqi24 分钟前
day37英语
python
进击的小头28 分钟前
第7篇:基于传递函数的PI控制器设计
python·算法