Ollama+Redis多轮对话助手
·
这个警告信息表明您当前使用的 ChatOllama 类已经从 LangChain 主库中移出,转移到了专门的 langchain-ollama 包中。这是 LangChain 0.3.1 版本开始的模块化调整,建议按照提示进行更新。
以下是优化后的代码(包含安装说明):
第一步:安装专用包
pip install -U langchain-ollama
第二步:更新后的代码
from langchain_ollama import ChatOllama # 使用新的专用包
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_community.chat_message_histories import RedisChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
# 初始化Ollama(专用包版本)
model = ChatOllama(
base_url="http://10.80.0.212:11434",
model="deepseek-r1:8b",
temperature=0.7
)
# 定义提示模板(优化为更自然的对话引导)
prompt = ChatPromptTemplate.from_template(
"""你是一个智能助手,可以回答通用问题和编写代码。请根据上下文自然交流。
历史对话:
{history}
新问题: {input}"""
)
# 构建对话链
runnable = prompt | model
# Redis配置(添加连接超时参数)
REDIS_URL = "redis://:OceanXECM!@10.80.0.212:6379/0"
REDIS_KEY_PREFIX = "message_store"
def get_message_history(conversation_id: str) -> RedisChatMessageHistory:
"""获取Redis消息历史(增加连接稳定性配置)"""
return RedisChatMessageHistory(
session_id=f"{REDIS_KEY_PREFIX}:{conversation_id}",
url=REDIS_URL,
socket_connect_timeout=10 # 添加超时设置
)
# 创建带历史记录的链
with_message_history = RunnableWithMessageHistory(
runnable,
get_message_history,
input_messages_key="input",
history_messages_key="history"
)
# 示例对话(封装为函数)
def chat(conversation_id: str, user_input: str):
response = with_message_history.invoke(
input={"knowledge_base": "general", "input": user_input},
config={"configurable": {"conversation_id": conversation_id}}
)
print(f"用户: {user_input}\nAI: {response.content}\n")
# 测试对话流
chat("abc123", "你好,你是谁?")
chat("abc123", "请用Python写个Hello World")
chat("abc123", "改成Java版本呢?")
关键优化点:
- 模块迁移:使用新的
langchain_ollama官方推荐包 - 稳定性增强:
- 添加Redis连接超时参数(
socket_connect_timeout) - 更清晰的错误提示路径
- 添加Redis连接超时参数(
- 代码结构优化:
- 将对话逻辑封装为
chat()函数 - 简化了输入参数的复杂度
- 将对话逻辑封装为
- 提示词改进:采用更自然的对话引导模板
注意:如果您的环境无法安装新包,临时解决方案是在代码开头添加:
import warnings warnings.filterwarnings("ignore", category=LangChainDeprecationWarning)但这只是临时规避方案,建议尽快迁移到新包。
更多推荐
所有评论(0)