finagent / app /routers /chat.py
omgy's picture
Update app/routers/chat.py
da83cd9 verified
"""
Chat router for handling conversational interactions.
Updated to work with new MasterAgent.process_message() method.
"""
from typing import Dict
from fastapi import APIRouter, HTTPException
from app.agents.master_agent import master_agent
from app.schemas import ChatRequest, ChatResponse
from app.services.firebase_service import firebase_service
from app.services.session_service import session_service
from app.utils.logger import setup_logger
logger = setup_logger("chat")
router = APIRouter()
@router.post("/", response_model=ChatResponse)
async def chat(request: ChatRequest):
"""
Process chat message and return agent response.
Args:
request: Chat request with session_id, user_id, and message
Returns:
ChatResponse with agent reply and metadata
"""
try:
logger.info(f"Chat request from user {request.user_id}, session {request.session_id}")
# Get or create session
session = session_service.get_session(request.session_id)
if not session:
logger.warning(f"Session not found: {request.session_id}")
session_id = session_service.create_session(request.user_id)
logger.info(f"Created new session {session_id} for user {request.user_id}")
else:
session_id = request.session_id
# Ensure user profile is set in session
if not session or "user_profile" not in session:
profile = firebase_service.get_user_profile(request.user_id)
if profile:
logger.info(f"Retrieved profile for user {request.user_id}")
session_service.set_user_profile(session_id, profile)
logger.info(f"Set user profile for session {session_id}")
# Process message through master agent
logger.info(f"Processing chat for session {session_id}, user {request.user_id}")
# Use the new process_message method
result = await master_agent.process_message(
user_id=request.user_id,
session_id=session_id,
user_message=request.message
)
logger.info(f"Agent response generated successfully for session {session_id}")
# Extract response components
reply = result.get("reply", "I apologize, but I couldn't process your request.")
decision = result.get("decision")
loan_id = result.get("loan_id")
# Determine step from decision
if decision == "APPROVED":
step = "APPROVED"
elif decision == "REJECTED":
step = "REJECTED"
elif decision == "ADJUST":
step = "ADJUST" # Keep ADJUST as ADJUST, not REJECTED
else:
# Check session for current step
session = session_service.get_session(session_id)
step = session.get("current_step", "GATHERING_DETAILS") if session else "GATHERING_DETAILS"
# Update session with current step
if decision:
session_service.update_session(session_id, {"current_step": step})
logger.info(f"Set step to {step} for session {session_id}")
# Build response
response = ChatResponse(
reply=reply,
step=step,
decision=decision,
loan_id=loan_id,
session_id=session_id,
meta=None
)
logger.info(f"Chat response sent: decision={decision}, step={step}")
return response
except Exception as e:
logger.error(f"Chat error: {str(e)}", exc_info=True)
raise HTTPException(
status_code=500,
detail=f"Error processing chat message: {str(e)}"
)
@router.get("/session/{session_id}/info")
async def get_session_info(session_id: str):
"""
Get session information including current step and loan details.
Args:
session_id: Session identifier
Returns:
Session information
"""
try:
session = session_service.get_session(session_id)
if not session:
logger.warning(f"Session not found: {session_id}")
raise HTTPException(status_code=404, detail="Session not found")
return {
"session_id": session_id,
"user_id": session.get("user_id"),
"current_step": session.get("current_step", "WELCOME"),
"loan_decision": session.get("loan_decision"),
"created_at": session.get("created_at"),
"updated_at": session.get("updated_at")
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Error getting session info: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Error retrieving session: {str(e)}"
)
@router.delete("/session/{session_id}")
async def clear_session(session_id: str):
"""
Clear session data and memory.
Args:
session_id: Session identifier
Returns:
Success message
"""
try:
# Clear agent memory
master_agent.clear_memory(session_id)
# Delete session from service
session_service.delete_session(session_id)
logger.info(f"Cleared session {session_id}")
return {
"message": "Session cleared successfully",
"session_id": session_id
}
except Exception as e:
logger.error(f"Error clearing session: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Error clearing session: {str(e)}"
)
@router.get("/session/{session_id}/history")
async def get_chat_history(session_id: str):
"""
Get chat history for a session.
Args:
session_id: Session identifier
Returns:
Chat history
"""
try:
session = session_service.get_session(session_id)
if not session:
raise HTTPException(status_code=404, detail="Session not found")
# Get chat history from agent memory
memory = master_agent.get_or_create_memory(session_id)
return {
"session_id": session_id,
"chat_history": memory.load_memory_variables({}).get("chat_history", ""),
"current_step": session.get("current_step")
}
except HTTPException:
raise
except Exception as e:
logger.error(f"Error getting chat history: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Error retrieving chat history: {str(e)}"
)