feat(stove-api): expose estimate and operator controls
This commit is contained in:
+213
@@ -0,0 +1,213 @@
|
||||
"""Bounded AI selection of normative resource codes for unmatched stove bill lines."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
|
||||
import agent_provider
|
||||
import db
|
||||
import fgis_ref
|
||||
import gateway
|
||||
import provider_health
|
||||
import quotas
|
||||
import stove_cache
|
||||
import stove_pricing
|
||||
import stove_history
|
||||
import zaika_quota
|
||||
from stove_units import convert_qty
|
||||
|
||||
USER = "stove-api@local"
|
||||
PATH = "api:stove-estimate"
|
||||
RESERVE_RUB = 5.0
|
||||
GLOBAL_RUB_DAY = 600.0
|
||||
_lock = threading.Lock()
|
||||
_semaphore = asyncio.Semaphore(3)
|
||||
|
||||
|
||||
class MatchingUnavailable(RuntimeError):
|
||||
def __init__(self, retry_after=30):
|
||||
super().__init__("Сопоставление материалов временно недоступно")
|
||||
self.retry_after = retry_after
|
||||
|
||||
|
||||
class BudgetExhausted(RuntimeError):
|
||||
retry_after = 3600
|
||||
|
||||
|
||||
def _reserve(key_id: int, budget: float, profile) -> int:
|
||||
now = time.time()
|
||||
with _lock:
|
||||
with db._conn() as con:
|
||||
row = con.execute(
|
||||
"SELECT COALESCE(SUM(price_rub),0) AS spent FROM llm_usage "
|
||||
"WHERE path=? AND tab_id=? AND ts>=? AND cost_basis!='unknown' "
|
||||
"AND (cost_basis!='pending' OR ts>=?)",
|
||||
(PATH, f"stove:{key_id}", now-86400, now-600)).fetchone()
|
||||
key_spent = float(row["spent"])
|
||||
row = con.execute(
|
||||
"SELECT COALESCE(SUM(price_rub),0) AS spent FROM llm_usage "
|
||||
"WHERE path=? AND ts>=?", (PATH, now-86400)).fetchone()
|
||||
total = float(row["spent"])
|
||||
stop = con.execute("SELECT value FROM app_settings WHERE key='agent_killswitch'").fetchone()
|
||||
reason = con.execute("SELECT value FROM app_settings WHERE key='agent_killswitch_reason'").fetchone()
|
||||
if key_spent + RESERVE_RUB > budget:
|
||||
raise BudgetExhausted()
|
||||
try:
|
||||
global_full = quotas.global_cap_reached()
|
||||
except Exception as exc:
|
||||
raise MatchingUnavailable(3600) from exc
|
||||
if total + RESERVE_RUB > GLOBAL_RUB_DAY or global_full:
|
||||
raise MatchingUnavailable(3600)
|
||||
if stop and stop[0] == "on" and reason and reason[0] == "manual":
|
||||
raise MatchingUnavailable(3600)
|
||||
return db.create_llm_usage_stub(USER, f"stove:{key_id}", PATH, RESERVE_RUB,
|
||||
provider=profile.name, model=profile.model)
|
||||
|
||||
|
||||
def _candidates(name: str, unit: str, region: str, zone: str | None) -> list[dict]:
|
||||
found = fgis_ref.find_resource_price(query=name, region=region, zone=zone, limit=12)
|
||||
if found.get("status") == "db_unavailable":
|
||||
raise MatchingUnavailable(30)
|
||||
if found.get("status") != "ok" or found.get("multiple_zones"):
|
||||
return []
|
||||
rows = []
|
||||
for row in found.get("results", []):
|
||||
if (row.get("code") and convert_qty(1, unit, row.get("unit")) is not None
|
||||
and stove_pricing._price(row)[0] is not None):
|
||||
rows.append(row)
|
||||
return rows[:12]
|
||||
|
||||
|
||||
def _profile_chain():
|
||||
chain = [p for p in agent_provider.provider_chain(USER)
|
||||
if p.uses_api_token and provider_health.should_include(p.name)]
|
||||
if any(p.name == "glm" for p in chain):
|
||||
quota = zaika_quota.snapshot()
|
||||
if quota.get("known") and (quota.get("percent_used") or 0) >= 80:
|
||||
chain = [p for p in chain if p.name != "glm"]
|
||||
return chain
|
||||
|
||||
|
||||
async def _call(profile, body: dict, timeout: float) -> tuple[str, dict]:
|
||||
async def consume():
|
||||
chunks, usage = [], {}
|
||||
async for event in gateway._provider_stream(profile, body):
|
||||
if "delta" in event:
|
||||
chunks.append(event["delta"])
|
||||
if "usage" in event:
|
||||
usage = event["usage"] or {}
|
||||
return "".join(chunks), usage
|
||||
return await asyncio.wait_for(consume(), timeout=timeout)
|
||||
|
||||
|
||||
async def _ask(batch: list[dict], key_id: int, budget: float, deadline: float, request_id: str) -> list[dict]:
|
||||
try:
|
||||
await asyncio.wait_for(_semaphore.acquire(), timeout=min(10, max(0.01, deadline-time.monotonic())))
|
||||
except asyncio.TimeoutError as exc:
|
||||
raise MatchingUnavailable() from exc
|
||||
try:
|
||||
chain = await asyncio.to_thread(_profile_chain)
|
||||
if not chain:
|
||||
raise MatchingUnavailable()
|
||||
prompt = {"task": "Выбери для каждой строки один код из её списка candidates или null. "
|
||||
"Верни только JSON массив объектов {index,code}. Не придумывай коды.",
|
||||
"lines": [{"index": x["index"], "name": x["line"]["name"],
|
||||
"unit": x["line"]["unit"],
|
||||
"candidates": [{"code": r["code"], "name": r["name"][:80], "unit": r["unit"]}
|
||||
for r in x["candidates"]]} for x in batch]}
|
||||
body = {"messages": [{"role": "user", "content": json.dumps(prompt, ensure_ascii=False)}],
|
||||
"max_tokens": 2000}
|
||||
for profile in chain[:2]:
|
||||
usage_id = await asyncio.to_thread(_reserve, key_id, budget, profile)
|
||||
started = time.time()
|
||||
usage = {}
|
||||
try:
|
||||
text, usage = await _call(profile, body, max(0.1, min(20, deadline-time.monotonic())))
|
||||
payload = json.loads(text.strip().removeprefix("```json").removesuffix("```").strip())
|
||||
if not isinstance(payload, list):
|
||||
raise ValueError("ответ модели не массив")
|
||||
valid = {x["index"]: {r["code"] for r in x["candidates"]} for x in batch}
|
||||
picked = {}
|
||||
for item in payload:
|
||||
if not isinstance(item, dict) or item.get("index") not in valid:
|
||||
raise ValueError("неизвестный номер строки")
|
||||
code = item.get("code")
|
||||
picked[item["index"]] = (code if code in valid[item["index"]] else
|
||||
None if code is None else "__invalid__")
|
||||
if set(picked) != set(valid):
|
||||
raise ValueError("пропущена строка")
|
||||
return [picked[x["index"]] for x in batch]
|
||||
except gateway.ProviderError as exc:
|
||||
if profile.name == "glm" and exc.status == 429:
|
||||
await asyncio.to_thread(zaika_quota.note_refusal, profile.name, str(exc))
|
||||
continue
|
||||
except (asyncio.TimeoutError, ValueError, RuntimeError, OSError, json.JSONDecodeError):
|
||||
continue
|
||||
finally:
|
||||
priced = gateway._price(USER, profile.model, usage, started) if usage else {}
|
||||
price = priced.get("price_rub")
|
||||
await asyncio.to_thread(db.settle_llm_usage_stub, usage_id,
|
||||
input_tokens=(usage.get("input_tokens") or 0),
|
||||
cache_tokens=usage.get("cache_read_input_tokens") or 0,
|
||||
output_tokens=usage.get("output_tokens") or 0,
|
||||
price_rub=price if price is not None else RESERVE_RUB,
|
||||
cost_rub=priced.get("cost_rub"), cost_usd=priced.get("cost_usd"),
|
||||
provider=profile.name, model=profile.model,
|
||||
cost_basis=priced.get("cost_basis") or "unknown")
|
||||
await asyncio.to_thread(stove_history.add_ai_cost, request_id,
|
||||
price if price is not None else RESERVE_RUB,
|
||||
priced.get("cost_usd"))
|
||||
raise MatchingUnavailable()
|
||||
finally:
|
||||
_semaphore.release()
|
||||
|
||||
|
||||
async def fill(prices: dict, *, key_id: int, budget: float, deadline: float, request_id: str) -> dict:
|
||||
"""Resolve only unmatched non-brick lines; all assignments are checked against candidates."""
|
||||
todo = []
|
||||
for index, line in enumerate(prices.get("lines") or []):
|
||||
if line.get("code") is not None or line.get("bricks"):
|
||||
continue
|
||||
ck = stove_cache.cache_key(key_id, prices["region"], prices.get("zone"),
|
||||
line["name"], line["unit"], prices["valid_at"])
|
||||
cached = await asyncio.to_thread(stove_cache.match_get, ck)
|
||||
if cached:
|
||||
if cached.get("code"):
|
||||
got = await asyncio.to_thread(fgis_ref.find_resource_price,
|
||||
query=cached["code"], region=prices["region"], zone=prices.get("zone"), limit=2)
|
||||
rows = [r for r in got.get("results", []) if r.get("code") == cached["code"]]
|
||||
if rows and stove_pricing._price(rows[0])[0] is not None:
|
||||
prices["lines"][index] = stove_pricing._line(line["name"], line["qty"], line["unit"], rows[0])
|
||||
continue
|
||||
await asyncio.to_thread(stove_cache.match_delete, ck)
|
||||
else:
|
||||
continue
|
||||
candidates = await asyncio.to_thread(_candidates, line["name"], line["unit"],
|
||||
prices["region"], prices.get("zone"))
|
||||
if candidates:
|
||||
todo.append({"index": index, "line": line, "candidates": candidates, "cache_key": ck})
|
||||
else:
|
||||
await asyncio.to_thread(stove_cache.match_put, ck, key_id=key_id,
|
||||
line_norm=fgis_ref.norm_text(line["name"]), kind="material",
|
||||
code=None, name=None, unit=None, ttl_sec=stove_cache.NEG_TTL_SEC,
|
||||
base_version=prices["valid_at"])
|
||||
if todo:
|
||||
for start in range(0, len(todo), 25):
|
||||
batch = todo[start:start+25]
|
||||
codes = await _ask(batch, key_id, budget, deadline, request_id)
|
||||
for item, code in zip(batch, codes):
|
||||
row = next((r for r in item["candidates"] if r["code"] == code), None)
|
||||
line = item["line"]
|
||||
if row:
|
||||
prices["lines"][item["index"]] = stove_pricing._line(line["name"], line["qty"], line["unit"], row)
|
||||
if code == "__invalid__":
|
||||
continue
|
||||
await asyncio.to_thread(stove_cache.match_put, item["cache_key"], key_id=key_id,
|
||||
line_norm=fgis_ref.norm_text(line["name"]), kind="material",
|
||||
code=code, name=row["name"] if row else None,
|
||||
unit=row["unit"] if row else None,
|
||||
ttl_sec=stove_cache.POS_TTL_SEC if row else stove_cache.NEG_TTL_SEC,
|
||||
base_version=prices["valid_at"])
|
||||
return prices
|
||||
Reference in New Issue
Block a user