Windows 环境下 llama.cpp 编译 + Qwen 模型本地部署全指南

在大模型落地场景中,本地轻量化部署因低延迟、高隐私性、无需依赖云端算力等优势,成为开发者与 AI 爱好者的热门需求。本文聚焦 Windows 10/11(64 位)环境,详细拆解 llama.cpp 工具的编译流程(支持 CPU/GPU 双模式,GPU 加速需依赖 NVIDIA CUDA),并指导如何通过 modelscope 下载 GGUF 格式的 Qwen-7B-Chat 模型,最终实现模型本地启动与 API 服务搭建。

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 18 2026"-A x64 -DLLAMA_CURL=OFF cmake --build.--config Release 如果已安装 CUDA Toolkit,添加 -DLLAMA_CUDA=ON 开启 GPU 支持 cmake ..-G"Visual Studio 18 2026"-A x64 -DLLAMA_CUDA=ON cmake --build.--config Release 

3、下载 GGUF 格式的 Qwen 模型(以 7B 为例)

https://www.modelscope.cn/models pip install modelscope modelscope download --model Xorbits/Qwen-7B-Chat-GGUF 

下载后的保存位置为 \modelscope\hub\models\Xorbits

4、运行模型启动 API 服务(支持 HTTP 调用)

# 命令行启动 chcp 65001 llama-cli.exe -m qwen.gguf -i-c4096# CPU 版 llama-server.exe -m qwen.gguf --host127.0.0.1 --port11433-c4096# GPU 加速版 llama-server.exe -m qwen-7b-chat.Q4_0.gguf -c4096 --n-gpu-layers -1

5、服务启动后默认监听 http://localhost:8080,可通过 curl 测试调用效果。

curl http://localhost:8080/completion -H"Content-Type: application/json"-d'{ "prompt": "你好,介绍一下通义千问", "temperature": 0.7, "max_tokens": 512 }'

6、工具测试,通过代码调用大模型测试效果。

基础非流式调用(completion 端点)

import requests import json url ="http://localhost:8080/completion" headers ={"Content-Type":"application/json"} data ={"model":"qwen.gguf","prompt":"你好,请用100字介绍一下通义千问","temperature":0.7,# 回答随机性(越低越保守)"max_tokens":512,# 最大生成token数"ctx_size":4096,# 上下文窗口(与服务启动时一致)"stop":["<|im_end|>"]# 停止符(适配Qwen的对话格式)}try: response = requests.post(url, headers=headers, data=json.dumps(data), timeout=60) response.raise_for_status() result = response.json()print("生成结果:")print(result["content"])except Exception as e:print(f"调用失败:{e}")

多轮对话示例(基于 chat/completions)

import requests import json chat_history =[] url ="http://localhost:8080/chat/completions" headers ={"Content-Type":"application/json"}defchat_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:returnf"调用失败:{e}"# 多轮对话示例print("开始多轮对话(输入'退出'结束):")whileTrue: user_input =input("你:")if user_input =="退出":break answer = chat_with_model(user_input)print(f"助手:{answer}\n")

带有对话记忆功能测试

import requests import json import re # 初始化对话历史(包含系统提示,引导模型记上下文) chat_history =[{"role":"system","content":"你是一个有帮助的助手,必须记住之前的对话内容,基于上下文回答用户问题。"}]# 你的服务实际地址(保持你原来的 11433 端口和 OpenAI 兼容路径) url ="http://localhost:11433/chat/completions" headers ={"Content-Type":"application/json"}defclean_pad_content(content):"""过滤模型返回的 [PAD...] 垃圾字符"""return re.sub(r'\[PAD\d+\]','', content).strip()defchat_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"]# 提前终止 PAD 字符的输出}try: response = requests.post(url, headers=headers, data=json.dumps(data), timeout=60) response.raise_for_status()# 触发 HTTP 错误(比如 404、500) result = response.json()print(f"调试:模型原始返回 = {json.dumps(result, ensure_ascii=False)[:500]}")# 可选:查看原始返回# 适配你的 OpenAI 兼容格式:从 choices[0].message.content 提取内容if"choices"in result andlen(result["choices"])>0: choice = result["choices"][0]if"message"in choice and"content"in choice["message"]: raw_answer = choice["message"]["content"] answer = clean_pad_content(raw_answer)# 过滤 PAD 垃圾字符# 关键:将助手回复加入历史,下次请求会带上 chat_history.append({"role":"assistant","content": answer})return answer else:returnf"返回格式异常:缺少 message/content 字段,原始返回:{json.dumps(result, ensure_ascii=False)[:300]}"else:returnf"返回格式异常:缺少 choices 字段,原始返回:{json.dumps(result, ensure_ascii=False)[:300]}"except requests.exceptions.ConnectionError:return"连接失败:请检查本地服务是否在 11433 端口运行"except requests.exceptions.Timeout:return"请求超时:模型响应过慢"except Exception as e:returnf"调用失败:{str(e)},原始返回:{response.text[:300]if'response'inlocals()else'无'}"# 多轮对话测试(重点测试上下文记忆)print("开始多轮对话(输入'退出'结束):")print("提示:先发送 '我的名字是李四',再发送 '我叫什么名字' 测试记忆功能\n")whileTrue: user_input =input("你:")if user_input.strip()=="退出":breakifnot user_input.strip():print("助手:请输入有效内容!\n")continue answer = chat_with_model(user_input)print(f"助手:{answer}\n")

函数工具调用测试

import requests import json import re from datetime import datetime # ====================== 1. 定义可用工具集 ======================# 工具1:获取当前时间defget_current_time():"""获取当前的本地时间,格式为 年-月-日 时:分:秒""" current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")returnf"当前时间为:{current_time}"# 工具2:加法计算defcalculate_add(a:float, b:float):"""计算两个数的加法结果"""returnf"{a} + {b} = {a + b}"# 工具注册表(核心:映射工具名到函数和描述,供模型识别) tool_registry ={"get_current_time":{"function": get_current_time,"description":"获取当前的本地时间,无需参数","parameters":{}# 无参数},"calculate_add":{"function": calculate_add,"description":"计算两个数字的加法,需要两个参数:a(数字)、b(数字)","parameters":{"a":{"type":"float","required":True,"description":"加数1"},"b":{"type":"float","required":True,"description":"加数2"}}}}# ====================== 2. 初始化对话历史和基础配置 ====================== chat_history =[{"role":"system","content":"""你是一个有帮助的助手,必须记住之前的对话内容,基于上下文回答用户问题。 你可以调用以下工具来辅助回答: 1. get_current_time:获取当前的本地时间,无需参数 2. calculate_add:计算两个数字的加法,需要参数a和b(均为数字) 如果需要调用工具,请严格按照以下JSON格式返回(仅返回JSON,不要加其他内容): {"name": "工具名", "parameters": {"参数名": 参数值}} 如果不需要调用工具,直接回答用户问题即可,不要返回JSON格式。"""}]# 本地LLM服务地址 url ="http://localhost:11433/chat/completions" headers ={"Content-Type":"application/json"}# ====================== 3. 工具调用相关辅助函数 ======================defclean_pad_content(content):"""过滤模型返回的 [PAD...] 垃圾字符"""return re.sub(r'\[PAD\d+\]','', content).strip()defparse_tool_call(content):"""解析模型返回的内容,提取工具调用指令(JSON格式)"""try:# 提取JSON部分(兼容模型返回时可能带的多余文字) json_match = re.search(r'\{[\s\S]*\}', content)ifnot json_match:returnNone tool_call = json.loads(json_match.group())# 验证必要字段if"name"in tool_call and"parameters"in tool_call:return tool_call returnNoneexcept(json.JSONDecodeError, Exception):returnNonedefexecute_tool(tool_call):"""执行工具调用,返回执行结果""" tool_name = tool_call["name"] parameters = tool_call.get("parameters",{})# 检查工具是否存在if tool_name notin tool_registry:returnf"错误:不存在名为 {tool_name} 的工具,可用工具:{list(tool_registry.keys())}" tool_info = tool_registry[tool_name] tool_func = tool_info["function"] tool_params = tool_info["parameters"]# 验证必填参数 missing_params =[]for param_name, param_info in tool_params.items():if param_info.get("required")and param_name notin parameters: missing_params.append(param_name)if missing_params:returnf"错误:调用 {tool_name} 缺少必填参数:{', '.join(missing_params)}"# 转换参数类型(比如字符串转数字)try:for param_name, param_info in tool_params.items():if param_name in parameters: param_type = param_info.get("type","str")if param_type =="float": parameters[param_name]=float(parameters[param_name])elif param_type =="int": parameters[param_name]=int(parameters[param_name])except ValueError as e:returnf"错误:参数类型转换失败 - {str(e)}"# 执行工具函数try: result = tool_func(**parameters)returnf"工具调用成功({tool_name}):{result}"except Exception as e:returnf"错误:执行 {tool_name} 失败 - {str(e)}"# ====================== 4. 核心对话函数(支持工具调用) ======================defchat_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 andlen(result["choices"])>0and"message"in result["choices"][0]: raw_answer = result["choices"][0]["message"]["content"] clean_answer = clean_pad_content(raw_answer)else:returnf"返回格式异常:{json.dumps(result, ensure_ascii=False)[:300]}"# 解析是否包含工具调用指令 tool_call = parse_tool_call(clean_answer)if tool_call:print(f"📢 检测到工具调用:{json.dumps(tool_call, ensure_ascii=False)}")# 执行工具并获取结果 tool_result = execute_tool(tool_call)print(f"🔧 工具执行结果:{tool_result}")# 将工具执行结果加入对话历史(让模型感知结果) chat_history.append({"role":"assistant","content":f"工具调用结果:{tool_result}"})# 第二步:基于工具结果,再次调用模型生成最终回答 second_response = requests.post(url, headers=headers, data=json.dumps(data), timeout=60) second_response.raise_for_status() second_result = second_response.json()# 解析第二次调用的结果if"choices"in second_result andlen(second_result["choices"])>0and"message"in \ second_result["choices"][0]: final_answer = clean_pad_content(second_result["choices"][0]["message"]["content"]) chat_history.append({"role":"assistant","content": final_answer})return final_answer else:returnf"工具调用后二次请求异常:{json.dumps(second_result, ensure_ascii=False)[:300]}"else:# 无需调用工具,直接返回模型回答 chat_history.append({"role":"assistant","content": clean_answer})return clean_answer except requests.exceptions.ConnectionError:return"连接失败:请检查本地服务是否在 11433 端口运行"except requests.exceptions.Timeout:return"请求超时:模型响应过慢"except Exception as e:returnf"调用失败:{str(e)},原始返回:{response.text[:300]if'response'inlocals()else'无'}"# ====================== 5. 多轮对话测试(含工具调用) ======================if __name__ =="__main__":print("开始多轮对话(输入'退出'结束):")print("📌 测试工具调用示例:")print(" 1. 现在几点了?(调用获取时间工具)")print(" 2. 计算123+456等于多少?(调用加法工具)")print(" 3. 我的名字是李四,我叫什么?(测试上下文记忆)\n")whileTrue: user_input =input("你:")if user_input.strip()=="退出":breakifnot user_input.strip():print("助手:请输入有效内容!\n")continue answer = chat_with_model(user_input)print(f"助手:{answer}\n")

Read more

Stable Diffusion底模对应的VAE推荐:提升生成质量的关键技术解析

Stable Diffusion底模对应的VAE推荐:提升生成质量的关键技术解析 引言:VAE在Stable Diffusion生态系统中的核心作用 变分自编码器(VAE)是Stable Diffusion生成架构中不可或缺的组件,负责将潜在空间表示与像素空间相互转换。尽管常常被忽视,VAE的质量直接影响图像生成的细节表现、色彩准确性和整体视觉效果。本文将深入解析不同Stable Diffusion底模对应的最优VAE配置,从技术原理到实践应用全面剖析VAE的选择策略。 VAE在Stable Diffusion中的核心功能包括: * 编码过程:将输入图像压缩到潜在空间表示(latent representation) * 解码过程:将潜在表示重构为高质量图像 * 正则化作用:确保潜在空间遵循高斯分布,便于扩散过程采样 一、VAE技术原理深度解析 1.1 变分自编码器的数学基础 变分自编码器的目标是学习数据的潜在表示,其数学基础建立在变分推断之上。给定输入数据 x x x,VAE试图最大化证据下界(ELBO): log ⁡ p ( x ) ≥ E q ( z ∣

Whisper-large-v3智能助手构建:基于Gradio的多语言语音交互界面

Whisper-large-v3智能助手构建:基于Gradio的多语言语音交互界面 想象一下,你有一段外语会议录音需要整理成文字,或者想为一段视频快速生成字幕,又或者只是想试试把语音实时转成文字。过去,你可能需要下载各种软件,或者忍受在线服务缓慢的速度和繁琐的步骤。 现在,情况完全不同了。基于OpenAI开源的Whisper Large v3模型,我们可以轻松搭建一个属于自己的、功能强大的语音识别Web服务。它不仅能识别99种语言,还能自动检测语言类型,支持上传文件和实时录音,而且完全在你的掌控之中。 今天,我就带你一步步构建这个智能语音助手,并用Gradio给它装上一个简洁好用的网页界面。整个过程就像搭积木一样简单,即使你不是专业的AI工程师,也能跟着完成。 1. 项目能做什么? 在开始动手之前,我们先看看这个项目搭建好后,能帮你解决哪些实际问题。 核心功能亮点: * 多语言识别:支持包括中文、英文、日语、法语、德语等在内的99种语言,系统能自动判断你上传的音频是哪种语言。 * 两种使用方式: * 文件上传:直接上传WAV、MP3、M4A等常见格式的音频文件

论文通关密码!paperxie 降重复 | AIGC 率工具,让学术写作告别 “红线” 焦虑

论文通关密码!paperxie 降重复 | AIGC 率工具,让学术写作告别 “红线” 焦虑

paperxie-免费查重复率aigc检测/开题报告/毕业论文/智能排版/文献综述/aippt https://www.paperxie.cn/weight?type=1https://www.paperxie.cn/weight?type=1https://www.paperxie.cn/weight?type=1 对于每一位学术创作者而言,论文的重复率与 AIGC 率,就像悬在头顶的两把 “达摩克利斯之剑”。重复率过高会被判定为学术不端,AIGC 率超标则可能被质疑内容真实性,二者任何一项不达标,都可能让数月的心血付诸东流。而 paperxie 的降重复 | AIGC 率功能,正是为破解这些痛点而生,用技术为学术写作保驾护航。 一、多场景覆盖,从源头解决学术 “合规” 难题 打开 paperxie

Qwen3-VL-WEBUI傻瓜式教程:文科生也能玩转AI绘画,1块钱体验

Qwen3-VL-WEBUI傻瓜式教程:文科生也能玩转AI绘画,1块钱体验 引言:AI绘画其实很简单 作为一名艺术生或创意工作者,你可能经常被各种AI绘画工具的技术术语吓退——"显存占用"、"量化精度"、"多模态模型"这些词听起来就像天书。但今天我要告诉你一个好消息:用Qwen3-VL-WEBUI玩转AI绘画,真的不需要懂编程。 Qwen3-VL是阿里最新推出的多模态大模型,它能同时理解文字和图像。而WEBUI则是它的"傻瓜操作界面",就像手机APP一样点按就能用。最关键的是,现在通过ZEEKLOG算力平台,1块钱就能体验这个强大的AI创作工具。 在这篇教程里,我会用最直白的语言,带你完成: 1. 零代码部署Qwen3-VL-WEBUI 2. 用自然语言生成惊艳画作 3. 调整几个简单参数获得理想效果 4. 解决新手常见问题 1. 准备工作:1分钟搞定环境 1.1 选择适合的GPU配置 虽然Qwen3-VL有多个版本,但我们要用的是专门优化过的8B版本,它对显存要求非常友好: