akshat1409 commited on
Commit
3fda415
Β·
verified Β·
1 Parent(s): a0359dd

Upload rag_chain.py

Browse files
Files changed (1) hide show
  1. rag_chain.py +195 -128
rag_chain.py CHANGED
@@ -1,128 +1,195 @@
1
- """
2
- rag_chain.py
3
- ------------
4
- Core RAG (Retrieval-Augmented Generation) pipeline.
5
- Loaded once at startup by main.py β€” all objects are module-level singletons.
6
-
7
- Flow:
8
- User question
9
- β†’ embed with sentence-transformers
10
- β†’ query ChromaDB for top-5 similar Q&As
11
- β†’ build prompt with those Q&As as context
12
- β†’ call Groq LLaMA-3.3-70b
13
- β†’ return grounded answer
14
- """
15
-
16
- import os
17
- import chromadb
18
- from chromadb.config import Settings
19
- from sentence_transformers import SentenceTransformer
20
- from groq import Groq
21
- from dotenv import load_dotenv
22
-
23
- load_dotenv()
24
-
25
- # ─── Config ──────────────────────────────────────────────────────────────────
26
- CHROMA_PATH = os.getenv("CHROMA_PATH", "chroma_db")
27
- COLLECTION = "python_qa"
28
- MODEL_NAME = "all-MiniLM-L6-v2"
29
- GROQ_MODEL = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
30
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
31
- TOP_K = 5 # How many SO Q&As to retrieve as context
32
-
33
- if not GROQ_API_KEY:
34
- raise EnvironmentError("❌ GROQ_API_KEY not set. Add it to your .env file.")
35
-
36
- # ─── Load once at module import (not per-request!) ───────────────────────────
37
- print(f"πŸ€– Loading embedding model '{MODEL_NAME}'...")
38
- _embedder = SentenceTransformer(MODEL_NAME)
39
-
40
- print(f"Connecting to ChromaDB at '{CHROMA_PATH}'...")
41
- _chroma_client = chromadb.PersistentClient(
42
- path=CHROMA_PATH,
43
- settings=Settings(anonymized_telemetry=False)
44
- )
45
- _collection = _chroma_client.get_collection(COLLECTION)
46
- print(f" βœ… {_collection.count():,} documents in index")
47
-
48
- print(f"⚑ Initializing Groq client (model: {GROQ_MODEL})...")
49
- _groq = Groq(api_key=GROQ_API_KEY)
50
-
51
- # ─── System prompt ───────────────────────────────────────────────────────────
52
- _SYSTEM_PROMPT = """You are an expert Python programming assistant powered by real Stack Overflow data.
53
-
54
- Rules:
55
- 1. Answer ONLY based on the Stack Overflow context provided below.
56
- 2. If the context does not fully cover the question, say so briefly, then answer from your knowledge.
57
- 3. Always include working code examples in Python using markdown code blocks (```python ... ```).
58
- 4. Be concise but complete β€” avoid unnecessary padding.
59
- 5. If multiple approaches exist, list them with trade-offs.
60
- """
61
-
62
- # ─── Main function called by FastAPI ─────────────────────────────────────────
63
- def get_answer(question: str) -> dict:
64
- """
65
- Parameters
66
- ----------
67
- question : str β€” The user's Python question
68
-
69
- Returns
70
- -------
71
- dict with keys: question, answer, sources, model, docs_retrieved
72
- """
73
- # 1️⃣ Embed the question
74
- query_vec = _embedder.encode(question).tolist()
75
-
76
- # 2️⃣ Retrieve top-K similar Q&As from vector DB
77
- results = _collection.query(
78
- query_embeddings=[query_vec],
79
- n_results=TOP_K,
80
- include=["documents", "metadatas", "distances"],
81
- )
82
-
83
- docs = results["documents"][0]
84
- metas = results["metadatas"][0]
85
- distances = results["distances"][0]
86
-
87
- # 3️⃣ Build context block from retrieved docs
88
- context_parts = []
89
- source_titles = []
90
- for i, (doc, meta, dist) in enumerate(zip(docs, metas, distances), 1):
91
- title = meta.get("title", "Unknown")
92
- score = meta.get("question_score", 0)
93
- context_parts.append(
94
- f"--- Stack Overflow Result {i} ---\n"
95
- f"Title: {title} (votes: {score})\n"
96
- f"Relevance: {(1 - dist) * 100:.1f}%\n\n"
97
- f"{doc}"
98
- )
99
- source_titles.append(title)
100
-
101
- context_str = "\n\n".join(context_parts)
102
-
103
- # 4️⃣ Build prompt and call Groq
104
- user_message = (
105
- f"Python Question: {question}\n\n"
106
- f"Stack Overflow Context:\n{context_str}\n\n"
107
- f"Please answer the question based on the context above."
108
- )
109
-
110
- response = _groq.chat.completions.create(
111
- model=GROQ_MODEL,
112
- messages=[
113
- {"role": "system", "content": _SYSTEM_PROMPT},
114
- {"role": "user", "content": user_message},
115
- ],
116
- temperature=0.1, # low temp = more factual, deterministic
117
- max_tokens=1024,
118
- )
119
-
120
- answer = response.choices[0].message.content
121
-
122
- return {
123
- "question": question,
124
- "answer": answer,
125
- "sources": source_titles,
126
- "model": GROQ_MODEL,
127
- "docs_retrieved": TOP_K,
128
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ rag_chain.py
3
+ ------------
4
+ Core RAG (Retrieval-Augmented Generation) pipeline.
5
+ Loaded once at startup by main.py β€” all objects are module-level singletons.
6
+
7
+ Flow:
8
+ User question
9
+ β†’ embed with sentence-transformers
10
+ β†’ query ChromaDB for top-5 similar Q&As
11
+ β†’ build prompt with those Q&As as context
12
+ β†’ call Groq LLaMA-3.3-70b
13
+ β†’ return grounded answer
14
+ """
15
+
16
+ import os
17
+ import chromadb
18
+ from chromadb.config import Settings
19
+ from sentence_transformers import SentenceTransformer
20
+ from groq import Groq
21
+ from dotenv import load_dotenv
22
+
23
+ load_dotenv()
24
+
25
+ # ─── Config ──────────────────────────────────────────────────────────────────
26
+ CHROMA_PATH = os.getenv("CHROMA_PATH", "chroma_db")
27
+ COLLECTION = "python_qa"
28
+ MODEL_NAME = "all-MiniLM-L6-v2"
29
+ PRIMARY_GROQ_MODEL = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
30
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
31
+ TOP_K = 5 # How many SO Q&As to retrieve as context
32
+
33
+ # Candidate fallback models if configured model is unavailable or deprecated
34
+ CANDIDATE_MODELS = [
35
+ PRIMARY_GROQ_MODEL,
36
+ "llama-3.3-70b-versatile",
37
+ "llama-3.1-8b-instant",
38
+ "llama-3.2-11b-vision-preview",
39
+ "llama-3.2-90b-vision-preview",
40
+ "llama3-70b-8192",
41
+ "llama3-8b-8192",
42
+ "mixtral-8x7b-32768",
43
+ "gemma2-9b-it",
44
+ ]
45
+ FALLBACK_MODELS = list(dict.fromkeys([m for m in CANDIDATE_MODELS if m]))
46
+
47
+ if not GROQ_API_KEY:
48
+ raise EnvironmentError("❌ GROQ_API_KEY not set. Add it to your .env file.")
49
+
50
+ # ─── Load once at module import (not per-request!) ───────────────────────────
51
+ print(f"πŸ€– Loading embedding model '{MODEL_NAME}'...")
52
+ _embedder = SentenceTransformer(MODEL_NAME)
53
+
54
+ print(f"Connecting to ChromaDB at '{CHROMA_PATH}'...")
55
+ _chroma_client = chromadb.PersistentClient(
56
+ path=CHROMA_PATH,
57
+ settings=Settings(anonymized_telemetry=False)
58
+ )
59
+ _collection = _chroma_client.get_collection(COLLECTION)
60
+ print(f" βœ… {_collection.count():,} documents in index")
61
+
62
+ print(f"⚑ Initializing Groq client...")
63
+ _groq = Groq(api_key=GROQ_API_KEY)
64
+
65
+ # Dynamically discover active models if API allows
66
+ _active_models = []
67
+ try:
68
+ models_resp = _groq.models.list()
69
+ _active_models = [m.id for m in models_resp.data if hasattr(m, 'id')]
70
+ print(f" Found {len(_active_models)} available Groq models: {_active_models}")
71
+ except Exception as e:
72
+ print(f" ⚠️ Could not fetch Groq model list dynamically: {e}")
73
+
74
+ # Determine starting model
75
+ if PRIMARY_GROQ_MODEL in _active_models:
76
+ GROQ_MODEL = PRIMARY_GROQ_MODEL
77
+ elif _active_models:
78
+ preferred = [m for m in _active_models if any(k in m.lower() for k in ["llama", "mixtral", "gemma"])]
79
+ GROQ_MODEL = preferred[0] if preferred else _active_models[0]
80
+ print(f" ⚠️ Model '{PRIMARY_GROQ_MODEL}' not in active list. Using '{GROQ_MODEL}'.")
81
+ else:
82
+ GROQ_MODEL = PRIMARY_GROQ_MODEL
83
+
84
+ print(f" βœ… Primary model set to: {GROQ_MODEL}")
85
+
86
+ # ─── System prompt ───────────────────────────────────────────────────────────
87
+ _SYSTEM_PROMPT = """You are an expert Python programming assistant powered by real Stack Overflow data.
88
+
89
+ Rules:
90
+ 1. Answer ONLY based on the Stack Overflow context provided below.
91
+ 2. If the context does not fully cover the question, say so briefly, then answer from your knowledge.
92
+ 3. Always include working code examples in Python using markdown code blocks (```python ... ```).
93
+ 4. Be concise but complete β€” avoid unnecessary padding.
94
+ 5. If multiple approaches exist, list them with trade-offs.
95
+ """
96
+
97
+ def _call_groq_with_fallback(messages: list) -> tuple[str, str]:
98
+ """
99
+ Calls Groq chat completion API with automatic model fallback
100
+ if the chosen model is not found or encounters a 404 error.
101
+
102
+ Returns: (answer_text, model_used)
103
+ """
104
+ global GROQ_MODEL
105
+
106
+ models_to_try = list(dict.fromkeys([GROQ_MODEL] + _active_models + FALLBACK_MODELS))
107
+
108
+ last_exception = None
109
+ for model_name in models_to_try:
110
+ try:
111
+ response = _groq.chat.completions.create(
112
+ model=model_name,
113
+ messages=messages,
114
+ temperature=0.1,
115
+ max_tokens=1024,
116
+ )
117
+ answer = response.choices[0].message.content
118
+ GROQ_MODEL = model_name
119
+ return answer, model_name
120
+ except Exception as e:
121
+ err_str = str(e)
122
+ if "404" in err_str or "model_not_found" in err_str or "does not exist" in err_str:
123
+ print(f"⚠️ Model '{model_name}' not available on Groq (404/model_not_found). Trying fallback...")
124
+ last_exception = e
125
+ continue
126
+ else:
127
+ raise e
128
+
129
+ raise RuntimeError(
130
+ f"All attempted Groq models ({models_to_try}) failed. Last error: {last_exception}"
131
+ )
132
+
133
+ # ─── Main function called by FastAPI ─────────────────────────────────────────
134
+ def get_answer(question: str) -> dict:
135
+ """
136
+ Parameters
137
+ ----------
138
+ question : str β€” The user's Python question
139
+
140
+ Returns
141
+ -------
142
+ dict with keys: question, answer, sources, model, docs_retrieved
143
+ """
144
+ # 1️⃣ Embed the question
145
+ query_vec = _embedder.encode(question).tolist()
146
+
147
+ # 2️⃣ Retrieve top-K similar Q&As from vector DB
148
+ results = _collection.query(
149
+ query_embeddings=[query_vec],
150
+ n_results=TOP_K,
151
+ include=["documents", "metadatas", "distances"],
152
+ )
153
+
154
+ docs = results["documents"][0]
155
+ metas = results["metadatas"][0]
156
+ distances = results["distances"][0]
157
+
158
+ # 3️⃣ Build context block from retrieved docs
159
+ context_parts = []
160
+ source_titles = []
161
+ for i, (doc, meta, dist) in enumerate(zip(docs, metas, distances), 1):
162
+ title = meta.get("title", "Unknown")
163
+ score = meta.get("question_score", 0)
164
+ context_parts.append(
165
+ f"--- Stack Overflow Result {i} ---\n"
166
+ f"Title: {title} (votes: {score})\n"
167
+ f"Relevance: {(1 - dist) * 100:.1f}%\n\n"
168
+ f"{doc}"
169
+ )
170
+ source_titles.append(title)
171
+
172
+ context_str = "\n\n".join(context_parts)
173
+
174
+ # 4️⃣ Build prompt and call Groq with fallback
175
+ user_message = (
176
+ f"Python Question: {question}\n\n"
177
+ f"Stack Overflow Context:\n{context_str}\n\n"
178
+ f"Please answer the question based on the context above."
179
+ )
180
+
181
+ messages = [
182
+ {"role": "system", "content": _SYSTEM_PROMPT},
183
+ {"role": "user", "content": user_message},
184
+ ]
185
+
186
+ answer, model_used = _call_groq_with_fallback(messages)
187
+
188
+ return {
189
+ "question": question,
190
+ "answer": answer,
191
+ "sources": source_titles,
192
+ "model": model_used,
193
+ "docs_retrieved": TOP_K,
194
+ }
195
+