langchain qwen3 构建一个简单的对话系统

创建一个conda环境

bash 复制代码
conda create -n llm python=3.10

软件库安装,缺少的软件包,会报错提示安装即可

bash 复制代码
pip install langchain transformers

代码:

python 复制代码
from langchain_huggingface import ChatHuggingFace, HuggingFacePipeline
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
import torch

# 1. 初始化本地 LLM (保持你之前的配置)
llm = HuggingFacePipeline.from_model_id(
    model_id="/data2/wanghq/models/Qwen/Qwen3-8B",
    task="text-generation",
    pipeline_kwargs={
        "max_new_tokens": 1024,
        "temperature": 0.5,
        "do_sample": True,
        "device_map": "auto",
        "trust_remote_code": True,
        "dtype": torch.bfloat16, 
    },
)

model = ChatHuggingFace(llm=llm)

# 2. 建立内存中的存储字典,用于存放不同 session 的历史记录
store = {}

def get_session_history(session_id: str):
    if session_id not in store:
        store[session_id] = InMemoryChatMessageHistory()
    return store[session_id]

# 3. 封装成带记忆能力的 Chain
# 这里的 config 会根据 session_id 自动提取或存储对话历史
with_message_history = RunnableWithMessageHistory(
    model,
    get_session_history,
)

# 4. 实现循环对话
print("\n--- 已进入连续对话模式(输入 'exit' 退出) ---")
session_config = {"configurable": {"session_id": "robot_research_01"}}

# 可选:先存入一个系统提示词
get_session_history("robot_research_01").add_message(
    SystemMessage(content="你是一个机器人专家。直接回复,不要输出 <think> 标签。")
)

while True:
    user_input = input("\nUser: ")
    if user_input.lower() in ["exit", "quit", "退出"]:
        break

    print("\nQwen: ", end="", flush=True)
    
    # 5. 调用并流式输出
    # 注意:with_message_history 会自动处理历史记录的注入和更新
    for chunk in with_message_history.stream(
        [HumanMessage(content=user_input)],
        config=session_config
    ):
        print(chunk.content, end="", flush=True)
    print("\n")

执行结果

相关推荐
Li emily13 小时前
解决了加密货币api多币种订阅时的数据乱序问题
人工智能·python·api·fastapi
2301_7815714213 小时前
Golang格式化输出占位符都有什么_Golang fmt占位符教程【通俗】
jvm·数据库·python
asdzx6713 小时前
使用 Python 为 PDF 添加页码 (详细教程)
python·pdf·页码
AI技术控14 小时前
《Transformers are Inherently Succinct》论文解读:从“能表达什么”到“多紧凑地表达”
人工智能·python·深度学习·机器学习·自然语言处理
金融大 k16 小时前
Python 全球指数监控面板:TickDB + REST + WebSocket 完整方案
python·websocket
啊哈哈1213816 小时前
系统设计复盘:为什么 Agent 的 ReAct 循环必须内嵌确定性保护层——以 FitMind 健康助手的路由与步骤控制为例
人工智能·python·react
一颗牙牙17 小时前
安装mmcv
开发语言·python·深度学习
大数据魔法师17 小时前
Streamlit(二)- Streamlit 架构与运行机制
python·web
m0_4708576417 小时前
PHP怎么实现工厂模式_Factory模式编写指南【指南】
jvm·数据库·python
大数据魔法师18 小时前
Streamlit(三)- Streamlit 多页面应用开发
python·web