44 lines
1.5 KiB
Python
44 lines
1.5 KiB
Python
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()
|