目录

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

【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 部署大模型比较简单,到 下载安装包后安装

    https://i-blog.csdnimg.cn/direct/cfcec07bf4954ef89d6e1ec8fb1b1f1f.png#pic_center

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

    https://i-blog.csdnimg.cn/direct/2f9b46a42d304184b2e742e3e96af67f.png#pic_center

  • 然后打开命令行,执行

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

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

使用langchain

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

    pip install langchain-ollama
  • 代码环节

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

    运行

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

llama.cpp(deepseek-r1:1.5b)

模型部署

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

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

    https://i-blog.csdnimg.cn/direct/fa6ebd41bc854ba7b288ff7546f4925c.png

  • 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 解压后的同级目录即可

    例如

    https://i-blog.csdnimg.cn/direct/eee2c1fbf0594fc790dda981fac81c3d.png

  • mac-m4

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

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

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

    ./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

    pip install langchain-openai
  • 代码环节

    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)

    运行

    (venv) PS D:\Code\langchain> python .\main.py
    <think>
    
    </think>
    
    你好!很高兴见到你,有什么我可以帮忙的吗?无论是聊天、解答问题还是提供建议,我都在这里为你服务。😊