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!
相关推荐
蜡台16 分钟前
通过Gradle脚本声明更改Java变量
android·java·开发语言·python·kotlin·gradle·groovy
智能体与具身智能1 小时前
TVA 本质内涵与核心特征(系列)
人工智能·python·智能体视觉
云雾J视界1 小时前
SST:高频变压器设计实战:铁氧体 vs 纳米晶 vs 非晶,磁性材料怎么选
python·acdc·dab·sst
第一程序员1 小时前
Rust trait 入门:把 AI 客户端抽象成可替换接口
python·rust·github
@蔓蔓喜欢你1 小时前
AI 辅助智能组件生成:从设计稿到可运行代码的工程化实践
人工智能·ai
Ulyanov2 小时前
Python实现6-DOF刚体仿真器(下)——环境扰动与控制闭环
开发语言·python·算法·系统仿真·雷达电子对抗·导引头
小小的木头人2 小时前
Python 批量解析 Excel 经纬度,调用高德地图 API 获取中文地址
开发语言·python·excel
子非鱼94272 小时前
07-Flutter 鸿蒙实战 07:故事集列表与缓存设计
学习·flutter·缓存·华为·harmonyos
金銀銅鐵3 小时前
[Python] 为 Vole 机器语言实现图形化界面
python·程序员