跳到主要内容
极客日志极客日志
首页博客AI提示词GitHub精选代理工具
|注册
博客列表

目录

  1. 1. 克隆代码
  2. 2. 编译配置
  3. 3. 下载模型
  4. 4. 启动服务
  5. CPU 版
  6. GPU 加速版 (Server)
  7. 5. 测试调用
  8. 6. Python 脚本调用
  9. 基础非流式调用
  10. 多轮对话示例
  11. 工具调用测试
PythonAI算法

Windows 环境 llama.cpp 编译与 Qwen 模型本地部署

介绍在 Windows 10/11 环境下编译 llama.cpp 并部署 Qwen 模型。步骤包括克隆代码、配置 CMake 编译(支持 CPU/GPU)、通过 ModelScope 下载 GGUF 格式模型、启动本地 API 服务,并提供 Python 脚本测试基础调用、多轮对话及工具功能。

佛系玩家发布于 2026/4/5更新于 2026/4/131 浏览

本地轻量化部署因低延迟、高隐私性、无需依赖云端算力等优势,成为开发者热门需求。本文聚焦 Windows 10/11(64 位)环境,详解 llama.cpp 编译流程及 Qwen 模型本地部署。

1. 克隆代码

打开管理员权限的 PowerShell/CMD,执行以下命令:

git clone https://github.com/ggml-org/llama.cpp
mkdir build
cd build

2. 编译配置

仅 CPU 支持或启用 GPU 加速(需安装 CUDA Toolkit)。

CPU 模式:

cmake .. -G "Visual Studio 17 2022" -A x64 -DLLAMA_CURL=OFF
cmake --build . --config Release

GPU 模式:

cmake .. -G "Visual Studio 17 2022" -A x64 -DLLAMA_CUDA=ON
cmake --build . --config Release

3. 下载模型

使用 ModelScope 下载 GGUF 格式的 Qwen 模型(以 7B 为例)。

pip install modelscope
modelscope download --model Xorbits/Qwen-7B-Chat-GGUF

下载后保存位置通常为 \modelscope\hub\models\Xorbits。

4. 启动服务

运行模型启动 API 服务,默认监听 8080 端口。

# CPU 版
chcp 65001
llama-cli.exe -m qwen.gguf -i -c 4096

# GPU 加速版 (Server)
llama-server.exe -m qwen-7b-chat.Q4_0.gguf -c 4096 --port 8080 --host 127.0.0.1 --n-gpu-layers -1

5. 测试调用

服务启动后,可通过 curl 测试。

curl http://localhost:8080/completion -H "Content-Type: application/json" -d '{ "prompt": "你好", "temperature": 0.7, "max_tokens": 512 }'

6. Python 脚本调用

基础非流式调用
import requests
import json

url = "http://localhost:8080/completion"
headers = {"Content-Type": "application/json"}
data = {
    "model": "qwen.gguf",
    "prompt": "你好,请用 100 字介绍一下通义千问",
    : ,
    : ,
    : ,
    : []
}

:
    response = requests.post(url, headers=headers, data=json.dumps(data), timeout=)
    response.raise_for_status()
    result = response.json()
    ()
    (result[])
 Exception  e:
    ()
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog

更多推荐文章

查看全部
  • Neo4j 安装与配置教程(Windows/MacOS/Linux)
  • Llama 3.1 开源模型快速部署教程
  • Vue 3 异步组件与智能加载方案:defineAsyncComponent、import.meta.glob 与 Suspense
  • CAM++ webUI 界面二次开发与自定义修改指南
  • AIGC 技术现状、应用场景与未来趋势
  • Spring Boot 集成 WebSocket 实现后台向前端推送信息
  • AMD 显卡 AI 绘画配置与性能优化指南

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • RSA密钥对生成器

    生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online

  • Mermaid 预览与可视化编辑

    基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online

  • curl 转代码

    解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

"temperature"
0.7
"max_tokens"
512
"ctx_size"
4096
"stop"
"<|im_end|"
try
60
print
"生成结果:"
print
"content"
except
as
print
f"调用失败:{e}"
多轮对话示例
import requests
import json

chat_history = []
url = "http://localhost:8080/chat/completions"
headers = {"Content-Type": "application/json"}

def chat_with_model(prompt):
    chat_history.append({"role": "user", "content": prompt})
    data = {
        "model": "qwen.gguf",
        "messages": chat_history,
        "temperature": 0.7,
        "max_tokens": 512
    }
    try:
        response = requests.post(url, headers=headers, data=json.dumps(data), timeout=60)
        response.raise_for_status()
        result = response.json()
        answer = result["choices"][0]["message"]["content"]
        chat_history.append({"role": "assistant", "content": answer})
        return answer
    except Exception as e:
        return f"调用失败:{e}"

print("开始多轮对话(输入'退出'结束):")
while True:
    user_input = input("你:")
    if user_input == "退出":
        break
    answer = chat_with_model(user_input)
    print(f"助手:{answer}\n")
工具调用测试
import requests
import json
import re
from datetime import datetime

tool_registry = {
    "get_current_time": {
        "function": lambda: f"当前时间为:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
        "description": "获取当前的本地时间,无需参数",
        "parameters": {}
    },
    "calculate_add": {
        "function": lambda a, b: f"{a} + {b} = {a + b}",
        "description": "计算两个数字的加法",
        "parameters": {
            "a": {"type": "float", "required": True},
            "b": {"type": "float", "required": True}
        }
    }
}

chat_history = [{"role": "system", "content": "你是一个有帮助的助手,可以调用工具辅助回答。"}]
url = "http://localhost:8080/chat/completions"
headers = {"Content-Type": "application/json"}

def clean_pad_content(content):
    return re.sub(r'\[PAD\d+\]', '', content).strip()

def parse_tool_call(content):
    try:
        json_match = re.search(r'\{[\s\S]*\}', content)
        if not json_match:
            return None
        tool_call = json.loads(json_match.group())
        if "name" in tool_call and "parameters" in tool_call:
            return tool_call
    except Exception:
        pass
    return None

def execute_tool(tool_call):
    tool_name = tool_call["name"]
    parameters = tool_call.get("parameters", {})
    if tool_name not in tool_registry:
        return f"错误:不存在名为 {tool_name} 的工具"
    tool_info = tool_registry[tool_name]
    try:
        result = tool_info["function"](**parameters)
        return f"工具调用成功:{result}"
    except Exception as e:
        return f"错误:执行失败 - {str(e)}"

def chat_with_model(prompt):
    global chat_history
    chat_history.append({"role": "user", "content": prompt})
    data = {
        "model": "qwen.gguf",
        "messages": chat_history,
        "temperature": 0.7,
        "max_tokens": 512,
        "stream": False,
        "stop": ["[PAD"]
    }
    try:
        response = requests.post(url, headers=headers, data=json.dumps(data), timeout=60)
        response.raise_for_status()
        result = response.json()
        if "choices" in result and len(result["choices"]) > 0:
            raw_answer = result["choices"][0]["message"]["content"]
            clean_answer = clean_pad_content(raw_answer)
            tool_call = parse_tool_call(clean_answer)
            if tool_call:
                tool_result = execute_tool(tool_call)
                chat_history.append({"role": "assistant", "content": f"工具调用结果:{tool_result}"})
                second_response = requests.post(url, headers=headers, data=json.dumps(data), timeout=60)
                second_result = second_response.json()
                final_answer = clean_pad_content(second_result["choices"][0]["message"]["content"])
                chat_history.append({"role": "assistant", "content": final_answer})
                return final_answer
            else:
                chat_history.append({"role": "assistant", "content": clean_answer})
                return clean_answer
    except Exception as e:
        return f"调用失败:{str(e)}"

if __name__ == "__main__":
    print("开始多轮对话(输入'退出'结束):")
    while True:
        user_input = input("你:")
        if user_input.strip() == "退出":
            break
        if not user_input.strip():
            continue
        answer = chat_with_model(user_input)
        print(f"助手:{answer}\n")
LLaMA-Factory 微调多模态大模型 Qwen3-VL
  • PX4 无人机 MID360 结合 FAST_LIO 实现室内自主定位与定点
  • Unity 开发:VS Code 集成 AI 编程插件配置指南
  • Spring MVC 快速入门:Web 响应处理
  • 15 个提示词降低 AIGC 检测率,优化写作人类化表达
  • FLUX.1-dev 工作流:Midjourney 迁移指南与 Prompt 工程适配
  • 本地搭建带知识库的 AI 助手:Ollama + Open WebUI
  • 基于小米 9 与天马 G 前端的复古掌机搭建指南
  • StreamVLN 具身导航复现与模型推理指南
  • HTML 网页结构搭建:从语义化标签到整站规划
  • HTML5 结合 AI 实现智能场景渲染与应用实践
  • AI 赋能原则 10 解读:政府 2.0 与全民能力跃迁
  • 循环神经网络(RNN)与序列数据处理实战