diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 3f4f543b7..123ea35f6 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -136,7 +136,7 @@ jobs: - name: Run unit tests run: | echo "🧪 Running tests with Python ${{ matrix.python-version }}" - pytest tests/ -v --tb=short --ignore=tests/agents/ || echo "⚠️ Some tests failed or no tests found" + pytest tests/ -v --tb=short env: PYTHONPATH: ${{ github.workspace }} diff --git a/pyproject.toml b/pyproject.toml index ed5841113..bd309d4e2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -68,6 +68,10 @@ select = [ # 其他规则都忽略,不强制要求 ] +extend-select = [ + "B006", # Do not use mutable data structures for argument defaults +] + # Ignore specific rules (放宽检查,只保留重要规则) ignore = [ "E501", # Line too long (handled by formatter) @@ -85,7 +89,6 @@ ignore = [ "PTH123", # open() should be replaced by Path.open() (允许使用 open) "PTH103", # os.makedirs() should be replaced by Path.mkdir() (允许使用 os.makedirs) "PTH118", # os.path.join() should be replaced by Path (允许使用 os.path.join) - "B904", # Within except clause, raise exceptions with raise ... from err "EM101", # Exception must not use a string literal "EM102", # Exception must not use an f-string literal "TRY002", # Create your own exception @@ -95,7 +98,6 @@ ignore = [ "PLW2901", # for loop variable overwritten by assignment target "F841", # Local variable assigned but never used "ERA001", # Found commented-out code (允许注释代码) - "B006", # Do not use mutable data structures for argument defaults ] # Exclude patterns diff --git a/src/services/llm/capabilities.py b/src/services/llm/capabilities.py index 035dc4b5b..0bdb0d497 100644 --- a/src/services/llm/capabilities.py +++ b/src/services/llm/capabilities.py @@ -18,11 +18,9 @@ Usage: # use streaming """ -from typing import Any, Optional - # Provider capabilities configuration # Keys are binding names (lowercase), values are capability dictionaries -PROVIDER_CAPABILITIES: dict[str, dict[str, Any]] = { +PROVIDER_CAPABILITIES: dict[str, dict[str, object]] = { # OpenAI and OpenAI-compatible providers "openai": { "supports_response_format": True, @@ -124,7 +122,7 @@ PROVIDER_CAPABILITIES: dict[str, dict[str, Any]] = { } # Default capabilities for unknown providers (assume OpenAI-compatible) -DEFAULT_CAPABILITIES: dict[str, Any] = { +DEFAULT_CAPABILITIES: dict[str, object] = { "supports_response_format": True, "supports_streaming": True, "supports_tools": False, @@ -136,7 +134,7 @@ DEFAULT_CAPABILITIES: dict[str, Any] = { # Model-specific overrides # Format: {model_pattern: {capability: value}} # Patterns are matched with case-insensitive startswith -MODEL_OVERRIDES: dict[str, dict[str, Any]] = { +MODEL_OVERRIDES: dict[str, dict[str, object]] = { "deepseek": { "supports_response_format": False, "has_thinking_tags": True, @@ -180,9 +178,9 @@ MODEL_OVERRIDES: dict[str, dict[str, Any]] = { def get_capability( binding: str, capability: str, - model: Optional[str] = None, - default: Any = None, -) -> Any: + model: str | None = None, + default: object = None, +) -> object: """ Get a capability value for a provider/model combination. @@ -225,7 +223,7 @@ def get_capability( return default -def supports_response_format(binding: str, model: Optional[str] = None) -> bool: +def supports_response_format(binding: str, model: str | None = None) -> bool: """ Check if the provider/model supports response_format parameter. @@ -238,10 +236,11 @@ def supports_response_format(binding: str, model: Optional[str] = None) -> bool: Returns: True if response_format is supported """ - return get_capability(binding, "supports_response_format", model, default=True) + value = get_capability(binding, "supports_response_format", model, default=True) + return bool(value) -def supports_streaming(binding: str, model: Optional[str] = None) -> bool: +def supports_streaming(binding: str, model: str | None = None) -> bool: """ Check if the provider/model supports streaming responses. @@ -252,10 +251,11 @@ def supports_streaming(binding: str, model: Optional[str] = None) -> bool: Returns: True if streaming is supported """ - return get_capability(binding, "supports_streaming", model, default=True) + value = get_capability(binding, "supports_streaming", model, default=True) + return bool(value) -def system_in_messages(binding: str, model: Optional[str] = None) -> bool: +def system_in_messages(binding: str, model: str | None = None) -> bool: """ Check if system prompt should be in messages array (OpenAI style) or as a separate parameter (Anthropic style). @@ -267,10 +267,11 @@ def system_in_messages(binding: str, model: Optional[str] = None) -> bool: Returns: True if system prompt goes in messages array """ - return get_capability(binding, "system_in_messages", model, default=True) + value = get_capability(binding, "system_in_messages", model, default=True) + return bool(value) -def has_thinking_tags(binding: str, model: Optional[str] = None) -> bool: +def has_thinking_tags(binding: str, model: str | None = None) -> bool: """ Check if the model output may contain thinking tags (...). @@ -281,10 +282,11 @@ def has_thinking_tags(binding: str, model: Optional[str] = None) -> bool: Returns: True if thinking tags should be filtered """ - return get_capability(binding, "has_thinking_tags", model, default=False) + value = get_capability(binding, "has_thinking_tags", model, default=False) + return bool(value) -def supports_tools(binding: str, model: Optional[str] = None) -> bool: +def supports_tools(binding: str, model: str | None = None) -> bool: """ Check if the provider/model supports function calling / tools. @@ -295,10 +297,11 @@ def supports_tools(binding: str, model: Optional[str] = None) -> bool: Returns: True if tools/function calling is supported """ - return get_capability(binding, "supports_tools", model, default=False) + value = get_capability(binding, "supports_tools", model, default=False) + return bool(value) -def requires_api_version(binding: str, model: Optional[str] = None) -> bool: +def requires_api_version(binding: str, model: str | None = None) -> bool: """ Check if the provider requires an API version parameter (e.g., Azure OpenAI). @@ -309,12 +312,13 @@ def requires_api_version(binding: str, model: Optional[str] = None) -> bool: Returns: True if api_version is required """ - return get_capability(binding, "requires_api_version", model, default=False) + value = get_capability(binding, "requires_api_version", model, default=False) + return bool(value) def get_effective_temperature( binding: str, - model: Optional[str] = None, + model: str | None = None, requested_temp: float = 0.7, ) -> float: """ @@ -332,8 +336,8 @@ def get_effective_temperature( The effective temperature to use for the API call """ forced_temp = get_capability(binding, "forced_temperature", model) - if forced_temp is not None: - return forced_temp + if isinstance(forced_temp, (int, float)): + return float(forced_temp) return requested_temp diff --git a/src/services/llm/client.py b/src/services/llm/client.py index 472685b1e..60b529dfa 100644 --- a/src/services/llm/client.py +++ b/src/services/llm/client.py @@ -9,7 +9,8 @@ Note: This is a legacy interface. Prefer using the factory functions directly: from src.services.llm import complete, stream """ -from typing import Any, Dict, List, Optional +from collections.abc import Awaitable, Callable +from typing import cast from src.logging import get_logger @@ -25,7 +26,7 @@ class LLMClient: Prefer using factory functions (complete, stream) directly for new code. """ - def __init__(self, config: Optional[LLMConfig] = None): + def __init__(self, config: LLMConfig | None = None) -> None: """ Initialize LLM client. @@ -42,7 +43,7 @@ class LLMClient: # We must set these env vars early to ensure all LightRAG operations work. self._setup_openai_env_vars() - def _setup_openai_env_vars(self): + def _setup_openai_env_vars(self) -> None: """ Set OpenAI environment variables for LightRAG compatibility. @@ -62,14 +63,14 @@ class LLMClient: if self.config.base_url: os.environ["OPENAI_BASE_URL"] = self.config.base_url - self.logger.debug(f"Set OPENAI_BASE_URL env var to {self.config.base_url}") + self.logger.debug("Set OPENAI_BASE_URL env var to %s" % self.config.base_url) async def complete( self, prompt: str, - system_prompt: Optional[str] = None, - history: Optional[List[Dict[str, str]]] = None, - **kwargs: Any, + system_prompt: str | None = None, + history: list[dict[str, str]] | None = None, + **kwargs: object, ) -> str: """ Call LLM completion via Factory. @@ -85,8 +86,9 @@ class LLMClient: """ from . import factory - # Delegate to factory for unified routing and retry handling - return await factory.complete( + factory_complete = cast(Callable[..., Awaitable[str]], factory.complete) + messages = history or None + return await factory_complete( prompt=prompt, system_prompt=system_prompt or "You are a helpful assistant.", model=self.config.model, @@ -94,15 +96,16 @@ class LLMClient: base_url=self.config.base_url, api_version=getattr(self.config, "api_version", None), binding=getattr(self.config, "binding", "openai"), + messages=messages, **kwargs, ) def complete_sync( self, prompt: str, - system_prompt: Optional[str] = None, - history: Optional[List[Dict[str, str]]] = None, - **kwargs: Any, + system_prompt: str | None = None, + history: list[dict[str, str]] | None = None, + **kwargs: object, ) -> str: """ Synchronous wrapper for complete(). @@ -122,7 +125,7 @@ class LLMClient: "Use `await llm.complete(...)` instead." ) - def get_model_func(self): + def get_model_func(self) -> Callable[..., object]: """ Get a function compatible with LightRAG's llm_model_func parameter. @@ -140,11 +143,12 @@ class LLMClient: def llm_model_func_via_factory( prompt: str, - system_prompt: Optional[str] = None, - history_messages: Optional[List[Dict]] = None, - **kwargs: Any, - ): - return factory.complete( + system_prompt: str | None = None, + history_messages: list[dict[str, object]] | None = None, + **kwargs: object, + ) -> object: + factory_complete = cast(Callable[..., object], factory.complete) + return factory_complete( prompt=prompt, system_prompt=system_prompt or "You are a helpful assistant.", model=self.config.model, @@ -163,12 +167,12 @@ class LLMClient: def llm_model_func( prompt: str, - system_prompt: Optional[str] = None, - history_messages: Optional[List[Dict]] = None, - **kwargs: Any, - ): + system_prompt: str | None = None, + history_messages: list[dict[str, object]] | None = None, + **kwargs: object, + ) -> object: # Only pass api_version if set (for Azure OpenAI) - lightrag_kwargs = { + lightrag_kwargs: dict[str, object] = { "system_prompt": system_prompt, "history_messages": history_messages or [], "api_key": self.config.api_key, @@ -178,15 +182,11 @@ class LLMClient: api_version = getattr(self.config, "api_version", None) if api_version: lightrag_kwargs["api_version"] = api_version - return openai_complete_if_cache( - self.config.model, - prompt, - **lightrag_kwargs, - ) + return openai_complete_if_cache(self.config.model, prompt, **lightrag_kwargs) return llm_model_func - def get_vision_model_func(self): + def get_vision_model_func(self) -> Callable[..., object]: """ Get a function compatible with RAG-Anything's vision_model_func parameter. @@ -204,14 +204,15 @@ class LLMClient: def vision_model_func_via_factory( prompt: str, - system_prompt: Optional[str] = None, - history_messages: Optional[List[Dict]] = None, - image_data: Optional[str] = None, - messages: Optional[List[Dict]] = None, - **kwargs: Any, - ): + system_prompt: str | None = None, + history_messages: list[dict[str, object]] | None = None, + image_data: str | None = None, + messages: list[dict[str, object]] | None = None, + **kwargs: object, + ) -> object: # Use factory for unified handling - return factory.complete( + factory_complete = cast(Callable[..., object], factory.complete) + return factory_complete( prompt=prompt, system_prompt=system_prompt or "You are a helpful assistant.", model=self.config.model, @@ -235,12 +236,12 @@ class LLMClient: def vision_model_func( prompt: str, - system_prompt: Optional[str] = None, - history_messages: Optional[List[Dict]] = None, - image_data: Optional[str] = None, - messages: Optional[List[Dict]] = None, - **kwargs: Any, - ): + system_prompt: str | None = None, + history_messages: list[dict[str, object]] | None = None, + image_data: str | None = None, + messages: list[dict[str, object]] | None = None, + **kwargs: object, + ) -> object: # Handle multimodal messages if messages: clean_kwargs = { @@ -308,11 +309,10 @@ class LLMClient: return vision_model_func -# Singleton instance -_client: Optional[LLMClient] = None +_client: LLMClient | None = None -def get_llm_client(config: Optional[LLMConfig] = None) -> LLMClient: +def get_llm_client(config: LLMConfig | None = None) -> LLMClient: """ Get or create the singleton LLM client. @@ -328,7 +328,7 @@ def get_llm_client(config: Optional[LLMConfig] = None) -> LLMClient: return _client -def reset_llm_client(): +def reset_llm_client() -> None: """Reset the singleton LLM client.""" global _client _client = None diff --git a/src/services/llm/cloud_provider.py b/src/services/llm/cloud_provider.py index fab533437..e6fb8dc9f 100644 --- a/src/services/llm/cloud_provider.py +++ b/src/services/llm/cloud_provider.py @@ -7,9 +7,11 @@ Handles all cloud API LLM calls (OpenAI, DeepSeek, Anthropic, etc.) Provides both complete() and stream() methods. """ +from collections.abc import AsyncGenerator, Mapping import logging import os -from typing import AsyncGenerator, Dict, List, Optional +import threading +from typing import Protocol, cast import aiohttp @@ -17,21 +19,118 @@ import aiohttp # (lightrag logs errors internally before raising exceptions) _lightrag_logger = logging.getLogger("lightrag") _openai_logger = logging.getLogger("openai") +logger = logging.getLogger(__name__) + +# Thread-safe lock for SSL-warning state +_ssl_warning_lock = threading.Lock() + + +class OpenAICompleteIfCache(Protocol): + """Protocol for the lightrag OpenAI completion helper.""" + + async def __call__( + self, + model: str, + prompt: str, + *, + system_prompt: str, + history_messages: list[dict[str, str]], + api_key: str | None, + base_url: str | None, + **kwargs: object, + ) -> str | None: + """Return cached completion content when available.""" + # Lazy import for lightrag to avoid import errors when not installed -_openai_complete_if_cache = None +_openai_complete_if_cache: OpenAICompleteIfCache | None = None -def _get_openai_complete_if_cache(): +def _get_openai_complete_if_cache() -> OpenAICompleteIfCache: """Lazy load openai_complete_if_cache from lightrag.""" global _openai_complete_if_cache if _openai_complete_if_cache is None: - from lightrag.llm.openai import openai_complete_if_cache + # Import inside the function to avoid circular dependencies + from lightrag.llm.openai import ( + openai_complete_if_cache, + ) - _openai_complete_if_cache = openai_complete_if_cache + _openai_complete_if_cache = cast(OpenAICompleteIfCache, openai_complete_if_cache) return _openai_complete_if_cache +def _coerce_float(value: object, default: float) -> float: + """ + Coerce a value into a float with a fallback. + + Booleans are treated specially because ``bool`` is a subclass of ``int`` in + Python. Coercing ``True``/``False`` into ``1.0``/``0.0`` would hide invalid + inputs, so we fall back to the default instead. + + Args: + value: The raw value. + default: Value to use when coercion fails. + + Returns: + A float value. + """ + if isinstance(value, bool): + return default + if isinstance(value, (int, float)): + return float(value) + return default + + +def _coerce_int(value: object, default: int | None) -> int | None: + """ + Coerce a value into an integer with a fallback. + + Booleans are rejected to avoid silently treating ``True``/``False`` as + ``1``/``0``. This mirrors the float coercion behavior and keeps invalid + inputs from slipping through because ``bool`` is a subclass of ``int``. + + Args: + value: The raw value. + default: Value to use when coercion fails. + + Returns: + An integer value or None. + """ + if isinstance(value, bool): + return default + if isinstance(value, int): + return value + return default + + +# Use lowercase to avoid constant redefinition warning +_ssl_warning_logged = False + + +def _get_aiohttp_connector() -> aiohttp.TCPConnector | None: + """ + Build an optional aiohttp connector with SSL verification disabled. + + Returns: + A TCPConnector with SSL verification disabled when DISABLE_SSL_VERIFY + is truthy; otherwise None to use aiohttp defaults. + """ + # Thread-safe check and one-time warning emission + disable_flag = os.getenv("DISABLE_SSL_VERIFY", "").lower() in ("true", "1", "yes") + if not disable_flag: + return None + + # Emit warning once across threads + with _ssl_warning_lock: + if not globals().get("_ssl_warning_logged", False): + logger.warning( + "SSL verification is disabled via DISABLE_SSL_VERIFY. This is unsafe and must " + "not be used in production environments." + ) + globals()["_ssl_warning_logged"] = True + return aiohttp.TCPConnector(ssl=False) + + from .capabilities import get_effective_temperature, supports_response_format from .config import get_token_limit_kwargs from .exceptions import LLMAPIError, LLMAuthenticationError, LLMConfigError @@ -39,6 +138,7 @@ from .utils import ( build_auth_headers, build_chat_url, clean_thinking_tags, + collect_model_names, extract_response_content, sanitize_url, ) @@ -47,12 +147,12 @@ from .utils import ( async def complete( prompt: str, system_prompt: str = "You are a helpful assistant.", - model: Optional[str] = None, - api_key: Optional[str] = None, - base_url: Optional[str] = None, - api_version: Optional[str] = None, + model: str | None = None, + api_key: str | None = None, + base_url: str | None = None, + api_version: str | None = None, binding: str = "openai", - **kwargs, + **kwargs: object, ) -> str: """ Complete a prompt using cloud API providers. @@ -73,15 +173,39 @@ async def complete( str: The LLM response """ binding_lower = (binding or "openai").lower() + if model is None or not model.strip(): + raise LLMConfigError("Model is required for cloud LLM provider") + + if binding_lower == "cohere": + raise LLMConfigError("Cohere streaming is not supported yet.") + + if binding_lower == "cohere": + raise LLMConfigError("Cohere streaming is not supported yet.") if binding_lower in ["anthropic", "claude"]: + max_tokens_value = _coerce_int(kwargs.get("max_tokens"), None) + temperature_value = _coerce_float(kwargs.get("temperature"), 0.7) return await _anthropic_complete( model=model, prompt=prompt, system_prompt=system_prompt, api_key=api_key, base_url=base_url, - **kwargs, + max_tokens=max_tokens_value, + temperature=temperature_value, + ) + + if binding_lower == "cohere": + max_tokens_value = _coerce_int(kwargs.get("max_tokens"), None) + temperature_value = _coerce_float(kwargs.get("temperature"), 0.7) + return await _cohere_complete( + model=model, + prompt=prompt, + system_prompt=system_prompt, + api_key=api_key, + base_url=base_url, + max_tokens=max_tokens_value, + temperature=temperature_value, ) # Default to OpenAI-compatible endpoint @@ -100,13 +224,13 @@ async def complete( async def stream( prompt: str, system_prompt: str = "You are a helpful assistant.", - model: Optional[str] = None, - api_key: Optional[str] = None, - base_url: Optional[str] = None, - api_version: Optional[str] = None, + model: str | None = None, + api_key: str | None = None, + base_url: str | None = None, + api_version: str | None = None, binding: str = "openai", - messages: Optional[List[Dict[str, str]]] = None, - **kwargs, + messages: list[dict[str, str]] | None = None, + **kwargs: object, ) -> AsyncGenerator[str, None]: """ Stream a response from cloud API providers. @@ -126,8 +250,12 @@ async def stream( str: Response chunks """ binding_lower = (binding or "openai").lower() + if model is None or not model.strip(): + raise LLMConfigError("Model is required for cloud LLM provider") if binding_lower in ["anthropic", "claude"]: + max_tokens_value = _coerce_int(kwargs.get("max_tokens"), None) + temperature_value = _coerce_float(kwargs.get("temperature"), 0.7) async for chunk in _anthropic_stream( model=model, prompt=prompt, @@ -135,7 +263,8 @@ async def stream( api_key=api_key, base_url=base_url, messages=messages, - **kwargs, + max_tokens=max_tokens_value, + temperature=temperature_value, ): yield chunk else: @@ -157,11 +286,11 @@ async def _openai_complete( model: str, prompt: str, system_prompt: str, - api_key: Optional[str], - base_url: Optional[str], - api_version: Optional[str] = None, + api_key: str | None, + base_url: str | None, + api_version: str | None = None, binding: str = "openai", - **kwargs, + **kwargs: object, ) -> str: """OpenAI-compatible completion.""" # Sanitize URL @@ -178,15 +307,13 @@ async def _openai_complete( # Try using lightrag's openai_complete_if_cache first (has caching) # Only pass api_version if it's set (for Azure OpenAI) # Standard OpenAI SDK doesn't accept api_version parameter - lightrag_kwargs = { - "system_prompt": system_prompt, - "history_messages": [], # Required by lightrag to build messages array - "api_key": api_key, - "base_url": base_url, - **kwargs, - } - if api_version: - lightrag_kwargs["api_version"] = api_version + history_messages: list[dict[str, str]] = [] + lightrag_kwargs: dict[str, object] = dict(kwargs) + lightrag_kwargs.pop("system_prompt", None) + lightrag_kwargs.pop("history_messages", None) + lightrag_kwargs.pop("api_key", None) + lightrag_kwargs.pop("base_url", None) + lightrag_kwargs.pop("api_version", None) # Suppress lightrag's and openai's internal error logging during the call # (errors are handled by our fallback mechanism) @@ -196,57 +323,102 @@ async def _openai_complete( _openai_logger.setLevel(logging.CRITICAL) try: # model and prompt must be positional arguments + if api_version: + lightrag_kwargs["api_version"] = api_version + openai_complete_if_cache = _get_openai_complete_if_cache() - content = await openai_complete_if_cache(model, prompt, **lightrag_kwargs) + content = await openai_complete_if_cache( + model, + prompt, + system_prompt=system_prompt, + history_messages=history_messages, + api_key=api_key, + base_url=base_url, + **lightrag_kwargs, + ) finally: _lightrag_logger.setLevel(original_lightrag_level) _openai_logger.setLevel(original_openai_level) - except Exception: - pass # Fall through to direct call - + except Exception as exc: + # Skip cache failures and fall back to direct aiohttp call + logger.debug("Exception occurred: %s", exc) # Fallback: Direct aiohttp call - if not content and base_url: - # Build URL using unified utility (use binding for Azure detection) - url = build_chat_url(base_url, api_version, binding) + if not content: + effective_base = base_url or "https://api.openai.com/v1" + url = build_chat_url(effective_base, api_version, binding) # Build headers using unified utility headers = build_auth_headers(api_key, binding) - data = { + temperature = get_effective_temperature( + binding, + model, + _coerce_float(kwargs.get("temperature"), 0.7), + ) + data: dict[str, object] = { "model": model, "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": prompt}, ], - "temperature": get_effective_temperature( - binding, model, kwargs.get("temperature", 0.7) - ), + "temperature": temperature, } # Handle max_tokens / max_completion_tokens based on model - max_tokens = kwargs.get("max_tokens") or kwargs.get("max_completion_tokens") or 4096 - data.update(get_token_limit_kwargs(model, max_tokens)) + max_tokens_value = _coerce_int(kwargs.get("max_tokens"), None) + max_completion_value = _coerce_int(kwargs.get("max_completion_tokens"), None) + if max_tokens_value is None: + max_tokens_value = max_completion_value + if max_tokens_value is None: + max_tokens_value = 4096 + data.update(get_token_limit_kwargs(model, max_tokens_value)) # Include response_format if present in kwargs - if "response_format" in kwargs: - data["response_format"] = kwargs["response_format"] + response_format = kwargs.get("response_format") + if response_format is not None: + data["response_format"] = response_format timeout = aiohttp.ClientTimeout(total=120) - async with aiohttp.ClientSession(timeout=timeout) as session: - async with session.post(url, headers=headers, json=data) as resp: - if resp.status == 200: - result = await resp.json() - if "choices" in result and result["choices"]: - msg = result["choices"][0].get("message", {}) - # Use unified response extraction - content = extract_response_content(msg) - else: - error_text = await resp.text() + connector = _get_aiohttp_connector() + async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session: + try: + async with session.post(url, headers=headers, json=data) as resp: + if resp.status == 200: + result = cast(dict[str, object], await resp.json()) + choices = result.get("choices") + if isinstance(choices, list) and choices: + choices_list = cast(list[object], choices) + first_choice = choices_list[0] + if isinstance(first_choice, Mapping): + message = cast(Mapping[str, object], first_choice).get("message") + else: + message = None + if isinstance(message, Mapping): + # Use unified response extraction + content = extract_response_content(cast(dict[str, object], message)) + else: + error_text = await resp.text() + raise LLMAPIError( + f"OpenAI API error: {error_text}", + status_code=resp.status, + provider=binding or "openai", + ) + except aiohttp.ClientError as e: + # Handle connection errors with more specific messages + if "forcibly closed" in str(e).lower() or "10054" in str(e): raise LLMAPIError( - f"OpenAI API error: {error_text}", - status_code=resp.status, + f"Connection to {binding} API was forcibly closed. " + "This may indicate network issues or server-side problems. " + "Please check your internet connection and try again.", + status_code=0, provider=binding or "openai", - ) + ) from e + else: + raise LLMAPIError( + f"Network error connecting to {binding} API: {e}", + status_code=0, + provider=binding or "openai", + ) from e if content is not None: # Clean thinking tags from response using unified utility @@ -259,12 +431,12 @@ async def _openai_stream( model: str, prompt: str, system_prompt: str, - api_key: Optional[str], - base_url: Optional[str], - api_version: Optional[str] = None, + api_key: str | None, + base_url: str | None, + api_version: str | None = None, binding: str = "openai", - messages: Optional[List[Dict[str, str]]] = None, - **kwargs, + messages: list[dict[str, str]] | None = None, + **kwargs: object, ) -> AsyncGenerator[str, None]: """OpenAI-compatible streaming.""" import json @@ -293,24 +465,33 @@ async def _openai_stream( {"role": "user", "content": prompt}, ] - data = { + temperature = get_effective_temperature( + binding, + model, + _coerce_float(kwargs.get("temperature"), 0.7), + ) + data: dict[str, object] = { "model": model, "messages": msg_list, - "temperature": get_effective_temperature(binding, model, kwargs.get("temperature", 0.7)), + "temperature": temperature, "stream": True, } # Handle max_tokens / max_completion_tokens based on model - max_tokens = kwargs.get("max_tokens") or kwargs.get("max_completion_tokens") - if max_tokens: - data.update(get_token_limit_kwargs(model, max_tokens)) + max_tokens_value = _coerce_int(kwargs.get("max_tokens"), None) + if max_tokens_value is None: + max_tokens_value = _coerce_int(kwargs.get("max_completion_tokens"), None) + if max_tokens_value is not None: + data.update(get_token_limit_kwargs(model, max_tokens_value)) # Include response_format if present in kwargs - if "response_format" in kwargs: - data["response_format"] = kwargs["response_format"] + response_format = kwargs.get("response_format") + if response_format is not None: + data["response_format"] = response_format timeout = aiohttp.ClientTimeout(total=300) - async with aiohttp.ClientSession(timeout=timeout) as session: + connector = _get_aiohttp_connector() + async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session: async with session.post(url, headers=headers, json=data) as resp: if resp.status != 200: error_text = await resp.text() @@ -334,20 +515,52 @@ async def _openai_stream( break try: - chunk_data = json.loads(data_str) - if "choices" in chunk_data and chunk_data["choices"]: - delta = chunk_data["choices"][0].get("delta", {}) - content = delta.get("content") - if content: - # Handle thinking tags in streaming - if "" in content: + chunk_data = cast(dict[str, object], json.loads(data_str)) + choices = chunk_data.get("choices") + if isinstance(choices, list) and choices: + choices_list = cast(list[object], choices) + first_choice = choices_list[0] + if isinstance(first_choice, Mapping): + delta = cast(Mapping[str, object], first_choice).get("delta") + else: + delta = None + if isinstance(delta, Mapping): + content = cast(Mapping[str, object], delta).get("content") + else: + content = None + if isinstance(content, str) and content: + # Handle thinking tags in streaming for different marker styles + open_markers = ("", "◣", "꽁") + close_markers = ("", "◢", "꽁") + + # Check for start tag (handle split tags) + if any(open_m in content for open_m in open_markers): in_thinking_block = True - thinking_buffer = content + # Handle case where content has text BEFORE + for open_m in open_markers: + if open_m in content: + parts = content.split(open_m, 1) + if parts[0]: + yield parts[0] + thinking_buffer = open_m + parts[1] + + # Check if closed immediately in same chunk + if any( + close_m in thinking_buffer for close_m in close_markers + ): + cleaned = clean_thinking_tags( + thinking_buffer, binding, model + ) + if cleaned: + yield cleaned + thinking_buffer = "" + in_thinking_block = False + break continue elif in_thinking_block: thinking_buffer += content - if "" in thinking_buffer: - # End of thinking block, clean and yield + if any(close_m in thinking_buffer for close_m in close_markers): + # Block finished cleaned = clean_thinking_tags(thinking_buffer, binding, model) if cleaned: yield cleaned @@ -364,10 +577,11 @@ async def _anthropic_complete( model: str, prompt: str, system_prompt: str, - api_key: Optional[str], - base_url: Optional[str], - messages: Optional[List[Dict[str, str]]] = None, - **kwargs, + api_key: str | None, + base_url: str | None, + messages: list[dict[str, str]] | None = None, + max_tokens: int | None = None, + temperature: float | None = None, ) -> str: """Anthropic (Claude) API completion.""" api_key = api_key or os.getenv("ANTHROPIC_API_KEY") @@ -393,16 +607,19 @@ async def _anthropic_complete( msg_list = [{"role": "user", "content": prompt}] system_content = system_prompt - data = { + max_tokens_value = max_tokens if max_tokens is not None else 4096 + temperature_value = temperature if temperature is not None else 0.7 + data: dict[str, object] = { "model": model, "system": system_content, "messages": msg_list, - "max_tokens": kwargs.get("max_tokens", 4096), - "temperature": kwargs.get("temperature", 0.7), + "max_tokens": max_tokens_value, + "temperature": temperature_value, } timeout = aiohttp.ClientTimeout(total=120) - async with aiohttp.ClientSession(timeout=timeout) as session: + connector = _get_aiohttp_connector() + async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session: async with session.post(url, headers=headers, json=data) as response: if response.status != 200: error_text = await response.text() @@ -412,18 +629,31 @@ async def _anthropic_complete( provider="anthropic", ) - result = await response.json() - return result["content"][0]["text"] + result = cast(dict[str, object], await response.json()) + content_items = result.get("content") + if isinstance(content_items, list) and content_items: + content_list = cast(list[object], content_items) + first_item = content_list[0] + if isinstance(first_item, Mapping): + text = cast(Mapping[str, object], first_item).get("text") + if isinstance(text, str): + return text + raise LLMAPIError( + "Anthropic API error: unexpected response payload", + status_code=response.status, + provider="anthropic", + ) async def _anthropic_stream( model: str, prompt: str, system_prompt: str, - api_key: Optional[str], - base_url: Optional[str], - messages: Optional[List[Dict[str, str]]] = None, - **kwargs, + api_key: str | None, + base_url: str | None, + messages: list[dict[str, str]] | None = None, + max_tokens: int | None = None, + temperature: float | None = None, ) -> AsyncGenerator[str, None]: """Anthropic (Claude) API streaming.""" import json @@ -451,17 +681,20 @@ async def _anthropic_stream( msg_list = [{"role": "user", "content": prompt}] system_content = system_prompt - data = { + max_tokens_value = max_tokens if max_tokens is not None else 4096 + temperature_value = temperature if temperature is not None else 0.7 + data: dict[str, object] = { "model": model, "system": system_content, "messages": msg_list, - "max_tokens": kwargs.get("max_tokens", 4096), - "temperature": kwargs.get("temperature", 0.7), + "max_tokens": max_tokens_value, + "temperature": temperature_value, "stream": True, } timeout = aiohttp.ClientTimeout(total=300) - async with aiohttp.ClientSession(timeout=timeout) as session: + connector = _get_aiohttp_connector() + async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session: async with session.post(url, headers=headers, json=data) as response: if response.status != 200: error_text = await response.text() @@ -481,22 +714,78 @@ async def _anthropic_stream( continue try: - chunk_data = json.loads(data_str) + chunk_data = cast(dict[str, object], json.loads(data_str)) event_type = chunk_data.get("type") if event_type == "content_block_delta": - delta = chunk_data.get("delta", {}) - text = delta.get("text") - if text: + delta = chunk_data.get("delta") + if isinstance(delta, Mapping): + text = cast(Mapping[str, object], delta).get("text") + else: + text = None + if isinstance(text, str) and text: yield text except json.JSONDecodeError: continue +async def _cohere_complete( + model: str, + prompt: str, + system_prompt: str, + api_key: str | None, + base_url: str | None, + max_tokens: int | None = None, + temperature: float | None = None, +) -> str: + """Cohere API completion.""" + api_key = api_key or os.getenv("COHERE_API_KEY") + if not api_key: + raise LLMAuthenticationError("Cohere API key is missing.", provider="cohere") + + # Build URL using unified utility + effective_base = base_url or "https://api.cohere.ai/v1" + url = f"{effective_base}/chat" + + # Build headers using unified utility + headers = build_auth_headers(api_key, binding="cohere") + + max_tokens_value = max_tokens if max_tokens is not None else 4096 + temperature_value = temperature if temperature is not None else 0.7 + data: dict[str, object] = { + "model": model, + "message": f"{system_prompt}\n\n{prompt}", + "max_tokens": max_tokens_value, + "temperature": temperature_value, + } + + timeout = aiohttp.ClientTimeout(total=120) + connector = _get_aiohttp_connector() + async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session: + async with session.post(url, headers=headers, json=data) as response: + if response.status != 200: + error_text = await response.text() + raise LLMAPIError( + f"Cohere API error: {error_text}", + status_code=response.status, + provider="cohere", + ) + + result = cast(dict[str, object], await response.json()) + text = result.get("text") + if isinstance(text, str): + return text + raise LLMAPIError( + "Cohere API error: unexpected response payload", + status_code=response.status, + provider="cohere", + ) + + async def fetch_models( base_url: str, - api_key: Optional[str] = None, + api_key: str | None = None, binding: str = "openai", -) -> List[str]: +) -> list[str]: """ Fetch available models from cloud provider. @@ -517,26 +806,23 @@ async def fetch_models( headers.pop("Content-Type", None) timeout = aiohttp.ClientTimeout(total=30) - async with aiohttp.ClientSession(timeout=timeout) as session: + connector = _get_aiohttp_connector() + async with aiohttp.ClientSession(timeout=timeout, connector=connector) as session: try: url = f"{base_url}/models" async with session.get(url, headers=headers) as resp: if resp.status == 200: - data = await resp.json() - if "data" in data and isinstance(data["data"], list): - return [ - m.get("id") or m.get("name") - for m in data["data"] - if m.get("id") or m.get("name") - ] - elif isinstance(data, list): - return [ - m.get("id") or m.get("name") if isinstance(m, dict) else str(m) - for m in data - ] + payload = await resp.json() + if isinstance(payload, Mapping): + mapping = cast(Mapping[str, object], payload) + items = mapping.get("data") + if isinstance(items, list): + return collect_model_names(cast(list[object], items)) + elif isinstance(payload, list): + return collect_model_names(cast(list[object], payload)) return [] except Exception as e: - print(f"Error fetching models from {base_url}: {e}") + logger.error("Error fetching models from %s: %s", base_url, e) return [] diff --git a/src/services/llm/config.py b/src/services/llm/config.py index c11ba6650..63986fd51 100644 --- a/src/services/llm/config.py +++ b/src/services/llm/config.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """ LLM Configuration ================= @@ -7,15 +6,38 @@ Configuration management for LLM services. Simplified version - loads from unified config service or falls back to .env. """ -from dataclasses import dataclass +from __future__ import annotations + +from dataclasses import dataclass, replace import logging import os from pathlib import Path import re -from typing import Optional +from typing import TYPE_CHECKING, TypedDict from dotenv import load_dotenv +if TYPE_CHECKING: + from .traffic_control import TrafficController + + +class LLMConfigUpdate(TypedDict, total=False): + """Fields allowed when cloning an LLMConfig instance.""" + + model: str + api_key: str + base_url: str | None + effective_url: str | None + binding: str + provider_name: str + api_version: str | None + max_tokens: int + temperature: float + max_concurrency: int + requests_per_minute: int + traffic_controller: "TrafficController" | None + + from .exceptions import LLMConfigError logger = logging.getLogger(__name__) @@ -24,9 +46,10 @@ logger = logging.getLogger(__name__) PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False) load_dotenv(PROJECT_ROOT / ".env", override=False) +load_dotenv(PROJECT_ROOT / ".env.local", override=False) -def _setup_openai_env_vars_early(): +def _setup_openai_env_vars_early() -> None: """ Set OPENAI_API_KEY environment variable early for LightRAG compatibility. @@ -50,7 +73,10 @@ def _setup_openai_env_vars_early(): if base_url and not os.getenv("OPENAI_BASE_URL"): os.environ["OPENAI_BASE_URL"] = base_url - logger.debug(f"Set OPENAI_BASE_URL env var to {base_url} (early init)") + logger.debug( + "Set OPENAI_BASE_URL env var to %s (early init)", + base_url, + ) # Execute early setup at module import time @@ -63,14 +89,59 @@ class LLMConfig: model: str api_key: str - base_url: Optional[str] = None + base_url: str | None = None + effective_url: str | None = None binding: str = "openai" - api_version: Optional[str] = None + provider_name: str = "routing" + api_version: str | None = None max_tokens: int = 4096 temperature: float = 0.7 + max_concurrency: int = 20 + requests_per_minute: int = 600 + traffic_controller: TrafficController | None = None + + def __post_init__(self) -> None: + if self.effective_url is None: + self.effective_url = self.base_url + + def model_copy(self, update: LLMConfigUpdate | None = None) -> "LLMConfig": + """Return a copy of the config with optional updates.""" + return replace(self, **(update or {})) + + def get_api_key(self) -> str: + """Return the API key string for provider consumers.""" + return self.api_key -def _strip_value(value: Optional[str]) -> Optional[str]: +_LLM_CONFIG_CACHE: LLMConfig | None = None + + +def initialize_environment() -> None: + """ + Explicitly initialize environment variables for compatibility. + + LightRAG's internal functions (e.g., create_openai_async_client) read directly + from os.environ["OPENAI_API_KEY"] instead of using the api_key parameter. + This function ensures the environment variable is set. + + Should be called during application startup (main.py/run_server.py). + """ + binding = _strip_value(os.getenv("LLM_BINDING")) or "openai" + api_key = _strip_value(os.getenv("LLM_API_KEY")) + base_url = _strip_value(os.getenv("LLM_HOST")) + + # Only set env vars for OpenAI-compatible bindings + if binding in ("openai", "azure_openai", "gemini"): + if api_key and not os.getenv("OPENAI_API_KEY"): + os.environ["OPENAI_API_KEY"] = api_key + logger.debug("Set OPENAI_API_KEY env var (LightRAG compatibility)") + + if base_url and not os.getenv("OPENAI_BASE_URL"): + os.environ["OPENAI_BASE_URL"] = base_url + logger.debug("Set OPENAI_BASE_URL env var to %s", base_url) + + +def _strip_value(value: str | None) -> str | None: """Remove leading/trailing whitespace and quotes from string.""" if value is None: return None @@ -79,7 +150,7 @@ def _strip_value(value: Optional[str]) -> Optional[str]: def _get_llm_config_from_env() -> LLMConfig: """Get LLM configuration from environment variables.""" - binding = _strip_value(os.getenv("LLM_BINDING", "openai")) + binding = _strip_value(os.getenv("LLM_BINDING")) or "openai" model = _strip_value(os.getenv("LLM_MODEL")) api_key = _strip_value(os.getenv("LLM_API_KEY")) base_url = _strip_value(os.getenv("LLM_HOST")) @@ -118,59 +189,60 @@ def get_llm_config() -> LLMConfig: Raises: LLMConfigError: If required configuration is missing """ + global _LLM_CONFIG_CACHE + + if _LLM_CONFIG_CACHE is not None: + return _LLM_CONFIG_CACHE + # 1. Try to get active config from unified config service try: from src.services.config import get_active_llm_config config = get_active_llm_config() if config: - return LLMConfig( - binding=config.get("provider", "openai"), + _LLM_CONFIG_CACHE = LLMConfig( + binding=config.get("provider") or "openai", model=config["model"], api_key=config.get("api_key", ""), base_url=config.get("base_url"), api_version=config.get("api_version"), ) + return _LLM_CONFIG_CACHE + except ImportError: # Unified config service not yet available, fall back to env pass except Exception as e: - logger.warning(f"Failed to load from unified config: {e}") + logger.warning("Failed to load from unified config: %s", e) # 2. Fallback to environment variables - return _get_llm_config_from_env() + _LLM_CONFIG_CACHE = _get_llm_config_from_env() + return _LLM_CONFIG_CACHE async def get_llm_config_async() -> LLMConfig: """ - Async version of get_llm_config for non-blocking configuration loading. + Async wrapper for get_llm_config. + + Useful for consistency in async contexts, though the underlying load is synchronous. Returns: LLMConfig: Configuration dataclass - - Raises: - LLMConfigError: If required configuration is missing """ - # 1. Try to get active config from unified config service - try: - from src.services.config import get_active_llm_config + return get_llm_config() - config = get_active_llm_config() - if config: - return LLMConfig( - binding=config.get("provider", "openai"), - model=config["model"], - api_key=config.get("api_key", ""), - base_url=config.get("base_url"), - api_version=config.get("api_version"), - ) - except ImportError: - pass - except Exception as e: - logger.warning(f"Failed to load from unified config: {e}") - # 2. Fallback to environment variables - return _get_llm_config_from_env() +def clear_llm_config_cache() -> None: + """Clear cached LLM configuration.""" + global _LLM_CONFIG_CACHE + + _LLM_CONFIG_CACHE = None + + +def reload_config() -> LLMConfig: + """Reload and return the LLM configuration.""" + clear_llm_config_cache() + return get_llm_config() def uses_max_completion_tokens(model: str) -> bool: @@ -206,7 +278,7 @@ def uses_max_completion_tokens(model: str) -> bool: return False -def get_token_limit_kwargs(model: str, max_tokens: int) -> dict: +def get_token_limit_kwargs(model: str, max_tokens: int) -> dict[str, int]: """ Get the appropriate token limit parameter for the model. @@ -226,6 +298,8 @@ __all__ = [ "LLMConfig", "get_llm_config", "get_llm_config_async", + "clear_llm_config_cache", + "reload_config", "uses_max_completion_tokens", "get_token_limit_kwargs", ] diff --git a/src/services/llm/error_mapping.py b/src/services/llm/error_mapping.py index a42fcb088..d413edd88 100644 --- a/src/services/llm/error_mapping.py +++ b/src/services/llm/error_mapping.py @@ -5,9 +5,9 @@ Error Mapping - Map provider-specific errors to unified exceptions. from __future__ import annotations +from collections.abc import Callable from dataclasses import dataclass import logging -from typing import Callable, List, Optional, Type # Import unified exceptions from exceptions.py from .exceptions import ( @@ -19,7 +19,7 @@ from .exceptions import ( ) try: - import openai # type: ignore + import openai _HAS_OPENAI = True except ImportError: # pragma: no cover @@ -36,10 +36,10 @@ ErrorClassifier = Callable[[Exception], bool] @dataclass(frozen=True) class MappingRule: classifier: ErrorClassifier - factory: Callable[[Exception, Optional[str]], LLMError] + factory: Callable[[Exception, str | None], LLMError] -def _instance_of(*types: Type[BaseException]) -> ErrorClassifier: +def _instance_of(*types: type[BaseException]) -> ErrorClassifier: return lambda exc: isinstance(exc, types) @@ -51,7 +51,7 @@ def _message_contains(*needles: str) -> ErrorClassifier: return _classifier -_GLOBAL_RULES: List[MappingRule] = [ +_GLOBAL_RULES: list[MappingRule] = [ MappingRule( classifier=_message_contains("rate limit", "429", "quota"), factory=lambda exc, provider: LLMRateLimitError(str(exc), provider=provider), @@ -62,7 +62,7 @@ _GLOBAL_RULES: List[MappingRule] = [ ), ] -if _HAS_OPENAI: +if _HAS_OPENAI and openai is not None: _GLOBAL_RULES[:0] = [ MappingRule( classifier=_instance_of(openai.AuthenticationError), @@ -88,7 +88,7 @@ except ImportError: pass -def map_error(exc: Exception, provider: Optional[str] = None) -> LLMError: +def map_error(exc: Exception, provider: str | None = None) -> LLMError: """Map provider-specific errors to unified internal exceptions.""" # Heuristic check for status codes before rules status_code = getattr(exc, "status_code", None) diff --git a/src/services/llm/exceptions.py b/src/services/llm/exceptions.py index bb85dc12d..515c6d241 100644 --- a/src/services/llm/exceptions.py +++ b/src/services/llm/exceptions.py @@ -8,14 +8,15 @@ Provides a consistent exception hierarchy for better error handling. Maintains parity with upstream dev branch. """ -from typing import Any, Dict, Optional - class LLMError(Exception): """Base exception for all LLM-related errors.""" def __init__( - self, message: str, details: Optional[Dict[str, Any]] = None, provider: Optional[str] = None + self, + message: str, + details: dict[str, object] | None = None, + provider: str | None = None, ): super().__init__(message) self.message = message @@ -41,6 +42,12 @@ class LLMProviderError(LLMError): pass +class LLMCircuitBreakerError(LLMError): + """Raised when circuit breaker blocks LLM execution.""" + + pass + + class LLMAPIError(LLMError): """ Raised when an API call to an LLM provider fails. @@ -50,9 +57,9 @@ class LLMAPIError(LLMError): def __init__( self, message: str, - status_code: Optional[int] = None, - provider: Optional[str] = None, - details: Optional[Dict[str, Any]] = None, + status_code: int | None = None, + provider: str | None = None, + details: dict[str, object] | None = None, ): super().__init__(message, details, provider) self.status_code = status_code @@ -73,8 +80,8 @@ class LLMTimeoutError(LLMAPIError): def __init__( self, message: str = "Request timed out", - timeout: Optional[float] = None, - provider: Optional[str] = None, + timeout: float | None = None, + provider: str | None = None, ): super().__init__(message, status_code=408, provider=provider) self.timeout = timeout @@ -86,8 +93,8 @@ class LLMRateLimitError(LLMAPIError): def __init__( self, message: str = "Rate limit exceeded", - retry_after: Optional[float] = None, - provider: Optional[str] = None, + retry_after: float | None = None, + provider: str | None = None, ): super().__init__(message, status_code=429, provider=provider) self.retry_after = retry_after @@ -99,7 +106,7 @@ class LLMAuthenticationError(LLMAPIError): def __init__( self, message: str = "Authentication failed", - provider: Optional[str] = None, + provider: str | None = None, ): super().__init__(message, status_code=401, provider=provider) @@ -110,8 +117,8 @@ class LLMModelNotFoundError(LLMAPIError): def __init__( self, message: str = "Model not found", - model: Optional[str] = None, - provider: Optional[str] = None, + model: str | None = None, + provider: str | None = None, ): super().__init__(message, status_code=404, provider=provider) self.model = model @@ -123,8 +130,8 @@ class LLMParseError(LLMError): def __init__( self, message: str = "Failed to parse LLM output", - provider: Optional[str] = None, - details: Optional[Dict[str, Any]] = None, + provider: str | None = None, + details: dict[str, object] | None = None, ): super().__init__(message, details=details, provider=provider) @@ -142,6 +149,7 @@ __all__ = [ "LLMError", "LLMConfigError", "LLMProviderError", + "LLMCircuitBreakerError", "LLMAPIError", "LLMTimeoutError", "LLMRateLimitError", diff --git a/src/services/llm/factory.py b/src/services/llm/factory.py index b9a31f60d..4484c7d88 100644 --- a/src/services/llm/factory.py +++ b/src/services/llm/factory.py @@ -2,11 +2,17 @@ """ LLM Factory - Central Hub for LLM Calls ======================================= - This module serves as the central hub for all LLM calls in DeepTutor. It provides a unified interface for agents to call LLMs, routing requests to the appropriate provider (cloud or local) based on URL detection. +Compatibility: + This factory preserves legacy behaviors from the pre-provider refactor, + including BaseAgent.call_llm()/stream_llm() signatures and retry semantics. + The adapter layer remains until all legacy entry points migrate to direct + provider calls. Once all agents and tools depend on provider modules + directly, this wrapper can be removed. + Architecture: Agents (ChatAgent, GuideAgent, etc.) ↓ @@ -32,14 +38,16 @@ Retry Mechanism: """ import asyncio -from typing import Any, AsyncGenerator, Dict, List, Optional +from collections.abc import AsyncGenerator, Mapping +from typing import TYPE_CHECKING, TypedDict import tenacity -from src.logging.logger import get_logger +from src.config.settings import settings +from src.logging.logger import Logger, get_logger -from . import cloud_provider, local_provider -from .config import get_llm_config +from . import local_provider +from .config import LLMConfig, get_llm_config from .exceptions import ( LLMAPIError, LLMAuthenticationError, @@ -48,16 +56,21 @@ from .exceptions import ( ) from .utils import is_local_llm_server +if TYPE_CHECKING: + from .providers.base_provider import BaseLLMProvider + # Initialize logger -logger = get_logger("LLMFactory") +logger: Logger = get_logger("LLMFactory") -# Default retry configuration -DEFAULT_MAX_RETRIES = 5 # Increased for complex agents like Research -DEFAULT_RETRY_DELAY = 2.0 # seconds -DEFAULT_EXPONENTIAL_BACKOFF = True +# Default retry configuration (bound to settings) +DEFAULT_MAX_RETRIES = settings.retry.max_retries +DEFAULT_RETRY_DELAY = settings.retry.base_delay +DEFAULT_EXPONENTIAL_BACKOFF = settings.retry.exponential_backoff + +CallKwargs = dict[str, object] -def _is_retriable_error(error: Exception) -> bool: +def _is_retriable_error(error: BaseException) -> bool: """ Check if an error is retriable. @@ -74,9 +87,8 @@ def _is_retriable_error(error: Exception) -> bool: - Client errors (4xx except 429) """ from aiohttp import ClientError - from requests.exceptions import RequestException - if isinstance(error, (asyncio.TimeoutError, ClientError, RequestException)): + if isinstance(error, (asyncio.TimeoutError, ClientError)): return True if isinstance(error, LLMTimeoutError): return True @@ -94,13 +106,15 @@ def _is_retriable_error(error: Exception) -> bool: # Don't retry on client errors (4xx except 429) if 400 <= status_code < 500: return False - return True # Retry by default for unknown API errors + + # When status_code is None (e.g. connection drop), retry. + return True # For other exceptions (network errors, etc.), retry return True -def _should_use_local(base_url: Optional[str]) -> bool: +def _should_use_local(base_url: str | None) -> bool: """ Determine if we should use the local provider based on URL. @@ -116,16 +130,16 @@ def _should_use_local(base_url: Optional[str]) -> bool: async def complete( prompt: str, system_prompt: str = "You are a helpful assistant.", - model: Optional[str] = None, - api_key: Optional[str] = None, - base_url: Optional[str] = None, - api_version: Optional[str] = None, - binding: Optional[str] = None, - messages: Optional[List[Dict[str, str]]] = None, + model: str | None = None, + api_key: str | None = None, + base_url: str | None = None, + api_version: str | None = None, + binding: str | None = None, + messages: list[dict[str, str]] | None = None, max_retries: int = DEFAULT_MAX_RETRIES, retry_delay: float = DEFAULT_RETRY_DELAY, exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF, - **kwargs, + **kwargs: object, ) -> str: """ Unified LLM completion function with automatic retry. @@ -162,125 +176,137 @@ async def complete( # Determine which provider to use use_local = _should_use_local(base_url) - # Define helper to determine if a generic LLMAPIError is retriable def _is_retriable_llm_api_error(exc: BaseException) -> bool: - """ - Return True for LLMAPIError instances that represent retriable conditions. + """Delegate retriable checks to shared helper.""" + return _is_retriable_error(exc) - We only retry on: - - HTTP 429 (rate limit), or - - HTTP 5xx server errors. + def _log_retry_warning(retry_state: tenacity.RetryCallState) -> None: + """Log retry warnings with safe handling for missing exceptions.""" + outcome = retry_state.outcome + exception = outcome.exception() if outcome else None + error_message = str(exception) if exception else "unknown error" + logger.warning( + "LLM call failed (attempt %s/%s), retrying in %.1fs... Error: %s" + % ( + retry_state.attempt_number, + max_retries + 1, + retry_state.upcoming_sleep, + error_message, + ) + ) - All other LLMAPIError instances (e.g., 4xx like 400, 401, 403, 404) are treated - as non-retriable to avoid unnecessary retries. - """ - if not isinstance(exc, LLMAPIError): - return False + wait_strategy = ( + tenacity.wait_exponential( + multiplier=retry_delay, + min=retry_delay, + max=120, + ) + if exponential_backoff + else tenacity.wait_fixed(retry_delay) + ) - status_code = getattr(exc, "status_code", None) - if status_code is None: - # Do not retry when status code is unknown to avoid retrying non-transient errors - return False - - if status_code == 429: - return True - - if 500 <= status_code < 600: - return True - - return False - - # Calculate total attempts for logging (1 initial + max_retries) total_attempts = max_retries + 1 - # Define the actual completion function with tenacity retry @tenacity.retry( retry=( tenacity.retry_if_exception_type(LLMRateLimitError) | tenacity.retry_if_exception_type(LLMTimeoutError) | tenacity.retry_if_exception(_is_retriable_llm_api_error) ), - wait=tenacity.wait_exponential(multiplier=retry_delay, min=retry_delay, max=120), + wait=wait_strategy, stop=tenacity.stop_after_attempt(total_attempts), - before_sleep=lambda retry_state: logger.warning( - f"LLM call failed (attempt {retry_state.attempt_number}/{total_attempts}), " - f"retrying in {retry_state.upcoming_sleep:.1f}s... Error: {str(retry_state.outcome.exception())}" - ), + before_sleep=_log_retry_warning, ) - async def _do_complete(**call_kwargs): + async def _do_complete( + *, + prompt_value: str, + system_prompt_value: str, + model_value: str, + api_key_value: str | None, + base_url_value: str | None, + api_version_value: str | None, + binding_value: str | None, + extra_kwargs: CallKwargs, + messages_value: list[dict[str, str]] | None, + ) -> str: try: if use_local: - return await local_provider.complete(**call_kwargs) - else: - return await cloud_provider.complete(**call_kwargs) - except Exception as e: - # Map raw SDK exceptions to unified exceptions for retry logic + return await local_provider.complete( + prompt=prompt_value, + system_prompt=system_prompt_value, + model=model_value, + api_key=api_key_value, + base_url=base_url_value, + messages=messages_value, + **extra_kwargs, + ) + from . import cloud_provider + + return await cloud_provider.complete( + prompt=prompt_value, + system_prompt=system_prompt_value, + model=model_value, + api_key=api_key_value, + base_url=base_url_value, + api_version=api_version_value, + binding=binding_value or "openai", + messages=messages_value, + **extra_kwargs, + ) + except Exception as exc: from .error_mapping import map_error - mapped_error = map_error(e, provider=call_kwargs.get("binding", "unknown")) - raise mapped_error from e + if use_local: + provider_name = "local" + else: + provider_name = binding_value if isinstance(binding_value, str) else "unknown" + mapped_error = map_error(exc, provider=provider_name) + raise mapped_error from exc - # Build call kwargs - call_kwargs = { - "prompt": prompt, - "system_prompt": system_prompt, - "model": model, - "api_key": api_key, - "base_url": base_url, - "messages": messages, - **kwargs, - } + extra_kwargs: CallKwargs = dict(kwargs) + extra_kwargs.pop("messages", None) - # Add cloud-specific kwargs if not local - if not use_local: - call_kwargs["api_version"] = api_version - call_kwargs["binding"] = binding or "openai" + if use_local: + return await _do_complete( + prompt_value=prompt, + system_prompt_value=system_prompt, + model_value=model, + api_key_value=api_key, + base_url_value=base_url, + api_version_value=None, + binding_value=None, + extra_kwargs=extra_kwargs, + messages_value=messages, + ) - # Execute with retry (handled by tenacity decorator) - return await _do_complete(**call_kwargs) + return await _do_complete( + prompt_value=prompt, + system_prompt_value=system_prompt, + model_value=model, + api_key_value=api_key, + base_url_value=base_url, + api_version_value=api_version, + binding_value=binding or "openai", + extra_kwargs=extra_kwargs, + messages_value=messages, + ) async def stream( prompt: str, system_prompt: str = "You are a helpful assistant.", - model: Optional[str] = None, - api_key: Optional[str] = None, - base_url: Optional[str] = None, - api_version: Optional[str] = None, - binding: Optional[str] = None, - messages: Optional[List[Dict[str, str]]] = None, + model: str | None = None, + api_key: str | None = None, + base_url: str | None = None, + api_version: str | None = None, + binding: str | None = None, + messages: list[dict[str, str]] | None = None, max_retries: int = DEFAULT_MAX_RETRIES, retry_delay: float = DEFAULT_RETRY_DELAY, exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF, - **kwargs, + **kwargs: object, ) -> AsyncGenerator[str, None]: - """ - Unified LLM streaming function with automatic retry. - - Routes to cloud_provider or local_provider based on configuration. - Includes automatic retry with exponential backoff for connection errors. - - Note: Retry only applies to initial connection errors. Once streaming - starts, errors during streaming will not be automatically retried. - - Args: - prompt: The user prompt - system_prompt: System prompt for context - model: Model name (optional, uses effective config if not provided) - api_key: API key (optional) - base_url: Base URL for the API (optional) - api_version: API version for Azure OpenAI (optional) - binding: Provider binding type (optional) - messages: Pre-built messages array (optional) - max_retries: Maximum number of retry attempts (default: 5) - retry_delay: Initial delay between retries in seconds (default: 2.0) - exponential_backoff: Whether to use exponential backoff (default: True) - **kwargs: Additional parameters (temperature, max_tokens, etc.) - - Yields: - str: Response chunks - """ - # Get config if parameters not provided + """Stream LLM responses with retry handling.""" if not model or not base_url: config = get_llm_config() model = model or config.model @@ -289,70 +315,68 @@ async def stream( api_version = api_version or config.api_version binding = binding or config.binding or "openai" - # Determine which provider to use use_local = _should_use_local(base_url) + extra_kwargs: CallKwargs = dict(kwargs) + extra_kwargs.pop("messages", None) - # Build call kwargs - call_kwargs = { - "prompt": prompt, - "system_prompt": system_prompt, - "model": model, - "api_key": api_key, - "base_url": base_url, - "messages": messages, - **kwargs, - } - - # Add cloud-specific kwargs if not local - if not use_local: - call_kwargs["api_version"] = api_version - call_kwargs["binding"] = binding or "openai" - - # Retry logic for streaming (retry on connection errors) - # Total attempts = 1 initial + max_retries total_attempts = max_retries + 1 - last_exception = None + last_exception: Exception | None = None delay = retry_delay - max_delay = 120 # Cap maximum delay at 120 seconds (consistent with complete()) + has_yielded = False + max_delay = 120 for attempt in range(total_attempts): try: - # Route to appropriate provider if use_local: - async for chunk in local_provider.stream(**call_kwargs): + async for chunk in local_provider.stream( + prompt=prompt, + system_prompt=system_prompt, + model=model, + api_key=api_key, + base_url=base_url, + messages=messages, + **extra_kwargs, + ): + has_yielded = True yield chunk else: - async for chunk in cloud_provider.stream(**call_kwargs): - yield chunk - # If we get here, streaming completed successfully - return - except Exception as e: - last_exception = e + from . import cloud_provider - # Check if we should retry - if attempt >= max_retries or not _is_retriable_error(e): + async for chunk in cloud_provider.stream( + prompt=prompt, + system_prompt=system_prompt, + model=model, + api_key=api_key, + base_url=base_url, + api_version=api_version, + binding=binding or "openai", + messages=messages, + **extra_kwargs, + ): + has_yielded = True + yield chunk + return + except Exception as exc: + last_exception = exc + if has_yielded: + raise + if attempt >= max_retries or not _is_retriable_error(exc): raise - # Calculate delay for next attempt if exponential_backoff: current_delay = min(delay * (2**attempt), max_delay) else: current_delay = delay - # Special handling for rate limit errors with retry_after - if isinstance(e, LLMRateLimitError) and e.retry_after: - current_delay = max(current_delay, e.retry_after) + if isinstance(exc, LLMRateLimitError) and exc.retry_after: + current_delay = max(current_delay, exc.retry_after) - # Log retry attempt (consistent with complete() function) logger.warning( - f"LLM streaming failed (attempt {attempt + 1}/{total_attempts}), " - f"retrying in {current_delay:.1f}s... Error: {str(e)}" + "LLM streaming failed (attempt %s/%s), retrying in %.1fs... Error: %s" + % (attempt + 1, total_attempts, current_delay, exc) ) - - # Wait before retrying await asyncio.sleep(current_delay) - # Should not reach here, but just in case if last_exception: raise last_exception @@ -360,8 +384,8 @@ async def stream( async def fetch_models( binding: str, base_url: str, - api_key: Optional[str] = None, -) -> List[str]: + api_key: str | None = None, +) -> list[str]: """ Fetch available models from the provider. @@ -378,11 +402,37 @@ async def fetch_models( if is_local_llm_server(base_url): return await local_provider.fetch_models(base_url, api_key) else: + from . import cloud_provider + return await cloud_provider.fetch_models(base_url, api_key, binding) +class ApiProviderPreset(TypedDict, total=False): + """Typed representation of API provider presets.""" + + name: str + base_url: str + requires_key: bool + models: list[str] + binding: str + + +class LocalProviderPreset(TypedDict, total=False): + """Typed representation of local provider presets.""" + + name: str + base_url: str + requires_key: bool + default_key: str + + +ProviderPreset = ApiProviderPreset | LocalProviderPreset +ProviderPresetMap = Mapping[str, ProviderPreset] +ProviderPresetBundle = Mapping[str, ProviderPresetMap] + + # API Provider Presets -API_PROVIDER_PRESETS = { +API_PROVIDER_PRESETS: dict[str, ApiProviderPreset] = { "openai": { "name": "OpenAI", "base_url": "https://api.openai.com/v1", @@ -406,12 +456,12 @@ API_PROVIDER_PRESETS = { "name": "OpenRouter", "base_url": "https://openrouter.ai/api/v1", "requires_key": True, - "models": [], # Dynamic + "models": [], }, } # Local Provider Presets -LOCAL_PROVIDER_PRESETS = { +LOCAL_PROVIDER_PRESETS: dict[str, LocalProviderPreset] = { "ollama": { "name": "Ollama", "base_url": "http://localhost:11434/v1", @@ -439,7 +489,7 @@ LOCAL_PROVIDER_PRESETS = { } -def get_provider_presets() -> Dict[str, Any]: +def get_provider_presets() -> ProviderPresetBundle: """ Get all provider presets for frontend display. """ @@ -460,4 +510,16 @@ __all__ = [ "DEFAULT_MAX_RETRIES", "DEFAULT_RETRY_DELAY", "DEFAULT_EXPONENTIAL_BACKOFF", + "LLMFactory", ] + + +class LLMFactory: + """Compatibility factory for legacy agent integrations.""" + + @staticmethod + def get_provider(config: "LLMConfig") -> "BaseLLMProvider": + """Return a provider instance for the supplied config.""" + from .providers.routing import RoutingProvider + + return RoutingProvider(config) diff --git a/src/services/llm/local_provider.py b/src/services/llm/local_provider.py index f921adcb0..99a3b30e6 100644 --- a/src/services/llm/local_provider.py +++ b/src/services/llm/local_provider.py @@ -12,8 +12,9 @@ Key features: - Extended timeouts for potentially slower local inference """ +from collections.abc import AsyncGenerator import json -from typing import AsyncGenerator, Dict, List, Optional +import logging import aiohttp @@ -22,10 +23,45 @@ from .utils import ( build_auth_headers, build_chat_url, clean_thinking_tags, + collect_model_names, extract_response_content, sanitize_url, ) +logger = logging.getLogger(__name__) + + +def _extract_message_from_payload(payload: dict[str, object]) -> str: + """Extract message content from a local provider payload. + + Args: + payload: Provider response payload. + Returns: + Extracted content string. + Raises: + None. + """ + if not payload: + return "" + + choices = payload.get("choices") + if isinstance(choices, list) and choices: + choice = choices[0] + for key in ("message", "delta"): + if not isinstance(choice, dict): + break + part = choice.get(key) + if part is not None: + return extract_response_content(part) + if isinstance(choice, dict) and "text" in choice: + return str(choice.get("text") or "") + + if "message" in payload: + return extract_response_content(payload.get("message")) + + return "" + + # Extended timeout for local servers (may be slower than cloud) DEFAULT_TIMEOUT = 300 # 5 minutes @@ -33,11 +69,11 @@ DEFAULT_TIMEOUT = 300 # 5 minutes async def complete( prompt: str, system_prompt: str = "You are a helpful assistant.", - model: Optional[str] = None, - api_key: Optional[str] = None, - base_url: Optional[str] = None, - messages: Optional[List[Dict[str, str]]] = None, - **kwargs, + model: str | None = None, + api_key: str | None = None, + base_url: str | None = None, + messages: list[dict[str, str]] | None = None, + **kwargs: object, ) -> str: """ Complete a prompt using local LLM server. @@ -87,7 +123,11 @@ async def complete( if kwargs.get("max_tokens"): data["max_tokens"] = kwargs["max_tokens"] - timeout = aiohttp.ClientTimeout(total=kwargs.get("timeout", DEFAULT_TIMEOUT)) + timeout_value = kwargs.get("timeout", DEFAULT_TIMEOUT) + timeout_seconds = ( + float(timeout_value) if isinstance(timeout_value, (int, float)) else DEFAULT_TIMEOUT + ) + timeout = aiohttp.ClientTimeout(total=timeout_seconds) async with aiohttp.ClientSession(timeout=timeout) as session: async with session.post(url, json=data, headers=headers) as response: @@ -100,26 +140,23 @@ async def complete( ) result = await response.json() - - if "choices" in result and result["choices"]: - msg = result["choices"][0].get("message", {}) - # Use unified response extraction - content = extract_response_content(msg) - # Clean thinking tags using unified utility - content = clean_thinking_tags(content) + content = _extract_message_from_payload(result) + content = clean_thinking_tags(content) + if content: return content + logger.warning("Local LLM returned no choices: %s", result) return "" async def stream( prompt: str, system_prompt: str = "You are a helpful assistant.", - model: Optional[str] = None, - api_key: Optional[str] = None, - base_url: Optional[str] = None, - messages: Optional[List[Dict[str, str]]] = None, - **kwargs, + model: str | None = None, + api_key: str | None = None, + base_url: str | None = None, + messages: list[dict[str, str]] | None = None, + **kwargs: object, ) -> AsyncGenerator[str, None]: """ Stream a response from local LLM server. @@ -169,7 +206,11 @@ async def stream( if kwargs.get("max_tokens"): data["max_tokens"] = kwargs["max_tokens"] - timeout = aiohttp.ClientTimeout(total=kwargs.get("timeout", DEFAULT_TIMEOUT)) + timeout_value = kwargs.get("timeout", DEFAULT_TIMEOUT) + timeout_seconds = ( + float(timeout_value) if isinstance(timeout_value, (int, float)) else DEFAULT_TIMEOUT + ) + timeout = aiohttp.ClientTimeout(total=timeout_seconds) try: async with aiohttp.ClientSession(timeout=timeout) as session: @@ -202,43 +243,54 @@ async def stream( try: chunk_data = json.loads(data_str) - if "choices" in chunk_data and chunk_data["choices"]: - delta = chunk_data["choices"][0].get("delta", {}) - content = delta.get("content") + content = _extract_message_from_payload(chunk_data) + if content: + # Handle thinking tags in streaming + if "" in content: + in_thinking_block = True + # Handle case where content has text BEFORE + parts = content.split("", 1) + if parts[0]: + yield parts[0] + thinking_buffer = "" + parts[1] - if content: - # Handle thinking tags in streaming - if "" in content: - in_thinking_block = True - thinking_buffer = content - continue - elif in_thinking_block: - thinking_buffer += content - if "" in thinking_buffer: - # End of thinking block, clean and yield - cleaned = clean_thinking_tags(thinking_buffer) - if cleaned: - yield cleaned - in_thinking_block = False - thinking_buffer = "" - continue - else: - yield content + # Check if closed immediately in same chunk + if "" in thinking_buffer: + cleaned = clean_thinking_tags(thinking_buffer) + if cleaned: + yield cleaned + thinking_buffer = "" + in_thinking_block = False + continue + elif in_thinking_block: + thinking_buffer += content + if "" in thinking_buffer: + # Block finished + cleaned = clean_thinking_tags(thinking_buffer) + if cleaned: + yield cleaned + in_thinking_block = False + thinking_buffer = "" + continue + else: + yield content except json.JSONDecodeError: - # Non-JSON response, might be raw text - if data_str and not data_str.startswith("{"): - yield data_str + # Log and skip malformed JSON chunks + logger.warning( + "Skipping malformed JSON chunk: %s...", + data_str[:50], + ) + continue # Some servers don't use SSE format elif line_str.startswith("{"): try: chunk_data = json.loads(line_str) - if "choices" in chunk_data and chunk_data["choices"]: - delta = chunk_data["choices"][0].get("delta", {}) - content = delta.get("content") - if content: - yield content + content = _extract_message_from_payload(chunk_data) + if content: + # TODO: Implement tag parsing for non-SSE JSON streams if supported + yield content except json.JSONDecodeError: pass @@ -246,7 +298,7 @@ async def stream( raise # Re-raise LLM errors as-is except Exception as e: # Streaming failed, fall back to non-streaming - print(f"⚠️ Streaming failed ({e}), falling back to non-streaming") + logger.warning("Streaming failed (%s), falling back to non-streaming", e) try: content = await complete( @@ -269,8 +321,8 @@ async def stream( async def fetch_models( base_url: str, - api_key: Optional[str] = None, -) -> List[str]: + api_key: str | None = None, +) -> list[str]: """ Fetch available models from local LLM server. @@ -304,9 +356,13 @@ async def fetch_models( if resp.status == 200: data = await resp.json() if "models" in data: - return [m["name"] for m in data.get("models", [])] - except Exception: - pass + return collect_model_names(data["models"]) + except Exception as exc: + logger.debug( + "Failed to fetch Ollama models from %s: %s", + base_url, + exc, + ) # Try OpenAI-compatible /models try: @@ -317,26 +373,13 @@ async def fetch_models( # Handle different response formats if "data" in data and isinstance(data["data"], list): - return [ - m.get("id") or m.get("name") - for m in data["data"] - if m.get("id") or m.get("name") - ] + return collect_model_names(data["data"]) elif "models" in data and isinstance(data["models"], list): - if data["models"] and isinstance(data["models"][0], dict): - return [ - m.get("id") or m.get("name") - for m in data["models"] - if m.get("id") or m.get("name") - ] - return [str(m) for m in data["models"]] + return collect_model_names(data["models"]) elif isinstance(data, list): - return [ - m.get("id") or m.get("name") if isinstance(m, dict) else str(m) - for m in data - ] + return collect_model_names(data) except Exception as e: - print(f"Error fetching models from {base_url}: {e}") + logger.error("Error fetching models from %s: %s", base_url, e) return [] diff --git a/src/services/llm/providers/anthropic.py b/src/services/llm/providers/anthropic.py index 810e01cda..bf4492ba2 100644 --- a/src/services/llm/providers/anthropic.py +++ b/src/services/llm/providers/anthropic.py @@ -1,34 +1,170 @@ -# -*- coding: utf-8 -*- +""" +Anthropic LLM provider implementation. +""" + +import asyncio +from collections.abc import AsyncIterator +from typing import Callable, Protocol, TypeVar, cast + import anthropic +from ..config import LLMConfig +from ..http_client import get_shared_http_client from ..registry import register_provider from ..telemetry import track_llm_call from ..types import AsyncStreamGenerator, TutorResponse, TutorStreamChunk from .base_provider import BaseLLMProvider +_DISALLOWED_KWARGS = { + "api_version", + "base_url", + "binding", + "logit_bias", + "max_retries", # Handled by factory retry mechanism + "response_format", + "seed", + "stream", + "stream_options", +} + +F = TypeVar("F", bound=Callable[..., object]) + + +class AnthropicDelta(Protocol): + """Protocol for Anthropic delta payloads.""" + + text: str | None + + +class AnthropicUsage(Protocol): + """Protocol for Anthropic usage payloads.""" + + input_tokens: int + output_tokens: int + + +class AnthropicChunk(Protocol): + """Protocol for Anthropic streaming chunks.""" + + type: str + delta: AnthropicDelta + usage: AnthropicUsage | None + + +class AnthropicStream(Protocol): + """Protocol for Anthropic streaming responses.""" + + def __aiter__(self) -> AsyncIterator[AnthropicChunk]: ... + + +def _coerce_int(value: object, default: int) -> int: + if isinstance(value, bool): + return default + if isinstance(value, int): + return value + if isinstance(value, float): + return int(value) + if isinstance(value, str) and value.isdigit(): + return int(value) + return default + + +def _typed_track_llm_call(provider: str) -> Callable[[F], F]: + return cast(Callable[[F], F], track_llm_call(provider)) + + +def _sanitize_kwargs(kwargs: dict[str, object]) -> dict[str, object]: + """ + Remove OpenAI-only and factory-specific kwargs before Anthropic calls. + + Args: + kwargs: Raw kwargs passed to the provider. + + Returns: + Sanitized kwargs safe for the Anthropic SDK. + """ + import logging + + sanitized = dict(kwargs) + removed_keys = [] + for key in _DISALLOWED_KWARGS: + if key in sanitized: + removed_keys.append(key) + sanitized.pop(key) + + if removed_keys: + logging.getLogger("AnthropicProvider").warning( + "Ignoring unsupported Anthropic kwargs (handled upstream): %s", + removed_keys, + ) + + return sanitized + @register_provider("anthropic") class AnthropicProvider(BaseLLMProvider): - """Anthropic Claude Provider.""" + """Anthropic Claude Provider with shared HTTP client.""" - def __init__(self, config): + def __init__(self, config: LLMConfig) -> None: + """ + Initialize the Anthropic provider. + + Args: + config: Provider configuration object. + + Returns: + None. + + Raises: + Exception: Propagates client initialization failures. + """ super().__init__(config) + self.client: anthropic.AsyncAnthropic | None = None + self._client_lock = asyncio.Lock() - self.client = anthropic.AsyncAnthropic( - api_key=self.api_key, + async def _get_client(self) -> anthropic.AsyncAnthropic: + if self.client is None: + async with self._client_lock: + if self.client is None: + http_client = await get_shared_http_client() + self.client = anthropic.AsyncAnthropic( + api_key=self.api_key, + http_client=http_client, + ) + return self.client + + @_typed_track_llm_call("anthropic") + async def complete(self, prompt: str, **kwargs: object) -> TutorResponse: + """ + Generate a completion using Anthropic. + + Args: + prompt: User prompt content. + **kwargs: Provider-specific options. + + Returns: + TutorResponse containing the completion result. + + Raises: + Exception: Propagates SDK or execution errors. + """ + model_raw = kwargs.pop("model", None) + model = ( + model_raw + if isinstance(model_raw, str) and model_raw + else self.config.model or "claude-3-sonnet-20240229" ) - - @track_llm_call("anthropic") - async def complete(self, prompt: str, **kwargs) -> TutorResponse: - model = kwargs.pop("model", None) or self.config.model_name or "claude-3-sonnet-20240229" + kwargs.pop("max_retries", None) kwargs.pop("stream", None) - async def _call_api(): - response = await self.client.messages.create( + async def _call_api() -> TutorResponse: + client = await self._get_client() + request_kwargs = _sanitize_kwargs(kwargs) + response = await client.messages.create( # type: ignore[call-overload] model=model, - max_tokens=kwargs.pop("max_tokens", 1024), + max_tokens=_coerce_int(request_kwargs.pop("max_tokens", 1024), 1024), messages=[{"role": "user", "content": prompt}], - **kwargs, + **request_kwargs, ) content = response.content[0].text if response.content else "" @@ -49,48 +185,74 @@ class AnthropicProvider(BaseLLMProvider): return await self.execute_with_retry(_call_api) - @track_llm_call("anthropic") - async def stream(self, prompt: str, **kwargs) -> AsyncStreamGenerator: - model = kwargs.pop("model", None) or self.config.model_name or "claude-3-sonnet-20240229" - max_tokens = kwargs.pop("max_tokens", 1024) + @_typed_track_llm_call("anthropic") + def stream(self, prompt: str, **kwargs: object) -> AsyncStreamGenerator: + """ + Stream a completion from Anthropic. - async def _create_stream(): - return await self.client.messages.create( - model=model, - max_tokens=max_tokens, - messages=[{"role": "user", "content": prompt}], - stream=True, - **kwargs, + Args: + prompt: User prompt content. + **kwargs: Provider-specific options. + + Returns: + AsyncStreamGenerator yielding TutorStreamChunk items. + + Raises: + Exception: Propagates SDK or execution errors. + """ + model_raw = kwargs.pop("model", None) + model = ( + model_raw + if isinstance(model_raw, str) and model_raw + else self.config.model or "claude-3-sonnet-20240229" + ) + max_tokens = kwargs.pop("max_tokens", 1024) + kwargs.pop("max_retries", None) + + async def _create_stream() -> AnthropicStream: + client = await self._get_client() + request_kwargs = _sanitize_kwargs(kwargs) + return cast( + AnthropicStream, + await client.messages.create( # type: ignore[call-overload] + model=model, + max_tokens=_coerce_int(max_tokens, 1024), + messages=[{"role": "user", "content": prompt}], + stream=True, + **request_kwargs, + ), ) - stream = await self.execute_with_retry(_create_stream) - accumulated_content = "" - usage = None + async def _stream() -> AsyncStreamGenerator: + stream = cast(AnthropicStream, await self.execute_with_retry(_create_stream)) + accumulated_content = "" + usage = None - async for chunk in stream: - if chunk.type == "content_block_delta" and chunk.delta.text: - delta = chunk.delta.text - accumulated_content += delta + async for chunk in stream: + if chunk.type == "content_block_delta" and chunk.delta.text: + delta = chunk.delta.text + accumulated_content += delta - yield TutorStreamChunk( - content=accumulated_content, - delta=delta, - provider="anthropic", - model=model, - is_complete=False, - ) - elif chunk.type == "message_delta" and hasattr(chunk, "usage"): - # Extract usage from the final message delta - usage = { - "input_tokens": chunk.usage.input_tokens, - "output_tokens": chunk.usage.output_tokens, - } + yield TutorStreamChunk( + content=accumulated_content, + delta=delta, + provider="anthropic", + model=model, + is_complete=False, + ) + elif chunk.type == "message_delta" and chunk.usage is not None: + usage = { + "input_tokens": chunk.usage.input_tokens, + "output_tokens": chunk.usage.output_tokens, + } - yield TutorStreamChunk( - content=accumulated_content, - delta="", - provider="anthropic", - model=model, - is_complete=True, - usage=usage, - ) + yield TutorStreamChunk( + content=accumulated_content, + delta="", + provider="anthropic", + model=model, + is_complete=True, + usage=usage, + ) + + return _stream() diff --git a/src/services/llm/providers/base_provider.py b/src/services/llm/providers/base_provider.py index f2b7355d9..c985f24c1 100644 --- a/src/services/llm/providers/base_provider.py +++ b/src/services/llm/providers/base_provider.py @@ -1,94 +1,204 @@ -# -*- coding: utf-8 -*- -""" -Base LLM Provider - Unified interface and configuration. -""" +"""Base LLM provider with unified configuration and retries.""" -from abc import ABC, abstractmethod -import asyncio +from abc import ABC +from collections.abc import Awaitable, Callable import logging -import random -from typing import Any, Callable, Dict +from typing import TypeVar -from ...utils.error_rate_tracker import record_provider_call -from ...utils.network.circuit_breaker import is_call_allowed, record_call_success +import tenacity +from tenacity import AsyncRetrying, retry_if_exception, stop_after_attempt + +from src.utils.error_rate_tracker import record_provider_call +from src.utils.network.circuit_breaker import ( + is_call_allowed, + record_call_failure, + record_call_success, +) + +from ..config import LLMConfig from ..error_mapping import map_error from ..exceptions import ( LLMAPIError, + LLMCircuitBreakerError, LLMError, LLMRateLimitError, LLMTimeoutError, ) +from ..traffic_control import TrafficController from ..types import AsyncStreamGenerator, TutorResponse +T = TypeVar("T") + logger = logging.getLogger(__name__) +# Cap retry delays to avoid excessive waits during outages. +MAX_RETRY_DELAY_SECONDS = 60.0 +BASE_RETRY_DELAY_SECONDS = 1.0 + class BaseLLMProvider(ABC): """Base class for all LLM providers with unified config and retries.""" - def __init__(self, config): + def __init__(self, config: LLMConfig) -> None: + """Initialize provider with shared configuration and traffic control.""" self.config = config self.provider_name = config.provider_name - self.api_key = config.api_key - self.base_url = getattr(config, "base_url", "") + self.api_key = getattr(config, "get_api_key", lambda: config.api_key)() + self.base_url = config.base_url or config.effective_url # Isolation: Each provider gets its own traffic controller instance - self.traffic_controller = getattr(config, "traffic_controller", None) - if self.traffic_controller is None: - from ..traffic_control import TrafficController + self.traffic_controller: TrafficController + traffic_controller = getattr(config, "traffic_controller", None) + if isinstance(traffic_controller, TrafficController): + self.traffic_controller = traffic_controller + else: + self.traffic_controller = TrafficController( + provider_name=self.provider_name, + max_concurrency=getattr(config, "max_concurrency", 20), + requests_per_minute=getattr(config, "requests_per_minute", 600), + ) - self.traffic_controller = TrafficController(provider_name=self.provider_name) + async def complete(self, prompt: str, **kwargs: object) -> TutorResponse: + """Run a completion call for the provider.""" + raise NotImplementedError - @abstractmethod - async def complete(self, prompt: str, **kwargs) -> TutorResponse: - pass - - @abstractmethod - async def stream(self, prompt: str, **kwargs) -> AsyncStreamGenerator: - pass + def stream(self, prompt: str, **kwargs: object) -> AsyncStreamGenerator: + """Return an async generator for streaming completions.""" + raise NotImplementedError def _map_exception(self, e: Exception) -> LLMError: return map_error(e, provider=self.provider_name) - def calculate_cost(self, usage: Dict[str, Any]) -> float: - """Placeholder for cost calculation logic.""" + def calculate_cost(self, usage: dict[str, object]) -> float: + """Calculate cost estimate for a provider call.""" return 0.0 - async def execute_with_retry(self, func: Callable, *args, max_retries=3, **kwargs): - """Standard retry wrapper with exponential backoff.""" + def _check_circuit_breaker(self) -> None: + """Raise when the circuit breaker is open for this provider.""" if not is_call_allowed(self.provider_name): record_provider_call(self.provider_name, success=False) + error = LLMCircuitBreakerError( + f"Circuit breaker open for provider {self.provider_name}", + provider=self.provider_name, + ) + setattr(error, "is_circuit_breaker", True) + raise error - raise LLMError(f"Circuit breaker open for provider {self.provider_name}") + def _should_record_failure(self, error: LLMError) -> bool: + """Return True when failures should trip the circuit breaker.""" + if isinstance(error, (LLMRateLimitError, LLMTimeoutError)): + return True + if isinstance(error, LLMAPIError): + status_code = error.status_code + if status_code is None: + return True + return status_code >= 500 + return False - for attempt in range(max_retries + 1): - try: - async with self.traffic_controller: - result = await func(*args, **kwargs) - record_provider_call(self.provider_name, success=True) - record_call_success(self.provider_name) - return result - except Exception as e: - mapped_e = self._map_exception(e) + def _should_retry_error(self, error: BaseException) -> bool: + """Return True when an error should trigger a retry.""" + if isinstance(error, (LLMRateLimitError, LLMTimeoutError)): + return True + if isinstance(error, LLMAPIError): + status_code = error.status_code + if status_code is None: + return True + return status_code >= 500 + return False - # Logic check: should we retry? - is_retriable = isinstance(mapped_e, (LLMRateLimitError, LLMTimeoutError)) - if isinstance(mapped_e, LLMAPIError): - status_code = getattr(mapped_e, "status_code", None) - if status_code is not None and status_code >= 500: - is_retriable = True + def _wait_strategy(self, retry_state: tenacity.RetryCallState) -> float: + """Return the next retry delay based on error context.""" + outcome = retry_state.outcome + if outcome is None: + return BASE_RETRY_DELAY_SECONDS + exc = outcome.exception() + if exc is None: + return BASE_RETRY_DELAY_SECONDS + if isinstance(exc, LLMRateLimitError): + retry_after = getattr(exc, "retry_after", None) + retry_after_value: float | None = None + if retry_after is not None: + try: + retry_after_value = float(retry_after) + except (TypeError, ValueError): + retry_after_value = None + if retry_after_value is not None: + return max(0.0, min(retry_after_value, MAX_RETRY_DELAY_SECONDS)) - if attempt >= max_retries or not is_retriable: - record_provider_call(self.provider_name, success=False) - raise mapped_e from e + wait_fn = tenacity.wait_exponential( + multiplier=1.5, + min=BASE_RETRY_DELAY_SECONDS, + max=MAX_RETRY_DELAY_SECONDS, + ) + return float(wait_fn(retry_state)) - delay = (1.5**attempt) + (random.random() * 0.5) - logger.warning( - "[%s] Call failed. Retry %d/%d in %.2fs. Error: %s", - self.provider_name, - attempt + 1, - max_retries, - delay, - str(mapped_e), - ) - await asyncio.sleep(delay) + async def _execute_core( + self, + func: Callable[..., Awaitable[T]], + *args: object, + **kwargs: object, + ) -> T: + """ + Core execution pipeline: + 1) circuit breaker check + 2) traffic control context + 3) call execution + 4) mapping + metrics + """ + self._check_circuit_breaker() + + try: + async with self.traffic_controller: + result = await func(*args, **kwargs) + record_provider_call(self.provider_name, success=True) + record_call_success(self.provider_name) + return result + except Exception as exc: + mapped_exc = self._map_exception(exc) + record_provider_call(self.provider_name, success=False) + if isinstance(mapped_exc, LLMError): + if self._should_record_failure(mapped_exc): + record_call_failure(self.provider_name) + raise mapped_exc from exc + # Internal/runtime errors should bubble up without being rewrapped. + raise mapped_exc + + async def execute( + self, + func: Callable[..., Awaitable[T]], + *args: object, + **kwargs: object, + ) -> T: + """Execute a single attempt without retry.""" + return await self._execute_core(func, *args, **kwargs) + + async def execute_with_retry( + self, + func: Callable[..., Awaitable[T]], + *args: object, + max_retries: int = 3, + sleep: Callable[[int | float], Awaitable[None] | None] | None = None, + **kwargs: object, + ) -> T: + """Execute with automatic retries using tenacity.""" + + def _default_sleep(_delay: int | float) -> None: + return None + + sleep_fn: Callable[[int | float], Awaitable[None] | None] + sleep_fn = _default_sleep if sleep is None else sleep + + retrying = AsyncRetrying( + stop=stop_after_attempt(max_retries + 1), + wait=self._wait_strategy, + retry=retry_if_exception(self._should_retry_error), + reraise=True, + before_sleep=tenacity.before_sleep_log(logger, logging.WARNING), + sleep=sleep_fn, + ) + + async for attempt in retrying: + with attempt: + return await self._execute_core(func, *args, **kwargs) + + raise RuntimeError("Retry loop exited without returning") diff --git a/src/services/llm/providers/open_ai.py b/src/services/llm/providers/open_ai.py index 3c4c9c661..ad28cd1de 100644 --- a/src/services/llm/providers/open_ai.py +++ b/src/services/llm/providers/open_ai.py @@ -1,84 +1,169 @@ -# -*- coding: utf-8 -*- +"""OpenAI provider implementation using shared HTTP client.""" + +from __future__ import annotations + +from collections.abc import AsyncIterator import os +from typing import Callable, Protocol, TypeVar, cast import httpx import openai +from src.logging import get_logger + +from ..config import LLMConfig, get_token_limit_kwargs +from ..exceptions import LLMConfigError from ..registry import register_provider from ..telemetry import track_llm_call from ..types import AsyncStreamGenerator, TutorResponse, TutorStreamChunk from .base_provider import BaseLLMProvider +logger = get_logger(__name__) +F = TypeVar("F", bound=Callable[..., object]) + + +class OpenAIChoiceDelta(Protocol): + """Protocol for OpenAI delta payloads.""" + + content: str | None + + +class OpenAIChoice(Protocol): + """Protocol for OpenAI choices in streaming responses.""" + + delta: OpenAIChoiceDelta + + +class OpenAIChunk(Protocol): + """Protocol for OpenAI streaming chunks.""" + + choices: list[OpenAIChoice] + + +class OpenAIStream(Protocol): + """Protocol for OpenAI streaming responses.""" + + def __aiter__(self) -> AsyncIterator[OpenAIChunk]: ... + + +def _typed_track_llm_call(provider: str) -> Callable[[F], F]: + return cast(Callable[[F], F], track_llm_call(provider)) + @register_provider("openai") class OpenAIProvider(BaseLLMProvider): - """Production-ready OpenAI Provider.""" + """Production-ready OpenAI Provider with shared HTTP client.""" - def __init__(self, config): + def __init__(self, config: LLMConfig) -> None: super().__init__(config) - - # SSL handling for dev/troubleshooting http_client = None if os.getenv("DISABLE_SSL_VERIFY", "").lower() in ("true", "1", "yes"): - http_client = httpx.AsyncClient(verify=False) - + if os.getenv("ENVIRONMENT", "").lower() in ("prod", "production"): + raise LLMConfigError("DISABLE_SSL_VERIFY is not allowed in production") + logger.warning("SSL verification disabled for OpenAI HTTP client") + http_client = httpx.AsyncClient(verify=False) # nosec B501 self.client = openai.AsyncOpenAI( api_key=self.api_key, base_url=self.base_url or None, http_client=http_client, ) - @track_llm_call("openai") - async def complete(self, prompt: str, **kwargs) -> TutorResponse: - model = kwargs.pop("model", None) or self.config.model_name or "gpt-4o" + @_typed_track_llm_call("openai") + async def complete(self, prompt: str, **kwargs: object) -> TutorResponse: + model_raw = kwargs.pop("model", None) + model = model_raw if isinstance(model_raw, str) and model_raw else self.config.model + if not model: + raise LLMConfigError("Model not configured for OpenAI provider") kwargs.pop("stream", None) - async def _call_api(): - response = await self.client.chat.completions.create( + requested_max_tokens = ( + kwargs.pop("max_tokens", None) + or kwargs.pop("max_completion_tokens", None) + or getattr(self.config, "max_tokens", 4096) + ) + if isinstance(requested_max_tokens, (int, float, str)): + max_tokens = int(requested_max_tokens) + else: + max_tokens = int(getattr(self.config, "max_tokens", 4096)) + kwargs.update(get_token_limit_kwargs(model, max_tokens)) + + async def _call_api() -> TutorResponse: + request_kwargs: dict[str, object] = dict(kwargs) + response = await self.client.chat.completions.create( # type: ignore[call-overload] model=model, messages=[{"role": "user", "content": prompt}], - **kwargs, + **request_kwargs, ) + if not response.choices: + raise ValueError("API returned no choices in response") choice = response.choices[0] + message = choice.message + content = message.content or "" + finish_reason = choice.finish_reason usage = response.usage.model_dump() if response.usage else {} + raw_response = response.model_dump() if hasattr(response, "model_dump") else {} + provider_label = ( + "azure" if isinstance(self.client, openai.AsyncAzureOpenAI) else "openai" + ) return TutorResponse( - content=choice.message.content or "", - raw_response=response.model_dump(), + content=content, + raw_response=raw_response, usage=usage, - provider="openai", + provider=provider_label, model=model, - finish_reason=choice.finish_reason, + finish_reason=finish_reason, cost_estimate=self.calculate_cost(usage), ) return await self.execute_with_retry(_call_api) - async def stream(self, prompt: str, **kwargs) -> AsyncStreamGenerator: # type: ignore[override] - model = kwargs.pop("model", None) or self.config.model_name or "gpt-4o" + def stream(self, prompt: str, **kwargs: object) -> AsyncStreamGenerator: + model_raw = kwargs.pop("model", None) + model = model_raw if isinstance(model_raw, str) and model_raw else self.config.model + if not model: + raise LLMConfigError("Model not configured for OpenAI provider") - async def _create_stream(): - return await self.client.chat.completions.create( - model=model, messages=[{"role": "user", "content": prompt}], stream=True, **kwargs + async def _create_stream() -> OpenAIStream: + request_kwargs: dict[str, object] = dict(kwargs) + return cast( + OpenAIStream, + await self.client.chat.completions.create( # type: ignore[call-overload] + model=model, + messages=[{"role": "user", "content": prompt}], + stream=True, + **request_kwargs, + ), ) - stream = await self.execute_with_retry(_create_stream) - accumulated_content = "" - - async for chunk in stream: - if chunk.choices and chunk.choices[0].delta.content: - delta = chunk.choices[0].delta.content - accumulated_content += delta + async def _stream() -> AsyncStreamGenerator: + stream = cast(OpenAIStream, await self.execute_with_retry(_create_stream)) + accumulated_content = "" + provider_label = ( + "azure" if isinstance(self.client, openai.AsyncAzureOpenAI) else "openai" + ) + try: + async for chunk in stream: + delta = "" + if chunk.choices and chunk.choices[0].delta.content: + delta = chunk.choices[0].delta.content + accumulated_content += delta + yield TutorStreamChunk( + content=accumulated_content, + delta=delta, + provider=provider_label, + model=model, + is_complete=False, + ) + finally: yield TutorStreamChunk( content=accumulated_content, - delta=delta, - provider="openai", + delta="", + provider=provider_label, model=model, - is_complete=False, + is_complete=True, ) - yield TutorStreamChunk( - content=accumulated_content, delta="", provider="openai", model=model, is_complete=True - ) + return _stream() diff --git a/src/services/llm/providers/routing.py b/src/services/llm/providers/routing.py new file mode 100644 index 000000000..00b2dca17 --- /dev/null +++ b/src/services/llm/providers/routing.py @@ -0,0 +1,264 @@ +"""Routing provider bridging legacy provider functions. + +This provider delegates to the existing function-based providers +(`cloud_provider` / `local_provider`) while inheriting the hardened +execution pipeline from `BaseLLMProvider` (traffic control, circuit +breaker, and exception mapping). + +It exists to keep the public API stable while incrementally migrating +call sites to provider objects. +""" + +from __future__ import annotations + +import asyncio +from importlib import import_module +from typing import Protocol, cast + +from src.logging import get_logger + +cloud_provider = import_module("src.services.llm.cloud_provider") +local_provider = import_module("src.services.llm.local_provider") +from ..config import LLMConfig +from ..exceptions import LLMConfigError +from ..registry import register_provider +from ..types import AsyncStreamGenerator, TutorResponse, TutorStreamChunk +from ..utils import is_local_llm_server +from .base_provider import BaseLLMProvider + +logger = get_logger(__name__) + + +class CacheModule(Protocol): + """Protocol for optional cache module bindings.""" + + DEFAULT_CACHE_TTL: int + + @staticmethod + def build_completion_cache_key(**kwargs: object) -> str: ... + + @staticmethod + async def get_cached_completion(key: str) -> str | None: ... + + @staticmethod + async def set_cached_completion( + key: str, + value: str, + *, + ttl_seconds: int, + ) -> None: ... + + +def _coerce_int(value: object, default: int) -> int: + if isinstance(value, bool): + return default + if isinstance(value, int): + return value + if isinstance(value, str) and value.isdigit(): + return int(value) + return default + + +def _coerce_str(value: object, default: str) -> str: + return value if isinstance(value, str) and value else default + + +@register_provider("routing") +class RoutingProvider(BaseLLMProvider): + """Provider that routes between cloud and local function providers.""" + + def __init__(self, config: LLMConfig) -> None: + super().__init__(config) + # Use per-route provider name for circuit-breaker/metrics when possible. + if is_local_llm_server(self.base_url or ""): + self.provider_name = "local" + + async def complete(self, prompt: str, **kwargs: object) -> TutorResponse: + """Complete via local_provider/cloud_provider with retries.""" + model = _coerce_str(kwargs.pop("model", None), self.config.model) + if not model: + raise LLMConfigError("Model is required") + + system_prompt = kwargs.pop("system_prompt", "You are a helpful assistant.") + messages = kwargs.pop("messages", None) + max_retries = _coerce_int(kwargs.pop("max_retries", 3), 3) + sleep_value = kwargs.pop("sleep", None) + sleep = sleep_value if callable(sleep_value) else None + + use_cache = bool(kwargs.pop("use_cache", True)) + cache_ttl_seconds = kwargs.pop("cache_ttl_seconds", None) + cache_key = kwargs.pop("cache_key", None) + + call_kwargs = { + "prompt": prompt, + "system_prompt": system_prompt, + "model": model, + "api_key": self.api_key, + "base_url": self.base_url, + "messages": messages, + **kwargs, + } + + if is_local_llm_server(self.base_url or ""): + target = local_provider.complete + else: + binding = _coerce_str(kwargs.pop("binding", None), self.config.binding) + api_version = kwargs.pop("api_version", None) or self.config.api_version + call_kwargs["binding"] = binding + call_kwargs["api_version"] = api_version + target = cloud_provider.complete + + async def _call() -> str: + cache_enabled = use_cache + cache_module: CacheModule | None = None + if cache_enabled: + try: + # Import lazily to keep routing provider lightweight. + module = import_module("src.services.llm.cache") + cache_module = cast(CacheModule, module) + except ModuleNotFoundError: + logger.warning("LLM cache module unavailable; disabling routing cache.") + cache_enabled = False + + if cache_enabled and cache_module is not None: + computed_cache_key = _coerce_str(cache_key, "") + if not computed_cache_key: + computed_cache_key = cache_module.build_completion_cache_key( + model=model, + binding=str(call_kwargs.get("binding") or "openai"), + base_url=call_kwargs.get("base_url"), + system_prompt=system_prompt, + prompt=prompt, + messages=messages, + **{ + k: v + for k, v in call_kwargs.items() + if k + not in { + "prompt", + "system_prompt", + "messages", + "model", + "api_key", + "base_url", + "binding", + } + }, + ) + cached = await cache_module.get_cached_completion(computed_cache_key) + if cached is not None: + return cached + + result = str(await target(**call_kwargs)) + await cache_module.set_cached_completion( + computed_cache_key, + result, + ttl_seconds=_coerce_int( + cache_ttl_seconds or cache_module.DEFAULT_CACHE_TTL, + cache_module.DEFAULT_CACHE_TTL, + ), + ) + return result + + return str(await target(**call_kwargs)) + + text = await self.execute_with_retry( + _call, + max_retries=max_retries, + sleep=sleep, + ) + + return TutorResponse( + content=str(text), + raw_response={}, + usage={ + "prompt_tokens": 0, + "completion_tokens": 0, + "total_tokens": 0, + }, + provider=self.provider_name, + model=model, + finish_reason=None, + cost_estimate=0.0, + ) + + def stream(self, prompt: str, **kwargs: object) -> AsyncStreamGenerator: + """Stream via local_provider/cloud_provider. + + Retry applies only to failures before the first yielded chunk. + """ + model = _coerce_str(kwargs.pop("model", None), self.config.model) + if not model: + raise LLMConfigError("Model is required") + + system_prompt = kwargs.pop("system_prompt", "You are a helpful assistant.") + messages = kwargs.pop("messages", None) + max_retries = _coerce_int(kwargs.pop("max_retries", 3), 3) + + call_kwargs = { + "prompt": prompt, + "system_prompt": system_prompt, + "model": model, + "api_key": self.api_key, + "base_url": self.base_url, + "messages": messages, + **kwargs, + } + + if is_local_llm_server(self.base_url or ""): + stream_func = local_provider.stream + else: + binding = _coerce_str(kwargs.pop("binding", None), self.config.binding) + api_version = kwargs.pop("api_version", None) or self.config.api_version + call_kwargs["binding"] = binding + call_kwargs["api_version"] = api_version + stream_func = cloud_provider.stream + + async def _stream() -> AsyncStreamGenerator: + attempt = 0 + while True: + attempt += 1 + emitted_any = False + accumulated = "" + + try: + self._check_circuit_breaker() + async with self.traffic_controller: + iterator = stream_func(**call_kwargs) + async for delta in iterator: + emitted_any = True + accumulated += str(delta) + yield TutorStreamChunk( + content=accumulated, + delta=str(delta), + provider=self.provider_name, + model=model, + is_complete=False, + ) + + yield TutorStreamChunk( + content=accumulated, + delta="", + provider=self.provider_name, + model=model, + is_complete=True, + ) + return + except asyncio.CancelledError: + raise + except Exception as exc: + mapped = self._map_exception(exc) + if emitted_any: + raise mapped from exc + + if attempt > max_retries + 1 or not self._should_retry_error(mapped): + raise mapped from exc + + delay_seconds = min(60.0, 1.5**attempt) + logger.warning( + "Stream start failed (attempt %d/%d): %s; retrying in %.2fs" + % (attempt, max_retries + 1, mapped, delay_seconds) + ) + await asyncio.sleep(delay_seconds) + + return _stream() diff --git a/src/services/llm/registry.py b/src/services/llm/registry.py index b6b137179..6063b9ad2 100644 --- a/src/services/llm/registry.py +++ b/src/services/llm/registry.py @@ -6,13 +6,13 @@ LLM Provider Registry Simple provider registration system for LLM providers. """ -from typing import Dict, Type +from collections.abc import Callable # Global registry for LLM providers -_provider_registry: Dict[str, Type] = {} +_provider_registry: dict[str, type] = {} -def register_provider(name: str): +def register_provider(name: str) -> Callable[[type], type]: """ Decorator to register an LLM provider class. @@ -23,17 +23,17 @@ def register_provider(name: str): Decorator function """ - def decorator(cls): + def decorator(cls: type) -> type: if name in _provider_registry: raise ValueError(f"Provider '{name}' is already registered") _provider_registry[name] = cls - cls.__provider_name__ = name # Store name on class for introspection + setattr(cls, "__provider_name__", name) return cls return decorator -def get_provider_class(name: str) -> Type: +def get_provider_class(name: str) -> type: """ Get a registered provider class by name. diff --git a/src/services/llm/telemetry.py b/src/services/llm/telemetry.py index cbadd2d9e..247aab47c 100644 --- a/src/services/llm/telemetry.py +++ b/src/services/llm/telemetry.py @@ -6,14 +6,20 @@ LLM Telemetry Basic telemetry tracking for LLM calls. """ +from collections.abc import Awaitable, Callable import functools import logging -from typing import Any, Callable +from typing import TypeVar logger = logging.getLogger(__name__) -def track_llm_call(provider_name: str): +T = TypeVar("T") + + +def track_llm_call( + provider_name: str, +) -> Callable[[Callable[..., Awaitable[T]]], Callable[..., Awaitable[T]]]: """ Decorator to track LLM calls for telemetry. @@ -24,16 +30,16 @@ def track_llm_call(provider_name: str): Decorator function """ - def decorator(func: Callable) -> Callable: + def decorator(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]: @functools.wraps(func) - async def wrapper(*args, **kwargs) -> Any: - logger.debug(f"LLM call to {provider_name}: {func.__name__}") + async def wrapper(*args, **kwargs): + logger.debug("LLM call to %s: %s", provider_name, func.__name__) try: result = await func(*args, **kwargs) - logger.debug(f"LLM call to {provider_name} completed successfully") + logger.debug("LLM call to %s completed successfully", provider_name) return result except Exception as e: - logger.warning(f"LLM call to {provider_name} failed: {e}") + logger.warning("LLM call to %s failed: %s", provider_name, e) raise return wrapper diff --git a/src/services/llm/traffic_control.py b/src/services/llm/traffic_control.py new file mode 100644 index 000000000..271fc4faa --- /dev/null +++ b/src/services/llm/traffic_control.py @@ -0,0 +1,126 @@ +"""Traffic control primitives for LLM providers.""" + +from __future__ import annotations + +import asyncio +import time +from types import TracebackType + +from src.logging import get_logger + +logger = get_logger(__name__) + + +class TrafficController: + """ + Controls concurrency and rate limits for LLM providers. + + Protects both the local system (resource exhaustion) and + remote provider (rate limits). + """ + + def __init__( + self, + provider_name: str, + max_concurrency: int = 20, + requests_per_minute: int = 600, + acquisition_timeout: float = 30.0, + ) -> None: + """ + Args: + provider_name: Label for logging. + max_concurrency: Max simultaneous in-flight requests (bulkheads). + requests_per_minute: Max RPM allowed before local throttling. + acquisition_timeout: Max seconds to wait for a slot before failing. + """ + self.provider_name = provider_name + self.max_concurrency = max_concurrency + if requests_per_minute <= 0: + raise ValueError("requests_per_minute must be > 0") + self.rpm = requests_per_minute + self.acquisition_timeout = acquisition_timeout + + # Concurrency Gate + self._semaphore = asyncio.Semaphore(max_concurrency) + + # Rate Limiting (Token Bucket) + self._tokens = float(requests_per_minute) + self._last_refill = time.monotonic() + self._fill_rate = requests_per_minute / 60.0 # tokens per second + self._lock = asyncio.Lock() # Protects token state + + async def _wait_for_token(self) -> None: + """Consumes a rate limit token, waiting if necessary.""" + async with self._lock: + now = time.monotonic() + elapsed = now - self._last_refill + + # Refill tokens + new_tokens = elapsed * self._fill_rate + if new_tokens > 0: + self._tokens = min(float(self.rpm), self._tokens + new_tokens) + self._last_refill = now + + # Consume token + if self._tokens >= 1: + self._tokens -= 1.0 + return + + # Calculate wait time needed for 1 token + wait_time = (1.0 - self._tokens) / self._fill_rate + + # Wait outside lock to avoid blocking other tasks + if wait_time > 0: + logger.debug("[%s] Rate limit active, waiting %.2fs" % (self.provider_name, wait_time)) + await asyncio.sleep(wait_time) + # Recursively try again (simplest way to ensure thread safety after sleep) + await self._wait_for_token() + + async def __aenter__(self) -> TrafficController: + """ + Acquire concurrency slot AND rate limit token. + Raises asyncio.TimeoutError if system is overloaded. + """ + start = time.monotonic() + + # 1. Acquire Concurrency Slot + try: + # wait_for adds a timeout to the semaphore acquisition + await asyncio.wait_for(self._semaphore.acquire(), timeout=self.acquisition_timeout) + except TimeoutError: + logger.error( + "[%s] Local concurrency limit (%s) exceeded for >%.1fs." + % (self.provider_name, self.max_concurrency, self.acquisition_timeout) + ) + raise + + # 2. Acquire Rate Limit Token (if we passed concurrency check) + # Note: We do this AFTER semaphore to ensure we don't wait for tokens + # while holding a concurrency slot if we don't have to, + # BUT strictly speaking, holding the semaphore while waiting for rate limits + # prevents queue jumping. + try: + await self._wait_for_token() + except Exception: + # If rate limiter fails/cancels, release semaphore + self._semaphore.release() + raise + + wait_duration = time.monotonic() - start + if wait_duration > 1.0: + logger.warning("[%s] Traffic control wait: %.2fs" % (self.provider_name, wait_duration)) + + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + """Release concurrency slot.""" + self._semaphore.release() + return None + + +__all__ = ["TrafficController"] diff --git a/src/services/llm/types.py b/src/services/llm/types.py index 88c62401e..09f64563e 100644 --- a/src/services/llm/types.py +++ b/src/services/llm/types.py @@ -1,28 +1,53 @@ -# -*- coding: utf-8 -*- -from typing import Any, AsyncGenerator, Dict, Optional +"""Shared LLM response data models.""" + +from collections.abc import AsyncGenerator from pydantic import BaseModel, Field +from src.logging import get_logger + +logger = get_logger(__name__) + class TutorResponse(BaseModel): + """LLM completion response container.""" + content: str - raw_response: Dict[str, Any] - usage: Dict[str, int] = Field( - default_factory=lambda: {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0} + raw_response: dict[str, object] = Field(default_factory=dict) + usage: dict[str, int] = Field( + default_factory=lambda: { + "prompt_tokens": 0, + "completion_tokens": 0, + "total_tokens": 0, + } ) - provider: str - model: str - finish_reason: Optional[str] = None + provider: str = "" + model: str = "" + finish_reason: str | None = None cost_estimate: float = 0.0 class TutorStreamChunk(BaseModel): - content: str + """Chunk emitted during streamed LLM responses.""" + delta: str - provider: str - model: str + content: str = "" + provider: str = "" + model: str = "" is_complete: bool = False - usage: Optional[Dict[str, int]] = None + usage: dict[str, int] | None = None AsyncStreamGenerator = AsyncGenerator[TutorStreamChunk, None] + +# Backwards-compatible type aliases used by some callers/tests. +LLMResponse = TutorResponse +StreamChunk = TutorStreamChunk + +__all__ = [ + "AsyncStreamGenerator", + "LLMResponse", + "StreamChunk", + "TutorResponse", + "TutorStreamChunk", +] diff --git a/src/services/llm/utils.py b/src/services/llm/utils.py index 859e18a7e..fe5f24448 100644 --- a/src/services/llm/utils.py +++ b/src/services/llm/utils.py @@ -3,16 +3,17 @@ LLM Utilities ============= -Utility functions for LLM service: -- URL handling for local and cloud servers -- Response content extraction -- Thinking tags cleaning +Shared helpers for URL handling, response parsing, and content cleanup. """ -import re -from typing import Any, Optional +from __future__ import annotations + +from collections.abc import Mapping, Sequence +import ipaddress +import os +import re +from urllib.parse import urlparse -# Known cloud provider domains (should never be treated as local) CLOUD_DOMAINS = [ ".openai.com", ".anthropic.com", @@ -28,145 +29,111 @@ CLOUD_DOMAINS = [ ".perplexity.ai", ] -# Common local server ports LOCAL_PORTS = [ - ":1234", # LM Studio - ":11434", # Ollama - ":8000", # vLLM - ":8080", # llama.cpp - ":5000", # Common dev port - ":3000", # Common dev port - ":8001", # Alternative vLLM - ":5001", # Alternative dev port + ":1234", + ":11434", + ":8000", + ":8080", + ":5000", + ":3000", + ":8001", + ":5001", ] -# Local hostname indicators LOCAL_HOSTS = [ "localhost", "127.0.0.1", - "0.0.0.0", + "0.0.0.0", # nosec B104 ] -# Ports that need /v1 suffix for OpenAI compatibility V1_SUFFIX_PORTS = { - ":11434", # Ollama - ":1234", # LM Studio - ":8000", # vLLM - ":8001", # Alternative vLLM - ":8080", # llama.cpp + ":11434", + ":1234", + ":8000", + ":8001", + ":8080", } -def is_local_llm_server(base_url: str) -> bool: +def is_local_llm_server(base_url: str, allow_private: bool | None = None) -> bool: """ - Check if the given URL points to a local LLM server. - - Detects local servers by: - 1. Checking for local hostnames (localhost, 127.0.0.1, 0.0.0.0) - 2. Checking for common local LLM server ports - 3. Excluding known cloud provider domains + Determine whether a URL points to a local LLM server. Args: - base_url: The base URL to check + base_url: URL to inspect. + allow_private: Optional override to treat private IPs as local. Returns: - True if the URL appears to be a local LLM server + True when the URL looks local. """ if not base_url: return False + if allow_private is None: + env_value = os.environ.get("LLM_TREAT_PRIVATE_AS_LOCAL") + if env_value is not None: + allow_private = env_value.strip().lower() in ("1", "true", "yes") + base_url_lower = base_url.lower() - - # First, exclude known cloud providers - for domain in CLOUD_DOMAINS: - if domain in base_url_lower: - return False - - # Check for local hostname indicators - for host in LOCAL_HOSTS: - if host in base_url_lower: - return True - - # Check for common local server ports - for port in LOCAL_PORTS: - if port in base_url_lower: - return True - - return False - - -def _needs_v1_suffix(url: str) -> bool: - """ - Check if the URL needs /v1 suffix for OpenAI compatibility. - - Most local LLM servers (Ollama, LM Studio, vLLM, llama.cpp) expose - OpenAI-compatible endpoints at /v1. - - Args: - url: The URL to check - - Returns: - True if /v1 should be appended - """ - if not url: + if any(domain in base_url_lower for domain in CLOUD_DOMAINS): return False - url_lower = url.lower() + parsed = urlparse(base_url) + hostname = parsed.hostname or parsed.netloc + if not hostname: + hostname = base_url - # Skip if already has /v1 - if url_lower.endswith("/v1"): - return False - - # Only add /v1 for local servers with known ports that need it - if not is_local_llm_server(url): - return False - - # Check if URL contains any port that needs /v1 suffix - # Also check for "ollama" in URL (but not ollama.com cloud service) - is_ollama = "ollama" in url_lower and "ollama.com" not in url_lower - if is_ollama: + hostname_lower = hostname.lower() + if any(host in hostname_lower for host in LOCAL_HOSTS): return True - return any(port in url_lower for port in V1_SUFFIX_PORTS) + try: + ip = ipaddress.ip_address(hostname) + if ip.is_loopback: + return True + if allow_private and ip.is_private: + return True + except ValueError: + pass + + return any(port in base_url_lower for port in LOCAL_PORTS) + + +def _needs_v1_suffix(base_url: str) -> bool: + """Return True when base_url should receive a /v1 suffix.""" + return any(port in base_url for port in V1_SUFFIX_PORTS) and not base_url.endswith("/v1") def sanitize_url(base_url: str, model: str = "") -> str: """ - Sanitize base URL for OpenAI-compatible APIs, with special handling for local LLM servers. - - Handles: - - Ollama (port 11434) - - LM Studio (port 1234) - - vLLM (port 8000) - - llama.cpp (port 8080) - - Other localhost OpenAI-compatible servers + Sanitize a base URL, normalizing scheme and removing known endpoints. Args: - base_url: The base URL to sanitize - model: Optional model name (unused, kept for API compatibility) + base_url: Base URL. + model: Unused (kept for API compatibility). Returns: - Sanitized URL string + Sanitized base URL. """ if not base_url: - return base_url + return "" + + if not re.match(r"^[a-zA-Z]+://", base_url): + base_url = f"http://{base_url}" url = base_url.rstrip("/") - - # Ensure URL has a protocol (default to http for local servers) if url and not url.startswith(("http://", "https://")): url = "http://" + url - # Standard OpenAI client library is strict about URLs: - # - No trailing slashes - # - No /chat/completions or /completions/messages/embeddings suffixes - # (it adds these automatically) - for suffix in ["/chat/completions", "/completions", "/messages", "/embeddings"]: + for suffix in [ + "/chat/completions", + "/completions", + "/messages", + "/embeddings", + ]: if url.endswith(suffix): - url = url[: -len(suffix)] - url = url.rstrip("/") + url = url[: -len(suffix)].rstrip("/") - # For local LLM servers, ensure /v1 is present for OpenAI compatibility if _needs_v1_suffix(url): url = url.rstrip("/") + "/v1" @@ -175,78 +142,58 @@ def sanitize_url(base_url: str, model: str = "") -> str: def clean_thinking_tags( content: str, - binding: Optional[str] = None, - model: Optional[str] = None, + binding: str | None = None, + model: str | None = None, ) -> str: - """ - Remove thinking tags from model output. - - Some reasoning models (DeepSeek, Qwen, etc.) include ... blocks - that should be stripped from the final response. - - Args: - content: Raw model output - binding: Provider binding name (optional, for capability check) - model: Model name (optional, for capability check) - - Returns: - Cleaned content without thinking tags - """ + """Remove tags from model output.""" if not content: - return content + return "" - # Check if model produces thinking tags (if binding/model provided) - if binding: - # Lazy import to avoid circular dependency - from .capabilities import has_thinking_tags - - if not has_thinking_tags(binding, model): - return content - - # Remove ... blocks - if "" in content: - content = re.sub(r".*?", "", content, flags=re.DOTALL) - - return content.strip() + pattern = re.compile(r".*?", re.DOTALL | re.IGNORECASE) + cleaned = re.sub(pattern, "", content) + return cleaned.strip() def build_chat_url( base_url: str, - api_version: Optional[str] = None, - binding: Optional[str] = None, + api_version: str | None = None, + binding: str | None = None, ) -> str: - """ - Build the full chat completions endpoint URL. + """Build a chat-completions endpoint URL.""" + base_url = base_url.rstrip("/") + binding_lower = (binding or "openai").lower() - Handles: - - Adding /chat/completions suffix for OpenAI-compatible endpoints - - Adding /messages suffix for Anthropic endpoints - - Adding api-version query parameter for Azure OpenAI + if binding_lower in {"anthropic", "claude"}: + url = f"{base_url}/messages" + elif binding_lower == "cohere": + url = f"{base_url}/chat" + else: + url = f"{base_url}/chat/completions" - Args: - base_url: Base URL (should be sanitized first) - api_version: API version for Azure OpenAI (optional) - binding: Provider binding name (optional, for Anthropic detection) + if api_version: + separator = "&" if "?" in url else "?" + url = f"{url}{separator}api-version={api_version}" - Returns: - Full endpoint URL - """ + return url + + +def build_completion_url( + base_url: str, + api_version: str | None = None, + binding: str | None = None, +) -> str: + """Build a legacy completions endpoint URL.""" if not base_url: return base_url url = base_url.rstrip("/") - - # Anthropic uses /messages endpoint binding_lower = (binding or "").lower() - if binding_lower in ["anthropic", "claude"]: - if not url.endswith("/messages"): - url += "/messages" - else: - # OpenAI-compatible endpoints use /chat/completions - if not url.endswith("/chat/completions"): - url += "/chat/completions" + if binding_lower in {"anthropic", "claude"}: + raise ValueError("Anthropic does not support /completions endpoint") + + if not url.endswith("/completions"): + url += "/completions" - # Add api-version for Azure OpenAI if api_version: separator = "&" if "?" in url else "?" url += f"{separator}api-version={api_version}" @@ -254,62 +201,65 @@ def build_chat_url( return url -def extract_response_content(message: dict[str, Any]) -> str: - """ - Extract content from LLM response message. - - Handles different response formats from various models: - - Standard content field - - Reasoning models that use reasoning_content, reasoning, or thought fields - - Args: - message: Message dict from LLM response (e.g., choices[0].message) - - Returns: - Extracted content string - """ - if not message: +def extract_response_content(message: object) -> str: + """Extract textual content from response payloads.""" + if message is None: return "" - content = message.get("content", "") + if isinstance(message, str): + return message - # Handle reasoning models that return content in different fields - if not content: - content = ( - message.get("reasoning_content") - or message.get("reasoning") - or message.get("thought") - or "" - ) + if isinstance(message, Mapping): + content = message.get("content") + if isinstance(content, list): + parts: list[str] = [] + for part in content: + if isinstance(part, Mapping) and "text" in part: + parts.append(str(part["text"])) + elif isinstance(part, str): + parts.append(part) + return "".join(parts) + if content is not None: + return str(content) + if "text" in message: + return str(message["text"]) - return content + return str(message) -def build_auth_headers( - api_key: Optional[str], - binding: Optional[str] = None, -) -> dict[str, str]: - """ - Build authentication headers for LLM API requests. +def _normalize_model_name(entry: object) -> str | None: + if isinstance(entry, str): + return entry + if isinstance(entry, Mapping): + for key in ("id", "name", "model"): + value = entry.get(key) + if isinstance(value, str): + return value + return None - Args: - api_key: API key - binding: Provider binding name (for provider-specific headers) - Returns: - Headers dict - """ +def collect_model_names(entries: Sequence[object]) -> list[str]: + """Collect model names from provider payloads.""" + names: list[str] = [] + for entry in entries: + name = _normalize_model_name(entry) + if name: + names.append(name) + return names + + +def build_auth_headers(api_key: str | None, binding: str | None = None) -> dict[str, str]: + """Build auth headers for provider requests.""" headers = {"Content-Type": "application/json"} if not api_key: return headers binding_lower = (binding or "").lower() - - if binding_lower in ["anthropic", "claude"]: + if binding_lower in {"anthropic", "claude"}: headers["x-api-key"] = api_key headers["anthropic-version"] = "2023-06-01" - elif binding_lower == "azure_openai": + elif binding_lower in {"azure_openai", "azure"}: headers["api-key"] = api_key else: headers["Authorization"] = f"Bearer {api_key}" @@ -318,15 +268,14 @@ def build_auth_headers( __all__ = [ - # URL utilities "sanitize_url", "is_local_llm_server", "build_chat_url", + "build_completion_url", "build_auth_headers", - # Content utilities + "collect_model_names", "clean_thinking_tags", "extract_response_content", - # Constants "CLOUD_DOMAINS", "LOCAL_PORTS", "LOCAL_HOSTS", diff --git a/src/utils/network/circuit_breaker.py b/src/utils/network/circuit_breaker.py index 299d3bfd5..d56333f9e 100644 --- a/src/utils/network/circuit_breaker.py +++ b/src/utils/network/circuit_breaker.py @@ -16,6 +16,7 @@ class CircuitBreaker: """ def __init__(self, failure_threshold: int = 5, recovery_timeout: int = 60): + """Initialize circuit breaker state for providers.""" self.failure_threshold = failure_threshold self.recovery_timeout = recovery_timeout self.failure_count: Dict[str, int] = {} @@ -32,23 +33,25 @@ class CircuitBreaker: elif state == "open": if time.time() - self.last_failure_time.get(provider, 0) > self.recovery_timeout: self.state[provider] = "half-open" - logger.info(f"Circuit breaker for {provider} entering half-open state") + logger.info("Circuit breaker for %s entering half-open state" % provider) return True return False elif state == "half-open": return True + logger.error("Circuit breaker for %s has unexpected state: %s" % (provider, state)) + return False - def record_success(self, provider: str): + def record_success(self, provider: str) -> None: """Record successful call.""" with self.lock: if self.state.get(provider) == "half-open": self.state[provider] = "closed" self.failure_count[provider] = 0 - logger.info(f"Circuit breaker for {provider} closed") + logger.info("Circuit breaker for %s closed" % provider) elif self.state.get(provider) == "closed": self.failure_count[provider] = 0 - def record_failure(self, provider: str): + def record_failure(self, provider: str) -> None: """Record failed call.""" with self.lock: self.failure_count[provider] = self.failure_count.get(provider, 0) + 1 @@ -56,7 +59,8 @@ class CircuitBreaker: if self.failure_count[provider] >= self.failure_threshold: self.state[provider] = "open" logger.warning( - f"Circuit breaker for {provider} opened due to {self.failure_count[provider]} failures" + "Circuit breaker for %s opened due to %s failures" + % (provider, self.failure_count[provider]) ) @@ -64,7 +68,7 @@ class CircuitBreaker: circuit_breaker = CircuitBreaker() -def alert_callback(provider: str, rate: float): +def alert_callback(provider: str, _rate: float) -> None: """Alert callback to trigger circuit breaker.""" circuit_breaker.record_failure(provider) @@ -74,6 +78,11 @@ def is_call_allowed(provider: str) -> bool: return circuit_breaker.call(provider) -def record_call_success(provider: str): +def record_call_success(provider: str) -> None: """Record successful call.""" circuit_breaker.record_success(provider) + + +def record_call_failure(provider: str) -> None: + """Record failed call.""" + circuit_breaker.record_failure(provider) diff --git a/tests/services/llm/test_base_provider.py b/tests/services/llm/test_base_provider.py new file mode 100644 index 000000000..356fd7eaa --- /dev/null +++ b/tests/services/llm/test_base_provider.py @@ -0,0 +1,38 @@ +"""Tests for BaseLLMProvider retry behavior.""" + +import asyncio + +from src.services.llm.config import LLMConfig +from src.services.llm.exceptions import LLMRateLimitError +from src.services.llm.providers.base_provider import BaseLLMProvider + + +class DummyProvider(BaseLLMProvider): + """Minimal provider used for retry tests.""" + + async def complete(self, prompt: str, **kwargs: object): + raise NotImplementedError + + async def stream(self, prompt: str, **kwargs: object): + raise NotImplementedError + + +def test_execute_with_retry_succeeds_after_rate_limit() -> None: + """execute_with_retry should retry on rate limit errors.""" + config = LLMConfig(model="test", api_key="", base_url="http://localhost:1234") + provider = DummyProvider(config) + attempts = {"count": 0} + + async def _call() -> str: + attempts["count"] += 1 + if attempts["count"] < 3: + raise LLMRateLimitError("rate limited", provider="test") + return "ok" + + async def _no_sleep(_delay: float) -> None: + return None + + result = asyncio.run(provider.execute_with_retry(_call, max_retries=2, sleep=_no_sleep)) + + assert result == "ok" + assert attempts["count"] == 3 diff --git a/tests/services/llm/test_capabilities.py b/tests/services/llm/test_capabilities.py new file mode 100644 index 000000000..d26219759 --- /dev/null +++ b/tests/services/llm/test_capabilities.py @@ -0,0 +1,26 @@ +"""Tests for LLM capability helpers.""" + +from src.services.llm.capabilities import ( + get_capability, + get_effective_temperature, + has_thinking_tags, + supports_response_format, +) + + +def test_model_override_capability() -> None: + """Model overrides should take precedence over provider defaults.""" + assert supports_response_format("openai", "deepseek-reasoner") is False + assert has_thinking_tags("openai", "deepseek-reasoner") is True + + +def test_capability_fallback_default() -> None: + """Unknown provider should fall back to defaults and explicit values.""" + assert get_capability("unknown", "supports_streaming") is True + assert get_capability("unknown", "nonexistent", default=False) is False + + +def test_effective_temperature_override() -> None: + """Forced temperature overrides should be applied for reasoning models.""" + assert get_effective_temperature("openai", "gpt-5") == 1.0 + assert get_effective_temperature("openai", "gpt-4o", requested_temp=0.4) == 0.4 diff --git a/tests/services/llm/test_client.py b/tests/services/llm/test_client.py new file mode 100644 index 000000000..9986b6b1f --- /dev/null +++ b/tests/services/llm/test_client.py @@ -0,0 +1,124 @@ +"""Tests for the LLM client wrapper.""" + +from __future__ import annotations + +import sys +import types + +from _pytest.monkeypatch import MonkeyPatch +import pytest + +from src.services.llm.client import LLMClient +from src.services.llm.config import LLMConfig + + +@pytest.mark.asyncio +async def test_client_complete_uses_factory(monkeypatch: MonkeyPatch) -> None: + """Client complete should delegate to factory.complete.""" + config = LLMConfig(model="model", api_key="key", base_url="https://example.com") + client = LLMClient(config) + + async def _fake_complete(**_kwargs: object) -> str: + return "ok" + + monkeypatch.setattr("src.services.llm.factory.complete", _fake_complete) + + result = await client.complete("hello") + + assert result == "ok" + + +def test_client_complete_sync(monkeypatch: MonkeyPatch) -> None: + """complete_sync should run in a fresh event loop.""" + config = LLMConfig(model="model", api_key="key", base_url="https://example.com") + client = LLMClient(config) + + async def _fake_complete( + _prompt: str, + _system_prompt: str | None = None, + _history: list[dict[str, str]] | None = None, + **_kwargs: object, + ) -> str: + return "ok" + + monkeypatch.setattr(client, "complete", _fake_complete) + + assert client.complete_sync("hello") == "ok" + + +@pytest.mark.asyncio +async def test_client_complete_sync_running_loop() -> None: + """complete_sync should raise when called from a running event loop.""" + config = LLMConfig(model="model", api_key="key", base_url="https://example.com") + client = LLMClient(config) + + with pytest.raises(RuntimeError): + client.complete_sync("hello") + + +def test_client_get_model_func_openai(monkeypatch: MonkeyPatch) -> None: + """OpenAI-style model func should call openai_complete_if_cache.""" + config = LLMConfig(model="model", api_key="key", base_url="https://example.com") + client = LLMClient(config) + + module = types.ModuleType("lightrag.llm.openai") + module.openai_complete_if_cache = lambda *_args, **_kwargs: "ok" + monkeypatch.setitem(sys.modules, "lightrag", types.ModuleType("lightrag")) + monkeypatch.setitem(sys.modules, "lightrag.llm", types.ModuleType("lightrag.llm")) + monkeypatch.setitem(sys.modules, "lightrag.llm.openai", module) + + monkeypatch.setattr("src.services.llm.client.system_in_messages", lambda *_a: True) + + func = client.get_model_func() + + assert func("hello") == "ok" + + +def test_client_get_model_func_factory(monkeypatch: MonkeyPatch) -> None: + """Non-OpenAI providers should route via factory.complete.""" + config = LLMConfig(model="model", api_key="key", base_url="https://example.com") + client = LLMClient(config) + + def _fake_complete(**_kwargs: object) -> str: + return "ok" + + monkeypatch.setattr("src.services.llm.factory.complete", _fake_complete) + monkeypatch.setattr("src.services.llm.client.system_in_messages", lambda *_a: False) + + func = client.get_model_func() + + assert func("hello") == "ok" + + +def test_client_get_vision_model_func_factory(monkeypatch: MonkeyPatch) -> None: + """Vision model func should route via factory for non-OpenAI bindings.""" + config = LLMConfig(model="model", api_key="key", base_url="https://example.com") + client = LLMClient(config) + + def _fake_complete(**_kwargs: object) -> str: + return "ok" + + monkeypatch.setattr("src.services.llm.factory.complete", _fake_complete) + monkeypatch.setattr("src.services.llm.client.system_in_messages", lambda *_a: False) + + func = client.get_vision_model_func() + + assert func("hello") == "ok" + + +def test_client_get_vision_model_func_openai(monkeypatch: MonkeyPatch) -> None: + """OpenAI-style vision model func should call openai_complete_if_cache.""" + config = LLMConfig(model="model", api_key="key", base_url="https://example.com") + client = LLMClient(config) + + module = types.ModuleType("lightrag.llm.openai") + module.openai_complete_if_cache = lambda *_args, **_kwargs: "ok" + monkeypatch.setitem(sys.modules, "lightrag", types.ModuleType("lightrag")) + monkeypatch.setitem(sys.modules, "lightrag.llm", types.ModuleType("lightrag.llm")) + monkeypatch.setitem(sys.modules, "lightrag.llm.openai", module) + + monkeypatch.setattr("src.services.llm.client.system_in_messages", lambda *_a: True) + + func = client.get_vision_model_func() + + assert func("hello", messages=[{"role": "user", "content": "hi"}]) == "ok" diff --git a/tests/services/llm/test_cloud_provider.py b/tests/services/llm/test_cloud_provider.py new file mode 100644 index 000000000..8abb4f5ee --- /dev/null +++ b/tests/services/llm/test_cloud_provider.py @@ -0,0 +1,222 @@ +"""Tests for cloud provider helpers.""" + +from __future__ import annotations + +import importlib +from types import TracebackType + +from _pytest.monkeypatch import MonkeyPatch +import pytest + +from src.services.llm.exceptions import LLMAPIError + +cloud_provider = importlib.import_module("src.services.llm.cloud_provider") + + +class _AsyncIterator: + def __init__(self, items: list[bytes]) -> None: + self._items = items + self._index = 0 + + def __aiter__(self): + return self + + async def __anext__(self) -> bytes: + if self._index >= len(self._items): + raise StopAsyncIteration + item = self._items[self._index] + self._index += 1 + return item + + +class _FakeResponse: + def __init__(self, status: int, json_data: dict[str, object]) -> None: + self.status = status + self._json_data = json_data + self.content = _AsyncIterator([]) + + async def __aenter__(self): + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + return None + + async def json(self): + return self._json_data + + async def text(self) -> str: + return "" + + +class _FakeStreamResponse(_FakeResponse): + def __init__(self, status: int, lines: list[bytes]) -> None: + super().__init__(status, {}) + self.content = _AsyncIterator(lines) + + +class _FakeSession: + def __init__(self, response: _FakeResponse) -> None: + self._response = response + + async def __aenter__(self): + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + return None + + def post(self, _url: str, **_kwargs: object) -> _FakeResponse: + return self._response + + def get(self, _url: str, **_kwargs: object) -> _FakeResponse: + return self._response + + +@pytest.mark.asyncio +async def test_cloud_complete_fallback(monkeypatch: MonkeyPatch) -> None: + """Fallback path should parse JSON content from aiohttp responses.""" + fake_response = _FakeResponse( + 200, + { + "choices": [ + {"message": {"content": "ok"}}, + ] + }, + ) + + async def _no_cache(*_args: object, **_kwargs: object) -> None: + return None + + monkeypatch.setattr(cloud_provider, "_get_openai_complete_if_cache", lambda: _no_cache) + monkeypatch.setattr( + cloud_provider.aiohttp, + "ClientSession", + lambda *args, **kwargs: _FakeSession(fake_response), + ) + + result = await cloud_provider.complete( + prompt="hello", + model="gpt-test", + api_key="", + base_url="https://api.openai.com/v1", + binding="openai", + ) + + assert result == "ok" + + +@pytest.mark.asyncio +async def test_cloud_stream_yields_chunks(monkeypatch: MonkeyPatch) -> None: + """Streaming should yield delta content from SSE lines.""" + lines = [ + b'data: {"choices": [{"delta": {"content": "hi"}}]}\n\n', + b"data: [DONE]\n\n", + ] + fake_response = _FakeStreamResponse(200, lines) + + monkeypatch.setattr( + cloud_provider.aiohttp, + "ClientSession", + lambda *args, **kwargs: _FakeSession(fake_response), + ) + + chunks = [] + async for chunk in cloud_provider.stream( + prompt="hello", + model="gpt-test", + api_key="", + base_url="https://api.openai.com/v1", + binding="openai", + ): + chunks.append(chunk) + + assert "".join(chunks) == "hi" + + +@pytest.mark.asyncio +async def test_cloud_complete_error(monkeypatch: MonkeyPatch) -> None: + """Non-200 responses should raise LLMAPIError.""" + response = _FakeResponse(500, {}) + + async def _no_cache(*_args: object, **_kwargs: object) -> None: + return None + + monkeypatch.setattr(cloud_provider, "_get_openai_complete_if_cache", lambda: _no_cache) + monkeypatch.setattr( + cloud_provider.aiohttp, + "ClientSession", + lambda *args, **kwargs: _FakeSession(response), + ) + + with pytest.raises(LLMAPIError): + await cloud_provider.complete( + prompt="hello", + model="gpt-test", + api_key="", + base_url="https://api.openai.com/v1", + binding="openai", + ) + + +@pytest.mark.asyncio +async def test_cloud_complete_cached(monkeypatch: MonkeyPatch) -> None: + """Cache hit should return cached content without fallback calls.""" + + async def _cached(*_args: object, **_kwargs: object) -> str: + return "cached" + + monkeypatch.setattr(cloud_provider, "_get_openai_complete_if_cache", lambda: _cached) + + result = await cloud_provider.complete( + prompt="hello", + model="gpt-test", + api_key="", + base_url="https://api.openai.com/v1", + binding="openai", + ) + + assert result == "cached" + + +def test_cloud_helpers(monkeypatch: MonkeyPatch) -> None: + """Helper coercion and SSL connector paths should behave as expected.""" + assert cloud_provider._coerce_float(True, 0.5) == 0.5 + assert cloud_provider._coerce_float(2, 0.5) == 2.0 + assert cloud_provider._coerce_int(True, None) is None + assert cloud_provider._coerce_int(3, None) == 3 + + monkeypatch.delenv("DISABLE_SSL_VERIFY", raising=False) + assert cloud_provider._get_aiohttp_connector() is None + + class _FakeConnector: + pass + + monkeypatch.setenv("DISABLE_SSL_VERIFY", "1") + monkeypatch.setitem(cloud_provider.__dict__, "_ssl_warning_logged", False) + monkeypatch.setattr(cloud_provider.aiohttp, "TCPConnector", lambda **_kw: _FakeConnector()) + connector = cloud_provider._get_aiohttp_connector() + assert connector is not None + + +@pytest.mark.asyncio +async def test_cloud_fetch_models(monkeypatch: MonkeyPatch) -> None: + """Fetch models should parse model lists from the response.""" + response = _FakeResponse(200, {"data": [{"id": "m1"}, {"id": "m2"}]}) + monkeypatch.setattr( + cloud_provider.aiohttp, + "ClientSession", + lambda *args, **kwargs: _FakeSession(response), + ) + + models = await cloud_provider.fetch_models("https://api.openai.com/v1") + + assert models == ["m1", "m2"] diff --git a/tests/services/llm/test_config_module.py b/tests/services/llm/test_config_module.py new file mode 100644 index 000000000..78c15bba4 --- /dev/null +++ b/tests/services/llm/test_config_module.py @@ -0,0 +1,67 @@ +"""Tests for LLM configuration helpers.""" + +from __future__ import annotations + +import os +import sys + +import pytest + +from src.services.llm import config as config_module +from src.services.llm.config import LLMConfig +from src.services.llm.exceptions import LLMConfigError + + +def _reset_config_cache() -> None: + config_module._LLM_CONFIG_CACHE = None + + +def test_get_llm_config_from_env(monkeypatch) -> None: + """Environment-based config loading should populate required fields.""" + _reset_config_cache() + fake_module = type("_Config", (), {"get_active_llm_config": lambda: None}) + monkeypatch.setitem(sys.modules, "src.services.config", fake_module) + monkeypatch.setenv("LLM_MODEL", "gpt-test") + monkeypatch.setenv("LLM_HOST", "https://api.openai.com") + monkeypatch.setenv("LLM_API_KEY", "key") + + config = config_module.get_llm_config() + + assert isinstance(config, LLMConfig) + assert config.model == "gpt-test" + assert config.base_url == "https://api.openai.com" + assert config.api_key == "key" + + +def test_initialize_environment_sets_openai_env(monkeypatch) -> None: + """initialize_environment should set OpenAI env vars for compatible bindings.""" + monkeypatch.setenv("LLM_BINDING", "openai") + monkeypatch.setenv("LLM_API_KEY", "test-key") + monkeypatch.setenv("LLM_HOST", "https://example.com") + monkeypatch.delenv("OPENAI_API_KEY", raising=False) + monkeypatch.delenv("OPENAI_BASE_URL", raising=False) + + config_module.initialize_environment() + + assert os.environ["OPENAI_API_KEY"] == "test-key" + assert os.environ["OPENAI_BASE_URL"] == "https://example.com" + + +def test_strip_value_handles_quotes() -> None: + """_strip_value should remove surrounding quotes and whitespace.""" + assert config_module._strip_value(" 'value' ") == "value" + + +def test_get_llm_config_missing_env(monkeypatch) -> None: + """Missing required env values should raise LLMConfigError.""" + _reset_config_cache() + monkeypatch.setenv("LLM_MODEL", "") + monkeypatch.setenv("LLM_HOST", "") + monkeypatch.setenv("LLM_API_KEY", "") + monkeypatch.setenv("LLM_BINDING", "openai") + + fake_module = type("_Config", (), {"get_active_llm_config": lambda: None}) + monkeypatch.setitem(sys.modules, "src.services.config", fake_module) + + with pytest.raises(LLMConfigError): + config_module.get_llm_config() diff --git a/tests/services/llm/test_error_mapping.py b/tests/services/llm/test_error_mapping.py new file mode 100644 index 000000000..007bbde8d --- /dev/null +++ b/tests/services/llm/test_error_mapping.py @@ -0,0 +1,42 @@ +"""Tests for LLM error mapping helpers.""" + +from src.services.llm.error_mapping import map_error +from src.services.llm.exceptions import ( + LLMAPIError, + LLMAuthenticationError, + LLMRateLimitError, + ProviderContextWindowError, +) + + +class DummyError(Exception): + """Custom error used for mapping tests.""" + + def __init__(self, message: str, status_code: int | None = None) -> None: + super().__init__(message) + self.status_code = status_code + + +def test_map_error_status_code_auth() -> None: + """401 errors should map to authentication failures.""" + mapped = map_error(DummyError("auth failed", status_code=401), provider="openai") + assert isinstance(mapped, LLMAuthenticationError) + + +def test_map_error_status_code_rate_limit() -> None: + """429 errors should map to rate limit failures.""" + mapped = map_error(DummyError("rate limited", status_code=429), provider="openai") + assert isinstance(mapped, LLMRateLimitError) + + +def test_map_error_message_context_window() -> None: + """Context length errors should map to the provider context window error.""" + mapped = map_error(DummyError("maximum context length exceeded"), provider="openai") + assert isinstance(mapped, ProviderContextWindowError) + + +def test_map_error_falls_back_to_api_error() -> None: + """Unknown errors should fall back to generic API error mapping.""" + mapped = map_error(DummyError("boom", status_code=500), provider="openai") + assert isinstance(mapped, LLMAPIError) + assert mapped.status_code == 500 diff --git a/tests/services/llm/test_registry.py b/tests/services/llm/test_registry.py new file mode 100644 index 000000000..56d7a4ebc --- /dev/null +++ b/tests/services/llm/test_registry.py @@ -0,0 +1,21 @@ +"""Tests for provider registry utilities.""" + +from src.services.llm import registry + + +def test_registry_register_and_lookup() -> None: + """Registering a provider should make it discoverable.""" + + class _Provider: + pass + + name = "registry_test" + registry._provider_registry.pop(name, None) + try: + decorated = registry.register_provider(name)(_Provider) + + assert registry.is_provider_registered(name) is True + assert registry.get_provider_class(name) is decorated + assert name in registry.list_providers() + finally: + registry._provider_registry.pop(name, None) diff --git a/tests/services/llm/test_routing_provider.py b/tests/services/llm/test_routing_provider.py new file mode 100644 index 000000000..9fb2789c2 --- /dev/null +++ b/tests/services/llm/test_routing_provider.py @@ -0,0 +1,70 @@ +"""Tests for the routing provider wrapper.""" + +import asyncio +from collections.abc import AsyncGenerator + +from src.services.llm.config import LLMConfig +from src.services.llm.providers.routing import RoutingProvider + + +async def _collect_stream(provider: RoutingProvider) -> list[object]: + chunks: list[object] = [] + async for chunk in provider.stream("hello", max_retries=0): + chunks.append(chunk) + return chunks + + +def test_routing_provider_local_complete(monkeypatch) -> None: + """Routing provider should delegate to local provider for local URLs.""" + + async def _fake_local_complete(**_kwargs: object) -> str: + return "local" + + monkeypatch.setattr( + "src.services.llm.local_provider.complete", + _fake_local_complete, + ) + + config = LLMConfig(model="test", api_key="", base_url="http://localhost:11434") + provider = RoutingProvider(config) + result = asyncio.run(provider.complete("hello", use_cache=False, max_retries=0)) + + assert result.content == "local" + assert result.provider == "local" + + +def test_routing_provider_cloud_complete(monkeypatch) -> None: + """Routing provider should delegate to cloud provider for remote URLs.""" + + async def _fake_cloud_complete(**_kwargs: object) -> str: + return "cloud" + + monkeypatch.setattr( + "src.services.llm.cloud_provider.complete", + _fake_cloud_complete, + ) + + config = LLMConfig(model="test", api_key="", base_url="https://api.openai.com") + provider = RoutingProvider(config) + result = asyncio.run(provider.complete("hello", use_cache=False, max_retries=0)) + + assert result.content == "cloud" + assert result.provider == "routing" + + +def test_routing_provider_stream(monkeypatch) -> None: + """Routing provider should emit accumulated stream chunks.""" + + async def _fake_stream(**_kwargs: object) -> AsyncGenerator[str, None]: + yield "A" + yield "B" + + monkeypatch.setattr("src.services.llm.local_provider.stream", _fake_stream) + + config = LLMConfig(model="test", api_key="", base_url="http://localhost:1234") + provider = RoutingProvider(config) + chunks = asyncio.run(_collect_stream(provider)) + + assert chunks + assert chunks[-1].is_complete is True + assert chunks[-1].content == "AB" diff --git a/tests/services/llm/test_telemetry.py b/tests/services/llm/test_telemetry.py new file mode 100644 index 000000000..1c88b4ed7 --- /dev/null +++ b/tests/services/llm/test_telemetry.py @@ -0,0 +1,49 @@ +"""Tests for telemetry decorator behavior.""" + +from _pytest.monkeypatch import MonkeyPatch +import pytest + +from src.services.llm import telemetry + + +class _FakeLogger: + def __init__(self) -> None: + self.messages: list[str] = [] + + def debug(self, message: str, *args: object, **_kwargs: object) -> None: + self.messages.append(message % args if args else message) + + def warning(self, message: str, *args: object, **_kwargs: object) -> None: + self.messages.append(message % args if args else message) + + +@pytest.mark.asyncio +async def test_track_llm_call_success(monkeypatch: MonkeyPatch) -> None: + """Successful calls should emit debug log entries.""" + fake_logger = _FakeLogger() + monkeypatch.setattr(telemetry, "logger", fake_logger) + + @telemetry.track_llm_call("test") + async def _func() -> str: + return "ok" + + result = await _func() + + assert result == "ok" + assert any("completed successfully" in msg for msg in fake_logger.messages) + + +@pytest.mark.asyncio +async def test_track_llm_call_failure(monkeypatch: MonkeyPatch) -> None: + """Failures should emit warning log entries.""" + fake_logger = _FakeLogger() + monkeypatch.setattr(telemetry, "logger", fake_logger) + + @telemetry.track_llm_call("test") + async def _func() -> str: + raise RuntimeError("boom") + + with pytest.raises(RuntimeError): + await _func() + + assert any("failed" in msg for msg in fake_logger.messages) diff --git a/tests/services/llm/test_traffic_control.py b/tests/services/llm/test_traffic_control.py new file mode 100644 index 000000000..b46e0b10d --- /dev/null +++ b/tests/services/llm/test_traffic_control.py @@ -0,0 +1,20 @@ +"""Tests for traffic control behavior.""" + +import pytest + +from src.services.llm.traffic_control import TrafficController + + +@pytest.mark.asyncio +async def test_traffic_control_context() -> None: + """Traffic control context manager should acquire and release slots.""" + controller = TrafficController( + provider_name="test", + max_concurrency=1, + requests_per_minute=60, + ) + + async with controller: + assert controller._semaphore.locked() is True + + assert controller._semaphore.locked() is False diff --git a/tests/services/llm/test_utils.py b/tests/services/llm/test_utils.py new file mode 100644 index 000000000..d484e5621 --- /dev/null +++ b/tests/services/llm/test_utils.py @@ -0,0 +1,77 @@ +"""Tests for LLM utility helpers.""" + +import pytest + +from src.services.llm.utils import ( + build_auth_headers, + build_chat_url, + build_completion_url, + clean_thinking_tags, + collect_model_names, + extract_response_content, + is_local_llm_server, + sanitize_url, +) + + +def test_sanitize_url_normalizes_local_host() -> None: + """Local hostnames should be normalized and include /v1 when needed.""" + url = sanitize_url("localhost:11434") + assert url == "http://localhost:11434/v1" + + +def test_build_chat_url_handles_provider_paths() -> None: + """Provider-specific endpoints should resolve correctly.""" + assert build_chat_url("https://api.anthropic.com", binding="anthropic") == ( + "https://api.anthropic.com/messages" + ) + assert build_chat_url("https://api.cohere.ai", binding="cohere") == ( + "https://api.cohere.ai/chat" + ) + + +def test_is_local_llm_server_private_ip(monkeypatch) -> None: + """Private IPs are treated as local when the override is enabled.""" + monkeypatch.setenv("LLM_TREAT_PRIVATE_AS_LOCAL", "true") + assert is_local_llm_server("http://10.0.0.5:1234") is True + + +def test_is_local_llm_server_cloud_domain() -> None: + """Known cloud domains should never be treated as local.""" + assert is_local_llm_server("https://api.openai.com/v1") is False + + +def test_build_completion_url_appends_version() -> None: + """Completion URLs should include api-version when provided.""" + url = build_completion_url("https://api.openai.com", api_version="2024-01-01") + assert url.endswith("/completions?api-version=2024-01-01") + + +def test_build_completion_url_rejects_anthropic() -> None: + """Anthropic bindings should raise when requesting /completions.""" + with pytest.raises(ValueError): + build_completion_url("https://api.anthropic.com", binding="anthropic") + + +def test_clean_thinking_tags() -> None: + """Thinking tags should be removed from model output.""" + assert clean_thinking_tags("Hello ignore World") == "Hello World" + + +def test_extract_response_content() -> None: + """Response content extraction should handle mapping payloads.""" + payload = {"content": [{"text": "Hello"}, {"text": "World"}]} + assert extract_response_content(payload) == "HelloWorld" + + +def test_collect_model_names() -> None: + """Model name collection should extract names from payload entries.""" + entries = ["m1", {"id": "m2"}, {"name": "m3"}, {"model": "m4"}] + assert collect_model_names(entries) == ["m1", "m2", "m3", "m4"] + + +def test_build_auth_headers() -> None: + """Auth headers should vary by provider binding.""" + assert build_auth_headers("key", binding="anthropic")["x-api-key"] == "key" + assert build_auth_headers("key", binding="azure")["api-key"] == "key" + assert build_auth_headers("key")["Authorization"] == "Bearer key"