🚀 Auto-deploy: BotVPS atualizado em 29/04/2026 01:10:16
This commit is contained in:
@@ -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":
|
||||
|
||||
Reference in New Issue
Block a user