VectorV17 commited on
Commit
a6e2103
·
verified ·
1 Parent(s): 72b125b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -109
app.py CHANGED
@@ -3,80 +3,59 @@ import datetime
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,7 +72,6 @@ prompt = PromptTemplate.from_template(system_prompt)
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,78 +83,134 @@ rag_chain = (
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()
 
 
3
  import warnings
4
  import gradio as gr
5
 
6
+ # Suppress deprecation warnings for a cleaner console
7
  warnings.filterwarnings("ignore", category=UserWarning, module="langchain_community")
8
 
9
+ from langchain_chroma import Chroma
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
+ # Load Environment Variables
20
+ load_dotenv()
21
  hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
22
 
23
  # -------------------------------------------------------------------------
24
+ # 1. Setup Vector Store & Embeddings Pipeline
25
  # -------------------------------------------------------------------------
26
  print("Loading semantic embedding vectors...")
27
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
28
 
 
29
  simplilearn_faq_data = [
30
  "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.",
31
  "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.",
32
+ "Live Virtual Class Attendance: If a student misses an interactive live session, high-definition cloud recordings are automatically processed and made available on the student LMS dashboard within 24 hours.",
33
+ "Technical Support Availability: Technical assistance for cloud labs, environment resets, or workspace access is available 24/7. Students can raise a ticket via the 'Help and Support' tab or email support@simplilearn.com.",
34
+ "Data Science Bootcamp Prerequisites: This flagship program spans 6 months. It requires basic exposure to high-school level mathematics and rudimentary programming logic (Python familiarity is highly recommended but not mandatory)."
35
  ]
36
 
37
+ vectorstore = Chroma.from_texts(texts=simplilearn_faq_data, embedding=embeddings)
38
+ retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 2})
 
 
 
 
 
 
 
 
39
 
40
  # -------------------------------------------------------------------------
41
+ # 2. Setup Robust LLM Interface via OpenAI-Compatible Endpoint
42
  # -------------------------------------------------------------------------
 
43
 
44
+ print("Configuring LLM Interface...")
 
 
 
 
 
45
 
46
+ if not hf_token:
47
+ print("⚠️ WARNING: HF_TOKEN is missing. The app will fail to generate responses.")
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ # CORRECT CONFIGURATION: Pass cold-start directive via headers
50
+ chatModel = HuggingFaceEndpoint(
51
+ repo_id="mistralai/Mistral-7B-Instruct-v0.3",
52
+ huggingfacehub_api_token=hf_token,
53
+ temperature=0.3,
54
+ max_new_tokens=400,
55
+ headers={"X-Wait-For-Model": "true"} # Fixes the TypeError and handles cold starts gracefully
56
+ )
57
 
58
+ # Use a clean text template matching the non-chat model endpoint structure
 
 
59
  system_prompt = """You are the Simplilearn MOOC Support Agent, an advanced, polite, and professional AI learning assistant named Lane.
60
  Answer the student's inquiry accurately using ONLY the retrieved context below.
61
  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.
 
72
  def format_docs(docs):
73
  return "\n\n".join(doc.page_content for doc in docs)
74
 
 
75
  rag_chain = (
76
  {
77
  "context": lambda x: format_docs(retriever.invoke(x["input"])),
 
83
  )
84
 
85
  # -------------------------------------------------------------------------
86
+ # 3. Application Core Logic
87
+ # -------------------------------------------------------------------------
88
+ def process_chat(message, history):
89
+ if not message.strip():
90
+ return "", history
91
+
92
+ if history is None:
93
+ history = []
94
+
95
+ try:
96
+ # Executes the RAG Chain
97
+ bot_response = rag_chain.invoke({"input": message})
98
+
99
+ except Exception as e:
100
+ # Gracefully handle HF timeout/wake-up errors instead of crashing the UI
101
+ bot_response = (
102
+ f"⚠️ **Connection Status:**\n\n"
103
+ f"`{str(e)}`\n\n"
104
+ 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!"
105
+ )
106
+
107
+ history.append({"role": "user", "content": message})
108
+ history.append({"role": "assistant", "content": bot_response})
109
+
110
+ return "", history
111
+
112
+ def handle_quick_reply(button_text, history):
113
+ return process_chat(button_text, history)
114
+
115
+ # -------------------------------------------------------------------------
116
+ # 4. Gradio Web Interface Layout
117
  # -------------------------------------------------------------------------
118
+ # Improved CSS: Explicitly setting foreground text colors to prevent invisible text in dark mode
119
  custom_css = """
120
+ .header-container { background-color: #f0f4f8 !important; padding: 25px; border-radius: 12px; margin-bottom: 20px; border: 1px solid #e2e8f0; }
121
+ .header-container h1, .header-container p { color: #0f172a !important; }
122
+ .meta-container { text-align: right; font-family: 'Georgia', serif; font-style: italic; }
123
+ .meta-container h3 { color: #334155 !important; margin: 4px 0; }
124
+ .sidebar-panel { background-color: #0f766e !important; color: white !important; padding: 25px; border-radius: 12px; text-align: center; }
125
+ .sidebar-panel p, .sidebar-panel h2 { color: white !important; }
126
+ .quick-btn { background-color: #f1f5f9 !important; border: 1px solid #cbd5e1 !important; color: #0f766e !important; font-weight: 600; }
127
+ .quick-btn:hover { background-color: #e2e8f0 !important; }
128
  """
129
 
130
+ # Native JS logic to toggle Gradio's standard dark mode class on the body
131
  toggle_js = """
132
  function() {
133
+ document.body.classList.toggle('dark');
 
 
 
 
 
134
  }
135
  """
136
 
137
+ with gr.Blocks(title="Simplilearn MOOC FAQ Agent") as demo:
 
 
138
 
139
+ # TOP HEADER SECTION
140
+ with gr.Row(elem_classes=["header-container"]):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  with gr.Column(scale=3):
142
+ gr.Markdown("""
143
+ # About Us
144
+ At Simplilearn Agentic Hub, we are passionate about the power of structured education and its ability
145
+ to transform careers. We are a leading knowledge processing framework dedicated to helping
146
+ learners unlock the full potential of specialized MOOC educational pathways.
147
+ """)
148
+ with gr.Column(scale=2, elem_classes=["meta-container"]):
149
+ current_date = datetime.datetime.now().strftime("%dth %B %Y | Time: %I:%M%p").lower()
150
+ gr.Markdown(f"### {current_date}")
151
+ mode_btn = gr.Button("☀️ 🌙 ➔ Change Mode (Day / Night)", variant="secondary", size="sm")
152
+ mode_btn.click(fn=None, js=toggle_js)
153
 
154
+ # MAIN WORKSPACE SECTION
155
+ with gr.Row():
156
+ # Chat interface
157
+ with gr.Column(scale=4):
158
+ chatbot = gr.Chatbot(
159
+ label="Lane AI Support Stream",
160
+ value=[{"role": "assistant", "content": "Hello! I'm Lane, your Simplilearn Support Agent. How can I assist you with your courses today?"}]
161
+ )
162
 
163
  with gr.Row():
164
+ user_input = gr.Textbox(
165
+ show_label=False,
166
+ placeholder="Ask Lane anything regarding Simplilearn policies...",
167
+ scale=5
168
  )
169
+ submit_btn = gr.Button("Send", variant="primary", scale=1)
170
+
171
+ with gr.Row():
172
+ btn_refund = gr.Button("What is the course refund policy?", elem_classes=["quick-btn"])
173
+ btn_cert = gr.Button("How do I unlock my completion certificate?", elem_classes=["quick-btn"])
174
+
175
+ # Agent Sidebar Identity
176
+ with gr.Column(scale=2, elem_classes=["sidebar-panel"]):
177
+ gr.HTML("""
178
+ <div style='margin-top: 10px;'>
179
+ <img src='https://cdn-icons-png.flaticon.com/512/4712/4712010.png' alt='Lane Avatar' style='width:120px; height:120px; object-fit:cover; margin:0 auto 15px auto; border: 4px solid #ffffff; border-radius: 50%; background-color: white;'>
180
+ <h2 style='margin-bottom: 5px; font-size: 24px; font-weight: bold;'>Lane <span style='background-color:#ffffff; color:#0f766e; padding:2px 8px; border-radius:4px; font-size:14px; vertical-align: middle;'>AI</span></h2>
181
+ <p style='font-style: italic; opacity: 0.9; margin-bottom: 15px;'>Your Agentic Learning Assistant</p>
182
+ <hr style='border-color: rgba(255,255,255,0.2); margin: 15px 0;'>
183
+ <p style='font-size: 14px; text-align: left; line-height: 1.5; opacity: 0.95;'>
184
+ 🎓 <b>Secure Session Activated</b><br>
185
+ Operational Node: Simplilearn-Chroma-01<br>
186
+ Processing Hardware: Base CPU Node
187
+ </p>
188
+ </div>
189
+ """)
190
+
191
+ # Event Wiring Architecture
192
+ submit_btn.click(
193
+ fn=process_chat,
194
+ inputs=[user_input, chatbot],
195
+ outputs=[user_input, chatbot]
196
+ )
197
+ user_input.submit(
198
+ fn=process_chat,
199
+ inputs=[user_input, chatbot],
200
+ outputs=[user_input, chatbot]
201
+ )
202
+
203
+ btn_refund.click(
204
+ fn=handle_quick_reply,
205
+ inputs=[btn_refund, chatbot],
206
+ outputs=[user_input, chatbot]
207
+ )
208
+ btn_cert.click(
209
+ fn=handle_quick_reply,
210
+ inputs=[btn_cert, chatbot],
211
+ outputs=[user_input, chatbot]
212
+ )
213
 
214
  if __name__ == "__main__":
215
+ # Launch with Gradio's Default theme to ensure dark/light mode hooks exist natively
216
+ demo.launch(server_name="0.0.0.0", server_port=7860, css=custom_css, theme=gr.themes.Default())