algospaced-dsa / ai_provider.py
iamfebin's picture
feat: zstd zip export, resilient streak date parsing, Python 3.14 modernization, and pathlib migration
a42236e
Raw History Blame Contribute Delete
31.5 kB
import json
import logging
import re
import urllib.error
import urllib.request
from typing import Any
import httpx
from gdrive_sync import get_secret
logger = logging.getLogger("ai_provider")
logger.setLevel(logging.INFO)
# Optional genai import
try:
from google import genai
from google.genai import types
except ImportError:
genai = None
types = None
def clean_json_response(raw_text: str) -> str:
"""Strips markdown code blocks, comments, or leading/trailing text to extract clean JSON."""
if not raw_text:
return ""
text = raw_text.strip()
# Remove markdown code fences if present
match = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", text, re.IGNORECASE)
if match:
text = match.group(1).strip()
# If text is still wrapped in another fence or has leading text
if not (text.startswith("{") or text.startswith("[")):
start_brace = text.find("{")
start_bracket = text.find("[")
if start_brace != -1 and (start_bracket == -1 or start_brace < start_bracket):
end_brace = text.rfind("}")
if end_brace != -1:
text = text[start_brace : end_brace + 1]
elif start_bracket != -1:
end_bracket = text.rfind("]")
if end_bracket != -1:
text = text[start_bracket : end_bracket + 1]
return text.strip()
def call_gemini(
api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
"""Calls Google Gemini API with fallback models."""
models = [
"gemini-3.5-flash-lite",
"gemini-2.5-flash",
"gemini-3.7-flash",
"gemini-2.5-flash-lite",
"gemini-3.5-flash",
"gemini-2.5-pro",
"gemini-2.0-flash",
"gemini-1.5-flash",
]
# If official SDK is available
if genai is not None:
client = genai.Client(api_key=api_key)
last_err = None
for model_name in models:
try:
config = (
types.GenerateContentConfig(
system_instruction=system_instruction,
response_mime_type="application/json",
)
if is_json
else types.GenerateContentConfig(
system_instruction=system_instruction,
)
)
response = client.models.generate_content(
model=model_name, contents=user_prompt, config=config
)
if response and hasattr(response, "text") and response.text:
return response.text
except Exception as e:
last_err = e
logger.warning(f"Gemini model {model_name} failed: {e}")
continue
if last_err:
raise last_err
raise RuntimeError("Gemini failed to return text")
# Fallback to direct REST call if SDK missing
last_err = None
for model_name in models:
try:
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_name}:generateContent?key={api_key}"
payload = {
"contents": [{"parts": [{"text": user_prompt}]}],
"systemInstruction": {"parts": [{"text": system_instruction}]},
}
if is_json:
payload["generationConfig"] = {"responseMimeType": "application/json"}
req = urllib.request.Request(
url,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
candidates = data.get("candidates", [])
if candidates:
parts = candidates[0].get("content", {}).get("parts", [])
if parts:
return parts[0].get("text", "")
except Exception as e:
last_err = e
continue
if last_err:
raise last_err
raise RuntimeError("Gemini REST API failed")
def stream_gemini(api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False):
"""Streams Google Gemini API responses chunk by chunk."""
models = [
"gemini-2.5-flash",
"gemini-3.5-flash-lite",
"gemini-3.7-flash",
"gemini-2.5-flash-lite",
"gemini-3.5-flash",
"gemini-2.0-flash",
"gemini-1.5-flash",
]
if genai is not None:
client = genai.Client(api_key=api_key)
for model_name in models:
try:
config = (
types.GenerateContentConfig(
system_instruction=system_instruction,
response_mime_type="application/json",
)
if is_json
else types.GenerateContentConfig(
system_instruction=system_instruction,
)
)
response = client.models.generate_content_stream(
model=model_name, contents=user_prompt, config=config
)
has_yielded = False
for chunk in response:
if chunk and hasattr(chunk, "text") and chunk.text:
has_yielded = True
yield chunk.text
if has_yielded:
return
except Exception as e:
logger.warning(f"Gemini streaming model {model_name} failed: {e}")
continue
# Fallback to standard call if streaming fails or SDK missing
full_text = call_gemini(api_key, system_instruction, user_prompt, is_json=is_json)
if full_text:
yield full_text
def call_groq(
api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
"""Calls Groq Cloud API with OpenAI-compatible payload."""
models = [
"qwen/qwen3.8-27b",
"openai/gpt-oss-20b",
"qwen/qwen3.6-27b",
"openai/gpt-oss-120b",
"groq/compound-mini",
"groq/compound",
]
url = "https://api.groq.com/openai/v1/chat/completions"
last_err = None
for model_name in models:
try:
payload: dict[str, Any] = {
"model": model_name,
"messages": [
{"role": "system", "content": system_instruction},
{"role": "user", "content": user_prompt},
],
"temperature": 0.2,
}
if is_json:
payload["response_format"] = {"type": "json_object"}
req = urllib.request.Request(
url,
data=json.dumps(payload).encode("utf-8"),
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AlgoSpaced/1.0",
},
)
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
choices = data.get("choices", [])
if choices:
content = choices[0].get("message", {}).get("content", "")
if content:
return content
except Exception as e:
last_err = e
logger.warning(f"Groq model {model_name} failed: {e}")
continue
if last_err:
raise last_err
raise RuntimeError("Groq failed to return content")
def call_openrouter(
api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
"""Calls OpenRouter API with free and standard model fallbacks."""
models = [
"openrouter/free",
"deepseek/deepseek-chat",
"meta-llama/llama-3.3-70b-instruct",
"minimax/minimax-m2.7:free",
"google/gemma-4-31b-it:free",
"meta-llama/llama-3.1-8b-instruct:free",
]
url = "https://openrouter.ai/api/v1/chat/completions"
last_err = None
for model_name in models:
try:
payload: dict[str, Any] = {
"model": model_name,
"messages": [
{"role": "system", "content": system_instruction},
{"role": "user", "content": user_prompt},
],
"temperature": 0.2,
}
if is_json:
payload["response_format"] = {"type": "json_object"}
req = urllib.request.Request(
url,
data=json.dumps(payload).encode("utf-8"),
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
"HTTP-Referer": "https://algospaced.io",
"X-Title": "AlgoSpaced DSA",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AlgoSpaced/1.0",
},
)
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
choices = data.get("choices", [])
if choices:
content = choices[0].get("message", {}).get("content", "")
if content:
return content
except Exception as e:
last_err = e
logger.warning(f"OpenRouter model {model_name} failed: {e}")
continue
if last_err:
raise last_err
raise RuntimeError("OpenRouter failed to return content")
def detect_provider(provider: str | None, api_key: str | None) -> str:
"""Infers provider from name or key pattern."""
if provider:
p = provider.lower().strip()
if "groq" in p:
return "groq"
if "openrouter" in p or "open_router" in p:
return "openrouter"
if "gemini" in p or "google" in p:
return "gemini"
if api_key:
k = api_key.strip()
if k.startswith("gsk_"):
return "groq"
if k.startswith("sk-or-"):
return "openrouter"
if k.startswith("AIza"):
return "gemini"
return "gemini"
def generate_ai_content(
system_instruction: str,
user_prompt: str,
is_json: bool = False,
custom_provider: str | None = None,
custom_api_key: str | None = None,
) -> tuple[str, str]:
"""
Unified multi-provider AI dispatcher with automatic failover.
Returns tuple of (response_text, provider_used).
"""
# 1. Custom BYOK Request
if custom_api_key and custom_api_key.strip():
key = custom_api_key.strip()
provider = detect_provider(custom_provider, key)
if provider == "groq":
text = call_groq(key, system_instruction, user_prompt, is_json=is_json)
return text, "groq (custom)"
elif provider == "openrouter":
text = call_openrouter(key, system_instruction, user_prompt, is_json=is_json)
return text, "openrouter (custom)"
else:
text = call_gemini(key, system_instruction, user_prompt, is_json=is_json)
return text, "gemini (custom)"
# 2. Server Shared Default Tier (Multi-Provider Fallback Chain)
gemini_key = get_secret("GEMINI_API_KEY")
groq_key = get_secret("GROQ_API_KEY")
openrouter_key = get_secret("OPENROUTER_API_KEY")
errors: list[str] = []
# Priority 1: Gemini
if gemini_key:
try:
text = call_gemini(gemini_key, system_instruction, user_prompt, is_json=is_json)
return text, "gemini (server)"
except Exception as e:
err_msg = f"Gemini server key failed: {e}"
logger.warning(err_msg)
errors.append(err_msg)
# Priority 2: Groq (if available on server)
if groq_key:
try:
text = call_groq(groq_key, system_instruction, user_prompt, is_json=is_json)
return text, "groq (server fallback)"
except Exception as e:
err_msg = f"Groq server key failed: {e}"
logger.warning(err_msg)
errors.append(err_msg)
# Priority 3: OpenRouter (if available on server)
if openrouter_key:
try:
text = call_openrouter(openrouter_key, system_instruction, user_prompt, is_json=is_json)
return text, "openrouter (server fallback)"
except Exception as e:
err_msg = f"OpenRouter server key failed: {e}"
logger.warning(err_msg)
errors.append(err_msg)
if not (gemini_key or groq_key or openrouter_key):
raise RuntimeError(
"No AI API keys configured on server. Please configure your API key in Settings."
)
raise RuntimeError(f"All AI providers failed. Summary of errors: {'; '.join(errors)}")
def stream_ai_content(
system_instruction: str,
user_prompt: str,
is_json: bool = False,
custom_provider: str | None = None,
custom_api_key: str | None = None,
):
"""
Streams AI content chunks. Yields tuples of (chunk_text, provider_name).
"""
# 1. Custom BYOK Request
if custom_api_key and custom_api_key.strip():
key = custom_api_key.strip()
provider = detect_provider(custom_provider, key)
if provider == "gemini":
for chunk in stream_gemini(key, system_instruction, user_prompt, is_json=is_json):
yield chunk, "gemini (custom)"
return
elif provider == "groq":
text = call_groq(key, system_instruction, user_prompt, is_json=is_json)
yield text, "groq (custom)"
return
elif provider == "openrouter":
text = call_openrouter(key, system_instruction, user_prompt, is_json=is_json)
yield text, "openrouter (custom)"
return
else:
for chunk in stream_gemini(key, system_instruction, user_prompt, is_json=is_json):
yield chunk, "gemini (custom)"
return
# 2. Server Shared Default Tier
gemini_key = get_secret("GEMINI_API_KEY")
if gemini_key:
try:
for chunk in stream_gemini(
gemini_key, system_instruction, user_prompt, is_json=is_json
):
yield chunk, "gemini (server)"
return
except Exception as e:
logger.warning(f"Gemini server stream failed: {e}")
# Fallback to standard generation
text, provider = generate_ai_content(
system_instruction=system_instruction,
user_prompt=user_prompt,
is_json=is_json,
custom_provider=custom_provider,
custom_api_key=custom_api_key,
)
yield text, provider
def generate_text(
prompt: str,
custom_api_key: str | None = None,
custom_provider: str | None = None,
) -> dict[str, Any]:
"""Helper for single-prompt text generation."""
try:
text, provider = generate_ai_content(
system_instruction="You are an expert programming assistant.",
user_prompt=prompt,
is_json=False,
custom_provider=custom_provider,
custom_api_key=custom_api_key,
)
return {"text": text, "provider": provider}
except Exception as e:
logger.error(f"Error in generate_text: {e}")
return {"text": "", "error": str(e)}
async def generate_text_async(
prompt: str,
custom_api_key: str | None = None,
custom_provider: str | None = None,
) -> dict[str, Any]:
"""Helper for async single-prompt text generation."""
try:
text, provider = await generate_ai_content_async(
system_instruction="You are an expert programming assistant.",
user_prompt=prompt,
is_json=False,
custom_provider=custom_provider,
custom_api_key=custom_api_key,
)
return {"text": text, "provider": provider}
except Exception as e:
logger.error(f"Error in generate_text_async: {e}")
return {"text": "", "error": str(e)}
async def call_gemini_async(
api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
"""Calls Google Gemini API asynchronously with fallback models."""
models = [
"gemini-3.5-flash-lite",
"gemini-2.5-flash",
"gemini-3.7-flash",
"gemini-2.5-flash-lite",
"gemini-3.5-flash",
"gemini-2.5-pro",
"gemini-2.0-flash",
"gemini-1.5-flash",
]
# If official SDK is available
if genai is not None:
client = genai.Client(api_key=api_key)
last_err = None
for model_name in models:
try:
config = (
types.GenerateContentConfig(
system_instruction=system_instruction,
response_mime_type="application/json",
)
if is_json
else types.GenerateContentConfig(
system_instruction=system_instruction,
)
)
response = await client.aio.models.generate_content(
model=model_name, contents=user_prompt, config=config
)
if response and hasattr(response, "text") and response.text:
return response.text
except Exception as e:
last_err = e
logger.warning(f"Gemini async model {model_name} failed: {e}")
continue
if last_err:
raise last_err
raise RuntimeError("Gemini failed to return text")
# Fallback to direct REST call via httpx if SDK missing
last_err = None
async with httpx.AsyncClient(timeout=30.0) as http_client:
for model_name in models:
try:
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model_name}:generateContent?key={api_key}"
payload = {
"contents": [{"parts": [{"text": user_prompt}]}],
"systemInstruction": {"parts": [{"text": system_instruction}]},
}
if is_json:
payload["generationConfig"] = {"responseMimeType": "application/json"}
resp = await http_client.post(
url, json=payload, headers={"Content-Type": "application/json"}
)
if resp.status_code == 200:
data = resp.json()
candidates = data.get("candidates", [])
if candidates:
parts = candidates[0].get("content", {}).get("parts", [])
if parts:
return parts[0].get("text", "")
else:
err_text = resp.text[:300]
last_err = RuntimeError(
f"Gemini {model_name} HTTP {resp.status_code}: {err_text}"
)
logger.warning(
f"Gemini async REST model {model_name} returned {resp.status_code}: {err_text}"
)
except Exception as e:
last_err = e
continue
if last_err:
raise last_err
raise RuntimeError("Gemini REST API failed")
async def stream_gemini_async(
api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
):
"""Streams Google Gemini API responses chunk by chunk asynchronously."""
models = [
"gemini-2.5-flash",
"gemini-3.5-flash-lite",
"gemini-3.7-flash",
"gemini-2.5-flash-lite",
"gemini-3.5-flash",
"gemini-2.0-flash",
"gemini-1.5-flash",
]
if genai is not None:
client = genai.Client(api_key=api_key)
for model_name in models:
has_yielded = False
try:
config = (
types.GenerateContentConfig(
system_instruction=system_instruction,
response_mime_type="application/json",
)
if is_json
else types.GenerateContentConfig(
system_instruction=system_instruction,
)
)
response = await client.aio.models.generate_content_stream(
model=model_name, contents=user_prompt, config=config
)
async for chunk in response:
if chunk and hasattr(chunk, "text") and chunk.text:
has_yielded = True
yield chunk.text
if has_yielded:
return
except Exception as e:
logger.warning(f"Gemini async streaming model {model_name} failed: {e}")
if has_yielded:
# Stream has already partially sent data to client; do not duplicate
return
continue
# Fallback to standard async call if streaming fails or SDK missing
full_text = await call_gemini_async(api_key, system_instruction, user_prompt, is_json=is_json)
if full_text:
yield full_text
async def call_groq_async(
api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
"""Calls Groq Cloud API asynchronously."""
models = [
"qwen/qwen3.8-27b",
"openai/gpt-oss-20b",
"qwen/qwen3.6-27b",
"openai/gpt-oss-120b",
"groq/compound-mini",
"groq/compound",
]
url = "https://api.groq.com/openai/v1/chat/completions"
last_err = None
async with httpx.AsyncClient(timeout=30.0) as http_client:
for model_name in models:
try:
payload: dict[str, Any] = {
"model": model_name,
"messages": [
{"role": "system", "content": system_instruction},
{"role": "user", "content": user_prompt},
],
"temperature": 0.2,
}
if is_json:
payload["response_format"] = {"type": "json_object"}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AlgoSpaced/1.0",
}
resp = await http_client.post(url, json=payload, headers=headers)
if resp.status_code == 200:
data = resp.json()
choices = data.get("choices", [])
if choices:
content = choices[0].get("message", {}).get("content", "")
if content:
return content
else:
err_text = resp.text[:300]
last_err = RuntimeError(
f"Groq {model_name} HTTP {resp.status_code}: {err_text}"
)
logger.warning(
f"Groq async model {model_name} returned {resp.status_code}: {err_text}"
)
except Exception as e:
last_err = e
logger.warning(f"Groq async model {model_name} failed: {e}")
continue
if last_err:
raise last_err
raise RuntimeError("Groq failed to return content")
async def call_openrouter_async(
api_key: str, system_instruction: str, user_prompt: str, is_json: bool = False
) -> str:
"""Calls OpenRouter API asynchronously."""
models = [
"openrouter/free",
"deepseek/deepseek-chat",
"meta-llama/llama-3.3-70b-instruct",
"minimax/minimax-m2.7:free",
"google/gemma-4-31b-it:free",
"meta-llama/llama-3.1-8b-instruct:free",
]
url = "https://openrouter.ai/api/v1/chat/completions"
last_err = None
async with httpx.AsyncClient(timeout=30.0) as http_client:
for model_name in models:
try:
payload: dict[str, Any] = {
"model": model_name,
"messages": [
{"role": "system", "content": system_instruction},
{"role": "user", "content": user_prompt},
],
"temperature": 0.2,
}
if is_json:
payload["response_format"] = {"type": "json_object"}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
"HTTP-Referer": "https://algospaced.io",
"X-Title": "AlgoSpaced DSA",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AlgoSpaced/1.0",
}
resp = await http_client.post(url, json=payload, headers=headers)
if resp.status_code == 200:
data = resp.json()
choices = data.get("choices", [])
if choices:
content = choices[0].get("message", {}).get("content", "")
if content:
return content
else:
err_text = resp.text[:300]
last_err = RuntimeError(
f"OpenRouter {model_name} HTTP {resp.status_code}: {err_text}"
)
logger.warning(
f"OpenRouter async model {model_name} returned {resp.status_code}: {err_text}"
)
except Exception as e:
last_err = e
logger.warning(f"OpenRouter async model {model_name} failed: {e}")
continue
if last_err:
raise last_err
raise RuntimeError("OpenRouter failed to return content")
async def generate_ai_content_async(
system_instruction: str,
user_prompt: str,
is_json: bool = False,
custom_provider: str | None = None,
custom_api_key: str | None = None,
) -> tuple[str, str]:
"""
Unified multi-provider AI dispatcher with automatic failover (async).
Returns tuple of (response_text, provider_used).
"""
# 1. Custom BYOK Request
if custom_api_key and custom_api_key.strip():
key = custom_api_key.strip()
provider = detect_provider(custom_provider, key)
if provider == "groq":
text = await call_groq_async(key, system_instruction, user_prompt, is_json=is_json)
return text, "groq (custom)"
elif provider == "openrouter":
text = await call_openrouter_async(
key, system_instruction, user_prompt, is_json=is_json
)
return text, "openrouter (custom)"
else:
text = await call_gemini_async(key, system_instruction, user_prompt, is_json=is_json)
return text, "gemini (custom)"
# 2. Server Shared Default Tier (Multi-Provider Fallback Chain)
gemini_key = get_secret("GEMINI_API_KEY")
groq_key = get_secret("GROQ_API_KEY")
openrouter_key = get_secret("OPENROUTER_API_KEY")
errors: list[str] = []
# Priority 1: Gemini
if gemini_key:
try:
text = await call_gemini_async(
gemini_key, system_instruction, user_prompt, is_json=is_json
)
return text, "gemini (server)"
except Exception as e:
err_msg = f"Gemini server key failed: {e}"
logger.warning(err_msg)
errors.append(err_msg)
# Priority 2: Groq (if available on server)
if groq_key:
try:
text = await call_groq_async(groq_key, system_instruction, user_prompt, is_json=is_json)
return text, "groq (server fallback)"
except Exception as e:
err_msg = f"Groq server key failed: {e}"
logger.warning(err_msg)
errors.append(err_msg)
# Priority 3: OpenRouter (if available on server)
if openrouter_key:
try:
text = await call_openrouter_async(
openrouter_key, system_instruction, user_prompt, is_json=is_json
)
return text, "openrouter (server fallback)"
except Exception as e:
err_msg = f"OpenRouter server key failed: {e}"
logger.warning(err_msg)
errors.append(err_msg)
if not (gemini_key or groq_key or openrouter_key):
raise RuntimeError(
"No AI API keys configured on server. Please configure your API key in Settings."
)
raise RuntimeError(f"All AI providers failed. Summary of errors: {'; '.join(errors)}")
async def stream_ai_content_async(
system_instruction: str,
user_prompt: str,
is_json: bool = False,
custom_provider: str | None = None,
custom_api_key: str | None = None,
):
"""
Streams AI content chunks asynchronously. Yields tuples of (chunk_text, provider_name).
"""
# 1. Custom BYOK Request
if custom_api_key and custom_api_key.strip():
key = custom_api_key.strip()
provider = detect_provider(custom_provider, key)
if provider == "gemini":
async for chunk in stream_gemini_async(
key, system_instruction, user_prompt, is_json=is_json
):
yield chunk, "gemini (custom)"
return
elif provider == "groq":
text = await call_groq_async(key, system_instruction, user_prompt, is_json=is_json)
yield text, "groq (custom)"
return
elif provider == "openrouter":
text = await call_openrouter_async(
key, system_instruction, user_prompt, is_json=is_json
)
yield text, "openrouter (custom)"
return
else:
async for chunk in stream_gemini_async(
key, system_instruction, user_prompt, is_json=is_json
):
yield chunk, "gemini (custom)"
return
# 2. Server Shared Default Tier
gemini_key = get_secret("GEMINI_API_KEY")
has_yielded_server = False
if gemini_key:
try:
async for chunk in stream_gemini_async(
gemini_key, system_instruction, user_prompt, is_json=is_json
):
has_yielded_server = True
yield chunk, "gemini (server)"
return
except Exception as e:
logger.warning(f"Gemini server async stream failed: {e}")
if has_yielded_server:
return
# Fallback to standard async generation
text, provider = await generate_ai_content_async(
system_instruction=system_instruction,
user_prompt=user_prompt,
is_json=is_json,
custom_provider=custom_provider,
custom_api_key=custom_api_key,
)
yield text, provider