Spaces:
Sleeping

File size: 7,155 Bytes
88fd288
 
 
 
 
c2da8e7
 
88fd288
 
 
 
 
 
e062689
88fd288
69ae982
 
 
 
 
88fd288
 
 
4484e32
88fd288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e062689
88fd288
e062689
88fd288
e062689
88fd288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2da8e7
 
88fd288
0c9151c
4484e32
 
 
 
88fd288
 
 
 
 
 
 
 
 
 
 
 
 
 
c2da8e7
88fd288
 
 
 
e062689
88fd288
 
c2da8e7
88fd288
 
 
 
4484e32
 
 
 
 
 
 
 
 
e062689
88fd288
c2da8e7
4484e32
c2da8e7
 
88fd288
 
e062689
88fd288
 
 
 
4484e32
88fd288
 
c2da8e7
 
 
 
 
 
 
 
88fd288
c2da8e7
 
 
 
 
 
 
88fd288
c2da8e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4484e32
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import os
import json
from uuid import uuid4
from groq import Groq
from langchain_core.documents import Document

# CHANGED: Replaced HuggingFaceEndpointEmbeddings with HuggingFaceEmbeddings for local inference
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_chroma import Chroma
from dotenv import load_dotenv
import random
import shutil
from optimized_quiz import OPTIMIZED_QUESTIONS
from chat_resources import *

# Load main env
load_dotenv(dotenv_path=".env")

# Load secrets env (this can override duplicates from .env)
load_dotenv(dotenv_path=".secrets.env", override=True)

# Config
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
DATA_PATH = "data.json"
CHROMA_PATH = "chroma_db"

TEMPERATURE = float(os.getenv("G_TEMPERATURE", 0.7))
MAX_TOKENS = int(os.getenv("G_MAX_TOKENS", 400))
RETRIEVE_K = int(os.getenv("G_RETRIEVE_K", 3))
TOP_P = float(os.getenv("G_TOP_P", 1.0))
MAX_CONVERSATION_HISTORY = int(os.getenv("G_MAX_CONVERSATION_HISTORY", 5))
MMR = str(os.getenv("MMR", "mmr"))
G_FETCH_K = int(os.getenv("G_FETCH_K", 20))
LAMBDA_MULT = float(os.getenv("LAMBDA_MULT", 0.5))


class GroqClient:
    def __init__(self):

        self.documents = self.load_json_data(DATA_PATH)
        if not self.documents:
            raise RuntimeError("No data loaded")

        self.vector_store = self.init_vector_store(self.documents)

        self.retriever = self.vector_store.as_retriever(
            search_type=MMR,  # Use Maximal Marginal Relevance
            search_kwargs={
                "k": RETRIEVE_K,  # Final number of docs to return
                "fetch_k": G_FETCH_K,  # Number of docs to initially fetch before filtering for diversity
                "lambda_mult": LAMBDA_MULT,  # Balance between relevance (1.0) and diversity (0.0)
            },
        )

        if not GROQ_API_KEY:
            raise RuntimeError("GROQ_API_KEY not found in environment")

        self.client = Groq(api_key=GROQ_API_KEY)

        self.SYSTEM_MESSSAGE = SYSTEM_MESSSAGE

        self.PROMPT_TEMPLATE = PROMPT_TEMPLATE

        self.BLACKLIST = BLACKLIST

    def load_json_data(self, path):
        try:
            with open(path, "r", encoding="utf-8") as f:
                data = json.load(f)

            documents = []

            if "qa" in data:
                for item in data["qa"]:
                    text = f"Q: {item['question']}\nA: {item['answer']}"
                    documents.append(
                        Document(
                            page_content=text,
                            metadata={
                                "id": item.get("id", str(uuid4())),
                                "category": item.get("category", "QA"),
                            },
                        )
                    )

            if "chunks" in data:
                for item in data["chunks"]:
                    documents.append(
                        Document(
                            page_content=item["chunk"],
                            metadata={
                                "id": item.get("id", str(uuid4())),
                                "category": "Chunk",
                            },
                        )
                    )

            return documents

        except Exception as e:
            print(f"Error loading JSON data: {e}")
            return []

    def init_vector_store(self, documents):
        # CHANGED: Replaced online HuggingFaceEndpointEmbeddings with local HuggingFaceEmbeddings
        # This downloads and stores the embedding model locally, eliminating API dependency
        embeddings_model = HuggingFaceEmbeddings(
            model_name="sentence-transformers/all-MiniLM-L6-v2",
            model_kwargs={"device": "cpu"},  # Force CPU usage to avoid GPU conflicts
            encode_kwargs={
                "normalize_embeddings": True
            },  # Normalize embeddings for better similarity search
        )

        # Clear old data to avoid duplicates
        if os.path.exists(CHROMA_PATH):
            shutil.rmtree(CHROMA_PATH)

        uuids = [str(uuid4()) for _ in documents]

        vector_store = Chroma(
            collection_name="user_data",
            embedding_function=embeddings_model,
            persist_directory=CHROMA_PATH,
        )

        # CHANGED: This now processes embeddings locally instead of making API calls
        vector_store.add_documents(documents=documents, ids=uuids)
        return vector_store

    def handle_unknown_query(self):
        return random.choice(FALLBACK_RESPONSES)

    def get_next_questions(self):
        return random.sample(OPTIMIZED_QUESTIONS, 3)

    # ---------------MAIN-----------------

    def ask(self, raw_query: str) -> str:
        if (
            not raw_query
            or raw_query is None
            or raw_query == ""
            or len(raw_query) > 1000
        ):
            return "Please provide a valid query under 1,000 characters."

        if raw_query.lower() in GREETINGS_TRIGGERS:
            return random.choice(GREETINGS)

        try:
            docs = self.retriever.invoke(raw_query)
        except Exception as e:
            return f"Error retrieving documents: {e}"

        if not docs:
            return self.handle_unknown_query()

        context = "\n".join([d.page_content for d in docs])
        fallback = self.handle_unknown_query()
        prompt = self.PROMPT_TEMPLATE.format(
            context=context, question=raw_query, fallback_response=fallback
        )

        messages = [
            {
                "role": "system",
                "content": self.SYSTEM_MESSSAGE,
            },
        ] + [
            {"role": "user", "content": prompt},
        ]

        # Try multiple models with fallback
        # Add fallback models if compound models fail
        models_to_try = [
            "compound-beta-mini",
            "llama-3.1-8b-instant",
            "gemma2-9b-it",
        ]

        random.shuffle(models_to_try)

        for model in models_to_try:
            try:
                completion = self.client.chat.completions.create(
                    model=model,
                    messages=messages,
                    temperature=TEMPERATURE,
                    max_completion_tokens=MAX_TOKENS,
                    top_p=TOP_P,
                    stream=False,
                )
                response = completion.choices[0].message.content
                if response and response.strip():
                    return response.strip()
                else:
                    continue  # Try next model

            except Exception as e:
                # Check if it's a rate limit error
                if "rate_limit_exceeded" in str(e) or "429" in str(e):
                    print(f"Rate limit hit for model {model}, trying fallback...")
                    continue
                else:
                    # For other errors, return immediately
                    return f"Error while calling LLM: {e}"

        # If all models fail
        return "I'm temporarily experiencing high demand. Please try again in a few minutes or rephrase your question."