benak / code /beam.py
PugarHuda's picture
Benak release
d9aaa5c verified
Raw History Blame Contribute Delete
6.6 kB
"""Beam client: OpenAI-compatible chat call + sqlite response cache (never pay twice) + cost ledger.
Route: HF Inference Providers (Baseten) by default; override with BEAM_BASE_URL / BEAM_API_KEY / BEAM_MODEL."""
import hashlib, json, os, sqlite3, threading, time, urllib.error, urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
_HERE = os.path.dirname(os.path.abspath(__file__))
_KEYFILE = os.path.join(_HERE, "data", ".reflection_key") # gitignored; never uploaded
_RKEY = os.environ.get("REFLECTION_API_KEY") or (open(_KEYFILE).read().strip() if os.path.exists(_KEYFILE) else "")
from huggingface_hub import get_token
# Routes in order of preference. Reflection: free daily allowance (1M output tok/day, 60 rpm). Baseten via HF: paid,
# pinned because HF auto-routing flaked with model_not_supported.
ROUTES = ([{"url": "https://api.reflection.ai/openai/v1", "model": "Beam-1.0-501B-A23B", "key": _RKEY, "free": True,
"min_gap": 1.05}] if _RKEY else []) + [{"url": "https://router.huggingface.co/v1", "model": "reflection/Beam-1.0-501B-A23B:baseten",
"key": os.environ.get("HF_TOKEN") or get_token() or "", "free": False, "min_gap": 0.0}]
_route = [0] # index into ROUTES; moves to the next route when Reflection's daily quota is exhausted
if os.environ.get("BENAK_ROUTE") == "baseten": # force the HF/Baseten route (used by the paired route check)
_route[0] = len(ROUTES) - 1
BASE_URL, MODEL = ROUTES[0]["url"], ROUTES[0]["model"]
PRICE_IN, PRICE_OUT = 0.40e-6, 1.20e-6 # Baseten list price per token (reasoning billed as output)
_gap_lock = threading.Lock(); _last = [0.0]
def _pace(gap):
"""Global request spacing (Reflection allows 60 requests/minute)."""
if not gap:
return
with _gap_lock:
wait = _last[0] + gap - time.time()
if wait > 0:
time.sleep(wait)
_last[0] = time.time()
BUDGET_USD = float(os.environ.get("BENAK_BUDGET_USD", "20"))
_db = sqlite3.connect(os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "cache.sqlite"),
check_same_thread=False)
_db.execute("create table if not exists c (k text primary key, v text, ts real)")
_lock = threading.Lock()
def _cost(row):
"""Paid USD for one cached response (Reflection free-allowance calls cost 0; list-price tokens tracked separately)."""
u = row.get("usage") or {}
if "reflection.ai" in row.get("route", ""):
return 0.0
return (u.get("prompt_tokens", 0) or 0) * PRICE_IN + (u.get("completion_tokens", 0) or 0) * PRICE_OUT
with _lock:
_spent = [sum(_cost(json.loads(v)) for (v,) in _db.execute("select v from c").fetchall())]
def spent():
"""USD spent so far (every cached row was one paid call)."""
return round(_spent[0], 4)
def chat(messages, effort="low", max_tokens=4096, temperature=0.7, tag="", retries=6):
"""Returns dict(content, reasoning, finish_reason, usage, latency_s, effort, cached)."""
body = {"model": "reflection/Beam-1.0-501B-A23B", "messages": messages, "max_tokens": max_tokens,
"temperature": temperature, "reasoning_effort": effort}
key_body = body # same weights on every route -> one cache identity; the route is recorded per row
key = hashlib.sha256(json.dumps(key_body, sort_keys=True, ensure_ascii=False).encode() + tag.encode()).hexdigest()
with _lock:
row = _db.execute("select v from c where k=?", (key,)).fetchone()
if row:
return json.loads(row[0]) | {"cached": True}
if spent() > BUDGET_USD:
raise RuntimeError(f"budget ${BUDGET_USD} exceeded")
for attempt in range(retries):
R = ROUTES[_route[0]]
req = urllib.request.Request(R["url"] + "/chat/completions",
json.dumps(body | {"model": R["model"]}, ensure_ascii=False).encode(),
{"Authorization": f"Bearer {R['key']}", "Content-Type": "application/json"})
_pace(R["min_gap"])
t0 = time.time()
try:
with urllib.request.urlopen(req, timeout=900) as r:
d = json.load(r)
ch = d["choices"][0]; m = ch["message"]
out = {"content": m.get("content") or "", "reasoning": m.get("reasoning_content") or m.get("reasoning") or "",
"finish_reason": ch.get("finish_reason"), "usage": d.get("usage") or {},
"latency_s": round(time.time() - t0, 2), "effort": effort, "model": R["model"], "route": R["url"]}
with _lock:
_db.execute("insert or replace into c values (?,?,?)", (key, json.dumps(out, ensure_ascii=False), time.time()))
_db.commit()
_spent[0] += _cost(out)
return out | {"cached": False}
except urllib.error.HTTPError as e:
msg = e.read().decode(errors="replace")[:300]
if R["free"] and e.code in (402, 403, 429) and any(w in msg.lower() for w in ("per day", "daily", "allowance", "-day", "tokens per day", "requests per day")):
with _lock: # free allowance exhausted -> fall through to the paid route for the rest of the run
if ROUTES[_route[0]] is R and _route[0] + 1 < len(ROUTES):
_route[0] += 1; print("!! Reflection daily allowance exhausted -> switching to", ROUTES[_route[0]]["url"], flush=True)
continue
if e.code not in (408, 409, 425, 429, 500, 502, 503, 504) or attempt == retries - 1:
raise RuntimeError(f"HTTP {e.code}: {msg}")
except (urllib.error.URLError, TimeoutError, ConnectionError, json.JSONDecodeError):
if attempt == retries - 1:
raise
time.sleep(min(60, 3 * 2 ** attempt))
def run_many(fn, jobs, workers=12, label=""):
"""Run fn(job) concurrently; yields (job, result | Exception). Prints progress + spend."""
done = 0
with ThreadPoolExecutor(workers) as ex:
futs = {ex.submit(fn, j): j for j in jobs}
for f in as_completed(futs):
done += 1
try:
res = f.result()
except Exception as e: # keep going; failures are reported by the caller
res = e
if done % 25 == 0 or done == len(jobs):
print(f"[{label}] {done}/{len(jobs)} spent=${spent()}", flush=True)
yield futs[f], res
if __name__ == "__main__":
print("spent so far: $", spent())