Spaces:
Runtime error
Runtime error
Upload inference.py with huggingface_hub
Browse files- inference.py +177 -61
inference.py
CHANGED
@@ -1,73 +1,189 @@
|
|
1 |
import google.generativeai as genai
|
2 |
-
import
|
3 |
-
|
4 |
-
import yaml
|
5 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
6 |
-
import torch
|
7 |
|
8 |
class InferenceManager:
|
9 |
-
def __init__(self):
|
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 |
def change_model(self, model_name):
|
39 |
-
|
40 |
-
|
41 |
-
if model_name == '
|
42 |
-
self.
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
-
def
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
try:
|
54 |
-
|
55 |
-
|
56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
|
71 |
except Exception as e:
|
72 |
-
print(f"Error en
|
73 |
-
return "Lo siento, hubo un error
|
|
|
1 |
import google.generativeai as genai
|
2 |
+
from huggingface_utils import HuggingFaceUtils
|
3 |
+
import time
|
|
|
|
|
|
|
4 |
|
5 |
class InferenceManager:
|
6 |
+
def __init__(self, config):
|
7 |
+
"""Inicializar modelos de IA con validaci贸n de configuraci贸n"""
|
8 |
+
try:
|
9 |
+
# Obtener API keys del diccionario anidado
|
10 |
+
api_keys = config.get('api_keys', {})
|
11 |
+
|
12 |
+
# Configurar par谩metros del modelo primero
|
13 |
+
self.generation_config = {
|
14 |
+
"temperature": 0.9,
|
15 |
+
"top_p": 1,
|
16 |
+
"top_k": 1,
|
17 |
+
"max_output_tokens": 2048,
|
18 |
+
}
|
19 |
+
|
20 |
+
self.safety_settings = [
|
21 |
+
{
|
22 |
+
"category": "HARM_CATEGORY_HARASSMENT",
|
23 |
+
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
24 |
+
},
|
25 |
+
{
|
26 |
+
"category": "HARM_CATEGORY_HATE_SPEECH",
|
27 |
+
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
28 |
+
},
|
29 |
+
{
|
30 |
+
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
31 |
+
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
32 |
+
},
|
33 |
+
{
|
34 |
+
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
|
35 |
+
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
36 |
+
},
|
37 |
+
]
|
38 |
+
|
39 |
+
# Validar API keys
|
40 |
+
self.google_api_key = api_keys.get('GOOGLE_API_KEY', '')
|
41 |
+
self.huggingface_token = api_keys.get('HUGGINGFACE_TOKEN', '')
|
42 |
+
|
43 |
+
# Configurar HuggingFace primero como fallback
|
44 |
+
if self.huggingface_token:
|
45 |
+
self.huggingface = HuggingFaceUtils(token=self.huggingface_token)
|
46 |
+
else:
|
47 |
+
print("Advertencia: No se configur贸 HuggingFace Token")
|
48 |
+
self.huggingface = None
|
49 |
+
|
50 |
+
# Intentar configurar Gemini
|
51 |
+
self.max_retries = 3
|
52 |
+
if self.google_api_key:
|
53 |
+
try:
|
54 |
+
genai.configure(api_key=self.google_api_key)
|
55 |
+
self.model = self._init_gemini_model()
|
56 |
+
self.current_model = 'gemini'
|
57 |
+
except Exception as e:
|
58 |
+
print(f"Error inicializando Gemini: {e}")
|
59 |
+
if self.huggingface:
|
60 |
+
print("Cambiando a Mixtral como fallback")
|
61 |
+
self.current_model = 'mixtral'
|
62 |
+
else:
|
63 |
+
raise ValueError("No hay modelos disponibles")
|
64 |
+
else:
|
65 |
+
if self.huggingface:
|
66 |
+
print("Usando Mixtral como modelo principal")
|
67 |
+
self.current_model = 'mixtral'
|
68 |
+
else:
|
69 |
+
raise ValueError("No hay modelos disponibles")
|
70 |
+
|
71 |
+
except Exception as e:
|
72 |
+
print(f"Error en inicializaci贸n: {e}")
|
73 |
+
raise
|
74 |
+
|
75 |
+
def _init_gemini_model(self, attempt=1):
|
76 |
+
"""Inicializar modelo Gemini con reintentos"""
|
77 |
+
try:
|
78 |
+
return genai.GenerativeModel(
|
79 |
+
'gemini-pro',
|
80 |
+
generation_config=self.generation_config,
|
81 |
+
safety_settings=self.safety_settings
|
82 |
)
|
83 |
+
except Exception as e:
|
84 |
+
if attempt < self.max_retries:
|
85 |
+
time.sleep(2 ** attempt)
|
86 |
+
return self._init_gemini_model(attempt + 1)
|
87 |
+
raise
|
88 |
|
89 |
def change_model(self, model_name):
|
90 |
+
"""Cambiar modelo de IA con validaci贸n"""
|
91 |
+
try:
|
92 |
+
if model_name == 'gemini' and hasattr(self, 'model'):
|
93 |
+
self.current_model = 'gemini'
|
94 |
+
return True
|
95 |
+
elif model_name == 'mixtral' and self.huggingface:
|
96 |
+
self.current_model = 'mixtral'
|
97 |
+
return True
|
98 |
+
else:
|
99 |
+
print(f"Modelo solicitado '{model_name}' no est谩 disponible.")
|
100 |
+
return False
|
101 |
+
except Exception as e:
|
102 |
+
print(f"Error cambiando modelo IA: {e}")
|
103 |
+
return False
|
104 |
|
105 |
+
def _generate_gemini_response(self, prompt, attempt=1):
|
106 |
+
"""Generar respuesta de Gemini con reintentos y fallback a Mixtral"""
|
107 |
+
try:
|
108 |
+
response = self.model.generate_content(prompt)
|
109 |
+
return response.text
|
110 |
+
except Exception as e:
|
111 |
+
if "safety" in str(e).lower():
|
112 |
+
return "Lo siento, no puedo responder a eso debido a restricciones de seguridad."
|
113 |
+
elif attempt < self.max_retries:
|
114 |
+
time.sleep(2 ** attempt)
|
115 |
+
return self._generate_gemini_response(prompt, attempt + 1)
|
116 |
+
else:
|
117 |
+
print(f"Error con Gemini, intentando Mixtral: {e}")
|
118 |
+
if self.huggingface:
|
119 |
+
self.current_model = 'mixtral'
|
120 |
+
return self.huggingface.generate_response(prompt)
|
121 |
+
return "Lo siento, el servicio no est谩 respondiendo. Por favor, intenta de nuevo en unos momentos."
|
122 |
|
123 |
+
def _generate_mixtral_response(self, prompt, attempt=1):
|
124 |
+
"""Generar respuesta de Mixtral con reintentos"""
|
125 |
+
try:
|
126 |
+
return self.huggingface.generate_response(prompt)
|
127 |
+
except Exception as e:
|
128 |
+
if attempt < self.max_retries:
|
129 |
+
print(f"Error con Mixtral (intento {attempt}), reintentando: {e}")
|
130 |
+
time.sleep(2 ** attempt)
|
131 |
+
return self._generate_mixtral_response(prompt, attempt + 1)
|
132 |
+
raise
|
133 |
+
|
134 |
+
def get_response(self, prompt, context='', history=None):
|
135 |
+
"""Generar respuesta usando el modelo actual con manejo de errores mejorado"""
|
136 |
try:
|
137 |
+
if not prompt:
|
138 |
+
return "No se proporcion贸 un mensaje"
|
139 |
+
|
140 |
+
# Construir el prompt completo
|
141 |
+
full_prompt = context + "\n\n" if context else ""
|
142 |
+
|
143 |
+
# Agregar historial si existe
|
144 |
+
if history:
|
145 |
+
full_prompt += "Historial de la conversaci贸n:\n"
|
146 |
+
for msg in history:
|
147 |
+
role = "Usuario" if msg["role"] == "user" else "Asistente"
|
148 |
+
full_prompt += f"{role}: {msg['content']}\n"
|
149 |
|
150 |
+
full_prompt += f"\nUsuario: {prompt}"
|
151 |
+
|
152 |
+
# Generar respuesta seg煤n el modelo
|
153 |
+
print(f"Usando modelo: {self.current_model}")
|
154 |
+
try:
|
155 |
+
if self.current_model == 'gemini':
|
156 |
+
response = self._generate_gemini_response(full_prompt)
|
157 |
+
if not response or len(response.strip()) < 10:
|
158 |
+
raise Exception("Respuesta inv谩lida de Gemini")
|
159 |
+
return response
|
160 |
+
elif self.current_model == 'mixtral' and self.huggingface:
|
161 |
+
response = self._generate_mixtral_response(full_prompt)
|
162 |
+
if not response or len(response.strip()) < 10:
|
163 |
+
raise Exception("Respuesta inv谩lida de Mixtral")
|
164 |
+
return response
|
165 |
+
else:
|
166 |
+
return "Lo siento, no hay modelos disponibles en este momento."
|
167 |
+
except Exception as model_error:
|
168 |
+
print(f"Error con el modelo {self.current_model}: {model_error}")
|
169 |
+
|
170 |
+
# Si Gemini falla, intentar con Mixtral
|
171 |
+
if self.current_model == 'gemini' and self.huggingface:
|
172 |
+
print("Cambiando a Mixtral como fallback")
|
173 |
+
self.current_model = 'mixtral'
|
174 |
+
response = self._generate_mixtral_response(full_prompt)
|
175 |
+
if response and len(response.strip()) >= 10:
|
176 |
+
return response
|
177 |
+
# Si Mixtral falla y tenemos Gemini disponible, intentar con Gemini
|
178 |
+
elif self.current_model == 'mixtral' and hasattr(self, 'model'):
|
179 |
+
print("Cambiando a Gemini como fallback")
|
180 |
+
self.current_model = 'gemini'
|
181 |
+
response = self._generate_gemini_response(full_prompt)
|
182 |
+
if response and len(response.strip()) >= 10:
|
183 |
+
return response
|
184 |
+
|
185 |
+
raise Exception("No se pudo obtener una respuesta v谩lida de ning煤n modelo")
|
186 |
|
187 |
except Exception as e:
|
188 |
+
print(f"Error general en get_response: {e}")
|
189 |
+
return "Lo siento, hubo un error inesperado. Por favor, intenta de nuevo."
|