| 1 | """Static provider catalog and runtime client implementations.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import ipaddress |
| 6 | import json |
| 7 | import os |
| 8 | import re |
| 9 | import sys |
| 10 | import time |
| 11 | from collections.abc import Iterator |
| 12 | from contextlib import contextmanager |
| 13 | from threading import Event |
| 14 | from typing import Any |
| 15 | from urllib.parse import quote, urlsplit, urlunsplit |
| 16 | |
| 17 | from . import env, http, proxy, schema |
| 18 | |
| 19 | GEMINI_FLASH_LITE = "gemini-3.1-flash-lite" |
| 20 | GEMINI_PRO = "gemini-3.1-pro-preview" |
| 21 | OPENAI_DEFAULT = "gpt-5.4-nano" |
| 22 | XAI_DEFAULT = "grok-4.20-0309-non-reasoning" |
| 23 | |
| 24 | GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent" |
| 25 | _GEMINI_MODEL_RE = re.compile(r"gemini-([0-9]+)(?:\.([0-9]+))?(?:-[A-Za-z0-9._-]+)?", re.ASCII) |
| 26 | _GEMINI_MODEL_SEGMENT_RE = re.compile(r"[A-Za-z0-9._-]+", re.ASCII) |
| 27 | OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses" |
| 28 | XAI_RESPONSES_URL = "https://api.x.ai/v1/responses" |
| 29 | OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions" |
| 30 | # OpenRouter routes the Gemini Flash Lite tier as the -preview slug; that is the |
| 31 | # stable form on that routing layer even though native Gemini's GEMINI_FLASH_LITE |
| 32 | # constant is suffix-free. If GEMINI_FLASH_LITE moves to a non-preview stable ID, |
| 33 | # double-check that OpenRouter's slug still maps to the same upstream model. |
| 34 | OPENROUTER_DEFAULT = "google/gemini-3.1-flash-lite-preview" |
| 35 | PROVIDER_BASE_URL_KEYS = frozenset({"OPENAI_BASE_URL", "XAI_BASE_URL", "OPENROUTER_BASE_URL", "SCRAPECREATORS_BASE_URL"}) |
| 36 | |
| 37 | |
| 38 | def _is_loopback(host: str) -> bool: |
| 39 | """True for hosts that never leave the machine.""" |
| 40 | if host == "localhost": |
| 41 | return True |
| 42 | try: |
| 43 | return ipaddress.ip_address(host).is_loopback |
| 44 | except ValueError: |
| 45 | return False |
| 46 | |
| 47 | |
| 48 | def allowed_base_url_override(value: str) -> bool: |
| 49 | try: |
| 50 | parts = urlsplit(value) |
| 51 | host = parts.hostname |
| 52 | except ValueError: |
| 53 | return False |
| 54 | return bool(host) and ( |
| 55 | parts.scheme == "https" or (parts.scheme == "http" and _is_loopback(host)) |
| 56 | ) |
| 57 | |
| 58 | |
| 59 | def is_loopback_http_endpoint(url: str) -> bool: |
| 60 | parts = urlsplit(url) |
| 61 | return parts.scheme == "http" and _is_loopback(parts.hostname or "") |
| 62 | |
| 63 | |
| 64 | def base_url_override(key: str, default: str) -> str: |
| 65 | """Resolve a provider base-URL override, refusing cleartext remote hosts. |
| 66 | |
| 67 | Every provider resolves its endpoint through here so one guard covers both |
| 68 | ways a value arrives: the process environment, and |
| 69 | ``_propagate_config_to_environ`` pushing a `.env` value into os.environ. |
| 70 | |
| 71 | A base-URL override redirects the request that carries the provider's bearer |
| 72 | token, so an `http://` override to a remote host would put the API key on |
| 73 | the wire in cleartext. That is refused and the built-in vendor endpoint is |
| 74 | used instead - failing closed protects the credential, and the warning makes |
| 75 | the drop visible instead of leaving the user to wonder why their gateway is |
| 76 | being bypassed. Loopback is the one legitimate `http://` case (a local |
| 77 | LiteLLM/Ollama gateway or an SSH tunnel never leaves the machine), so it is |
| 78 | allowed. |
| 79 | """ |
| 80 | raw = (os.environ.get(key) or "").strip() |
| 81 | if not raw: |
| 82 | return default |
| 83 | if allowed_base_url_override(raw): |
| 84 | return raw |
| 85 | sys.stderr.write( |
| 86 | f"[last30days] WARNING: ignoring {key} - a provider endpoint override " |
| 87 | "must be https:// (http:// is allowed only on localhost), otherwise the API " |
| 88 | f"key would be sent in cleartext. Using {default} instead.\n" |
| 89 | ) |
| 90 | sys.stderr.flush() |
| 91 | return default |
| 92 | |
| 93 | |
| 94 | _ENDPOINT_PATHS = { |
| 95 | OPENAI_RESPONSES_URL: "/responses", |
| 96 | XAI_RESPONSES_URL: "/responses", |
| 97 | OPENROUTER_URL: "/chat/completions", |
| 98 | } |
| 99 | |
| 100 | |
| 101 | def resolve_endpoint(env_var: str, default_url: str) -> str: |
| 102 | """Resolve a ``*_BASE_URL`` override into a full endpoint URL. |
| 103 | |
| 104 | By the convention every OpenAI-compatible provider documents, ``*_BASE_URL`` |
| 105 | names the API root (``https://host/v1``) and the client appends the endpoint |
| 106 | path. This module historically required the full endpoint URL instead, so a |
| 107 | value copied from a provider's setup guide POSTed to the API root and failed. |
| 108 | |
| 109 | Accept both forms: a host or versioned API root gets the endpoint path |
| 110 | appended, and a complete gateway route is used unchanged. Query strings |
| 111 | stay after the path in either form. |
| 112 | """ |
| 113 | override = base_url_override(env_var, default_url) |
| 114 | if override == default_url: |
| 115 | return default_url |
| 116 | parts = urlsplit(override) |
| 117 | root_path = parts.path.rstrip("/") |
| 118 | last_segment = root_path.rsplit("/", 1)[-1] |
| 119 | if not root_path or re.fullmatch(r"v\d+(?:beta\d*)?", last_segment): |
| 120 | return urlunsplit(parts._replace(path=root_path + _ENDPOINT_PATHS[default_url])) |
| 121 | return override |
| 122 | |
| 123 | |
| 124 | class ReasoningClient: |
| 125 | """Shared interface for planner and rerank providers.""" |
| 126 | |
| 127 | name: str |
| 128 | |
| 129 | def __init__(self) -> None: |
| 130 | self._usage_calls = 0 |
| 131 | self._usage_prompt_tokens = 0 |
| 132 | self._usage_completion_tokens = 0 |
| 133 | self._usage_complete = True |
| 134 | self._request_deadline: float | None = None |
| 135 | self._request_cancel: Event | None = None |
| 136 | self._request_attempts: int | None = None |
| 137 | |
| 138 | def set_request_budget(self, deadline: float, cancel: Event | None) -> None: |
| 139 | self._request_deadline = deadline |
| 140 | self._request_cancel = cancel |
| 141 | |
| 142 | @contextmanager |
| 143 | def request_budget( |
| 144 | self, deadline: float, cancel: Event | None, *, attempts: int, |
| 145 | ) -> Iterator[None]: |
| 146 | """Apply a smaller budget to one stage without affecting later calls.""" |
| 147 | previous = (self._request_deadline, self._request_cancel, self._request_attempts) |
| 148 | self.set_request_budget(deadline, cancel) |
| 149 | self._request_attempts = attempts |
| 150 | try: |
| 151 | yield |
| 152 | finally: |
| 153 | self._request_deadline, self._request_cancel, self._request_attempts = previous |
| 154 | |
| 155 | @staticmethod |
| 156 | def _valid_token_count(value: Any) -> bool: |
| 157 | return isinstance(value, int) and not isinstance(value, bool) and value >= 0 |
| 158 | |
| 159 | def record_usage( |
| 160 | self, |
| 161 | prompt_tokens: Any, |
| 162 | completion_tokens: Any, |
| 163 | total_tokens: Any = None, |
| 164 | ) -> None: |
| 165 | self._usage_calls += 1 |
| 166 | if not self._valid_token_count(prompt_tokens): |
| 167 | self._usage_complete = False |
| 168 | return |
| 169 | if total_tokens is not None: |
| 170 | if ( |
| 171 | not self._valid_token_count(total_tokens) |
| 172 | or total_tokens < prompt_tokens |
| 173 | or ( |
| 174 | completion_tokens is not None |
| 175 | and ( |
| 176 | not self._valid_token_count(completion_tokens) |
| 177 | or total_tokens < prompt_tokens + completion_tokens |
| 178 | ) |
| 179 | ) |
| 180 | ): |
| 181 | self._usage_complete = False |
| 182 | return |
| 183 | # Reported totals can include reasoning tokens absent from completion counts. |
| 184 | completion_tokens = total_tokens - prompt_tokens |
| 185 | elif not self._valid_token_count(completion_tokens): |
| 186 | self._usage_complete = False |
| 187 | return |
| 188 | self._usage_prompt_tokens += prompt_tokens |
| 189 | self._usage_completion_tokens += completion_tokens |
| 190 | |
| 191 | @property |
| 192 | def total_usage(self) -> dict[str, int] | None: |
| 193 | if not self._usage_calls or not self._usage_complete: |
| 194 | return None |
| 195 | return { |
| 196 | "calls": self._usage_calls, |
| 197 | "promptTokens": self._usage_prompt_tokens, |
| 198 | "completionTokens": self._usage_completion_tokens, |
| 199 | "totalTokens": self._usage_prompt_tokens + self._usage_completion_tokens, |
| 200 | } |
| 201 | |
| 202 | def _mark_usage_incomplete(self) -> None: |
| 203 | self._usage_complete = False |
| 204 | |
| 205 | def _post(self, url: str, payload: dict[str, Any], **kwargs: Any) -> dict[str, Any]: |
| 206 | if self._request_deadline is not None: |
| 207 | now = time.monotonic() |
| 208 | if now >= self._request_deadline or ( |
| 209 | self._request_cancel is not None and self._request_cancel.is_set() |
| 210 | ): |
| 211 | raise http.DeadlineExceeded() |
| 212 | kwargs["deadline_monotonic"] = min(self._request_deadline, now + kwargs["timeout"]) |
| 213 | kwargs["cancel"] = self._request_cancel |
| 214 | if self._request_attempts is not None: |
| 215 | kwargs["retries"] = self._request_attempts |
| 216 | kwargs["retry_dns"] = False |
| 217 | try: |
| 218 | return http.post(url, payload, on_retry=self._mark_usage_incomplete, **kwargs) |
| 219 | except Exception: |
| 220 | self._mark_usage_incomplete() |
| 221 | raise |
| 222 | |
| 223 | def _record_response_usage( |
| 224 | self, |
| 225 | response: dict[str, Any], |
| 226 | *, |
| 227 | metadata_key: str, |
| 228 | prompt_key: str, |
| 229 | completion_key: str, |
| 230 | total_key: str, |
| 231 | prompt_fallback_key: str | None = None, |
| 232 | completion_fallback_key: str | None = None, |
| 233 | ) -> None: |
| 234 | usage = response.get(metadata_key) |
| 235 | if not isinstance(usage, dict): |
| 236 | usage = {} |
| 237 | prompt_tokens = usage.get(prompt_key) |
| 238 | completion_tokens = usage.get(completion_key) |
| 239 | if prompt_tokens is None and prompt_fallback_key: |
| 240 | prompt_tokens = usage.get(prompt_fallback_key) |
| 241 | if completion_tokens is None and completion_fallback_key: |
| 242 | completion_tokens = usage.get(completion_fallback_key) |
| 243 | self.record_usage( |
| 244 | prompt_tokens, |
| 245 | completion_tokens, |
| 246 | usage.get(total_key), |
| 247 | ) |
| 248 | |
| 249 | def generate_text( |
| 250 | self, |
| 251 | model: str, |
| 252 | prompt: str, |
| 253 | *, |
| 254 | tools: list[dict[str, Any]] | None = None, |
| 255 | response_mime_type: str | None = None, |
| 256 | ) -> str: |
| 257 | raise NotImplementedError |
| 258 | |
| 259 | def generate_json( |
| 260 | self, |
| 261 | model: str, |
| 262 | prompt: str, |
| 263 | *, |
| 264 | tools: list[dict[str, Any]] | None = None, |
| 265 | ) -> dict[str, Any]: |
| 266 | text = self.generate_text(model, prompt, tools=tools, response_mime_type="application/json") |
| 267 | return extract_json(text) |
| 268 | |
| 269 | |
| 270 | class GeminiClient(ReasoningClient): |
| 271 | name = "gemini" |
| 272 | |
| 273 | def __init__(self, api_key: str): |
| 274 | super().__init__() |
| 275 | self.api_key = api_key |
| 276 | |
| 277 | def _generate_content( |
| 278 | self, |
| 279 | model: str, |
| 280 | prompt: str, |
| 281 | *, |
| 282 | tools: list[dict[str, Any]] | None = None, |
| 283 | response_mime_type: str | None = None, |
| 284 | ) -> dict[str, Any]: |
| 285 | safe_model = _validate_gemini_model_segment(model) |
| 286 | body: dict[str, Any] = { |
| 287 | "contents": [{"parts": [{"text": prompt}]}], |
| 288 | "generationConfig": {"temperature": 0}, |
| 289 | } |
| 290 | if response_mime_type: |
| 291 | body["generationConfig"]["responseMimeType"] = response_mime_type |
| 292 | if tools: |
| 293 | body["tools"] = tools |
| 294 | url = GEMINI_URL.format(model=safe_model) |
| 295 | expected_origin = http._request_origin(url) |
| 296 | |
| 297 | def _same_origin_redirect(newurl: str) -> bool: |
| 298 | try: |
| 299 | return http._request_origin(newurl) == expected_origin |
| 300 | except ValueError: |
| 301 | return False |
| 302 | |
| 303 | return self._post( |
| 304 | url, |
| 305 | body, |
| 306 | headers={ |
| 307 | "Content-Type": "application/json", |
| 308 | "x-goog-api-key": self.api_key, |
| 309 | }, |
| 310 | timeout=90, |
| 311 | redirect_guard=_same_origin_redirect, |
| 312 | ) |
| 313 | |
| 314 | def generate_text( |
| 315 | self, |
| 316 | model: str, |
| 317 | prompt: str, |
| 318 | *, |
| 319 | tools: list[dict[str, Any]] | None = None, |
| 320 | response_mime_type: str | None = None, |
| 321 | ) -> str: |
| 322 | payload = self._generate_content( |
| 323 | model, |
| 324 | prompt, |
| 325 | tools=tools, |
| 326 | response_mime_type=response_mime_type, |
| 327 | ) |
| 328 | self._record_response_usage( |
| 329 | payload, |
| 330 | metadata_key="usageMetadata", |
| 331 | prompt_key="promptTokenCount", |
| 332 | completion_key="candidatesTokenCount", |
| 333 | total_key="totalTokenCount", |
| 334 | ) |
| 335 | return extract_gemini_text(payload) |
| 336 | |
| 337 | class OpenAIClient(ReasoningClient): |
| 338 | name = "openai" |
| 339 | |
| 340 | def __init__(self, token: str): |
| 341 | super().__init__() |
| 342 | self.token = token |
| 343 | |
| 344 | def generate_text( |
| 345 | self, |
| 346 | model: str, |
| 347 | prompt: str, |
| 348 | *, |
| 349 | tools: list[dict[str, Any]] | None = None, |
| 350 | response_mime_type: str | None = None, |
| 351 | ) -> str: |
| 352 | del tools, response_mime_type |
| 353 | payload = { |
| 354 | "model": model, |
| 355 | "store": False, |
| 356 | "input": prompt, |
| 357 | "temperature": 0, |
| 358 | } |
| 359 | endpoint = resolve_endpoint("OPENAI_BASE_URL", OPENAI_RESPONSES_URL) |
| 360 | response = self._post( |
| 361 | endpoint, |
| 362 | payload, |
| 363 | headers={ |
| 364 | "Authorization": f"Bearer {self.token}", |
| 365 | "Content-Type": "application/json", |
| 366 | }, |
| 367 | timeout=90, |
| 368 | bypass_proxy=is_loopback_http_endpoint(endpoint), |
| 369 | ) |
| 370 | self._record_response_usage( |
| 371 | response, |
| 372 | metadata_key="usage", |
| 373 | prompt_key="input_tokens", |
| 374 | completion_key="output_tokens", |
| 375 | total_key="total_tokens", |
| 376 | ) |
| 377 | return extract_openai_text(response) |
| 378 | |
| 379 | |
| 380 | class XAIClient(ReasoningClient): |
| 381 | name = "xai" |
| 382 | |
| 383 | def __init__(self, api_key: str): |
| 384 | super().__init__() |
| 385 | self.api_key = api_key |
| 386 | |
| 387 | def generate_text( |
| 388 | self, |
| 389 | model: str, |
| 390 | prompt: str, |
| 391 | *, |
| 392 | tools: list[dict[str, Any]] | None = None, |
| 393 | response_mime_type: str | None = None, |
| 394 | ) -> str: |
| 395 | del tools, response_mime_type |
| 396 | payload = { |
| 397 | "model": model, |
| 398 | "input": [{"role": "user", "content": prompt}], |
| 399 | } |
| 400 | endpoint = resolve_endpoint("XAI_BASE_URL", XAI_RESPONSES_URL) |
| 401 | response = self._post( |
| 402 | endpoint, |
| 403 | payload, |
| 404 | headers={ |
| 405 | "Authorization": f"Bearer {self.api_key}", |
| 406 | "Content-Type": "application/json", |
| 407 | }, |
| 408 | timeout=90, |
| 409 | bypass_proxy=is_loopback_http_endpoint(endpoint), |
| 410 | ) |
| 411 | self._record_response_usage( |
| 412 | response, |
| 413 | metadata_key="usage", |
| 414 | prompt_key="input_tokens", |
| 415 | completion_key="output_tokens", |
| 416 | total_key="total_tokens", |
| 417 | prompt_fallback_key="prompt_tokens", |
| 418 | completion_fallback_key="completion_tokens", |
| 419 | ) |
| 420 | return extract_openai_text(response) |
| 421 | |
| 422 | |
| 423 | class OpenRouterClient(ReasoningClient): |
| 424 | name = "openrouter" |
| 425 | |
| 426 | def __init__(self, api_key: str): |
| 427 | super().__init__() |
| 428 | self.api_key = api_key |
| 429 | |
| 430 | def generate_text( |
| 431 | self, |
| 432 | model: str, |
| 433 | prompt: str, |
| 434 | *, |
| 435 | tools: list[dict[str, Any]] | None = None, |
| 436 | response_mime_type: str | None = None, |
| 437 | ) -> str: |
| 438 | del tools, response_mime_type |
| 439 | payload = { |
| 440 | "model": model, |
| 441 | "messages": [{"role": "user", "content": prompt}], |
| 442 | "temperature": 0, |
| 443 | } |
| 444 | endpoint = resolve_endpoint("OPENROUTER_BASE_URL", OPENROUTER_URL) |
| 445 | response = self._post( |
| 446 | endpoint, |
| 447 | payload, |
| 448 | headers={ |
| 449 | "Authorization": f"Bearer {self.api_key}", |
| 450 | "Content-Type": "application/json", |
| 451 | }, |
| 452 | timeout=90, |
| 453 | bypass_proxy=is_loopback_http_endpoint(endpoint), |
| 454 | ) |
| 455 | self._record_response_usage( |
| 456 | response, |
| 457 | metadata_key="usage", |
| 458 | prompt_key="prompt_tokens", |
| 459 | completion_key="completion_tokens", |
| 460 | total_key="total_tokens", |
| 461 | ) |
| 462 | return extract_openai_text(response) |
| 463 | |
| 464 | |
| 465 | _MODEL_DEFAULTS: dict[str, tuple[str, str]] = { |
| 466 | "gemini": (GEMINI_FLASH_LITE, GEMINI_FLASH_LITE), |
| 467 | "openai": (OPENAI_DEFAULT, OPENAI_DEFAULT), |
| 468 | "xai": (XAI_DEFAULT, XAI_DEFAULT), |
| 469 | "openrouter": (OPENROUTER_DEFAULT, OPENROUTER_DEFAULT), |
| 470 | } |
| 471 | |
| 472 | |
| 473 | def _resolve_model_pins(config: dict[str, Any], depth: str, provider_name: str) -> tuple[str, str, str]: |
| 474 | """Resolve planner, rerank, and grounding model pins for a provider.""" |
| 475 | default_planner, default_rerank = _MODEL_DEFAULTS.get(provider_name, (GEMINI_FLASH_LITE, GEMINI_FLASH_LITE)) |
| 476 | if depth == "deep" and provider_name == "gemini": |
| 477 | default_rerank = GEMINI_PRO |
| 478 | |
| 479 | planner_model = config.get("LAST30DAYS_PLANNER_MODEL") or default_planner |
| 480 | rerank_model = config.get("LAST30DAYS_RERANK_MODEL") or default_rerank |
| 481 | |
| 482 | if provider_name == "gemini": |
| 483 | if not _is_gemini_31_or_newer(planner_model): |
| 484 | _warn_stale_gemini_pin(planner_model, default_planner, role="planner") |
| 485 | planner_model = default_planner |
| 486 | if not _is_gemini_31_or_newer(rerank_model): |
| 487 | _warn_stale_gemini_pin(rerank_model, default_rerank, role="rerank") |
| 488 | rerank_model = default_rerank |
| 489 | |
| 490 | return planner_model, rerank_model |
| 491 | |
| 492 | |
| 493 | def mock_runtime(config: dict[str, Any], depth: str) -> schema.ProviderRuntime: |
| 494 | """Resolve model pins for mock mode without requiring live credentials.""" |
| 495 | provider_name = (config.get("LAST30DAYS_REASONING_PROVIDER") or "gemini").strip().lower() |
| 496 | if provider_name == "auto": |
| 497 | provider_name = "gemini" |
| 498 | if provider_name in {"local", "off", "none"}: |
| 499 | return schema.ProviderRuntime( |
| 500 | reasoning_provider="local", |
| 501 | planner_model="deterministic", |
| 502 | rerank_model="local-score", |
| 503 | x_search_backend=_resolve_x_backend(config), |
| 504 | ) |
| 505 | if provider_name not in _MODEL_DEFAULTS: |
| 506 | raise RuntimeError(f"Unsupported reasoning provider: {provider_name}") |
| 507 | |
| 508 | planner_model, rerank_model = _resolve_model_pins(config, depth, provider_name) |
| 509 | return schema.ProviderRuntime( |
| 510 | reasoning_provider=provider_name, |
| 511 | planner_model=planner_model, |
| 512 | rerank_model=rerank_model, |
| 513 | |
| 514 | x_search_backend=_resolve_x_backend(config), |
| 515 | ) |
| 516 | |
| 517 | |
| 518 | def resolve_runtime(config: dict[str, Any], depth: str) -> tuple[schema.ProviderRuntime, ReasoningClient | None]: |
| 519 | """Resolve the reasoning provider and pinned models.""" |
| 520 | provider_name = (config.get("LAST30DAYS_REASONING_PROVIDER") or "auto").strip().lower() |
| 521 | if provider_name in {"local", "off", "none"}: |
| 522 | return schema.ProviderRuntime( |
| 523 | reasoning_provider="local", |
| 524 | planner_model="deterministic", |
| 525 | rerank_model="local-score", |
| 526 | x_search_backend=_resolve_x_backend(config), |
| 527 | ), None |
| 528 | |
| 529 | google_key = config.get("GOOGLE_API_KEY") or config.get("GEMINI_API_KEY") or config.get("GOOGLE_GENAI_API_KEY") |
| 530 | openai_token = config.get("OPENAI_API_KEY") |
| 531 | xai_key = config.get("XAI_API_KEY") |
| 532 | |
| 533 | if provider_name == "auto": |
| 534 | # An xAI lane served by the API-key proxy ranks after every provider |
| 535 | # the user holds a key for. |
| 536 | xai_proxied = xai_key == proxy.SENTINEL |
| 537 | if google_key: |
| 538 | provider_name = "gemini" |
| 539 | elif openai_token and config.get("OPENAI_AUTH_STATUS") == env.AUTH_STATUS_OK: |
| 540 | provider_name = "openai" |
| 541 | elif xai_key and not xai_proxied: |
| 542 | provider_name = "xai" |
| 543 | elif config.get("OPENROUTER_API_KEY"): |
| 544 | provider_name = "openrouter" |
| 545 | elif xai_key: |
| 546 | provider_name = "xai" |
| 547 | else: |
| 548 | return schema.ProviderRuntime( |
| 549 | reasoning_provider="local", |
| 550 | planner_model="deterministic", |
| 551 | rerank_model="local-score", |
| 552 | x_search_backend=_resolve_x_backend(config), |
| 553 | ), None |
| 554 | |
| 555 | planner_model, rerank_model = _resolve_model_pins(config, depth, provider_name) |
| 556 | |
| 557 | if provider_name == "gemini": |
| 558 | if not google_key: |
| 559 | raise RuntimeError("Gemini selected but no Google API key is configured.") |
| 560 | runtime = schema.ProviderRuntime( |
| 561 | reasoning_provider="gemini", |
| 562 | planner_model=planner_model, |
| 563 | rerank_model=rerank_model, |
| 564 | |
| 565 | x_search_backend=_resolve_x_backend(config), |
| 566 | ) |
| 567 | return runtime, GeminiClient(google_key) |
| 568 | |
| 569 | if provider_name == "openai": |
| 570 | if not openai_token or config.get("OPENAI_AUTH_STATUS") != env.AUTH_STATUS_OK: |
| 571 | raise RuntimeError("OpenAI selected but no valid OpenAI auth is configured.") |
| 572 | runtime = schema.ProviderRuntime( |
| 573 | reasoning_provider="openai", |
| 574 | planner_model=planner_model, |
| 575 | rerank_model=rerank_model, |
| 576 | |
| 577 | x_search_backend=_resolve_x_backend(config), |
| 578 | ) |
| 579 | return runtime, OpenAIClient( |
| 580 | openai_token |
| 581 | ) |
| 582 | |
| 583 | if provider_name == "xai": |
| 584 | if not xai_key: |
| 585 | raise RuntimeError("xAI selected but XAI_API_KEY is not configured.") |
| 586 | runtime = schema.ProviderRuntime( |
| 587 | reasoning_provider="xai", |
| 588 | planner_model=planner_model, |
| 589 | rerank_model=rerank_model, |
| 590 | |
| 591 | x_search_backend=_resolve_x_backend(config), |
| 592 | ) |
| 593 | return runtime, XAIClient(xai_key) |
| 594 | |
| 595 | if provider_name == "openrouter": |
| 596 | openrouter_key = config.get("OPENROUTER_API_KEY") |
| 597 | if not openrouter_key: |
| 598 | raise RuntimeError("OpenRouter selected but OPENROUTER_API_KEY is not configured.") |
| 599 | runtime = schema.ProviderRuntime( |
| 600 | reasoning_provider="openrouter", |
| 601 | planner_model=planner_model, |
| 602 | rerank_model=rerank_model, |
| 603 | x_search_backend=_resolve_x_backend(config), |
| 604 | ) |
| 605 | return runtime, OpenRouterClient(openrouter_key) |
| 606 | |
| 607 | raise RuntimeError(f"Unsupported reasoning provider: {provider_name}") |
| 608 | |
| 609 | |
| 610 | def _resolve_x_backend(config: dict[str, Any]) -> str | None: |
| 611 | """Resolve the X backend for runtime fetch. |
| 612 | |
| 613 | Delegates to env.get_x_source which handles: |
| 614 | - Any known pin (X_BACKEND_KNOWN) exclusively: returns pin if available, None otherwise |
| 615 | - Unpinned: walks auto-chain (X_BACKEND_ORDER) only, never auto-selects opt-in backends |
| 616 | """ |
| 617 | return env.get_x_source(config) |
| 618 | |
| 619 | |
| 620 | def _validate_gemini_model_segment(model: str) -> str: |
| 621 | """Validate and percent-encode a Gemini model name used as a URL path segment.""" |
| 622 | if ( |
| 623 | not isinstance(model, str) |
| 624 | or not _GEMINI_MODEL_SEGMENT_RE.fullmatch(model) |
| 625 | or model in {".", ".."} |
| 626 | or ".." in model |
| 627 | ): |
| 628 | raise ValueError(f"Invalid Gemini model name: {model!r}") |
| 629 | return quote(model, safe="") |
| 630 | |
| 631 | |
| 632 | def _is_gemini_31_or_newer(model: str) -> bool: |
| 633 | if not isinstance(model, str) or ".." in model: |
| 634 | return False |
| 635 | match = _GEMINI_MODEL_RE.fullmatch(model) |
| 636 | if not match: |
| 637 | return False |
| 638 | return (int(match.group(1)), int(match.group(2) or 0)) >= (3, 1) |
| 639 | |
| 640 | |
| 641 | def _warn_stale_gemini_pin(model: str, default: str, *, role: str) -> None: |
| 642 | print( |
| 643 | f"[Providers] {role} model {model!r} is not Gemini 3.1 or newer; using {default}.", |
| 644 | file=sys.stderr, |
| 645 | ) |
| 646 | |
| 647 | |
| 648 | def extract_json(text: str) -> dict[str, Any]: |
| 649 | """Extract the first JSON object from a model response.""" |
| 650 | text = text.strip() |
| 651 | if not text: |
| 652 | raise ValueError("Expected JSON response, got empty text") |
| 653 | try: |
| 654 | value = json.loads(text) |
| 655 | except json.JSONDecodeError: |
| 656 | match = re.search(r"\{[\s\S]*\}", text) |
| 657 | if not match: |
| 658 | raise |
| 659 | value = json.loads(match.group(0)) |
| 660 | # Valid JSON is not always an object (Gemini's JSON mode allows a |
| 661 | # top-level array). Callers read it with .get(), so a list, null, or |
| 662 | # number must fail here, where their ValueError fallback catches it. |
| 663 | if not isinstance(value, dict): |
| 664 | raise ValueError(f"Expected a JSON object, got {type(value).__name__}") |
| 665 | return value |
| 666 | |
| 667 | |
| 668 | def extract_gemini_text(payload: dict[str, Any]) -> str: |
| 669 | if not isinstance(payload, dict): |
| 670 | return "" |
| 671 | candidates = payload.get("candidates") |
| 672 | if isinstance(candidates, list): |
| 673 | for candidate in candidates: |
| 674 | if not isinstance(candidate, dict): |
| 675 | continue |
| 676 | content = candidate.get("content") |
| 677 | if not isinstance(content, dict): |
| 678 | continue |
| 679 | parts = content.get("parts") |
| 680 | if not isinstance(parts, list): |
| 681 | continue |
| 682 | texts = [ |
| 683 | part["text"] |
| 684 | for part in parts |
| 685 | if isinstance(part, dict) |
| 686 | and part.get("thought") is not True |
| 687 | and isinstance(part.get("text"), str) |
| 688 | and part["text"] |
| 689 | ] |
| 690 | joined = "".join(texts) |
| 691 | if joined.strip(): |
| 692 | return joined |
| 693 | if payload: |
| 694 | print(f"[Providers] extract_gemini_text: no text in payload keys: {list(payload.keys())}", file=sys.stderr) |
| 695 | return "" |
| 696 | |
| 697 | |
| 698 | _OPENAI_REASONING_PART_TYPES = frozenset({"reasoning", "reasoning_text", "summary_text", "thinking"}) |
| 699 | _OPENAI_TEXT_PART_TYPES = frozenset({"output_text", "text"}) |
| 700 | |
| 701 | |
| 702 | def _extract_openai_content_parts(content: list[Any]) -> str: |
| 703 | """Extract joined non-reasoning text from a list of OpenAI/OpenRouter content parts.""" |
| 704 | preferred: list[str] = [] |
| 705 | fallback: list[str] = [] |
| 706 | for part in content: |
| 707 | if isinstance(part, str): |
| 708 | if part: |
| 709 | fallback.append(part) |
| 710 | continue |
| 711 | if not isinstance(part, dict): |
| 712 | continue |
| 713 | part_type = part.get("type") |
| 714 | if (isinstance(part_type, str) and part_type in _OPENAI_REASONING_PART_TYPES) or part.get("thought") is True: |
| 715 | continue |
| 716 | text = part.get("text") |
| 717 | if not isinstance(text, str) or not text: |
| 718 | continue |
| 719 | if isinstance(part_type, str) and part_type in _OPENAI_TEXT_PART_TYPES: |
| 720 | preferred.append(text) |
| 721 | else: |
| 722 | fallback.append(text) |
| 723 | preferred_joined = "".join(preferred) |
| 724 | if preferred_joined.strip(): |
| 725 | return preferred_joined |
| 726 | fallback_joined = "".join(fallback) |
| 727 | if fallback_joined.strip(): |
| 728 | return fallback_joined |
| 729 | return "" |
| 730 | |
| 731 | |
| 732 | def extract_openai_text(payload: dict[str, Any]) -> str: |
| 733 | if not isinstance(payload, dict): |
| 734 | return "" |
| 735 | output_text = payload.get("output_text") |
| 736 | if isinstance(output_text, str) and output_text.strip(): |
| 737 | return output_text |
| 738 | containers: list[Any] = [] |
| 739 | for key in ("output", "choices"): |
| 740 | seq = payload.get(key) |
| 741 | if isinstance(seq, list): |
| 742 | containers.extend(seq) |
| 743 | for item in containers: |
| 744 | if isinstance(item, str): |
| 745 | if item.strip(): |
| 746 | return item |
| 747 | continue |
| 748 | if not isinstance(item, dict): |
| 749 | continue |
| 750 | item_type = item.get("type") |
| 751 | if (isinstance(item_type, str) and item_type in _OPENAI_REASONING_PART_TYPES) or item.get("thought") is True: |
| 752 | continue |
| 753 | item_text = item.get("text") |
| 754 | if isinstance(item_text, str) and item_text.strip(): |
| 755 | return item_text |
| 756 | content = item.get("content") |
| 757 | if isinstance(content, str) and content.strip(): |
| 758 | return content |
| 759 | if isinstance(content, list): |
| 760 | extracted = _extract_openai_content_parts(content) |
| 761 | if extracted: |
| 762 | return extracted |
| 763 | message = item.get("message") |
| 764 | if isinstance(message, dict): |
| 765 | msg_content = message.get("content") |
| 766 | if isinstance(msg_content, str) and msg_content.strip(): |
| 767 | return msg_content |
| 768 | if isinstance(msg_content, list): |
| 769 | extracted = _extract_openai_content_parts(msg_content) |
| 770 | if extracted: |
| 771 | return extracted |
| 772 | if payload: |
| 773 | print(f"[Providers] extract_openai_text: no text in payload keys: {list(payload.keys())}", file=sys.stderr) |
| 774 | return "" |
| 775 |