Add backend/app/services/llm_provider.py — universal LLM provider + complete API
Browse files- backend/app/services/llm_provider.py +111 -105
backend/app/services/llm_provider.py
CHANGED
|
@@ -1,118 +1,124 @@
|
|
| 1 |
"""
|
| 2 |
-
TestGenius AI — LLM Provider
|
| 3 |
-
==============================
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import os
|
| 9 |
-
import json
|
| 10 |
import logging
|
| 11 |
-
|
|
|
|
| 12 |
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
async def call_gemini(prompt: str, system_prompt: str, config: Dict = None) -> str:
|
| 18 |
-
"""Call Google Gemini API."""
|
| 19 |
-
import google.generativeai as genai
|
| 20 |
-
|
| 21 |
-
api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
|
| 22 |
-
if not api_key:
|
| 23 |
-
raise ValueError("GEMINI_API_KEY not set")
|
| 24 |
-
|
| 25 |
-
genai.configure(api_key=api_key)
|
| 26 |
-
model = genai.GenerativeModel("gemini-2.0-flash")
|
| 27 |
-
|
| 28 |
-
response = model.generate_content(
|
| 29 |
-
f"{system_prompt}\n\n{prompt}",
|
| 30 |
-
generation_config=genai.types.GenerationConfig(
|
| 31 |
-
temperature=0.3,
|
| 32 |
-
max_output_tokens=8192,
|
| 33 |
-
),
|
| 34 |
-
)
|
| 35 |
-
return response.text
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
async def call_groq(prompt: str, system_prompt: str, config: Dict = None) -> str:
|
| 39 |
-
"""Call Groq API (Llama 3.3 70B)."""
|
| 40 |
-
import httpx
|
| 41 |
-
|
| 42 |
-
api_key = os.environ.get("GROQ_API_KEY")
|
| 43 |
-
if not api_key:
|
| 44 |
-
raise ValueError("GROQ_API_KEY not set")
|
| 45 |
-
|
| 46 |
-
async with httpx.AsyncClient(timeout=60.0) as client:
|
| 47 |
-
resp = await client.post(
|
| 48 |
-
"https://api.groq.com/openai/v1/chat/completions",
|
| 49 |
-
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
|
| 50 |
-
json={
|
| 51 |
-
"model": "llama-3.3-70b-versatile",
|
| 52 |
-
"messages": [
|
| 53 |
-
{"role": "system", "content": system_prompt},
|
| 54 |
-
{"role": "user", "content": prompt},
|
| 55 |
-
],
|
| 56 |
-
"temperature": 0.3,
|
| 57 |
-
"max_tokens": 8192,
|
| 58 |
-
},
|
| 59 |
-
)
|
| 60 |
-
resp.raise_for_status()
|
| 61 |
-
return resp.json()["choices"][0]["message"]["content"]
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
async def call_openai(prompt: str, system_prompt: str, config: Dict = None) -> str:
|
| 65 |
-
"""Call OpenAI API."""
|
| 66 |
-
import httpx
|
| 67 |
-
|
| 68 |
-
api_key = os.environ.get("OPENAI_API_KEY")
|
| 69 |
-
if not api_key:
|
| 70 |
-
raise ValueError("OPENAI_API_KEY not set")
|
| 71 |
-
|
| 72 |
-
async with httpx.AsyncClient(timeout=60.0) as client:
|
| 73 |
-
resp = await client.post(
|
| 74 |
-
"https://api.openai.com/v1/chat/completions",
|
| 75 |
-
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
|
| 76 |
-
json={
|
| 77 |
-
"model": "gpt-4o-mini",
|
| 78 |
-
"messages": [
|
| 79 |
-
{"role": "system", "content": system_prompt},
|
| 80 |
-
{"role": "user", "content": prompt},
|
| 81 |
-
],
|
| 82 |
-
"temperature": 0.3,
|
| 83 |
-
"max_tokens": 8192,
|
| 84 |
-
},
|
| 85 |
-
)
|
| 86 |
-
resp.raise_for_status()
|
| 87 |
-
return resp.json()["choices"][0]["message"]["content"]
|
| 88 |
-
|
| 89 |
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
-
PROVIDERS = [
|
| 93 |
-
("gemini", call_gemini),
|
| 94 |
-
("groq", call_groq),
|
| 95 |
-
("openai", call_openai),
|
| 96 |
-
]
|
| 97 |
|
| 98 |
-
async def generate_with_llm(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
"""
|
| 100 |
-
Generate text using
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
"""
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(
|
| 45 |
+
"LLM_API_KEY not set. Configure in .env:\n"
|
| 46 |
+
" LLM_BASE_URL=https://api.groq.com/openai/v1\n"
|
| 47 |
+
" LLM_API_KEY=your-key\n"
|
| 48 |
+
" LLM_MODEL=llama-3.3-70b-versatile"
|
| 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"
|
| 62 |
+
|
| 63 |
+
payload = {
|
| 64 |
+
"model": LLM_MODEL,
|
| 65 |
+
"messages": [
|
| 66 |
+
{"role": "system", "content": system_prompt},
|
| 67 |
+
{"role": "user", "content": prompt},
|
| 68 |
+
],
|
| 69 |
+
"temperature": temperature or LLM_TEMPERATURE,
|
| 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 |
+
|
| 112 |
+
def _detect_provider() -> str:
|
| 113 |
+
url = LLM_BASE_URL.lower()
|
| 114 |
+
if "openai.com" in url: return "OpenAI"
|
| 115 |
+
if "featherless" in url: return "Featherless"
|
| 116 |
+
if "groq.com" in url: return "Groq"
|
| 117 |
+
if "together" in url: return "Together.ai"
|
| 118 |
+
if "deepseek" in url: return "DeepSeek"
|
| 119 |
+
if "openrouter" in url: return "OpenRouter"
|
| 120 |
+
if "mistral" in url: return "Mistral"
|
| 121 |
+
if "localhost:11434" in url: return "Ollama"
|
| 122 |
+
if "localhost:1234" in url: return "LM Studio"
|
| 123 |
+
if "localhost" in url: return "Local"
|
| 124 |
+
return "Custom"
|