代码中使用了 langchain_community.chat_models.ChatOllama
类来初始化 Ollama 聊天模型(例如 qwen3:1.7b
),会触发 LangChainDeprecationWarning
,提示该类在 LangChain 0.3.1 中已被废弃,并将在 1.0.0 中移除。官方推荐使用 langchain_ollama
包中的 ChatOllama
类替代。本文基于 LangChain 0.3.x,详细解释如何迁移 ChatOllama
到 langchain_ollama.ChatOllama
,并提供代码示例。
废弃代码告警:
LangChainDeprecationWarning: The classChatOllama
was deprecated in LangChain 0.3.1 and will be removed in 1.0.0. An updated version of the class exists in the :class:~langchain-ollama package and should be used instead. To use it run
pip install -U :class:~langchain-ollama
and import asfrom :class:
~langchain_ollama import ChatOllama``.
chat = ChatOllama(model = ‘qwen3:1.7b’) ……
为什么需要迁移?
langchain_community.chat_models.ChatOllama
是 LangChain 早期用于与 Ollama 聊天模型交互的类,设计为支持消息格式的对话场景。但随着 LangChain 的模块化重构,Ollama 相关的功能已被移到独立的 langchain_ollama
包中。迁移的原因包括:
- 模块化:将特定模型的集成移到社区维护的包,保持
langchain-core
轻量。 - 功能优化:
langchain_ollama.ChatOllama
更稳定,支持最新的 Ollama 功能(如工具调用、结构化输出)。 - 长期支持:旧的
ChatOllama
类将在 LangChain 1.0 中移除,新类是未来标准。
新的 langchain_ollama.ChatOllama
提供与旧类相同的对话功能,但更适配 LangChain 0.3.x 的生态(如 LCEL、工具调用、对话历史管理)。
迁移步骤
以下是将 langchain_community.chat_models.ChatOllama
迁移到 langchain_ollama.ChatOllama
的详细步骤,假设你使用 Ollama 本地模型(如 qwen3:1.7b
)。
1. 分析原始代码
假设你的代码如下,使用 langchain_community.chat_models.ChatOllama
初始化聊天模型:
from langchain_community.chat_models import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
# 初始化 ChatOllama 模型
chat = ChatOllama(model="qwen3:1.7b")
# 定义提示模板
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个助手,请准确回答问题。"),
("human", "{question}")
])
# 创建链
chain = prompt | chat
# 调用链
response = chain.invoke({"question": "什么是人工智能?"})
print(response.content)
输出示例:
人工智能(AI)是计算机科学的一个分支,旨在开发能够执行需要人类智能的任务的系统,例如学习、推理、问题解决和决策。
问题:
from langchain_community.chat_models import ChatOllama
已废弃,需替换为from langchain_ollama import ChatOllama
。- 需要安装
langchain_ollama
包。 - 确保本地 Ollama 服务运行并支持指定模型(如
qwen3:1.7b
)。
2. 安装必要依赖
确保安装 LangChain 0.3.x 和 langchain_ollama
:
pip install --upgrade langchain langchain-ollama
此外,需确保本地已安装并运行 Ollama 服务:
- 安装 Ollama:参考 Ollama 官网,下载并安装。
- 拉取模型:
ollama pull qwen3:1.7b
- 启动 Ollama 服务:
ollama serve
3. 迁移到 langchain_ollama.ChatOllama
以下是迁移后的代码,替换 ChatOllama
的导入:
from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain_core.output_parsers import StrOutputParser
# 初始化 ChatOllama 模型
chat = ChatOllama(model="qwen3:1.7b")
# 创建系统消息模板
system_template = SystemMessagePromptTemplate.from_template(
"你是一个助手,请准确回答问题。"
)
# 创建用户消息模板
human_template = HumanMessagePromptTemplate.from_template(
"{question}"
)
# 构建 ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
system_template,
human_template
])
# 创建 LCEL 链
chain = prompt | chat | StrOutputParser()
# 调用链
response = chain.invoke({"question": "什么是人工智能?"})
print(response)
输出示例:
人工智能(AI)是计算机科学的一个分支,旨在开发能够执行需要人类智能的任务的系统,例如学习、推理、问题解决和决策。
代码说明
- 导入替换:
- 将
from langchain_community.chat_models import ChatOllama
替换为from langchain_ollama import ChatOllama
。 - 功能保持不变,
ChatOllama
与本地 Ollama 服务交互,支持消息格式。
- 将
- 模型初始化:
ChatOllama(model="qwen3:1.7b")
指定模型名称,确保本地已拉取该模型。- 默认连接到本地 Ollama 服务(
http://localhost:11434
)。
- 提示模板:
- 使用
ChatPromptTemplate
定义系统和用户消息,适合聊天模型。
- 使用
- LCEL 链:
prompt | chat
创建链,处理消息输入并生成AIMessage
输出。
- 调用:
- 输入为字典(
{"question": "..."}
),输出为AIMessage
,访问response.content
。
- 输入为字典(
4. 结合对话历史(推荐)
为了支持多轮对话,结合 RunnableWithMessageHistory
:
from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
# 初始化 ChatOllama 模型
chat = ChatOllama(model="qwen3:1.7b")
# 创建系统消息模板
system_template = SystemMessagePromptTemplate.from_template(
"你是一个助手,请根据对话历史回答问题。"
)
# 创建用户消息模板
human_template = HumanMessagePromptTemplate.from_template(
"{input}"
)
# 构建 ChatPromptTemplate
prompt = ChatPromptTemplate.from_messages([
system_template,
MessagesPlaceholder(variable_name="history"),
human_template
])
# 创建 LCEL 链
runnable = prompt | chat
# 初始化消息历史存储
store = {}
def get_session_history(session_id: str) -> ChatMessageHistory:
if session_id not in store:
store[session_id] = ChatMessageHistory()
return store[session_id]
# 创建带历史的链
chain = RunnableWithMessageHistory(
runnable,
get_session_history,
input_messages_key="input",
history_messages_key="history"
)
# 调用链
session_id = "user1"
response = chain.invoke(
{"input": "我叫鲍勃"},
config={"configurable": {"session_id": session_id}}
)
print(response.content)
response = chain.invoke(
{"input": "我的名字是什么?"},
config={"configurable": {"session_id": session_id}}
)
print(response.content)
输出示例:
你好,鲍勃!很高兴认识你!有什么可以帮助你的?
你的名字是鲍勃。
说明:
RunnableWithMessageHistory
管理对话历史,ChatMessageHistory
存储消息。MessagesPlaceholder
插入历史消息,支持多轮对话。- 输入为字典(
{"input": "..."}
),输出为AIMessage
。
5. 结合工具调用(可选)
若需支持工具调用,ChatOllama
支持部分模型的工具调用功能(需确认 qwen3:1.7b
是否支持)。示例:
from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import tool
# 定义工具
@tool
def search_web(query: str) -> str:
"""搜索网络以获取信息。"""
return f"搜索 {query} 的结果:[示例内容]"
# 初始化 ChatOllama 模型并绑定工具
chat = ChatOllama(model="qwen3:1.7b").bind_tools([search_web])
# 定义提示模板
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个助手,可以使用工具回答问题。"),
("human", "{question}")
])
# 创建 LCEL 链
chain = prompt | chat
# 调用链
response = chain.invoke({"question": "成都的天气如何?"})
print(response.tool_calls)
输出示例(若模型支持工具调用):
[{'name': 'search_web', 'args': {'query': '成都天气'}, 'id': 'call_123'}]
说明:
- 使用
bind_tools
绑定工具,ChatOllama
将尝试生成工具调用。 - 需验证
qwen3:1.7b
是否支持工具调用(部分 Ollama 模型可能不支持)。
6. 测试与验证
- 确认 Ollama 服务:
- 确保 Ollama 服务运行(
ollama serve
)。 - 验证模型可用:
ollama list
检查是否包含qwen3:1.7b
。
- 确保 Ollama 服务运行(
- 运行代码:
- 确认迁移后输出与原代码一致。
- 测试多轮对话(若使用历史管理),验证上下文保留。
- 若使用工具调用,验证工具调用输出。
- 检查依赖:
- 确保
langchain_ollama
已安装。 - 无需 OpenAI 密钥,除非代码涉及其他 OpenAI 功能。
- 确保
注意事项
-
Ollama 服务:
- 确保本地 Ollama 服务运行,默认监听
http://localhost:11434
。 - 若自定义地址,设置
base_url
参数:chat = ChatOllama(model="qwen3:1.7b", base_url="http://your-host:port")
- 确保本地 Ollama 服务运行,默认监听
-
模型支持:
- 确认
qwen3:1.7b
已通过ollama pull
下载。 - 支持其他 Ollama 模型(如
llama3
、mistral
),参考 Ollama 模型库。 - 工具调用需模型支持,参考 Ollama 文档。
- 确认
-
性能:
- 本地 Ollama 模型性能依赖硬件(CPU/GPU),可能比云端模型(如
gpt-4o-mini
)慢。 - 调整参数(如
num_ctx
、temperature
)优化性能:chat = ChatOllama(model="qwen3:1.7b", temperature=0.7, num_ctx=2048)
- 本地 Ollama 模型性能依赖硬件(CPU/GPU),可能比云端模型(如
-
LCEL 兼容性:
langchain_ollama.ChatOllama
完全支持 LCEL,适合现代工作流(如prompt | chat
)。
常见问题
Q1:可以继续使用 langchain_community.chat_models.ChatOllama
吗?
A:可以,但不建议。它将在 LangChain 1.0 中移除,迁移到 langchain_ollama.ChatOllama
更安全。
Q2:langchain_ollama.ChatOllama
和旧 ChatOllama
功能有差异吗?
A:功能基本相同,但新类更稳定,支持 LangChain 0.3.x 的新功能(如 LCEL、工具调用优化)。
Q3:如何选择 Ollama 模型?
A:根据任务和硬件选择。qwen3:1.7b
轻量,适合低资源环境;llama3:8b
或 mistral
更强大,需更多内存。
Q4:ChatOllama
支持工具调用吗?
A:支持,但需模型支持工具调用(如 qwen3
的具体版本)。参考 Ollama 文档。
总结
从 langchain_community.chat_models.ChatOllama
迁移到 langchain_ollama.ChatOllama
的步骤包括:
- 安装
langchain
和langchain-ollama
(pip install langchain langchain-ollama
)。 - 替换导入:
from langchain_community.chat_models import ChatOllama
改为from langchain_ollama import ChatOllama
。 - 确保本地 Ollama 服务运行并包含指定模型(如
qwen3:1.7b
)。 - 使用
ChatPromptTemplate
和 LCEL 构建现代对话工作流。 - 可选添加
RunnableWithMessageHistory
支持对话历史,或bind_tools
支持工具调用。