【langchain/入门】使用langchain调用本地部署的大模型(以llama.cpp以及ollama为例)

文章目录

说在前面

  • 操作系统:windows
  • python版本:3.9
  • langchain版本:0.3.20
  • pycharm版本:2023.1.2 (Community Edition)
  • ollama版本:0.5.4
  • llama.cpp版本:b4870

ollama(qwen2.5-coder:7b)

部署模型

  • ollama部署大模型比较简单,到官网下载安装包后安装

  • 根据自己电脑的条件选择合适的模型,比如

  • 然后打开命令行,执行

    shell 复制代码
    ollama run qwen2.5-coder
  • 然后就可以直接在命令行对话了

    shell 复制代码
    $ ollama run qwen2.5-coder:latest
    >>> 你好
    你好!有什么我可以帮忙的吗?
    
    >>> Send a message (/? for help)

使用langchain

  • langchain提供了直接调用ollama api的package,安装后直接使用即可

    shell 复制代码
    pip install langchain-ollama
  • 代码环节

    shell 复制代码
    from langchain_ollama import OllamaLLM
    
    ollm = OllamaLLM(model="qwen2.5-coder:latest")
    print(ollm.invoke("你好"))

    运行

    shell 复制代码
    (venv) PS D:\Code\langchain> python .\main.py
    你好!有什么我可以帮忙的吗?

llama.cpp(deepseek-r1:1.5b)

模型部署

  • 算力不足,搞个1.5b测试吧

  • llama.cpp部署也挺简单的,到github选择合适的版本

  • x64-windows-nvdia gpu
    下载cudart-llama-bin-win-cuxx.x-x64.zip以及llama-b4870-bin-win-cuda-cuxx.x-x64.zip,其中cudart是cuda相关的依赖,解压后将里面的文件放到llama...zip解压后的同级目录即可
    例如

  • mac-m4
    下载llama-b4870-bin-macos-arm64.zip解压即可

  • 使用llama-client即可在命令行下进行交互,例如

    shell 复制代码
    ./llama-cli -m DeepSeek-R1-Distill-Qwen-1.5B-Q4_K_M.gguf
    > 你好
    <think>
    
    </think>
    你好!很高兴见到你,有什么我可以帮忙的吗?无论是聊天、解答问题还是提供建议,我都在这里为你服务。😊
  • 如果需要让langchain能够使用,需要部署服务,即使用llama-server

    shell 复制代码
    ./llama-sever -m DeepSeek-R1-Distill-Qwen-1.5B-Q4_K_M.gguf --port 50052 --host 0.0.0.0 -c 2048

使用langchain

  • llama.cpp部署的服务使用的API格式是与openai兼容的,所以在langchain中,我们可以使用openai对应的package

    shell 复制代码
    pip install langchain-openai
  • 代码环节

    python 复制代码
    from langchain_openai import ChatOpenAI
    
    llm = ChatOpenAI(max_tokens=None,
                     timeout=None,
                     openai_api_base="http://127.0.0.1:50052",
                     openai_api_key="none")
    # openai_api_base 就是llama-server 部署时监听的地址
    # openai_api_key 必须要填 随便填就行 不能为 ""
    print(llm.invoke("你好").content)

    运行

    shell 复制代码
    (venv) PS D:\Code\langchain> python .\main.py
    <think>
    
    </think>
    
    你好!很高兴见到你,有什么我可以帮忙的吗?无论是聊天、解答问题还是提供建议,我都在这里为你服务。😊
相关推荐
是一碗螺丝粉12 小时前
LangChain 链(Chains)完全指南:从线性流程到智能路由
前端·langchain·aigc
前端付豪12 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
神秘的猪头12 小时前
🔌 给 AI 装上“三头六臂”!实战大模型接入第三方 MCP 全攻略
langchain·llm·mcp
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
神秘的猪头1 天前
🔌 把 MCP 装进大脑!手把手带你构建能“热插拔”工具的 AI Agent
langchain·llm·mcp
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
是一碗螺丝粉2 天前
5分钟上手LangChain.js:用DeepSeek给你的App加上AI能力
前端·人工智能·langchain
是一碗螺丝粉2 天前
LangChain 核心组件深度解析:模型与提示词模板
前端·langchain·aigc
大模型真好玩3 天前
大模型训练全流程实战指南工具篇(七)——EasyDataset文档处理流程
人工智能·langchain·deepseek