Shubham 10000 commited on
Commit Β·
136f50c
1
Parent(s): c0ba77d
Initial Docker Deployment
Browse files- app.py +60 -173
- requirements.txt +3 -2
app.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# app.py - Hugging Face Spaces
|
| 2 |
import streamlit as st
|
| 3 |
import requests
|
| 4 |
import os
|
|
@@ -16,21 +16,20 @@ st.set_page_config(
|
|
| 16 |
)
|
| 17 |
|
| 18 |
# Get API key from environment (HF Secrets or Docker env)
|
|
|
|
| 19 |
try:
|
| 20 |
-
# Try Streamlit secrets first (HF Spaces)
|
| 21 |
GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
|
| 22 |
except:
|
| 23 |
-
# Fall back to environment variable (Docker)
|
| 24 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 25 |
|
| 26 |
GROQ_MODEL = os.getenv("GROQ_MODEL", "mixtral-8x7b-32768")
|
| 27 |
|
| 28 |
# Initialize vector index
|
|
|
|
|
|
|
| 29 |
@st.cache_resource
|
| 30 |
def get_vector_index():
|
| 31 |
-
|
| 32 |
-
VECTOR_INDEX = VectorIndex(storage_dir="/tmp/vector_data")
|
| 33 |
-
return VectorIndex(storage_dir="/app/data")
|
| 34 |
|
| 35 |
try:
|
| 36 |
VECTOR_INDEX = get_vector_index()
|
|
@@ -44,18 +43,10 @@ except Exception as e:
|
|
| 44 |
def call_groq_chat(messages: List[Dict], temperature: float = 0.3) -> str:
|
| 45 |
"""Call Groq Chat API."""
|
| 46 |
if not GROQ_API_KEY:
|
| 47 |
-
return "β οΈ Error: GROQ_API_KEY not configured.\
|
| 48 |
-
|
| 49 |
-
headers = {
|
| 50 |
-
"Authorization": f"Bearer {GROQ_API_KEY}",
|
| 51 |
-
"Content-Type": "application/json"
|
| 52 |
-
}
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
"messages": messages,
|
| 57 |
-
"temperature": temperature
|
| 58 |
-
}
|
| 59 |
|
| 60 |
try:
|
| 61 |
resp = requests.post(
|
|
@@ -64,20 +55,18 @@ def call_groq_chat(messages: List[Dict], temperature: float = 0.3) -> str:
|
|
| 64 |
json=payload,
|
| 65 |
timeout=60
|
| 66 |
)
|
| 67 |
-
|
| 68 |
if resp.status_code == 200:
|
| 69 |
return resp.json()["choices"][0]["message"]["content"]
|
| 70 |
elif resp.status_code == 401:
|
| 71 |
-
return "β Error: Invalid API key.
|
| 72 |
elif resp.status_code == 429:
|
| 73 |
-
return "β Error: Rate limit exceeded.
|
| 74 |
else:
|
| 75 |
return f"β Error ({resp.status_code}): {resp.text}"
|
| 76 |
-
|
| 77 |
except requests.exceptions.Timeout:
|
| 78 |
-
return "β Error: Request timed out.
|
| 79 |
except requests.exceptions.ConnectionError:
|
| 80 |
-
return "β Error: Cannot connect to Groq API.
|
| 81 |
except Exception as e:
|
| 82 |
return f"β Error: {str(e)}"
|
| 83 |
|
|
@@ -88,7 +77,6 @@ def get_system_prompt(department: str, role: Optional[str]) -> str:
|
|
| 88 |
"You should be concise, helpful, and provide actionable outputs such as email drafts, "
|
| 89 |
"templates, or short guides."
|
| 90 |
)
|
| 91 |
-
|
| 92 |
dept_map = {
|
| 93 |
"HR": "As an HR assistant, help recruiters with writing mails, interview questions, and onboarding docs.",
|
| 94 |
"Finance": "As a Finance assistant, help prepare reports, budget summaries, and analyses.",
|
|
@@ -96,7 +84,6 @@ def get_system_prompt(department: str, role: Optional[str]) -> str:
|
|
| 96 |
"Product Manager": "As a Product Manager assistant, help with PRDs, user stories, and product strategies.",
|
| 97 |
"Other": "General assistant role. Adapt to user's context."
|
| 98 |
}
|
| 99 |
-
|
| 100 |
return f"{base}\n\n{dept_map.get(department, dept_map['Other'])} Role: {role or 'Employee'}."
|
| 101 |
|
| 102 |
# ==============================
|
|
@@ -128,182 +115,104 @@ with st.sidebar:
|
|
| 128 |
with st.expander("π How to add API Key"):
|
| 129 |
st.markdown("""
|
| 130 |
**For Hugging Face Spaces:**
|
| 131 |
-
1. Go to Space Settings
|
| 132 |
-
2.
|
| 133 |
-
3. Add secret:
|
| 134 |
- Name: `GROQ_API_KEY`
|
| 135 |
- Value: Your Groq API key
|
| 136 |
-
|
| 137 |
-
**Get Free API Key:**
|
| 138 |
-
https://console.groq.com/
|
| 139 |
""")
|
| 140 |
-
|
| 141 |
# Vector Index Status
|
| 142 |
if VECTOR_INDEX:
|
| 143 |
st.success("β
Vector Index Ready")
|
| 144 |
else:
|
| 145 |
st.error("β Vector Index Failed")
|
| 146 |
-
|
| 147 |
st.markdown("---")
|
| 148 |
-
|
| 149 |
-
# Settings
|
| 150 |
st.subheader("Settings")
|
| 151 |
|
| 152 |
-
department = st.selectbox(
|
| 153 |
-
"Department",
|
| 154 |
-
["HR", "Finance", "IT", "Product Manager", "Other"],
|
| 155 |
-
index=0
|
| 156 |
-
)
|
| 157 |
-
|
| 158 |
role = st.text_input("Your Role (optional)", placeholder="e.g., Senior Manager")
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
use_rag = st.checkbox("Enable RAG", value=False,
|
| 164 |
-
help="Use uploaded documents as context")
|
| 165 |
-
|
| 166 |
-
if use_rag:
|
| 167 |
-
top_k = st.slider("Top K Documents", 1, 10, 3,
|
| 168 |
-
help="Number of relevant documents to retrieve")
|
| 169 |
-
else:
|
| 170 |
-
top_k = 3
|
| 171 |
-
|
| 172 |
st.markdown("---")
|
| 173 |
-
|
| 174 |
-
# Document Management
|
| 175 |
st.subheader("π Documents")
|
| 176 |
|
| 177 |
if VECTOR_INDEX:
|
| 178 |
-
|
| 179 |
-
with st.expander("βΉοΈ Storage Info"):
|
| 180 |
-
st.info(
|
| 181 |
-
"π¦ Documents are stored in Docker volume.\n"
|
| 182 |
-
"β οΈ They persist during session but may be lost on Space restart."
|
| 183 |
-
)
|
| 184 |
-
|
| 185 |
-
# File upload
|
| 186 |
-
uploaded_files = st.file_uploader(
|
| 187 |
-
"Upload documents (.txt, .md)",
|
| 188 |
-
type=["txt", "md"],
|
| 189 |
-
accept_multiple_files=True,
|
| 190 |
-
key="file_uploader"
|
| 191 |
-
)
|
| 192 |
|
| 193 |
if uploaded_files:
|
| 194 |
if st.button("π€ Upload Files", use_container_width=True):
|
| 195 |
with st.spinner("Processing..."):
|
| 196 |
-
uploaded_count = 0
|
| 197 |
-
errors = []
|
| 198 |
-
|
| 199 |
for file in uploaded_files:
|
| 200 |
try:
|
| 201 |
content = file.getvalue().decode("utf-8", errors="ignore")
|
| 202 |
-
|
| 203 |
-
if len(content.strip()) == 0:
|
| 204 |
errors.append(f"{file.name}: Empty file")
|
| 205 |
continue
|
| 206 |
-
|
| 207 |
-
doc_id = VECTOR_INDEX.add_document(
|
| 208 |
-
content,
|
| 209 |
-
source="user-upload",
|
| 210 |
-
metadata={"filename": file.name}
|
| 211 |
-
)
|
| 212 |
uploaded_count += 1
|
| 213 |
-
|
| 214 |
except Exception as e:
|
| 215 |
errors.append(f"{file.name}: {str(e)}")
|
| 216 |
-
|
| 217 |
-
if uploaded_count > 0:
|
| 218 |
st.success(f"β
Uploaded {uploaded_count} document(s)")
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
st.error(f"β {error}")
|
| 223 |
-
|
| 224 |
-
if uploaded_count > 0:
|
| 225 |
st.rerun()
|
| 226 |
|
| 227 |
-
# Document list
|
| 228 |
col1, col2 = st.columns(2)
|
| 229 |
-
|
| 230 |
with col1:
|
| 231 |
-
if st.button("π List
|
| 232 |
docs = VECTOR_INDEX.list_documents()
|
| 233 |
if docs:
|
| 234 |
st.markdown("**Available Documents:**")
|
| 235 |
for doc in docs:
|
| 236 |
-
filename = doc.metadata.get(
|
| 237 |
st.markdown(f"β’ {filename}")
|
| 238 |
else:
|
| 239 |
st.info("No documents yet.")
|
| 240 |
-
|
| 241 |
with col2:
|
| 242 |
-
if st.button("ποΈ Clear
|
| 243 |
VECTOR_INDEX.clear()
|
| 244 |
st.warning("Cleared all documents!")
|
| 245 |
st.rerun()
|
| 246 |
|
| 247 |
-
|
| 248 |
-
doc_count = VECTOR_INDEX.count()
|
| 249 |
-
st.metric("Total Documents", doc_count)
|
| 250 |
else:
|
| 251 |
st.error("Vector index not available")
|
| 252 |
-
doc_count = 0
|
| 253 |
|
| 254 |
# ==============================
|
| 255 |
-
#
|
| 256 |
# ==============================
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
-
# Display chat messages
|
| 259 |
-
for message in st.session_state.messages:
|
| 260 |
-
with st.chat_message(message["role"]):
|
| 261 |
-
st.markdown(message["content"])
|
| 262 |
-
|
| 263 |
-
# Chat input
|
| 264 |
if prompt := st.chat_input("Type your message here..."):
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
if not GROQ_API_KEY:
|
| 268 |
-
st.error("β οΈ Please configure GROQ_API_KEY first!")
|
| 269 |
-
st.stop()
|
| 270 |
-
|
| 271 |
-
if not VECTOR_INDEX:
|
| 272 |
-
st.error("β οΈ Vector index not initialized!")
|
| 273 |
st.stop()
|
| 274 |
|
| 275 |
-
# Add user message
|
| 276 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 277 |
with st.chat_message("user"):
|
| 278 |
st.markdown(prompt)
|
| 279 |
|
| 280 |
# Prepare conversation
|
| 281 |
-
conversation = []
|
| 282 |
-
|
| 283 |
-
#
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
for i, doc in enumerate(docs, 1):
|
| 294 |
-
filename = doc.metadata.get('filename', 'Unknown')
|
| 295 |
-
content_preview = doc.content[:800] # Limit context size
|
| 296 |
-
context_parts.append(f"[Document {i}: {filename}]\n{content_preview}")
|
| 297 |
-
|
| 298 |
-
context = "\n\n".join(context_parts)
|
| 299 |
-
rag_context = f"Relevant context from uploaded documents:\n\n{context}"
|
| 300 |
-
conversation.append({"role": "system", "content": rag_context})
|
| 301 |
-
except Exception as e:
|
| 302 |
-
st.warning(f"β οΈ RAG search failed: {e}")
|
| 303 |
-
|
| 304 |
-
# Add chat history (last 10 exchanges)
|
| 305 |
-
recent_messages = st.session_state.messages[-20:] # Last 10 exchanges (20 messages)
|
| 306 |
-
for msg in recent_messages:
|
| 307 |
conversation.append({"role": msg["role"], "content": msg["content"]})
|
| 308 |
|
| 309 |
# Get response
|
|
@@ -311,54 +220,32 @@ if prompt := st.chat_input("Type your message here..."):
|
|
| 311 |
with st.spinner("π€ Thinking..."):
|
| 312 |
response = call_groq_chat(conversation, temperature=temperature)
|
| 313 |
st.markdown(response)
|
| 314 |
-
|
| 315 |
-
# Save response
|
| 316 |
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 317 |
|
| 318 |
# ==============================
|
| 319 |
# FOOTER
|
| 320 |
# ==============================
|
| 321 |
st.markdown("---")
|
| 322 |
-
|
| 323 |
col1, col2, col3, col4 = st.columns(4)
|
| 324 |
-
|
| 325 |
with col1:
|
| 326 |
-
if st.button("π Clear Chat"
|
| 327 |
st.session_state.messages = []
|
| 328 |
st.rerun()
|
| 329 |
-
|
| 330 |
with col2:
|
| 331 |
st.markdown(f"**Dept:** {department}")
|
| 332 |
-
|
| 333 |
with col3:
|
| 334 |
st.markdown(f"**RAG:** {'β
' if use_rag else 'β'}")
|
| 335 |
-
|
| 336 |
with col4:
|
| 337 |
-
st.markdown(f"**Docs:** {
|
| 338 |
|
| 339 |
-
# About
|
| 340 |
with st.expander("βΉοΈ About This App"):
|
| 341 |
st.markdown("""
|
| 342 |
### AI Assistant with RAG
|
| 343 |
-
|
| 344 |
-
**Technology Stack:**
|
| 345 |
-
- π§ **LLM**: Groq API (Mixtral-8x7B-32768)
|
| 346 |
-
- π **Embeddings**: Sentence Transformers (all-MiniLM-L6-v2)
|
| 347 |
-
- π **Vector DB**: FAISS (Facebook AI Similarity Search)
|
| 348 |
-
- π¨ **UI**: Streamlit
|
| 349 |
-
- π³ **Deployment**: Docker on Hugging Face Spaces
|
| 350 |
-
|
| 351 |
**Features:**
|
| 352 |
-
- Department-specific AI
|
| 353 |
-
- Upload
|
| 354 |
-
- Multi-turn
|
| 355 |
-
- Adjustable response
|
| 356 |
-
- Persistent storage (
|
| 357 |
-
|
| 358 |
-
**Links:**
|
| 359 |
-
- [Groq API](https://console.groq.com/)
|
| 360 |
-
- [Hugging Face Spaces](https://huggingface.co/Shubham-10000)
|
| 361 |
-
- [GitHub Repository](https://github.com/yourusername/ai-assistant-rag)
|
| 362 |
-
|
| 363 |
-
**Version:** 1.0.0 (Docker)
|
| 364 |
-
""")
|
|
|
|
| 1 |
+
# app.py - Hugging Face Spaces Ready
|
| 2 |
import streamlit as st
|
| 3 |
import requests
|
| 4 |
import os
|
|
|
|
| 16 |
)
|
| 17 |
|
| 18 |
# Get API key from environment (HF Secrets or Docker env)
|
| 19 |
+
GROQ_API_KEY = None
|
| 20 |
try:
|
|
|
|
| 21 |
GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
|
| 22 |
except:
|
|
|
|
| 23 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 24 |
|
| 25 |
GROQ_MODEL = os.getenv("GROQ_MODEL", "mixtral-8x7b-32768")
|
| 26 |
|
| 27 |
# Initialize vector index
|
| 28 |
+
STORAGE_PATH = "/tmp/vector_data"
|
| 29 |
+
|
| 30 |
@st.cache_resource
|
| 31 |
def get_vector_index():
|
| 32 |
+
return VectorIndex(storage_dir=STORAGE_PATH)
|
|
|
|
|
|
|
| 33 |
|
| 34 |
try:
|
| 35 |
VECTOR_INDEX = get_vector_index()
|
|
|
|
| 43 |
def call_groq_chat(messages: List[Dict], temperature: float = 0.3) -> str:
|
| 44 |
"""Call Groq Chat API."""
|
| 45 |
if not GROQ_API_KEY:
|
| 46 |
+
return "β οΈ Error: GROQ_API_KEY not configured.\nAdd it in HF Space secrets or Docker env."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
|
| 49 |
+
payload = {"model": GROQ_MODEL, "messages": messages, "temperature": temperature}
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
try:
|
| 52 |
resp = requests.post(
|
|
|
|
| 55 |
json=payload,
|
| 56 |
timeout=60
|
| 57 |
)
|
|
|
|
| 58 |
if resp.status_code == 200:
|
| 59 |
return resp.json()["choices"][0]["message"]["content"]
|
| 60 |
elif resp.status_code == 401:
|
| 61 |
+
return "β Error: Invalid API key."
|
| 62 |
elif resp.status_code == 429:
|
| 63 |
+
return "β Error: Rate limit exceeded."
|
| 64 |
else:
|
| 65 |
return f"β Error ({resp.status_code}): {resp.text}"
|
|
|
|
| 66 |
except requests.exceptions.Timeout:
|
| 67 |
+
return "β Error: Request timed out."
|
| 68 |
except requests.exceptions.ConnectionError:
|
| 69 |
+
return "β Error: Cannot connect to Groq API."
|
| 70 |
except Exception as e:
|
| 71 |
return f"β Error: {str(e)}"
|
| 72 |
|
|
|
|
| 77 |
"You should be concise, helpful, and provide actionable outputs such as email drafts, "
|
| 78 |
"templates, or short guides."
|
| 79 |
)
|
|
|
|
| 80 |
dept_map = {
|
| 81 |
"HR": "As an HR assistant, help recruiters with writing mails, interview questions, and onboarding docs.",
|
| 82 |
"Finance": "As a Finance assistant, help prepare reports, budget summaries, and analyses.",
|
|
|
|
| 84 |
"Product Manager": "As a Product Manager assistant, help with PRDs, user stories, and product strategies.",
|
| 85 |
"Other": "General assistant role. Adapt to user's context."
|
| 86 |
}
|
|
|
|
| 87 |
return f"{base}\n\n{dept_map.get(department, dept_map['Other'])} Role: {role or 'Employee'}."
|
| 88 |
|
| 89 |
# ==============================
|
|
|
|
| 115 |
with st.expander("π How to add API Key"):
|
| 116 |
st.markdown("""
|
| 117 |
**For Hugging Face Spaces:**
|
| 118 |
+
1. Go to Space Settings β Repository secrets
|
| 119 |
+
2. Add secret:
|
|
|
|
| 120 |
- Name: `GROQ_API_KEY`
|
| 121 |
- Value: Your Groq API key
|
|
|
|
|
|
|
|
|
|
| 122 |
""")
|
| 123 |
+
|
| 124 |
# Vector Index Status
|
| 125 |
if VECTOR_INDEX:
|
| 126 |
st.success("β
Vector Index Ready")
|
| 127 |
else:
|
| 128 |
st.error("β Vector Index Failed")
|
| 129 |
+
|
| 130 |
st.markdown("---")
|
|
|
|
|
|
|
| 131 |
st.subheader("Settings")
|
| 132 |
|
| 133 |
+
department = st.selectbox("Department", ["HR", "Finance", "IT", "Product Manager", "Other"], index=0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
role = st.text_input("Your Role (optional)", placeholder="e.g., Senior Manager")
|
| 135 |
+
temperature = st.slider("Temperature", 0.0, 1.0, 0.2, 0.1)
|
| 136 |
+
use_rag = st.checkbox("Enable RAG", value=False)
|
| 137 |
+
top_k = st.slider("Top K Documents", 1, 10, 3) if use_rag else 3
|
| 138 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
st.markdown("---")
|
|
|
|
|
|
|
| 140 |
st.subheader("π Documents")
|
| 141 |
|
| 142 |
if VECTOR_INDEX:
|
| 143 |
+
uploaded_files = st.file_uploader("Upload documents (.txt, .md)", type=["txt", "md"], accept_multiple_files=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
if uploaded_files:
|
| 146 |
if st.button("π€ Upload Files", use_container_width=True):
|
| 147 |
with st.spinner("Processing..."):
|
| 148 |
+
uploaded_count, errors = 0, []
|
|
|
|
|
|
|
| 149 |
for file in uploaded_files:
|
| 150 |
try:
|
| 151 |
content = file.getvalue().decode("utf-8", errors="ignore")
|
| 152 |
+
if not content.strip():
|
|
|
|
| 153 |
errors.append(f"{file.name}: Empty file")
|
| 154 |
continue
|
| 155 |
+
VECTOR_INDEX.add_document(content, source="user-upload", metadata={"filename": file.name})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
uploaded_count += 1
|
|
|
|
| 157 |
except Exception as e:
|
| 158 |
errors.append(f"{file.name}: {str(e)}")
|
| 159 |
+
if uploaded_count:
|
|
|
|
| 160 |
st.success(f"β
Uploaded {uploaded_count} document(s)")
|
| 161 |
+
for err in errors:
|
| 162 |
+
st.error(f"β {err}")
|
| 163 |
+
if uploaded_count:
|
|
|
|
|
|
|
|
|
|
| 164 |
st.rerun()
|
| 165 |
|
|
|
|
| 166 |
col1, col2 = st.columns(2)
|
|
|
|
| 167 |
with col1:
|
| 168 |
+
if st.button("π List Documents"):
|
| 169 |
docs = VECTOR_INDEX.list_documents()
|
| 170 |
if docs:
|
| 171 |
st.markdown("**Available Documents:**")
|
| 172 |
for doc in docs:
|
| 173 |
+
filename = doc.metadata.get("filename", "Untitled")
|
| 174 |
st.markdown(f"β’ {filename}")
|
| 175 |
else:
|
| 176 |
st.info("No documents yet.")
|
|
|
|
| 177 |
with col2:
|
| 178 |
+
if st.button("ποΈ Clear Documents"):
|
| 179 |
VECTOR_INDEX.clear()
|
| 180 |
st.warning("Cleared all documents!")
|
| 181 |
st.rerun()
|
| 182 |
|
| 183 |
+
st.metric("Total Documents", VECTOR_INDEX.count())
|
|
|
|
|
|
|
| 184 |
else:
|
| 185 |
st.error("Vector index not available")
|
|
|
|
| 186 |
|
| 187 |
# ==============================
|
| 188 |
+
# CHAT INTERFACE
|
| 189 |
# ==============================
|
| 190 |
+
for msg in st.session_state.messages:
|
| 191 |
+
with st.chat_message(msg["role"]):
|
| 192 |
+
st.markdown(msg["content"])
|
| 193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
if prompt := st.chat_input("Type your message here..."):
|
| 195 |
+
if not GROQ_API_KEY or not VECTOR_INDEX:
|
| 196 |
+
st.error("β οΈ Configure GROQ_API_KEY and ensure vector index is ready!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
st.stop()
|
| 198 |
|
|
|
|
| 199 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 200 |
with st.chat_message("user"):
|
| 201 |
st.markdown(prompt)
|
| 202 |
|
| 203 |
# Prepare conversation
|
| 204 |
+
conversation = [{"role": "system", "content": get_system_prompt(department, role)}]
|
| 205 |
+
|
| 206 |
+
# Add RAG context
|
| 207 |
+
if use_rag and VECTOR_INDEX.count() > 0:
|
| 208 |
+
docs = VECTOR_INDEX.search(prompt, top_k=top_k)
|
| 209 |
+
if docs:
|
| 210 |
+
context = "\n\n".join([f"[{i+1}: {d.metadata.get('filename','Unknown')}]\n{d.content[:800]}" for i,d in enumerate(docs)])
|
| 211 |
+
conversation.append({"role": "system", "content": f"Relevant context from uploaded documents:\n\n{context}"})
|
| 212 |
+
|
| 213 |
+
# Add recent messages
|
| 214 |
+
recent_msgs = st.session_state.messages[-20:]
|
| 215 |
+
for msg in recent_msgs:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
conversation.append({"role": msg["role"], "content": msg["content"]})
|
| 217 |
|
| 218 |
# Get response
|
|
|
|
| 220 |
with st.spinner("π€ Thinking..."):
|
| 221 |
response = call_groq_chat(conversation, temperature=temperature)
|
| 222 |
st.markdown(response)
|
|
|
|
|
|
|
| 223 |
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 224 |
|
| 225 |
# ==============================
|
| 226 |
# FOOTER
|
| 227 |
# ==============================
|
| 228 |
st.markdown("---")
|
|
|
|
| 229 |
col1, col2, col3, col4 = st.columns(4)
|
|
|
|
| 230 |
with col1:
|
| 231 |
+
if st.button("π Clear Chat"):
|
| 232 |
st.session_state.messages = []
|
| 233 |
st.rerun()
|
|
|
|
| 234 |
with col2:
|
| 235 |
st.markdown(f"**Dept:** {department}")
|
|
|
|
| 236 |
with col3:
|
| 237 |
st.markdown(f"**RAG:** {'β
' if use_rag else 'β'}")
|
|
|
|
| 238 |
with col4:
|
| 239 |
+
st.markdown(f"**Docs:** {VECTOR_INDEX.count() if VECTOR_INDEX else 0}")
|
| 240 |
|
|
|
|
| 241 |
with st.expander("βΉοΈ About This App"):
|
| 242 |
st.markdown("""
|
| 243 |
### AI Assistant with RAG
|
| 244 |
+
**Stack:** Groq LLM, FAISS, Sentence Transformers, Streamlit, Docker/HF Spaces
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
**Features:**
|
| 246 |
+
- Department-specific AI assistant
|
| 247 |
+
- Upload/search documents (RAG)
|
| 248 |
+
- Multi-turn conversation memory
|
| 249 |
+
- Adjustable response creativity
|
| 250 |
+
- Persistent session storage (ephemeral on HF)
|
| 251 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
# requirements.txt - All dependencies for HF Spaces with Docker
|
| 2 |
streamlit==1.28.0
|
| 3 |
-
sentence-transformers==2.2.2
|
| 4 |
faiss-cpu==1.7.4
|
| 5 |
torch>=2.0.0
|
| 6 |
requests==2.31.0
|
| 7 |
numpy>=1.24.0
|
| 8 |
scikit-learn>=1.3.0
|
| 9 |
-
transformers>=4.30.0
|
|
|
|
|
|
|
|
|
| 1 |
# requirements.txt - All dependencies for HF Spaces with Docker
|
| 2 |
streamlit==1.28.0
|
|
|
|
| 3 |
faiss-cpu==1.7.4
|
| 4 |
torch>=2.0.0
|
| 5 |
requests==2.31.0
|
| 6 |
numpy>=1.24.0
|
| 7 |
scikit-learn>=1.3.0
|
| 8 |
+
transformers>=4.30.0
|
| 9 |
+
sentence-transformers==2.2.2
|
| 10 |
+
huggingface-hub==0.17.4
|