MCPcopy Create free account
hub / github.com/CommonstackAI/UncommonRoute / ModelMapper

Class ModelMapper

uncommon_route/model_map.py:327–713  ·  view source on GitHub ↗

Discovers upstream models and provides a dynamic pool with pricing, capabilities, and name resolution. After ``discover()`` runs, the mapper knows every model the upstream serves and can provide live pricing and inferred capabilities for each. Static config (``DEFAULT_MODEL_PRICING`

Source from the content-addressed store, hash-verified

325
326@dataclass
327class ModelMapper:
328 """Discovers upstream models and provides a dynamic pool with pricing,
329 capabilities, and name resolution.
330
331 After ``discover()`` runs, the mapper knows every model the upstream
332 serves and can provide live pricing and inferred capabilities for each.
333 Static config (``DEFAULT_MODEL_PRICING``, etc.) is only used as a
334 fallback when discovery has not yet run.
335 """
336
337 upstream_url: str
338 provider: str = ""
339 is_gateway: bool = False
340
341 _upstream_models: set[str] = field(default_factory=set, repr=False)
342 _map: dict[str, str] = field(default_factory=dict, repr=False)
343 _discovered: bool = False
344
345 _pool: dict[str, DiscoveredModel] = field(default_factory=dict, repr=False)
346 _learned_aliases: dict[str, str] = field(default_factory=dict, repr=False)
347 _last_discovery_time: float = 0.0
348
349 def __post_init__(self) -> None:
350 self.provider, self.is_gateway = detect_provider(self.upstream_url)
351 self._load_learned_aliases()
352
353 # ---- discovery --------------------------------------------------------
354
355 async def discover(self, api_key: str | None = None) -> int:
356 """Fetch ``/v1/models`` from upstream and build the model pool.
357
358 Extracts pricing and infers capabilities from upstream data.
359 Returns the number of models discovered (0 on failure).
360 """
361 if not self.upstream_url:
362 return 0
363
364 models_url = f"{self.upstream_url.rstrip('/')}/models"
365 headers: dict[str, str] = {"user-agent": "uncommon-route/model-discovery"}
366 if api_key:
367 headers["authorization"] = f"Bearer {api_key}"
368
369 try:
370 async with httpx.AsyncClient(
371 timeout=httpx.Timeout(10.0, connect=5.0),
372 ) as client:
373 resp = await client.get(models_url, headers=headers)
374 if resp.status_code != 200:
375 logger.warning(
376 "Model discovery: HTTP %d from %s", resp.status_code, models_url,
377 )
378 return 0
379 data = resp.json()
380 raw = data.get("data", [])
381
382 self._pool.clear()
383 self._upstream_models.clear()
384

Calls

no outgoing calls