muthuk2 commited on
Commit
f8d563c
Β·
verified Β·
1 Parent(s): 0e6af57

fix: LLM provider with exponential backoff, streaming, token tracking

Browse files
Files changed (1) hide show
  1. backend/app/services/llm_provider.py +203 -39
backend/app/services/llm_provider.py CHANGED
@@ -1,44 +1,101 @@
1
  """
2
- TestGenius AI β€” Universal LLM Provider (Custom Base URL + Model)
3
- =================================================================
4
- Users configure in .env:
5
- LLM_BASE_URL=https://api.featherless.ai/v1
6
- LLM_API_KEY=your-key
7
- LLM_MODEL=meta-llama/Meta-Llama-3.1-70B-Instruct
8
-
9
- Works with ANY OpenAI-compatible API: OpenAI, Featherless, Groq, Together,
10
- DeepSeek, OpenRouter, Mistral, Ollama, LM Studio, vLLM, etc.
11
  """
12
 
13
  import os
 
14
  import logging
 
15
  import httpx
16
- from typing import Optional, Dict
 
17
 
18
  logger = logging.getLogger(__name__)
19
 
20
- # ═══ CONFIGURATION FROM .env ═══
21
 
22
  LLM_BASE_URL = os.environ.get("LLM_BASE_URL", "https://api.groq.com/openai/v1")
23
  LLM_API_KEY = os.environ.get("LLM_API_KEY", "")
24
  LLM_MODEL = os.environ.get("LLM_MODEL", "llama-3.3-70b-versatile")
25
  LLM_MAX_TOKENS = int(os.environ.get("LLM_MAX_TOKENS", "8192"))
26
  LLM_TEMPERATURE = float(os.environ.get("LLM_TEMPERATURE", "0.3"))
 
27
 
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  async def generate_with_llm(
30
  prompt: str,
31
  system_prompt: str,
32
  temperature: Optional[float] = None,
33
  max_tokens: Optional[int] = None,
 
34
  ) -> str:
35
  """
36
  Generate text using ANY OpenAI-compatible LLM provider.
37
-
38
- Configure via environment variables:
39
- LLM_BASE_URL β€” API endpoint (e.g., https://api.featherless.ai/v1)
40
- LLM_API_KEY β€” API key
41
- LLM_MODEL β€” Model name (e.g., meta-llama/Meta-Llama-3.1-70B-Instruct)
42
  """
43
  if not LLM_API_KEY:
44
  raise RuntimeError(
@@ -49,13 +106,12 @@ async def generate_with_llm(
49
  )
50
 
51
  url = f"{LLM_BASE_URL.rstrip('/')}/chat/completions"
52
-
53
  headers = {
54
  "Content-Type": "application/json",
55
  "Authorization": f"Bearer {LLM_API_KEY}",
56
  }
57
-
58
- # Some providers need extra headers
59
  if "openrouter" in LLM_BASE_URL:
60
  headers["HTTP-Referer"] = "https://testgenius-ai.app"
61
  headers["X-Title"] = "TestGenius AI"
@@ -70,42 +126,150 @@ async def generate_with_llm(
70
  "max_tokens": max_tokens or LLM_MAX_TOKENS,
71
  }
72
 
73
- try:
74
- async with httpx.AsyncClient(timeout=120.0) as client:
75
- response = await client.post(url, headers=headers, json=payload)
76
 
77
- if response.status_code == 429:
78
- logger.warning("Rate limited β€” retrying after 2s")
79
- import asyncio
80
- await asyncio.sleep(2)
 
81
  response = await client.post(url, headers=headers, json=payload)
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  if response.status_code != 200:
84
- error_text = response.text[:300]
85
- logger.error(f"LLM Error [{LLM_BASE_URL}] {response.status_code}: {error_text}")
86
- raise RuntimeError(f"LLM API error {response.status_code}: {error_text}")
87
 
88
- data = response.json()
89
- content = data["choices"][0]["message"]["content"]
90
-
91
- logger.info(f"LLM response: {len(content)} chars from {LLM_MODEL} via {_detect_provider()}")
92
- return content
 
 
 
 
 
 
 
 
 
93
 
94
- except httpx.TimeoutException:
95
- raise RuntimeError(f"LLM request timed out (120s) β€” model: {LLM_MODEL}")
96
- except httpx.ConnectError:
97
- raise RuntimeError(f"Cannot connect to LLM at {LLM_BASE_URL} β€” check your configuration")
98
 
 
99
 
100
  def get_provider_info() -> Dict:
101
- """Return current LLM configuration (for health check / UI display)."""
102
  return {
103
  "configured": bool(LLM_API_KEY),
104
  "base_url": LLM_BASE_URL,
105
  "model": LLM_MODEL,
106
  "max_tokens": LLM_MAX_TOKENS,
107
  "temperature": LLM_TEMPERATURE,
 
108
  "provider": _detect_provider(),
 
109
  }
110
 
111
 
 
1
  """
2
+ TestGenius AI β€” Universal LLM Provider (v2 β€” ALL FIXES)
3
+ =========================================================
4
+ FIXES:
5
+ 1. βœ… Exponential backoff retry (not just single 429 retry)
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, Any
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")
27
  LLM_MAX_TOKENS = int(os.environ.get("LLM_MAX_TOKENS", "8192"))
28
  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:
47
+ return self.total_prompt_tokens + self.total_completion_tokens
48
+
49
+ @property
50
+ def avg_latency_ms(self) -> float:
51
+ return self.total_latency_ms / max(self.total_requests, 1)
52
+
53
+ def to_dict(self) -> Dict:
54
+ return {
55
+ "total_prompt_tokens": self.total_prompt_tokens,
56
+ "total_completion_tokens": self.total_completion_tokens,
57
+ "total_tokens": self.total_tokens,
58
+ "total_requests": self.total_requests,
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._estimate_cost(),
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,
92
  temperature: Optional[float] = None,
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(
 
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"
 
126
  "max_tokens": max_tokens or LLM_MAX_TOKENS,
127
  }
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
+ wait_time = (2 ** attempt) + 1 # 2s, 5s, 9s
144
+ retry_after = response.headers.get("Retry-After")
145
+ if retry_after:
146
+ try:
147
+ wait_time = min(int(retry_after), 30)
148
+ except ValueError:
149
+ pass
150
+ logger.warning(f"Rate limited (429). Retry {attempt+1}/{max_retries} after {wait_time}s")
151
+ await asyncio.sleep(wait_time)
152
+ continue
153
+ else:
154
+ _usage.total_errors += 1
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
+ wait_time = (2 ** attempt) + 1
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
+ error_text = response.text[:300]
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 request timed out after {max_retries} retries ({request_timeout}s each)")
200
+
201
+ except httpx.ConnectError:
202
+ _usage.total_errors += 1
203
+ raise RuntimeError(f"Cannot connect to LLM at {LLM_BASE_URL}")
204
+
205
+ _usage.total_errors += 1
206
+ raise RuntimeError("LLM request failed after all retries")
207
+
208
+
209
+ async def generate_with_llm_streaming(
210
+ prompt: str,
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,
237
+ }
238
+
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"LLM streaming error: {response.status_code}")
 
 
243
 
244
+ async for line in response.aiter_lines():
245
+ if line.startswith("data: "):
246
+ data = line[6:]
247
+ if data == "[DONE]":
248
+ break
249
+ try:
250
+ import json
251
+ chunk = json.loads(data)
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,
267
  "model": LLM_MODEL,
268
  "max_tokens": LLM_MAX_TOKENS,
269
  "temperature": LLM_TEMPERATURE,
270
+ "timeout_seconds": LLM_TIMEOUT,
271
  "provider": _detect_provider(),
272
+ "usage": _usage.to_dict(),
273
  }
274
 
275