Yermek68 commited on
Commit
c5f1e55
·
verified ·
1 Parent(s): e08a706

Create core/models.py

Browse files
Files changed (1) hide show
  1. core/models.py +93 -12
core/models.py CHANGED
@@ -1,15 +1,96 @@
1
  import requests
 
 
2
 
3
- def query_hf_model(prompt: str, model: str = "microsoft/phi-3.5-mini-instruct") -> str:
4
- api_url = f"https://api-inference.huggingface.co/models/{model}"
5
- response = requests.post(api_url, headers={"Content-Type": "application/json"}, json={"inputs": prompt})
6
- if response.status_code == 200:
7
- try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  data = response.json()
9
- if isinstance(data, list) and len(data) > 0 and "generated_text" in data[0]:
10
- return data[0]["generated_text"].strip()
11
- return data
12
- except Exception:
13
- return response.text
14
- else:
15
- return f"⚠️ Ошибка модели: {response.status_code} — {response.text}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import requests
2
+ import random
3
+ import time
4
 
5
+ # ===============================
6
+ # 🤖 Eroha AgentAPI — Auto Model Selector (Guru+ Edition)
7
+ # ===============================
8
+
9
+ # 🧠 Основные доступные модели (все работают через бесплатный HF Inference API)
10
+ AVAILABLE_MODELS = {
11
+ "mistralai/Mistral-7B-Instruct-v0.2": {
12
+ "desc": "Универсальная reasoning-модель с высокой точностью ответов",
13
+ "tier": "balanced"
14
+ },
15
+ "google/gemma-2b-it": {
16
+ "desc": "Быстрая и лёгкая модель, подходит для коротких ответов и диалогов",
17
+ "tier": "fast"
18
+ },
19
+ "tiiuae/falcon-7b-instruct": {
20
+ "desc": "Разговорная модель с нейтральным стилем",
21
+ "tier": "chat"
22
+ },
23
+ "meta-llama/Llama-3-8b-instruct": {
24
+ "desc": "Очень сильная reasoning-модель, но может быть медленной при cold start",
25
+ "tier": "guru"
26
+ }
27
+ }
28
+
29
+ # 🌐 Hugging Face Inference API базовый URL
30
+ HF_API_BASE = "https://api-inference.huggingface.co/models/"
31
+
32
+
33
+ def auto_select_model(prompt: str) -> str:
34
+ """
35
+ Автоматически выбирает модель в зависимости от типа запроса.
36
+ """
37
+ p = prompt.lower()
38
+
39
+ if any(x in p for x in ["почему", "объясни", "анализ", "расскажи подробно", "compare", "explain"]):
40
+ return "mistralai/Mistral-7B-Instruct-v0.2" # аналитические вопросы
41
+
42
+ if any(x in p for x in ["коротко", "в двух словах", "summary", "резюме", "описание"]):
43
+ return "google/gemma-2b-it" # быстрые ответы
44
+
45
+ if any(x in p for x in ["напиши", "создай", "придумай", "творческий", "creative"]):
46
+ return "tiiuae/falcon-7b-instruct" # креатив
47
+
48
+ # fallback (по умолчанию “гуру”)
49
+ return "meta-llama/Llama-3-8b-instruct"
50
+
51
+
52
+ def query_hf_model(prompt: str) -> str:
53
+ """
54
+ Отправляет запрос в Hugging Face Inference API с автоматическим выбором модели.
55
+ """
56
+ model = auto_select_model(prompt)
57
+ api_url = f"{HF_API_BASE}{model}"
58
+ headers = {"Content-Type": "application/json"}
59
+ payload = {"inputs": prompt, "options": {"wait_for_model": True}}
60
+
61
+ print(f"🧠 Выбрана модель: {model}")
62
+
63
+ try:
64
+ response = requests.post(api_url, headers=headers, json=payload, timeout=90)
65
+
66
+ if response.status_code == 200:
67
  data = response.json()
68
+ if isinstance(data, list) and len(data) > 0:
69
+ if "generated_text" in data[0]:
70
+ return data[0]["generated_text"].strip()
71
+ elif isinstance(data[0], str):
72
+ return data[0].strip()
73
+ elif isinstance(data, dict):
74
+ return data.get("generated_text", str(data))
75
+ return str(data)
76
+
77
+ elif response.status_code == 503:
78
+ return "⏳ Модель просыпается... подожди несколько секунд и повтори запрос."
79
+
80
+ elif response.status_code == 401:
81
+ return "🔒 Требуется Hugging Face API Token — добавь его в настройки Space."
82
+
83
+ elif response.status_code == 404:
84
+ return f"⚠️ Модель {model} временно недоступна. Попробуй снова или измени запрос."
85
+
86
+ else:
87
+ return f"⚠️ Ошибка API ({response.status_code}): {response.text[:200]}"
88
+
89
+ except Exception as e:
90
+ return f"❌ Ошибка соединения с HF API: {str(e)}"
91
+
92
+
93
+ if __name__ == "__main__":
94
+ # 🔧 Тест при локальном запуске
95
+ test_prompt = "Объясни, как работает квантовая суперпозиция"
96
+ print("🧩 Ответ:", query_hf_model(test_prompt))