File size: 13,472 Bytes
90264a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
"""Async DeepSeek client for the pipeline: JSON mode, many parallel requests, response cache, cost ledger, budget.

- model `deepseek-flash` (DeepSeek-V4.1-Flash); thinking disabled unless asked (`thinking=True, effort='low'`)
- the key is read from $DEEPSEEK_API_KEY or /root/.config/deepseek/api_key and never printed
- every successful response is cached in runs/cache.sqlite (key = hash of the request) -> reruns cost nothing
- every paid call is appended to runs/ledger.jsonl with its token usage and price
- budget: stops scheduling new calls when ledger total + in-flight reservations would exceed `budget_usd`,
  or when the live account balance (GET /user/balance, checked every 60 s) drops below `min_balance`
"""
import asyncio
import hashlib
import json
import os
import random
import sqlite3
import time
from datetime import datetime, timezone
from pathlib import Path

import httpx
from openai import APIConnectionError, APIStatusError, APITimeoutError, AsyncOpenAI

from common import RUNS

# USD per 1M tokens: (input cache hit, input cache miss, output); api-docs.deepseek.com/quick_start/pricing, 26.09.2026
PRICES = {"deepseek-flash": {"peak": (0.006, 0.30, 1.20), "offpeak": (0.003, 0.15, 0.60)},
          "deepseek-v4-pro": {"peak": (0.044, 1.32, 3.96), "offpeak": (0.022, 0.66, 1.98)}}


def is_peak(ts=None):
    d = datetime.fromtimestamp(ts or time.time(), timezone.utc)
    return d.weekday() < 5 and (1 <= d.hour < 4 or 6 <= d.hour < 10)


def price(model, usage, ts=None):
    hit_p, miss_p, out_p = PRICES[model]["peak" if is_peak(ts) else "offpeak"]
    hit = usage.get("prompt_cache_hit_tokens") or 0
    miss = usage.get("prompt_cache_miss_tokens")
    if miss is None:
        miss = (usage.get("prompt_tokens") or 0) - hit
    return (hit * hit_p + miss * miss_p + (usage.get("completion_tokens") or 0) * out_p) / 1e6


class BudgetExceeded(Exception):
    pass


class DS:
    def __init__(self, model="deepseek-flash", concurrency=256, budget_usd=None, min_balance=0.3, tag="",
                 cache_path=None, ledger_path=None, timeout=900):
        key = os.environ.get("DEEPSEEK_API_KEY") or Path("/root/.config/deepseek/api_key").read_text().strip()
        self._key = key
        limits = httpx.Limits(max_connections=concurrency + 16, max_keepalive_connections=concurrency + 16)
        self.http = httpx.AsyncClient(limits=limits, timeout=httpx.Timeout(timeout, connect=30))
        self.client = AsyncOpenAI(api_key=key, base_url="https://api.deepseek.com", max_retries=0,
                                  http_client=self.http)
        self.model, self.tag = model, tag
        self.sem = asyncio.Semaphore(concurrency)
        self.budget, self.min_balance = budget_usd, min_balance
        RUNS.mkdir(parents=True, exist_ok=True)
        self.cache = sqlite3.connect(cache_path or RUNS / "cache.sqlite", timeout=60, check_same_thread=False)
        self.cache.execute("PRAGMA journal_mode=WAL")
        self.cache.execute("CREATE TABLE IF NOT EXISTS cache(k TEXT PRIMARY KEY, content TEXT, usage TEXT, ts REAL)")
        self.ledger_path = Path(ledger_path or RUNS / "ledger.jsonl")
        self.inflight = 0.0
        self.spent_run = 0.0
        self.stats = {"calls": 0, "cached": 0, "retries": 0, "failed": 0, "repairs": 0, "invalid": 0}
        self._ledger_total, self._ledger_ts = self._read_ledger(), time.time()
        self._balance, self._balance_ts = None, 0.0
        self._bal_lock = asyncio.Lock()
        self.stopped = False

    # ------------------------------------------------------------ accounting
    def _read_ledger(self):
        if not self.ledger_path.exists():
            return 0.0
        tot = 0.0
        with open(self.ledger_path, encoding="utf-8") as f:
            for line in f:
                try:
                    tot += json.loads(line)["cost"]
                except Exception:
                    pass
        return tot

    def spent_total(self):
        if time.time() - self._ledger_ts > 20:          # other processes may be spending too
            self._ledger_total, self._ledger_ts = self._read_ledger(), time.time()
            self.spent_run = 0.0
        return self._ledger_total + self.spent_run

    async def balance(self, force=False):
        """Live account balance, refreshed at most once a minute by a single coroutine (no thundering herd)."""
        if not force and time.time() - self._balance_ts < 60:
            return self._balance
        if self._bal_lock.locked():
            return self._balance
        async with self._bal_lock:
            if not force and time.time() - self._balance_ts < 60:
                return self._balance
            try:
                r = await self.http.get("https://api.deepseek.com/user/balance", timeout=15,
                                        headers={"Authorization": f"Bearer {self._key}"})
                self._balance = float(r.json()["balance_infos"][0]["total_balance"])
            except Exception:
                pass
            finally:
                self._balance_ts = time.time()
        return self._balance

    async def _check_budget(self, reserve):
        if self.stopped:
            raise BudgetExceeded("stopped")
        if self.budget is not None and self.spent_total() + self.inflight + reserve > self.budget:
            self.stopped = True
            raise BudgetExceeded(f"budget {self.budget} USD reached (spent {self.spent_total():.3f})")
        bal = await self.balance()
        if bal is not None and bal - self.inflight < self.min_balance:
            self.stopped = True
            raise BudgetExceeded(f"account balance {bal:.2f} USD below floor {self.min_balance}")

    def _account(self, usage, tag):
        ts = time.time()
        cost = price(self.model, usage, ts)
        self.spent_run += cost
        rec = {"ts": round(ts, 1), "tag": tag or self.tag, "model": self.model, "peak": is_peak(ts),
               "hit": usage.get("prompt_cache_hit_tokens") or 0, "miss": usage.get("prompt_cache_miss_tokens") or 0,
               "out": usage.get("completion_tokens") or 0,
               "reasoning": ((usage.get("completion_tokens_details") or {}).get("reasoning_tokens") or 0),
               "cost": round(cost, 7)}
        with open(self.ledger_path, "a", encoding="utf-8") as f:
            f.write(json.dumps(rec) + "\n")

    # ------------------------------------------------------------ cache
    def _key_of(self, payload):
        return hashlib.sha256(json.dumps(payload, ensure_ascii=False, sort_keys=True).encode()).hexdigest()

    def _cache_get(self, k):
        r = self.cache.execute("SELECT content, usage FROM cache WHERE k=?", (k,)).fetchone()
        return (r[0], json.loads(r[1])) if r else None

    def _cache_put(self, k, content, usage):
        for _ in range(5):
            try:
                self.cache.execute("INSERT OR REPLACE INTO cache VALUES (?,?,?,?)",
                                   (k, content, json.dumps(usage), time.time()))
                self.cache.commit()
                return
            except sqlite3.OperationalError:
                time.sleep(0.5)

    # ------------------------------------------------------------ calls
    async def raw(self, messages, *, max_tokens, temperature=0.7, thinking=False, effort="low", json_mode=True,
                  tag=""):
        """One chat completion -> (content, usage) or (None, reason). Cached, retried, budgeted."""
        payload = {"model": self.model, "messages": messages, "max_tokens": max_tokens, "json": json_mode,
                   "temperature": None if thinking else temperature, "thinking": effort if thinking else False}
        k = self._key_of(payload)
        hit = self._cache_get(k)
        if hit:
            self.stats["cached"] += 1
            return hit
        hit_p, miss_p, out_p = PRICES[self.model]["peak" if is_peak() else "offpeak"]
        est_in = sum(len(m["content"]) for m in messages) / 2.6
        reserve = (est_in * miss_p + max_tokens * out_p * 0.6) / 1e6
        await self._check_budget(reserve)
        async with self.sem:
            await self._check_budget(reserve)
            self.inflight += reserve
            try:
                kw = {"model": self.model, "messages": messages, "max_tokens": max_tokens}
                if json_mode:
                    kw["response_format"] = {"type": "json_object"}
                if thinking:
                    kw["reasoning_effort"] = effort
                    kw["extra_body"] = {"thinking": {"type": "enabled"}}
                else:
                    kw["temperature"] = temperature
                    kw["extra_body"] = {"thinking": {"type": "disabled"}}
                last = "unknown"
                for attempt in range(8):
                    try:
                        r = await self.client.chat.completions.create(**kw)
                        self.stats["calls"] += 1
                        usage = r.usage.model_dump() if r.usage else {}
                        self._account(usage, tag)
                        ch = r.choices[0]
                        content = ch.message.content or ""
                        if ch.finish_reason == "length":
                            return None, "length"
                        if not content.strip():
                            last = "empty"
                            raise ValueError("empty content")
                        self._cache_put(k, content, usage)
                        return content, usage
                    except APIStatusError as e:
                        last = f"http {e.status_code}"
                        if e.status_code not in (408, 409, 429) and e.status_code < 500:
                            self.stats["failed"] += 1
                            return None, f"{last}: {str(e)[:200]}"
                    except (APIConnectionError, APITimeoutError, ValueError, httpx.HTTPError) as e:
                        last = type(e).__name__
                    self.stats["retries"] += 1
                    await asyncio.sleep(min(60, 2 ** attempt) + random.random() * 2)
                self.stats["failed"] += 1
                return None, last
            finally:
                self.inflight -= reserve

    async def json(self, messages, *, max_tokens, temperature=0.7, thinking=False, effort="low", validate=None,
                   repairs=2, tag="", return_last=False):
        """JSON call with validation; on a bad answer asks the model to fix it (up to `repairs` times).

        `validate(obj)` returns None when OK or an error message (Polish) shown to the model.
        Returns (obj, None) or (None, error); with return_last=True a still-invalid last object is returned
        together with its error (the caller may keep its valid parts)."""
        msgs = list(messages)
        err, last = None, None
        for attempt in range(repairs + 1):
            mt = max_tokens if attempt == 0 else int(max_tokens * 1.3)
            content, info = await self.raw(msgs, max_tokens=mt, temperature=temperature, thinking=thinking,
                                           effort=effort, tag=tag)
            if content is None:
                if info == "length" and attempt < repairs:
                    max_tokens = int(max_tokens * 1.6)
                    continue
                return None, f"api: {info}"
            try:
                obj = json.loads(content)
                err = validate(obj) if validate else None
            except json.JSONDecodeError as e:
                obj, err = None, f"niepoprawny JSON ({e})"
            except Exception as e:                       # validator crashed on an unexpected shape
                obj, err = None, f"zła struktura JSON ({type(e).__name__}: {e})"
            if not err:
                return obj, None
            if isinstance(obj, dict):
                last = obj
            self.stats["invalid"] += 1
            try:
                with open(RUNS / "invalid.jsonl", "a", encoding="utf-8") as f:
                    f.write(json.dumps({"ts": round(time.time()), "tag": tag, "attempt": attempt, "err": err[:400]},
                                       ensure_ascii=False) + "\n")
            except OSError:
                pass
            if attempt < repairs:
                self.stats["repairs"] += 1
                msgs = msgs + [{"role": "assistant", "content": content},
                               {"role": "user", "content": f"Odpowiedź wymaga poprawy: {err}\n"
                                                           f"Zwróć CAŁY poprawiony obiekt json w tym samym formacie."}]
        return (last if return_last else None), f"invalid: {err}"

    def summary(self):
        return (f"calls={self.stats['calls']} cached={self.stats['cached']} retries={self.stats['retries']} "
                f"failed={self.stats['failed']} invalid={self.stats['invalid']} repairs={self.stats['repairs']} "
                f"spent_total={self.spent_total():.3f}$ inflight={self.inflight:.3f}$ balance={self._balance}")

    async def progress(self, label, done_fn, total, every=30):
        t0 = time.time()
        while not self.stopped:
            await asyncio.sleep(every)
            d = done_fn()
            rate = d / max(1e-6, time.time() - t0) * 60
            print(f"[{time.strftime('%H:%M:%S')}] {label}: {d}/{total} ({rate:.0f}/min) {self.summary()}", flush=True)

    async def aclose(self):
        await self.http.aclose()