aboutsummaryrefslogtreecommitdiffstats
path: root/deckit/modules/llm.py
blob: 2e1cda489a10819128f93b308745d5124096f1ca (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
"""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"]
        latest = limits[-1] if isinstance(limits, list) and limits else (
            limits if isinstance(limits, dict) else {})
        return {
            "offline": False,
            "claude": {
                "context_pct": latest.get("context_pct", data["/api/claude_session"].get("context_used")),
                "five_hour": latest.get("five_hour"),
                "seven_day": latest.get("seven_day"),
                "monthly_used": latest.get("extra_used_credits"),
                "monthly_limit": latest.get("extra_monthly_limit"),
            },
            "opencode": data["/api/summary"],
        }

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