获取版本 (GET /api/version)

获取版本接口返回当前运行的 Ollama 版本信息,常用于健康检查和版本兼容性判断。

基本用法

curl http://localhost:11434/api/version

响应:

{
  "version": "0.1.27"
}

响应字段

字段说明
versionOllama 版本号

代码示例

Python

import requests

def get_version():
    response = requests.get("http://localhost:11434/api/version")
    return response.json()["version"]

version = get_version()
print(f"Ollama 版本: {version}")

检查服务状态

def check_ollama_status():
    try:
        response = requests.get("http://localhost:11434/api/version", timeout=5)
        if response.status_code == 200:
            version = response.json()["version"]
            print(f"Ollama 运行正常,版本: {version}")
            return True
    except requests.exceptions.RequestException:
        print("Ollama 服务未运行")
        return False

check_ollama_status()

版本比较

from packaging import version

def check_version(required_version):
    current = get_version()
    
    if version.parse(current) >= version.parse(required_version):
        print(f"版本满足要求 ({current} >= {required_version})")
        return True
    else:
        print(f"版本过低 ({current} < {required_version})")
        return False

check_version("0.1.20")

JavaScript

async function getVersion() {
    const response = await fetch('http://localhost:11434/api/version');
    const data = await response.json();
    return data.version;
}

const version = await getVersion();
console.log(`Ollama 版本: ${version}`);

健康检查

async function healthCheck() {
    try {
        const response = await fetch('http://localhost:11434/api/version', {
            signal: AbortSignal.timeout(5000)
        });
        
        if (response.ok) {
            const data = await response.json();
            return { status: 'ok', version: data.version };
        }
    } catch (error) {
        return { status: 'error', message: error.message };
    }
}

const health = await healthCheck();
console.log(health);

Go

package main

import (
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "time"
)

type VersionResponse struct {
    Version string `json:"version"`
}

func getVersion() (string, error) {
    client := &http.Client{Timeout: 5 * time.Second}
    
    resp, err := client.Get("http://localhost:11434/api/version")
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()
    
    data, _ := io.ReadAll(resp.Body)
    var result VersionResponse
    json.Unmarshal(data, &result)
    
    return result.Version, nil
}

func main() {
    version, err := getVersion()
    if err != nil {
        fmt.Println("Ollama 服务未运行")
        return
    }
    
    fmt.Printf("Ollama 版本: %s\n", version)
}

实际应用

应用启动检查

class OllamaClient:
    def __init__(self, base_url="http://localhost:11434"):
        self.base_url = base_url
        self._check_connection()
    
    def _check_connection(self):
        try:
            response = requests.get(f"{self.base_url}/api/version", timeout=5)
            if response.status_code == 200:
                self.version = response.json()["version"]
                print(f"已连接 Ollama {self.version}")
            else:
                raise Exception("连接失败")
        except Exception as e:
            raise Exception(f"无法连接 Ollama: {e}")

client = OllamaClient()

兼容性检查

FEATURE_VERSIONS = {
    "vision": "0.1.15",
    "tools": "0.1.20",
    "embeddings": "0.1.10"
}

def check_feature_support(feature):
    current = get_version()
    required = FEATURE_VERSIONS.get(feature)
    
    if not required:
        return True
    
    from packaging import version
    return version.parse(current) >= version.parse(required)

if check_feature_support("tools"):
    print("支持工具调用")
else:
    print("不支持工具调用,请升级 Ollama")

监控脚本

import time

def monitor_ollama(interval=60):
    while True:
        try:
            version = get_version()
            print(f"[{time.strftime('%H:%M:%S')}] Ollama {version} 运行中")
        except:
            print(f"[{time.strftime('%H:%M:%S')}] Ollama 无响应")
        
        time.sleep(interval)

monitor_ollama()

小结

版本接口是最简单的 API,但很实用:

  1. 健康检查:快速判断服务是否正常
  2. 版本兼容:判断是否支持某些功能
  3. 监控告警:定期检查服务状态

到这里,我们已经介绍了所有主要的 API 端点。下一部分开始,我们将深入学习各语言的 SDK 使用方法。