From fa98956bcc2437e39c92e1510838fcced909c3ab Mon Sep 17 00:00:00 2001 From: admtracksteel Date: Wed, 29 Apr 2026 01:10:16 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=80=20Auto-deploy:=20BotVPS=20atualiza?= =?UTF-8?q?do=20em=2029/04/2026=2001:10:16?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- llm_providers.py | 57 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/llm_providers.py b/llm_providers.py index 5db5cb2..a0aa76d 100644 --- a/llm_providers.py +++ b/llm_providers.py @@ -2,9 +2,59 @@ import os import httpx import json import asyncio +import time from typing import Optional, Dict, List +from collections import deque from config import get_config, save_config +# Monitor de requisições (Rate Limiting Monitoring) +REQUEST_HISTORY = deque() +ALERT_THRESHOLD = 20 +ALERT_WINDOW = 60 +LAST_ALERT_TIME = 0 +ALERT_COOLDOWN = 300 # Evita flood de alertas (5 min) + +async def send_telegram_alert(message: str): + """Envia um alerta diretamente para o Telegram do administrador.""" + token = os.getenv("TELEGRAM_BOT_TOKEN") + chat_id = os.getenv("TELEGRAM_CHAT_ID") + if not token or not chat_id: + return + + url = f"https://api.telegram.org/bot{token}/sendMessage" + payload = {"chat_id": chat_id, "text": f"⚠️ **ALERTA DE MONITORAMENTO**\n\n{message}", "parse_mode": "Markdown"} + try: + async with httpx.AsyncClient() as client: + await client.post(url, json=payload, timeout=10) + except Exception as e: + print(f"Erro ao enviar alerta Telegram: {e}") + +def track_request(): + """Registra uma requisição e verifica se o limite foi atingido.""" + global LAST_ALERT_TIME + now = time.time() + REQUEST_HISTORY.append(now) + + # Remove registros mais antigos que a janela de 60s + while REQUEST_HISTORY and REQUEST_HISTORY[0] < now - ALERT_WINDOW: + REQUEST_HISTORY.popleft() + + # Verifica threshold + if len(REQUEST_HISTORY) > ALERT_THRESHOLD: + # Verifica cooldown para não floodar o Telegram + if now - LAST_ALERT_TIME > ALERT_COOLDOWN: + LAST_ALERT_TIME = now + msg = ( + f"Detectado alto volume de requisições LLM!\n" + f"• Total: {len(REQUEST_HISTORY)} requisições nos últimos {ALERT_WINDOW}s\n" + f"• Limite: {ALERT_THRESHOLD} requisições\n" + f"• Horário: {time.strftime('%H:%M:%S', time.localtime(now))}" + ) + # Como track_request é sync e chamada de locais variados, + # vamos disparar o alerta via background task ou garantir que seja async onde importa. + return msg + return None + # ============================================================ # CONFIGURAÇÃO DE PROVIDERS # ============================================================ @@ -182,7 +232,12 @@ async def get_available_models(provider: str = None) -> List[Dict]: # ============================================================ async def call_llm(provider: str, model: str, prompt: str, system_prompt: str = None, **kwargs) -> str: - """Suporte universal async para chamadas de LLM.""" + """Suporte universal async para chamadas de LLM com monitoramento de tráfego.""" + # Monitoramento de Rate Limit + alert_msg = track_request() + if alert_msg: + asyncio.create_task(send_telegram_alert(alert_msg)) + if provider == "gemini": return await _call_gemini_async(model, prompt, system_prompt) elif provider == "openai":