File size: 2,666 Bytes
9a70e05
782d7c5
 
2d03a43
c048479
6a22c55
 
9a70e05
 
e543a7f
 
 
9a70e05
e543a7f
9a70e05
 
6a22c55
 
 
e543a7f
9a70e05
6a22c55
e543a7f
9a70e05
e543a7f
9a70e05
e543a7f
9a70e05
e543a7f
9a70e05
e543a7f
9a70e05
ffa79be
e543a7f
 
ffa79be
 
e543a7f
ffa79be
 
e543a7f
ffa79be
 
 
e543a7f
 
ffa79be
e543a7f
 
ffa79be
 
 
 
e543a7f
 
ffa79be
 
 
 
 
 
 
6a22c55
 
 
ffa79be
e543a7f
ffa79be
9a70e05
 
6a22c55
9a70e05
 
 
4572d5f
ffa79be
 
9a70e05
 
 
 
 
ffa79be
9a70e05
 
 
 
 
6a22c55
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import gradio as gr
from huggingface_hub import InferenceClient

client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")

# Inicializa a memória da conversa
conversation_history = []

def respond(
    message,
    history: list[tuple[str, str]],
    system_message,
    max_tokens,
    temperature,
    top_p,
):
    # Armazena a mensagem do usuário na memória
    conversation_history.append((message, None))

    messages = [{"role": "system", "content": system_message}]

    # Adiciona histórico de conversas anteriores
    for val in history:
        if val[0]:
            messages.append({"role": "user", "content": val[0]})
        if val[1]:
            messages.append({"role": "assistant", "content": val[1]})

    messages.append({"role": "user", "content": message})

    response = ""

    try:
        for message in client.chat_completion(
            messages,
            max_tokens=max_tokens,
            stream=True,
            temperature=temperature,
            top_p=top_p,
        ):
            if not message or not isinstance(message, dict):
                continue
            
            try:
                content = message.choices[0].delta.content
                finish_reason = message.choices[0].finish_reason

                if content.strip() == "":
                    if finish_reason == "stop":
                        break
                    else:
                        continue

                response += content
                yield response

            except (AttributeError, IndexError, KeyError) as e:
                continue

    except Exception as e:
        yield "Ocorreu um erro ao gerar a resposta."

    # Armazena a resposta gerada na memória
    conversation_history[-1] = (message, response)  # Atualiza a última entrada com a resposta

    # Verificação final se a resposta está vazia
    if response.strip() == "":
        yield "Nenhuma resposta gerada. Por favor, tente novamente ou ajuste as configurações."


# Interface do Gradio
demo = gr.ChatInterface(
    respond,
    additional_inputs=[
        gr.Textbox(value="Você é uma IA feita por Daniel Netto Heckert. Seu nome é Matrix e foi feita dia 29 de setembro de 2024.", label="Mensagem do sistema"),
        gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Máximo de novos tokens"),
        gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperatura"),
        gr.Slider(
            minimum=0.1,
            maximum=1.0,
            value=0.95,
            step=0.05,
            label="Top-p (amostragem de núcleo)",
        ),
    ],
)

if __name__ == "__main__":
    demo.launch()