From 2c6639fa43198a058105f4545349e8519cf0c922 Mon Sep 17 00:00:00 2001 From: kennethcheng Date: Tue, 14 Apr 2026 19:40:17 +0800 Subject: [PATCH] =?UTF-8?q?v0.0.7=20memory=E6=9B=B4=E6=96=B0=EF=BC=8C?= =?UTF-8?q?=E6=94=BE=E5=BC=83=20LLMChain?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- memory/memory_demo.py | 56 ++++++++++++++++++++++++++++++------------- memory/memory_desc.py | 2 +- 2 files changed, 40 insertions(+), 18 deletions(-) diff --git a/memory/memory_demo.py b/memory/memory_demo.py index 7eca400..2512432 100644 --- a/memory/memory_demo.py +++ b/memory/memory_demo.py @@ -1,37 +1,59 @@ -import logging import os - import dotenv -from langchain.chains.llm import LLMChain -from langchain.memory import ConversationBufferMemory -from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder +import logging from langchain_openai import ChatOpenAI +from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder +from langchain_core.runnables.history import RunnableWithMessageHistory +from langchain_community.chat_message_histories import ChatMessageHistory +from langchain_core.chat_history import BaseChatMessageHistory + logging.basicConfig( level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) + dotenv.load_dotenv() -## 设置环境变量 +# 1. 设置环境变量 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="Qwen/Qwen3-8B") +# 2. 初始化模型 +llm = ChatOpenAI(model="deepseek-ai/DeepSeek-V3.1") +# 3. 定义 Prompt (现代版无需手动处理 question 变量) prompt = ChatPromptTemplate.from_messages([ ("system", "你是一个万能的人工智能AI"), MessagesPlaceholder(variable_name="history"), - ("human", "问题:{question}") + ("human", "{question}") ]) -## 创建 Memory 对象 -memory = ConversationBufferMemory(return_messages=True) +# 4. 【核心改動】使用 LCEL 組合鏈 +# 這裡不需要 LLMChain,直接用管道符 +chain = prompt | llm -chain = LLMChain(prompt=prompt, memory=memory, llm=llm) -res1 = chain.invoke({"question":"我是小明"}) -print(res1) -print() -res2 = chain.invoke({"question":"我是谁?"}) -print(res2) +# 5. 管理記憶體 (現代版做法:使用字典存儲不同 Session 的歷史) +store = {} + +def get_session_history(session_id: str) -> BaseChatMessageHistory: + if session_id not in store: + store[session_id] = ChatMessageHistory() + return store[session_id] + +# 包裝成帶有記憶功能的鏈 +with_message_history = RunnableWithMessageHistory( + chain, + get_session_history, + input_messages_key="question", + history_messages_key="history", +) + +# 6. 執行調用 +config = {"configurable": {"session_id": "xiaoming_test"}} + +res1 = with_message_history.invoke({"question": "我是小明"}, config=config) +print(f"回答1: {res1.content}") + +res2 = with_message_history.invoke({"question": "我是谁?"}, config=config) +print(f"回答2: {res2.content}") \ No newline at end of file diff --git a/memory/memory_desc.py b/memory/memory_desc.py index 38f15c0..82a68c2 100644 --- a/memory/memory_desc.py +++ b/memory/memory_desc.py @@ -34,7 +34,7 @@ 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="moonshotai/Kimi-Dev-72B") +llm = ChatOpenAI(model="deepseek-ai/DeepSeek-V3.1") memory_test = ConversationSummaryMemory(llm=llm) memory_test.save_context({"input": "我叫小明"}, {"output": "噢,好的,你叫小明"})