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!
相关推荐
凤城老人25 分钟前
开源少儿编程教材《代码岛》:41 讲 Python 入门,PDF/EPUB 免费下载
python·pdf·pygame
俊俊几年的26 分钟前
RK3588 硬件架构详解:CPU、GPU、NPU 与 RKNN 软件栈
linux·c++·python·yolo·numpy·rockchip
极客先躯32 分钟前
智能体开发高级面试每日一题|2026-06-05|什么是 Agentic AI 与传统 RPA 的区别?
人工智能·ai·代理模式·rpa·每日一题·高级面试·智能体开发
琪宝58533 分钟前
AI大模型应用开发 001|Python 环境搭建零基础第一课:Windows/Mac 全平台安装与避坑
人工智能·windows·python
yiangL_34 分钟前
自主学习:Python 嵌套循环实验|双层循环与图形打印实践
开发语言·python·学习
七夜zippoe44 分钟前
国产库性能调优:索引/执行计划实战(四步处理顺序与四类慢的归因)
java·ai·信创
打工仔折腾 AI1 小时前
Linux网络:UDP一次sendto对应一次recvfrom的底层机制解析
linux·网络·人工智能·后端·python·性能优化·udp
极客先躯1 小时前
智能体开发高级面试每日一题|2026-06-03|如何判断一个业务需求适合用 Agent 解决还是用传统程序解决?
ai·架构·agent·每日一题·高级面试题·智能体开发·传统业务
开发者导航2 小时前
Cursor plugins 插件仓库上手:结构解析与安装使用教程
android·linux·ubuntu·ai·typescript·cursor·插件开发