LangChain调用大模型有两种方式。
1、使用Ollama
此方式需要先到 https://ollama.com/ 下载Ollama并进行安装,安装成功后打开一个终端运行 ollama run qwen2.5:3b,意思是拉取并运行qwen2.5:3b。如果成功则说明ollama已可以正常使用,接着安装LangChain,安装它还是很方便的,如下:
LangChain 核心包:pip install langchain-core
LangChain 社区包:pip install langchain-community
LangChain 实验包:pip install langchain-experimental
LangGraph 库:pip install langgraph
LangServe 工具:pip install “langserve(all)”
OpenAI 集成包:pip install langchain-openai
安装成功后就可以编写python代码了,如下:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_ollama import ChatOllama
import gradio as gr
class TechArticleGenerator:
def __init__(self, model_name="qwen2.5:7b"):
template = """
你好!我叫枫叶,是一名技术博主,欢迎与您的到来,让我们共同进步吧!。
"""
self.prompt = ChatPromptTemplate.from_messages([("system", template), ("user", "{input}")])
self.model = ChatOllama(model=model_name)
self.chain = self.prompt | self.model | StrOutputParser()
def generate_article(self, query, history=None):
print("Human: ", query)
result = self.chain.invoke({"input": query})
print("AI: ", result)
return result
# 初始化技术文章生成器
tech_generator = TechArticleGenerator()
def query_with_chatollama(query, history=None):
return tech_generator.generate_article(query)
iface = gr.ChatInterface(
fn=query_with_chatollama,
title="技术博主在线助手",
description="您好!欢迎使用技术博主在线助手。",
examples=["RAG应用开发与优化", "Java多线程变编程", "Python数据分析与可视化"]
)
# 启动Gradio接口
iface.launch()
顺便说下,为了输出好看,顺便采用了gradio。如此一个简易的LangChain+ollama使用大模型demo就完成了。
2、使用本机部署的大模型
此方式对硬件要求较高,一般要求有cuda,显存至少16G。首先先到魔塔社区下载大模型,如下:
from modelscope import snapshot_download
# 设置下载模型的本地目录路径
local_model_dir = './models/qwen25-1dot5b'
# 调用 snapshot_download 函数,并指定 cache_dir 参数
print("Downloading Qwen2.5-1.5b model...")
model_dir = snapshot_download(
"Qwen/Qwen2.5-1.5B-Instruct",
cache_dir=local_model_dir # 指定下载目录
)
print("Model downloaded to:", model_dir)
print("Done!")
通过上述代码就将大模型下载到本机,这里下载的是Qwen2.5-1.5b模型,如果需要下载其他模型可以登录莫塔社区官网的大模型模块中自行选择,上面也有很详细的下载方法,此处不再赘述。使用本机部署的大模型还需要安装tensorflow和torch两个开源模块,安装方法也是很简单,pip install tensorflow,pip install torch即可,接着就可以编写代码了,如下:
from langchain_core.prompts import ChatPromptTemplate
import gradio as gr
from transformers import AutoModelForCausalLM,AutoTokenizer
import torch
class InteractiveWithQwen25:
def __init__(self,model_path="./models/qwen25-3b"):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {self.device}")
print("加载模型中...")
self.tokenizer = AutoTokenizer.from_pretrained(model_path)
self.model = AutoModelForCausalLM.from_pretrained(model_path)
self.model.to(self.device)
self.model.eval()
print("模型加载完成!")
template = """
你好!我叫枫叶,是一名技术博主,欢迎与您的到来,让我们共同进步吧!。
"""
self.prompt = ChatPromptTemplate.from_messages([("system", template), ("user", "{input}")])
def generate_article(self, query, history=None):
print("Human: ", query)
prompt = self.prompt.format_prompt(input=query).to_messages()
prompt_text = "\n".join([msg.content for msg in prompt])
inputs = self.tokenizer(prompt_text, return_tensors="pt").to(self.device)
outputs = self.model.generate(**inputs, max_new_tokens=1024, do_sample=True, temperature=0.7)
result = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
print("AI: ", result)
return result
if __name__ == "__main__":
tech_generator = InteractiveWithQwen25()
def query_with_chatollama(query,history=None):
return tech_generator.generate_article(query)
iface = gr.ChatInterface(
fn=query_with_chatollama,
title="技术博主在线助手",
description="您好!欢迎使用技术博主在线助手。",
examples=["RAG应用开发与优化", "Java多线程编程", "Python数据分析与可视化"]
)
iface.launch()
如此,一个简易的LangChain+本机部署大模型搭建的demo就完成了!