langchain-learning/memory/with_memory_demo.py
2026-04-14 01:33:51 +08:00

44 lines
1.5 KiB
Python
Raw Permalink 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 logging
from langchain_core.messages import AIMessage, HumanMessage
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import PromptTemplate, ChatPromptTemplate
from langchain_openai import ChatOpenAI
import os
import dotenv
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
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="Qwen/Qwen3-8B")
def chat_with_llm():
prompt_template = ChatPromptTemplate.from_messages([
("system", "你是一个人工智能助手,你是万能的"),
("human", "{question}")
])
while True:
chain = prompt_template | llm
user_input = input("请继续你的问题,如果没有问题了,输入 [quit] 结束会话:")
if user_input == "quit":
break
response = chain.invoke({"question": user_input})
print(f"AI:{response.content}")
## 将当前轮次的聊天内容ai的回答和下一轮的问题保存到prompt中带入下一次聊天。
## 这是非标准做法。
prompt_template.messages.append(AIMessage(content=response.content))
prompt_template.messages.append(HumanMessage(content=user_input))
chat_with_llm()