diff --git a/src/api/v1/router.py b/src/api/v1/router.py index ed83c4e..1009f5b 100644 --- a/src/api/v1/router.py +++ b/src/api/v1/router.py @@ -46,6 +46,21 @@ async def insurance_chat(request: models.InsuranceChatRequest): # raise e raise HTTPException(status_code=500, detail=f"Error processing chat request: {str(e)}") +@router.post("/initialize", response_model=models.InitializeChatResponse) +async def init_chat(request: models.InitializeChatRequest): + application = None + if request.context and request.context.application: + application = request.context.application + elif request.context and request.context.applicationDTO: + application = json.loads(base64.b64decode(request.context.applicationDTO).decode()) + + result = await chat_service.initialize_chat(str(request.userId), application) + return models.InitializeChatResponse( + session_id=result["session_id"], + answer=result["answer"], + ) + + @router.post("/estimation", response_model=models.EstimationResponse) async def estimate(request: models.EstimationRequest): """Handle insurance estimation requests""" diff --git a/src/models.py b/src/models.py index 75bdbc0..684250c 100644 --- a/src/models.py +++ b/src/models.py @@ -96,6 +96,14 @@ class InsuranceChatRequest(BaseModel): session_id: str | None = Field(None, description="Chat session ID") context: InsuranceChatContext | None = None +class InitializeChatRequest(BaseModel): + userId: str | int + context: InsuranceChatContext | None = None + +class InitializeChatResponse(BaseModel): + session_id: str + answer: str + class Source(BaseModel): plan_name: str chunk_number: int diff --git a/src/services/chat_service.py b/src/services/chat_service.py index 705a0a1..c88ecd9 100644 --- a/src/services/chat_service.py +++ b/src/services/chat_service.py @@ -8,6 +8,14 @@ from .session_service import session_service from ..api.v1.models import Source, HistoryItem from ..config import settings from ..database import Session, UserSession +from datetime import datetime + +# vars: name +INIT_MESSAGES = [ + "Hi. I’m Alia, your personal benefits assistant! If you have a question at any point in the enrollment process, just ask, and I’ll try to get you an answer.", + "Hi, {name}! Welcome back! As usual, I’m here if you have any questions!", + "Hi, {name}! Welcome back! Do you want to pick up where you left off and complete your PHQ?", +] class ChatService: @@ -125,6 +133,18 @@ class ChatService: # raise e print(f"Error getting chat history: {e}") return [] + + async def get_last_chat_message_date(self, session_id: str): + async with await self.get_client() as client: + try: + response = await client.get("/chat/", params={"chat_session_id": session_id, "limit": 1}) + resp_json = response.json() + msg_date = resp_json[0]["created_at"] + return datetime.fromisoformat(msg_date) + except: + return None + + def _extract_sources_from_response(self, response_text: str) -> List[Source]: """Extract sources from RAG search results if available""" @@ -153,6 +173,51 @@ class ChatService: session.add(user_session) session.commit() + async def initialize_chat(self, uid: str, application): + session_id = await self.get_user_session(uid) + if not session_id or not await session_service.validate_session(session_id): + session_id = await session_service.create_session(agent_id=settings.TALESTORM_AGENT_ID) + try: + await self.create_user_session(uid, session_id) + except: + pass + + try: + name = application["applicants"][0]["firstName"] + except: + return { + "session_id": session_id, + "answer": INIT_MESSAGES[0], + } + + last_message = self.get_last_chat_message_date(session_id) + if not last_message: + return { + "session_id": session_id, + "answer": INIT_MESSAGES[0], + } + + applicant = application["applicants"][0] + if not applicant.get("gender") or not applicant.get("dob") or applicant.get("dob") == "-01-" or not applicant.get("weight") or applicant.get("heightFt") is None or applicant.get("heightIn") is None: + return { + "session_id": session_id, + "answer": INIT_MESSAGES[2].format(name=name) + } + + return { + "session_id": session_id, + "answer": INIT_MESSAGES[1].format(name=name) + } + + + + + + + + + + async def process_insurance_chat(self, message: str, session_id: Optional[str] = None, uid: Optional[str] = None, current_page: Optional[str] = None, application: Optional[dict] = None) -> Dict[str, Any]: """Process an insurance chat request""" @@ -162,7 +227,10 @@ class ChatService: session_id = await self.get_user_session(uid) if not session_id or not await session_service.validate_session(session_id): session_id = await session_service.create_session(agent_id=settings.TALESTORM_AGENT_ID) - await self.create_user_session(uid, session_id) + try: + await self.create_user_session(uid, session_id) + except: + pass else: session_id = await session_service.create_session(agent_id=settings.TALESTORM_AGENT_ID)