import uuid from typing import Any, Dict, List, Optional import urllib3 from dotenv import load_dotenv from fastapi import FastAPI, HTTPException from pydantic import BaseModel from src.constants import CATEGORY_SUBCATEGORY_MAP, DEFAULT_DRILL_INFO from src.utils import (DatabaseHandler, DateHandler, create_naming_assistant, extract_partner_info, find_partner_by_url, generate_drill_description, get_llm, infer_drill_type, infer_eligibility, infer_purpose, infer_subcategory, infer_user_uncertainty, infer_yes_no, prepare_api_payload, register_event, register_partner, save_to_database, validate_partner_url) urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) load_dotenv() app = FastAPI() date_handler = DateHandler(default_timezone="Asia/Kolkata") db_handler = DatabaseHandler() llm = get_llm() class SessionInput(BaseModel): session_id: Optional[str] = None message: str current_question: Optional[str] = None class SessionResponse(BaseModel): session_id: str message: str event_link: Optional[str] = None current_question: Optional[str] = None registration_complete: bool = False session_store: Dict[str, Dict[str, Any]] = {} @app.post("/chat", response_model=SessionResponse) async def chat_endpoint(chat_input: SessionInput): try: session_id = chat_input.session_id or str(uuid.uuid4()) if session_id not in session_store: session_store[session_id] = { "context": {"hackathon_details": DEFAULT_DRILL_INFO.copy()}, "current_question": None, } session_data = session_store[session_id] message = chat_input.message context = session_data["context"] current_question = ( chat_input.current_question or session_data["current_question"] ) if not current_question: session_data.update({"current_question": "drillSubCategory"}) return SessionResponse( session_id=session_id, message="What type of event you want to host : Workshop, Webinar, Masterclass, Innovation Hackathon, Squad Program, Case Study, Hiring Hackathon, Innovation, Tech Conferences, Bootcamp, Startup, Conclave, Contractual, Ideathon, Internal Hackathon, Smart India Hackathon?", current_question="drillSubCategory", ) if current_question == "drillSubCategory": subcategory = infer_subcategory(message, CATEGORY_SUBCATEGORY_MAP, llm) if not subcategory: return SessionResponse( session_id=session_id, message="Could not determine a valid subcategory. Please try again.", current_question="drillSubCategory", ) context["hackathon_details"]["drillSubCategory"] = subcategory context["hackathon_details"]["drillCategory"] = CATEGORY_SUBCATEGORY_MAP[ subcategory ] session_data.update({"current_question": "drillName"}) return SessionResponse( session_id=session_id, message="What name do you want to give to your event?", current_question="drillName", ) if current_question == "drillName": # Check if user is uncertain or needs help if infer_user_uncertainty(message, llm) or session_store[session_id].get( "in_naming_conversation" ): # Initialize naming conversation if not exists if "naming_assistant" not in session_store[session_id]: naming_assistant = create_naming_assistant(llm) session_store[session_id]["naming_assistant"] = naming_assistant session_store[session_id]["in_naming_conversation"] = True session_store[session_id]["naming_history"] = [] # Start the conversation response = naming_assistant.invoke( { "input": "I need help naming my event. It's a " + context["hackathon_details"]["drillSubCategory"], "history": [], } ) session_store[session_id]["naming_history"].append( {"user": message, "assistant": response} ) return SessionResponse( session_id=session_id, message=response, current_question="drillName", ) # Continue naming conversation naming_assistant = session_store[session_id]["naming_assistant"] history = session_store[session_id]["naming_history"] # Format history for the prompt formatted_history = "\n".join( [f"User: {h['user']}\nAssistant: {h['assistant']}" for h in history] ) response = naming_assistant.invoke( {"input": message, "history": formatted_history} ) # Update conversation history history.append({"user": message, "assistant": response}) # Check if a name was selected if "SELECTED_NAME:" in response: selected_name = response.split("SELECTED_NAME:")[1].strip() context["hackathon_details"]["drillName"] = selected_name # Clean up naming conversation session_store[session_id].pop("naming_assistant", None) session_store[session_id].pop("in_naming_conversation", None) session_store[session_id].pop("naming_history", None) session_data.update({"current_question": "phaseStartDt"}) return SessionResponse( session_id=session_id, message=f"Perfect! Your event name is set to {selected_name}. When do you want to organize it?", current_question="phaseStartDt", ) return SessionResponse( session_id=session_id, message=response, current_question="drillName", ) # Direct name input else: context["hackathon_details"]["drillName"] = message session_data.update({"current_question": "phaseStartDt"}) return SessionResponse( session_id=session_id, message=f"Great! Your event name is set to {message}. When do you want to organize it?", current_question="phaseStartDt", ) elif current_question == "phaseStartDt": parsed_date = date_handler.parse_date_string(message) if parsed_date is None: return SessionResponse( session_id=session_id, message="I couldn't understand that date format. Please provide a date in DD-MM-YYYY format.", current_question="phaseStartDt", ) formatted_date = parsed_date.strftime("%d-%m-%Y") is_valid, transformed_date, error_message = date_handler.validate_date( formatted_date ) if not is_valid: return SessionResponse( session_id=session_id, message=error_message, current_question="phaseStartDt", ) phase_dates = date_handler.get_phase_dates(transformed_date, "Asia/Kolkata") context["hackathon_details"].update(phase_dates) return SessionResponse( session_id=session_id, message="Do you want submissions based on specific themes or solutions to problems? (Problems Based or Theme Based)", current_question="drillType", ) elif current_question == "drillType": drill_type = infer_drill_type(message, llm) context["hackathon_details"]["drillType"] = drill_type return SessionResponse( session_id=session_id, message="Will this event be paid? (Yes/No)", current_question="isDrillPaid", ) elif current_question == "isDrillPaid": is_paid = infer_yes_no(message, llm) context["hackathon_details"]["isDrillPaid"] = is_paid == "Yes" return SessionResponse( session_id=session_id, message="What is the purpose of this event? (Provide a one-liner answer)", current_question="drillPurpose", ) elif current_question == "drillPurpose": purpose = infer_purpose(context, message, llm) context["hackathon_details"]["drillPurpose"] = purpose session_data.update({"current_question": "eligibility"}) return SessionResponse( session_id=session_id, message="Who can participate in this event? (Options: Graduate, College Students, Working Professionals)", current_question="eligibility", ) elif current_question == "eligibility": eligibility = infer_eligibility(message, llm) if not eligibility: return SessionResponse( session_id=session_id, message="Could not determine eligibility. Please specify who can participate (Graduate, College Students, Working Professionals)", current_question="eligibility", ) context["hackathon_details"]["eligibility"] = eligibility session_data.update({"current_question": "hasPartner"}) return SessionResponse( session_id=session_id, message="Do you want to add a partner organization for this event? (Yes/No)", current_question="hasPartner", ) elif current_question == "hasPartner": has_partner = infer_yes_no(message, llm) context["has_partner"] = has_partner == "Yes" if context["has_partner"]: session_data.update({"current_question": "partnerUrl"}) return SessionResponse( session_id=session_id, message="Please provide the website URL of the partner organization:", current_question="partnerUrl", ) else: context["hackathon_details"].update( { "drillPartnerId": "b886470e-52ac-4d34-8621-ff3e4d8335fb", "drillPartnerName": "WUElev8 Innovation services private ltd", } ) try: drill_info = context["hackathon_details"] drill_info["drillDescription"] = generate_drill_description( drill_info, llm ) api_payload = prepare_api_payload(drill_info) event_link = register_event(api_payload, drill_info["eligibility"]) save_to_database(drill_info, db_handler) session_store.pop(session_id, None) return SessionResponse( session_id=session_id, message="Your event has been successfully registered!", event_link=event_link, registration_complete=True, ) except Exception as e: print(f"Registration error: {str(e)}") return SessionResponse( session_id=session_id, message=f"An error occurred during registration: {str(e)}", current_question=current_question, ) elif current_question == "partnerUrl": partner_url = message.strip() try: if not validate_partner_url(partner_url): return SessionResponse( session_id=session_id, message="The provided URL seems to be invalid or inaccessible. Please provide a valid URL.", current_question="partnerUrl", ) existing_partner = find_partner_by_url(partner_url) if existing_partner and "partnerId" in existing_partner: partner_id = existing_partner["partnerId"] partner_name = ( existing_partner.get("partnerDisplayName") or existing_partner.get("partnerName") or partner_url.split("/")[2] .replace("www.", "") .split(".")[0] .title() ) print(f"Using existing partner: {partner_name} (ID: {partner_id})") else: try: partner_info = extract_partner_info(partner_url, llm) partner_response = register_partner(partner_info) if not partner_response or "partnerId" not in partner_response: raise ValueError("Failed to register partner") partner_id = partner_response["partnerId"] partner_name = ( partner_response.get("partnerDisplayName") or partner_response.get("partnerName") or partner_url.split("/")[2] .replace("www.", "") .split(".")[0] .title() ) print( f"Registered new partner: {partner_name} (ID: {partner_id})" ) except Exception as e: print(f"Partner extraction error: {str(e)}") raise ValueError( f"Failed to extract partner information: {str(e)}" ) context["hackathon_details"].update( {"drillPartnerId": partner_id, "drillPartnerName": partner_name} ) drill_info = context["hackathon_details"] drill_info["drillDescription"] = generate_drill_description( drill_info, llm ) api_payload = prepare_api_payload(drill_info) event_link = register_event(api_payload, drill_info["eligibility"]) save_to_database(drill_info, db_handler) session_store.pop(session_id, None) return SessionResponse( session_id=session_id, message=f"Event successfully registered with partner {partner_name}!", event_link=event_link, registration_complete=True, ) except Exception as e: print(f"Partner registration error: {str(e)}") return SessionResponse( session_id=session_id, message="There was an issue with the partner registration. Please try again with a different URL.", current_question="partnerUrl", ) except Exception as e: print(f"Chat endpoint error: {str(e)}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/sessions/{session_id}/status") async def get_session_status(session_id: str): """Get the current status of a session.""" if session_id not in session_store: raise HTTPException(status_code=404, detail="Session not found") return session_store[session_id] @app.delete("/sessions/{session_id}") async def clear_session(session_id: str): """Clear a session from memory.""" if session_id in session_store: session_store.pop(session_id) return {"message": "Session cleared"}