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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import datetime
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
import gradio as gr
|
| 5 |
+
|
| 6 |
+
# LangChain & Chroma Vector DB Components
|
| 7 |
+
from langchain_chroma import Chroma
|
| 8 |
+
from langchain_huggingface import HuggingFaceEmbeddings, HuggingFaceEndpoint
|
| 9 |
+
from langchain_core.prompts import PromptTemplate
|
| 10 |
+
from langchain_core.runnables import RunnablePassthrough
|
| 11 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 12 |
+
|
| 13 |
+
# Load Environment Variables (HUGGINGFACEHUB_API_TOKEN)
|
| 14 |
+
load_dotenv()
|
| 15 |
+
|
| 16 |
+
# -------------------------------------------------------------------------
|
| 17 |
+
# 1. Mock Data Setup (Simplilearn MOOC FAQs)
|
| 18 |
+
# -------------------------------------------------------------------------
|
| 19 |
+
# In a full app, you would load these from a JSON or CSV text file.
|
| 20 |
+
faq_data = [
|
| 21 |
+
{
|
| 22 |
+
"question": "What is the refund policy for Simplilearn courses?",
|
| 23 |
+
"answer": "Simplilearn offers a 7-day money-back guarantee for its online self-paced learning and blended learning programs. Raise a refund request within 7 days of purchase, provided you haven't accessed more than 25% of the content."
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"question": "Can I access my Simplilearn courses on a smartphone?",
|
| 27 |
+
"answer": "Yes, Simplilearn has an official mobile app available on both Android and iOS platforms. You can download your video lessons to watch offline, complete quizzes, and track your learning progress on the go."
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"question": "Do I get a certificate after completing a course?",
|
| 31 |
+
"answer": "Yes, upon successfully fulfilling the course completion criteria (which typically includes finishing 85% of the course material and clearing the simulation projects/exams), you will receive an industry-recognized digital certificate."
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"question": "Are there any prerequisites for enrolling in the AI and ML Bootcamps?",
|
| 35 |
+
"answer": "While basic programming knowledge (preferably in Python) and a fundamental understanding of mathematics/statistics are helpful, Simplilearn's bootcamps include foundational electives to bring beginners up to speed."
|
| 36 |
+
}
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
# Extract text chunks and metadata for the Vector Database
|
| 40 |
+
documents = [item["answer"] for item in faq_data]
|
| 41 |
+
metadatas = [{"question": item["question"]} for item in faq_data]
|
| 42 |
+
ids = [f"faq_{i}" for i in range(len(faq_data))]
|
| 43 |
+
|
| 44 |
+
# -------------------------------------------------------------------------
|
| 45 |
+
# 2. RAG Pipeline Initialization (CPU-Optimized)
|
| 46 |
+
# -------------------------------------------------------------------------
|
| 47 |
+
# Initialize a lightweight, highly accurate sentence encoder for local CPU execution
|
| 48 |
+
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
|
| 49 |
+
|
| 50 |
+
# Create an in-memory Chroma DB Vector Store
|
| 51 |
+
vector_store = Chroma.from_texts(
|
| 52 |
+
texts=documents,
|
| 53 |
+
embedding=embeddings,
|
| 54 |
+
metadatas=metadatas,
|
| 55 |
+
ids=ids
|
| 56 |
+
)
|
| 57 |
+
retriever = vector_store.as_retriever(search_kwargs={"k": 2})
|
| 58 |
+
|
| 59 |
+
# Setup an Encoder-Decoder generative pipeline via Hugging Face Hosted Inference API
|
| 60 |
+
# Mistral-7B-Instruct handles complex reasoning over text efficiently without running locally
|
| 61 |
+
llm = HuggingFaceEndpoint(
|
| 62 |
+
repo_id="mistralai/Mistral-7B-Instruct-v0.3",
|
| 63 |
+
temperature=0.3,
|
| 64 |
+
max_new_tokens=256,
|
| 65 |
+
huggingfacehub_api_token=os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
# Explicitly craft a strict contextual RAG prompt template
|
| 69 |
+
prompt_template = """You are Lane, an intelligent, helpful, and friendly Agentic AI Assistant for Simplilearn MOOC.
|
| 70 |
+
Use the following pieces of retrieved context to answer the user's question accurately.
|
| 71 |
+
If you do not know the answer based on the context, politely state that you do not know.
|
| 72 |
+
|
| 73 |
+
Context:
|
| 74 |
+
{context}
|
| 75 |
+
|
| 76 |
+
Question: {question}
|
| 77 |
+
|
| 78 |
+
Helpful Answer:"""
|
| 79 |
+
|
| 80 |
+
rag_prompt = PromptTemplate.from_template(prompt_template)
|
| 81 |
+
|
| 82 |
+
# Build the complete LangChain Expression Language (LCEL) chain
|
| 83 |
+
def format_docs(docs):
|
| 84 |
+
return "\n\n".join(doc.page_content for doc in docs)
|
| 85 |
+
|
| 86 |
+
rag_chain = (
|
| 87 |
+
{"context": retriever | format_docs, "question": RunnablePassthrough()}
|
| 88 |
+
| rag_prompt
|
| 89 |
+
| llm
|
| 90 |
+
| StrOutputParser()
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# -------------------------------------------------------------------------
|
| 94 |
+
# 3. Application Core Logic
|
| 95 |
+
# -------------------------------------------------------------------------
|
| 96 |
+
def get_current_time_string():
|
| 97 |
+
"""Generates the localized timestamp format highlighted in the UI reference."""
|
| 98 |
+
now = datetime.datetime.now()
|
| 99 |
+
return now.strftime("%dth %B %Y | Time: %I:%M%p").lower()
|
| 100 |
+
|
| 101 |
+
def chat_interface(user_message, history):
|
| 102 |
+
"""Processes inbound user chat messages through the RAG framework."""
|
| 103 |
+
if not user_message.strip():
|
| 104 |
+
return "", history
|
| 105 |
+
|
| 106 |
+
# Process query through our tokenized encoder-decoder RAG architecture
|
| 107 |
+
ai_response = rag_chain.invoke(user_message)
|
| 108 |
+
|
| 109 |
+
# Update Gradio Chat history payload format
|
| 110 |
+
history.append({"role": "user", "content": user_message})
|
| 111 |
+
history.append({"role": "assistant", "content": ai_response})
|
| 112 |
+
|
| 113 |
+
return "", history
|
| 114 |
+
|
| 115 |
+
def handle_quick_reply(button_text, history):
|
| 116 |
+
"""Bypasses standard empty chat entries to process pre-baked suggestions instantly."""
|
| 117 |
+
return chat_interface(button_text, history)
|
| 118 |
+
|
| 119 |
+
# -------------------------------------------------------------------------
|
| 120 |
+
# 4. Gradio Web Interface Layout
|
| 121 |
+
# -------------------------------------------------------------------------
|
| 122 |
+
# Injecting custom CSS rules to strictly align font colors, themes, and container styles to your visual specs
|
| 123 |
+
custom_css = """
|
| 124 |
+
.header-container { background-color: #f7f9fc; padding: 20px; border-radius: 8px; margin-bottom: 15px; }
|
| 125 |
+
.meta-container { text-align: right; font-family: 'Georgia', serif; font-style: italic; color: #3b5998; }
|
| 126 |
+
.sidebar-panel { background-color: #004d40; color: white; padding: 25px; border-radius: 8px; text-align: center; height: 100%; }
|
| 127 |
+
.sidebar-panel img { border-radius: 50%; max-width: 150px; margin: 0 auto 15px auto; }
|
| 128 |
+
.quick-btn { background-color: #e0f2f1 !important; border: 1px solid #b2dfdb !important; color: #004d40 !important; font-weight: 600; }
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
with gr.Blocks(css=custom_css, title="Simplilearn MOOC FAQ Agent") as demo:
|
| 132 |
+
|
| 133 |
+
# TOP SECTION: Header banner split into Info Branding and Dynamic Meta Controls
|
| 134 |
+
with gr.Row(elem_classes=["header-container"]):
|
| 135 |
+
with gr.Column(scale=3):
|
| 136 |
+
gr.Markdown("""
|
| 137 |
+
# About Us
|
| 138 |
+
At Simplilearn Agentic Hub, we are passionate about the power of structured education and its ability
|
| 139 |
+
to transform careers. We are a leading knowledge processing framework dedicated to helping
|
| 140 |
+
learners unlock the full potential of specialized MOOC educational pathways.
|
| 141 |
+
""")
|
| 142 |
+
with gr.Column(scale=2, elem_classes=["meta-container"]):
|
| 143 |
+
# UI display showcasing timestamping and system state parameters
|
| 144 |
+
time_display = gr.Markdown(value=f"### {get_current_time_string()}")
|
| 145 |
+
gr.Markdown("### ☀️ 🌙 ➔ Change Mode (Day / Night)")
|
| 146 |
+
|
| 147 |
+
# MAIN SECTION: Split layout dividing Interactive Workspace from Identity Card
|
| 148 |
+
with gr.Row():
|
| 149 |
+
# Chat Canvas Engine
|
| 150 |
+
with gr.Column(scale=4):
|
| 151 |
+
chatbot = gr.Chatbot(
|
| 152 |
+
label="Lane AI Conversation",
|
| 153 |
+
type="messages",
|
| 154 |
+
value=[{"role": "assistant", "content": "Hello! I'm Lane, your friendly AI Agent. How can I help you today?"}]
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# Input Area
|
| 158 |
+
with gr.Row():
|
| 159 |
+
user_input = gr.Textbox(
|
| 160 |
+
show_label=False,
|
| 161 |
+
placeholder="Type your query regarding Simplilearn courses here...",
|
| 162 |
+
scale=5
|
| 163 |
+
)
|
| 164 |
+
submit_btn = gr.Button("Send", variant="primary", scale=1)
|
| 165 |
+
|
| 166 |
+
# Quick Reply Interaction Layer
|
| 167 |
+
with gr.Row():
|
| 168 |
+
btn_refund = gr.Button("Provide refund policy details", elem_classes=["quick-btn"])
|
| 169 |
+
btn_cert = gr.Button("Learn about course certification", elem_classes=["quick-btn"])
|
| 170 |
+
|
| 171 |
+
# Identity Profile Display Card
|
| 172 |
+
with gr.Column(scale=2, elem_classes=["sidebar-panel"]):
|
| 173 |
+
# Placeholder for Avatar matching the style from the mockup
|
| 174 |
+
gr.HTML("""
|
| 175 |
+
<div style='margin-top: 20px;'>
|
| 176 |
+
<img src='https://cdn-icons-png.flaticon.com/512/4712/4712010.png' alt='Lane Avatar' style='width:130px; height:130px; object-fit:cover; margin-bottom:15px; border: 4px solid #ffffff;'>
|
| 177 |
+
<h2 style='color: white; margin-bottom: 5px;'>Lane <span style='background-color:#ffffff; color:#004d40; padding:2px 6px; border-radius:4px; font-size:14px;'>AI</span></h2>
|
| 178 |
+
<p style='color: #e0f2f1; font-style: italic;'>Your Agentic AI Assistant</p>
|
| 179 |
+
<hr style='border-color: rgba(255,255,255,0.2); margin: 20px 0;'>
|
| 180 |
+
<p style='font-size: 14px; text-align: justify; color: #e0f2f1;'>
|
| 181 |
+
Lane runs an optimized RAG vector-space framework pipeline. It targets relevant local enterprise facts instantly without remote workflow friction.
|
| 182 |
+
</p>
|
| 183 |
+
</div>
|
| 184 |
+
""")
|
| 185 |
+
|
| 186 |
+
# -------------------------------------------------------------------------
|
| 187 |
+
# 5. Event Binding Pipeline Connections
|
| 188 |
+
# -------------------------------------------------------------------------
|
| 189 |
+
# Interactive workflow triggers for text submission
|
| 190 |
+
submit_btn.click(chat_interface, inputs=[user_input, chatbot], outputs=[user_input, chatbot])
|
| 191 |
+
user_input.submit(chat_interface, inputs=[user_input, chatbot], outputs=[user_input, chatbot])
|
| 192 |
+
|
| 193 |
+
# Event routing configuration mapping pre-configured quick buttons to context generation
|
| 194 |
+
btn_refund.click(handle_quick_reply, inputs=[btn_refund, chatbot], outputs=[user_input, chatbot])
|
| 195 |
+
btn_cert.click(handle_quick_reply, inputs=[btn_cert, chatbot], outputs=[user_input, chatbot])
|
| 196 |
+
|
| 197 |
+
# Run production runtime thread configuration
|
| 198 |
+
if __name__ == "__main__":
|
| 199 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|