HBV_AI_Assistant / API_DOCUMENTATION.md
moazx's picture
Update the documentation
91b29af
# HBV AI Assistant - API Documentation for Frontend Engineers
## Table of Contents
- [Overview](#overview)
- [Base URL](#base-url)
- [Core Endpoints](#core-endpoints)
- [1. POST /assess](#1-post-assess)
- [2. POST /assess/text](#2-post-assesstext)
- [3. POST /ask](#3-post-ask)
- [4. POST /ask/stream](#4-post-askstream)
- [5. GET /health](#5-get-health)
- [Additional Endpoints](#additional-endpoints)
- [Error Handling](#error-handling)
- [Code Examples](#code-examples)
---
## Overview
The HBV AI Assistant API provides endpoints for evaluating patient eligibility for HBV (Hepatitis B Virus) treatment according to SASLT 2021 guidelines. The API supports both structured data input and free-form text parsing, along with an interactive AI chat for guideline exploration.
**API Version:** 1.0.0
---
## Base URL
```
Development: http://127.0.0.1:8000
Production: https://moazx-hbv-ai-assistant.hf.space/
```
---
## Core Endpoints
### 1. POST /assess
**Primary endpoint for HBV patient eligibility assessment with structured data input.**
#### Request
**URL:** `/assess`
**Method:** `POST`
**Content-Type:** `application/json`
**Request Body Schema:**
```json
{
"sex": "Male", // Required: "Male" or "Female"
"age": 45, // Required: 0-120
"pregnancy_status": "Not pregnant", // Required: "Not pregnant" or "Pregnant"
"hbsag_status": "Positive", // Required: "Positive" or "Negative"
"duration_hbsag_months": 12, // Required: Duration in months (≥0)
"hbv_dna_level": 5000, // Required: HBV DNA in IU/mL (≥0)
"hbeag_status": "Positive", // Required: "Positive" or "Negative"
"alt_level": 80, // Required: ALT in U/L (≥0)
"fibrosis_stage": "F2-F3", // Required: "F0-F1", "F2-F3", or "F4"
"necroinflammatory_activity": "A2", // Required: "A0", "A1", "A2", or "A3"
"extrahepatic_manifestations": false, // Required: true or false
"immunosuppression_status": "None", // Optional: "None", "Chemotherapy", "Other"
"coinfections": [], // Optional: Array of "HIV", "HCV", "HDV"
"family_history_cirrhosis_hcc": false, // Required: true or false
"other_comorbidities": [] // Optional: Array of strings
}
```
#### Response
**Status Code:** `200 OK`
**Response Body:**
```json
{
"eligible": true,
"recommendations": "Based on SASLT 2021 guidelines, this patient IS ELIGIBLE for HBV antiviral treatment.\n\n**Eligibility Criteria Met:**\n- HBeAg-positive chronic hepatitis B with HBV DNA >2,000 IU/mL and ALT elevation (80 U/L) [SASLT 2021, Page 15]\n- Significant fibrosis (F2-F3) with moderate necroinflammatory activity (A2) [SASLT 2021, Page 18]\n\n**Treatment Recommendations:**\n1. **First-line therapy:** Entecavir (ETV) 0.5mg daily or Tenofovir Disoproxil Fumarate (TDF) 300mg daily [SASLT 2021, Page 22]\n2. **Alternative:** Tenofovir Alafenamide (TAF) 25mg daily for patients with renal concerns [SASLT 2021, Page 23]\n\n**Monitoring:**\n- HBV DNA every 3 months during first year\n- ALT and complete blood count every 3-6 months\n- HBeAg/anti-HBe every 6-12 months [SASLT 2021, Page 28]"
}
```
#### Field Descriptions
| Field | Type | Description | Validation |
|-------|------|-------------|------------|
| `sex` | string | Patient's biological sex | "Male" or "Female" |
| `age` | integer | Patient's age in years | 0-120 |
| `pregnancy_status` | string | Current pregnancy status | "Not pregnant" or "Pregnant" |
| `hbsag_status` | string | Hepatitis B surface antigen status | "Positive" or "Negative" |
| `duration_hbsag_months` | integer | How long HBsAg has been positive | ≥0 |
| `hbv_dna_level` | float | HBV DNA viral load | ≥0 IU/mL |
| `hbeag_status` | string | Hepatitis B e-antigen status | "Positive" or "Negative" |
| `alt_level` | float | Alanine aminotransferase level | ≥0 U/L |
| `fibrosis_stage` | string | Liver fibrosis/cirrhosis stage | "F0-F1", "F2-F3", or "F4" |
| `necroinflammatory_activity` | string | Degree of liver inflammation | "A0", "A1", "A2", or "A3" |
| `extrahepatic_manifestations` | boolean | Presence of HBV-related conditions outside liver | true/false |
| `immunosuppression_status` | string | Current immunosuppression | "None", "Chemotherapy", "Other" |
| `coinfections` | array | Other viral infections | ["HIV", "HCV", "HDV"] or [] |
| `family_history_cirrhosis_hcc` | boolean | First-degree relative with cirrhosis/HCC | true/false |
| `other_comorbidities` | array | Additional medical conditions | Array of strings or [] |
---
### 2. POST /assess/text
**Text-based HBV patient eligibility assessment - parses free-form clinical text.**
#### Request
**URL:** `/assess/text`
**Method:** `POST`
**Content-Type:** `application/json`
**Request Body Schema:**
```json
{
"text_input": "45-year-old male patient\nHBsAg: Positive for 12 months\nHBV DNA: 5000 IU/mL\nHBeAg: Positive\nALT: 80 U/L\nFibrosis stage: F2-F3\nNecroinflammatory activity: A2\nNo extrahepatic manifestations\nNo immunosuppression\nNo coinfections (HIV, HCV, HDV)\nNo family history of cirrhosis or HCC"
}
```
**Field:**
- `text_input` (string, required): Free-form text containing patient clinical data. Minimum 10 characters.
#### Response
**Status Code:** `200 OK`
**Response Body:** Same as `/assess` endpoint
```json
{
"eligible": true,
"recommendations": "Based on SASLT 2021 guidelines, this patient IS ELIGIBLE for HBV antiviral treatment..."
}
```
#### How It Works
1. **LLM-based parsing:** The API uses an AI model to extract structured patient data from the free-form text
2. **Validation:** Extracted data is validated against the same schema as `/assess`
3. **Assessment:** Performs identical assessment logic as the structured endpoint
4. **Response:** Returns the same structured response format
#### Text Input Tips
- Include all relevant clinical parameters
- Use clear labels (e.g., "HBV DNA:", "ALT:", "Age:")
- Can use natural language or structured format
- The AI will extract and interpret the data intelligently
---
### 3. POST /ask
**Interactive AI chat for exploring HBV treatment guidelines.**
#### Request
**URL:** `/ask`
**Method:** `POST`
**Content-Type:** `application/json`
**Request Body Schema:**
```json
{
"query": "What are the first-line treatment options for HBeAg-positive chronic hepatitis B?",
"session_id": "doctor_123_session_1",
"patient_context": {
// Optional: Include HBVPatientInput object for context
"age": 45,
"sex": "Male",
"hbv_dna_level": 5000,
// ... other patient fields
},
"assessment_result": {
// Optional: Include prior assessment result for context
"eligible": true,
"recommendations": "..."
}
}
```
**Fields:**
- `query` (string, required): Doctor's question about HBV guidelines. Max 2000 characters.
- `session_id` (string, optional): Session identifier for conversation continuity. Default: "default"
- `patient_context` (object, optional): Patient data from a prior assessment to provide context
- `assessment_result` (object, optional): Assessment result to provide context
#### Response
**Status Code:** `200 OK`
**Response Body:**
```json
{
"response": "According to SASLT 2021 guidelines, the first-line treatment options for HBeAg-positive chronic hepatitis B are:\n\n1. **Entecavir (ETV)** - 0.5mg once daily [SASLT 2021, Page 22]\n2. **Tenofovir Disoproxil Fumarate (TDF)** - 300mg once daily [SASLT 2021, Page 22]\n\nBoth medications have:\n- High barrier to resistance\n- Excellent efficacy in viral suppression\n- Well-established safety profiles\n\n**Alternative option:**\n- **Tenofovir Alafenamide (TAF)** - 25mg once daily, particularly for patients with renal concerns or bone disease [SASLT 2021, Page 23]",
"session_id": "doctor_123_session_1"
}
```
#### Session Management
- **Conversation continuity:** Use the same `session_id` to maintain conversation context across multiple questions
- **New conversation:** Use a different `session_id` or omit it for a fresh conversation
- **Clear session:** Use `DELETE /session/{session_id}` to clear conversation history
---
### 4. POST /ask/stream
**Streaming version of the AI chat endpoint for real-time responses.**
#### Request
**URL:** `/ask/stream`
**Method:** `POST`
**Content-Type:** `application/json`
**Request Body:** Same as `/ask` endpoint
```json
{
"query": "What monitoring is required during HBV treatment?",
"session_id": "doctor_123_session_1"
}
```
#### Response
**Status Code:** `200 OK`
**Content-Type:** `text/markdown`
**Transfer-Encoding:** `chunked`
**Response:** Streaming text/markdown chunks
The response streams in real-time as the AI generates the answer. This provides a better user experience for longer responses.
---
### 5. GET /health
**Simple health check endpoint to verify API is running.**
#### Request
**URL:** `/health`
**Method:** `GET`
#### Response
**Status Code:** `200 OK`
**Response Body:**
```json
{
"status": "healthy",
"version": "1.0.0",
"timestamp": "2024-01-15T10:30:00.123456"
}
```
**Fields:**
- `status` (string): API health status ("healthy")
- `version` (string): API version
- `timestamp` (string): Current server timestamp in ISO format
#### Use Case
Use this endpoint to:
- Verify the API is running and accessible
- Monitor API availability
- Check server time for debugging
---
## Additional Endpoints
### API Information
**GET** `/`
**Response:**
```json
{
"name": "HBV AI Assistant API",
"version": "1.0.0",
"description": "HBV Patient Selection System - Evaluates patient eligibility for HBV treatment according to SASLT 2021 guidelines",
"docs": "/docs",
"endpoints": {
"assess": "/assess (POST) - Primary endpoint for HBV patient eligibility assessment",
"assess_text": "/assess/text (POST) - Text-based HBV patient eligibility assessment",
"ask": "/ask (POST) - Optional AI chat for guideline exploration",
"ask_stream": "/ask/stream (POST) - Streaming AI chat responses",
"health": "/health (GET) - Simple health check"
}
}
```
---
## Error Handling
### HTTP Status Codes
| Code | Description |
|------|-------------|
| 200 | Success |
| 400 | Bad Request - Invalid input data |
| 422 | Validation Error - Request body doesn't match schema |
| 429 | Too Many Requests - Rate limit exceeded |
| 500 | Internal Server Error |
### Error Response Format
```json
{
"detail": "Error message describing what went wrong"
}
```
### Validation Error Example
**Request with invalid data:**
```json
{
"sex": "Unknown", // Invalid: must be "Male" or "Female"
"age": 150 // Invalid: must be 0-120
}
```
**Response (422):**
```json
{
"detail": [
{
"loc": ["body", "sex"],
"msg": "Sex must be either Male or Female",
"type": "value_error"
},
{
"loc": ["body", "age"],
"msg": "ensure this value is less than or equal to 120",
"type": "value_error.number.not_le"
}
]
}
```
---
## Interactive API Documentation
For interactive API documentation with a built-in testing interface, visit:
**Swagger UI:** `http://127.0.0.1:8000/docs`
**ReDoc:** `http://127.0.0.1:8000/redoc`
These interfaces allow you to:
- View all endpoints and their schemas
- Test endpoints directly from the browser
- See example requests and responses
- Understand validation rules
---
## Rate Limiting
The API implements rate limiting:
- **Default limit:** 100 requests per minute per IP address
- **Response header:** `X-RateLimit-Remaining` shows remaining requests
- **Status code:** 429 when limit exceeded
---
## Best Practices
1. **Error Handling:**
- Always check `response.ok` before parsing JSON
- Display validation errors to users clearly
- Implement retry logic for 500 errors
2. **Session Management:**
- Use unique session IDs for different patient conversations
- Clear sessions when switching patients
- Consider using user ID + timestamp for session IDs
3. **Performance:**
- Use `/ask/stream` for better UX on longer responses
- Cache assessment results when appropriate
- Consider debouncing text input for `/assess/text` endpoint
4. **Data Validation:**
- Validate input on frontend before sending to API
- Use the exact enum values specified in the documentation
- Handle validation errors gracefully
---
## Support
For questions or issues:
- Check the interactive documentation at `/docs`
- Review error messages carefully - they indicate what's wrong
- Ensure all required fields are provided with correct data types
---
**Last Updated:** 2024-01-15
**API Version:** 1.0.0