91 lines
2.8 KiB
Python
91 lines
2.8 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 not found (neither env nor workspace/.env)")
|
|
|
|
|
|
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(td.total_seconds() / 3600)} hours"
|
|
return f"{max(1, round(td.total_seconds() / 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 error: HTTP {e.code}")
|
|
except urllib.error.URLError as e:
|
|
sys.exit(f"ollama.com unreachable: {e.reason}")
|
|
|
|
limits = data.get("limits", {})
|
|
session = limits.get("session", {})
|
|
weekly = limits.get("weekly", {})
|
|
now = datetime.now(timezone.utc)
|
|
|
|
print("Ollama Cloud usage")
|
|
print(
|
|
f'Session: {session.get("usage", 0) * 100:.1f} %, '
|
|
f'resets in {fmt_delta_short(until_next_full_hour(now))}'
|
|
)
|
|
print(
|
|
f'Weekly: {weekly.get("usage", 0) * 100:.1f} %, '
|
|
f'resets in {fmt_delta_short(until_next_monday(now))}'
|
|
)
|
|
|
|
models = weekly.get("models", [])
|
|
if models:
|
|
print("Models (request count, weekly window):")
|
|
for m in models:
|
|
print(f' {m["name"]}: {m["request_count"]}')
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |