feat: llm_provider.py v2 with backoff, streaming, token tracking
Browse files- backend/app/services/llm_provider.py +37 -110
backend/app/services/llm_provider.py
CHANGED
|
@@ -1,26 +1,21 @@
|
|
| 1 |
"""
|
| 2 |
-
TestGenius AI — Universal LLM Provider (v2 —
|
| 3 |
-
=========================================================
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
2. ✅ Streaming support for long generations
|
| 7 |
-
3. ✅ Token usage tracking per request
|
| 8 |
-
4. ✅ Request/response logging for debugging
|
| 9 |
-
5. ✅ Configurable timeout per-call
|
| 10 |
"""
|
| 11 |
|
| 12 |
import os
|
| 13 |
import time
|
|
|
|
| 14 |
import logging
|
| 15 |
import asyncio
|
| 16 |
import httpx
|
| 17 |
-
from typing import Optional, Dict
|
| 18 |
from dataclasses import dataclass, field
|
| 19 |
|
| 20 |
logger = logging.getLogger(__name__)
|
| 21 |
|
| 22 |
-
# ═══ CONFIGURATION ═══
|
| 23 |
-
|
| 24 |
LLM_BASE_URL = os.environ.get("LLM_BASE_URL", "https://api.groq.com/openai/v1")
|
| 25 |
LLM_API_KEY = os.environ.get("LLM_API_KEY", "")
|
| 26 |
LLM_MODEL = os.environ.get("LLM_MODEL", "llama-3.3-70b-versatile")
|
|
@@ -29,18 +24,14 @@ LLM_TEMPERATURE = float(os.environ.get("LLM_TEMPERATURE", "0.3"))
|
|
| 29 |
LLM_TIMEOUT = float(os.environ.get("LLM_TIMEOUT", "120"))
|
| 30 |
|
| 31 |
|
| 32 |
-
# ═══ TOKEN TRACKING ═══
|
| 33 |
-
|
| 34 |
@dataclass
|
| 35 |
class UsageStats:
|
| 36 |
-
"""Track token usage across the session."""
|
| 37 |
total_prompt_tokens: int = 0
|
| 38 |
total_completion_tokens: int = 0
|
| 39 |
total_requests: int = 0
|
| 40 |
total_errors: int = 0
|
| 41 |
total_retries: int = 0
|
| 42 |
total_latency_ms: float = 0
|
| 43 |
-
requests: list = field(default_factory=list)
|
| 44 |
|
| 45 |
@property
|
| 46 |
def total_tokens(self) -> int:
|
|
@@ -59,33 +50,22 @@ class UsageStats:
|
|
| 59 |
"total_errors": self.total_errors,
|
| 60 |
"total_retries": self.total_retries,
|
| 61 |
"avg_latency_ms": round(self.avg_latency_ms, 1),
|
| 62 |
-
"estimated_cost_usd": self.
|
| 63 |
}
|
| 64 |
|
| 65 |
-
def _estimate_cost(self) -> float:
|
| 66 |
-
# Rough estimate based on common pricing
|
| 67 |
-
prompt_cost = self.total_prompt_tokens * 0.0000003 # ~$0.30/1M tokens
|
| 68 |
-
completion_cost = self.total_completion_tokens * 0.0000006 # ~$0.60/1M tokens
|
| 69 |
-
return round(prompt_cost + completion_cost, 4)
|
| 70 |
-
|
| 71 |
|
| 72 |
-
# Global usage tracker
|
| 73 |
_usage = UsageStats()
|
| 74 |
|
| 75 |
|
| 76 |
def get_usage_stats() -> Dict:
|
| 77 |
-
"""Get current token usage statistics."""
|
| 78 |
return _usage.to_dict()
|
| 79 |
|
| 80 |
|
| 81 |
def reset_usage_stats():
|
| 82 |
-
"""Reset usage tracking."""
|
| 83 |
global _usage
|
| 84 |
_usage = UsageStats()
|
| 85 |
|
| 86 |
|
| 87 |
-
# ═══ MAIN LLM INTERFACE ═══
|
| 88 |
-
|
| 89 |
async def generate_with_llm(
|
| 90 |
prompt: str,
|
| 91 |
system_prompt: str,
|
|
@@ -93,25 +73,13 @@ async def generate_with_llm(
|
|
| 93 |
max_tokens: Optional[int] = None,
|
| 94 |
timeout: Optional[float] = None,
|
| 95 |
) -> str:
|
| 96 |
-
"""
|
| 97 |
-
Generate text using ANY OpenAI-compatible LLM provider.
|
| 98 |
-
FIX: Exponential backoff, token tracking, better error handling.
|
| 99 |
-
"""
|
| 100 |
if not LLM_API_KEY:
|
| 101 |
-
raise RuntimeError(
|
| 102 |
-
"LLM_API_KEY not set. Configure in .env:\n"
|
| 103 |
-
" LLM_BASE_URL=https://api.groq.com/openai/v1\n"
|
| 104 |
-
" LLM_API_KEY=your-key\n"
|
| 105 |
-
" LLM_MODEL=llama-3.3-70b-versatile"
|
| 106 |
-
)
|
| 107 |
|
| 108 |
url = f"{LLM_BASE_URL.rstrip('/')}/chat/completions"
|
| 109 |
-
headers = {
|
| 110 |
-
"Content-Type": "application/json",
|
| 111 |
-
"Authorization": f"Bearer {LLM_API_KEY}",
|
| 112 |
-
}
|
| 113 |
|
| 114 |
-
# Provider-specific headers
|
| 115 |
if "openrouter" in LLM_BASE_URL:
|
| 116 |
headers["HTTP-Referer"] = "https://testgenius-ai.app"
|
| 117 |
headers["X-Title"] = "TestGenius AI"
|
|
@@ -128,76 +96,59 @@ async def generate_with_llm(
|
|
| 128 |
|
| 129 |
request_timeout = timeout or LLM_TIMEOUT
|
| 130 |
start_time = time.time()
|
| 131 |
-
|
| 132 |
-
# Exponential backoff retry
|
| 133 |
max_retries = 3
|
|
|
|
| 134 |
for attempt in range(max_retries + 1):
|
| 135 |
try:
|
| 136 |
async with httpx.AsyncClient(timeout=request_timeout) as client:
|
| 137 |
response = await client.post(url, headers=headers, json=payload)
|
| 138 |
|
| 139 |
if response.status_code == 429:
|
| 140 |
-
# Rate limited — exponential backoff
|
| 141 |
_usage.total_retries += 1
|
| 142 |
if attempt < max_retries:
|
| 143 |
-
|
| 144 |
retry_after = response.headers.get("Retry-After")
|
| 145 |
if retry_after:
|
| 146 |
try:
|
| 147 |
-
|
| 148 |
except ValueError:
|
| 149 |
pass
|
| 150 |
-
logger.warning(f"Rate limited
|
| 151 |
-
await asyncio.sleep(
|
| 152 |
continue
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
raise RuntimeError(f"Rate limited after {max_retries} retries. Try again later.")
|
| 156 |
|
| 157 |
if response.status_code == 503:
|
| 158 |
-
# Service unavailable — retry
|
| 159 |
_usage.total_retries += 1
|
| 160 |
if attempt < max_retries:
|
| 161 |
-
|
| 162 |
-
logger.warning(f"Service unavailable (503). Retry {attempt+1}/{max_retries}")
|
| 163 |
-
await asyncio.sleep(wait_time)
|
| 164 |
continue
|
| 165 |
|
| 166 |
if response.status_code != 200:
|
| 167 |
_usage.total_errors += 1
|
| 168 |
-
|
| 169 |
-
logger.error(f"LLM Error [{LLM_BASE_URL}] {response.status_code}: {error_text}")
|
| 170 |
-
raise RuntimeError(f"LLM API error {response.status_code}: {error_text}")
|
| 171 |
|
| 172 |
data = response.json()
|
| 173 |
content = data["choices"][0]["message"]["content"]
|
| 174 |
|
| 175 |
-
# Track token usage
|
| 176 |
usage = data.get("usage", {})
|
| 177 |
latency = (time.time() - start_time) * 1000
|
| 178 |
-
|
| 179 |
_usage.total_prompt_tokens += usage.get("prompt_tokens", 0)
|
| 180 |
_usage.total_completion_tokens += usage.get("completion_tokens", 0)
|
| 181 |
_usage.total_requests += 1
|
| 182 |
_usage.total_latency_ms += latency
|
| 183 |
|
| 184 |
-
logger.info(
|
| 185 |
-
f"LLM: {len(content)} chars, "
|
| 186 |
-
f"{usage.get('total_tokens', '?')} tokens, "
|
| 187 |
-
f"{latency:.0f}ms — {LLM_MODEL} via {_detect_provider()}"
|
| 188 |
-
)
|
| 189 |
-
|
| 190 |
return content
|
| 191 |
|
| 192 |
except httpx.TimeoutException:
|
| 193 |
_usage.total_retries += 1
|
| 194 |
if attempt < max_retries:
|
| 195 |
-
logger.warning(f"Timeout after {request_timeout}s. Retry {attempt+1}/{max_retries}")
|
| 196 |
await asyncio.sleep(2 ** attempt)
|
| 197 |
continue
|
| 198 |
_usage.total_errors += 1
|
| 199 |
-
raise RuntimeError(f"LLM
|
| 200 |
-
|
| 201 |
except httpx.ConnectError:
|
| 202 |
_usage.total_errors += 1
|
| 203 |
raise RuntimeError(f"Cannot connect to LLM at {LLM_BASE_URL}")
|
|
@@ -206,31 +157,16 @@ async def generate_with_llm(
|
|
| 206 |
raise RuntimeError("LLM request failed after all retries")
|
| 207 |
|
| 208 |
|
| 209 |
-
async def generate_with_llm_streaming(
|
| 210 |
-
|
| 211 |
-
system_prompt: str,
|
| 212 |
-
temperature: Optional[float] = None,
|
| 213 |
-
max_tokens: Optional[int] = None,
|
| 214 |
-
):
|
| 215 |
-
"""
|
| 216 |
-
FIX: Streaming generation for long outputs. Yields chunks as they arrive.
|
| 217 |
-
Use when generating large test suites to reduce perceived latency.
|
| 218 |
-
"""
|
| 219 |
if not LLM_API_KEY:
|
| 220 |
raise RuntimeError("LLM_API_KEY not set")
|
| 221 |
|
| 222 |
url = f"{LLM_BASE_URL.rstrip('/')}/chat/completions"
|
| 223 |
-
headers = {
|
| 224 |
-
"Content-Type": "application/json",
|
| 225 |
-
"Authorization": f"Bearer {LLM_API_KEY}",
|
| 226 |
-
}
|
| 227 |
-
|
| 228 |
payload = {
|
| 229 |
"model": LLM_MODEL,
|
| 230 |
-
"messages": [
|
| 231 |
-
{"role": "system", "content": system_prompt},
|
| 232 |
-
{"role": "user", "content": prompt},
|
| 233 |
-
],
|
| 234 |
"temperature": temperature or LLM_TEMPERATURE,
|
| 235 |
"max_tokens": max_tokens or LLM_MAX_TOKENS,
|
| 236 |
"stream": True,
|
|
@@ -239,28 +175,22 @@ async def generate_with_llm_streaming(
|
|
| 239 |
async with httpx.AsyncClient(timeout=LLM_TIMEOUT) as client:
|
| 240 |
async with client.stream("POST", url, headers=headers, json=payload) as response:
|
| 241 |
if response.status_code != 200:
|
| 242 |
-
raise RuntimeError(f"
|
| 243 |
-
|
| 244 |
async for line in response.aiter_lines():
|
| 245 |
if line.startswith("data: "):
|
| 246 |
-
|
| 247 |
-
if
|
| 248 |
break
|
| 249 |
try:
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
delta = chunk.get("choices", [{}])[0].get("delta", {})
|
| 253 |
-
content = delta.get("content", "")
|
| 254 |
if content:
|
| 255 |
yield content
|
| 256 |
except (json.JSONDecodeError, IndexError, KeyError):
|
| 257 |
continue
|
| 258 |
|
| 259 |
|
| 260 |
-
# ═══ PROVIDER INFO ═══
|
| 261 |
-
|
| 262 |
def get_provider_info() -> Dict:
|
| 263 |
-
"""Return current LLM configuration and usage stats."""
|
| 264 |
return {
|
| 265 |
"configured": bool(LLM_API_KEY),
|
| 266 |
"base_url": LLM_BASE_URL,
|
|
@@ -275,14 +205,11 @@ def get_provider_info() -> Dict:
|
|
| 275 |
|
| 276 |
def _detect_provider() -> str:
|
| 277 |
url = LLM_BASE_URL.lower()
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
if "localhost:11434" in url: return "Ollama"
|
| 286 |
-
if "localhost:1234" in url: return "LM Studio"
|
| 287 |
-
if "localhost" in url: return "Local"
|
| 288 |
return "Custom"
|
|
|
|
| 1 |
"""
|
| 2 |
+
TestGenius AI — Universal LLM Provider (v2 — Production Ready)
|
| 3 |
+
================================================================
|
| 4 |
+
Works with ANY OpenAI-compatible API.
|
| 5 |
+
Features: exponential backoff, streaming, token tracking, proper timeouts.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import os
|
| 9 |
import time
|
| 10 |
+
import json
|
| 11 |
import logging
|
| 12 |
import asyncio
|
| 13 |
import httpx
|
| 14 |
+
from typing import Optional, Dict
|
| 15 |
from dataclasses import dataclass, field
|
| 16 |
|
| 17 |
logger = logging.getLogger(__name__)
|
| 18 |
|
|
|
|
|
|
|
| 19 |
LLM_BASE_URL = os.environ.get("LLM_BASE_URL", "https://api.groq.com/openai/v1")
|
| 20 |
LLM_API_KEY = os.environ.get("LLM_API_KEY", "")
|
| 21 |
LLM_MODEL = os.environ.get("LLM_MODEL", "llama-3.3-70b-versatile")
|
|
|
|
| 24 |
LLM_TIMEOUT = float(os.environ.get("LLM_TIMEOUT", "120"))
|
| 25 |
|
| 26 |
|
|
|
|
|
|
|
| 27 |
@dataclass
|
| 28 |
class UsageStats:
|
|
|
|
| 29 |
total_prompt_tokens: int = 0
|
| 30 |
total_completion_tokens: int = 0
|
| 31 |
total_requests: int = 0
|
| 32 |
total_errors: int = 0
|
| 33 |
total_retries: int = 0
|
| 34 |
total_latency_ms: float = 0
|
|
|
|
| 35 |
|
| 36 |
@property
|
| 37 |
def total_tokens(self) -> int:
|
|
|
|
| 50 |
"total_errors": self.total_errors,
|
| 51 |
"total_retries": self.total_retries,
|
| 52 |
"avg_latency_ms": round(self.avg_latency_ms, 1),
|
| 53 |
+
"estimated_cost_usd": round(self.total_prompt_tokens * 3e-7 + self.total_completion_tokens * 6e-7, 4),
|
| 54 |
}
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
|
|
|
| 57 |
_usage = UsageStats()
|
| 58 |
|
| 59 |
|
| 60 |
def get_usage_stats() -> Dict:
|
|
|
|
| 61 |
return _usage.to_dict()
|
| 62 |
|
| 63 |
|
| 64 |
def reset_usage_stats():
|
|
|
|
| 65 |
global _usage
|
| 66 |
_usage = UsageStats()
|
| 67 |
|
| 68 |
|
|
|
|
|
|
|
| 69 |
async def generate_with_llm(
|
| 70 |
prompt: str,
|
| 71 |
system_prompt: str,
|
|
|
|
| 73 |
max_tokens: Optional[int] = None,
|
| 74 |
timeout: Optional[float] = None,
|
| 75 |
) -> str:
|
| 76 |
+
"""Generate text with exponential backoff retry."""
|
|
|
|
|
|
|
|
|
|
| 77 |
if not LLM_API_KEY:
|
| 78 |
+
raise RuntimeError("LLM_API_KEY not set. Configure in .env")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
url = f"{LLM_BASE_URL.rstrip('/')}/chat/completions"
|
| 81 |
+
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {LLM_API_KEY}"}
|
|
|
|
|
|
|
|
|
|
| 82 |
|
|
|
|
| 83 |
if "openrouter" in LLM_BASE_URL:
|
| 84 |
headers["HTTP-Referer"] = "https://testgenius-ai.app"
|
| 85 |
headers["X-Title"] = "TestGenius AI"
|
|
|
|
| 96 |
|
| 97 |
request_timeout = timeout or LLM_TIMEOUT
|
| 98 |
start_time = time.time()
|
|
|
|
|
|
|
| 99 |
max_retries = 3
|
| 100 |
+
|
| 101 |
for attempt in range(max_retries + 1):
|
| 102 |
try:
|
| 103 |
async with httpx.AsyncClient(timeout=request_timeout) as client:
|
| 104 |
response = await client.post(url, headers=headers, json=payload)
|
| 105 |
|
| 106 |
if response.status_code == 429:
|
|
|
|
| 107 |
_usage.total_retries += 1
|
| 108 |
if attempt < max_retries:
|
| 109 |
+
wait = (2 ** attempt) + 1
|
| 110 |
retry_after = response.headers.get("Retry-After")
|
| 111 |
if retry_after:
|
| 112 |
try:
|
| 113 |
+
wait = min(int(retry_after), 30)
|
| 114 |
except ValueError:
|
| 115 |
pass
|
| 116 |
+
logger.warning(f"Rate limited. Retry {attempt+1}/{max_retries} in {wait}s")
|
| 117 |
+
await asyncio.sleep(wait)
|
| 118 |
continue
|
| 119 |
+
_usage.total_errors += 1
|
| 120 |
+
raise RuntimeError("Rate limited after all retries")
|
|
|
|
| 121 |
|
| 122 |
if response.status_code == 503:
|
|
|
|
| 123 |
_usage.total_retries += 1
|
| 124 |
if attempt < max_retries:
|
| 125 |
+
await asyncio.sleep((2 ** attempt) + 1)
|
|
|
|
|
|
|
| 126 |
continue
|
| 127 |
|
| 128 |
if response.status_code != 200:
|
| 129 |
_usage.total_errors += 1
|
| 130 |
+
raise RuntimeError(f"LLM API error {response.status_code}: {response.text[:200]}")
|
|
|
|
|
|
|
| 131 |
|
| 132 |
data = response.json()
|
| 133 |
content = data["choices"][0]["message"]["content"]
|
| 134 |
|
|
|
|
| 135 |
usage = data.get("usage", {})
|
| 136 |
latency = (time.time() - start_time) * 1000
|
|
|
|
| 137 |
_usage.total_prompt_tokens += usage.get("prompt_tokens", 0)
|
| 138 |
_usage.total_completion_tokens += usage.get("completion_tokens", 0)
|
| 139 |
_usage.total_requests += 1
|
| 140 |
_usage.total_latency_ms += latency
|
| 141 |
|
| 142 |
+
logger.info(f"LLM: {len(content)} chars, {usage.get('total_tokens', '?')} tokens, {latency:.0f}ms")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
return content
|
| 144 |
|
| 145 |
except httpx.TimeoutException:
|
| 146 |
_usage.total_retries += 1
|
| 147 |
if attempt < max_retries:
|
|
|
|
| 148 |
await asyncio.sleep(2 ** attempt)
|
| 149 |
continue
|
| 150 |
_usage.total_errors += 1
|
| 151 |
+
raise RuntimeError(f"LLM timed out after {max_retries} retries")
|
|
|
|
| 152 |
except httpx.ConnectError:
|
| 153 |
_usage.total_errors += 1
|
| 154 |
raise RuntimeError(f"Cannot connect to LLM at {LLM_BASE_URL}")
|
|
|
|
| 157 |
raise RuntimeError("LLM request failed after all retries")
|
| 158 |
|
| 159 |
|
| 160 |
+
async def generate_with_llm_streaming(prompt: str, system_prompt: str, temperature: Optional[float] = None, max_tokens: Optional[int] = None):
|
| 161 |
+
"""Streaming generation — yields chunks as they arrive."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
if not LLM_API_KEY:
|
| 163 |
raise RuntimeError("LLM_API_KEY not set")
|
| 164 |
|
| 165 |
url = f"{LLM_BASE_URL.rstrip('/')}/chat/completions"
|
| 166 |
+
headers = {"Content-Type": "application/json", "Authorization": f"Bearer {LLM_API_KEY}"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
payload = {
|
| 168 |
"model": LLM_MODEL,
|
| 169 |
+
"messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": prompt}],
|
|
|
|
|
|
|
|
|
|
| 170 |
"temperature": temperature or LLM_TEMPERATURE,
|
| 171 |
"max_tokens": max_tokens or LLM_MAX_TOKENS,
|
| 172 |
"stream": True,
|
|
|
|
| 175 |
async with httpx.AsyncClient(timeout=LLM_TIMEOUT) as client:
|
| 176 |
async with client.stream("POST", url, headers=headers, json=payload) as response:
|
| 177 |
if response.status_code != 200:
|
| 178 |
+
raise RuntimeError(f"Streaming error: {response.status_code}")
|
|
|
|
| 179 |
async for line in response.aiter_lines():
|
| 180 |
if line.startswith("data: "):
|
| 181 |
+
data_str = line[6:]
|
| 182 |
+
if data_str == "[DONE]":
|
| 183 |
break
|
| 184 |
try:
|
| 185 |
+
chunk = json.loads(data_str)
|
| 186 |
+
content = chunk.get("choices", [{}])[0].get("delta", {}).get("content", "")
|
|
|
|
|
|
|
| 187 |
if content:
|
| 188 |
yield content
|
| 189 |
except (json.JSONDecodeError, IndexError, KeyError):
|
| 190 |
continue
|
| 191 |
|
| 192 |
|
|
|
|
|
|
|
| 193 |
def get_provider_info() -> Dict:
|
|
|
|
| 194 |
return {
|
| 195 |
"configured": bool(LLM_API_KEY),
|
| 196 |
"base_url": LLM_BASE_URL,
|
|
|
|
| 205 |
|
| 206 |
def _detect_provider() -> str:
|
| 207 |
url = LLM_BASE_URL.lower()
|
| 208 |
+
providers = [("openai.com", "OpenAI"), ("featherless", "Featherless"), ("groq.com", "Groq"),
|
| 209 |
+
("together", "Together.ai"), ("deepseek", "DeepSeek"), ("openrouter", "OpenRouter"),
|
| 210 |
+
("mistral", "Mistral"), ("localhost:11434", "Ollama"), ("localhost:1234", "LM Studio"),
|
| 211 |
+
("localhost", "Local")]
|
| 212 |
+
for key, name in providers:
|
| 213 |
+
if key in url:
|
| 214 |
+
return name
|
|
|
|
|
|
|
|
|
|
| 215 |
return "Custom"
|