103 lines
4.0 KiB
Python
103 lines
4.0 KiB
Python
from dotenv import load_dotenv
|
|
from langgraph_tools.nodes import ChatBotState
|
|
from langgraph_tools.graph import create_chat_graph
|
|
from langchain_core.messages import HumanMessage
|
|
import streamlit as st
|
|
import re
|
|
|
|
def validate_phone(phone: str) -> bool:
|
|
"""Valida que el número de teléfono tenga el formato correcto"""
|
|
phone_pattern = re.compile(r"^\d{10}$")
|
|
return bool(phone_pattern.match(phone))
|
|
|
|
def initialize_session_state():
|
|
"""Inicializa el estado de la sesión si no existe"""
|
|
if "messages" not in st.session_state:
|
|
st.session_state.messages = []
|
|
if "phone" not in st.session_state:
|
|
st.session_state.phone = None
|
|
if "current_state" not in st.session_state:
|
|
st.session_state.current_state = None
|
|
if "graph" not in st.session_state:
|
|
load_dotenv()
|
|
st.session_state.graph = create_chat_graph()
|
|
if "waiting_for_response" not in st.session_state:
|
|
st.session_state.waiting_for_response = False
|
|
|
|
def main():
|
|
st.markdown("<h1 style='text-align: center;'>DonConfiao - Asistente Virtual</h1>",
|
|
unsafe_allow_html=True)
|
|
|
|
# Inicializar estado de sesión
|
|
initialize_session_state()
|
|
|
|
# Solicitar número de teléfono en el sidebar
|
|
phone = st.sidebar.text_input(
|
|
"Ingresa tu número de teléfono (10 dígitos):",
|
|
value=st.session_state.phone if st.session_state.phone else "",
|
|
key="phone_input"
|
|
)
|
|
|
|
# Validar teléfono
|
|
if phone:
|
|
if validate_phone(phone):
|
|
st.session_state.phone = phone
|
|
if st.session_state.current_state is None:
|
|
st.session_state.current_state = ChatBotState(
|
|
messages=[],
|
|
query="",
|
|
category="",
|
|
response="",
|
|
phone=phone
|
|
)
|
|
else:
|
|
st.sidebar.error("Número inválido. Debe contener exactamente 10 dígitos.")
|
|
return
|
|
|
|
# Si no hay teléfono válido, no mostrar el chat
|
|
if not st.session_state.phone:
|
|
st.info("Por favor, ingresa un número de teléfono válido para comenzar.")
|
|
return
|
|
|
|
# Mostrar historial de mensajes
|
|
for message in st.session_state.messages:
|
|
with st.chat_message(message["role"]):
|
|
st.markdown(message["content"])
|
|
|
|
# Input del usuario
|
|
user_input = st.chat_input("¿En qué puedo ayudarte hoy?")
|
|
|
|
if user_input and st.session_state.current_state:
|
|
# Agregar mensaje del usuario al historial inmediatamente
|
|
st.session_state.messages.append({"role": "user", "content": user_input})
|
|
st.session_state.waiting_for_response = True
|
|
|
|
# Mostrar el mensaje del usuario inmediatamente
|
|
with st.chat_message("user"):
|
|
st.markdown(user_input)
|
|
|
|
# Mostrar indicador de carga mientras se procesa la respuesta
|
|
with st.chat_message("assistant"):
|
|
with st.spinner("Generando respuesta..."):
|
|
# Actualizar estado y obtener respuesta
|
|
st.session_state.current_state["query"] = user_input
|
|
try:
|
|
result = st.session_state.graph.invoke(st.session_state.current_state)
|
|
|
|
# Actualizar estado
|
|
st.session_state.current_state = result
|
|
if "phone" not in st.session_state.current_state:
|
|
st.session_state.current_state["phone"] = st.session_state.phone
|
|
|
|
# Agregar respuesta al historial
|
|
response_text = f"**Categoría:** {result['category']}\n\n{result['response']}"
|
|
st.session_state.messages.append({"role": "assistant", "content": response_text})
|
|
st.markdown(response_text)
|
|
|
|
except Exception as e:
|
|
st.error(f"Error: {str(e)}")
|
|
|
|
st.session_state.waiting_for_response = False
|
|
|
|
if __name__ == "__main__":
|
|
main() |