Files
nanobot-runtime/skills/usage/scripts/ollama_usage.py

101 lines
3.1 KiB
Python

#!/usr/bin/env python3
"""Ollama Cloud usage — GET https://ollama.com/api/usage with Bearer key."""
from __future__ import annotations
import json
import os
import sys
import urllib.error
import urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path
API_URL = "https://ollama.com/api/usage"
def load_api_key() -> str:
env = os.environ.get("OLLAMA_API_KEY")
if env:
return env.strip()
# workspace root = three levels above this script
env_file = Path(__file__).resolve().parents[3] / ".env"
if env_file.is_file():
for line in env_file.read_text().splitlines():
line = line.strip()
if line.startswith("OLLAMA_API_KEY="):
return line.split("=", 1)[1].strip().strip('"').strip("'")
sys.exit("OLLAMA_API_KEY nenalezen (ani env, ani workspace/.env)")
def fmt_models(models: list[dict]) -> str:
if not models:
return ""
return ", ".join(f'{m["name"]} ({m["request_count"]})' for m in models)
def until_next_full_hour(now: datetime) -> timedelta:
nxt = (now.replace(minute=0, second=0, microsecond=0)
+ timedelta(hours=1))
return nxt - now
def until_next_monday(now: datetime) -> timedelta:
# days until Monday (weekday(): Mon == 0)
days = (7 - now.weekday()) % 7 or 7
nxt = (now.replace(hour=0, minute=0, second=0, microsecond=0)
+ timedelta(days=days))
return nxt - now
def fmt_delta_short(td: timedelta) -> str:
"""Human countdown, dashboard style: '1 hour', '55 minutes', '6 days'."""
total = td.total_seconds()
if total >= 86400:
return f"{int(total // 86400)} days"
if total >= 3600:
return f"{round(total / 3600)} hours"
return f"{max(1, round(total / 60))} minutes"
def main() -> None:
req = urllib.request.Request(API_URL, headers={
"Authorization": f"Bearer {load_api_key()}",
"Accept": "application/json",
})
try:
with urllib.request.urlopen(req, timeout=15) as resp:
data = json.load(resp)
except urllib.error.HTTPError as e:
sys.exit(f"ollama.com API chyba: HTTP {e.code}")
except urllib.error.URLError as e:
sys.exit(f"ollama.com nedostupné: {e.reason}")
limits = data.get("limits", {})
session = limits.get("session", {})
weekly = limits.get("weekly", {})
now = datetime.now(timezone.utc)
print("Ollama Cloud — spotřeba")
s_models = fmt_models(session.get("models", []))
print(
f'Session: {session.get("usage", 0) * 100:.1f} %, '
f'resets in {fmt_delta_short(until_next_full_hour(now))}'
+ (f"{s_models}" if s_models else "")
)
w_models = fmt_models(weekly.get("models", []))
print(
f'Weekly: {weekly.get("usage", 0) * 100:.1f} %, '
f'resets in {fmt_delta_short(until_next_monday(now))}'
+ (f"{w_models}" if w_models else "")
)
models = weekly.get("models", [])
if models:
print("Modely (počet požadavků, weekly okno):")
for m in models:
print(f' {m["name"]}: {m["request_count"]}')
if __name__ == "__main__":
main()