Icd-cpt-coding-api / src /services /groq_service.py
Distopia22's picture
Fix: Update groq library version and add error handling
c481ed9
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()