Spaces:
Sleeping
Sleeping
Modelo Fallback
Browse files
app.py
CHANGED
@@ -3,37 +3,25 @@ import gradio as gr
|
|
3 |
from huggingface_hub import InferenceClient
|
4 |
from huggingface_hub.utils import HfHubHTTPError
|
5 |
|
6 |
-
# Modelo
|
7 |
-
|
|
|
|
|
8 |
|
9 |
# token vindo do secret HF_TOKEN do Space (ou env local)
|
10 |
token = os.environ.get("HF_TOKEN")
|
11 |
|
12 |
-
# Cliente (se token for None, o client tenta usar config local)
|
13 |
-
client = InferenceClient(model=MODEL_ID, token=token)
|
14 |
-
|
15 |
def _extract_text_from_response(resp):
|
16 |
-
"""
|
17 |
-
Tenta extrair texto de várias possíveis formas de retorno da API.
|
18 |
-
Retorna string sempre.
|
19 |
-
"""
|
20 |
-
# string direta
|
21 |
if isinstance(resp, str):
|
22 |
return resp
|
23 |
-
|
24 |
-
# dataclass-like (possível)
|
25 |
try:
|
26 |
-
# alguns SDKs retornam objeto com atributo 'generated_text' ou 'text'
|
27 |
if hasattr(resp, "generated_text"):
|
28 |
return getattr(resp, "generated_text") or ""
|
29 |
if hasattr(resp, "text"):
|
30 |
return getattr(resp, "text") or ""
|
31 |
except Exception:
|
32 |
pass
|
33 |
-
|
34 |
-
# dict-like formas comuns
|
35 |
if isinstance(resp, dict):
|
36 |
-
# chaves óbvias
|
37 |
for key in ("generated_text", "generated_texts", "text", "output_text", "result"):
|
38 |
if key in resp:
|
39 |
v = resp[key]
|
@@ -41,27 +29,31 @@ def _extract_text_from_response(resp):
|
|
41 |
return v[0] if isinstance(v[0], str) else str(v[0])
|
42 |
if isinstance(v, str):
|
43 |
return v
|
44 |
-
|
45 |
-
# choices -> message -> content (formato chat-like)
|
46 |
if "choices" in resp and isinstance(resp["choices"], list) and resp["choices"]:
|
47 |
first = resp["choices"][0]
|
48 |
if isinstance(first, dict):
|
49 |
-
# try message.content
|
50 |
if "message" in first and isinstance(first["message"], dict) and "content" in first["message"]:
|
51 |
maybe = first["message"]["content"]
|
52 |
if isinstance(maybe, str):
|
53 |
return maybe
|
54 |
-
# try text or content directly
|
55 |
for k in ("text", "content", "generated_text"):
|
56 |
if k in first and isinstance(first[k], str):
|
57 |
return first[k]
|
58 |
-
|
59 |
-
# fallback
|
60 |
try:
|
61 |
return str(resp)
|
62 |
except Exception:
|
63 |
return "<unable to decode response>"
|
64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
def respond(
|
66 |
message,
|
67 |
history: list[tuple[str, str]],
|
@@ -70,12 +62,10 @@ def respond(
|
|
70 |
temperature,
|
71 |
top_p,
|
72 |
):
|
73 |
-
# valida token
|
74 |
if not token:
|
75 |
-
yield "ERRO: variável
|
76 |
return
|
77 |
|
78 |
-
# monta prompt estilo chat (simples)
|
79 |
prompt = f"{system_message}\n\n"
|
80 |
for user_msg, bot_msg in history:
|
81 |
if user_msg:
|
@@ -85,27 +75,30 @@ def respond(
|
|
85 |
prompt += f"User: {message}\nAssistant:"
|
86 |
|
87 |
try:
|
88 |
-
|
89 |
-
out = client.text_generation(
|
90 |
-
prompt,
|
91 |
-
max_new_tokens=int(max_tokens),
|
92 |
-
temperature=float(temperature),
|
93 |
-
top_p=float(top_p),
|
94 |
-
do_sample=True,
|
95 |
-
)
|
96 |
except HfHubHTTPError as e:
|
97 |
-
|
98 |
-
|
99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
100 |
except Exception as e:
|
101 |
yield f"Erro inesperado ao chamar a API: {e}"
|
102 |
return
|
103 |
|
104 |
-
# extrai texto (robusto a vários formatos de retorno)
|
105 |
text = _extract_text_from_response(out)
|
106 |
yield text
|
107 |
|
108 |
-
|
109 |
demo = gr.ChatInterface(
|
110 |
respond,
|
111 |
additional_inputs=[
|
@@ -114,7 +107,7 @@ demo = gr.ChatInterface(
|
|
114 |
gr.Slider(minimum=0.0, maximum=2.0, value=0.7, step=0.05, label="Temperature"),
|
115 |
gr.Slider(minimum=0.0, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
|
116 |
],
|
117 |
-
title="Chat com
|
118 |
)
|
119 |
|
120 |
if __name__ == "__main__":
|
|
|
3 |
from huggingface_hub import InferenceClient
|
4 |
from huggingface_hub.utils import HfHubHTTPError
|
5 |
|
6 |
+
# Modelo preferido
|
7 |
+
PREFERRED_MODEL = os.environ.get("MODEL_ID", "mistralai/Mistral-7B-Instruct-v0.2")
|
8 |
+
# Modelo de fallback atualizado
|
9 |
+
FALLBACK_MODEL = os.environ.get("FALLBACK_MODEL", "unsloth/Llama-3.2-3B-Instruct")
|
10 |
|
11 |
# token vindo do secret HF_TOKEN do Space (ou env local)
|
12 |
token = os.environ.get("HF_TOKEN")
|
13 |
|
|
|
|
|
|
|
14 |
def _extract_text_from_response(resp):
|
|
|
|
|
|
|
|
|
|
|
15 |
if isinstance(resp, str):
|
16 |
return resp
|
|
|
|
|
17 |
try:
|
|
|
18 |
if hasattr(resp, "generated_text"):
|
19 |
return getattr(resp, "generated_text") or ""
|
20 |
if hasattr(resp, "text"):
|
21 |
return getattr(resp, "text") or ""
|
22 |
except Exception:
|
23 |
pass
|
|
|
|
|
24 |
if isinstance(resp, dict):
|
|
|
25 |
for key in ("generated_text", "generated_texts", "text", "output_text", "result"):
|
26 |
if key in resp:
|
27 |
v = resp[key]
|
|
|
29 |
return v[0] if isinstance(v[0], str) else str(v[0])
|
30 |
if isinstance(v, str):
|
31 |
return v
|
|
|
|
|
32 |
if "choices" in resp and isinstance(resp["choices"], list) and resp["choices"]:
|
33 |
first = resp["choices"][0]
|
34 |
if isinstance(first, dict):
|
|
|
35 |
if "message" in first and isinstance(first["message"], dict) and "content" in first["message"]:
|
36 |
maybe = first["message"]["content"]
|
37 |
if isinstance(maybe, str):
|
38 |
return maybe
|
|
|
39 |
for k in ("text", "content", "generated_text"):
|
40 |
if k in first and isinstance(first[k], str):
|
41 |
return first[k]
|
|
|
|
|
42 |
try:
|
43 |
return str(resp)
|
44 |
except Exception:
|
45 |
return "<unable to decode response>"
|
46 |
|
47 |
+
def _call_model(model_id, prompt, max_new_tokens, temperature, top_p):
|
48 |
+
client = InferenceClient(model=model_id, token=token)
|
49 |
+
return client.text_generation(
|
50 |
+
prompt,
|
51 |
+
max_new_tokens=int(max_new_tokens),
|
52 |
+
temperature=float(temperature),
|
53 |
+
top_p=float(top_p),
|
54 |
+
do_sample=True,
|
55 |
+
)
|
56 |
+
|
57 |
def respond(
|
58 |
message,
|
59 |
history: list[tuple[str, str]],
|
|
|
62 |
temperature,
|
63 |
top_p,
|
64 |
):
|
|
|
65 |
if not token:
|
66 |
+
yield "ERRO: variável HF_TOKEN não encontrada. Adicione o secret HF_TOKEN no Settings do Space."
|
67 |
return
|
68 |
|
|
|
69 |
prompt = f"{system_message}\n\n"
|
70 |
for user_msg, bot_msg in history:
|
71 |
if user_msg:
|
|
|
75 |
prompt += f"User: {message}\nAssistant:"
|
76 |
|
77 |
try:
|
78 |
+
out = _call_model(PREFERRED_MODEL, prompt, max_tokens, temperature, top_p)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
except HfHubHTTPError as e:
|
80 |
+
try:
|
81 |
+
code = e.response.status_code if e.response is not None else None
|
82 |
+
except Exception:
|
83 |
+
code = None
|
84 |
+
|
85 |
+
if code == 404:
|
86 |
+
yield f"Aviso: modelo `{PREFERRED_MODEL}` não disponível via Inference API (404). Tentando fallback para `{FALLBACK_MODEL}`..."
|
87 |
+
try:
|
88 |
+
out = _call_model(FALLBACK_MODEL, prompt, max_tokens, temperature, top_p)
|
89 |
+
except Exception as e2:
|
90 |
+
yield f"Falha no fallback para {FALLBACK_MODEL}: {e2}"
|
91 |
+
return
|
92 |
+
else:
|
93 |
+
yield f"ERRO na chamada de inferência: {e}\n(verifique HF_TOKEN, permissões e se o modelo está disponível via Inference API)"
|
94 |
+
return
|
95 |
except Exception as e:
|
96 |
yield f"Erro inesperado ao chamar a API: {e}"
|
97 |
return
|
98 |
|
|
|
99 |
text = _extract_text_from_response(out)
|
100 |
yield text
|
101 |
|
|
|
102 |
demo = gr.ChatInterface(
|
103 |
respond,
|
104 |
additional_inputs=[
|
|
|
107 |
gr.Slider(minimum=0.0, maximum=2.0, value=0.7, step=0.05, label="Temperature"),
|
108 |
gr.Slider(minimum=0.0, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
|
109 |
],
|
110 |
+
title="Chat (Mistral fallback com Llama 3.2 3B)",
|
111 |
)
|
112 |
|
113 |
if __name__ == "__main__":
|