【LangChain专栏】LangChain 调用Ollama本地大模型

文章目录

随着本地大模型生态逐渐成熟,越来越多开发者开始使用本地部署的模型来构建 AI 应用。相比调用云端 API,本地模型具备:
• 数据隐私可控
• 无需外网依赖
• 成本更低
• 可定制化强

一、什么是Ollama?

Ollama 是一个本地运行大语言模型的工具,支持一键下载并运行模型,如:

• Llama 3

• Mistral

• Qwen

特点:

• 安装简单(支持 macOS / Linux / Windows)

• 支持 REST API

• 支持模型管理与自定义 Modelfile

• 资源占用相对可控

二、环境准备

1.安装Ollama

官网下载安装即可,安装完成后验证:

ollama --version下载模型:

ollama pull llama3 启动模型:

ollama run llama3 若能正常对话,说明模型运行成功。

2.安装Python 依赖

bash 复制代码
pip install langchain langchain-community langchain-core

如果需要 Web API:

bash 复制代码
pip install fastapi uvicorn

三、LangChain 调用 Ollama

1.基础调用示例

bash 复制代码
from langchain_community.llms import Ollama

llm = Ollama(
    model="qwen3:4b"
)

response = llm.invoke("请用一句话介绍人工智能")
print(response)

执行后,LangChain 会调用本地 Ollama 服务,并返回模型生成结果。

2.使用Chat模型方式

bash 复制代码
from langchain_community.chat_models import ChatOllama
from langchain_core.messages import HumanMessage

chat = ChatOllama(
    model="qwen3:4b"
)

response = chat.invoke([
    HumanMessage(content="帮我写一段Java代码实现冒泡排序")
])

print(response.content)

适合多轮对话场景。

四、结合PromptTemplate 使用

bash 复制代码
from langchain_classic.chains.llm import LLMChain
from langchain_community.llms import Ollama
from langchain_core.prompts import PromptTemplate

template = """
你是一名专业程序员,请回答以下问题:
问题:{question}
"""

prompt = PromptTemplate(
    input_variables=["question"],
    template=template
)

llm = Ollama(model="qwen3:4b")

chain = LLMChain(llm=llm, prompt=prompt)

result = chain.invoke({"question": "什么是线程安全?"})
print(result["text"])

五、构建一个简单对话接口(FastAPI)

bash 复制代码
from fastapi import FastAPI
from langchain_community.chat_models import ChatOllama
from langchain_core.messages import HumanMessage

app = FastAPI()

chat = ChatOllama(model="llama3")

@app.post("/chat")
def chat_api(question: str):
    response = chat.invoke([HumanMessage(content=question)])
    return {"answer": response.content}

启动:

bash 复制代码
uvicorn main:app --reload

访问:

bash 复制代码
POST http://localhost:8000/chat

即可调用本地大模型接口。

六、常见问题

1.模型响应慢怎么办?

优化方式:

• 选择参数较小的模型(如 7B)

• 使用量化模型(Q4/Q8)

• 增加内存

• 调整 num_ctx

2.如何查看已安装模型?

bash 复制代码
ollama list

3.mac m1安装ollama安装包dmg失败

当前版本不支持m1架构,可切换到其他版本安装

https://github.com/ollama/ollama/releases

相关推荐
正经教主12 小时前
【FDE系列】阶段3:Day 77:LangChain 基础 — LCEL 管道与三件套
人工智能·langchain·agent·fde
小林ixn13 小时前
FastAPI + LangChain 实战:从 0 到 1 打造高性能 AI 后端服务
人工智能·langchain·fastapi
LMT流氓兔16 小时前
第五单元——第9课:防止同一次操作重复执行
java·服务器·数据库·算法·ai·langchain
一千柯橘18 小时前
LangChain Tools 进阶:动态工具、Headless 客户端工具、MCP 协议集成与服务端工具
langchain
LMT流氓兔20 小时前
第五单元——第11课:自动测试“拒绝后绝不能写入”
数据库·人工智能·python·langchain
ratel️20 小时前
小墨析 · Office Agent 日常办公不烧心
python·langchain·word·excel·fastapi·js·ppt
一千柯橘21 小时前
LangChain Tools:从基础定义、上下文访问到错误处理
langchain
LMT流氓兔1 天前
第五单元——第10课:用自动化测试验证工具逻辑
数据库·ai·oracle·langchain
云和数据.ChenGuang1 天前
Python 集合(set)常用函数详解与实战案例
开发语言·python·深度学习·langchain
吴凡wudianmei2 天前
线上出问题不知道卡在哪?全链路追踪 + 三端统一部署
架构·langchain·llm