virgil-ai/src/api/v1/router.py
2025-09-29 18:09:44 +03:00

89 lines
No EOL
3.1 KiB
Python

import base64
import json
from fastapi import APIRouter, HTTPException
from src.services.estimation_service_v2 import EstimationService
from . import models
from ...cache.page_cache import get_page_description
from ...services.chat_service import chat_service
router = APIRouter()
@router.post("/insurance_chat", response_model=models.InsuranceChatResponse)
async def insurance_chat(request: models.InsuranceChatRequest):
"""Handle insurance chat requests"""
try:
current_page = None
if request.context and request.context.page:
page_id = str(request.context.page).lower()
current_page = await get_page_description(page_id)
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.process_insurance_chat(
message=request.message,
session_id=request.session_id,
uid=str(request.userId) if request.userId else None,
current_page=current_page,
application=application,
)
return models.InsuranceChatResponse(
session_id=result["session_id"],
answer=result["answer"],
sources=result["sources"],
history=result["history"],
hooks=result["hooks"],
)
except Exception as e:
# 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"""
try:
if not request.applicants or not request.plans:
raise HTTPException(
status_code=400,
detail="Missing required applicants or plans"
)
estimation_service = EstimationService()
estimation_response = await estimation_service.estimate_insurance(request.applicants, request.phq, request.plans)
return estimation_response
except HTTPException as e:
print("HTTPException in estimate: ", e)
raise e
except Exception as e:
print("Exception in estimate: ", e)
raise HTTPException(
status_code=500,
detail=f"Server error: {str(e)}"
)