chburhan64 commited on
Commit
b32100a
Β·
verified Β·
1 Parent(s): e1f77d2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -84
app.py CHANGED
@@ -12,7 +12,9 @@ import time
12
  import random
13
  from urllib.parse import quote_plus
14
  import os
 
15
  from langchain_openai import ChatOpenAI
 
16
  from langchain_community.tools import DuckDuckGoSearchRun
17
 
18
  # Configuration
@@ -102,92 +104,105 @@ class ShoppingTools:
102
  return f"Error comparing products: {str(e)}"
103
 
104
  def create_agents(api_key=None):
105
- """Create the shopping agent crew using AIML API"""
106
 
107
- # Initialize LLM with AIML API configuration
108
- aiml_api_key = api_key or os.environ.get("AIML_API_KEY")
109
 
110
- if not aiml_api_key:
111
  try:
112
- aiml_api_key = st.secrets.get("AIML_API_KEY")
113
  except:
114
  pass
115
 
116
- if not aiml_api_key or aiml_api_key.strip() == "":
117
  return None, None, None
118
 
119
  # Clean the API key (remove any whitespace)
120
- aiml_api_key = aiml_api_key.strip()
 
 
 
 
 
121
 
122
  try:
123
- # CRITICAL FIX: Set both environment variables for compatibility
124
- os.environ["AIML_API_KEY"] = aiml_api_key
125
- os.environ["OPENAI_API_KEY"] = aiml_api_key # CrewAI/LangChain expects this
126
 
127
- # AIML API models to try (these are available on aimlapi.com)
128
- aiml_models = [
129
- "gpt-4o-mini",
130
- "gpt-4o",
131
- "gpt-4-turbo",
132
- "gpt-3.5-turbo",
133
- "claude-3-5-sonnet-20241022",
134
- "claude-3-haiku-20240307",
135
- "llama-3.1-8b-instruct",
136
- "llama-3.1-70b-instruct",
137
- "mixtral-8x7b-instruct"
138
  ]
139
 
140
  llm = None
141
  successful_model = None
142
 
143
- for model in aiml_models:
144
  try:
145
- st.info(f"πŸ”„ Trying AIML API model: {model}")
146
-
147
- # Create ChatOpenAI client configured for AIML API
148
- llm = ChatOpenAI(
149
- model=model,
150
- openai_api_key=aiml_api_key, # Explicitly pass the API key
151
- openai_api_base="https://api.aimlapi.com/v1", # Use openai_api_base for compatibility
152
  temperature=0.1,
153
- max_tokens=1024,
154
- request_timeout=30
155
  )
156
 
157
  # Test the LLM with a simple prompt
158
  test_response = llm.invoke("Say 'Hello'")
159
  successful_model = model
160
- st.success(f"βœ… Successfully initialized AIML API LLM with model: {model}")
161
  break
162
 
163
  except Exception as model_error:
164
  error_msg = str(model_error)
165
- if "401" in error_msg or "invalid_api_key" in error_msg or "unauthorized" in error_msg:
166
  st.error(f"❌ API Key Error: {error_msg}")
167
- st.error("Please check your AIML API key at https://aimlapi.com/app/keys")
168
  return None, None, None
169
  elif "404" in error_msg or "model_not_found" in error_msg:
170
  st.warning(f"⚠️ Model {model} not available, trying next...")
171
  continue
172
- elif "rate_limit" in error_msg:
173
- st.warning(f"⚠️ Rate limit for model {model}, trying next...")
174
- continue
175
  else:
176
  st.warning(f"⚠️ Error with model {model}: {error_msg}")
177
  continue
178
 
179
  if llm is None:
180
- st.error("❌ Failed to initialize any AIML API model. Please check your API key and try again.")
181
  return None, None, None
182
 
183
- st.success(f"πŸŽ‰ Using model: {successful_model}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
  except Exception as e:
186
  error_msg = str(e)
187
- if "401" in error_msg or "invalid_api_key" in error_msg or "unauthorized" in error_msg:
188
- st.error("❌ Invalid AIML API Key. Please check your key at https://aimlapi.com/app/keys")
189
  else:
190
- st.error(f"❌ Error initializing AIML API: {error_msg}")
191
  return None, None, None
192
 
193
  # Product Search Agent
@@ -196,7 +211,7 @@ def create_agents(api_key=None):
196
  goal="Search for products based on user queries and find relevant options",
197
  backstory="You are an expert at finding products online. You know how to search effectively and find the most relevant products for users.",
198
  tools=[ShoppingTools.search_products],
199
- llm=llm,
200
  verbose=True,
201
  allow_delegation=False
202
  )
@@ -207,7 +222,7 @@ def create_agents(api_key=None):
207
  goal="Extract and analyze product information including prices, specifications, and ratings",
208
  backstory="You are a meticulous analyst who can extract structured information from unstructured data and identify key product features.",
209
  tools=[ShoppingTools.extract_product_info],
210
- llm=llm,
211
  verbose=True,
212
  allow_delegation=False
213
  )
@@ -218,7 +233,7 @@ def create_agents(api_key=None):
218
  goal="Compare products and recommend the best options based on various criteria",
219
  backstory="You are an expert at comparing products and providing recommendations. You consider price, quality, ratings, and features to make the best suggestions.",
220
  tools=[ShoppingTools.compare_products],
221
- llm=llm,
222
  verbose=True,
223
  allow_delegation=False
224
  )
@@ -379,46 +394,36 @@ def main():
379
  # Header
380
  st.title("πŸ›’ Smart Shopping Agent")
381
  st.markdown("### AI-Powered Product Search, Comparison & Recommendation System")
382
- st.markdown("**Now powered by AIML API with 300+ AI models!**")
383
 
384
  # Sidebar for configuration
385
  with st.sidebar:
386
  st.header("βš™οΈ Configuration")
387
 
388
  # API Key input
389
- aiml_api_key = st.text_input("AIML API Key", type="password", help="Enter your AIML API key for LLM access")
390
 
391
  # Demo mode toggle
392
  demo_mode = st.checkbox("Demo Mode", value=True, help="Use mock data for demonstration")
393
 
394
  # Add instructions for getting API key
395
  st.markdown("---")
396
- st.markdown("**πŸ”‘ Get Your AIML API Key:**")
397
- st.markdown("1. Visit [aimlapi.com](https://aimlapi.com/)")
398
- st.markdown("2. Sign up for an account")
399
- st.markdown("3. Go to [API Keys](https://aimlapi.com/app/keys)")
400
- st.markdown("4. Generate a new API key")
401
- st.markdown("5. Copy and paste it above")
402
 
403
  # Add API key validation info
404
  st.markdown("---")
405
- st.markdown("**πŸ” API Key Status:**")
406
- if aiml_api_key:
407
- if len(aiml_api_key.strip()) > 10: # Basic length check
408
- st.success("βœ… API key provided")
409
  else:
410
- st.error("❌ API key too short")
411
  else:
412
- st.info("πŸ’‘ Enter your API key above")
413
-
414
- # Add model info
415
- st.markdown("---")
416
- st.markdown("**πŸ€– Available Models:**")
417
- st.markdown("- GPT-4o, GPT-4 Turbo")
418
- st.markdown("- Claude 3.5 Sonnet, Claude 3 Haiku")
419
- st.markdown("- Llama 3.1 (8B, 70B)")
420
- st.markdown("- Mixtral 8x7B")
421
- st.markdown("- And 290+ more models!")
422
 
423
  st.markdown("---")
424
  st.markdown("**How to use:**")
@@ -427,8 +432,8 @@ def main():
427
  st.markdown("3. View comparison and recommendations")
428
 
429
  st.markdown("---")
430
- st.markdown("**Powered by:**")
431
- st.markdown("- AIML API (300+ models)")
432
  st.markdown("- DuckDuckGo Search")
433
  st.markdown("- CrewAI Framework")
434
  st.markdown("- Streamlit")
@@ -457,14 +462,14 @@ def main():
457
 
458
  else:
459
  # Check if API key is provided
460
- if not aiml_api_key:
461
- st.error("Please enter your AIML API key in the sidebar to use AI agents, or enable Demo Mode.")
462
- st.info("You can get a free API key from [aimlapi.com](https://aimlapi.com/app/keys)")
463
  return
464
 
465
- # Use real CrewAI agents with AIML API
466
  try:
467
- agents = create_agents(aiml_api_key)
468
  if not all(agents):
469
  st.error("Failed to initialize AI agents. Please check your API key.")
470
  st.info("Falling back to demo mode...")
@@ -490,8 +495,6 @@ def main():
490
  st.session_state.search_results = products
491
  st.session_state.comparison_data = comparison_data
492
  except:
493
- # If JSON parsing fails, use mock data
494
- st.warning("Could not parse AI response, using mock data")
495
  st.session_state.search_results = mock_search_results(product_query)
496
  st.session_state.comparison_data = st.session_state.search_results
497
 
@@ -538,13 +541,6 @@ def main():
538
  file_name=f"{product_query.replace(' ', '_')}_comparison.json",
539
  mime="application/json"
540
  )
541
-
542
- # Footer
543
- st.markdown("---")
544
- st.markdown("**πŸ’‘ Pro Tips:**")
545
- st.markdown("- Be specific in your search queries (e.g., 'wireless noise-cancelling headphones under $200')")
546
- st.markdown("- Try different models if one doesn't work well")
547
- st.markdown("- Use demo mode to test the interface before adding your API key")
548
 
549
  if __name__ == "__main__":
550
  main()
 
12
  import random
13
  from urllib.parse import quote_plus
14
  import os
15
+ from langchain_groq import ChatGroq
16
  from langchain_openai import ChatOpenAI
17
+ from langchain_community.llms import Ollama
18
  from langchain_community.tools import DuckDuckGoSearchRun
19
 
20
  # Configuration
 
104
  return f"Error comparing products: {str(e)}"
105
 
106
  def create_agents(api_key=None):
107
+ """Create the shopping agent crew"""
108
 
109
+ # Initialize LLM with proper configuration for CrewAI
110
+ groq_api_key = api_key or os.environ.get("GROQ_API_KEY")
111
 
112
+ if not groq_api_key:
113
  try:
114
+ groq_api_key = st.secrets.get("GROQ_API_KEY")
115
  except:
116
  pass
117
 
118
+ if not groq_api_key or groq_api_key.strip() == "" or groq_api_key == "your-groq-api-key-here":
119
  return None, None, None
120
 
121
  # Clean the API key (remove any whitespace)
122
+ groq_api_key = groq_api_key.strip()
123
+
124
+ # Validate API key format (Groq keys typically start with gsk_)
125
+ if not groq_api_key.startswith('gsk_'):
126
+ st.error("⚠️ Invalid Groq API key format. Groq API keys should start with 'gsk_'")
127
+ return None, None, None
128
 
129
  try:
130
+ # Set environment variable for CrewAI
131
+ os.environ["GROQ_API_KEY"] = groq_api_key
 
132
 
133
+ # Try different Groq models with proper provider prefix for CrewAI
134
+ groq_models = [
135
+ "groq/llama3-8b-8192",
136
+ "groq/llama-3.1-8b-instant",
137
+ "groq/mixtral-8x7b-32768",
138
+ "groq/llama3-70b-8192",
139
+ "groq/gemma-7b-it"
 
 
 
 
140
  ]
141
 
142
  llm = None
143
  successful_model = None
144
 
145
+ for model in groq_models:
146
  try:
147
+ st.info(f"πŸ”„ Trying Groq model: {model}")
148
+ llm = ChatGroq(
149
+ model=model.replace("groq/", ""), # Remove prefix for ChatGroq
150
+ api_key=groq_api_key,
 
 
 
151
  temperature=0.1,
152
+ max_tokens=1024
 
153
  )
154
 
155
  # Test the LLM with a simple prompt
156
  test_response = llm.invoke("Say 'Hello'")
157
  successful_model = model
158
+ st.success(f"βœ… Successfully initialized Groq LLM with model: {model}")
159
  break
160
 
161
  except Exception as model_error:
162
  error_msg = str(model_error)
163
+ if "401" in error_msg or "invalid_api_key" in error_msg:
164
  st.error(f"❌ API Key Error: {error_msg}")
165
+ st.error("Please check your Groq API key at https://console.groq.com/")
166
  return None, None, None
167
  elif "404" in error_msg or "model_not_found" in error_msg:
168
  st.warning(f"⚠️ Model {model} not available, trying next...")
169
  continue
 
 
 
170
  else:
171
  st.warning(f"⚠️ Error with model {model}: {error_msg}")
172
  continue
173
 
174
  if llm is None:
175
+ st.error("❌ Failed to initialize any Groq model. Please check your API key and try again.")
176
  return None, None, None
177
 
178
+ # For CrewAI, we need to specify the model with provider prefix
179
+ # Create a wrapper that uses the correct model name for CrewAI
180
+ class CrewAIGroqLLM:
181
+ def __init__(self, model, api_key):
182
+ self.model = model
183
+ self.api_key = api_key
184
+ self.llm = ChatGroq(
185
+ model=model.replace("groq/", ""),
186
+ api_key=api_key,
187
+ temperature=0.1,
188
+ max_tokens=1024
189
+ )
190
+
191
+ def invoke(self, prompt):
192
+ return self.llm.invoke(prompt)
193
+
194
+ def __call__(self, prompt):
195
+ return self.llm.invoke(prompt)
196
+
197
+ # Use the successful model
198
+ crewai_llm = CrewAIGroqLLM(successful_model, groq_api_key)
199
 
200
  except Exception as e:
201
  error_msg = str(e)
202
+ if "401" in error_msg or "invalid_api_key" in error_msg:
203
+ st.error("❌ Invalid Groq API Key. Please check your key at https://console.groq.com/")
204
  else:
205
+ st.error(f"❌ Error initializing Groq: {error_msg}")
206
  return None, None, None
207
 
208
  # Product Search Agent
 
211
  goal="Search for products based on user queries and find relevant options",
212
  backstory="You are an expert at finding products online. You know how to search effectively and find the most relevant products for users.",
213
  tools=[ShoppingTools.search_products],
214
+ llm=crewai_llm,
215
  verbose=True,
216
  allow_delegation=False
217
  )
 
222
  goal="Extract and analyze product information including prices, specifications, and ratings",
223
  backstory="You are a meticulous analyst who can extract structured information from unstructured data and identify key product features.",
224
  tools=[ShoppingTools.extract_product_info],
225
+ llm=crewai_llm,
226
  verbose=True,
227
  allow_delegation=False
228
  )
 
233
  goal="Compare products and recommend the best options based on various criteria",
234
  backstory="You are an expert at comparing products and providing recommendations. You consider price, quality, ratings, and features to make the best suggestions.",
235
  tools=[ShoppingTools.compare_products],
236
+ llm=crewai_llm,
237
  verbose=True,
238
  allow_delegation=False
239
  )
 
394
  # Header
395
  st.title("πŸ›’ Smart Shopping Agent")
396
  st.markdown("### AI-Powered Product Search, Comparison & Recommendation System")
 
397
 
398
  # Sidebar for configuration
399
  with st.sidebar:
400
  st.header("βš™οΈ Configuration")
401
 
402
  # API Key input
403
+ groq_api_key = st.text_input("Groq API Key", type="password", help="Enter your Groq API key for LLM access")
404
 
405
  # Demo mode toggle
406
  demo_mode = st.checkbox("Demo Mode", value=True, help="Use mock data for demonstration")
407
 
408
  # Add instructions for getting API key
409
  st.markdown("---")
410
+ st.markdown("**πŸ”‘ Get Free Groq API Key:**")
411
+ st.markdown("1. Visit [console.groq.com](https://console.groq.com/)")
412
+ st.markdown("2. Sign up for free")
413
+ st.markdown("3. Generate API key")
414
+ st.markdown("4. Copy the key (starts with 'gsk_')")
415
+ st.markdown("5. Paste it above")
416
 
417
  # Add API key validation info
418
  st.markdown("---")
419
+ st.markdown("**πŸ” API Key Validation:**")
420
+ if groq_api_key:
421
+ if groq_api_key.strip().startswith('gsk_'):
422
+ st.success("βœ… API key format looks correct")
423
  else:
424
+ st.error("❌ Invalid format. Groq keys start with 'gsk_'")
425
  else:
426
+ st.info("πŸ’‘ Enter your API key above to validate")
 
 
 
 
 
 
 
 
 
427
 
428
  st.markdown("---")
429
  st.markdown("**How to use:**")
 
432
  st.markdown("3. View comparison and recommendations")
433
 
434
  st.markdown("---")
435
+ st.markdown("**Free Resources Used:**")
436
+ st.markdown("- Groq LLM (Free tier)")
437
  st.markdown("- DuckDuckGo Search")
438
  st.markdown("- CrewAI Framework")
439
  st.markdown("- Streamlit")
 
462
 
463
  else:
464
  # Check if API key is provided
465
+ if not groq_api_key:
466
+ st.error("Please enter your Groq API key in the sidebar to use AI agents, or enable Demo Mode.")
467
+ st.info("You can get a free API key from [console.groq.com](https://console.groq.com/)")
468
  return
469
 
470
+ # Use real CrewAI agents
471
  try:
472
+ agents = create_agents(groq_api_key)
473
  if not all(agents):
474
  st.error("Failed to initialize AI agents. Please check your API key.")
475
  st.info("Falling back to demo mode...")
 
495
  st.session_state.search_results = products
496
  st.session_state.comparison_data = comparison_data
497
  except:
 
 
498
  st.session_state.search_results = mock_search_results(product_query)
499
  st.session_state.comparison_data = st.session_state.search_results
500
 
 
541
  file_name=f"{product_query.replace(' ', '_')}_comparison.json",
542
  mime="application/json"
543
  )
 
 
 
 
 
 
 
544
 
545
  if __name__ == "__main__":
546
  main()