from __future__ import annotations import os import time from pathlib import Path from typing import Dict, List import requests from dotenv import load_dotenv load_dotenv(dotenv_path=Path(__file__).with_name(".env")) UNIVERSITY_BASE_URL = os.getenv("UNIVERSITY_BASE_URL", "https://ui.tukekemt.xyz/api/v1/chat/completions") UNIVERSITY_MODEL = os.getenv("UNIVERSITY_MODEL", "model2") UNIVERSITY_TIMEOUT = int(os.getenv("UNIVERSITY_TIMEOUT", "600")) UNIVERSITY_RETRIES = int(os.getenv("UNIVERSITY_RETRIES", "3")) UNIVERSITY_MAX_TOKENS = int(os.getenv("UNIVERSITY_MAX_TOKENS", "8192")) RETRYABLE_STATUS_CODES = {429, 500, 502, 503, 504} def llm_call(messages: List[Dict[str, str]]) -> str: """Call the project's existing university LLM using local environment configuration.""" api_key = os.getenv("UNIVERSITY_API_KEY") if not api_key: raise RuntimeError("UNIVERSITY_API_KEY is not configured") for attempt in range(UNIVERSITY_RETRIES + 1): try: response = requests.post( UNIVERSITY_BASE_URL, json={ "model": UNIVERSITY_MODEL, "messages": messages, "stream": False, "max_tokens": UNIVERSITY_MAX_TOKENS, }, headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, timeout=UNIVERSITY_TIMEOUT, ) if response.status_code in RETRYABLE_STATUS_CODES and attempt < UNIVERSITY_RETRIES: time.sleep(2 ** attempt) continue response.raise_for_status() payload = response.json() content = payload["choices"][0]["message"].get("content") if not isinstance(content, str) or not content.strip(): if attempt < UNIVERSITY_RETRIES: time.sleep(2 ** attempt) continue raise RuntimeError( "The LLM returned no final answer content after retries; " "the provider may have exhausted its reasoning budget" ) return content except requests.exceptions.Timeout as error: if attempt >= UNIVERSITY_RETRIES: raise RuntimeError("The LLM service timed out") from error time.sleep(2 ** attempt) except requests.exceptions.ConnectionError as error: if attempt >= UNIVERSITY_RETRIES: raise RuntimeError("The LLM service could not be reached") from error time.sleep(2 ** attempt) raise RuntimeError("LLM request failed")