-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
241 lines (198 loc) · 7.57 KB
/
Copy pathmain.py
File metadata and controls
241 lines (198 loc) · 7.57 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#!/usr/bin/env python3
# main.py - Interfaz web con Streamlit para el agente LangGraph
import streamlit as st
import os
from dotenv import load_dotenv
from agent_langgraph import run_agent
# Cargar variables de entorno
load_dotenv()
# ============================================
# CONFIGURACIÓN DE LA PÁGINA
# ============================================
st.set_page_config(
page_title="Agente SQL CitiBike - Kevin Inofuente Colque",
page_icon="🚴",
layout="wide",
initial_sidebar_state="expanded"
)
# ============================================
# ESTILOS PERSONALIZADOS
# ============================================
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
font-weight: bold;
color: #1f77b4;
text-align: center;
padding: 1rem 0;
}
.sub-header {
font-size: 1.2rem;
color: #666;
text-align: center;
margin-bottom: 2rem;
}
.stChatMessage {
background-color: #f0f2f6;
border-radius: 10px;
padding: 1rem;
margin: 0.5rem 0;
}
.success-box {
padding: 1rem;
background-color: #d4edda;
border-left: 5px solid #28a745;
border-radius: 5px;
margin: 1rem 0;
}
.info-box {
padding: 1rem;
background-color: #d1ecf1;
border-left: 5px solid #17a2b8;
border-radius: 5px;
margin: 1rem 0;
}
</style>
""", unsafe_allow_html=True)
# ============================================
# SIDEBAR - INFORMACIÓN Y EJEMPLOS
# ============================================
with st.sidebar:
# Mostrar logo si existe
if os.path.exists("images/datapath-logo.png"):
st.image("images/datapath-logo.png", width=200)
st.markdown("## 🚴 Agente SQL CitiBike")
st.markdown("---")
st.markdown("### 📊 Sobre este proyecto")
st.info("""
Este agente inteligente utiliza **LangGraph** y **OpenAI** para responder
preguntas en lenguaje natural sobre los datos de CitiBike NYC almacenados en BigQuery.
""")
st.markdown("### 💡 Ejemplos de preguntas:")
ejemplos = [
"¿Cuántos viajes en total hay?",
"¿Cuál es la ruta más popular?",
"¿Cuál es la duración promedio?",
"¿Cuántos usuarios son subscribers?",
"Dame las 5 estaciones más usadas",
"¿En qué año hay más viajes?"
]
for ejemplo in ejemplos:
if st.button(f"📝 {ejemplo}", key=ejemplo, use_container_width=True):
st.session_state.ejemplo_seleccionado = ejemplo
st.markdown("---")
st.markdown("### 🛠️ Tecnologías")
st.markdown("""
- **LangGraph 1.0** - Orquestación de agentes
- **OpenAI GPT-4o** - Modelo de lenguaje
- **BigQuery** - Base de datos
- **Streamlit** - Interface web
""")
st.markdown("---")
st.markdown("### ℹ️ Estado del sistema")
# Verificar configuración
openai_ok = bool(os.getenv("OPENAI_API_KEY"))
bigquery_ok = bool(os.getenv("GOOGLE_APPLICATION_CREDENTIALS"))
st.markdown(f"**OpenAI:** {'✅' if openai_ok else '❌'}")
st.markdown(f"**BigQuery:** {'✅' if bigquery_ok else '❌'}")
if not openai_ok or not bigquery_ok:
st.error("⚠️ Faltan configuraciones. Revisa el archivo .env")
# ============================================
# HEADER PRINCIPAL
# ============================================
st.markdown('<p class="main-header">🚴 Agente Analista de CitiBike NYC</p>', unsafe_allow_html=True)
st.markdown('<p class="sub-header">Pregúntame cualquier cosa sobre los datos de viajes de CitiBike</p>', unsafe_allow_html=True)
# ============================================
# INICIALIZAR SESSION STATE
# ============================================
if "messages" not in st.session_state:
st.session_state.messages = []
# Mensaje de bienvenida
st.session_state.messages.append({
"role": "assistant",
"content": """¡Hola! 👋 Soy tu asistente para analizar datos de CitiBike NYC.
Puedo responder preguntas sobre:
- 📊 Estadísticas de viajes
- 🗺️ Rutas y estaciones populares
- ⏱️ Duraciones y patrones temporales
- 👥 Tipos de usuarios
**¿Qué te gustaría saber?**"""
})
if "ejemplo_seleccionado" not in st.session_state:
st.session_state.ejemplo_seleccionado = None
# ============================================
# MOSTRAR HISTORIAL DE CHAT
# ============================================
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# ============================================
# INPUT DEL USUARIO
# ============================================
# Si se seleccionó un ejemplo desde el sidebar
if st.session_state.ejemplo_seleccionado:
prompt = st.session_state.ejemplo_seleccionado
st.session_state.ejemplo_seleccionado = None
else:
# Input normal del chat
prompt = st.chat_input("Escribe tu pregunta aquí...")
# ============================================
# PROCESAR PREGUNTA
# ============================================
if prompt:
# Agregar mensaje del usuario al historial
st.session_state.messages.append({"role": "user", "content": prompt})
# Mostrar mensaje del usuario
with st.chat_message("user"):
st.markdown(prompt)
# Mostrar indicador de que está pensando
with st.chat_message("assistant"):
with st.spinner("🤔 Analizando tu pregunta y consultando BigQuery..."):
try:
# Llamar al agente
respuesta = run_agent(prompt)
# Mostrar respuesta
st.markdown(respuesta)
# Agregar al historial
st.session_state.messages.append({
"role": "assistant",
"content": respuesta
})
except Exception as e:
error_msg = f"❌ **Error:** {str(e)}\n\nPor favor, intenta reformular tu pregunta o contacta al administrador."
st.error(error_msg)
# Agregar error al historial
st.session_state.messages.append({
"role": "assistant",
"content": error_msg
})
# ============================================
# BOTÓN PARA LIMPIAR CONVERSACIÓN
# ============================================
col1, col2, col3 = st.columns([1, 1, 1])
with col2:
if st.button("🗑️ Limpiar conversación", use_container_width=True):
st.session_state.messages = []
st.session_state.messages.append({
"role": "assistant",
"content": """¡Conversación reiniciada! 🔄
¿Qué te gustaría saber sobre los datos de CitiBike?"""
})
st.rerun()
# ============================================
# FOOTER
# ============================================
st.markdown("---")
st.markdown("""
<div style='text-align: center; color: #666; font-size: 0.9rem;'>
<p>Desarrollado con ❤️ usando LangGraph 1.0 + OpenAI GPT-4o + BigQuery</p>
<p>👨💻 Desarrollado por <strong>Ing. Kevin Inofuente Colque</strong> — AI Engineer</p>
<p>
<a href="https://github.com/KevinInoCol" target="_blank" style="text-decoration: none; color: #333;">🐙 GitHub</a>
|
<a href="https://www.linkedin.com/in/kevin-inofuente-colque" target="_blank" style="text-decoration: none; color: #0077b5;">💼 LinkedIn</a>
</p>
<p>📚 Proyecto educativo para enseñanza de agentes con LangGraph</p>
</div>
""", unsafe_allow_html=True)