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!
相关推荐
2402_8548083718 小时前
JavaScript中模块化在游戏引擎开发中的资源调度作用
jvm·数据库·python
生信研究猿18 小时前
第2题-模型推理量化加速优化问题
python·算法
看海的四叔18 小时前
【Python】阿里云 DataWorks + ODPS + 钉钉联动实战:配合[特殊字符]全搞定
python·阿里云·api·odps·requests·openclaw
康燕19 小时前
2026 程序员 AI新范式-- 第三章:寻找新奶酪——AI辅助下的全栈转型
人工智能·ai·ai新范式
2401_8654396320 小时前
HTML函数在低温环境下启动慢吗_温度对硬件启动影响【方法】
jvm·数据库·python
耿雨飞1 天前
第三章:LangChain Classic vs. 新版 LangChain —— 架构演进与迁移指南
人工智能·架构·langchain
俊哥V1 天前
AI一周事件 · 2026年4月8日至4月14日
人工智能·ai
m0_377618231 天前
Golang怎么连接MySQL数据库_Golang MySQL连接教程【总结】
jvm·数据库·python
LN花开富贵1 天前
【ROS】鱼香ROS2学习笔记一
linux·笔记·python·学习·嵌入式·ros·agv
weixin_586061461 天前
C#怎么通过反射获取类属性_C#如何动态读取元数据【进阶】
jvm·数据库·python