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!
相关推荐
一木 之林12 小时前
AI实战 : Numpy图像处理与深度学习框架
python
c_lb728812 小时前
零基础选策略工具,先分清三件事
人工智能·python
夜雪一千12 小时前
Python如何使用XPath定位没有特征的元素?无id、无class通用定位技巧
开发语言·python
特立独行的猫a12 小时前
DeepSeek Harness插件和工具的区别介绍及开发入门指南
前端·ai·agent·插件·deepseek·harness
安逸sgr12 小时前
优化器是什么?SGD、Momentum、Adam 有什么区别?
人工智能·ai·大模型·agent·智能体
王莹月12 小时前
全店商品图风格怎么统一?生图API 用 nano banana pro 批量出同一套视觉
gpt·ai·chatgpt·ai作画·aigc·agi
流浪00112 小时前
Python 基础语法(一):常量、变量、输入输出与运算符
开发语言·python
光影少年12 小时前
react离线缓存、图片缓存方案
开发语言·前端·javascript·react native·react.js·缓存·前端框架
鸿芯微控科技12 小时前
MFC关断后还有流量怎么办?零流量、阀门泄漏、压差与Python分析
c++·python·mfc·质量流量控制器·关断泄漏·零流量测试
AI导出鸭13 小时前
怎么让豆包做表格?AI导出鸭苹果版将豆包输出的管道表格智能解析为二维结构,一键导出为Excel或Word标准表格。
人工智能·chatgpt·word·excel·ai导出鸭