langchain 缓存 Caching

使用 LangChain 框架连接 DeepSeek API 的初始化代码

python 复制代码
from langchain_deepseek import ChatDeepSeek
chat = ChatDeepSeek(
    model="deepseek-chat",
    temperature=0,
    api_key=API_KEY,
)

1. 内存缓存

python 复制代码
from langchain.globals import set_llm_cache #用于设置全局的LLM缓存机制。
from langchain.cache import InMemoryCache #将缓存数据存储在内存中,而不是磁盘上,需要 pip install langchain-community
set_llm_cache(InMemoryCache()) #使用内存缓存来存储和检索LLM的调用结果。
chat.invoke("3只鸭子几条腿?")
chat.invoke("3只鸭子几条腿?") # 当提问第2次一模一样的问题时,返回速度相当快

2. 硬盘缓存

python 复制代码
from langchain.globals import set_llm_cache
from langchain.cache import SQLiteCache
set_llm_cache(SQLiteCache(database_path="./langchain.db")) # 会在当前目录生成 langchain.db 文件

#加入问答到缓存中
chat.invoke("讲一个10个字的故事?")
chat.invoke("讲一个10个字的故事?")
相关推荐
花千树_0103 分钟前
插件加载方式选不好,迟早被同事吐槽——四种姿势全解析
langchain·agent
Alluxio13 分钟前
Alluxio + Anyscale Ray框架,实现跨区域训练数据读取速度20倍提升
人工智能·分布式·机器学习·缓存·ai
fenglllle1 小时前
python3t pip3安装langchain失败心得
langchain
大模型真好玩3 小时前
LangChain DeepAgents 速通指南(十一)—— DeepAgents Code 记忆与状态管理
人工智能·langchain·agent
lhxcc_fly3 小时前
LangGraph基础知识点
python·langchain·llm·langgraph
BraveWang6 小时前
【LangChain 1.x】05、结构化输出|三种结构定义模式与两种结果获取方式
langchain
俊俊谢6 小时前
从零搭建:本地LangChain Agent调用远程LLaMA-Factory模型服务
langchain·llama
怕浪猫7 小时前
第15章 安全、伦理与合规
langchain·openai·agent
手握风云-7 小时前
Redis:不只是缓存那么简单(十四)
redis·缓存
向日的葵00618 小时前
langchain的Tools教程(三)
python·langchain·tools