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!
相关推荐
王小义笔记9 分钟前
大模型微调步骤与精髓总结
python·大模型·llm
LaughingZhu15 分钟前
Product Hunt 每日热榜 | 2026-03-29
数据库·人工智能·经验分享·神经网络·chatgpt
Flittly34 分钟前
【SpringAIAlibaba新手村系列】(4)流式输出与响应式编程
java·spring boot·spring·ai
LuoQuHen37 分钟前
第四章:Agent架构全景图—— 从最小可行体到完整分层设计
ai·agent
shao6530841 分钟前
AI解2026年Solar应急响应公益月赛-3月赛两道题
ai·应急响应
xiami_world1 小时前
AI Agent生成PPT技术解析:从一键生成到意图理解,Agent模式如何重构PPT工作流?
人工智能·经验分享·ai·信息可视化·powerpoint
147API1 小时前
GPT-5.4 vs Claude 4.6 接入差异对比(含迁移与统一接入)
gpt·claude·api中转·api大模型
我是胡杨学长1 小时前
ChatGPT 连续三月流量下滑,是热度凉了还是 AI 泡沫要来了?
人工智能·ai·chatgpt
刘 大 望1 小时前
开发自定义MCP Server并部署
java·spring·ai·语言模型·aigc·信息与通信·ai编程
源码之家1 小时前
计算机毕业设计:Python汽车销量数据采集分析可视化系统 Flask框架 requests爬虫 可视化 车辆 大数据 机器学习 hadoop(建议收藏)✅
大数据·爬虫·python·django·flask·课程设计·美食