giseldo commited on
Commit
ea66d0d
·
verified ·
1 Parent(s): ba3a0aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -57
app.py CHANGED
@@ -1,64 +1,110 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
  top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ from openai import OpenAI
3
 
4
+ client = OpenAI()
 
 
 
5
 
6
+ def process_message(message, history, temperature=1.0, max_tokens=2048, top_p=1.0, model="gpt-4.1", system_prompt=""):
7
+
8
+ # Verificar se já existe uma mensagem do sistema no início do histórico
9
+ system_message_exists = any(msg.get("role") == "system" for msg in history)
10
+
11
+ # Se não existir e o system_prompt não estiver vazio, adicionar no início do histórico
12
+ if not system_message_exists and system_prompt.strip():
13
+ history.insert(0, {"role": "system", "content": system_prompt})
14
+
15
+ history.append({"role": "user", "content": message})
16
+
17
+ # Filtrar o histórico e remover metadata e options
18
+ filtered_history = []
19
+ for msg in history:
20
+ if msg.get("role") in ["user", "system", "assistant"]:
21
+ # Criar novo dicionário apenas com role e content
22
+ filtered_msg = {
23
+ "role": msg["role"],
24
+ "content": msg["content"]
25
+ }
26
+ filtered_history.append(filtered_msg)
27
+
28
+ print(history)
29
 
30
+ response = client.responses.create(
31
+ model=model,
32
+ input=filtered_history, # Usando o histórico filtrado
33
+ text={
34
+ "format": {
35
+ "type": "text"
36
+ }
37
+ },
38
+ reasoning={},
39
+
40
+ tools=[
41
+ {
42
+ "type": "file_search",
43
+ "vector_store_ids": [
44
+ "vs_680171e31fcc8191937768624f4f4a18"
45
+ ]
46
+ }
47
+ ],
48
+
49
+ temperature=temperature, # Use as variáveis de parâmetros
50
+ max_output_tokens=max_tokens, # Corrigido de max_output_tokens para max_tokens
 
 
 
 
51
  top_p=top_p,
52
+ store=True
53
+ )
54
+
55
+ # Atualize para obter o texto da resposta do objeto de resposta corretamente
56
+ history.append({"role": "assistant", "content": response.output_text})
57
+ return "", history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
+ with gr.Blocks() as interface:
60
+ with gr.Row():
61
+ with gr.Column():
62
+ history = gr.Chatbot(type='messages')
63
+ msg = gr.Textbox(label="Mensagem")
64
+ clear = gr.Button("Limpar")
65
+
66
+ with gr.Column():
67
+ system_prompt = gr.Textbox(
68
+ label="Prompt do Sistema",
69
+ value="Você é um assistente inteligente treinado para responder exclusivamente com base nas informações fornecidas nos documentos anexados (armazenados na base vetorial).\nNunca forneça respostas baseadas em conhecimento próprio, conhecimento geral, ou treinamento anterior.\nSe a resposta à pergunta não estiver clara ou presente nos documentos fornecidos, responda educadamente que você não tem essa informação.\n",
70
+ lines=3,
71
+ info="Define o comportamento base do assistente"
72
+ )
73
+ model = gr.Dropdown(
74
+ choices=["gpt-4.1", "GPT-4.1-mini", "GPT-4.1-nano"],
75
+ value="gpt-4.1",
76
+ label="Modelo",
77
+ info="Selecione o modelo de linguagem"
78
+ )
79
+ temperature = gr.Slider(
80
+ minimum=0.0,
81
+ maximum=2.0,
82
+ value=1.0,
83
+ step=0.1,
84
+ label="Temperatura",
85
+ info="Controla a aleatoriedade das respostas (0=focado, 2=criativo)"
86
+ )
87
+ max_tokens = gr.Slider(
88
+ minimum=256,
89
+ maximum=4096,
90
+ value=4096,
91
+ step=256,
92
+ label="Tokens máximos",
93
+ info="Limite máximo de tokens na resposta"
94
+ )
95
+ top_p = gr.Slider(
96
+ minimum=0.0,
97
+ maximum=1.0,
98
+ value=1.0,
99
+ step=0.1,
100
+ label="Top P",
101
+ info="Controla a diversidade das respostas"
102
+ )
103
+
104
+ msg.submit(process_message,
105
+ [msg, history, temperature, max_tokens, top_p, model, system_prompt],
106
+ [msg, history])
107
+ # clear.click(lambda: None, None, history, queue=False)
108
 
109
+ if __name__ == "__main__":
110
+ interface.launch()