Thread lock
Browse files3 unmodified lines45678915 unmodified lines25262728293043 unmodified lines747576777879808 unmodified lines89909192939495969798991001011021031041053 unmodified lines10911011111211311414 unmodified lines12913013113213313413510 unmodified lines1461471481491501511521531541551561571581591601611621631642 unmodified lines1671681691701711721731741751761771783 unmodified linesimport requestsimport osimport logging# Configure logginglogging.basicConfig(level=logging.INFO)15 unmodified linesif not OPENROUTER_API_KEY:raise RuntimeError("OPENROUTER_API_KEY environment variable not set!")# Request schemaclass ExplainRequest(BaseModel):message: str43 unmodified lines"Respond using the same language as the message.")url = "https://openrouter.ai/api/v1/chat/completions"headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}","Content-Type": "application/json"8 unmodified linestry:logger.info(f"Calling OpenRouter /explain with model: {req.model_id}")response = requests.post(url, headers=headers, json=payload, timeout=20)response.raise_for_status()result = response.json()# Check for OpenRouter error in response body (even with 200 status)if "error" in result:error_detail = result.get("error", {}).get("message", str(result.get("error")))logger.error(f"OpenRouter returned error in /explain: {error_detail}")logger.error(f"Full response: {result}")raise HTTPException(status_code=500, detail=f"OpenRouter error: {error_detail}")reply = result.get("choices", [{}])[0].get("message", {}).get("content", "").strip()if not reply:logger.error(f"OpenRouter returned empty response in /explain. Full result: {result}")3 unmodified linesexcept requests.RequestException as e:logger.error(f"OpenRouter network error in /explain: {e}")raise HTTPException(status_code=500, detail=f"Error contacting OpenRouter: {e}")except Exception as e:logger.error(f"Unexpected error in /explain: {e}")raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")14 unmodified lines'No other text.')url = "https://openrouter.ai/api/v1/chat/completions"headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}","Content-Type": "application/json"10 unmodified linestry:logger.info(f"Calling OpenRouter /classify with model: {model_id}")response = requests.post(url, headers=headers, json=payload, timeout=20)response.raise_for_status()result = response.json()# Check for OpenRouter error in response body (even with 200 status)if "error" in result:error_detail = result.get("error", {}).get("message", str(result.get("error")))logger.error(f"OpenRouter returned error in /classify: {error_detail}")logger.error(f"Full response: {result}")raise HTTPException(status_code=500, detail=f"OpenRouter error: {error_detail}")reply = result.get("choices", [{}])[0].get("message", {}).get("content", "").strip()if not reply:logger.warning(f"Empty content in response. Finish reason: {result.get('choices', [{}])[0].get('finish_reason')}")# If content is empty, try to extract from reasoning or log for debugging2 unmodified lineslogger.warning(f"Model has reasoning but no content. This may indicate truncation.")logger.error(f"OpenRouter returned empty response in /classify. Full result: {result}")raise HTTPException(status_code=500, detail="No response from OpenRouter")logger.info(f"Classification successful with model {model_id}: {reply}")return {"reply": reply, "status": response.status_code, "model": model_id}except requests.RequestException as e:logger.error(f"OpenRouter network error in /classify: {e}")raise HTTPException(status_code=500, detail=f"Error contacting OpenRouter: {e}")except Exception as e:logger.error(f"Unexpected error in /classify: {e}")raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")3 unmodified lines456789101115 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162636465666768697043 unmodified lines1141151161171181198 unmodified lines1281291301311321331341351361371381391401411421431443 unmodified lines14814915015115215315415514 unmodified lines17017117217317417510 unmodified lines1861871881891901911921931941951961971981992002012022032042 unmodified lines2072082092102112122132142152162172182192203 unmodified linesimport requestsimport osimport loggingimport threadingimport time# Configure logginglogging.basicConfig(level=logging.INFO)15 unmodified linesif not OPENROUTER_API_KEY:raise RuntimeError("OPENROUTER_API_KEY environment variable not set!")# ---------------------------------------------------------------------------# Global rate limiter for OpenRouter calls## Free-tier OpenRouter models throttle/reject requests that arrive too close# together. Since /classify and /explain can be hit concurrently by the# frontend (each running in its own thread pool worker), we serialize ALL# outbound OpenRouter calls behind a single lock and enforce a minimum gap# between them. Whichever request arrives second simply waits its turn.# ---------------------------------------------------------------------------MIN_INTERVAL_SECONDS = float(os.environ.get("OPENROUTER_MIN_INTERVAL", "2.0"))_or_lock = threading.Lock()_last_call_time = 0.0def call_openrouter(payload: dict, headers: dict, timeout: int = 20):"""Thread-safe, rate-limited call to OpenRouter's chat completions endpoint.Ensures at least MIN_INTERVAL_SECONDS has elapsed since the previousOpenRouter call (across ALL endpoints) before firing this one."""global _last_call_timeurl = "https://openrouter.ai/api/v1/chat/completions"with _or_lock:now = time.monotonic()elapsed = now - _last_call_timewait_for = MIN_INTERVAL_SECONDS - elapsedif wait_for > 0:logger.info(f"Rate limiting: waiting {wait_for:.2f}s before next OpenRouter call")time.sleep(wait_for)response = requests.post(url, headers=headers, json=payload, timeout=timeout)_last_call_time = time.monotonic()return response# Request schemaclass ExplainRequest(BaseModel):message: str43 unmodified lines"Respond using the same language as the message.")headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}","Content-Type": "application/json"8 unmodified linestry:logger.info(f"Calling OpenRouter /explain with model: {req.model_id}")response = call_openrouter(payload, headers)response.raise_for_status()result = response.json()# Check for OpenRouter error in response body (even with 200 status)if "error" in result:error_detail = result.get("error", {}).get("message", str(result.get("error")))logger.error(f"OpenRouter returned error in /explain: {error_detail}")logger.error(f"Full response: {result}")raise HTTPException(status_code=500, detail=f"OpenRouter error: {error_detail}")reply = result.get("choices", [{}])[0].get("message", {}).get("content", "").strip()if not reply:logger.error(f"OpenRouter returned empty response in /explain. Full result: {result}")3 unmodified linesexcept requests.RequestException as e:logger.error(f"OpenRouter network error in /explain: {e}")raise HTTPException(status_code=500, detail=f"Error contacting OpenRouter: {e}")except HTTPException:raiseexcept Exception as e:logger.error(f"Unexpected error in /explain: {e}")raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")14 unmodified lines'No other text.')headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}","Content-Type": "application/json"10 unmodified linestry:logger.info(f"Calling OpenRouter /classify with model: {model_id}")response = call_openrouter(payload, headers)response.raise_for_status()result = response.json()# Check for OpenRouter error in response body (even with 200 status)if "error" in result:error_detail = result.get("error", {}).get("message", str(result.get("error")))logger.error(f"OpenRouter returned error in /classify: {error_detail}")logger.error(f"Full response: {result}")raise HTTPException(status_code=500, detail=f"OpenRouter error: {error_detail}")reply = result.get("choices", [{}])[0].get("message", {}).get("content", "").strip()if not reply:logger.warning(f"Empty content in response. Finish reason: {result.get('choices', [{}])[0].get('finish_reason')}")# If content is empty, try to extract from reasoning or log for debugging2 unmodified lineslogger.warning(f"Model has reasoning but no content. This may indicate truncation.")logger.error(f"OpenRouter returned empty response in /classify. Full result: {result}")raise HTTPException(status_code=500, detail="No response from OpenRouter")logger.info(f"Classification successful with model {model_id}: {reply}")return {"reply": reply, "status": response.status_code, "model": model_id}except requests.RequestException as e:logger.error(f"OpenRouter network error in /classify: {e}")raise HTTPException(status_code=500, detail=f"Error contacting OpenRouter: {e}")except HTTPException:raiseexcept Exception as e:logger.error(f"Unexpected error in /classify: {e}")raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")
app.py+52-10