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!
相关推荐
“AI国潮设计-小江”2 分钟前
AIGC实战:Python+SDXL批量生成英歌舞IP立牌,解锁猪猪蛋糕“反差萌”流量密码(附完整API源码)
开发语言·人工智能·python·prompt·aigc
李纲明13 分钟前
WordPress 挂上 Cloudflare 后询盘和后台异常:缓存规则、SSL 模式和真实 IP 怎么核
运维·缓存·https·cdn·wordpress·cloudflare
远航计算机14 分钟前
收录从分钟级变 3 到 7 天,抢首发为什么失效了
大数据·人工智能·爬虫·chatgpt·aigc·1024程序员节
奈落2415 分钟前
从“你问它答”到“它主动推”:ChatGPT Pulse 把记忆、反馈和日历变成一条信息策划流水线
人工智能·chatgpt·ai 编程
成信吴彦祖23 分钟前
当前专业的无人机RID侦测主站供应商主要有哪些
python·1024程序员节
weixin_4684668526 分钟前
让机器像视网膜一样“看”:事件相机与脉冲神经网络如何重构视觉感知
人工智能·神经网络·ai·机器视觉·1024程序员节
紧跟先前的步伐27 分钟前
Go AI Agent 实战 15|context.Context、超时与取消机制
人工智能·安全·ai·golang·1024程序员节
编程的一拳超人31 分钟前
【元宝搜索开发者征文大赛】四语实战:Java/Python/Go/Node.js 构建 AI 搜索应用全攻略
java·python·golang·node.js·agent
fanruitian40 分钟前
python anaconda jupyter notebook
python
云和数据.ChenGuang1 小时前
Python 菜鸟入门:字典(dict)类型详解与 CRUD 实战案例
开发语言·人工智能·python