HBV_AI_Assistant / api /routers /hbv_assessment.py
moazx's picture
Update assess and assess/text endpoints to simplify context handling
3699d7c
raw
history blame
4.72 kB
"""
HBV Patient Assessment Router
API endpoint for HBV treatment eligibility assessment
"""
from fastapi import APIRouter, HTTPException
from api.models import HBVPatientInput, HBVAssessmentResponse, TextAssessmentInput
import logging
from core.hbv_assessment import assess_hbv_eligibility
from core.text_parser import parse_patient_text, validate_extracted_data
logger = logging.getLogger(__name__)
router = APIRouter(
prefix="",
tags=["HBV Assessment"]
)
@router.post("/assess", response_model=HBVAssessmentResponse)
async def assess_patient(patient: HBVPatientInput) -> HBVAssessmentResponse:
"""
Assess HBV patient eligibility for treatment according to SASLT 2021 guidelines
This endpoint:
1. Validates patient data
2. Provides SASLT 2021 guideline pages (3, 4, 6, 7, 8, 9, 10) directly as context
3. Uses LLM to analyze patient against the guidelines
4. Returns structured assessment with eligibility and comprehensive recommendations
Returns:
HBVAssessmentResponse containing:
- eligible: Whether patient is eligible for treatment
- recommendations: Comprehensive narrative including eligibility determination,
specific criteria met, treatment options (ETV, TDF, TAF), and special considerations,
with inline citations in format [SASLT 2021, Page X]
"""
try:
logger.info(f"Assessing HBV patient: Age {patient.age}, Sex {patient.sex}, HBV DNA {patient.hbv_dna_level}")
# Convert Pydantic model to dict for core function
patient_data = patient.dict()
# Call core assessment function
result = assess_hbv_eligibility(patient_data)
# Convert dict result back to Pydantic response model
response = HBVAssessmentResponse(**result)
logger.info(f"Assessment complete: Eligible={response.eligible}")
return response
except Exception as e:
logger.error(f"Error assessing patient: {str(e)}")
raise HTTPException(status_code=500, detail=f"Error assessing patient: {str(e)}")
@router.post("/assess/text", response_model=HBVAssessmentResponse)
async def assess_patient_from_text(text_input: TextAssessmentInput) -> HBVAssessmentResponse:
"""
Assess HBV patient eligibility from free-form text input
This endpoint:
1. Parses free-form text to extract structured patient data using LLM
2. Validates the extracted data
3. Provides SASLT 2021 guideline pages directly as context
4. Uses LLM to analyze patient against the guidelines
5. Returns structured assessment with eligibility and recommendations
Example text input:
"45-year-old male patient
HBsAg: Positive for 12 months
HBV DNA: 5000 IU/mL
HBeAg: Positive
ALT: 80 U/L
Fibrosis stage: F2-F3
Necroinflammatory activity: A2
No extrahepatic manifestations
No immunosuppression
No coinfections (HIV, HCV, HDV)
No family history of cirrhosis or HCC"
Returns:
HBVAssessmentResponse containing:
- eligible: Whether patient is eligible for treatment
- recommendations: Comprehensive narrative with inline citations
"""
try:
logger.info(f"Received text input for assessment (length: {len(text_input.text_input)} characters)")
logger.info(f"Text input preview: {text_input.text_input[:200]}...")
# Parse text to extract structured patient data
logger.info("Parsing text input to extract patient data...")
patient_data = parse_patient_text(text_input.text_input)
logger.info(f"Extracted patient data: {patient_data}")
# Validate extracted data
logger.info("Validating extracted patient data...")
validated_data = validate_extracted_data(patient_data)
logger.info("Patient data validated successfully")
# Call core assessment function with extracted data
logger.info("Performing HBV eligibility assessment...")
result = assess_hbv_eligibility(validated_data)
# Convert dict result to Pydantic response model
response = HBVAssessmentResponse(**result)
logger.info(f"Text-based assessment complete: Eligible={response.eligible}")
return response
except ValueError as e:
logger.error(f"Validation error in text assessment: {str(e)}")
raise HTTPException(status_code=400, detail=f"Invalid patient data: {str(e)}")
except Exception as e:
logger.error(f"Error in text-based assessment: {str(e)}")
raise HTTPException(status_code=500, detail=f"Error processing text input: {str(e)}")