Spaces:
Running
Running
Speed up NIM provider with failure tracking and faster timeouts
Browse files- Add ModelHealthTracker for per-model failure tracking (30s TTL)
- Faster timeouts: connect=10s, first_chunk=30s, fallback=20s
- Auto model pre-checks health before attempting requests
- Record failures on timeout/rate-limit for smart fallback
- Skip unhealthy models in both router and services
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Files changed (15)
- .claude/settings.local.json+5-1
- api/__pycache__/detection.cpython-314.pyc
- api/__pycache__/model_router.cpython-314.pyc
- api/__pycache__/optimization_handlers.cpython-314.pyc
- api/__pycache__/routes.cpython-314.pyc
- api/__pycache__/runtime.cpython-314.pyc
- api/__pycache__/services.cpython-314.pyc
- api/model_router.py+8-2
- api/services.py+14-2
- core/__pycache__/session_tracker.cpython-314.pyc
- providers/__pycache__/openai_compat.cpython-314.pyc
- providers/__pycache__/rate_limit.cpython-314.pyc
- providers/nvidia_nim/__pycache__/client.cpython-314.pyc
- providers/nvidia_nim/client.py+4-4
- providers/rate_limit.py+79
9 unmodified lines101112131415169 unmodified lines"Bash(git push *)","Bash(python -c \"import ast; ast.parse\\(open\\('api/services.py'\\).read\\(\\)\\); print\\('Syntax OK'\\)\")","mcp__github__list_issues","mcp__github__update_issue"]},"enableAllProjectMcpServers": true,9 unmodified lines10111213141516171819209 unmodified lines"Bash(git push *)","Bash(python -c \"import ast; ast.parse\\(open\\('api/services.py'\\).read\\(\\)\\); print\\('Syntax OK'\\)\")","mcp__github__list_issues","mcp__github__update_issue","Bash(git commit *)","Bash(dir \"C:\\\\Users\\\\yashw\\\\.gemini\\\\antigravity\\\\llm_wiki_v2\\\\wiki\\\\entities\")","Bash(dir *)","Bash(node -e ' *)"]},"enableAllProjectMcpServers": true,
195 unmodified lines196197198199200201202203204205206195 unmodified linesif provider_id == "zen":is_blocked = Falseif is_blocked:logger.debug("Routing: candidate '{}' (from {}) is BLOCKED",normalized_ref,source,)blocked_candidates.append(resolved)else:195 unmodified lines196197198199200201202203204205206207208209210211212195 unmodified linesif provider_id == "zen":is_blocked = False# Check model health (recent failures)is_healthy = limiter.is_healthy(normalized_ref)if is_blocked or not is_healthy:reason = "BLOCKED" if is_blocked else "UNHEALTHY"logger.debug("Routing: candidate '{}' (from {}) is {} (health={})",normalized_ref,source,reason,is_healthy,)blocked_candidates.append(resolved)else:
243 unmodified lines24424524624724824925025125225325425525625725825926026140 unmodified lines3023033043053063073 unmodified lines31131231331431531617 unmodified lines334335336337338339243 unmodified linesfor i, resolved in enumerate(candidates):try:# Pre-check: skip candidates that are currently rate limitedfrom providers.rate_limit import GlobalRateLimiterlimiter = GlobalRateLimiter.get_scoped_instance(resolved.provider_id)if limiter.is_blocked() and resolved.provider_id != "zen":logger.warning("Provider '{} is currently rate limited, skipping to next candidate...",resolved.provider_id,)last_exc = Exception("Rate limited")continueprovider = self._provider_getter(resolved.provider_id)routed_request = request_data.model_copy(deep=True)routed_request.model = resolved.provider_model40 unmodified linesresolved.provider_id,e.status_code,)last_exc = econtinueexcept TimeoutError as e:3 unmodified linesresolved.provider_id,type(e).__name__,)last_exc = econtinueexcept Exception as e:17 unmodified linestype(e).__name__,e,)last_exc = econtinue243 unmodified lines24424524624724824925025125225325425525625725825926026126226326426526626726826927040 unmodified lines3113123133143153163173 unmodified lines32132232332432532632717 unmodified lines345346347348349350351243 unmodified linesfor i, resolved in enumerate(candidates):try:# Pre-check: skip candidates that are currently rate limited or unhealthyfrom providers.rate_limit import GlobalRateLimiterlimiter = GlobalRateLimiter.get_scoped_instance(resolved.provider_id)if limiter.is_blocked() and resolved.provider_id != "zen":logger.warning("Provider '{}' is currently rate limited, skipping to next candidate...",resolved.provider_id,)last_exc = Exception("Rate limited")continue# Check model health (recent failures)if not limiter.is_healthy(resolved.provider_model_ref):logger.warning("Provider '{}' has recent failures, skipping to next candidate...",resolved.provider_model_ref,)last_exc = Exception("Recent failures")continueprovider = self._provider_getter(resolved.provider_id)routed_request = request_data.model_copy(deep=True)routed_request.model = resolved.provider_model40 unmodified linesresolved.provider_id,e.status_code,)limiter.record_failure(resolved.provider_model_ref)last_exc = econtinueexcept TimeoutError as e:3 unmodified linesresolved.provider_id,type(e).__name__,)limiter.record_failure(resolved.provider_model_ref)last_exc = econtinueexcept Exception as e:17 unmodified linestype(e).__name__,e,)limiter.record_failure(resolved.provider_model_ref)last_exc = econtinue
107 unmodified lines108109110111112113114115116117107 unmodified lines"""from config.settings import get_settings# Reduced timeouts for faster fallback detectionconnect_timeout_s = 15 # Reduced from 30first_chunk_timeout_s = 45 # Reduced from 60fallback_first_chunk_timeout_s = 30 # Reduced from 60 - faster fallbacktry:client = self._client_for_body(body)107 unmodified lines108109110111112113114115116117107 unmodified lines"""from config.settings import get_settings# Faster timeouts for quick failover detectionconnect_timeout_s = 10 # Reduced from 15first_chunk_timeout_s = 30 # Reduced from 45fallback_first_chunk_timeout_s = 20 # Reduced from 30try:client = self._client_for_body(body)
15 unmodified lines161718192021159 unmodified lines18118218318418518615 unmodified linesT = TypeVar("T")class GlobalRateLimiter:"""Global singleton rate limiter that blocks all requests159 unmodified lines"""Get remaining reactive wait time in seconds."""return max(0.0, self._blocked_until - time.monotonic())@asynccontextmanagerasync def concurrency_slot(self) -> AsyncIterator[None]:"""Async context manager that holds one concurrency slot for a stream.15 unmodified lines161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475159 unmodified lines23523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426515 unmodified linesT = TypeVar("T")class ModelHealthTracker:"""Track per-model health based on recent failures."""_instance: ClassVar["ModelHealthTracker | None"] = Nonedef __init__(self, failure_ttl: float = 30.0, max_failures: int = 3) -> None:self._failure_ttl = failure_ttlself._max_failures = max_failuresself._failures: dict[str, list[float]] = {}@classmethoddef get_instance(cls) -> "ModelHealthTracker":if cls._instance is None:cls._instance = cls()return cls._instancedef record_failure(self, model_ref: str) -> None:"""Record a failure timestamp for a model."""now = time.monotonic()if model_ref not in self._failures:self._failures[model_ref] = []self._failures[model_ref].append(now)logger.debug("HEALTH: recorded failure for '{}'", model_ref)def is_healthy(self, model_ref: str) -> bool:"""Check if model has had fewer than max_failures in the TTL window."""if model_ref not in self._failures:return Truecutoff = time.monotonic() - self._failure_ttlrecent = [t for t in self._failures[model_ref] if t > cutoff]self._failures[model_ref] = recenthealthy = len(recent) < self._max_failuresif not healthy:logger.debug("HEALTH: model '{}' is unhealthy ({} failures in {}s)",model_ref,len(recent),self._failure_ttl,)return healthydef get_failure_count(self, model_ref: str) -> int:"""Get number of recent failures for a model."""if model_ref not in self._failures:return 0cutoff = time.monotonic() - self._failure_ttlreturn len([t for t in self._failures[model_ref] if t > cutoff])def clear_failures(self, model_ref: str) -> None:"""Clear failure history for a model (on success)."""if model_ref in self._failures:self._failures.pop(model_ref)class GlobalRateLimiter:"""Global singleton rate limiter that blocks all requests159 unmodified lines"""Get remaining reactive wait time in seconds."""return max(0.0, self._blocked_until - time.monotonic())def record_failure(self, model_ref: str | None = None) -> None:"""Record a failure for rate limit tracking.Args:model_ref: Optional model identifier for health tracking."""# Record in the shared health tracker if model providedif model_ref:health = ModelHealthTracker.get_instance()health.record_failure(model_ref)def is_healthy(self, model_ref: str | None = None) -> bool:"""Check if provider/model is healthy based on failure history.Args:model_ref: Optional model identifier for health tracking.Returns:True if no recent failures or model_ref is None."""if model_ref is None:return Truehealth = ModelHealthTracker.get_instance()return health.is_healthy(model_ref)@asynccontextmanagerasync def concurrency_slot(self) -> AsyncIterator[None]:"""Async context manager that holds one concurrency slot for a stream.
.claude/settings.local.json+5-1
api/__pycache__/detection.cpython-314.pyc
api/__pycache__/model_router.cpython-314.pyc
api/__pycache__/optimization_handlers.cpython-314.pyc
api/__pycache__/routes.cpython-314.pyc
api/__pycache__/runtime.cpython-314.pyc
api/__pycache__/services.cpython-314.pyc
api/model_router.py+8-2
api/services.py+14-2
core/__pycache__/session_tracker.cpython-314.pyc
providers/__pycache__/openai_compat.cpython-314.pyc
providers/__pycache__/rate_limit.cpython-314.pyc
providers/nvidia_nim/__pycache__/client.cpython-314.pyc
providers/nvidia_nim/client.py+4-4
providers/rate_limit.py+79