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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -141
app.py CHANGED
@@ -3,57 +3,80 @@ import datetime
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
- # Load Environment Variables
19
- load_dotenv()
 
20
  hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
21
 
22
  # -------------------------------------------------------------------------
23
- # 1. Setup Vector Store & Embeddings Pipeline
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 processed and made available on the student LMS dashboard within 24 hours.",
32
- "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.",
33
- "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)."
34
  ]
35
 
36
- vectorstore = Chroma.from_texts(texts=simplilearn_faq_data, embedding=embeddings)
37
- retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 2})
 
 
 
 
 
 
 
 
38
 
39
  # -------------------------------------------------------------------------
40
- # 2. Setup Robust LLM Interface via OpenAI-Compatible Endpoint
41
  # -------------------------------------------------------------------------
42
  print("Configuring LLM Interface...")
43
 
44
- if not hf_token:
45
- print("⚠️ WARNING: HF_TOKEN is missing. The app will fail to generate responses.")
46
-
47
- # CORRECT CONFIGURATION: Pass cold-start directive via headers
48
- chatModel = HuggingFaceEndpoint(
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
- # Use a clean text template matching the non-chat model endpoint structure
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- # 3. Application Core Logic
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
- .header-container { background-color: #f0f4f8 !important; padding: 25px; border-radius: 12px; margin-bottom: 20px; border: 1px solid #e2e8f0; }
119
- .header-container h1, .header-container p { color: #0f172a !important; }
120
- .meta-container { text-align: right; font-family: 'Georgia', serif; font-style: italic; }
121
- .meta-container h3 { color: #334155 !important; margin: 4px 0; }
122
- .sidebar-panel { background-color: #0f766e !important; color: white !important; padding: 25px; border-radius: 12px; text-align: center; }
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.classList.toggle('dark');
 
 
 
 
 
132
  }
133
  """
134
 
135
- with gr.Blocks(title="Simplilearn MOOC FAQ Agent") as demo:
 
 
136
 
137
- # TOP HEADER SECTION
138
- with gr.Row(elem_classes=["header-container"]):
139
- with gr.Column(scale=3):
140
- gr.Markdown("""
141
- # About Us
142
- At Simplilearn Agentic Hub, we are passionate about the power of structured education and its ability
143
- to transform careers. We are a leading knowledge processing framework dedicated to helping
144
- learners unlock the full potential of specialized MOOC educational pathways.
145
- """)
146
- with gr.Column(scale=2, elem_classes=["meta-container"]):
147
- current_date = datetime.datetime.now().strftime("%dth %B %Y | Time: %I:%M%p").lower()
148
- gr.Markdown(f"### {current_date}")
149
- mode_btn = gr.Button("☀️ 🌙 ➔ Change Mode (Day / Night)", variant="secondary", size="sm")
150
- mode_btn.click(fn=None, js=toggle_js)
151
-
152
- # MAIN WORKSPACE SECTION
153
  with gr.Row():
154
- # Chat interface
155
  with gr.Column(scale=4):
156
- chatbot = gr.Chatbot(
157
- label="Lane AI Support Stream",
158
- value=[{"role": "assistant", "content": "Hello! I'm Lane, your Simplilearn Support Agent. How can I assist you with your courses today?"}]
159
- )
 
 
 
 
 
 
 
160
 
161
  with gr.Row():
162
- user_input = gr.Textbox(
163
- show_label=False,
164
- placeholder="Ask Lane anything regarding Simplilearn policies...",
165
- scale=5
166
- )
167
- submit_btn = gr.Button("Send", variant="primary", scale=1)
168
-
169
  with gr.Row():
170
- btn_refund = gr.Button("What is the course refund policy?", elem_classes=["quick-btn"])
171
- btn_cert = gr.Button("How do I unlock my completion certificate?", elem_classes=["quick-btn"])
172
-
173
- # Agent Sidebar Identity
174
- with gr.Column(scale=2, elem_classes=["sidebar-panel"]):
175
- gr.HTML("""
176
- <div style='margin-top: 10px;'>
177
- <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;'>
178
- <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>
179
- <p style='font-style: italic; opacity: 0.9; margin-bottom: 15px;'>Your Agentic Learning Assistant</p>
180
- <hr style='border-color: rgba(255,255,255,0.2); margin: 15px 0;'>
181
- <p style='font-size: 14px; text-align: left; line-height: 1.5; opacity: 0.95;'>
182
- 🎓 <b>Secure Session Activated</b><br>
183
- Operational Node: Simplilearn-Chroma-01<br>
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
- # Launch with Gradio's Default theme to ensure dark/light mode hooks exist natively
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()