python-langchain框架(1-8-1 缓存机制——让 AI 应用“记住”高频问题)

张开发
2026/4/4 5:32:42 15 分钟阅读
python-langchain框架(1-8-1 缓存机制——让 AI 应用“记住”高频问题)
我们会发现一个奇怪的现象——每天有30%的问题是完全相同的用户都在问快递几天能到、怎么退货、商品有保修吗……每个问题都要调用GPT-4每次花费0.03美元一天就是数万美元更糟的是相同的回答用户要等3-5秒才能看到……解决方案引入缓存机制如下使用sqlite当缓存数据库当用户问道相同问题时从缓存里直接给出答案不用将问题在送给大模型既节约金钱成本也节约时间成本。直接看代码12345678910111213141516171819202122232425262728fromlangchain_community.cacheimportSQLiteCachefromlangchain.globalsimportset_llm_cachefromlangchain_openaiimportChatOpenAIimportos#指定缓存 对比提问同样的问题返回时间set_llm_cache(SQLiteCache(database_pathlangchain_demo.db))llmChatOpenAI(api_keyos.getenv(DEEPSEEK_API_KEY),base_urlos.getenv(DEEP_URL),# Deepseek 的 API 基础地址modeldeepseek-v3:671b,# Deepseek 对话模型可选deepseek-chat-pro 等高级模型temperature0.7,# 温度参数0-1越低越稳定max_tokens1024# 最大生成 tokens)#这时会向数据库里插入一条数据responsellm.invoke(hello world)print(response.content)#再插入一条数据 注是否插入要根据提示词和调用的模型模型参数改变也会认为是不同responsellm.invoke(how are you)print(response.content)#这时就会从缓存里直接出结果不会送往大模型数据库里也不会新插入一条数据responsellm.invoke(hello world)print(response.content)运行结果可以看到 第一次的回答和第三次的回答是完全一样的。1234567Hello! How can I assist you today? Whether you have questions, needhelpwith a task,orjust want to chat, Im hereforyou! Hey there! Thanksforasking! Im functioning at full capacity and ready to help you out. While I dont experience feelingsinthe way humans do, I genuinely enjoy our conversationsandam always excited to learnandassist. How can I support you today? Imallears! Hello! How can I assist you today? Whether you have questions, needhelpwith a task,orjust want to chat, Im hereforyou!

更多文章