72 lines
2.3 KiB
Python
72 lines
2.3 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 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 ""
|
|
parts = [f'{m["name"]} ({m["request_count"]} req)' for m in models]
|
|
return ", ".join(parts)
|
|
|
|
|
|
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", {})
|
|
|
|
print("Ollama Cloud — spotřeba")
|
|
s_models = fmt_models(session.get("models", []))
|
|
print(f'Session: ${session.get("usage", 0):.3f}' + (f" — {s_models}" if s_models else ""))
|
|
w_models = fmt_models(weekly.get("models", []))
|
|
print(f'Weekly: ${weekly.get("usage", 0):.3f}' + (f" — {w_models}" if w_models else ""))
|
|
|
|
activity = data.get("activity", {})
|
|
cost = activity.get("cost")
|
|
if cost is not None:
|
|
period = activity.get("period", {})
|
|
print(
|
|
f'Aktivita: ${float(cost):.5f}'
|
|
f' ({period.get("type", "?")} {period.get("starting_at", "")[:10]}'
|
|
f' → {period.get("ending_at", "")[:10]})'
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |