79 lines
2.4 KiB
Python
79 lines
2.4 KiB
Python
import os
|
|||
|
|
import time
|
||
|
|
import requests
|
||
|
|
|
||
|
|
OLLAMA_HOST = os.environ.get("OLLAMA_HOST", "http://192.168.2.15:11434")
|
||
|
|
DEFAULT_MODEL = os.environ.get("OLLAMA_MODEL", "Qwen3.6:27b")
|
||
|
|
|
||
|
|
PROBE_TIMEOUT = 5
|
||
|
|
CHAT_TIMEOUT = 120
|
||
|
|
|
||
|
|
|
||
|
|
def _url(path):
|
||
|
|
return f"{OLLAMA_HOST.rstrip('/')}{path}"
|
||
|
|
|
||
|
|
|
||
|
|
def list_models(timeout=PROBE_TIMEOUT):
|
||
|
|
resp = requests.get(_url("/api/tags"), timeout=timeout)
|
||
|
|
resp.raise_for_status()
|
||
|
|
models = []
|
||
|
|
for entry in resp.json().get("models", []):
|
||
|
|
details = entry.get("details") or {}
|
||
|
|
models.append({
|
||
|
|
"name": entry.get("name"),
|
||
|
|
"size": entry.get("size"),
|
||
|
|
"family": details.get("family"),
|
||
|
|
"parameter_size": details.get("parameter_size"),
|
||
|
|
"quantization": details.get("quantization_level"),
|
||
|
|
"capabilities": entry.get("capabilities", []),
|
||
|
|
"vision": "vision" in entry.get("capabilities", []),
|
||
|
|
})
|
||
|
|
return models
|
||
|
|
|
||
|
|
|
||
|
|
def health(model=None, timeout=PROBE_TIMEOUT):
|
||
|
|
info = {
|
||
|
|
"host": OLLAMA_HOST,
|
||
|
|
"reachable": False,
|
||
|
|
"version": None,
|
||
|
|
"model_count": 0,
|
||
|
|
"model": model,
|
||
|
|
"model_present": False,
|
||
|
|
"latency_ms": None,
|
||
|
|
"error": None,
|
||
|
|
}
|
||
|
|
start = time.time()
|
||
|
|
try:
|
||
|
|
resp = requests.get(_url("/"), timeout=timeout)
|
||
|
|
resp.raise_for_status()
|
||
|
|
info["reachable"] = True
|
||
|
|
info["version"] = resp.text.strip()
|
||
|
|
|
||
|
|
models = list_models(timeout=timeout)
|
||
|
|
info["model_count"] = len(models)
|
||
|
|
if model:
|
||
|
|
info["model_present"] = any(m["name"] == model for m in models)
|
||
|
|
info["latency_ms"] = round((time.time() - start) * 1000, 1)
|
||
|
|
except requests.RequestException as exc:
|
||
|
|
info["error"] = f"{type(exc).__name__}: {exc}"
|
||
|
|
except ValueError as exc:
|
||
|
|
info["error"] = f"BadResponse: {exc}"
|
||
|
|
return info
|
||
|
|
|
||
|
|
|
||
|
|
def chat(model, prompt, system=None, timeout=CHAT_TIMEOUT):
|
||
|
|
payload = {
|
||
|
|
"model": model,
|
||
|
|
"messages": ([{"role": "system", "content": system}] if system else [])
|
||
|
|
+ [{"role": "user", "content": prompt}],
|
||
|
|
"stream": False,
|
||
|
|
}
|
||
|
|
start = time.time()
|
||
|
|
resp = requests.post(_url("/api/chat"), json=payload, timeout=timeout)
|
||
|
|
resp.raise_for_status()
|
||
|
|
body = resp.json()
|
||
|
|
return {
|
||
|
|
"reply": (body.get("message") or {}).get("content", "").strip(),
|
||
|
|
"duration_ms": round((time.time() - start) * 1000, 1),
|
||
|
|
"eval_count": body.get("eval_count"),
|
||
|
|
}
|