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个字的故事?")
相关推荐
AI应用实战 | RE1 小时前
004、语言模型接口实战:OpenAI、本地模型与流式响应的那些坑
langchain
AI应用实战 | RE1 小时前
012、检索器(Retrievers)核心:从向量库中智能查找信息
人工智能·算法·机器学习·langchain
海兰2 小时前
【第2篇】LangChain的初步实践
人工智能·langchain
難釋懷5 小时前
缓存同步
spring·缓存·mybatis
AI应用实战 | RE6 小时前
014、索引高级实战:当单一向量库不够用的时候
数据库·人工智能·langchain
呼啦啦5616 小时前
C++vector
java·c++·缓存
刘~浪地球7 小时前
数据库与缓存--分库分表实战指南
网络·数据库·缓存
是小蟹呀^8 小时前
【总结】LangChain中如何维持记忆
python·langchain·memory
Rick19938 小时前
LangChain和spring ai是什么关系?
人工智能·spring·langchain
AI应用实战 | RE8 小时前
011、向量数据库入门:Embeddings原理与ChromaDB实战
开发语言·数据库·langchain·php