72 lines
1.9 KiB
Python
72 lines
1.9 KiB
Python
from fastapi import FastAPI, HTTPException
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from pydantic import BaseModel
|
|
from app.langgraph_tools.graph import create_chat_graph
|
|
import logging
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
app = FastAPI(title="ChatBot API")
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
graph = create_chat_graph()
|
|
|
|
|
|
class ChatRequest(BaseModel):
|
|
user_id: str
|
|
query: str
|
|
|
|
|
|
chat_states = {}
|
|
|
|
|
|
@app.post("/chat/")
|
|
async def chat(request: ChatRequest):
|
|
try:
|
|
logger.info(
|
|
f"Recibido mensaje: user_id={request.user_id}, query={request.query}"
|
|
)
|
|
|
|
if request.user_id not in chat_states:
|
|
chat_states[request.user_id] = {
|
|
"messages": [],
|
|
"query": "",
|
|
"response": "",
|
|
"phone": request.user_id,
|
|
}
|
|
|
|
state = chat_states[request.user_id]
|
|
state["query"] = request.query
|
|
|
|
try:
|
|
result = graph.invoke(state)
|
|
chat_states[request.user_id] = result
|
|
|
|
# Asegurar que siempre devolvemos una respuesta válida
|
|
if isinstance(result, dict) and "response" in result:
|
|
return {"response": result["response"]}
|
|
else:
|
|
logger.warning(f"Resultado inesperado del graph: {result}")
|
|
return {"response": str(result)}
|
|
|
|
except Exception as graph_error:
|
|
logger.error(f"Error en el graph: {str(graph_error)}", exc_info=True)
|
|
return {"response": "Lo siento, hubo un error al procesar tu solicitud."}
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error general: {str(e)}", exc_info=True)
|
|
return {"response": "Lo siento, ocurrió un error inesperado."}
|
|
|
|
|
|
@app.get("/health")
|
|
async def health_check():
|
|
return {"status": "ok"}
|