Download backend.py from VAH6002/CBMB: direct link, hf CLI and curl.
- Browser
- Download file 2.1 kB
-
https://huggingface.co/spaces/VAH6002/CBMB/resolve/main/backend.py
- Command line
-
hf download hf://spaces/VAH6002/CBMB/backend.py
-
curl -L -o backend.py https://huggingface.co/spaces/VAH6002/CBMB/resolve/main/backend.py
2.1 kB
| import os | |
| import google.generativeai as genai # type: ignore | |
| import json | |
| import os | |
| from groq import Groq | |
| # Load API Keys from environment variables | |
| GOOGLE_GEMINI_API_KEY = os.getenv("GOOGLE_GEMINI_API_KEY", "AIzaSyCg-nx7szAFMMPfCkBEyP2GHfq74ZJSBd4") | |
| GROQ_API_KEY = os.getenv("GROQ_API_KEY", "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") | |
| genai.configure(api_key=GOOGLE_GEMINI_API_KEY) | |
| # Initialize OpenRouter client | |
| groq_client = Groq(api_key=GROQ_API_KEY) | |
| with open('mobile_accessories_kb.json', 'r') as f: | |
| mobile_accessories_knowledge = json.load(f) | |
| def generate_response(user_query): | |
| """ | |
| Generates a response for the Mobile Accessories Chat-Bot. | |
| """ | |
| prompt = f""" | |
| Query: {user_query} | |
| You are a Mobile Accessories Chat-Bot. Provide helpful and friendly responses about mobile accessories. | |
| Knowledge Base: | |
| Accessories: {json.dumps(mobile_accessories_knowledge['accessories'])} | |
| """ | |
| try: | |
| # Call Gemini API | |
| model = genai.GenerativeModel("gemini-2.5-flash") | |
| response = model.generate_content(prompt) | |
| return response.text | |
| except Exception as e: | |
| print(f"Gemini API failed: {e}. Falling back to Groq.") | |
| if GROQ_API_KEY: | |
| try: | |
| # Fallback to Groq API | |
| response = groq_client.chat.completions.create( | |
| model="mixtral-8x7b-32768", | |
| messages=[{"role": "user", "content": prompt}], | |
| temperature=0.5, | |
| max_tokens=1024, | |
| top_p=1, | |
| stop=None, | |
| stream=False, | |
| ) | |
| return response.choices[0].message.content | |
| except Exception as e_groq: | |
| print(f"Groq API failed: {e_groq}") | |
| return "Sorry, I couldn't generate a response from either API." | |
| else: | |
| return "Sorry, Gemini API failed and Groq API key is not set." | |
| # Test API | |
| if __name__ == "__main__": | |
| query = "What are the best headphones?" | |
| print(generate_response(query)) | |