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!
相关推荐
我叫侯小科6 分钟前
PyTorch 实战:手写数字识别(MNIST)从入门到精通
人工智能·pytorch·python
青衫客366 分钟前
浅谈 Python 的 C3 线性化算法(C3 Linearization):多继承背后的秩序之美
python·mro·c3线性化算法
Gitpchy16 分钟前
Day 47 注意力热图可视化
python·深度学习·cnn
杜子不疼.1 小时前
【Linux】进程状态全解析:从 R/S/D/T 到僵尸 / 孤儿进程
linux·人工智能·ai
zhjadsf2 小时前
Huggingface_hub源码解析 - 简介篇
python·huggingface
20岁30年经验的码农2 小时前
Python语言基础文档
开发语言·python
清静诗意3 小时前
独立 IoT 客户端绕过 Django 生命周期导致数据库断链:诊断与修复
python·mysql·django·生命周期
不知更鸟6 小时前
Django 项目设置流程
后端·python·django
CoderJia程序员甲7 小时前
GitHub 热榜项目 - 日榜(2025-11-15)
ai·开源·大模型·github·ai教程
自动化代码美学7 小时前
【Python3.13】官网学习之控制流
开发语言·windows·python·学习