aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/llm.py
blob: fb2366fa7eb657c1fc00deac96f9c1ac1a83d473 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""Claude Code and opencode usage, relayed from llm-cost-dashboard's API.

Everything here is read-only. The dashboard stays the owner of the data and the
pricing; deck-it only renders it.
"""

import json
import urllib.request

from ..module import Module

ENDPOINTS = ("/api/claude_limits", "/api/claude_session", "/api/summary")


def _fetch_for(base):
    def fetch(endpoint):
        with urllib.request.urlopen(base + endpoint, timeout=2) as r:
            return json.loads(r.read())
    return fetch


def make(cfg: dict) -> Module:
    base = cfg.get("llm", {}).get("url", "http://127.0.0.1:8420").rstrip("/")
    fetch = cfg.get("fetch") or _fetch_for(base)

    def state():
        try:
            data = {ep: fetch(ep) for ep in ENDPOINTS}
        except (OSError, ValueError):
            return {"offline": True}
        limits = data["/api/claude_limits"]
        if isinstance(limits, dict):
            latest = limits.get("latest") or {}
        elif isinstance(limits, list) and limits:
            latest = limits[-1]
        else:
            latest = {}
        return {
            "offline": False,
            "claude": {
                "context_pct": latest.get("context_pct"),
                "five_hour_pct": latest.get("five_hour_pct"),
                "five_hour_resets_at": latest.get("five_hour_resets_at"),
                "seven_day_pct": latest.get("seven_day_pct"),
                "seven_day_resets_at": latest.get("seven_day_resets_at"),
                "extra_used": latest.get("extra_used_credits"),
                "extra_limit": latest.get("extra_monthly_limit"),
                "extra_utilization": latest.get("extra_utilization"),
                "extra_currency": latest.get("extra_currency"),
            },
            "opencode": data["/api/summary"],
        }

    return Module(name="llm", title="LLM usage", state=state)