Christhofer commited on
Commit
d818c3a
1 Parent(s): 6b79bfe

new interface of chat app

Browse files
Files changed (1) hide show
  1. app.py +122 -86
app.py CHANGED
@@ -1,99 +1,135 @@
 
1
  import gradio as gr
2
  from google import genai
3
- import os
4
 
5
- # Configure Gemini API
6
- # You will need to set the GEMINI_API_KEY environment variable in Hugging Face Secrets
7
- client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
8
 
9
- # Define available behaviors
10
- BEHAVIORS = {
11
- "Helpful Assistant": "You are a helpful, polite, and concise AI assistant.",
12
- "Creative Writer": "You are a creative writer. Your responses should be imaginative, descriptive, and engaging.",
13
- "Code Expert": "You are an expert software engineer. Provide clear, optimized, and well-commented code examples.",
14
- "Philosopher": "You are a deep-thinking philosopher. Explore the nuances and underlying meanings of every question."
15
- }
16
 
17
- def chat_with_gemini(message, history, system_behavior, model_name, temperature):
18
- # Convert Gradio history to Gemini format
19
- contents = []
20
- for msg in history:
21
- # Gradio uses "user" and "assistant", Gemini uses "user" and "model"
22
- role = "user" if msg["role"] == "user" else "model"
23
-
24
- # Robustly extract text content
25
- content = msg["content"]
26
- if isinstance(content, list):
27
- # Extract text from complex Gradio message parts
28
- text_parts = []
29
- for part in content:
30
- if isinstance(part, dict) and "text" in part:
31
- if isinstance(part["text"], str):
32
- text_parts.append(part["text"])
33
- elif isinstance(part["text"], list):
34
- for subpart in part["text"]:
35
- if isinstance(subpart, dict) and "text" in subpart:
36
- text_parts.append(subpart["text"])
37
- text_content = "".join(text_parts)
38
- else:
39
- text_content = str(content)
40
-
41
- contents.append({"role": role, "parts": [{"text": text_content}]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- # Add current message
44
- contents.append({"role": "user", "parts": [{"text": message}]})
 
 
 
 
45
 
46
- # Get the system instruction from the selected behavior
47
- system_instruction = BEHAVIORS.get(system_behavior, BEHAVIORS["Helpful Assistant"])
 
 
 
 
48
 
49
- # Streaming response using the new SDK
50
- response = client.models.generate_content_stream(
51
- model=model_name,
52
- contents=contents,
53
- config={
54
- "system_instruction": system_instruction,
55
- "temperature": temperature,
56
- }
57
- )
58
 
59
- full_response = ""
60
- for chunk in response:
61
- full_response += chunk.text
62
- yield full_response
63
-
64
- # Create Gradio interface
65
- with gr.Blocks(theme="soft") as demo:
66
- gr.HTML("<h1 style='text-align: center;'>Gemini Chat Explorer</h1>")
67
- gr.HTML("<p style='text-align: center;'>A simple chat interface powered by Google Gemini. Changing the behavior will clear the history.</p>")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- # Define inputs that will be passed to the chat function
70
- behavior_input = gr.Dropdown(
71
- choices=list(BEHAVIORS.keys()),
72
- value="Helpful Assistant",
73
- label="System Behavior"
74
- )
75
- model_input = gr.Dropdown(
76
- choices=["gemini-2.0-flash", "gemini-2.0-pro-exp-02-05"],
77
- value="gemini-2.0-flash",
78
- label="Model"
79
- )
80
- temp_input = gr.Slider(
81
- minimum=0.0,
82
- maximum=1.0,
83
- value=0.7,
84
- step=0.1,
85
- label="Temperature (Creativity)"
86
- )
87
-
88
- # Initialize ChatInterface
89
- chat_interface = gr.ChatInterface(
90
- fn=chat_with_gemini,
91
- additional_inputs=[behavior_input, model_input, temp_input],
92
- )
93
-
94
- # Clear history when behavior changes
95
- # We return None to the chatbot component to clear it
96
- behavior_input.change(lambda: None, outputs=chat_interface.chatbot)
 
 
 
 
 
 
97
 
98
  if __name__ == "__main__":
99
  demo.launch()
 
1
+ import os
2
  import gradio as gr
3
  from google import genai
4
+ from google.genai import types
5
 
6
+ api_key = os.environ.get("GEMINI_API_KEY")
 
 
7
 
8
+ client = None
9
+ if api_key:
10
+ client = genai.Client(api_key=api_key)
 
 
 
 
11
 
12
+ SYSTEM_PROMPT = """
13
+ Eres un Asistente de Planificaci贸n Maestro experto. Tu objetivo es ayudar al usuario a planificar proyectos en tres 谩reas espec铆ficas:
14
+ 1. Planificaci贸n de Producci贸n (Demanda, Inventario, Capacidades).
15
+ 2. Planificaci贸n de Proyectos de Ingenier铆a de Datos.
16
+ 3. Planificaci贸n de Proyectos de IA Generativa.
17
+
18
+ Al inicio de la conversaci贸n, DEBES presentarte brevemente y ofrecer estas 3 capacidades de planificaci贸n.
19
+
20
+ REGLAS GENERALES:
21
+ - Habla siempre en Espa帽ol.
22
+ - S茅 profesional, anal铆tico y servicial.
23
+ - Si el usuario elige una opci贸n, gu铆alo paso a paso solicitando la informaci贸n necesaria.
24
+ - Solicita informaci贸n paso a paso en lugar de pedir todo de una vez.
25
+
26
+ MODULO 1: PLANIFICACI脫N DE PRODUCCI脫N
27
+ Si el usuario elige esta opci贸n, debes solicitar:
28
+ 1. Producto(s) a planificar.
29
+ 2. Demanda esperada por periodo (d铆as, semanas o meses).
30
+ 3. Inventario disponible actual (terminado y materias primas).
31
+ 4. Capacidad de producci贸n (m谩ximo por periodo).
32
+ 5. Tiempo de producci贸n por unidad o lote.
33
+ 6. Prioridades o restricciones opcionales.
34
+
35
+ Una vez tengas los datos, aplica uno de estos m茅todos (explica cu谩l usas):
36
+ - Cl谩sico (MRP): C谩lculo de necesidades netas y fechas.
37
+ - Temporal: Basado en cronogramas y carga de capacidad.
38
+ - Probabil铆stico: Considera incertidumbre y propone buffers.
39
+
40
+ RESULTADOS ESPERADOS:
41
+ - Plan de producci贸n por periodo (Ej: Semana 1: X unidades, Semana 2: Y unidades).
42
+ - Necesidades de materiales (Cantidades de materias primas).
43
+ - Alertas de capacidad o stock insuficiente.
44
+ - Resumen final (producci贸n total, inventario final estimado, posibles retrasos).
45
+
46
+ MODULO 2: INGENIER脥A DE DATOS
47
+ Ayuda a planificar pipelines ETL, lagos de datos, modelado de almacenes, etc. Solicita objetivos, fuentes de datos, volumen y frecuencia.
48
+
49
+ MODULO 3: IA GENERATIVA
50
+ Ayuda a planificar sistemas RAG, fine-tuning, agentes, etc. Solicita casos de uso, modelos base, datos de entrenamiento/contexto y m茅tricas de evaluaci贸n.
51
+
52
+ IMPORTANTE: No inventes datos si el usuario no los proporciona. P铆delos amablemente.
53
+ """
54
+
55
+ def extract_text(content):
56
+ if isinstance(content, str):
57
+ return content
58
 
59
+ if isinstance(content, list):
60
+ texts = []
61
+ for item in content:
62
+ if isinstance(item, dict) and item.get("type") == "text":
63
+ texts.append(item.get("text", ""))
64
+ return " ".join(texts)
65
 
66
+ return str(content)
67
+
68
+ def predict(message, history):
69
+ if not client:
70
+ yield "Error: No se ha configurado la clave de API de Gemini (GEMINI_API_KEY)."
71
+ return
72
 
73
+ contents = []
 
 
 
 
 
 
 
 
74
 
75
+ for msg in history:
76
+ if isinstance(msg, dict):
77
+ role = msg.get("role")
78
+ raw_text = msg.get("content", "")
79
+ text = extract_text(raw_text)
80
+
81
+ if role == "user":
82
+ contents.append(
83
+ types.Content(
84
+ role="user",
85
+ parts=[types.Part.from_text(text=text)]
86
+ )
87
+ )
88
+ elif role == "assistant":
89
+ contents.append(
90
+ types.Content(
91
+ role="model",
92
+ parts=[types.Part.from_text(text=text)]
93
+ )
94
+ )
95
+
96
+ # A帽adir el mensaje actual
97
+ contents.append(types.Content(role="user", parts=[types.Part.from_text(text=message)]))
98
 
99
+
100
+ try:
101
+ generate_content_config = types.GenerateContentConfig(
102
+ system_instruction=SYSTEM_PROMPT,
103
+ temperature=0.7,
104
+ )
105
+
106
+ response = client.models.generate_content_stream(
107
+ model="gemini-2.0-flash",
108
+ contents=contents,
109
+ config=generate_content_config,
110
+ )
111
+
112
+ partial_message = ""
113
+ for chunk in response:
114
+ if chunk.text:
115
+ partial_message += chunk.text
116
+ yield partial_message
117
+ except Exception as e:
118
+ yield f"Ocurri贸 un error: {str(e)}"
119
+
120
+ demo = gr.ChatInterface(
121
+ predict,
122
+ title="Planificador Maestro AI",
123
+ description="Asistente inteligente para planificaci贸n de producci贸n, ingenier铆a de datos e IA generativa.",
124
+ examples=[
125
+ "Quiero planificar la producci贸n de galletas",
126
+ "Ay煤dame a planificar un proyecto de ingenier铆a de datos",
127
+ "Necesito un plan para implementar un sistema RAG"
128
+ ],
129
+ flagging_mode="manual",
130
+ flagging_options=["Like", "Spam", "Inappropriate", "Other"],
131
+ save_history=True,
132
+ )
133
 
134
  if __name__ == "__main__":
135
  demo.launch()