Spaces:
Running
Running
File size: 12,066 Bytes
6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 aefac4f 6dc9d46 | 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 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 | # RagBot API
**REST API for Medical Biomarker Analysis**
Exposes the RagBot multi-agent RAG system as a FastAPI REST service for web integration.
---
## π― Overview
This API wraps the RagBot clinical analysis system, providing:
- **Natural language input** - Extract biomarkers from conversational text
- **Structured JSON input** - Direct biomarker analysis
- **Full detailed responses** - All agent outputs, citations, recommendations
- **Example endpoint** - Pre-run diabetes case for testing
---
## π Table of Contents
- [Quick Start](#quick-start)
- [Endpoints](#endpoints)
- [Request/Response Examples](#requestresponse-examples)
- [Deployment](#deployment)
- [Development](#development)
- [Troubleshooting](#troubleshooting)
---
## π Quick Start
### Prerequisites
1. **Python 3.11+** installed
2. **Free API key** from one of:
- [Groq](https://console.groq.com/keys) β Recommended (fast, free)
- [Google Gemini](https://aistudio.google.com/app/apikey) β Alternative
3. **RagBot dependencies installed** (see root README)
### Option 1: Run Locally (Development)
```bash
# From RagBot root directory
cd api
# Install dependencies
pip install -r ../requirements.txt
pip install -r requirements.txt
# Ensure .env is configured in project root with your API keys
# GROQ_API_KEY=gsk_...
# LLM_PROVIDER=groq
# Run server
python -m uvicorn app.main:app --reload --port 8000
```
### Option 2: Run with Docker
```bash
# From api directory
docker-compose up --build
```
Server will start on `http://localhost:8000`
---
## π‘ Endpoints
### 1. Health Check
```http
GET /api/v1/health
```
**Response:**
```json
{
"status": "healthy",
"timestamp": "2026-02-23T10:30:00Z",
"llm_status": "connected",
"vector_store_loaded": true,
"available_models": ["llama-3.3-70b-versatile (Groq)"],
"uptime_seconds": 3600.0,
"version": "1.0.0"
}
```
---
### 2. List Biomarkers
```http
GET /api/v1/biomarkers
```
**Returns:** All 24 supported biomarkers with reference ranges, units, and clinical significance.
---
### 3. Natural Language Analysis
```http
POST /api/v1/analyze/natural
Content-Type: application/json
```
**Request:**
```json
{
"message": "My glucose is 185, HbA1c is 8.2 and cholesterol is 210",
"patient_context": {
"age": 52,
"gender": "male",
"bmi": 31.2
}
}
```
**Response:** Full detailed analysis (see [Response Structure](#response-structure))
---
### 4. Structured Analysis
```http
POST /api/v1/analyze/structured
Content-Type: application/json
```
**Request:**
```json
{
"biomarkers": {
"Glucose": 185.0,
"HbA1c": 8.2,
"Cholesterol": 210.0,
"Triglycerides": 210.0,
"HDL": 38.0
},
"patient_context": {
"age": 52,
"gender": "male",
"bmi": 31.2
}
}
```
**Response:** Same as natural language analysis
---
### 5. Example Case
```http
GET /api/v1/example
```
**Returns:** Pre-run diabetes case (52-year-old male with elevated glucose/HbA1c)
---
## π Request/Response Examples
### Response Structure
```json
{
"status": "success",
"request_id": "req_abc123xyz",
"timestamp": "2025-11-23T10:30:00.000Z",
"extracted_biomarkers": {
"Glucose": 185.0,
"HbA1c": 8.2
},
"input_biomarkers": {
"Glucose": 185.0,
"HbA1c": 8.2
},
"patient_context": {
"age": 52,
"gender": "male",
"bmi": 31.2
},
"prediction": {
"disease": "Diabetes",
"confidence": 0.87,
"probabilities": {
"Diabetes": 0.87,
"Heart Disease": 0.08,
"Anemia": 0.03,
"Thalassemia": 0.01,
"Thrombocytopenia": 0.01
}
},
"analysis": {
"biomarker_flags": [
{
"name": "Glucose",
"value": 185.0,
"unit": "mg/dL",
"status": "CRITICAL_HIGH",
"reference_range": "70-100 mg/dL",
"warning": "Hyperglycemia"
}
],
"safety_alerts": [
{
"severity": "CRITICAL",
"biomarker": "Glucose",
"message": "Glucose is 185.0 mg/dL, above critical threshold",
"action": "SEEK IMMEDIATE MEDICAL ATTENTION"
}
],
"key_drivers": [
{
"biomarker": "Glucose",
"value": 185.0,
"explanation": "Glucose at 185.0 mg/dL is CRITICAL_HIGH...",
"evidence": "Retrieved from medical literature..."
}
],
"disease_explanation": {
"pathophysiology": "Detailed disease mechanism...",
"citations": ["Source 1", "Source 2"],
"retrieved_chunks": [...]
},
"recommendations": {
"immediate_actions": [
"Consult healthcare provider immediately..."
],
"lifestyle_changes": [
"Follow a balanced, nutrient-rich diet..."
],
"monitoring": [
"Monitor glucose levels daily..."
]
},
"confidence_assessment": {
"prediction_reliability": "MODERATE",
"evidence_strength": "STRONG",
"limitations": ["Limited biomarkers provided"],
"reasoning": "High confidence based on glucose and HbA1c..."
}
},
"agent_outputs": [
{
"agent_name": "Biomarker Analyzer",
"findings": {...},
"metadata": {...}
}
],
"workflow_metadata": {
"sop_version": "Baseline",
"processing_timestamp": "2025-11-23T10:30:00Z",
"agents_executed": 5,
"workflow_success": true
},
"conversational_summary": "Hi there! π\n\nBased on your biomarkers...",
"processing_time_ms": 3542.0,
"sop_version": "Baseline"
}
```
### cURL Examples
**Health Check:**
```bash
curl http://localhost:8000/api/v1/health
```
**Natural Language Analysis:**
```bash
curl -X POST http://localhost:8000/api/v1/analyze/natural \
-H "Content-Type: application/json" \
-d '{
"message": "My glucose is 185 and HbA1c is 8.2",
"patient_context": {
"age": 52,
"gender": "male"
}
}'
```
**Structured Analysis:**
```bash
curl -X POST http://localhost:8000/api/v1/analyze/structured \
-H "Content-Type: application/json" \
-d '{
"biomarkers": {
"Glucose": 185.0,
"HbA1c": 8.2
},
"patient_context": {
"age": 52,
"gender": "male"
}
}'
```
**Get Example:**
```bash
curl http://localhost:8000/api/v1/example
```
---
## π³ Deployment
### Docker Deployment
1. **Build and run:**
```bash
cd api
docker-compose up --build
```
2. **Check health:**
```bash
curl http://localhost:8000/api/v1/health
```
3. **View logs:**
```bash
docker-compose logs -f ragbot-api
```
4. **Stop:**
```bash
docker-compose down
```
### Production Deployment
For production:
1. **Update `.env`:**
```bash
CORS_ORIGINS=https://your-frontend-domain.com
API_RELOAD=false
LOG_LEVEL=WARNING
```
2. **Use production WSGI server:**
```bash
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker
```
3. **Add reverse proxy (nginx):**
```nginx
location /api {
proxy_pass http://localhost:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
```
---
## π» Development
### Project Structure
```
api/
βββ app/
β βββ __init__.py
β βββ main.py # FastAPI application
β βββ models/
β β βββ __init__.py
β β βββ schemas.py # Pydantic models
β βββ routes/
β β βββ __init__.py
β β βββ analyze.py # Analysis endpoints
β β βββ biomarkers.py # Biomarkers list
β β βββ health.py # Health check
β βββ services/
β βββ __init__.py
β βββ extraction.py # Natural language extraction
β βββ ragbot.py # Workflow wrapper
βββ requirements.txt
βββ Dockerfile
βββ docker-compose.yml
βββ .env.example
βββ README.md
```
### Running Tests
```bash
# Test health endpoint
curl http://localhost:8000/api/v1/health
# Test example case
curl http://localhost:8000/api/v1/example
# Test natural language
curl -X POST http://localhost:8000/api/v1/analyze/natural \
-H "Content-Type: application/json" \
-d '{"message": "glucose 140, HbA1c 7.5"}'
```
### Hot Reload
For development with auto-reload:
```bash
uvicorn app.main:app --reload --port 8000
```
---
## π§ Troubleshooting
### Issue: "API key not found"
**Symptom:** Health check shows `llm_status: "disconnected"`
**Solutions:**
1. Ensure `.env` in project root has your API key:
```bash
GROQ_API_KEY=gsk_...
LLM_PROVIDER=groq
```
2. Get a free key at https://console.groq.com/keys
3. Restart the API server after editing `.env`
---
### Issue: "Vector store not loaded"
**Symptom:** Health check shows `vector_store_loaded: false`
**Solutions:**
1. Run vector store setup from RagBot root:
```bash
python scripts/setup_embeddings.py
```
2. Check `data/vector_stores/medical_knowledge.faiss` exists
3. Restart API server
---
### Issue: "No biomarkers found"
**Symptom:** Natural language endpoint returns error
**Solutions:**
1. Be explicit: "My glucose is 140" (not "blood sugar is high")
2. Include numbers: "glucose 140" works better than "elevated glucose"
3. Use structured endpoint if you have exact values
---
### Issue: Docker container can't reach LLM API
**Symptom:** Container health check fails
**Solutions:**
Ensure your API keys are passed as environment variables in `docker-compose.yml`:
```yaml
environment:
- GROQ_API_KEY=${GROQ_API_KEY}
- LLM_PROVIDER=groq
```
For local Ollama (optional):
**Windows/Mac (Docker Desktop):**
```yaml
environment:
- OLLAMA_BASE_URL=http://host.docker.internal:11434
```
**Linux:**
```yaml
network_mode: "host"
```
---
## π Integration Examples
### JavaScript/TypeScript
```typescript
// Analyze biomarkers from natural language
async function analyzeBiomarkers(userInput: string) {
const response = await fetch('http://localhost:8000/api/v1/analyze/natural', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: userInput,
patient_context: {
age: 52,
gender: "male"
}
})
});
const result = await response.json();
return result;
}
// Display results
const analysis = await analyzeBiomarkers("My glucose is 185 and HbA1c is 8.2");
console.log(`Prediction: ${analysis.prediction.disease}`);
console.log(`Confidence: ${(analysis.prediction.confidence * 100).toFixed(0)}%`);
console.log(`\n${analysis.conversational_summary}`);
```
### Python
```python
import requests
# Structured analysis
response = requests.post(
'http://localhost:8000/api/v1/analyze/structured',
json={
'biomarkers': {
'Glucose': 185.0,
'HbA1c': 8.2
},
'patient_context': {
'age': 52,
'gender': 'male'
}
}
)
result = response.json()
print(f"Disease: {result['prediction']['disease']}")
print(f"Confidence: {result['prediction']['confidence']:.1%}")
```
---
## π API Documentation
Once the server is running, visit:
- **Swagger UI:** http://localhost:8000/docs
- **ReDoc:** http://localhost:8000/redoc
- **OpenAPI Schema:** http://localhost:8000/openapi.json
---
## π€ Support
For issues or questions:
1. Check [Troubleshooting](#troubleshooting) section
2. Review API documentation at `/docs`
3. Check RagBot main README
---
## π Performance Notes
- **Initial startup:** 10-30 seconds (loads vector store)
- **Analysis time:** 15-25 seconds per request (6 agents + RAG retrieval)
- **Concurrent requests:** Supported (FastAPI async)
- **Memory usage:** ~2-4GB (vector store + embeddings model)
---
## π Security Notes
**For MVP/Development:**
- CORS allows all origins (`*`)
- No authentication required
- Runs on localhost
**For Production:**
- Restrict CORS to specific origins
- Add API key authentication
- Use HTTPS
- Implement rate limiting
- Add request validation
---
Built with β€οΈ on top of RagBot Multi-Agent RAG System
|