|
import gradio as gr |
|
from huggingface_hub import InferenceClient |
|
|
|
|
|
client = InferenceClient(model="meta-llama/Llama-3.3-70B-Instruct") |
|
|
|
|
|
def responder(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 in client.chat_completion( |
|
mensagens, |
|
max_tokens=300, |
|
stream=True, |
|
temperature=0.4, |
|
top_p=0.8, |
|
): |
|
if not mensagem or not isinstance(mensagem, dict): |
|
continue |
|
|
|
try: |
|
conteudo = mensagem["choices"][0]["delta"].get("content", "") |
|
if conteudo.strip(): |
|
resposta += conteudo |
|
yield resposta |
|
except (AttributeError, IndexError, KeyError) as e: |
|
print(f"Erro ao processar mensagem: {e}") |
|
continue |
|
|
|
except Exception as e: |
|
print(f"Erro inesperado: {e}") |
|
yield "Ocorreu um erro ao gerar a resposta." |
|
|
|
if not resposta.strip(): |
|
yield "Nenhuma resposta gerada. Tente novamente." |
|
|
|
|
|
demo = gr.ChatInterface( |
|
responder, |
|
title="Benjamin – Assistente Virtual da CEaD - IBC. Tire dúvidas com minha inteligência artificial (minha base de dados vai até 2021)", |
|
textbox=gr.Textbox(placeholder="Digite uma mensagem e depois tecle Enter"), |
|
type="messages" |
|
) |
|
|
|
if __name__ == "__main__": |
|
demo.launch() |
|
|