Spaces:
Sleeping
Sleeping
File size: 9,605 Bytes
c280a92 508a7e5 65ab80b c280a92 508a7e5 c280a92 0a7f9b4 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 0a7f9b4 159faf0 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 159faf0 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 159faf0 508a7e5 c280a92 508a7e5 c280a92 159faf0 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 a3b3a5c c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 159faf0 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 c280a92 508a7e5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 |
"""
LLM Service for RAG Application
This module provides integration with Large Language Models through multiple
providers including OpenRouter and Groq, with fallback capabilities and
comprehensive error handling.
Updated: October 18, 2025 - CI/CD pipeline compatibility verification
"""
import logging
import os
import time
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
import requests
from src.llm.llm_configuration_error import LLMConfigurationError
logger = logging.getLogger(__name__)
@dataclass
class LLMConfig:
"""Configuration for LLM providers."""
provider: str # "openrouter" or "groq"
api_key: str
model_name: str
base_url: str
max_tokens: int = 1000
temperature: float = 0.1
timeout: int = 30
@dataclass
class LLMResponse:
"""Standardized response from LLM providers."""
content: str
provider: str
model: str
usage: Dict[str, Any]
response_time: float
success: bool
error_message: Optional[str] = None
class LLMService:
"""
Service for interacting with Large Language Models.
Supports multiple providers with automatic fallback and retry logic.
Designed for corporate policy Q&A with appropriate guardrails.
"""
def __init__(self, configs: List[LLMConfig]):
"""
Initialize LLMService with provider configurations.
Args:
configs: List of LLMConfig objects for different providers
Raises:
ValueError: If no valid configurations provided
"""
if not configs:
raise ValueError("At least one LLM configuration must be provided")
self.configs = configs
self.current_config_index = 0
logger.info(f"LLMService initialized with {len(configs)} provider(s)")
@classmethod
def from_environment(cls) -> "LLMService":
"""
Create LLMService instance from environment variables.
Expected environment variables:
- OPENROUTER_API_KEY: API key for OpenRouter
- GROQ_API_KEY: API key for Groq
Returns:
LLMService instance with available providers
Raises:
ValueError: If no API keys found in environment
"""
configs = []
# OpenRouter configuration
openrouter_key = os.getenv("OPENROUTER_API_KEY")
if openrouter_key:
configs.append(
LLMConfig(
provider="openrouter",
api_key=openrouter_key,
model_name="microsoft/wizardlm-2-8x22b", # Free tier model
base_url="https://openrouter.ai/api/v1",
max_tokens=1000,
temperature=0.1,
)
)
# Groq configuration
groq_key = os.getenv("GROQ_API_KEY")
if groq_key:
configs.append(
LLMConfig(
provider="groq",
api_key=groq_key,
model_name="llama3-8b-8192", # Free tier model
base_url="https://api.groq.com/openai/v1",
max_tokens=1000,
temperature=0.1,
)
)
if not configs:
raise LLMConfigurationError(
"No LLM API keys found in environment. " "Please set OPENROUTER_API_KEY or GROQ_API_KEY"
)
return cls(configs)
def generate_response(self, prompt: str, max_retries: int = 2) -> LLMResponse:
"""
Generate response from LLM with fallback support.
Args:
prompt: Input prompt for the LLM
max_retries: Maximum retry attempts per provider
Returns:
LLMResponse with generated content or error information
"""
last_error = None
# Try each provider configuration
for attempt in range(len(self.configs)):
config = self.configs[self.current_config_index]
try:
logger.debug(f"Attempting generation with {config.provider}")
response = self._call_provider(config, prompt, max_retries)
if response.success:
logger.info(f"Successfully generated response using {config.provider}")
return response
last_error = response.error_message
logger.warning(f"Provider {config.provider} failed: {last_error}")
except Exception as e:
last_error = str(e)
logger.error(f"Error with provider {config.provider}: {last_error}")
# Move to next provider
self.current_config_index = (self.current_config_index + 1) % len(self.configs)
# All providers failed
logger.error("All LLM providers failed")
return LLMResponse(
content="",
provider="none",
model="none",
usage={},
response_time=0.0,
success=False,
error_message=f"All providers failed. Last error: {last_error}",
)
def _call_provider(self, config: LLMConfig, prompt: str, max_retries: int) -> LLMResponse:
"""
Make API call to specific provider with retry logic.
Args:
config: Provider configuration
prompt: Input prompt
max_retries: Maximum retry attempts
Returns:
LLMResponse from the provider
"""
start_time = time.time()
for attempt in range(max_retries + 1):
try:
headers = {
"Authorization": f"Bearer {config.api_key}",
"Content-Type": "application/json",
}
# Add provider-specific headers
if config.provider == "openrouter":
referer_url = "https://github.com/sethmcknight/msse-ai-engineering"
headers["HTTP-Referer"] = referer_url
headers["X-Title"] = "MSSE RAG Application"
payload = {
"model": config.model_name,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": config.max_tokens,
"temperature": config.temperature,
}
response = requests.post(
f"{config.base_url}/chat/completions",
headers=headers,
json=payload,
timeout=config.timeout,
)
response.raise_for_status()
data = response.json()
# Extract response content
content = data["choices"][0]["message"]["content"]
usage = data.get("usage", {})
response_time = time.time() - start_time
return LLMResponse(
content=content,
provider=config.provider,
model=config.model_name,
usage=usage,
response_time=response_time,
success=True,
)
except requests.exceptions.RequestException as e:
logger.warning(f"Request failed for {config.provider} (attempt {attempt + 1}): {e}")
if attempt < max_retries:
time.sleep(2**attempt) # Exponential backoff
continue
return LLMResponse(
content="",
provider=config.provider,
model=config.model_name,
usage={},
response_time=time.time() - start_time,
success=False,
error_message=str(e),
)
except Exception as e:
logger.error(f"Unexpected error with {config.provider}: {e}")
return LLMResponse(
content="",
provider=config.provider,
model=config.model_name,
usage={},
response_time=time.time() - start_time,
success=False,
error_message=str(e),
)
def health_check(self) -> Dict[str, Any]:
"""
Check health status of all configured providers.
Returns:
Dictionary with provider health status
"""
health_status = {}
for config in self.configs:
try:
# Simple test prompt
test_response = self._call_provider(
config,
"Hello, this is a test. Please respond with 'OK'.",
max_retries=1,
)
health_status[config.provider] = {
"status": "healthy" if test_response.success else "unhealthy",
"model": config.model_name,
"response_time": test_response.response_time,
"error": test_response.error_message,
}
except Exception as e:
health_status[config.provider] = {
"status": "unhealthy",
"model": config.model_name,
"response_time": 0.0,
"error": str(e),
}
return health_status
def get_available_providers(self) -> List[str]:
"""Get list of available provider names."""
return [config.provider for config in self.configs]
|