Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,57 +3,80 @@ import datetime
|
|
| 3 |
import warnings
|
| 4 |
import gradio as gr
|
| 5 |
|
| 6 |
-
# Suppress deprecation warnings
|
| 7 |
warnings.filterwarnings("ignore", category=UserWarning, module="langchain_community")
|
| 8 |
|
| 9 |
-
from
|
| 10 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 11 |
-
from langchain_openai import ChatOpenAI
|
| 12 |
-
from langchain_core.prompts import ChatPromptTemplate
|
| 13 |
-
from langchain_core.output_parsers import StrOutputParser
|
| 14 |
-
from dotenv import load_dotenv
|
| 15 |
-
from langchain_huggingface import HuggingFaceEndpoint
|
| 16 |
from langchain_core.prompts import PromptTemplate
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
|
|
|
| 20 |
hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
|
| 21 |
|
| 22 |
# -------------------------------------------------------------------------
|
| 23 |
-
#
|
| 24 |
# -------------------------------------------------------------------------
|
| 25 |
print("Loading semantic embedding vectors...")
|
| 26 |
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 27 |
|
|
|
|
| 28 |
simplilearn_faq_data = [
|
| 29 |
"Simplilearn Refund Policy: Learners are entitled to a full 100% refund within 7 days of course purchase, provided they have not accessed more than 25% of the unlocked asynchronous content or attended any live virtual cohort sessions.",
|
| 30 |
"Professional Certification Requirements: To unlock your official Simplilearn digital certificate, you must achieve a minimum score of 80% in the final course assessment and successfully submit all mandatory course projects.",
|
| 31 |
-
"Live Virtual Class Attendance: If a student misses an interactive live session, high-definition cloud recordings are automatically
|
| 32 |
-
"
|
| 33 |
-
"
|
| 34 |
]
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
# -------------------------------------------------------------------------
|
| 40 |
-
#
|
| 41 |
# -------------------------------------------------------------------------
|
| 42 |
print("Configuring LLM Interface...")
|
| 43 |
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
repo_id="mistralai/Mistral-7B-Instruct-v0.3",
|
| 50 |
-
huggingfacehub_api_token=hf_token,
|
| 51 |
-
temperature=0.3,
|
| 52 |
-
max_new_tokens=400,
|
| 53 |
-
headers={"X-Wait-For-Model": "true"} # Fixes the TypeError and handles cold starts gracefully
|
| 54 |
)
|
| 55 |
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
system_prompt = """You are the Simplilearn MOOC Support Agent, an advanced, polite, and professional AI learning assistant named Lane.
|
| 58 |
Answer the student's inquiry accurately using ONLY the retrieved context below.
|
| 59 |
If the answer cannot be found in the context, politely inform them that you only handle Simplilearn academic protocols and advise them to contact support@simplilearn.com.
|
|
@@ -70,6 +93,7 @@ prompt = PromptTemplate.from_template(system_prompt)
|
|
| 70 |
def format_docs(docs):
|
| 71 |
return "\n\n".join(doc.page_content for doc in docs)
|
| 72 |
|
|
|
|
| 73 |
rag_chain = (
|
| 74 |
{
|
| 75 |
"context": lambda x: format_docs(retriever.invoke(x["input"])),
|
|
@@ -81,134 +105,78 @@ rag_chain = (
|
|
| 81 |
)
|
| 82 |
|
| 83 |
# -------------------------------------------------------------------------
|
| 84 |
-
#
|
| 85 |
# -------------------------------------------------------------------------
|
| 86 |
-
def process_chat(message, history):
|
| 87 |
-
if not message.strip():
|
| 88 |
-
return "", history
|
| 89 |
-
|
| 90 |
-
if history is None:
|
| 91 |
-
history = []
|
| 92 |
-
|
| 93 |
-
try:
|
| 94 |
-
# Executes the RAG Chain
|
| 95 |
-
bot_response = rag_chain.invoke({"input": message})
|
| 96 |
-
|
| 97 |
-
except Exception as e:
|
| 98 |
-
# Gracefully handle HF timeout/wake-up errors instead of crashing the UI
|
| 99 |
-
bot_response = (
|
| 100 |
-
f"⚠️ **Connection Status:**\n\n"
|
| 101 |
-
f"`{str(e)}`\n\n"
|
| 102 |
-
f"**Note:** The Hugging Face inference model is currently waking up. This takes about 30-60 seconds. Please wait a moment and try sending your message again!"
|
| 103 |
-
)
|
| 104 |
-
|
| 105 |
-
history.append({"role": "user", "content": message})
|
| 106 |
-
history.append({"role": "assistant", "content": bot_response})
|
| 107 |
-
|
| 108 |
-
return "", history
|
| 109 |
-
|
| 110 |
-
def handle_quick_reply(button_text, history):
|
| 111 |
-
return process_chat(button_text, history)
|
| 112 |
-
|
| 113 |
-
# -------------------------------------------------------------------------
|
| 114 |
-
# 4. Gradio Web Interface Layout
|
| 115 |
-
# -------------------------------------------------------------------------
|
| 116 |
-
# Improved CSS: Explicitly setting foreground text colors to prevent invisible text in dark mode
|
| 117 |
custom_css = """
|
| 118 |
-
|
| 119 |
-
.
|
| 120 |
-
.
|
| 121 |
-
.
|
| 122 |
-
.sidebar-panel { background
|
| 123 |
-
.sidebar-panel p, .sidebar-panel h2 { color: white !important; }
|
| 124 |
-
.quick-btn { background-color: #f1f5f9 !important; border: 1px solid #cbd5e1 !important; color: #0f766e !important; font-weight: 600; }
|
| 125 |
-
.quick-btn:hover { background-color: #e2e8f0 !important; }
|
| 126 |
"""
|
| 127 |
|
| 128 |
-
# Native JS logic to toggle Gradio's standard dark mode class on the body
|
| 129 |
toggle_js = """
|
| 130 |
function() {
|
| 131 |
-
document.body
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
}
|
| 133 |
"""
|
| 134 |
|
| 135 |
-
|
|
|
|
|
|
|
| 136 |
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
# MAIN WORKSPACE SECTION
|
| 153 |
with gr.Row():
|
| 154 |
-
# Chat interface
|
| 155 |
with gr.Column(scale=4):
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
with gr.Row():
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
scale=5
|
| 166 |
-
)
|
| 167 |
-
submit_btn = gr.Button("Send", variant="primary", scale=1)
|
| 168 |
-
|
| 169 |
with gr.Row():
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
Processing Hardware: Base CPU Node
|
| 185 |
-
</p>
|
| 186 |
-
</div>
|
| 187 |
-
""")
|
| 188 |
-
|
| 189 |
-
# Event Wiring Architecture
|
| 190 |
-
submit_btn.click(
|
| 191 |
-
fn=process_chat,
|
| 192 |
-
inputs=[user_input, chatbot],
|
| 193 |
-
outputs=[user_input, chatbot]
|
| 194 |
-
)
|
| 195 |
-
user_input.submit(
|
| 196 |
-
fn=process_chat,
|
| 197 |
-
inputs=[user_input, chatbot],
|
| 198 |
-
outputs=[user_input, chatbot]
|
| 199 |
-
)
|
| 200 |
-
|
| 201 |
-
btn_refund.click(
|
| 202 |
-
fn=handle_quick_reply,
|
| 203 |
-
inputs=[btn_refund, chatbot],
|
| 204 |
-
outputs=[user_input, chatbot]
|
| 205 |
-
)
|
| 206 |
-
btn_cert.click(
|
| 207 |
-
fn=handle_quick_reply,
|
| 208 |
-
inputs=[btn_cert, chatbot],
|
| 209 |
-
outputs=[user_input, chatbot]
|
| 210 |
-
)
|
| 211 |
|
| 212 |
if __name__ == "__main__":
|
| 213 |
-
|
| 214 |
-
demo.launch(server_name="0.0.0.0", server_port=7860, css=custom_css, theme=gr.themes.Default())
|
|
|
|
| 3 |
import warnings
|
| 4 |
import gradio as gr
|
| 5 |
|
| 6 |
+
# Suppress deprecation warnings to keep Hugging Face logs clean
|
| 7 |
warnings.filterwarnings("ignore", category=UserWarning, module="langchain_community")
|
| 8 |
|
| 9 |
+
from langchain_community.vectorstores import Chroma
|
| 10 |
from langchain_huggingface import HuggingFaceEmbeddings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
from langchain_core.prompts import PromptTemplate
|
| 12 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 13 |
+
from langchain_core.runnables import RunnableLambda
|
| 14 |
+
from huggingface_hub import InferenceClient
|
| 15 |
|
| 16 |
+
# -------------------------------------------------------------------------
|
| 17 |
+
# 1. Fetching the Hugging Face Space security token
|
| 18 |
+
# -------------------------------------------------------------------------
|
| 19 |
hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
|
| 20 |
|
| 21 |
# -------------------------------------------------------------------------
|
| 22 |
+
# 2. Setup Vector Store & Embeddings Pipeline (Using ChromaDB)
|
| 23 |
# -------------------------------------------------------------------------
|
| 24 |
print("Loading semantic embedding vectors...")
|
| 25 |
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 26 |
|
| 27 |
+
# Simplilearn MOOC Domain-Specific FAQ Knowledge Base
|
| 28 |
simplilearn_faq_data = [
|
| 29 |
"Simplilearn Refund Policy: Learners are entitled to a full 100% refund within 7 days of course purchase, provided they have not accessed more than 25% of the unlocked asynchronous content or attended any live virtual cohort sessions.",
|
| 30 |
"Professional Certification Requirements: To unlock your official Simplilearn digital certificate, you must achieve a minimum score of 80% in the final course assessment and successfully submit all mandatory course projects.",
|
| 31 |
+
"Live Virtual Class Attendance: If a student misses an interactive live session, high-definition cloud recordings are automatically made available on the LMS portal within 4 hours of class conclusion.",
|
| 32 |
+
"Course Extension Requests: Students can request a one-time 14-day course access extension via the support portal, subject to approval if their cohort timeline has been disrupted by medical emergencies.",
|
| 33 |
+
"Job Guarantee Program Terms: The placement guarantee becomes valid only after successful completion of all capstone projects, maintaining 90% attendance across all live modules, and passing the mock interview clearing rounds."
|
| 34 |
]
|
| 35 |
|
| 36 |
+
# Check if Chroma database already exists to prevent duplicate loading
|
| 37 |
+
db_dir = "./chroma_db"
|
| 38 |
+
if not os.path.exists(db_dir):
|
| 39 |
+
print("Initializing vector store database...")
|
| 40 |
+
vectordb = Chroma.from_texts(simplilearn_faq_data, embeddings, persist_directory=db_dir)
|
| 41 |
+
else:
|
| 42 |
+
print("Loading existing vector store database...")
|
| 43 |
+
vectordb = Chroma(persist_directory=db_dir, embedding_function=embeddings)
|
| 44 |
+
|
| 45 |
+
retriever = vectordb.as_retriever(search_kwargs={"k": 2})
|
| 46 |
|
| 47 |
# -------------------------------------------------------------------------
|
| 48 |
+
# 3. Setup Native Hugging Face Interface (Bypasses Buggy Wrappers)
|
| 49 |
# -------------------------------------------------------------------------
|
| 50 |
print("Configuring LLM Interface...")
|
| 51 |
|
| 52 |
+
# Initialize the official native client; this natively handles the wait header correctly
|
| 53 |
+
client = InferenceClient(
|
| 54 |
+
model="mistralai/Mistral-7B-Instruct-v0.3",
|
| 55 |
+
token=hf_token,
|
| 56 |
+
headers={"X-Wait-For-Model": "true"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
)
|
| 58 |
|
| 59 |
+
def hf_llm_wrapper(prompt_value):
|
| 60 |
+
"""
|
| 61 |
+
Custom LangChain runnable that extracts the rendered string format of the prompt
|
| 62 |
+
and sends it straight to the official Hugging Face client.
|
| 63 |
+
"""
|
| 64 |
+
prompt_str = prompt_value.to_string()
|
| 65 |
+
|
| 66 |
+
# Clean, direct text generation call immune to LangChain package updates
|
| 67 |
+
response = client.text_generation(
|
| 68 |
+
prompt=prompt_str,
|
| 69 |
+
max_new_tokens=400,
|
| 70 |
+
temperature=0.3
|
| 71 |
+
)
|
| 72 |
+
return response
|
| 73 |
+
|
| 74 |
+
# Wrap our function into a reliable, chain-compatible component
|
| 75 |
+
chatModel = RunnableLambda(hf_llm_wrapper)
|
| 76 |
+
|
| 77 |
+
# -------------------------------------------------------------------------
|
| 78 |
+
# 4. Prompt Template and RAG Pipeline Assembly
|
| 79 |
+
# -------------------------------------------------------------------------
|
| 80 |
system_prompt = """You are the Simplilearn MOOC Support Agent, an advanced, polite, and professional AI learning assistant named Lane.
|
| 81 |
Answer the student's inquiry accurately using ONLY the retrieved context below.
|
| 82 |
If the answer cannot be found in the context, politely inform them that you only handle Simplilearn academic protocols and advise them to contact support@simplilearn.com.
|
|
|
|
| 93 |
def format_docs(docs):
|
| 94 |
return "\n\n".join(doc.page_content for doc in docs)
|
| 95 |
|
| 96 |
+
# Build out the operational RAG pipeline execution chain
|
| 97 |
rag_chain = (
|
| 98 |
{
|
| 99 |
"context": lambda x: format_docs(retriever.invoke(x["input"])),
|
|
|
|
| 105 |
)
|
| 106 |
|
| 107 |
# -------------------------------------------------------------------------
|
| 108 |
+
# 5. Build the Gradio Interface layout & interactions
|
| 109 |
# -------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
custom_css = """
|
| 111 |
+
body { background-color: #f4f6f9; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
|
| 112 |
+
.gradio-container { max-width: 950px !important; margin: 40px auto !important; box-shadow: 0 10px 25px rgba(0,0,0,0.05); border-radius: 12px; background: white; padding: 20px; }
|
| 113 |
+
.preset-btn { background-color: #eef2f7 !important; border: 1px solid #dcdfe6 !important; color: #409eff !important; font-weight: 500; transition: all 0.2s; border-radius: 6px; }
|
| 114 |
+
.preset-btn:hover { background-color: #409eff !important; color: white !important; }
|
| 115 |
+
.sidebar-panel { background: #fafafa; border-radius: 8px; padding: 15px; border: 1px solid #ebeef5; text-align: center; }
|
|
|
|
|
|
|
|
|
|
| 116 |
"""
|
| 117 |
|
|
|
|
| 118 |
toggle_js = """
|
| 119 |
function() {
|
| 120 |
+
const body = document.body;
|
| 121 |
+
if (body.classList.contains('dark')) {
|
| 122 |
+
body.classList.remove('dark');
|
| 123 |
+
} else {
|
| 124 |
+
body.classList.add('dark');
|
| 125 |
+
}
|
| 126 |
}
|
| 127 |
"""
|
| 128 |
|
| 129 |
+
def process_chat(user_message, chat_history):
|
| 130 |
+
if not user_message.strip():
|
| 131 |
+
return "", chat_history
|
| 132 |
|
| 133 |
+
try:
|
| 134 |
+
# Run the RAG pipeline execution flow
|
| 135 |
+
bot_response = rag_chain.invoke({"input": user_message})
|
| 136 |
+
except Exception as e:
|
| 137 |
+
bot_response = f"⚠️ Connection Status Error: {str(e)}\n\nPlease ensure your HF_TOKEN is valid and try again."
|
| 138 |
+
|
| 139 |
+
chat_history.append((user_message, bot_response))
|
| 140 |
+
return "", chat_history
|
| 141 |
+
|
| 142 |
+
def click_preset_button(btn_text, chat_history):
|
| 143 |
+
_, updated_history = process_chat(btn_text, chat_history)
|
| 144 |
+
return updated_history
|
| 145 |
+
|
| 146 |
+
with gr.Blocks(css=custom_css, title="Simplilearn FAQ Support Stream") as demo:
|
|
|
|
|
|
|
| 147 |
with gr.Row():
|
|
|
|
| 148 |
with gr.Column(scale=4):
|
| 149 |
+
gr.Markdown("# 🎓 Simplilearn Automated Helpdesk")
|
| 150 |
+
gr.Markdown("Welcome! Interact with **Lane**, your specialized academic assistance agent.")
|
| 151 |
+
with gr.Column(scale=1):
|
| 152 |
+
mode_btn = gr.Button("🌗 Change Mode (Day/Night)", variant="secondary")
|
| 153 |
+
mode_btn.click(fn=None, js=toggle_js)
|
| 154 |
+
|
| 155 |
+
gr.Markdown("<br>")
|
| 156 |
+
|
| 157 |
+
with gr.Row():
|
| 158 |
+
with gr.Column(scale=3):
|
| 159 |
+
chatbot = gr.Chatbot(label="Simplilearn FAQ Support Stream")
|
| 160 |
|
| 161 |
with gr.Row():
|
| 162 |
+
preset_refund = gr.Button("What is the course refund policy?", elem_classes=["preset-btn"])
|
| 163 |
+
preset_cert = gr.Button("How do I unlock my completion certificate?", elem_classes=["preset-btn"])
|
| 164 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
with gr.Row():
|
| 166 |
+
msg_input = gr.Textbox(
|
| 167 |
+
placeholder="Ask Lane anything regarding Simplilearn policies, bootcamps, or classes...",
|
| 168 |
+
show_label=False,
|
| 169 |
+
scale=9
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
with gr.Column(scale=1, elem_classes=["sidebar-panel"]):
|
| 173 |
+
gr.Markdown("## Lane AI")
|
| 174 |
+
gr.Markdown("### *Your Agentic Learning Assistant*")
|
| 175 |
+
gr.Markdown("<br>🎓<br><br>🛡️ **Secure Session Activated**<br>Operational Node: Simplilearn-Chroma-01<br>Processing Hardware: Base CPU Node")
|
| 176 |
+
|
| 177 |
+
msg_input.submit(process_chat, [msg_input, chatbot], [msg_input, chatbot])
|
| 178 |
+
preset_refund.click(fn=click_preset_button, inputs=[preset_refund, chatbot], outputs=[chatbot])
|
| 179 |
+
preset_cert.click(fn=click_preset_button, inputs=[preset_cert, chatbot], outputs=[chatbot])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
if __name__ == "__main__":
|
| 182 |
+
demo.launch()
|
|
|