Spaces:
Sleeping
Sleeping
# gpt_analyzer.py | |
import json | |
from openai import OpenAI | |
from typing import Dict, List, Any | |
class GPTAnalyzer: | |
def __init__(self, api_key: str): | |
print("Initializing GPT Analyzer") | |
self.client = OpenAI(api_key=api_key) | |
def analyze_request(self, request_text: str, available_categories: List[str]) -> Dict[str, Any]: | |
print(f"Analyzing request with available categories: {available_categories}") | |
prompt = f""" | |
As a hospital data analyst, analyze this data request: | |
"{request_text}" | |
Consider these available data sources in hospital Web Data system: | |
{json.dumps(available_categories, indent=2, ensure_ascii=False)} | |
You must return a response that exactly matches this JSON structure. Fields must exactly match the available report fields. DO NOT include any other text in your response except the JSON: | |
{{ | |
"required_reports": [ | |
{{ | |
"category": "OPD", | |
"report_type": "diagnosis", | |
"fields_needed": ["HN", "Patient_Name", "VisitDate", "Doctor_Name", "ICD_Code", "ICD_Name"], | |
"filters": {{ | |
"date_range": "January 2024", | |
"other_filters": [] | |
}} | |
}} | |
], | |
"interpretation": "Brief explanation of what data is needed", | |
"confidence_score": "HIGH/MEDIUM/LOW" | |
}} | |
IMPORTANT: | |
- report_type must match exactly one of the available report names | |
- fields_needed must match exactly the field names in the reports | |
- Return only the JSON, no other text | |
""" | |
try: | |
print("Sending request to GPT") | |
response = self.client.chat.completions.create( | |
messages=[ | |
{ | |
"role": "system", | |
"content": "You are a healthcare data analyst expert who understands hospital information systems. Always return exact matching report names and field names. Return only JSON, no other text." | |
}, | |
{ | |
"role": "user", | |
"content": prompt | |
} | |
], | |
model="gpt-4o-mini", | |
) | |
response_text = response.choices[0].message.content.strip() | |
print(f"GPT Response received: {response_text}") | |
return json.loads(response_text) | |
except json.JSONDecodeError as e: | |
print(f"JSON Parse Error: {str(e)}") | |
return {"error": f"Failed to parse GPT response as JSON: {str(e)}"} | |
except Exception as e: | |
print(f"General Error: {str(e)}") | |
return {"error": str(e)} |