|
|
import gradio as gr |
|
|
from huggingface_hub import InferenceClient |
|
|
import os |
|
|
import sys |
|
|
|
|
|
print(f"Versão do Python: {sys.version}") |
|
|
print(f"Versão do Gradio: {gr.__version__}") |
|
|
|
|
|
HUGGING_FACE_TOKEN = os.getenv("HUGGING_FACE_HUB_TOKEN") |
|
|
|
|
|
client = InferenceClient( |
|
|
model="google/gemma-7b-it", |
|
|
token=HUGGING_FACE_TOKEN |
|
|
) |
|
|
|
|
|
def responder_gemma(mensagem, historico): |
|
|
mensagens = [] |
|
|
if historico is None: |
|
|
historico = [] |
|
|
|
|
|
for item in historico: |
|
|
if isinstance(item, list) and len(item) == 2: |
|
|
user_msg, bot_msg = item |
|
|
mensagens.append({"role": "user", "content": user_msg}) |
|
|
if bot_msg: |
|
|
mensagens.append({"role": "assistant", "content": bot_msg}) |
|
|
|
|
|
mensagens.append({"role": "user", "content": mensagem}) |
|
|
resposta = "" |
|
|
|
|
|
try: |
|
|
for mensagem_chunk in client.chat_completion( |
|
|
messages=mensagens, |
|
|
max_tokens=300, |
|
|
stream=True, |
|
|
temperature=0.7, |
|
|
top_p=0.9, |
|
|
): |
|
|
if not mensagem_chunk or not isinstance(mensagem_chunk, dict): |
|
|
continue |
|
|
|
|
|
try: |
|
|
conteudo = mensagem_chunk["choices"][0]["delta"].get("content", "") |
|
|
if conteudo.strip(): |
|
|
resposta += conteudo |
|
|
yield resposta |
|
|
|
|
|
|
|
|
except (AttributeError, IndexError, KeyError) as e: |
|
|
print(f"Erro ao processar mensagem do chunk: {e}") |
|
|
continue |
|
|
|
|
|
except Exception as e: |
|
|
print(f"Erro inesperado ao chamar a API do Hugging Face com Gemma: {e}") |
|
|
yield "Ocorreu um erro ao gerar a resposta. Tente novamente." |
|
|
|
|
|
if not resposta.strip(): |
|
|
yield "Nenhuma resposta gerada. Tente novamente." |
|
|
|
|
|
|
|
|
demo = gr.ChatInterface( |
|
|
responder_gemma, |
|
|
title="Benjamin – Assistente Virtual da CEaD - IBC", |
|
|
textbox=gr.Textbox(placeholder="Digite uma mensagem e depois tecle Enter"), |
|
|
examples=[ |
|
|
"O que é Acessibilidade Digital?", |
|
|
"Qual a importância da educação inclusiva?" |
|
|
], |
|
|
theme="soft", |
|
|
fill_height=True, |
|
|
|
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
demo.launch() |