File size: 2,367 Bytes
1441b40
 
 
 
 
 
 
 
 
 
 
 
 
c481ed9
 
 
 
 
 
 
 
1441b40
 
 
 
 
 
c481ed9
1441b40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c481ed9
1441b40
 
 
 
 
c481ed9
1441b40
 
c481ed9
1441b40
 
c481ed9
1441b40
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
from groq import Groq
import json
import sys
import os

# Add parent directory to path for imports
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from config.settings import settings
from utils.prompts import SYSTEM_PROMPT, create_user_prompt

class GroqService:
    def __init__(self):
        try:
            print(f"πŸ”§ Initializing Groq client...")
            self.client = Groq(api_key=settings.GROQ_API_KEY)
            self.model_id = settings.MODEL_ID
            print(f"βœ… Groq client initialized successfully with model: {self.model_id}")
        except Exception as e:
            print(f"❌ Failed to initialize Groq client: {str(e)}")
            raise
    
    async def analyze_provider_notes(self, provider_notes: str) -> dict:
        """
        Analyze provider notes and return ICD and CPT codes with explanations
        """
        try:
            print(f"πŸ“ Analyzing provider notes...")
            # Create the chat completion with system and user prompts
            chat_completion = self.client.chat.completions.create(
                messages=[
                    {
                        "role": "system",
                        "content": SYSTEM_PROMPT
                    },
                    {
                        "role": "user",
                        "content": create_user_prompt(provider_notes)
                    }
                ],
                model=self.model_id,
                temperature=0.1,  # Low temperature for consistent, factual outputs
                response_format={"type": "json_object"}  # Force JSON response
            )
            
            # Extract and parse the response
            response_content = chat_completion.choices[0].message.content
            print(f"βœ… Received response from Groq API")
            parsed_response = json.loads(response_content)
            
            return parsed_response
            
        except json.JSONDecodeError as e:
            print(f"❌ JSON parsing error: {str(e)}")
            raise ValueError(f"Failed to parse JSON response from model: {str(e)}")
        except Exception as e:
            print(f"❌ Groq API error: {str(e)}")
            raise Exception(f"Error calling Groq API: {str(e)}")

# Don't initialize here - let it be initialized when imported
groq_service = GroqService()