游乐游手机版
首页/AI热点日报/热点详情

Ollama服务监测程序安装配置与使用详解

类型:热点整理2026-07-03
高效监控本地DeepSeek-R1服务,确保业务系统持续稳定运行,实现自动化故障恢复。 核心要点: 1 客户私有化部署DeepSeek-R1模型的真实业务需求 2 Ollama服务监测程序的设计原理与实现流程 3 Python代码实现细节及日志配置方案 Ollama服务监测程序——保障Deep

高效监控本地DeepSeek-R1服务,确保业务系统持续稳定运行,实现自动化故障恢复。 核心要点: 1. 客户私有化部署DeepSeek-R1模型的真实业务需求 2. Ollama服务监测程序的设计原理与实现流程 3. Python代码实现细节及日志配置方案

Ollama之服务监测程序

Ollama服务监测程序——保障DeepSeek-R1稳定运行

业务背景

近期DeepSeek-R1模型热度极高,某业务系统需要在本地接入该模型,客户明确要求私有化部署。恰好手中闲置了一张RTX 3090显卡,于是通过Ollama拉取deepseek-r1:32b模型。起初运行流畅,但服务运行一段时间后却出现无响应卡死现象。尝试多种排查手段仍未定位确切原因,最终决定编写一个监测程序进行兜底防护。思路非常直接:定时调用Ollama的API接口,若请求超时则自动执行服务重启操作,确保AI推理服务的高可用性。

代码实现详解

采用Python语言实现,在项目目录中创建ollama_monitor.py文件,核心逻辑如下:

import requests
import time
import subprocess
import psutil
import logging
import os
from datetime import datetime

OLLAMA_HOST = os.environ.get("OLLAMA_HOST", "localhost:11434")
try:
    port = OLLAMA_HOST.split(":")[1]  # 提取端口号
    OLLAMA_API_URL = f"http://localhost:{port}/api/tags"
except IndexError:
    logging.error("OLLAMA_HOST 环境变量格式错误,应为 '主机:端口'")
    port = "11434"  # 默认端口
    OLLAMA_API_URL = f"http://localhost:{port}/api/tags"

TIMEOUT_SECONDS = 10
RESTART_COMMAND = "ollama ps"

def setup_logging():
    """配置日志记录器,同时输出到文件和控制台。"""
    log_dir = "logs"
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    log_file_path = os.path.join(log_dir, f"ollama_monitor_{current_time}.log")

    # 创建文件处理器
    file_handler = logging.FileHandler(log_file_path)
    file_handler.setLevel(logging.INFO)
    file_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    file_handler.setFormatter(file_formatter)

    # 创建控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    console_handler.setFormatter(console_formatter)

    # 获取根日志记录器并添加处理器
    logging.basicConfig(level=logging.INFO, handlers=[file_handler, console_handler])

def check_ollama_status():
    """检查 Ollama 状态,如果卡住则返回 True,否则返回 False。"""
    try:
        response = requests.get(OLLAMA_API_URL, timeout=TIMEOUT_SECONDS)
        response.raise_for_status()
        return False
    except requests.exceptions.RequestException as e:
        logging.error(f"Ollama 可能卡住:{e}")
        return True

def restart_ollama():
    """重启 Ollama 服务。"""
    logging.info("重启 Ollama 服务...")
    try:
        for proc in psutil.process_iter(['pid', 'name']):
            if proc.info['name'] == 'ollama.exe':
                p = psutil.Process(proc.info['pid'])
                p.terminate()

        subprocess.Popen(RESTART_COMMAND, shell=True)
        logging.info("Ollama 服务已重启。")
    except Exception as e:
        logging.error(f"重启 Ollama 服务失败:{e}")

if __name__ == "__main__":
    setup_logging()
    while True:
        if check_ollama_status():
            restart_ollama()
        sleep_time = int(os.environ.get("OLLAMA_MONITOR_INTERVAL", 60))
        time.sleep(sleep_time)

此监测程序检测的是http://localhost:{port}/api/tags接口(用于获取模型列表),利用psutil库查找进程,并未直接使用系统级ps命令(经测试效果不佳)。监控间隔可通过环境变量OLLAMA_MONITOR_INTERVAL自定义,默认每60秒执行一次健康检查。

依赖包安装

编写requirements.txt文件,内容如下:

requests
psutil
pyinstaller

执行命令 pip install -r requirements.txt 即可完成依赖安装。

程序打包与部署

在程序所在目录中运行命令:pyinstaller --onefile ollama_monitor.py,生成的独立可执行文件位于根目录的dist/ollama_monitor.exe。将该exe文件复制到目标服务器上,直接运行即可实现对Ollama服务的全天候监控与自动恢复。

来源:https://www.53ai.com/news/finetuning/2025031112746.html

相关热点

继续查看同栏目近期热点。

延伸阅读

补充最近整理过的热点入口。