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个字的故事?")
相关推荐
2401_837088501 分钟前
Redis通用命令
数据库·redis·缓存
马尚来1 小时前
helloworld入门【从0到1,LangChain+RAG全链路实战AI知识库】
langchain
马尚来1 小时前
从0到1,LangChain+RAG全链路实战AI知识库
langchain
来旺5 小时前
互联网大厂Java面试全解析及三轮问答专项
java·数据库·spring boot·安全·缓存·微服务·面试
摇滚侠6 小时前
Spring Boot 3零基础教程,WEB 开发 HTTP 缓存机制 笔记29
spring boot·笔记·缓存
cr7xin6 小时前
基于Session和Redis实现短信验证码登录
数据库·redis·缓存
叼菠萝7 小时前
AI 应用开发三剑客系列:LangChain 如何撑起 LLM 应用开发基石?
python·langchain
MichaelIp7 小时前
基于MCP协议的多AGENT文章自动编写系统
语言模型·langchain·prompt·ai写作·llamaindex·langgraph·mcp
玲小珑8 小时前
LangChain.js 完全开发手册(十六)实战综合项目二:AI 驱动的代码助手
前端·langchain·ai编程
viperrrrrrrrrr721 小时前
Agent向量存储中的记忆衰退与记忆过载解决方案
langchain·大模型·agent·rag