Spaces:
Sleeping
Sleeping
File size: 7,008 Bytes
0c0893a 89ceaa4 459fc0f 95e544d 0c0893a f480b87 0c0893a 95e544d 0c0893a 95e544d 0c0893a 95e544d 89ceaa4 95e544d f480b87 0c0893a 95e544d 0c0893a 95e544d 0c0893a 95e544d de49f0b 95e544d 9db56d8 1c02ede 459fc0f 95e544d 0c0893a 95e544d f480b87 95e544d 459fc0f f480b87 95e544d 0c0893a 95e544d 0c0893a c6523e3 1c02ede 243ac06 95e544d c6523e3 0c0893a 95e544d f480b87 95e544d 0c0893a 95e544d 0c0893a 95e544d 0c0893a 95e544d 0c0893a 95e544d 0c0893a 95e544d 89ceaa4 95e544d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | import os
import requests
import sqlite3
from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from duckduckgo_search import DDGS
app = FastAPI(title="HilmanAI Real Cloud Proxy Gateway")
# --- ÇEVRE DEĞİŞKENLERİ (Hugging Face Secrets'tan çekilir) ---
MY_SECRET_KEY = os.getenv("MY_SECRET_KEY", "sk-hilman-proxy-2026")
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
ANTIGRAVITY_API_KEY = os.getenv("ANTIGRAVITY_API_KEY")
# --- VERİTABANI (İstek Logları ve Hafıza) ---
DB_PATH = "hilman_space_memory.db"
def init_db():
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
role TEXT,
content TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()
except Exception as e:
print(f"DB Başlatma Hatası: {e}")
init_db()
def save_message(role, content):
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("INSERT INTO messages (role, content) VALUES (?, ?)", (role, content))
conn.commit()
conn.close()
except Exception as e:
print(f"DB Kayıt Hatası: {e}")
# --- İNTERNET ARAMA MOTORU ---
def web_search(query: str) -> str:
try:
print(f"[İNTERNET ARAMASI]: '{query}' aranıyor...")
results_text = ""
with DDGS() as ddgs:
results = list(ddgs.text(query, max_results=5))
for r in results:
title = r.get("title", "Başlık Yok")
body = r.get("body", "Açıklama Yok")
href = r.get("href", "#")
results_text += f"- Ürün/Kaynak: {title}\n Özet/Detay: {body}\n Link: {href}\n\n"
return results_text if results_text else "Web aramasında sonuç bulunamadı."
except Exception as e:
print(f"[ARAMA HATASI]: {e}")
return f"Arama sırasında hata oluştu: {e}"
class ChatRequest(BaseModel):
model: str = "google/gemini-2.0-flash-lite-001"
messages: list
temperature: float = 0.2
# --- SUNUCU SAĞLIK VE DURUM KONTROLÜ ---
@app.get("/")
def root():
return {
"status": "online",
"message": "HilmanAI Cloud Proxy is active and running 24/7, Halil.",
"endpoints": {
"chat_completions": "/v1/chat/completions",
"status": "/server-status"
}
}
@app.get("/server-status")
def server_status():
return {
"service": "Running",
"port": 7860,
"auth_enabled": True,
"providers_loaded": {
"openrouter": bool(OPENROUTER_API_KEY),
"antigravity": bool(ANTIGRAVITY_API_KEY)
}
}
# --- GERÇEK PROXY İSTEK YÖNLENDİRİCİSİ ---
@app.post("/v1/chat/completions")
def proxy_chat_completions(req: ChatRequest, authorization: str = Header(None)):
# 1. Güvenlik ve Yetkilendirme Kontrolü
if not authorization or authorization != f"Bearer {MY_SECRET_KEY}":
raise HTTPException(status_code=401, detail="Yetkisiz erişim! Geçersiz Secret Key.")
# 2. Gelen Mesajları Veritabanına Kaydet
last_user_msg = ""
for m in req.messages:
if isinstance(m, dict):
role = m.get("role", "user")
content = m.get("content", "")
if role == "user":
last_user_msg = content
save_message(role, content)
# 3. Canlı İnternet Arama Tetikleyicisi
search_keywords = ["bul", "ara", "fiyat", "en ucuz", "nerede", "satın al", "karşılaştır", "incele"]
search_context = ""
if any(kw in last_user_msg.lower() for kw in search_keywords):
search_results = web_search(last_user_msg)
search_context = f"\n\n[CANLI İNTERNET ARAMA SONUÇLARI]:\n{search_results}\nYukarıdaki güncel internet verilerini kullanarak Halil'e net, fiyatlı ve detaylı bilgi sun."
# Sistem Talimatı Ekleme
system_instruction = {
"role": "system",
"content": (
"Sen HilmanAI'sın. Kullanıcıya her zaman 'Halil' diye hitap edeceksin. "
"İşletim sistemi WINDOWS'tur. "
"Halil internetten ürün, fiyat veya araştırma istediğinde sana sağlanan [CANLI İNTERNET ARAMA SONUÇLARI]'nı kullan."
)
}
full_messages = [system_instruction] + req.messages
if search_context and len(full_messages) > 1:
if isinstance(full_messages[-1], dict):
full_messages[-1]["content"] += search_context
ai_response_text = "Tüm yapay zeka servisleri şu an yanıt vermiyor."
# 4. Antigravity API Üzerinden Proxy İsteği
if ANTIGRAVITY_API_KEY:
try:
headers = {
"Authorization": f"Bearer {ANTIGRAVITY_API_KEY.strip()}",
"Content-Type": "application/json"
}
payload = {
"model": "gemini-2.0-flash",
"messages": full_messages,
"temperature": req.temperature
}
res = requests.post("https://api.antigravity.dev/v1/chat/completions", json=payload, headers=headers, timeout=15)
if res.status_code == 200:
data = res.json()
ai_response_text = data["choices"][0]["message"]["content"]
save_message("assistant", ai_response_text)
return res.json()
except Exception as e:
print(f"Antigravity Proxy Hatası: {e}")
# 5. OpenRouter API Üzerinden Proxy İsteği (Yedek)
if OPENROUTER_API_KEY:
try:
headers = {
"Authorization": f"Bearer {OPENROUTER_API_KEY.strip()}",
"Content-Type": "application/json",
"HTTP-Referer": "https://huggingface.co",
"X-Title": "HilmanAI"
}
fallback_models = [
req.model,
"google/gemini-2.0-flash-lite-001",
"meta-llama/llama-3.3-70b-instruct"
]
for model_name in fallback_models:
payload = {
"model": model_name,
"messages": full_messages,
"temperature": req.temperature
}
res = requests.post("https://openrouter.ai/api/v1/chat/completions", json=payload, headers=headers, timeout=15)
if res.status_code == 200:
data = res.json()
ai_response_text = data["choices"][0]["message"]["content"]
save_message("assistant", ai_response_text)
return res.json()
except Exception as e:
print(f"OpenRouter Proxy Hatası: {e}")
raise HTTPException(status_code=500, detail="Hiçbir AI Sağlayıcısından yanıt alınamadı.") |