EN

在 Ollama 本地服务器上部署任意 GGUF 模型 — 本地开发 AI

在 Ollama 本地服务器上运行任意 GGUF 模型的完整设置指南,用于本地开发 AI

返回教程列表🌐 Read in English
高级15 分钟

在 Ollama 本地服务器上部署任意 GGUF 模型 — 本地开发 AI

在 Ollama 本地服务器上运行任意 GGUF 模型的完整设置指南,用于本地开发 AI

在 Ollama 本地服务器上部署任意 GGUF 模型 概述 直接在 Ollama 本地服务器上运行任意 GGUF 模型,用于本地开发 AI。本地推理提供隐私、零延迟和无持续 API 成本。**规格**:CPU/GPU 自动 · 可变 安装

在 Ollama 本地服务器上部署任意 GGUF 模型

概述

直接在 Ollama 本地服务器上运行任意 GGUF 模型,用于本地开发 AI。本地推理提供隐私、零延迟和无持续 API 成本。

规格:CPU/GPU 自动 · 可变

安装

bash

安装 Ollama — 最简单的本地推理运行时

curl -fsSL https://ollama.com/install.sh | sh

验证安装

ollama --version

下载模型

bash

拉取任意 GGUF 模型(自动下载 GGUF 量化权重)

ollama pull any-gguf-model

运行交互式聊天

ollama run any-gguf-model

启动 API 服务器

ollama serve

API 地址:http://localhost:11434

Python 集成

python
import httpx
from typing import Iterator

class LocalAI: """本地任意 GGUF 模型的接口,运行在 Ollama 本地服务器上。""" BASE_URL = "http://localhost:11434" MODEL = "any-gguf-model" def chat(self, message: str, system: str = "") -> str: """单轮聊天。""" resp = httpx.post( f"{self.BASE_URL}/api/chat", json={ "model": self.MODEL, "messages": [ {"role": "system", "content": system}, {"role": "user", "content": message} ], "stream": False }, timeout=120 ) resp.raise_for_status() return resp.json()["message"]["content"] def stream(self, message: str) -> Iterator[str]: """流式聊天,实时输出。""" with httpx.stream( "POST", f"{self.BASE_URL}/api/chat", json={"model": self.MODEL, "messages": [{"role": "user", "content": message}], "stream": True}, timeout=120 ) as r: for line in r.iter_lines(): if line: import json chunk = json.loads(line) if not chunk.get("done"): yield chunk["message"]["content"]

使用示例

ai = LocalAI() response = ai.chat("帮我进行本地开发 AI") print(response)

流式输出

for token in ai.stream("逐步解释本地开发 AI"): print(token, end="", flush=True)

自定义 Modelfile

bash

为本地开发 AI 创建优化配置

cat > Modelfile << 'MODELEOF' FROM any-gguf-model

PARAMETER num_ctx 4096 PARAMETER temperature 0.7 PARAMETER top_p 0.9

SYSTEM "你是一个专注于本地开发 AI 的 AI 助手。你在 Ollama 本地服务器上运行。请保持简洁、准确和有用。" MODELEOF

ollama create local-development-AI-assistant -f Modelfile ollama run local-development-AI-assistant

性能概况

指标值

硬件CPU/GPU 自动 内存可变 速度10-40 tokens/秒 (CPU) / 40-100+ tok/s (GPU) 首 token<200ms (GPU) / <1s (CPU) 上下文4096-32768 tokens 成本$0(硬件除外)

使用 FastAPI 的生产设置

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="Ollama 本地服务器 AI API") ai = LocalAI()

class ChatRequest(BaseModel): message: str system: str = ""

class ChatResponse(BaseModel): response: str model: str device: str

@app.post("/chat", response_model=ChatResponse) async def chat_endpoint(req: ChatRequest): response = ai.chat(req.message, req.system) return ChatResponse(response=response, model="任意 GGUF 模型", device="Ollama 本地服务器")

@app.get("/health") async def health(): return {"status": "ok", "model": "任意 GGUF 模型", "device": "Ollama 本地服务器"}

故障排除

推理速度慢:切换到 Q4_K_M 量化,减小上下文窗口 内存不足:使用更小的模型或 Q3_K_S 量化 未使用 GPU:安装 CUDA/Metal 驱动,检查 ollama logs 高延迟:启动时发送一个虚拟请求预热模型

资源

相关工具

ollamallama.cppany