Santitonelli commited on
Commit
8432bf0
1 Parent(s): 8408bd8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -62
app.py CHANGED
@@ -1,63 +1,117 @@
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
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import plotly.express as px
3
+ from openai import OpenAI
4
+ import time
5
+
6
+ # Configura el cliente de OpenAI con la API key directamente
7
+ client = OpenAI(api_key="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")
8
+ print("Cliente OpenAI inicializado")
9
+
10
+ # ID de tu asistente
11
+ assistant_id = "asst_0hq3iRy6LX0YLZP0QVzg17fT"
12
+
13
+ def random_plot():
14
+ df = px.data.iris()
15
+ fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
16
+ size='petal_length', hover_data=['petal_width'])
17
+ return fig
18
+
19
+ def print_like_dislike(x: gr.LikeData):
20
+ print(x.index, x.value, x.liked)
21
+
22
+ def add_message(history, message):
23
+ if message["text"] is not None and message["text"].strip() != "":
24
+ history.append((message["text"], None))
25
+ return history, gr.MultimodalTextbox(value=None, interactive=True)
26
+
27
+ def bot(history):
28
+ print("Iniciando función bot")
29
+ try:
30
+ last_message = history[-1][0] if history else "Hola"
31
+ print(f"Último mensaje: {last_message}")
32
+
33
+ thread = client.beta.threads.create()
34
+ print(f"Hilo creado: {thread.id}")
35
+
36
+ client.beta.threads.messages.create(
37
+ thread_id=thread.id,
38
+ role="user",
39
+ content=last_message
40
+ )
41
+ print("Mensaje del usuario añadido al hilo")
42
+
43
+ run = client.beta.threads.runs.create(
44
+ thread_id=thread.id,
45
+ assistant_id=assistant_id
46
+ )
47
+ print(f"Ejecución iniciada: {run.id}")
48
+
49
+ timeout = 120
50
+ start_time = time.time()
51
+ while run.status not in ["completed", "failed", "cancelled"]:
52
+ if time.time() - start_time > timeout:
53
+ print("Tiempo de espera agotado")
54
+ client.beta.threads.runs.cancel(thread_id=thread.id, run_id=run.id)
55
+ return history + [("Lo siento, la respuesta está tardando demasiado. Por favor, intenta reformular tu pregunta.", None)]
56
+
57
+ time.sleep(2)
58
+ run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
59
+ print(f"Estado de la ejecución: {run.status}")
60
+
61
+ if run.status == "requires_action":
62
+ print("La ejecución requiere una acción")
63
+ required_actions = run.required_action.submit_tool_outputs.tool_calls
64
+ for action in required_actions:
65
+ print(f"Acción requerida: {action.type}")
66
+ print(f"Función: {action.function.name}")
67
+ print(f"Argumentos: {action.function.arguments}")
68
+
69
+ # Aquí deberías manejar las acciones requeridas
70
+ # Por ahora, vamos a cancelar la ejecución
71
+ client.beta.threads.runs.cancel(thread_id=thread.id, run_id=run.id)
72
+ return history + [("Lo siento, el asistente requiere acciones adicionales que no puedo manejar en este momento. Por favor, intenta reformular tu pregunta.", None)]
73
+
74
+ if run.status != "completed":
75
+ print(f"La ejecución terminó con estado: {run.status}")
76
+ return history + [("Lo siento, hubo un problema al procesar tu mensaje. Por favor, intenta de nuevo o reformula tu pregunta.", None)]
77
+
78
+ messages = client.beta.threads.messages.list(thread_id=thread.id)
79
+ print("Mensajes recuperados del hilo")
80
+
81
+ bot_response = ""
82
+ for message in messages.data:
83
+ if message.role == "assistant":
84
+ for content in message.content:
85
+ if content.type == 'text':
86
+ bot_response += content.text.value + "\n"
87
+
88
+ if not bot_response:
89
+ print("No se encontró respuesta del asistente")
90
+ bot_response = "Lo siento, no pude generar una respuesta. Por favor, intenta reformular tu pregunta."
91
+
92
+ print(f"Respuesta del bot: {bot_response}")
93
+ history[-1] = (history[-1][0], bot_response.strip())
94
+ return history
95
+ except Exception as e:
96
+ print(f"Error en la función bot: {e}")
97
+ return history + [("Lo siento, ocurrió un error inesperado. Por favor, intenta de nuevo.", None)]
98
+
99
+ fig = random_plot()
100
+
101
+ with gr.Blocks(fill_height=True) as demo:
102
+ chatbot = gr.Chatbot(
103
+ elem_id="chatbot",
104
+ bubble_full_width=False,
105
+ scale=1,
106
+ )
107
+ chat_input = gr.MultimodalTextbox(interactive=True,
108
+ file_count="multiple",
109
+ placeholder="Enter message or upload file...", show_label=False)
110
+ chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input])
111
+ bot_msg = chat_msg.then(bot, chatbot, chatbot, api_name="bot_response")
112
+ bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])
113
+ chatbot.like(print_like_dislike, None, None)
114
+
115
+ print("Iniciando la aplicación Gradio")
116
+ demo.queue()
117
+ demo.launch(share=True)