Gntuxer commited on
Commit
53c6ec8
·
verified ·
1 Parent(s): 216eb44

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -182
app.py CHANGED
@@ -1,25 +1,7 @@
1
  import gradio as gr
2
- import json
3
  from huggingface_hub import InferenceClient
4
 
5
- # ============================================
6
- # CONFIGURACIÓN POR DEFECTO (se guarda en memoria)
7
- # ============================================
8
- CONFIG = {
9
- "nombre": "Mi Asistente",
10
- "descripcion": "Asistente personalizado",
11
- "system_prompt": "Eres un asistente virtual útil y amigable. Responde de forma clara y concisa en español. Sé amable y profesional.",
12
- "empresa": "",
13
- "servicios": "",
14
- "contacto": "",
15
- "web_search": False,
16
- "image_gen": False,
17
- "temperature": 0.7
18
- }
19
 
20
- # ============================================
21
- # FUNCIONES DE RESPUESTA
22
- # ============================================
23
  def respond(
24
  message,
25
  history: list[dict[str, str]],
@@ -29,20 +11,19 @@ def respond(
29
  top_p,
30
  hf_token: gr.OAuthToken,
31
  ):
32
- """Genera respuestas del asistente"""
33
- model_name = "mistralai/Mistral-7B-Instruct-v0.2"
34
-
35
- if hf_token is None:
36
- yield "Por favor, inicia sesión con tu cuenta de Hugging Face."
37
- return
38
-
39
- client = InferenceClient(token=hf_token.token, model=model_name)
40
 
41
  messages = [{"role": "system", "content": system_message}]
 
42
  messages.extend(history)
 
43
  messages.append({"role": "user", "content": message})
44
 
45
  response = ""
 
46
  for message in client.chat_completion(
47
  messages,
48
  max_tokens=max_tokens,
@@ -54,169 +35,35 @@ def respond(
54
  token = ""
55
  if len(choices) and choices[0].delta.content:
56
  token = choices[0].delta.content
 
57
  response += token
58
  yield response
59
 
60
- # ============================================
61
- # FUNCIONES DE CONFIGURACIÓN
62
- # ============================================
63
- def cargar_config():
64
- """Carga la configuración desde el archivo (o usa la por defecto)"""
65
- try:
66
- with open("config.json", "r", encoding="utf-8") as f:
67
- return json.load(f)
68
- except:
69
- return CONFIG
70
-
71
- def guardar_config(nombre, descripcion, system_prompt, empresa, servicios, contacto, web_search, image_gen, temperatura):
72
- """Guarda la configuración en archivo"""
73
- config = {
74
- "nombre": nombre,
75
- "descripcion": descripcion,
76
- "system_prompt": system_prompt,
77
- "empresa": empresa,
78
- "servicios": servicios,
79
- "contacto": contacto,
80
- "web_search": web_search,
81
- "image_gen": image_gen,
82
- "temperature": temperatura
83
- }
84
- try:
85
- with open("config.json", "w", encoding="utf-8") as f:
86
- json.dump(config, f, indent=4, ensure_ascii=False)
87
- return "✅ ¡Configuración guardada! Ve a la pestaña Chat para probar tu asistente."
88
- except Exception as e:
89
- return f"❌ Error al guardar: {str(e)}"
90
-
91
- def obtener_system_prompt():
92
- """Obtiene el system prompt guardado"""
93
- config = cargar_config()
94
- return config["system_prompt"]
95
-
96
- # ============================================
97
- # PLANTILLA DE SYSTEM PROMPT
98
- # ============================================
99
- PLANTILLA = """Eres {nombre}, el asistente virtual de {empresa}.
100
 
101
- QUIÉN SOY:
102
- {empresa}
103
-
104
- MIS SERVICIOS:
105
- {servicios}
106
-
107
- CÓMO DEBO ACTUAR:
108
- - Sé amable y profesional siempre
109
- - Responde en español
110
- - No inventes información
111
- - Sugiere contactar por: {contacto}
112
-
113
- REGLAS:
114
- 1. Responde de forma concisa pero completa
115
- 2. Usa tono {tono}
116
- 3. Incluye emojis偶尔 para ser más cercano
117
- 4. Al final, ofrece ayuda adicional
118
-
119
- CONTACTO:
120
- {contacto}
121
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- # ============================================
124
- # INTERFAZ GRADIO
125
- # ============================================
126
- with gr.Blocks(title="Asistente Virtual", theme=gr.themes.Soft()) as demo:
127
-
128
- gr.Markdown("# 🤖 Asistente Virtual Personalizado")
129
- gr.Markdown("### Personaliza tu asistente sin tocar código")
130
- gr.Markdown("---")
131
-
132
- with gr.Tabs():
133
-
134
- # ===== PESTAÑA 1: CHAT =====
135
- with gr.TabItem("💬 Chat"):
136
- gr.Markdown("#### Habla con tu asistente")
137
- chatbot = gr.ChatInterface(
138
- respond,
139
- additional_inputs=[
140
- gr.Textbox(
141
- value=obtener_system_prompt,
142
- label="📝 System Prompt",
143
- info="Este texto define cómo actúa tu asistente",
144
- lines=8
145
- ),
146
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="📏 Max tokens"),
147
- gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="🎯 Temperature (creatividad)"),
148
- gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="📊 Top-p"),
149
- ],
150
- )
151
-
152
- # ===== PESTAÑA 2: CONFIGURACIÓN =====
153
- with gr.TabItem("⚙️ Configurar"):
154
- gr.Markdown("## 🎨 Personaliza tu Asistente")
155
- gr.Markdown("Rellena los campos y guarda. Los cambios se aplicarán al asistente.")
156
- gr.Markdown("---")
157
-
158
- with gr.Row():
159
- with gr.Column(scale=1):
160
- gr.Markdown("### 🏢 Identidad del Asistente")
161
- nombre = gr.Textbox(label="Nombre del asistente", placeholder="Ej: Asistente del Instituto XYZ")
162
- descripcion = gr.Textbox(label="Descripción breve", placeholder="Ej: Assistant para ayudar a estudiantes")
163
-
164
- with gr.Column(scale=1):
165
- gr.Markdown("### 🎭 Personalidad")
166
- tono_select = gr.Dropdown(
167
- choices=["formal", "formal_amigable", "informal", "técnico"],
168
- value="formal_amigable",
169
- label="Tono de comunicación"
170
- )
171
- usar_plantilla_btn = gr.Button("📋 Usar plantilla", variant="secondary")
172
-
173
- gr.Markdown("---")
174
-
175
- with gr.Accordion("🧠 System Prompt (Directrices)", open=True):
176
- system_prompt = gr.Textbox(
177
- label="Escribe las instrucciones que definirán cómo actúa tu asistente:",
178
- lines=10,
179
- placeholder="Ej: Eres un asistente virtual delInstituto XYZ que ayuda a estudiantes..."
180
- )
181
- gr.Markdown("*💡 El System Prompt es el cerebro de tu asistente. Aquí defines su personalidad, reglas y forma de responder.*")
182
-
183
- gr.Markdown("---")
184
-
185
- with gr.Row():
186
- with gr.Column():
187
- gr.Markdown("### 📚 Base de Conocimiento")
188
- empresa = gr.Textbox(label="Quién es la empresa/entidad", placeholder="Ej: Instituto XYZ, un centro educativo de secundaria...")
189
- servicios = gr.Textbox(label="Servicios que ofrece", placeholder="Ej: Clases de ESO, Bachillerato, actividades extraescolares...", lines=4)
190
- contacto = gr.Textbox(label="Información de contacto", placeholder="Ej: Tel: 912 345 678\nEmail: info@email.es\nWeb: www.instituto.es", lines=3)
191
-
192
- with gr.Column():
193
- gr.Markdown("### 🔧 Herramientas")
194
- web_search = gr.Checkbox(label="🔍 Búsqueda en Internet", info="El asistente puede buscar información online")
195
- image_gen = gr.Checkbox(label="🎨 Generación de imágenes", info="El asistente puede crear imágenes")
196
- gr.Markdown("### ⚡ Parámetros")
197
- temperatura = gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature")
198
-
199
- gr.Markdown("---")
200
-
201
- with gr.Row():
202
- guardar_btn = gr.Button("💾 Guardar Configuración", variant="primary", size="lg")
203
- estado = gr.Textbox(label="📋 Estado", interactive=False, lines=2)
204
-
205
- # Cargar valores iniciales
206
- demo.load(fn=cargar_config, outputs=[nombre, descripcion, system_prompt, empresa, servicios, contacto, web_search, image_gen, temperatura])
207
-
208
- # Botón de guardar
209
- guardar_btn.click(
210
- fn=guardar_config,
211
- inputs=[nombre, descripcion, system_prompt, empresa, servicios, contacto, web_search, image_gen, temperatura],
212
- outputs=estado
213
- )
214
-
215
- gr.Markdown("---")
216
- gr.Markdown("*🤖 Creado con Hugging Face + Gradio | Espacio educativo*")
217
-
218
  with gr.Sidebar():
219
  gr.LoginButton()
 
 
220
 
221
  if __name__ == "__main__":
222
- demo.launch()
 
1
  import gradio as gr
 
2
  from huggingface_hub import InferenceClient
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
 
 
 
5
  def respond(
6
  message,
7
  history: list[dict[str, str]],
 
11
  top_p,
12
  hf_token: gr.OAuthToken,
13
  ):
14
+ """
15
+ 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
16
+ """
17
+ client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
 
 
 
 
18
 
19
  messages = [{"role": "system", "content": system_message}]
20
+
21
  messages.extend(history)
22
+
23
  messages.append({"role": "user", "content": message})
24
 
25
  response = ""
26
+
27
  for message in client.chat_completion(
28
  messages,
29
  max_tokens=max_tokens,
 
35
  token = ""
36
  if len(choices) and choices[0].delta.content:
37
  token = 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
+ chatbot = 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
+ with gr.Blocks() as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  with gr.Sidebar():
64
  gr.LoginButton()
65
+ chatbot.render()
66
+
67
 
68
  if __name__ == "__main__":
69
+ demo.launch()