Spaces:
Running
Running
File size: 4,118 Bytes
fc40c4d c5f1e55 fc40c4d c5f1e55 fc40c4d c5f1e55 |
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 |
import requests
import random
import time
# ===============================
# 🤖 Eroha AgentAPI — Auto Model Selector (Guru+ Edition)
# ===============================
# 🧠 Основные доступные модели (все работают через бесплатный HF Inference API)
AVAILABLE_MODELS = {
"mistralai/Mistral-7B-Instruct-v0.2": {
"desc": "Универсальная reasoning-модель с высокой точностью ответов",
"tier": "balanced"
},
"google/gemma-2b-it": {
"desc": "Быстрая и лёгкая модель, подходит для коротких ответов и диалогов",
"tier": "fast"
},
"tiiuae/falcon-7b-instruct": {
"desc": "Разговорная модель с нейтральным стилем",
"tier": "chat"
},
"meta-llama/Llama-3-8b-instruct": {
"desc": "Очень сильная reasoning-модель, но может быть медленной при cold start",
"tier": "guru"
}
}
# 🌐 Hugging Face Inference API базовый URL
HF_API_BASE = "https://api-inference.huggingface.co/models/"
def auto_select_model(prompt: str) -> str:
"""
Автоматически выбирает модель в зависимости от типа запроса.
"""
p = prompt.lower()
if any(x in p for x in ["почему", "объясни", "анализ", "расскажи подробно", "compare", "explain"]):
return "mistralai/Mistral-7B-Instruct-v0.2" # аналитические вопросы
if any(x in p for x in ["коротко", "в двух словах", "summary", "резюме", "описание"]):
return "google/gemma-2b-it" # быстрые ответы
if any(x in p for x in ["напиши", "создай", "придумай", "творческий", "creative"]):
return "tiiuae/falcon-7b-instruct" # креатив
# fallback (по умолчанию “гуру”)
return "meta-llama/Llama-3-8b-instruct"
def query_hf_model(prompt: str) -> str:
"""
Отправляет запрос в Hugging Face Inference API с автоматическим выбором модели.
"""
model = auto_select_model(prompt)
api_url = f"{HF_API_BASE}{model}"
headers = {"Content-Type": "application/json"}
payload = {"inputs": prompt, "options": {"wait_for_model": True}}
print(f"🧠 Выбрана модель: {model}")
try:
response = requests.post(api_url, headers=headers, json=payload, timeout=90)
if response.status_code == 200:
data = response.json()
if isinstance(data, list) and len(data) > 0:
if "generated_text" in data[0]:
return data[0]["generated_text"].strip()
elif isinstance(data[0], str):
return data[0].strip()
elif isinstance(data, dict):
return data.get("generated_text", str(data))
return str(data)
elif response.status_code == 503:
return "⏳ Модель просыпается... подожди несколько секунд и повтори запрос."
elif response.status_code == 401:
return "🔒 Требуется Hugging Face API Token — добавь его в настройки Space."
elif response.status_code == 404:
return f"⚠️ Модель {model} временно недоступна. Попробуй снова или измени запрос."
else:
return f"⚠️ Ошибка API ({response.status_code}): {response.text[:200]}"
except Exception as e:
return f"❌ Ошибка соединения с HF API: {str(e)}"
if __name__ == "__main__":
# 🔧 Тест при локальном запуске
test_prompt = "Объясни, как работает квантовая суперпозиция"
print("🧩 Ответ:", query_hf_model(test_prompt))
|