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!
相关推荐
c***42102 分钟前
python的sql解析库-sqlparse
数据库·python·sql
Q一件事12 分钟前
arcpy选择特定区域进行分析
python
天下·第二15 分钟前
python处理【orc】下载压缩的.zip文件,windows和linux同时适配
linux·windows·python
笨笨没好名字34 分钟前
AI4CAD:用python+creo实现批量参数建模(creo二次开发示例)
数据库·python·microsoft
e***v35637 分钟前
redis分页查询
数据库·redis·缓存
Python×CATIA工业智造39 分钟前
Python多进程爬虫实战:豆瓣读书数据采集与法律合规指南
开发语言·爬虫·python
倔强的石头10644 分钟前
Rokid AI眼镜:连接现实与数字的桥梁,探索下一代智能应用开发
人工智能·ai·ar·rokid·ai眼镜
java1234_小锋44 分钟前
基于Python深度学习的车辆车牌识别系统(PyTorch2卷积神经网络CNN+OpenCV4实现)视频教程 - 集成到web系统-识别历史记录实现
python·深度学习·cnn·车牌识别
美团测试工程师1 小时前
软件测试面试题2025年末总结
开发语言·python·测试工具
wumingxiaoyao1 小时前
AI - AI Agent 是什么?为什么最近这么火?
人工智能·ai·chatgpt·ai agent