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!
相关推荐
鲸落✗4 分钟前
深入解析单HTML实现的网页版《我的世界》(附代码下载链接)
前端·python·html
Aerelin8 分钟前
豆瓣数据采集案例
前端·爬虫·python·js·playwright
lqwh535418 分钟前
python控制修改comsol边界条件仿真方法
开发语言·python
WenGyyyL30 分钟前
基于昇腾平台的Qwen大模型推理部署实战:从模型转换到推理(含代码)
人工智能·python·语言模型·nlp·昇腾
e***985730 分钟前
Window下Redis的安装和部署详细图文教程(Redis的安装和可视化工具的使用)
数据库·redis·缓存
爬山算法37 分钟前
Redis(156)Redis的延迟问题如何解决?
数据库·redis·缓存
q***547538 分钟前
解决no main manifest attribute错误
ide·python·pycharm
玩大数据的龙威1 小时前
农经权二轮延包—批量替换签名盖章页扫描页
python
羊仔AI探索1 小时前
GLM-4.6接入Claude Code插件,国内丝滑编程
ide·人工智能·ai·aigc·ai编程
张彦峰ZYF1 小时前
Coze文章仿写:智能体 + 工作流实现内容自动生成与插图输出
人工智能·ai·coze dify