From 454108655bb354ffe8a80f8eda5ff032e9a8efec Mon Sep 17 00:00:00 2001 From: anor Date: Thu, 24 Sep 2026 02:14:23 +1000 Subject: [PATCH] =?UTF-8?q?fix:=20=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BE?= =?UTF-8?q?=D1=87=D0=BD=D1=8B=D0=B9=20=D0=BF=D1=83=D1=82=D1=8C=20=D1=83?= =?UTF-8?q?=D1=85=D0=BE=D0=B4=D0=B8=D1=82=20=D0=BD=D0=B0=20=D0=B7=D0=B0?= =?UTF-8?q?=D0=B9=D0=BA=D1=83=20=D0=BF=D1=80=D0=B8=20=D0=BE=D1=82=D0=BA?= =?UTF-8?q?=D0=B0=D0=B7=D0=B5=20=D0=B4=D0=B8=D0=BF=D1=81=D0=B8=D0=BA=D0=B0?= =?UTF-8?q?,=20=D1=81=D1=82=D0=BE=D1=80=D0=BE=D0=B6=20=D0=B2=D0=B8=D0=B4?= =?UTF-8?q?=D0=B8=D1=82=20=D0=BF=D1=83=D1=81=D1=82=D0=BE=D0=B9=20=D1=81?= =?UTF-8?q?=D1=87=D1=91=D1=82,=20=D1=82=D0=B5=D0=BB=D0=B5=D0=B3=D1=80?= =?UTF-8?q?=D0=B0=D0=BC=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20=D0=B2=D0=BF?= =?UTF-8?q?=D0=BD=20=D1=81=D0=B5=D1=80=D0=B2=D0=B5=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 (1M context) --- alerts.py | 12 ++- claude_bridge_glm.py | 71 ++++------------ health_checks.py | 11 ++- provider_health.py | 77 ++++++++++------- qa_fallback.py | 169 ++++++++++++++++++++++++++++++++++++++ telegram_verify.py | 6 +- tests/test_qa_fallback.py | 18 +++- 7 files changed, 267 insertions(+), 97 deletions(-) create mode 100644 qa_fallback.py diff --git a/alerts.py b/alerts.py index a3c0d74..8cdd77b 100644 --- a/alerts.py +++ b/alerts.py @@ -13,10 +13,18 @@ import time _log = logging.getLogger("smeta_web") +def tg_proxy() -> str | None: + """Местный вход впн для Телеграма (TG_PROXY_URL). Напрямую с сервера до api.telegram.org + доходит треть запросов, через впн — все (замер 24.09.2026). Прокси из окружения не берём + (trust_env=False): там адрес для песочницы агента, а не для Телеграма.""" + return os.environ.get("TG_PROXY_URL", "").strip() or None + + def _post(url: str, data: dict) -> int: - """Выделено для тестов (мокается). Прямой доступ, без прокси — как канарейка.""" + """Выделено для тестов (мокается).""" import httpx - r = httpx.post(url, data=data, timeout=5, trust_env=False) + kw = {"proxy": tg_proxy()} if tg_proxy() else {} + r = httpx.post(url, data=data, timeout=5, trust_env=False, **kw) return r.status_code diff --git a/claude_bridge_glm.py b/claude_bridge_glm.py index 294bca1..d3a4322 100644 --- a/claude_bridge_glm.py +++ b/claude_bridge_glm.py @@ -13,8 +13,6 @@ import re from pathlib import Path from typing import AsyncGenerator -import httpx - from path_safety import safe_work_dir _log = logging.getLogger("smeta_web") @@ -33,6 +31,7 @@ from chat_context import history_messages # Инжекты новых БД (матрица БИМ / базисные ФСНБ / региональные ФГИС ЦС) + общие # хелперы разбора вопроса, переехавшие туда из этого модуля. +import qa_fallback import qa_inject from qa_inject import _bim_extract_quarter @@ -1040,59 +1039,23 @@ async def stream_claude( + [{"role": "user", "content": user_content}] ) - # Stream from GLM API + # Дипсик, при его отказе до первого текста — зайка (qa_fallback, инцидент 24.09.2026). full_response = "" _qa_usage: dict = {} - proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") - try: - async with httpx.AsyncClient(timeout=120, proxy=proxy) as client: - resp = await client.post( - f"{ZAI_BASE_URL}/chat/completions", - headers={"Authorization": f"Bearer {ZAI_API_KEY}"}, - json={ - "model": ZAI_MODEL, - "messages": messages, - "stream": True, - # usage в финальном чанке стрима (OpenAI-совм.) — питает учёт llm_usage (Ф2). - "stream_options": {"include_usage": True}, - "temperature": 0.1, - "max_tokens": 4096, - "thinking": {"type": "disabled"}, - }, - ) - resp.raise_for_status() - - async for line in resp.aiter_lines(): - if not line.startswith("data: "): - continue - data_str = line[6:] - if data_str == "[DONE]": - break - try: - chunk = json.loads(data_str) - if chunk.get("usage"): - # финальный usage-чанк (choices пуст) — переводим в Anthropic-формат Ф2 - _qa_usage = { - "input_tokens": chunk["usage"].get("prompt_tokens", 0), - "cache_read_input_tokens": - (chunk["usage"].get("prompt_tokens_details") or {}).get("cached_tokens", 0), - "output_tokens": chunk["usage"].get("completion_tokens", 0), - } - if not chunk.get("choices"): - continue - delta = chunk["choices"][0].get("delta", {}) - # GLM-5.1: skip reasoning_content (internal thinking), use only content - text = delta.get("content", "") - if text: - full_response += text - yield f"event: text\ndata: {json.dumps({'text': text}, ensure_ascii=False)}\n\n" - except (json.JSONDecodeError, KeyError, IndexError): - continue - - except Exception as e: - error_msg = f"Ошибка GLM API: {e}" - yield f"event: text\ndata: {json.dumps({'text': error_msg}, ensure_ascii=False)}\n\n" - full_response = error_msg + _provider, _model = "deepseek-qa", ZAI_MODEL + primary = qa_fallback.Endpoint("deepseek", "deepseek-qa", ZAI_BASE_URL, ZAI_API_KEY, ZAI_MODEL) + async for kind, payload in qa_fallback.stream_with_fallback( + messages, primary=primary, username=username, tab_id=tab_id): + if kind == "text": + full_response += payload + yield f"event: text\ndata: {json.dumps({'text': payload}, ensure_ascii=False)}\n\n" + elif kind == "done": + _qa_usage, _provider, _model = payload["usage"], payload["provider"], payload["model"] + else: + # Префикс «Ошибка GLM API» — сигнатура маски error_mask: main подменит его заглушкой. + error_msg = f"Ошибка GLM API: {payload}" + yield f"event: text\ndata: {json.dumps({'text': error_msg}, ensure_ascii=False)}\n\n" + full_response = error_msg # Детерминированная проверка шифров (faithfulness-слой поверх промпт-guard). # Не зависит от послушания LLM; показывает только уверенные HARD-случаи @@ -1119,7 +1082,7 @@ async def stream_claude( # usage/provider/model — учёт стоимости Ф2 (суффикс '-qa' → path='qa' в llm_usage). yield ("event: done\ndata: " + json.dumps( {"result": full_response, "usage": _qa_usage, - "provider": "deepseek-qa", "model": ZAI_MODEL}, ensure_ascii=False) + "\n\n") + "provider": _provider, "model": _model}, ensure_ascii=False) + "\n\n") def list_user_files(username: str, tab_id: str = "default") -> list[dict]: diff --git a/health_checks.py b/health_checks.py index 9630ba6..faf5302 100644 --- a/health_checks.py +++ b/health_checks.py @@ -254,11 +254,14 @@ def check_providers() -> Check: import asyncio import provider_health - bad = [] + bad, alive = [], [] for name in checkable: - if not asyncio.run(provider_health.ping_provider(name)): - bad.append(name) - detail = ("ключ не отвечает: " + ", ".join(bad)) if bad else "ключи живы: " + ", ".join(checkable) + ok, why = asyncio.run(provider_health.probe_provider(name)) + (alive if ok else bad).append(f"{name} — {why}") + if bad: + detail = "мёртв: " + "; ".join(bad) + (" | жив: " + "; ".join(alive) if alive else "") + else: + detail = "ключи живы: " + "; ".join(alive) if unknown: detail += "; проба не описана: " + ", ".join(unknown) return Check("providers", not bad, detail) diff --git a/provider_health.py b/provider_health.py index 2064ff1..5704894 100644 --- a/provider_health.py +++ b/provider_health.py @@ -268,19 +268,44 @@ async def _tick() -> None: async def ping_provider(name: str) -> bool: - """Проба живости нужного провайдера. Адрес и ключ — свои у каждого: общий пинг стучался + """Проба живости нужного провайдера — только вердикт, для монитора размыкателя.""" + return (await probe_provider(name))[0] + + +async def probe_provider(name: str) -> tuple[bool, str]: + """Проба живости с причиной. Адрес и ключ — свои у каждого: общий пинг стучался бы к дипсику и подтверждал бы жизнь зайки, пока она лежит.""" if name == "glm": key = os.environ.get("ZAI_GLM_API_KEY") or _key_from_settings("AGENT_SETTINGS_GLM", "glm") base = os.environ.get("GLM_PING_BASE", "https://api.z.ai/api/anthropic") - return await _http_ok(f"{base}/v1/messages", key, method="POST") + return await _http_probe(f"{base}/v1/messages", key, method="POST") if name == "deepseek": key = (os.environ.get("DEEPSEEK_API_KEY") or os.environ.get("ZAI_API_KEY") or _key_from_settings("AGENT_SETTINGS_DEEPSEEK", "deepseek")) base = os.environ.get("DEEPSEEK_PING_BASE", "https://api.deepseek.com") - return await _http_ok(f"{base}/user/balance", key, method="GET") + return await _http_probe(f"{base}/user/balance", key, method="GET", + verdict=_deepseek_verdict) _log.warning("проба для неизвестного провайдера %s не описана", name) - return False + return False, "проба не описана" + + +def _deepseek_verdict(r) -> tuple[bool, str]: + """Ручка остатка отвечает 200 и при пустом счёте (24.09.2026: is_available false, + остаток -0.05 USD) — жив лишь тот, у кого is_available true. Непонятный ответ = мёртв.""" + if r.status_code != 200: + return False, f"HTTP {r.status_code}" + try: + body = r.json() + except Exception: # noqa: BLE001 + return False, "ответ ручки остатка не разобран" + if not isinstance(body, dict) or "is_available" not in body: + return False, "в ответе ручки нет is_available" + infos = [i for i in (body.get("balance_infos") or []) if isinstance(i, dict)] + info = next((i for i in infos if i.get("currency") == "USD"), infos[0] if infos else None) + left = f"{info.get('total_balance')} {info.get('currency')}" if info else "неизвестен" + if body["is_available"] is True: + return True, f"остаток {left}" + return False, f"нет денег на счёте (остаток {left})" def _key_from_settings(env_name: str, provider: str = "") -> str: @@ -312,12 +337,17 @@ def _key_from_settings(env_name: str, provider: str = "") -> str: async def _http_ok(url: str, key: str, *, method: str = "GET") -> bool: - """Один дешёвый запрос: 200 = провайдер отвечает. Нет ключа, не-200 или сетевой сбой → - False (не подтвердили → держим цепь разомкнутой).""" + return (await _http_probe(url, key, method=method))[0] + + +async def _http_probe(url: str, key: str, *, method: str = "GET", + verdict=None) -> tuple[bool, str]: + """Один дешёвый запрос: 200 = провайдер отвечает (или решает verdict). Нет ключа, + не-200 или сетевой сбой → не подтверждён (держим цепь разомкнутой).""" import httpx if not key: - return False + return False, "ключ не задан" # Пустая переменная прокси — частое дело в контейнерах; пустая строка вместо адреса # роняет запрос, и провайдер ложно числится мёртвым. proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or None @@ -331,30 +361,15 @@ async def _http_ok(url: str, key: str, *, method: str = "GET") -> bool: "max_tokens": 1, "messages": [{"role": "user", "content": "."}]}) else: r = await client.get(url, headers={"Authorization": f"Bearer {key}"}) - return r.status_code == 200 - except Exception: # noqa: BLE001 — сетевые сбои = «не подтверждён» - return False + except Exception as e: # noqa: BLE001 — сетевые сбои = «не подтверждён» + return False, f"сеть: {type(e).__name__}" + if verdict is not None: + return verdict(r) + return (True, "отвечает") if r.status_code == 200 else (False, f"HTTP {r.status_code}") async def _ping_deepseek() -> bool: - """Дешёвый пинг DeepSeek с хоста: GET /user/balance (0 токенов, любой ответ - 200 = жив) — проверяет «сеть + ключ + аккаунт». НЕ проверяет контейнерный - anthropic-путь (settings/tinyproxy) — потому ping OK ведёт только в - HALF_OPEN, а CLOSED требует реального commit пробы (false-close guard). - Нет ключа / не-200 / исключение → False (не можем подтвердить → держим OPEN). - Хост имеет прямой outbound к api.deepseek.com (изоляция --internal+tinyproxy — - только для docker-контейнера агента, не для FastAPI-процесса).""" - import httpx - key = (os.environ.get("DEEPSEEK_API_KEY") or os.environ.get("ZAI_API_KEY") - or _key_from_settings("AGENT_SETTINGS_DEEPSEEK", "deepseek")) - if not key: - return False - base = os.environ.get("DEEPSEEK_PING_BASE", "https://api.deepseek.com") - proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") - try: - async with httpx.AsyncClient(timeout=10, proxy=proxy) as client: - r = await client.get(f"{base}/user/balance", - headers={"Authorization": f"Bearer {key}"}) - return r.status_code == 200 - except Exception: # noqa: BLE001 — сетевые сбои = «не подтверждён» - return False + """Пинг DeepSeek с хоста: GET /user/balance (0 токенов) — «сеть + ключ + деньги». НЕ + проверяет контейнерный anthropic-путь (settings/tinyproxy) — потому ping OK ведёт только + в HALF_OPEN, а CLOSED требует реального commit пробы (false-close guard).""" + return (await probe_provider("deepseek"))[0] diff --git a/qa_fallback.py b/qa_fallback.py new file mode 100644 index 0000000..1458002 --- /dev/null +++ b/qa_fallback.py @@ -0,0 +1,169 @@ +"""Справочный путь: основной провайдер и запасной. + +Дипсик (OpenAI-совместимый /chat/completions) отказал ДО первого отданного текста — 402, 401, +429, 5xx, сеть — и тот же запрос уходит зайке по подписке (OpenAI-совместимый вход Coding +Plan). Уже отданный текст не переигрываем: два ответа склеились бы в один. + +Инцидент 24.09.2026: у дипсика кончились деньги, а у справочного пути запасного не было — +человек получал только маску «сервис недоступен». +""" + +import asyncio +import json +import logging +import os +import re +from dataclasses import dataclass +from typing import AsyncGenerator + +import httpx + +import provider_health +import zaika_quota + +_log = logging.getLogger("smeta_web") + +# Вход подписки Coding Plan: у потокового входа z.ai «нет баланса», работает только этот. +ZAIKA_BASE_URL = os.environ.get("QA_FALLBACK_BASE_URL", "https://api.z.ai/api/coding/paas/v4") + + +@dataclass(frozen=True) +class Endpoint: + name: str # имя для размыкателя: "deepseek" | "glm" + label: str # подпись в учёте: суффикс -qa уводит строку на путь qa + base_url: str + key: str + model: str + + +class ProviderRefused(Exception): + """Провайдер ответил не-2xx. В тексте код и начало тела — без адреса и ключа, чтобы + причина годилась и в журнал, и в маску.""" + + def __init__(self, status: int, body: str = ""): + self.status, self.body = status, body + snippet = re.sub(r"\s+", " ", body or "").strip()[:160] + super().__init__(f"HTTP {status}" + (f" — {snippet}" if snippet else "")) + + +def describe(e: BaseException) -> str: + if isinstance(e, ProviderRefused): + return str(e) + # Текст сетевых ошибок httpx бывает с адресом — берём только имя класса. + return type(e).__name__ + + +def zaika_endpoint() -> Endpoint: + import agent_provider + key = (os.environ.get("ZAI_GLM_API_KEY") + or provider_health._key_from_settings("AGENT_SETTINGS_GLM", "glm")) + return Endpoint("glm", "glm-qa", ZAIKA_BASE_URL, key, + agent_provider._profile_by_name("glm").model) + + +def request_body(model: str, messages: list) -> dict: + return { + "model": model, + "messages": messages, + "stream": True, + # usage в финальном чанке стрима (OpenAI-совм.) — питает учёт llm_usage (Ф2). + "stream_options": {"include_usage": True}, + "temperature": 0.1, + "max_tokens": 4096, + "thinking": {"type": "disabled"}, + } + + +async def stream_chat(ep: Endpoint, messages: list) -> AsyncGenerator[tuple[str, object], None]: + """Куски ответа: ("text", str) и ("usage", dict в формате Anthropic). Не-2xx → + ProviderRefused, сеть → исключение httpx.""" + # Пустая переменная прокси — не адрес: пустая строка роняет запрос. + proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or None + async with httpx.AsyncClient(timeout=120, proxy=proxy) as client: + async with client.stream("POST", f"{ep.base_url}/chat/completions", + headers={"Authorization": f"Bearer {ep.key}"}, + json=request_body(ep.model, messages)) as resp: + if resp.status_code >= 400: + raise ProviderRefused(resp.status_code, + (await resp.aread()).decode("utf-8", "replace")) + async for line in resp.aiter_lines(): + if not line.startswith("data: "): + continue + data_str = line[6:] + if data_str == "[DONE]": + break + try: + chunk = json.loads(data_str) + if chunk.get("usage"): + u = chunk["usage"] + yield "usage", { + "input_tokens": u.get("prompt_tokens", 0), + "cache_read_input_tokens": + (u.get("prompt_tokens_details") or {}).get("cached_tokens", 0), + "output_tokens": u.get("completion_tokens", 0), + } + if not chunk.get("choices"): + continue + # reasoning_content — внутренние рассуждения модели, человеку не показываем + text = chunk["choices"][0].get("delta", {}).get("content", "") + if text: + yield "text", text + except (json.JSONDecodeError, KeyError, IndexError): + continue + + +async def stream_with_fallback(messages: list, *, primary: Endpoint, username: str, + tab_id: str) -> AsyncGenerator[tuple[str, object], None]: + """События: ("text", str) | ("done", {"usage", "provider", "model"}) | ("error", причина).""" + chain = [primary, zaika_endpoint()] + for idx, ep in enumerate(chain): + if ep.name == "glm": + snap = await asyncio.to_thread(zaika_quota.snapshot) + if snap.get("source") == "refusal": + _log.warning("справочный путь: зайку не зову — окно подписки исчерпано") + continue + if not ep.key: + _log.warning("справочный путь: у %s нет ключа — пропускаю", ep.name) + continue + allowed, is_probe = provider_health.attempt_gate(ep.name) + if not allowed: + _log.info("справочный путь: %s закрыт размыкателем — пропускаю", ep.name) + continue + committed, usage, failure = False, {}, "" + try: + async for kind, payload in stream_chat(ep, messages): + if kind == "usage": + usage = payload + elif payload: + committed = True + yield "text", payload + # Отмена клиентом (CancelledError/GeneratorExit) сюда не попадает: вердикта нет. + except Exception as e: # noqa: BLE001 + failure = f"{ep.name}: {describe(e)}" + finally: + if is_probe: + provider_health.release_probe(ep.name) + if not failure and not committed: + failure = f"{ep.name}: пустой ответ" + if not failure: + provider_health.record_success(ep.name) + yield "done", {"usage": usage, "provider": ep.label, "model": ep.model} + return + if committed: + _log.warning("справочный путь: %s оборвался после начала ответа (%s)", ep.name, failure) + yield "error", failure + return + quota = ep.name == "glm" and await asyncio.to_thread(zaika_quota.note_refusal, "glm", failure) + if not quota: + provider_health.record_failure(ep.name) + if idx < len(chain) - 1: + nxt = chain[idx + 1].name + _log.warning("справочный путь: %s отказал до первого текста (%s) — отвечает %s", + ep.name, failure, nxt) + import db + await asyncio.to_thread(db.log_action, username, "qa_fallback", "STREAM", "/api/chat", + f"{ep.name}→{nxt}: {failure}"[:200], None, 502) + continue + yield "error", failure + return + yield "error", "ни один провайдер справочного пути не доступен" diff --git a/telegram_verify.py b/telegram_verify.py index 78c08da..2de11bd 100644 --- a/telegram_verify.py +++ b/telegram_verify.py @@ -17,7 +17,7 @@ t.me/<бот>?start=<метка>, жмёт «Старт», и Telegram прин сообщения с нами). Отдельный ключ снимает этот вопрос целиком, а его утечка не позволяет подделывать тревоги оператору. -Сеть — httpx напрямую, без прокси (trust_env=False), как в alerts.py; опрос +Сеть — httpx без прокси из окружения (trust_env=False), через TG_PROXY_URL, как в alerts.py; опрос обновлений живёт отдельно, в `telegram_poll.py`. """ @@ -76,9 +76,11 @@ def _api(method: str, data: dict) -> dict: чем Telegram по нашей же просьбе держит длинный опрос, — иначе рвался бы каждый тихий заход.""" import httpx + from alerts import tg_proxy чтение = _READ_TIMEOUT + int(data.get("timeout") or 0) + kw = {"proxy": tg_proxy()} if tg_proxy() else {} r = httpx.post(f"https://api.telegram.org/bot{_token()}/{method}", json=data, - timeout=httpx.Timeout(чтение, connect=_CONNECT_TIMEOUT), trust_env=False) + timeout=httpx.Timeout(чтение, connect=_CONNECT_TIMEOUT), trust_env=False, **kw) return r.json() diff --git a/tests/test_qa_fallback.py b/tests/test_qa_fallback.py index 1c3cf56..bddcf67 100644 --- a/tests/test_qa_fallback.py +++ b/tests/test_qa_fallback.py @@ -167,8 +167,9 @@ def test_success_closes_the_streak(env): assert ph.snapshot()["deepseek"]["streak"] == 0 -def test_probe_slot_is_released_on_failure(env, monkeypatch): - """Порча: убрать release_probe → проба зайки залипнет, и она не вернётся до TTL.""" +def test_probe_slot_is_released_when_the_person_leaves(env, monkeypatch): + """Человек закрыл вкладку посреди ответа пробной попытки — вердикта нет, но слот пробы + обязан освободиться. Порча: убрать release_probe → зайка залипнет до TTL (21 минута).""" qf, ph, db, calls, script = env now = [1000.0] monkeypatch.setattr(ph, "_now", lambda: now[0]) @@ -176,9 +177,18 @@ def test_probe_slot_is_released_on_failure(env, monkeypatch): ph.record_failure("glm") now[0] += 61 script["deepseek"] = [("text", refused(402))] - script["glm"] = [("text", httpx.ConnectError("x"))] - run(qf) + script["glm"] = [("text", "начало"), ("text", "продолжение")] + + async def go(): + agen = qf.stream_with_fallback([{"role": "user", "content": "в"}], primary=primary(qf), + username="u@x", tab_id="t") + first = await agen.__anext__() + await agen.aclose() + return first + + assert asyncio.run(go()) == ("text", "начало") assert ph.snapshot()["glm"]["half_open_inflight"] is False + assert ph.snapshot()["glm"]["status"] == ph.HALF_OPEN def test_quota_mark_skips_zaika(env):