Spaces:
Running
Running
File size: 12,804 Bytes
73c6377 91b29af 73c6377 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 |
# 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
|