Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,78 +4,72 @@ from fastapi.responses import HTMLResponse
|
|
| 4 |
|
| 5 |
app = FastAPI()
|
| 6 |
|
| 7 |
-
# Pool de 15 Chaves -
|
| 8 |
KEYS = [os.getenv(f"OR_KEY_{i}") for i in range(1, 16)]
|
| 9 |
KEYS = [k for k in KEYS if k and k.strip()]
|
| 10 |
|
| 11 |
-
# MAPEAMENTO UNIFICADO
|
| 12 |
-
# Usamos sufixos para que o Python aceite as chaves únicas
|
| 13 |
MODEL_MAP = {
|
| 14 |
-
"aria_med": "google/gemini-2.5-pro:free", #
|
| 15 |
-
"aria_logic": "qwen/qwen3-coder-480b:free", #
|
| 16 |
-
"aria_vision": "nvidia/nemotron-nano-12b-2-vl:free", #
|
| 17 |
-
"aria_brain": "meta-llama/llama-3.3-70b-instruct:free", # Cérebro
|
| 18 |
-
"aria_default": "qwen/qwen3-coder:free"
|
| 19 |
}
|
| 20 |
|
| 21 |
@app.get("/", response_class=HTMLResponse)
|
| 22 |
async def root():
|
| 23 |
-
status = "🟢
|
| 24 |
return f"""
|
| 25 |
-
<body style='background:#
|
| 26 |
-
<h1 style='border
|
| 27 |
-
<p style='font-size:1.5em;'>
|
| 28 |
-
<p style='color:#
|
| 29 |
</body>
|
| 30 |
"""
|
| 31 |
|
| 32 |
@app.post("/v1/chat/completions")
|
| 33 |
async def proxy(request: Request):
|
| 34 |
if not KEYS:
|
| 35 |
-
return Response(content='{"error": "
|
| 36 |
|
| 37 |
body = await request.json()
|
| 38 |
incoming_model = body.get("model", "")
|
| 39 |
msg_content = str(body.get("messages", "")).lower()
|
| 40 |
|
| 41 |
-
# ---
|
| 42 |
-
|
| 43 |
-
# 1. Ordem Direta (Prefixo Fortune)
|
| 44 |
if "fortune/" in incoming_model:
|
|
|
|
| 45 |
target = incoming_model.replace("fortune/", "", 1)
|
| 46 |
-
print(f"🎯 Comando Manual: {target}")
|
| 47 |
-
|
| 48 |
-
# 2. Seleção Automática (Aria detecta o contexto)
|
| 49 |
else:
|
| 50 |
-
#
|
| 51 |
-
if any(word in msg_content for word in ["
|
| 52 |
target = MODEL_MAP["aria_med"]
|
| 53 |
-
elif any(word in msg_content for word in ["nexos", "
|
| 54 |
target = MODEL_MAP["aria_logic"]
|
| 55 |
-
elif any(word in msg_content for word in ["nutrilens", "
|
| 56 |
target = MODEL_MAP["aria_vision"]
|
| 57 |
-
elif "aria" in msg_content:
|
| 58 |
-
target = MODEL_MAP["aria_brain"]
|
| 59 |
else:
|
| 60 |
-
target = MODEL_MAP["
|
| 61 |
-
|
| 62 |
-
body["model"] = target
|
| 63 |
|
| 64 |
-
#
|
| 65 |
-
|
|
|
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
async with httpx.AsyncClient() as client:
|
| 68 |
-
for attempt in range(
|
| 69 |
selected_key = random.choice(KEYS)
|
| 70 |
headers = {
|
| 71 |
"Authorization": f"Bearer {selected_key}",
|
| 72 |
-
"X-Title": "
|
| 73 |
-
"HTTP-Referer": "https://fortune-dev-moz.io",
|
| 74 |
"Content-Type": "application/json"
|
| 75 |
}
|
| 76 |
|
| 77 |
try:
|
| 78 |
-
# Timeout de 120s para modelos massivos
|
| 79 |
resp = await client.post(
|
| 80 |
"https://openrouter.ai/api/v1/chat/completions",
|
| 81 |
json=body, headers=headers, timeout=120.0
|
|
@@ -84,22 +78,17 @@ async def proxy(request: Request):
|
|
| 84 |
if resp.status_code == 200:
|
| 85 |
return Response(content=resp.content, status_code=200)
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
continue
|
| 90 |
-
|
| 91 |
except Exception as e:
|
| 92 |
-
print(f"
|
| 93 |
await asyncio.sleep(0.3)
|
| 94 |
continue
|
| 95 |
|
| 96 |
-
#
|
| 97 |
body["model"] = "openrouter/free"
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
return Response(content=emerg_resp.content, status_code=emerg_resp.status_code)
|
| 101 |
-
except:
|
| 102 |
-
return Response(content='{"error": "Falha crítica no Escudo. Reinicie as chaves."}', status_code=503)
|
| 103 |
|
| 104 |
if __name__ == "__main__":
|
| 105 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 4 |
|
| 5 |
app = FastAPI()
|
| 6 |
|
| 7 |
+
# Pool de 15 Chaves - Arsenal Aria
|
| 8 |
KEYS = [os.getenv(f"OR_KEY_{i}") for i in range(1, 16)]
|
| 9 |
KEYS = [k for k in KEYS if k and k.strip()]
|
| 10 |
|
| 11 |
+
# MAPEAMENTO UNIFICADO ARIA (Com sufixos únicos para o Python)
|
|
|
|
| 12 |
MODEL_MAP = {
|
| 13 |
+
"aria_med": "google/gemini-2.5-pro:free", # Vitalis
|
| 14 |
+
"aria_logic": "qwen/qwen3-coder-480b:free", # Nexos
|
| 15 |
+
"aria_vision": "nvidia/nemotron-nano-12b-2-vl:free", # Nutrilens
|
| 16 |
+
"aria_brain": "meta-llama/llama-3.3-70b-instruct:free", # Cérebro Principal
|
| 17 |
+
"aria_default": "qwen/qwen3-coder:free"
|
| 18 |
}
|
| 19 |
|
| 20 |
@app.get("/", response_class=HTMLResponse)
|
| 21 |
async def root():
|
| 22 |
+
status = "🟢 SISTEMA OPERACIONAL" if KEYS else "🔴 FALHA NAS CHAVES"
|
| 23 |
return f"""
|
| 24 |
+
<body style='background:#0a0a0a; color:#00ff99; font-family:monospace; text-align:center; padding-top:50px;'>
|
| 25 |
+
<h1 style='border: 2px solid #00ff99; display:inline-block; padding:20px;'>🛡️ ARIA SOVEREIGN SHIELD V2.5</h1>
|
| 26 |
+
<p style='font-size:1.5em;'>Chaves Ativas: {len(KEYS)} | Local: Beira, MZ</p>
|
| 27 |
+
<p style='color:#555;'>Status: {status}</p>
|
| 28 |
</body>
|
| 29 |
"""
|
| 30 |
|
| 31 |
@app.post("/v1/chat/completions")
|
| 32 |
async def proxy(request: Request):
|
| 33 |
if not KEYS:
|
| 34 |
+
return Response(content='{"error": "Adicione as chaves nos Secrets do HF!"}', status_code=500)
|
| 35 |
|
| 36 |
body = await request.json()
|
| 37 |
incoming_model = body.get("model", "")
|
| 38 |
msg_content = str(body.get("messages", "")).lower()
|
| 39 |
|
| 40 |
+
# --- LOGICA DE ROTEAMENTO ---
|
|
|
|
|
|
|
| 41 |
if "fortune/" in incoming_model:
|
| 42 |
+
# Extrai o modelo real enviado pelo CEO
|
| 43 |
target = incoming_model.replace("fortune/", "", 1)
|
|
|
|
|
|
|
|
|
|
| 44 |
else:
|
| 45 |
+
# Seleção por contexto se o CEO não especificar fortune/
|
| 46 |
+
if any(word in msg_content for word in ["medicina", "vitalis", "paciente"]):
|
| 47 |
target = MODEL_MAP["aria_med"]
|
| 48 |
+
elif any(word in msg_content for word in ["nexos", "venda", "gestão", "erp"]):
|
| 49 |
target = MODEL_MAP["aria_logic"]
|
| 50 |
+
elif any(word in msg_content for word in ["nutrilens", "vejo", "câmara", "visão"]):
|
| 51 |
target = MODEL_MAP["aria_vision"]
|
|
|
|
|
|
|
| 52 |
else:
|
| 53 |
+
target = MODEL_MAP["aria_brain"]
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
# Correção de Segurança: Garante que modelos free tenham o sufixo :free
|
| 56 |
+
if "instruct" in target and not target.endswith(":free"):
|
| 57 |
+
target = f"{target}:free"
|
| 58 |
|
| 59 |
+
body["model"] = target
|
| 60 |
+
print(f"📡 Roteando para: {target}")
|
| 61 |
+
|
| 62 |
+
# --- CICLO DE RESILIÊNCIA ---
|
| 63 |
async with httpx.AsyncClient() as client:
|
| 64 |
+
for attempt in range(5):
|
| 65 |
selected_key = random.choice(KEYS)
|
| 66 |
headers = {
|
| 67 |
"Authorization": f"Bearer {selected_key}",
|
| 68 |
+
"X-Title": "Aria_Sovereign",
|
|
|
|
| 69 |
"Content-Type": "application/json"
|
| 70 |
}
|
| 71 |
|
| 72 |
try:
|
|
|
|
| 73 |
resp = await client.post(
|
| 74 |
"https://openrouter.ai/api/v1/chat/completions",
|
| 75 |
json=body, headers=headers, timeout=120.0
|
|
|
|
| 78 |
if resp.status_code == 200:
|
| 79 |
return Response(content=resp.content, status_code=200)
|
| 80 |
|
| 81 |
+
print(f"⚠️ Tentativa {attempt+1} falhou (Status {resp.status_code}). Rodando chave...")
|
| 82 |
+
|
|
|
|
|
|
|
| 83 |
except Exception as e:
|
| 84 |
+
print(f"❌ Erro de rede: {str(e)}")
|
| 85 |
await asyncio.sleep(0.3)
|
| 86 |
continue
|
| 87 |
|
| 88 |
+
# Fallback Final para o roteador livre
|
| 89 |
body["model"] = "openrouter/free"
|
| 90 |
+
emerg = await client.post("https://openrouter.ai/api/v1/chat/completions", json=body, headers=headers, timeout=60.0)
|
| 91 |
+
return Response(content=emerg.content, status_code=emerg.status_code)
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
if __name__ == "__main__":
|
| 94 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|