File size: 2,256 Bytes
2f4af3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62db04d
2f4af3f
 
 
 
 
 
 
 
 
 
 
 
62db04d
 
 
2f4af3f
 
 
62db04d
 
 
 
 
 
 
2f4af3f
 
 
 
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
import os
from config import Config

class GroqClient:
    def __init__(self):
        self.config = Config()
        self.api_key = self.config.GROQ_API_KEY or os.getenv("GROQ_API_KEY")
        self.client = None
        
        if self.api_key:
            try:
                from groq import Groq
                self.client = Groq(api_key=self.api_key)
                print("[INFO] Groq client initialized successfully")
            except ImportError:
                print("[WARN] groq package not installed. Run 'pip install groq'.")
            except Exception as e:
                print(f"[ERROR] Failed to initialize Groq client: {e}")
        else:
            print("[WARN] GROQ_API_KEY not found in configuration or environment.")

    def is_available(self) -> bool:
        """Check if Groq API client is available and configured"""
        return self.client is not None

    def generate_response(self, system_prompt: str, user_prompt: str, max_tokens: int = 1024, response_format = None) -> str:
        """Generate response from Groq LLM"""
        if not self.is_available():
            print("[WARN] GroqClient not available for generating response.")
            return ""

        try:
            # Use stable model name or configured fallback
            model = self.config.GROQ_MODEL
            # Common model fallbacks if config is generic or outdated
            if model == "openai/gpt-oss-120b":
                model = "llama-3.1-8b-instant"  # standard Groq model
                
            params = {
                "model": model,
                "messages": [
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt}
                ],
                "temperature": getattr(self.config, 'GROQ_TEMPERATURE', 0.7),
                "max_completion_tokens": max_tokens,
            }
            if response_format is not None:
                params["response_format"] = response_format
                
            completion = self.client.chat.completions.create(**params)
            return completion.choices[0].message.content
        except Exception as e:
            print(f"[ERROR] Groq API call failed: {e}")
            return ""