diff --git a/deeptutor/services/llm/provider_core/codebuddy_model_probe.py b/deeptutor/services/llm/provider_core/codebuddy_model_probe.py new file mode 100644 index 000000000..a57163a09 --- /dev/null +++ b/deeptutor/services/llm/provider_core/codebuddy_model_probe.py @@ -0,0 +1,257 @@ +"""Filter the CodeBuddy catalog down to models the account can actually call. + +The cached product config is a *product* catalog, not an account catalog: it +lists every model the product knows about. Picking a model the account cannot +use fails at request time with ``11102 service info not found``. There is no +public "list my models" route, so the only reliable check is a real request. + +This module probes each candidate once with a one-token streaming request and +keeps only models that answer. It is deliberately conservative: a network +outage, an expired token, a rate limit or a 5xx is *not* evidence that a model +is missing, so those preserve the previous verdict instead of hiding anything. + +No Agent SDK and no CLI subprocess are required; ``httpx`` is already a +project dependency (see ``probe_account`` in ``codebuddy_credentials``). +""" + +from __future__ import annotations + +import asyncio +import json +import os +import time +from dataclasses import dataclass +from typing import Any, Iterable + +from deeptutor.services.codebuddy_credentials import ( + CodeBuddyCredentials, + cached_model_catalog, + load_credentials, +) + +NOT_PROVISIONED = "11102" +REASONING_PARAMS = "11150" + +OK_TTL_SECONDS = 6 * 3600 +MISSING_TTL_SECONDS = 7 * 24 * 3600 +TRANSIENT_TTL_SECONDS = 3600 +CACHE_TTL_SECONDS = 6 * 3600 + +DEFAULT_CONCURRENCY = 6 +DEFAULT_TIMEOUT = 6.0 +DEFAULT_BUDGET = 20.0 + +AVAILABLE = "available" +MISSING = "not-provisioned" +NEEDS_REASONING = "needs-reasoning" +TRANSIENT = "transient" +INCONCLUSIVE = "inconclusive" + +_ENV_SWITCH = "DEEPTUTOR_CODEBUDDY_PROBE_MODELS" + +# Keyed by (user id, candidate tuple). Only conclusive results are cached. +_CACHE: dict[tuple[str, tuple[str, ...]], tuple[float, list[str]]] = {} + + +@dataclass(frozen=True) +class Verdict: + status: str + business_code: str | None = None + at: float = 0.0 + + @property + def ttl(self) -> float: + if self.status == AVAILABLE: + return OK_TTL_SECONDS + if self.status == MISSING: + return MISSING_TTL_SECONDS + return TRANSIENT_TTL_SECONDS + + def expired(self, now: float | None = None) -> bool: + return (time.time() if now is None else now) - self.at >= self.ttl + + +def business_code(body: str) -> str | None: + """Extract the cloud business code from a JSON or SSE error body.""" + for line in body.splitlines(): + text = line.strip() + if text.startswith("data:"): + text = text[5:].strip() + if not text or text == "[DONE]": + continue + try: + payload = json.loads(text) + except (ValueError, TypeError): + continue + if not isinstance(payload, dict): + continue + for container in (payload, payload.get("error")): + if not isinstance(container, dict): + continue + for key in ("businessCode", "code", "errorCode"): + value = container.get(key) + if isinstance(value, (str, int)) and str(value): + return str(value) + return None + + +def classify(status_code: int | None, body: str = "") -> tuple[str, str | None]: + """Classify one probe. Pure, so tests never need a network.""" + code = business_code(body) + if code == NOT_PROVISIONED: + return MISSING, code + if code == REASONING_PARAMS: + return NEEDS_REASONING, code + if status_code is None: + return INCONCLUSIVE, code + if 200 <= status_code < 300 and code is None: + return AVAILABLE, code + if status_code in (401, 403, 408, 429) or status_code >= 500: + return INCONCLUSIVE, code + if code is None: + # An unrecognised 4xx says nothing about whether the model exists. + return INCONCLUSIVE, None + return TRANSIENT, code + + +def select_available( + candidates: Iterable[str], + verdicts: dict[str, Verdict], + previous: Iterable[str] | None = None, +) -> list[str]: + """Keep usable models; keep uncertain ones only when visible before.""" + prior = set(previous or ()) + result: list[str] = [] + for model in candidates: + verdict = verdicts.get(model) + if verdict is None: + if model in prior: + result.append(model) + continue + if verdict.status == AVAILABLE: + result.append(model) + elif verdict.status in (INCONCLUSIVE, TRANSIENT, NEEDS_REASONING) and model in prior: + result.append(model) + return result + + +async def _probe_one( + client: Any, + url: str, + headers: dict[str, str], + model: str, + reasoning_effort: str | None = None, +) -> tuple[str, str | None]: + payload: dict[str, Any] = { + "model": model, + "messages": [{"role": "user", "content": "hi"}], + "max_tokens": 1, + "stream": True, + } + if reasoning_effort: + payload["reasoning_effort"] = reasoning_effort + response = await client.post(url, headers=headers, json=payload) + return classify(response.status_code, response.text[:2000]) + + +async def probe_models( + credentials: CodeBuddyCredentials, + candidates: list[str], + *, + concurrency: int = DEFAULT_CONCURRENCY, + timeout: float = DEFAULT_TIMEOUT, + budget: float = DEFAULT_BUDGET, + client: Any | None = None, +) -> dict[str, Verdict]: + """Probe every candidate, bounded by ``budget`` seconds in total.""" + import httpx + + url = f"{credentials.api_base.rstrip('/')}/chat/completions" + headers = { + "Authorization": f"Bearer {credentials.access_token}", + "Content-Type": "application/json", + "Accept": "text/event-stream", + } + if credentials.user_id: + headers["X-User-Id"] = credentials.user_id + + async def run(active_client: Any) -> dict[str, Verdict]: + semaphore = asyncio.Semaphore(max(1, concurrency)) + now = time.time() + + async def one(model: str) -> tuple[str, Verdict]: + async with semaphore: + try: + status, code = await _probe_one(active_client, url, headers, model) + if status == NEEDS_REASONING: + # Reasoning models reject a bare request but work with + # an explicit effort. They are not missing models. + retry, retry_code = await _probe_one( + active_client, url, headers, model, reasoning_effort="medium" + ) + if retry == AVAILABLE: + status, code = retry, retry_code + return model, Verdict(status, code, now) + except Exception: # noqa: BLE001 - network/auth noise is inconclusive + return model, Verdict(INCONCLUSIVE, at=now) + + tasks = [asyncio.create_task(one(model)) for model in candidates] + done, pending = await asyncio.wait(tasks, timeout=budget) + for task in pending: + task.cancel() + return dict(task.result() for task in done if not task.cancelled() and not task.exception()) + + if client is not None: + return await run(client) + async with httpx.AsyncClient(timeout=timeout) as owned: + return await run(owned) + + +async def available_codebuddy_models( + api_key: str | None = None, + candidates: list[str] | None = None, +) -> list[str] | None: + """Return the usable subset, or ``None`` when the verdict is not reliable. + + ``None`` tells the caller to keep the catalog unchanged. That happens when + nobody is signed in, the switch is off, or every probe was inconclusive + (offline launch, expired token, cloud incident). + """ + if os.environ.get(_ENV_SWITCH, "1").strip().lower() in {"0", "false", "no", "off"}: + return None + credentials = load_credentials() + if credentials is None or not credentials.access_token: + return None + + pool = list(candidates) if candidates is not None else cached_model_catalog() + if not pool: + return None + + uid = credentials.user_id or credentials.domain or "default" + key = (uid, tuple(pool)) + hit = _CACHE.get(key) + if hit and time.time() - hit[0] < CACHE_TTL_SECONDS: + return list(hit[1]) + + verdicts = await probe_models(credentials, pool) + if not verdicts or all(v.status == INCONCLUSIVE for v in verdicts.values()): + return None + + result = select_available(pool, verdicts, previous=pool) + _CACHE[key] = (time.time(), result) + return result + + +__all__ = [ + "AVAILABLE", + "INCONCLUSIVE", + "MISSING", + "NEEDS_REASONING", + "TRANSIENT", + "Verdict", + "available_codebuddy_models", + "business_code", + "classify", + "probe_models", + "select_available", +] diff --git a/deeptutor/services/llm/provider_core/codebuddy_models.py b/deeptutor/services/llm/provider_core/codebuddy_models.py index 78fd1cebb..2af1190ae 100644 --- a/deeptutor/services/llm/provider_core/codebuddy_models.py +++ b/deeptutor/services/llm/provider_core/codebuddy_models.py @@ -3,6 +3,12 @@ The cloud has no public model-list route, so the catalog comes from the config the CodeBuddy CLI caches on disk. The CLI subprocess probe is only used as a fallback, and ``default`` resolves on every deployment. + +The cached product config lists every model the *product* knows about, which is +not necessarily what the signed-in account can call. A runtime availability +probe narrows that list to models which actually answer; see +``codebuddy_model_probe``. When the probe cannot reach a reliable verdict the +catalog is returned untouched. """ from __future__ import annotations @@ -10,12 +16,16 @@ from __future__ import annotations import importlib.util from deeptutor.services.codebuddy_credentials import FALLBACK_MODEL_CATALOG, cached_model_catalog +from deeptutor.services.llm.provider_core.codebuddy_model_probe import available_codebuddy_models async def fetch_codebuddy_models(api_key: str | None = None) -> list[str]: """Return the model ids available to the signed-in CodeBuddy account.""" cached = cached_model_catalog() if cached: + probed = await available_codebuddy_models(api_key, candidates=cached) + if probed is not None: + return probed return cached if importlib.util.find_spec("codebuddy_agent_sdk") is not None: diff --git a/docs-for-dev/codebuddy-model-probe.md b/docs-for-dev/codebuddy-model-probe.md new file mode 100644 index 000000000..233b1502b --- /dev/null +++ b/docs-for-dev/codebuddy-model-probe.md @@ -0,0 +1,46 @@ +# CodeBuddy model availability probe + +The CodeBuddy product config cached in `~/.codebuddy/local_storage/` is a +**product** catalog. It lists models the product knows about, not the ones the +signed-in account can call. Choosing a model that is not provisioned for the +account fails at request time with `11102 service info not found`. + +`deeptutor/services/llm/provider_core/codebuddy_model_probe.py` filters that +list before it reaches the Settings model dropdown: + +1. `fetch_codebuddy_models()` reads the cached product config as before. +2. Each candidate gets one minimal streaming completion (`max_tokens: 1`) under + the shared CodeBuddy OAuth session. Requests are bounded by concurrency 6, + a 6 s per-request timeout and a 20 s total budget. +3. Only models that answer are returned. `11102` means the account cannot call + the model, so it is hidden. `11150` means a reasoning model rejected the bare + request, so it is retried once with `reasoning_effort: "medium"` instead of + being hidden. +4. Results are memoised per account for 6 hours; a repeat sync makes no network + calls. + +## Failure policy + +An outage, an expired token, a rate limit or a 5xx is **not** evidence that a +model is missing. Those probes are inconclusive and the caller keeps the +catalog unchanged, so an offline launch never empties the model list. If every +probe is inconclusive, `available_codebuddy_models()` returns `None` and +`fetch_codebuddy_models()` falls back to the unfiltered cache. + +Set `DEEPTUTOR_CODEBUDDY_PROBE_MODELS=0` to disable probing (the previous +behaviour). No Agent SDK and no `codebuddy` CLI subprocess are needed; the +probe uses `httpx`, already a project dependency. + +## Evidence + +Measured on a macOS desktop build against an education-edition account with +43 cached candidates: 27 answered `200`, 15 returned `11102`, 1 returned +`11134` (temporarily unavailable). The Settings endpoint returned exactly the +27 usable models, with no `11102` entries. Cold start added ~5 s on the first +launch and 0 s on cached launches. + +Run the unit tests with: + +```bash +pytest tests/services/llm/test_codebuddy_model_probe.py -q +``` diff --git a/tests/services/llm/test_codebuddy_model_probe.py b/tests/services/llm/test_codebuddy_model_probe.py new file mode 100644 index 000000000..75b39773f --- /dev/null +++ b/tests/services/llm/test_codebuddy_model_probe.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import pytest + +from deeptutor.services.llm.provider_core.codebuddy_model_probe import ( + AVAILABLE, + INCONCLUSIVE, + MISSING, + NEEDS_REASONING, + TRANSIENT, + Verdict, + business_code, + classify, + select_available, +) + + +def test_business_code_from_json_and_sse(): + assert business_code('{"code": 11102, "message": "service info not found"}') == "11102" + assert business_code('data: {"businessCode":"11150"}\n\ndata: [DONE]') == "11150" + assert business_code('data: {"choices":[{"delta":{"content":"hi"}}]}') is None + assert business_code("") is None + + +def test_classify_provisioning_errors(): + assert classify(200, 'data: {"code":"11102"}')[0] == MISSING + assert classify(400, '{"error":{"code":"11102"}}')[0] == MISSING + assert classify(400, '{"error":{"code":"11150"}}')[0] == NEEDS_REASONING + assert classify(200, 'data: {"choices":[]}')[0] == AVAILABLE + + +def test_auth_and_network_noise_is_inconclusive(): + assert classify(None)[0] == INCONCLUSIVE + assert classify(401)[0] == INCONCLUSIVE + assert classify(429)[0] == INCONCLUSIVE + assert classify(503)[0] == INCONCLUSIVE + assert classify(400, "unreadable body")[0] == INCONCLUSIVE + assert classify(400, '{"code":"11134"}')[0] == TRANSIENT + + +def test_select_available_drops_only_missing_models(): + candidates = ["hunyuan-chat", "not-provisioned", "reasoning", "offline"] + verdicts = { + "hunyuan-chat": Verdict(AVAILABLE, at=0), + "not-provisioned": Verdict(MISSING, "11102", at=0), + "reasoning": Verdict(NEEDS_REASONING, "11150", at=0), + "offline": Verdict(INCONCLUSIVE, at=0), + } + assert select_available(candidates, verdicts, previous=candidates) == [ + "hunyuan-chat", + "reasoning", + "offline", + ] + assert select_available(candidates, verdicts) == ["hunyuan-chat"] + assert select_available(candidates, {}, previous=candidates) == candidates + + +def test_verdict_ttl_and_expiry(): + assert Verdict(AVAILABLE, at=100).ttl == 6 * 3600 + assert Verdict(MISSING, "11102", at=100).ttl == 7 * 24 * 3600 + assert Verdict(INCONCLUSIVE, at=100).ttl == 3600 + assert Verdict(AVAILABLE, at=100).expired(now=100 + 6 * 3600) + assert not Verdict(AVAILABLE, at=100).expired(now=101) + + +@pytest.mark.asyncio +async def test_available_codebuddy_models_without_login_keeps_catalog(monkeypatch): + from deeptutor.services.llm.provider_core import codebuddy_model_probe + + monkeypatch.setattr(codebuddy_model_probe, "load_credentials", lambda: None) + assert await codebuddy_model_probe.available_codebuddy_models(candidates=["a"]) is None + + +@pytest.mark.asyncio +async def test_available_codebuddy_models_can_be_switched_off(monkeypatch): + from deeptutor.services.llm.provider_core import codebuddy_model_probe + + monkeypatch.setenv("DEEPTUTOR_CODEBUDDY_PROBE_MODELS", "0") + assert await codebuddy_model_probe.available_codebuddy_models(candidates=["a"]) is None