Spaces:
Sleeping
Sleeping
Alteração modelo...
Browse files12345678910112 unmodified lines141516171819202 unmodified lines232425262728293031323334353637383940414243444546import osimport gradio as grfrom huggingface_hub import InferenceClientMODEL_ID = "unsloth/Qwen3-30B-A3B-GGUF"token = os.environ.get("HF_TOKEN")client = InferenceClient(model=MODEL_ID, token=token)def respond(message,history: list[tuple[str, str]],2 unmodified linestemperature,top_p,):# Monta o prompt tipo chat manualmenteprompt = f"{system_message}\n\n"for user_msg, bot_msg in history:if user_msg:2 unmodified linesprompt += f"Assistant: {bot_msg}\n"prompt += f"User: {message}\nAssistant:"# Chama o endpoint de geração de texto normal, sem streamingresponse = client.text_generation(prompt,max_new_tokens=max_tokens,temperature=temperature,top_p=top_p,)# A resposta vem como string simplesyield responsedemo = gr.ChatInterface(respond,additional_inputs=[gr.Textbox(value="You are a friendly Chatbot.", label="System message"),gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),],)if __name__ == "__main__":123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566672 unmodified lines7071727374757677787980812 unmodified lines84858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import osimport gradio as grfrom huggingface_hub import InferenceClientfrom huggingface_hub.utils import HfHubHTTPError# Modelo Mistral Instruct disponível no HubMODEL_ID = "mistralai/Mistral-7B-Instruct-v0.2"# token vindo do secret HF_TOKEN do Space (ou env local)token = os.environ.get("HF_TOKEN")# Cliente (se token for None, o client tenta usar config local)client = InferenceClient(model=MODEL_ID, token=token)def _extract_text_from_response(resp):"""Tenta extrair texto de várias possíveis formas de retorno da API.Retorna string sempre."""# string diretaif isinstance(resp, str):return resp# dataclass-like (possível)try:# alguns SDKs retornam objeto com atributo 'generated_text' ou 'text'if hasattr(resp, "generated_text"):return getattr(resp, "generated_text") or ""if hasattr(resp, "text"):return getattr(resp, "text") or ""except Exception:pass# dict-like formas comunsif isinstance(resp, dict):# chaves óbviasfor key in ("generated_text", "generated_texts", "text", "output_text", "result"):if key in resp:v = resp[key]if isinstance(v, list) and v:return v[0] if isinstance(v[0], str) else str(v[0])if isinstance(v, str):return v# choices -> message -> content (formato chat-like)if "choices" in resp and isinstance(resp["choices"], list) and resp["choices"]:first = resp["choices"][0]if isinstance(first, dict):# try message.contentif "message" in first and isinstance(first["message"], dict) and "content" in first["message"]:maybe = first["message"]["content"]if isinstance(maybe, str):return maybe# try text or content directlyfor k in ("text", "content", "generated_text"):if k in first and isinstance(first[k], str):return first[k]# fallbacktry:return str(resp)except Exception:return "<unable to decode response>"def respond(message,history: list[tuple[str, str]],2 unmodified linestemperature,top_p,):# valida tokenif not token:yield "ERRO: variável de ambiente HF_TOKEN não encontrada. Adicione um secret HF_TOKEN no Settings do Space."return# monta prompt estilo chat (simples)prompt = f"{system_message}\n\n"for user_msg, bot_msg in history:if user_msg:2 unmodified linesprompt += f"Assistant: {bot_msg}\n"prompt += f"User: {message}\nAssistant:"try:# chamada sem streaming (resposta completa)out = client.text_generation(prompt,max_new_tokens=int(max_tokens),temperature=float(temperature),top_p=float(top_p),do_sample=True,)except HfHubHTTPError as e:# captura erros HTTP da Hugging Face e retorna mensagem legívelyield f"ERRO na chamada de inferência: {e}\n(verifique HF_TOKEN, permissões e se o modelo está disponível via Inference API)"returnexcept Exception as e:yield f"Erro inesperado ao chamar a API: {e}"return# extrai texto (robusto a vários formatos de retorno)text = _extract_text_from_response(out)yield textdemo = gr.ChatInterface(respond,additional_inputs=[gr.Textbox(value="You are a helpful assistant.", label="System message"),gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),gr.Slider(minimum=0.0, maximum=2.0, value=0.7, step=0.05, label="Temperature"),gr.Slider(minimum=0.0, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),],title="Chat com Mistral-7B",)if __name__ == "__main__":
app.py+88-14