Aditya commited on
Commit
594b780
·
1 Parent(s): 3f1169d

Fix: Update API key handling for HF Spaces environment variables

Browse files

- Modified app.py to properly read GROQ_API_KEY from environment variables
- Updated classifier.py with better error handling and logging
- Added fallback for both HF Spaces and local development
- Improved user-friendly error messages with setup instructions
- Switch to llama-3.1-70b-versatile model for better reliability

Files changed (2) hide show
  1. app.py +43 -25
  2. classifier.py +14 -6
app.py CHANGED
@@ -22,32 +22,50 @@ load_dotenv()
22
  logging.basicConfig(level=logging.INFO)
23
  logger = logging.getLogger(__name__)
24
 
25
- try:
26
- # Try Streamlit Cloud secrets first, then fall back to .env
27
- if hasattr(st, 'secrets') and 'GROQ_API_KEY' in st.secrets:
28
- os.environ['GROQ_API_KEY'] = st.secrets['GROQ_API_KEY']
29
- st.success("🔑 API key loaded from Streamlit Cloud secrets")
30
- elif 'GROQ_API_KEY' not in os.environ:
31
- st.error("⚠️ GROQ_API_KEY not found!")
32
- st.info("**For Streamlit Cloud deployment:**")
33
- st.info("Add your API key in the Streamlit Cloud app settings > Secrets tab")
34
- st.code("""
35
- # In Streamlit Cloud Secrets:
36
- GROQ_API_KEY = "your_groq_api_key_here"
37
- """)
38
- st.info("**For local development:**")
39
- st.info("Add GROQ_API_KEY to your .env file")
40
- st.code("""
41
- # In .env file:
42
- GROQ_API_KEY=your_groq_api_key_here
43
- """)
44
- st.stop()
45
- else:
46
- st.success("🔑 API key loaded from environment")
47
- except Exception as e:
48
- st.error(f"⚠️ Error accessing API key: {e}")
49
- st.error("Please check your configuration")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  st.stop()
 
 
 
 
51
 
52
  try:
53
  from models import Ticket, TicketClassification, TopicTagEnum, SentimentEnum, PriorityEnum
 
22
  logging.basicConfig(level=logging.INFO)
23
  logger = logging.getLogger(__name__)
24
 
25
+ # Function to get API key from multiple sources
26
+ def get_groq_api_key():
27
+ """Get GROQ API key from environment variables or Streamlit secrets"""
28
+ # Try environment variable first (HF Spaces and Docker way)
29
+ api_key = os.getenv('GROQ_API_KEY')
30
+ if api_key:
31
+ return api_key
32
+
33
+ # Try Streamlit secrets as fallback (for Streamlit Cloud)
34
+ try:
35
+ if hasattr(st, 'secrets') and 'GROQ_API_KEY' in st.secrets:
36
+ return st.secrets['GROQ_API_KEY']
37
+ except Exception as e:
38
+ logger.warning(f"Could not access Streamlit secrets: {e}")
39
+
40
+ return None
41
+
42
+ # Check API key availability
43
+ groq_api_key = get_groq_api_key()
44
+
45
+ if not groq_api_key:
46
+ st.error("🚨 **GROQ API Key Missing!**")
47
+ st.markdown("""
48
+ ### Please add your GROQ API key:
49
+
50
+ **For Hugging Face Spaces:**
51
+ 1. Go to your Space settings tab
52
+ 2. Scroll to "Repository secrets"
53
+ 3. Add secret: `GROQ_API_KEY` = `your_actual_key`
54
+ 4. Restart the space
55
+
56
+ **For local development:**
57
+ Add to `.streamlit/secrets.toml`:
58
+ ```toml
59
+ GROQ_API_KEY = "your_groq_api_key_here"
60
+ ```
61
+
62
+ **Get your API key:** https://console.groq.com/keys
63
+ """)
64
  st.stop()
65
+ else:
66
+ # Set the API key in environment for other modules
67
+ os.environ['GROQ_API_KEY'] = groq_api_key
68
+ st.success("🔑 API key loaded successfully")
69
 
70
  try:
71
  from models import Ticket, TicketClassification, TopicTagEnum, SentimentEnum, PriorityEnum
classifier.py CHANGED
@@ -10,15 +10,23 @@ logger = logging.getLogger(__name__)
10
 
11
  class TicketClassifier:
12
  def __init__(self):
 
13
  api_key = os.getenv("GROQ_API_KEY")
14
  if not api_key:
15
- raise ValueError("GROQ_API_KEY environment variable is required")
 
16
 
17
- self.client = Groq(api_key=api_key)
18
- self.models = [
19
- "moonshotai/kimi-k2-instruct"
20
- ]
21
- self.model = "moonshotai/kimi-k2-instruct"
 
 
 
 
 
 
22
 
23
  def _create_classification_prompt(self, ticket: Ticket) -> str:
24
 
 
10
 
11
  class TicketClassifier:
12
  def __init__(self):
13
+ # Get API key from environment
14
  api_key = os.getenv("GROQ_API_KEY")
15
  if not api_key:
16
+ logger.error("GROQ_API_KEY environment variable not found")
17
+ raise ValueError("GROQ_API_KEY environment variable is required. Please set it in your HF Spaces secrets or local environment.")
18
 
19
+ try:
20
+ self.client = Groq(api_key=api_key)
21
+ # Use the more reliable model for classification
22
+ self.models = [
23
+ "llama-3.1-70b-versatile"
24
+ ]
25
+ self.model = "llama-3.1-70b-versatile"
26
+ logger.info("TicketClassifier initialized successfully with Groq client")
27
+ except Exception as e:
28
+ logger.error(f"Failed to initialize Groq client: {e}")
29
+ raise
30
 
31
  def _create_classification_prompt(self, ticket: Ticket) -> str:
32