Spaces:
Sleeping
Sleeping
Commit
Β·
4cfc34d
1
Parent(s):
9db63ff
Final
Browse files- .gitattributes +3 -0
- app.py +239 -0
- chroma_db/bca992f1-533f-4712-9825-dffc5cb4917e/data_level0.bin +3 -0
- chroma_db/bca992f1-533f-4712-9825-dffc5cb4917e/header.bin +3 -0
- chroma_db/bca992f1-533f-4712-9825-dffc5cb4917e/length.bin +3 -0
- chroma_db/bca992f1-533f-4712-9825-dffc5cb4917e/link_lists.bin +0 -0
- chroma_db/chroma.sqlite3 +3 -0
- requiremnts.txt +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
chromadb/*.bin filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
chromadb/*.sqlite3 filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
chroma_db/**/* filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import chromadb
|
| 3 |
+
from chromadb.utils import embedding_functions
|
| 4 |
+
import groq
|
| 5 |
+
from typing import Dict
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
class CourseAdvisor:
|
| 9 |
+
def __init__(self, db_path: str = "./chroma_db"):
|
| 10 |
+
"""Initialize the course advisor with existing ChromaDB database."""
|
| 11 |
+
# Initialize persistent client with path
|
| 12 |
+
self.chroma_client = chromadb.PersistentClient(path=db_path)
|
| 13 |
+
|
| 14 |
+
# Initialize embedding function
|
| 15 |
+
self.embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(
|
| 16 |
+
model_name="jinaai/jina-embeddings-v2-base-en"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
# Get existing collection
|
| 20 |
+
self.collection = self.chroma_client.get_collection(
|
| 21 |
+
name="courses",
|
| 22 |
+
embedding_function=self.embedding_function
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
def query_courses(self, query_text: str, chat_history: str, api_key: str, n_results: int = 3) -> Dict:
|
| 26 |
+
"""Query the vector database and get course recommendations."""
|
| 27 |
+
# Initialize Groq client with provided API key
|
| 28 |
+
groq_client = groq.Groq(api_key=api_key)
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
# Get relevant documents from vector DB
|
| 32 |
+
results = self.collection.query(
|
| 33 |
+
query_texts=[query_text],
|
| 34 |
+
n_results=min(n_results, self.collection.count()),
|
| 35 |
+
include=['documents', 'metadatas']
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Prepare context from retrieved documents
|
| 39 |
+
docs_context = "\n\n".join(results['documents'][0])
|
| 40 |
+
|
| 41 |
+
except Exception as e:
|
| 42 |
+
st.error(f"Error querying database: {str(e)}")
|
| 43 |
+
return {
|
| 44 |
+
'llm_response': "I encountered an error while searching the course database. Please try again.",
|
| 45 |
+
'retrieved_courses': []
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
# Create prompt with chat history
|
| 49 |
+
prompt = f"""Previous conversation:
|
| 50 |
+
{chat_history}
|
| 51 |
+
|
| 52 |
+
Current user query: {query_text}
|
| 53 |
+
|
| 54 |
+
Relevant course information:
|
| 55 |
+
{docs_context}
|
| 56 |
+
|
| 57 |
+
Please provide course recommendations based on the entire conversation context. Format your response as:
|
| 58 |
+
1. Understanding of the user's needs (based on conversation history)
|
| 59 |
+
2. Overall recommendation with reasoning
|
| 60 |
+
3. Specific benefits of each recommended course
|
| 61 |
+
4. Learning path suggestion (if applicable)
|
| 62 |
+
5. Any prerequisites or important notes"""
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
# Get response from Groq
|
| 66 |
+
completion = groq_client.chat.completions.create(
|
| 67 |
+
messages=[
|
| 68 |
+
{"role": "system", "content": "You are a helpful course advisor who provides detailed, relevant course recommendations based on the user's needs and conversation history. Keep responses clear and well-structured."},
|
| 69 |
+
{"role": "user", "content": prompt}
|
| 70 |
+
],
|
| 71 |
+
model="mixtral-8x7b-32768",
|
| 72 |
+
temperature=0.7,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
return {
|
| 76 |
+
'llm_response': completion.choices[0].message.content,
|
| 77 |
+
'retrieved_courses': results['metadatas'][0]
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
except Exception as e:
|
| 81 |
+
st.error(f"Error with Groq API: {str(e)}")
|
| 82 |
+
return {
|
| 83 |
+
'llm_response': "I encountered an error while generating recommendations. Please check your API key and try again.",
|
| 84 |
+
'retrieved_courses': []
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
def initialize_session_state():
|
| 88 |
+
"""Initialize session state variables."""
|
| 89 |
+
if 'messages' not in st.session_state:
|
| 90 |
+
st.session_state.messages = []
|
| 91 |
+
if 'course_advisor' not in st.session_state:
|
| 92 |
+
st.session_state.course_advisor = CourseAdvisor()
|
| 93 |
+
if 'api_key' not in st.session_state:
|
| 94 |
+
st.session_state.api_key = ""
|
| 95 |
+
|
| 96 |
+
def get_chat_history() -> str:
|
| 97 |
+
"""Format chat history for LLM context."""
|
| 98 |
+
history = []
|
| 99 |
+
for message in st.session_state.messages[-5:]: # Only use last 5 messages for context
|
| 100 |
+
role = message["role"]
|
| 101 |
+
content = message["content"]
|
| 102 |
+
history.append(f"{role}: {content}")
|
| 103 |
+
return "\n".join(history)
|
| 104 |
+
|
| 105 |
+
def display_course_card(course: Dict):
|
| 106 |
+
"""Display a single course recommendation in a card format."""
|
| 107 |
+
with st.container():
|
| 108 |
+
# Add a light background and padding
|
| 109 |
+
with st.container():
|
| 110 |
+
st.markdown("""
|
| 111 |
+
<style>
|
| 112 |
+
.course-card {
|
| 113 |
+
background-color: #f8f9fa;
|
| 114 |
+
padding: 1rem;
|
| 115 |
+
border-radius: 0.5rem;
|
| 116 |
+
margin-bottom: 1rem;
|
| 117 |
+
}
|
| 118 |
+
</style>
|
| 119 |
+
""", unsafe_allow_html=True)
|
| 120 |
+
|
| 121 |
+
with st.container():
|
| 122 |
+
st.markdown('<div class="course-card">', unsafe_allow_html=True)
|
| 123 |
+
|
| 124 |
+
# Course title
|
| 125 |
+
st.markdown(f"### {course['title']}")
|
| 126 |
+
|
| 127 |
+
col1, col2 = st.columns(2)
|
| 128 |
+
|
| 129 |
+
with col1:
|
| 130 |
+
# Handle categories - convert to list if string
|
| 131 |
+
categories = course.get('categories', 'N/A')
|
| 132 |
+
if isinstance(categories, str):
|
| 133 |
+
# Split by comma if it's a comma-separated string
|
| 134 |
+
categories = [cat.strip() for cat in categories.split(',')]
|
| 135 |
+
elif not isinstance(categories, list):
|
| 136 |
+
categories = [str(categories)]
|
| 137 |
+
|
| 138 |
+
# Display categories as bullet points if multiple
|
| 139 |
+
if len(categories) > 1:
|
| 140 |
+
st.markdown("**Categories:**")
|
| 141 |
+
for category in categories:
|
| 142 |
+
st.markdown(f"- {category}")
|
| 143 |
+
else:
|
| 144 |
+
st.markdown(f"**Category:** {categories[0]}")
|
| 145 |
+
|
| 146 |
+
st.markdown(f"**Lessons:** {course.get('lessons', 'N/A')}")
|
| 147 |
+
|
| 148 |
+
with col2:
|
| 149 |
+
st.markdown(f"**Price:** {course.get('price', 'N/A')}")
|
| 150 |
+
if 'url' in course:
|
| 151 |
+
st.markdown(f"**[Visit Course]({course['url']})**")
|
| 152 |
+
|
| 153 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 154 |
+
|
| 155 |
+
st.markdown("---")
|
| 156 |
+
|
| 157 |
+
def main():
|
| 158 |
+
st.set_page_config(
|
| 159 |
+
page_title="Course Recommender",
|
| 160 |
+
page_icon="π",
|
| 161 |
+
layout="wide"
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
st.title("π AI Course Recommender")
|
| 165 |
+
|
| 166 |
+
# Initialize session state
|
| 167 |
+
initialize_session_state()
|
| 168 |
+
|
| 169 |
+
# Display collection info
|
| 170 |
+
collection = st.session_state.course_advisor.collection
|
| 171 |
+
st.sidebar.info(f"Connected to database with {collection.count()} courses")
|
| 172 |
+
|
| 173 |
+
# Sidebar
|
| 174 |
+
with st.sidebar:
|
| 175 |
+
st.header("Settings")
|
| 176 |
+
|
| 177 |
+
# API key input
|
| 178 |
+
api_key = st.text_input("Enter Groq API Key",
|
| 179 |
+
type="password",
|
| 180 |
+
value=st.session_state.api_key)
|
| 181 |
+
if api_key != st.session_state.api_key:
|
| 182 |
+
st.session_state.api_key = api_key
|
| 183 |
+
|
| 184 |
+
# Clear chat button
|
| 185 |
+
if st.button("Clear Chat History"):
|
| 186 |
+
st.session_state.messages = []
|
| 187 |
+
|
| 188 |
+
# Main chat interface
|
| 189 |
+
st.header("Chat with AI Course Advisor")
|
| 190 |
+
|
| 191 |
+
# Display chat history
|
| 192 |
+
for message in st.session_state.messages:
|
| 193 |
+
with st.chat_message(message["role"]):
|
| 194 |
+
st.markdown(message["content"])
|
| 195 |
+
|
| 196 |
+
# Chat input
|
| 197 |
+
if prompt := st.chat_input("What would you like to learn?"):
|
| 198 |
+
# Check if API key is provided
|
| 199 |
+
if not st.session_state.api_key:
|
| 200 |
+
st.error("Please enter your Groq API key in the sidebar.")
|
| 201 |
+
return
|
| 202 |
+
|
| 203 |
+
# Add user message to chat history
|
| 204 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 205 |
+
|
| 206 |
+
with st.chat_message("user"):
|
| 207 |
+
st.markdown(prompt)
|
| 208 |
+
|
| 209 |
+
# Get AI response
|
| 210 |
+
with st.chat_message("assistant"):
|
| 211 |
+
with st.spinner("Thinking..."):
|
| 212 |
+
# Get formatted chat history
|
| 213 |
+
chat_history = get_chat_history()
|
| 214 |
+
|
| 215 |
+
# Query courses with chat history
|
| 216 |
+
response = st.session_state.course_advisor.query_courses(
|
| 217 |
+
prompt,
|
| 218 |
+
chat_history,
|
| 219 |
+
st.session_state.api_key
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
# Display AI recommendation
|
| 223 |
+
st.markdown(response['llm_response'])
|
| 224 |
+
|
| 225 |
+
# Display course cards if any courses were retrieved
|
| 226 |
+
if response['retrieved_courses']:
|
| 227 |
+
st.markdown("### π Recommended Courses")
|
| 228 |
+
for course in response['retrieved_courses']:
|
| 229 |
+
display_course_card(course)
|
| 230 |
+
|
| 231 |
+
# Add assistant response to chat history
|
| 232 |
+
st.session_state.messages.append({
|
| 233 |
+
"role": "assistant",
|
| 234 |
+
"content": response['llm_response'] + "\n\n" + "### Recommended Courses\n" +
|
| 235 |
+
"\n".join([f"- {course['title']}" for course in response['retrieved_courses']])
|
| 236 |
+
})
|
| 237 |
+
|
| 238 |
+
if __name__ == "__main__":
|
| 239 |
+
main()
|
chroma_db/bca992f1-533f-4712-9825-dffc5cb4917e/data_level0.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a13e72541800c513c73dccea69f79e39cf4baef4fa23f7e117c0d6b0f5f99670
|
| 3 |
+
size 3212000
|
chroma_db/bca992f1-533f-4712-9825-dffc5cb4917e/header.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0ec6df10978b056a10062ed99efeef2702fa4a1301fad702b53dd2517103c746
|
| 3 |
+
size 100
|
chroma_db/bca992f1-533f-4712-9825-dffc5cb4917e/length.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2823f194bebd05c68f5f4e78e39d91ac3064fb61f9163082a55db490fea91b56
|
| 3 |
+
size 4000
|
chroma_db/bca992f1-533f-4712-9825-dffc5cb4917e/link_lists.bin
ADDED
|
File without changes
|
chroma_db/chroma.sqlite3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8973c5639f318e93a15f9963255d93350efdf75478f940cd8410ee3195646e07
|
| 3 |
+
size 2293760
|
requiremnts.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
chromadb
|
| 3 |
+
groq
|