""" Minimal OpenRouter REST client (sync). API-Key und Basis-URL aus der Umgebung. Das wirksame Standardmodell kommt aus platform_ai_settings (Superadmin), sonst aus OPENROUTER_MODEL. """ from __future__ import annotations import json import logging import os import re import threading import time from datetime import datetime, timezone from typing import Any, Dict, List, Mapping, Optional, Tuple import httpx _logger = logging.getLogger("shinkan.openrouter") _SKIP_ANTHROPIC_BLOCK_TYPES = frozenset( { "thinking", "redacted_thinking", "reasoning", "tool_use", "tool_calls", } ) def _shinkan_ai_debug() -> bool: return os.getenv("SHINKAN_AI_DEBUG", "").strip().lower() in ("1", "true", "yes", "full") def _coerce_nested_text(val: Any) -> str: if val is None: return "" if isinstance(val, str): return val.strip() if isinstance(val, bool) or isinstance(val, (int, float)): return str(val).strip() if isinstance(val, list): return "".join(_coerce_nested_text(x) for x in val).strip() if isinstance(val, dict): # OpenRouter/Anthropic: verschachtelte text/content-Hüllen for key in ("text", "content", "value"): if key in val: nested = _coerce_nested_text(val.get(key)) if nested: return nested return "" return str(val).strip() def _flatten_message_content(content: Any) -> str: """ Chat-Completion: `content` als String oder als Liste strukturierter Blöcke (Anthropic Claude über OpenRouter/Bedrock, teils verschachtelt). """ if content is None: return "" if isinstance(content, str): return content.strip() if isinstance(content, list): parts: List[str] = [] for block in content: if isinstance(block, str): bits = _coerce_nested_text(block) if bits: parts.append(bits) elif isinstance(block, dict): t_raw = block.get("type") ts = str(t_raw or "").strip().lower() if ts and (ts in _SKIP_ANTHROPIC_BLOCK_TYPES or ts.endswith("_thinking")): continue txt = None if ts in ("text", "output_text", ""): txt = block.get("text") if txt is None: txt = block.get("content") else: # unbekannten Typ weiter versuchen (Provider-Varianten), aber tool-use überspringen low = ts if "tool_use" in low or low.startswith("tool_"): continue txt = block.get("text") if block.get("text") is not None else block.get("content") bits = _coerce_nested_text(txt) if bits: parts.append(bits) return "".join(parts).strip() if isinstance(content, dict): return _coerce_nested_text(content) return str(content).strip() class OpenRouterError(Exception): """Upstream or transport failure.""" def openrouter_chat_completion( *, api_key: str, model: str, user_content: str, system_content: Optional[str] = None, timeout_sec: float = 120.0, temperature: float = 0.25, site_url: Optional[str] = None, app_title: Optional[str] = None, ) -> str: """ Returns assistant message content (plain string). Caller validates empty responses. """ base = (os.getenv("OPENROUTER_BASE_URL") or "").strip().rstrip("/") or "https://openrouter.ai/api/v1" url = f"{base}/chat/completions" headers: Dict[str, str] = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", } referer = (site_url or os.getenv("APP_URL") or "").strip() if referer: headers["HTTP-Referer"] = referer title = (app_title or os.getenv("OPENROUTER_APP_TITLE") or "Shinkan Jinkendo").strip() if title: headers["X-Title"] = title messages: List[Dict[str, str]] = [] if system_content and str(system_content).strip(): messages.append({"role": "system", "content": str(system_content).strip()}) messages.append({"role": "user", "content": user_content}) payload: Dict[str, Any] = { "model": model, "messages": messages, "temperature": temperature, } try: with httpx.Client(timeout=timeout_sec) as client: resp = client.post(url, headers=headers, json=payload) except httpx.RequestError as e: raise OpenRouterError(str(e)) from e if resp.status_code >= 400: detail = "" try: j = resp.json() detail = ( str(j.get("error", {}).get("message")) if isinstance(j.get("error"), dict) else str(j.get("message") or j) ) except Exception: detail = (resp.text or "")[:600] raise OpenRouterError(f"HTTP {resp.status_code}: {detail}".strip()) try: data = resp.json() except json.JSONDecodeError as e: raise OpenRouterError("Ungueltige JSON-Antwort von OpenRouter") from e choices = data.get("choices") if isinstance(data, dict) else None if not choices or not isinstance(choices, list): raise OpenRouterError("OpenRouter: keine choices in Antwort") msg0 = choices[0] if choices else {} inner = msg0.get("message") if isinstance(msg0, dict) else None blobs: List[Any] = [] if isinstance(inner, dict): if inner.get("content") is not None: blobs.append(inner.get("content")) if inner.get("refusal") is not None: blobs.append(inner.get("refusal")) elif isinstance(inner, str): blobs.append(inner) if isinstance(msg0, dict) and msg0.get("content") is not None and msg0.get("content") not in blobs: blobs.append(msg0.get("content")) pieces = [_flatten_message_content(b).strip() for b in blobs if b is not None] joined = ("\n".join(p for p in pieces if p)).strip() if _shinkan_ai_debug(): fr = str(msg0.get("finish_reason") or "") if isinstance(msg0, dict) else "" fu = data.get("usage") if isinstance(data.get("usage"), dict) else {} pu = str(fu.get("prompt_tokens") or "") pc = str(fu.get("completion_tokens") or "") pt = str(fu.get("total_tokens") or "") raw_cls = type(blobs[0]).__name__ if blobs else "none" cc = str(len(joined)) _logger.warning( "[AI_DEBUG/openrouter] model=%s finish_reason=%s usage_prompt=%s usage_completion=%s usage_total=%s " "raw_content_cls=%s out_chars=%s", model, fr, pu, pc, pt, raw_cls, cc, ) try: from planning_llm_usage import record_planning_llm_call record_planning_llm_call(1) except Exception: pass return joined _MODEL_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:@+/-]{0,198}$") _CATALOG_TTL_SEC = 600 _catalog_lock = threading.Lock() _catalog_cache: Dict[str, Any] = {"fetched_at": 0.0, "fetched_at_iso": None, "models": None} _settings_read_failed = False _FALLBACK_MODEL = "anthropic/claude-sonnet-4" def openrouter_base_url() -> str: return (os.getenv("OPENROUTER_BASE_URL") or "").strip().rstrip("/") or "https://openrouter.ai/api/v1" def normalize_openrouter_model_id(raw: Optional[str]) -> Optional[str]: """Leer wird None. Ungültige IDs werfen ValueError.""" if raw is None: return None text = str(raw).strip() if not text: return None if any(ch.isspace() for ch in text): raise ValueError("OpenRouter-Modell-ID darf keine Leer- oder Steuerzeichen enthalten.") if ( not _MODEL_ID_RE.match(text) or "/" not in text or text.startswith("/") or text.endswith("/") or "//" in text ): raise ValueError("OpenRouter-Modell-ID muss wie anbieter/modell aussehen.") return text def env_openrouter_model_id() -> str: model = (os.getenv("OPENROUTER_MODEL") or _FALLBACK_MODEL).strip() return model or _FALLBACK_MODEL def resolve_default_openrouter_model_id( stored: Optional[str], env_model: Optional[str] = None, ) -> Tuple[str, str]: """Wirksame ID und Quelle (`database` oder `environment`).""" custom: Optional[str] = None try: custom = normalize_openrouter_model_id(stored) except ValueError: custom = None if custom: return custom, "database" env = env_openrouter_model_id() if env_model is None else (str(env_model).strip() or _FALLBACK_MODEL) return env or _FALLBACK_MODEL, "environment" def read_stored_platform_openrouter_model() -> Optional[str]: """Gespeichertes Plattformmodell. Bei fehlender Tabelle oder DB-Fehler: None.""" global _settings_read_failed try: from db import get_cursor, get_db with get_db() as conn: cur = get_cursor(conn) cur.execute("SELECT openrouter_model FROM platform_ai_settings WHERE id = 1") row = cur.fetchone() _settings_read_failed = False if not row: return None raw = row.get("openrouter_model") if isinstance(row, dict) else row[0] text = str(raw or "").strip() return text or None except Exception as exc: if not _settings_read_failed: _logger.warning( "Plattform-OpenRouter-Modell nicht lesbar, nutze OPENROUTER_MODEL: %s", exc, ) _settings_read_failed = True return None def normalize_openrouter_env() -> tuple[str, str]: """API-Key und Env-Modell. Das wirksame Modell liefert default_openrouter_model_id().""" key = (os.getenv("OPENROUTER_API_KEY") or "").strip() return key, env_openrouter_model_id() def default_openrouter_model_id() -> str: """Plattform-Standard aus der Datenbank, sonst OPENROUTER_MODEL.""" effective, _source = resolve_default_openrouter_model_id(read_stored_platform_openrouter_model()) return effective def effective_openrouter_model_for_prompt_row(row: Optional[Mapping[str, Any]]) -> str: """ Pro-Prompt-Override in ai_prompts.openrouter_model, sonst Plattform-Standard. `row` kann eine partial Row aus load_ai_prompt_row sein (Felder slug, openrouter_model, …). """ if row: custom = str(row.get("openrouter_model") or "").strip() if custom: return custom return default_openrouter_model_id() def _price_str(pricing: Any, key: str) -> Optional[str]: if not isinstance(pricing, dict): return None raw = pricing.get(key) if raw is None or raw == "": return None try: float(str(raw)) except (TypeError, ValueError): return None return str(raw) def _modalities(item: Mapping[str, Any], side: str) -> List[str]: arch = item.get("architecture") if isinstance(item.get("architecture"), dict) else {} key = "input_modalities" if side == "input" else "output_modalities" raw = arch.get(key) if isinstance(raw, list): out = [str(x).strip().lower() for x in raw if str(x).strip()] if out: return out modality = str(arch.get("modality") or "") parts = modality.split("->") chunk = parts[0] if side == "input" else (parts[1] if len(parts) > 1 else "") return [p.strip().lower() for p in chunk.split("+") if p.strip()] def _context_length(item: Mapping[str, Any]) -> Optional[int]: candidates = [item.get("context_length")] top = item.get("top_provider") if isinstance(top, dict): candidates.append(top.get("context_length")) for raw in candidates: try: value = int(raw) except (TypeError, ValueError): continue if value > 0: return value return None def parse_openrouter_models_payload(data: Any) -> List[Dict[str, Any]]: """OpenRouter `/models` auf eine schlanke, stabile Liste bringen.""" rows = data.get("data") if isinstance(data, dict) else None if not isinstance(rows, list): raise OpenRouterError("OpenRouter: Modellliste ohne data-Array") out: List[Dict[str, Any]] = [] seen = set() for item in rows: if not isinstance(item, dict): continue model_id = str(item.get("id") or "").strip() if not model_id or model_id in seen: continue seen.add(model_id) provider = model_id.split("/", 1)[0] description = str(item.get("description") or "").replace("\r", " ").replace("\n", " ").strip() if len(description) > 400: description = description[:397].rstrip() + "…" prompt_price = _price_str(item.get("pricing"), "prompt") completion_price = _price_str(item.get("pricing"), "completion") try: prompt_num = float(prompt_price) if prompt_price is not None else None completion_num = float(completion_price) if completion_price is not None else None except ValueError: prompt_num = None completion_num = None is_free = model_id.endswith(":free") or ( prompt_num == 0 and completion_num == 0 and (prompt_num is not None or completion_num is not None) ) out.append( { "id": model_id, "name": str(item.get("name") or model_id).strip() or model_id, "description": description, "context_length": _context_length(item), "prompt_usd_per_token": prompt_price, "completion_usd_per_token": completion_price, "input_modalities": _modalities(item, "input"), "output_modalities": _modalities(item, "output"), "provider": provider, "is_free": bool(is_free), } ) out.sort(key=lambda row: (row["name"].lower(), row["id"].lower())) return out def clear_openrouter_model_catalog_cache() -> None: with _catalog_lock: _catalog_cache["fetched_at"] = 0.0 _catalog_cache["fetched_at_iso"] = None _catalog_cache["models"] = None def _download_openrouter_models() -> List[Dict[str, Any]]: url = f"{openrouter_base_url()}/models" headers: Dict[str, str] = {"Accept": "application/json"} key = (os.getenv("OPENROUTER_API_KEY") or "").strip() if key: headers["Authorization"] = f"Bearer {key}" referer = (os.getenv("APP_URL") or "").strip() if referer: headers["HTTP-Referer"] = referer title = (os.getenv("OPENROUTER_APP_TITLE") or "Shinkan Jinkendo").strip() if title: headers["X-Title"] = title try: with httpx.Client(timeout=25.0) as client: resp = client.get(url, headers=headers) except httpx.RequestError as exc: raise OpenRouterError("Verbindung zu OpenRouter fehlgeschlagen") from exc if resp.status_code >= 400: raise OpenRouterError(f"OpenRouter antwortet mit HTTP {resp.status_code}") try: payload = resp.json() except json.JSONDecodeError as exc: raise OpenRouterError("OpenRouter hat kein gültiges JSON geliefert") from exc return parse_openrouter_models_payload(payload) def fetch_openrouter_model_catalog(*, force: bool = False) -> Dict[str, Any]: """Modellkatalog, zehn Minuten im Prozess zwischengespeichert.""" now = time.monotonic() with _catalog_lock: cached = _catalog_cache.get("models") age = now - float(_catalog_cache.get("fetched_at") or 0) if isinstance(cached, list) and not force and age < _CATALOG_TTL_SEC: return { "models": cached, "count": len(cached), "cached": True, "stale": False, "fetched_at": _catalog_cache.get("fetched_at_iso"), } try: models = _download_openrouter_models() except OpenRouterError: with _catalog_lock: cached = _catalog_cache.get("models") if isinstance(cached, list): return { "models": cached, "count": len(cached), "cached": True, "stale": True, "fetched_at": _catalog_cache.get("fetched_at_iso"), } raise fetched_iso = datetime.now(timezone.utc).isoformat() with _catalog_lock: _catalog_cache["models"] = models _catalog_cache["fetched_at"] = time.monotonic() _catalog_cache["fetched_at_iso"] = fetched_iso return { "models": models, "count": len(models), "cached": False, "stale": False, "fetched_at": fetched_iso, }