A FastAPI application for medical policy analysis using GPT-4, featuring multiple specialized endpoints for different types of analysis and processing.
POST /api/generate-encodingConverts medical policy documents into structured JSON format with criteria and logical relationships.
Request:
{
"body": "Medical Policy Text...",
"max_tokens": 4000,
"temperature": 0.7
}Response:
{
"Source": "filename",
"Name": "policyname",
"case_scenario": "",
"encoding_issues": "",
"criteria": [
{
"no": "1",
"var": "age_requirement",
"crit": "Patient is 18 years or older"
}
],
"logic": "AND(OR(age_requirement), NOT(contraindications))"
}POST /api/generate-claim-reviewAnalyzes medical claims against policy requirements.
Request:
{
"body": [
"Policy Document Text...",
"Claim Details..."
],
"max_tokens": 4000,
"temperature": 0.7
}Response:
{
"claim_comparison": [
{
"policy_criterion": "Maximum hospital stay: 7 days",
"extracted_patient_data": "Hospital Stay: 9 days",
"matching_status": "Not Met",
"explanation": "Exceeds by 2 days..."
}
],
"error_detection": [
{
"error_type": "Duplicate Charge",
"service": "X-Ray",
"explanation": "Service billed twice..."
}
],
"approval_status": "Requires Additional Review"
}POST /api/generate-recommendation-and-mappingGenerates treatment recommendations based on policy criteria.
Request:
{
"body": {
"policy": [
{
"no": "1",
"var": "condition_severity",
"crit": "Severe condition requiring intervention"
}
],
"patient_data": "Patient history and current condition..."
}
}Response:
{
"Mapping": [
{
"no": "1",
"var": "condition_severity",
"supporting_data": "Patient presents with severe symptoms...",
"evaluation": true,
"rationale": "Symptoms meet severity criteria"
}
],
"Final Decision": {
"recommendation": "Approved",
"decision_rationale": "Patient meets all criteria...",
"confidence_score": "95"
}
}POST /api/generate-alternative-care-pathwaySuggests alternative treatment options.
Request:
{
"body": {
"PatientData": "Patient condition and history...",
"requestedProcedure": "97140"
}
}Response:
[
{
"procedure_code": "97110",
"alternative": "Therapeutic Exercise",
"rationale": "Improves flexibility and strength",
"auto_approval": false
}
]POST /api/start-sessionRequest:
{
"body": "Initial context or policy information..."
}Response:
{
"session_id": "uuid-string"
}POST /api/send-messageRequest:
{
"session_id": "uuid-string",
"message": "User query or input..."
}Response:
{
"response": "Assistant's response..."
}GET /healthResponse:
{
"status": "healthy",
"timestamp": "2024-01-01T12:00:00.000Z"
}All endpoints return error responses in this format:
{
"error": "Error description",
"type": "error_type"
}- Handles large responses through chunking
- Maintains context across chunks
- Merges partial responses intelligently
- Maintains conversation context
- Automatic cleanup of old sessions
- Stateful interactions
- Retry mechanism with exponential backoff
- JSON validation and repair
- Detailed error logging
- Context preservation
- Intelligent chunking
- Response validation
- Format verification
-
Response Processing:
- Maximum 5 chunks per response
- Automatic JSON structure repair
- Duplicate detection in merged responses
-
Session Handling:
- 24-hour session timeout
- Hourly cleanup of expired sessions
- Context maintenance across requests
-
Error Recovery:
- 3 retry attempts with exponential backoff
- Partial response recovery
- Context preservation on errors
-
Performance:
- 30-second timeout per request
- Chunked processing for large responses
- Efficient memory management
- Python 3.9 or higher
- Virtual environment (recommended)
- OpenAI API key
- Clone the repository:
git clone [repository-url]
cd [project-directory]- Create and activate virtual environment:
# Windows
python -m venv venv
.\venv\Scripts\activate
# Linux/Mac
python -m venv venv
source venv/bin/activate- Install dependencies:
pip install -r requirements.txt- Create
.envfile:
OPENAI_API_KEY=your_api_key_here- Run the application:
python -m uvicorn app.main:app --reload- Test Policy Encoding:
curl -X POST http://localhost:8000/api/generate-encoding \
-H "Content-Type: application/json" \
-d '{
"body": "Medical Policy Content...",
"max_tokens": 4000,
"temperature": 0.7
}'- Test Claim Review:
curl -X POST http://localhost:8000/api/generate-claim-review \
-H "Content-Type: application/json" \
-d '{
"body": ["Policy Document", "Claim Details"],
"max_tokens": 4000
}'import requests
def test_encoding():
response = requests.post(
"http://localhost:8000/api/generate-encoding",
json={
"body": "Medical Policy Content...",
"max_tokens": 4000
}
)
print(response.json())
def test_session():
# Start session
session_response = requests.post(
"http://localhost:8000/api/start-session",
json={"body": "Initial context..."}
)
session_id = session_response.json()["session_id"]
# Send message
message_response = requests.post(
"http://localhost:8000/api/send-message",
json={
"session_id": session_id,
"message": "Query..."
}
)
print(message_response.json())- Maximum request size: 8000 tokens
- Maximum response chunks: 5
- Session timeout: 24 hours
- Request timeout: 30 seconds
-
Chunk Size Management:
- Default: 4000 tokens
- Adjustable via max_tokens parameter
- Automatic chunking for large responses
-
Session Optimization:
- Automatic context pruning
- Memory efficient storage
- Regular cleanup of inactive sessions
-
Error Recovery:
- Exponential backoff retry
- Partial response recovery
- Context preservation
-
Policy Encoding:
- Keep policy text clear and structured
- Include all relevant sections
- Specify clear criteria boundaries
-
Claim Review:
- Provide complete policy documents
- Include detailed claim information
- Specify all relevant codes
-
Session Management:
- Maintain active sessions
- Clear unused sessions
- Handle timeouts gracefully
-
Client-Side:
- Implement retry logic
- Handle timeout errors
- Validate responses
-
Response Processing:
- Validate JSON structure
- Handle partial responses
- Merge multi-part responses
All successful responses will have HTTP status code 200 and contain:
- Valid JSON data
- Complete response structure
- Required fields based on endpoint
Error responses include:
- HTTP status code (4xx or 5xx)
- Error type identifier
- Detailed error message
- Traceable error ID
-
API Key Management:
- Store securely in .env
- Rotate regularly
- Never expose in code
-
Data Protection:
- No PII storage
- Session data encryption
- Regular session cleanup
-
Access Control:
- Rate limiting
- Session validation
- Request validation
- Connection Errors:
# Check API status
curl http://localhost:8000/health- Token Errors:
- Verify API key in .env
- Check token limits
- Monitor usage
- Response Errors:
- Check request format
- Validate input data
- Review error messages
Enable debug logging:
logging.basicConfig(level=logging.DEBUG)