File size: 2,417 Bytes
23927e6
ec53365
97b2894
1ecd827
94472f0
1ecd827
a77c5e5
97b2894
f913617
94472f0
f913617
97b2894
a77c5e5
f913617
 
 
0251b38
 
 
d5e68ae
 
 
 
 
a77c5e5
d5e68ae
 
0251b38
a77c5e5
ec53365
 
f913617
a77c5e5
 
 
 
 
d5e68ae
f913617
d5e68ae
 
 
f913617
a77c5e5
d5e68ae
a77c5e5
 
 
d5e68ae
f913617
a77c5e5
d5e68ae
ec53365
f913617
a77c5e5
94472f0
ec53365
a77c5e5
94472f0
a77c5e5
ec53365
a77c5e5
cf85019
a77c5e5
 
e7b34ce
f913617
 
a77c5e5
 
 
ec53365
94472f0
23927e6
97b2894
1
2
3
4
5
6
7
8
9
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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__}") # Ainda mostrará 5.38.2, mas o código irá rodar

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
                # else: # Comentei para evitar mensagens desnecessárias nos logs
                #     print(f"Chunk sem conteúdo: {mensagem_chunk}")
            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."

# Interface do chat com labels em português
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()