【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>
    
    你好!很高兴见到你,有什么我可以帮忙的吗?无论是聊天、解答问题还是提供建议,我都在这里为你服务。😊
相关推荐
云和数据.ChenGuang7 小时前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain
AI日报派送佬11 小时前
2026年11月01日AI行业日报|可灵AI198亿融资落地、DeepSeek开源超级智能体、Anthropic取消Ultra时长限制
人工智能·开源·openai·deepseek·anthropic·ai日报
张张123y12 小时前
后端第十六课:Multi-Agent 多智能体(让多个 Agent 分工协作)
大数据·数据库·人工智能·python·deepseek·dsh·agent 框架
hqk16 小时前
AI Agent 学习总结:从模型到 Harness
langchain·aigc
一枕槐安48717 小时前
开源大模型 Llama3 本地部署全过程,Ollama 上手
开源·本地部署·大模型推理·ollama·llama3·modelfile
日日大王学编程19 小时前
开源Agent项目记忆设计决策对比
python·ai·langchain·开源·ai编程
fellow9920 小时前
DSH Desktop - Android Edition
android·agent·deepseek·harness·dsh
潘锦1 天前
DeepSeek Harness 的 Harness 到底做了什么
deepseek
前端精髓1 天前
结构化输出with_structured_output(抽卡)
python·langchain
LMT流氓兔1 天前
第五单元——第十六课:给书店助手加上网页界面
java·开发语言·jvm·人工智能·oracle·langchain·1024程序员节