langchain-learning/memory/memory_desc.py
kennethcheng 2c6639fa43 v0.0.7
memory更新,放弃 LLMChain
2026-04-14 19:40:17 +08:00

44 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import dotenv
from langchain.memory import ConversationBufferMemory, ConversationTokenBufferMemory, ConversationSummaryMemory
from langchain_openai import ChatOpenAI
memory = ConversationBufferMemory()
memory.chat_memory.add_user_message("我叫小明")
memory.chat_memory.add_ai_message("噢,好的,你叫小明")
print(memory)
print(memory.memory_key)
print(memory.load_memory_variables({}))
print('---------')
memory2 = ConversationBufferMemory(memory_key="memory2")
memory2.chat_memory.add_user_message("我叫小明")
memory2.chat_memory.add_ai_message("噢,好的,你叫小明")
print(memory2)
print(memory2.memory_key)
print(memory2.load_memory_variables({}))
print('---------')
memory3 = ConversationBufferMemory(return_messages=True)
memory3.chat_memory.add_user_message("我叫小明")
memory3.chat_memory.add_ai_message("噢,好的,你叫小明")
print(memory3)
print(memory3.memory_key)
print(memory3.load_memory_variables({}))
print('---------')
dotenv.load_dotenv()
## 设置环境变量
os.environ['OPENAI_API_KEY'] = os.getenv("SILICONFLOW_API_KEY")
os.environ['OPENAI_BASE_URL'] = os.getenv("SILICONFLOW_BASE_URL")
# 默认的 'model_name': 'deepseek-ai/DeepSeek-V3.1',
llm = ChatOpenAI(model="deepseek-ai/DeepSeek-V3.1")
memory_test = ConversationSummaryMemory(llm=llm)
memory_test.save_context({"input": "我叫小明"}, {"output": "噢,好的,你叫小明"})
memory_test.save_context({"input": "那么你是谁呢"}, {"output": "我是一个无所不能的AI聊天助手可以帮你解答任何问题。"})
print(memory_test.load_memory_variables({}))
# {'history': '\n\nThe human introduces themselves as xiaoming. The AI confirms the name and responds. The human then asks who the AI is. The AI introduces itself as an all-powerful AI chat assistant who can answer any questions.'}