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!
相关推荐
天才测试猿28 分钟前
Postman接口测试:如何导入swagger接口文档?
自动化测试·软件测试·python·测试工具·职场和发展·接口测试·postman
番茄迷人蛋36 分钟前
欢迎使用AI美食大师项目
人工智能·ai
计算机学姐36 分钟前
基于Python的校园美食推荐系统【2026最新】
开发语言·vue.js·后端·python·mysql·django·推荐算法
天天进步20151 小时前
Python全栈实战:基于机器学习的用户行为分析系统
python
linzeyang1 小时前
Advent of Code 2025 挑战全手写代码 Day 5 - 餐厅
后端·python
乄bluefox1 小时前
如何快速迁移redis - RedisShake(RDB方式)
数据库·redis·缓存
祝余Eleanor1 小时前
Day 29 类的定义及参数
人工智能·python·机器学习
码界奇点1 小时前
基于Dash+FastAPI的通用中后台管理系统设计与实现
python·车载系统·毕业设计·fastapi·源代码管理·dash
white-persist1 小时前
【攻防世界】reverse | Mysterious 详细题解 WP
c语言·开发语言·网络·汇编·c++·python·安全
少许极端2 小时前
Redis入门指南:从零到分布式缓存-string类型
redis·分布式·缓存