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!
相关推荐
紫小米4 小时前
后端日志管理
python·fastapi
视觉&物联智能4 小时前
【杂谈】-人工智能风险文化对组织决策的深远影响
人工智能·安全·ai·agi
白雪茫茫5 小时前
监督学习、半监督学习、无监督学习算法详解
python·学习·算法·ai
つ安静与叛逆的小籹人5 小时前
小红书API:通过笔记ID获取笔记详情数据教程
笔记·python
05候补工程师5 小时前
[实战复盘] 拒绝 AI 屎山!我从设计模式中学到的“调教”AI 新范式
人工智能·python·设计模式·ai·ai编程
飞Link5 小时前
垂直领域 AI 的曙光:GPT-Rosalind 如何重塑生命科学与药物研发?
人工智能·gpt
cczixun6 小时前
OpenAI连发GPT-5.5系列:免费版幻觉大降,安全版能力飙升,千亿融资估值直冲8520亿美元
人工智能·gpt·安全
进击的雷神7 小时前
别再对着祖传代码发愁了,再乱的项目 Zread 也能快速生成可读文档
ai·wiki·zread
阿豪只会阿巴7 小时前
【没事学点啥】TurboBlog轻量级个人博客项目——项目介绍
javascript·python·django·html
木子七8 小时前
RAG质量评估&实施RAG工程核心步骤
ai·rag