Spaces:
VAH6002
/
Sleeping

File size: 2,098 Bytes
fb4d941
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
63
64
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))