Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -16,7 +16,6 @@ load_dotenv()
|
|
| 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?",
|
|
@@ -36,7 +35,6 @@ faq_data = [
|
|
| 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))]
|
|
@@ -44,10 +42,8 @@ ids = [f"faq_{i}" for i in range(len(faq_data))]
|
|
| 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,
|
|
@@ -56,8 +52,6 @@ vector_store = Chroma.from_texts(
|
|
| 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,
|
|
@@ -65,7 +59,6 @@ llm = HuggingFaceEndpoint(
|
|
| 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.
|
|
@@ -79,7 +72,6 @@ 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 |
|
|
@@ -94,32 +86,28 @@ rag_chain = (
|
|
| 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 |
-
#
|
| 107 |
ai_response = rag_chain.invoke(user_message)
|
| 108 |
|
| 109 |
-
#
|
| 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; }
|
|
@@ -128,9 +116,10 @@ custom_css = """
|
|
| 128 |
.quick-btn { background-color: #e0f2f1 !important; border: 1px solid #b2dfdb !important; color: #004d40 !important; font-weight: 600; }
|
| 129 |
"""
|
| 130 |
|
| 131 |
-
|
|
|
|
| 132 |
|
| 133 |
-
# TOP SECTION
|
| 134 |
with gr.Row(elem_classes=["header-container"]):
|
| 135 |
with gr.Column(scale=3):
|
| 136 |
gr.Markdown("""
|
|
@@ -140,21 +129,18 @@ with gr.Blocks(css=custom_css, title="Simplilearn MOOC FAQ Agent") as demo:
|
|
| 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
|
| 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,
|
|
@@ -163,14 +149,12 @@ with gr.Blocks(css=custom_css, title="Simplilearn MOOC FAQ Agent") as demo:
|
|
| 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 |
-
#
|
| 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;'>
|
|
@@ -183,17 +167,14 @@ with gr.Blocks(css=custom_css, title="Simplilearn MOOC FAQ Agent") as demo:
|
|
| 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
|
| 198 |
if __name__ == "__main__":
|
| 199 |
-
|
|
|
|
|
|
| 16 |
# -------------------------------------------------------------------------
|
| 17 |
# 1. Mock Data Setup (Simplilearn MOOC FAQs)
|
| 18 |
# -------------------------------------------------------------------------
|
|
|
|
| 19 |
faq_data = [
|
| 20 |
{
|
| 21 |
"question": "What is the refund policy for Simplilearn courses?",
|
|
|
|
| 35 |
}
|
| 36 |
]
|
| 37 |
|
|
|
|
| 38 |
documents = [item["answer"] for item in faq_data]
|
| 39 |
metadatas = [{"question": item["question"]} for item in faq_data]
|
| 40 |
ids = [f"faq_{i}" for i in range(len(faq_data))]
|
|
|
|
| 42 |
# -------------------------------------------------------------------------
|
| 43 |
# 2. RAG Pipeline Initialization (CPU-Optimized)
|
| 44 |
# -------------------------------------------------------------------------
|
|
|
|
| 45 |
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
|
| 46 |
|
|
|
|
| 47 |
vector_store = Chroma.from_texts(
|
| 48 |
texts=documents,
|
| 49 |
embedding=embeddings,
|
|
|
|
| 52 |
)
|
| 53 |
retriever = vector_store.as_retriever(search_kwargs={"k": 2})
|
| 54 |
|
|
|
|
|
|
|
| 55 |
llm = HuggingFaceEndpoint(
|
| 56 |
repo_id="mistralai/Mistral-7B-Instruct-v0.3",
|
| 57 |
temperature=0.3,
|
|
|
|
| 59 |
huggingfacehub_api_token=os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 60 |
)
|
| 61 |
|
|
|
|
| 62 |
prompt_template = """You are Lane, an intelligent, helpful, and friendly Agentic AI Assistant for Simplilearn MOOC.
|
| 63 |
Use the following pieces of retrieved context to answer the user's question accurately.
|
| 64 |
If you do not know the answer based on the context, politely state that you do not know.
|
|
|
|
| 72 |
|
| 73 |
rag_prompt = PromptTemplate.from_template(prompt_template)
|
| 74 |
|
|
|
|
| 75 |
def format_docs(docs):
|
| 76 |
return "\n\n".join(doc.page_content for doc in docs)
|
| 77 |
|
|
|
|
| 86 |
# 3. Application Core Logic
|
| 87 |
# -------------------------------------------------------------------------
|
| 88 |
def get_current_time_string():
|
|
|
|
| 89 |
now = datetime.datetime.now()
|
| 90 |
return now.strftime("%dth %B %Y | Time: %I:%M%p").lower()
|
| 91 |
|
| 92 |
def chat_interface(user_message, history):
|
|
|
|
| 93 |
if not user_message.strip():
|
| 94 |
return "", history
|
| 95 |
|
| 96 |
+
# Generate RAG response
|
| 97 |
ai_response = rag_chain.invoke(user_message)
|
| 98 |
|
| 99 |
+
# Append structured history dictionary mapping (Gradio 5/6 standard native format)
|
| 100 |
history.append({"role": "user", "content": user_message})
|
| 101 |
history.append({"role": "assistant", "content": ai_response})
|
| 102 |
|
| 103 |
return "", history
|
| 104 |
|
| 105 |
def handle_quick_reply(button_text, history):
|
|
|
|
| 106 |
return chat_interface(button_text, history)
|
| 107 |
|
| 108 |
# -------------------------------------------------------------------------
|
| 109 |
# 4. Gradio Web Interface Layout
|
| 110 |
# -------------------------------------------------------------------------
|
|
|
|
| 111 |
custom_css = """
|
| 112 |
.header-container { background-color: #f7f9fc; padding: 20px; border-radius: 8px; margin-bottom: 15px; }
|
| 113 |
.meta-container { text-align: right; font-family: 'Georgia', serif; font-style: italic; color: #3b5998; }
|
|
|
|
| 116 |
.quick-btn { background-color: #e0f2f1 !important; border: 1px solid #b2dfdb !important; color: #004d40 !important; font-weight: 600; }
|
| 117 |
"""
|
| 118 |
|
| 119 |
+
# Fixed: Removed 'css' parameter from constructor to satisfy Gradio 6 specifications
|
| 120 |
+
with gr.Blocks(title="Simplilearn MOOC FAQ Agent") as demo:
|
| 121 |
|
| 122 |
+
# TOP SECTION
|
| 123 |
with gr.Row(elem_classes=["header-container"]):
|
| 124 |
with gr.Column(scale=3):
|
| 125 |
gr.Markdown("""
|
|
|
|
| 129 |
learners unlock the full potential of specialized MOOC educational pathways.
|
| 130 |
""")
|
| 131 |
with gr.Column(scale=2, elem_classes=["meta-container"]):
|
|
|
|
| 132 |
time_display = gr.Markdown(value=f"### {get_current_time_string()}")
|
| 133 |
gr.Markdown("### ☀️ 🌙 ➔ Change Mode (Day / Night)")
|
| 134 |
|
| 135 |
+
# MAIN ROW SECTION
|
| 136 |
with gr.Row():
|
|
|
|
| 137 |
with gr.Column(scale=4):
|
| 138 |
+
# Fixed: Removed 'type="messages"' parameter since it's now default
|
| 139 |
chatbot = gr.Chatbot(
|
| 140 |
label="Lane AI Conversation",
|
|
|
|
| 141 |
value=[{"role": "assistant", "content": "Hello! I'm Lane, your friendly AI Agent. How can I help you today?"}]
|
| 142 |
)
|
| 143 |
|
|
|
|
| 144 |
with gr.Row():
|
| 145 |
user_input = gr.Textbox(
|
| 146 |
show_label=False,
|
|
|
|
| 149 |
)
|
| 150 |
submit_btn = gr.Button("Send", variant="primary", scale=1)
|
| 151 |
|
|
|
|
| 152 |
with gr.Row():
|
| 153 |
btn_refund = gr.Button("Provide refund policy details", elem_classes=["quick-btn"])
|
| 154 |
btn_cert = gr.Button("Learn about course certification", elem_classes=["quick-btn"])
|
| 155 |
|
| 156 |
+
# RIGHT SIDEBAR PANEL
|
| 157 |
with gr.Column(scale=2, elem_classes=["sidebar-panel"]):
|
|
|
|
| 158 |
gr.HTML("""
|
| 159 |
<div style='margin-top: 20px;'>
|
| 160 |
<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;'>
|
|
|
|
| 167 |
</div>
|
| 168 |
""")
|
| 169 |
|
| 170 |
+
# Event Connections
|
|
|
|
|
|
|
|
|
|
| 171 |
submit_btn.click(chat_interface, inputs=[user_input, chatbot], outputs=[user_input, chatbot])
|
| 172 |
user_input.submit(chat_interface, inputs=[user_input, chatbot], outputs=[user_input, chatbot])
|
| 173 |
|
|
|
|
| 174 |
btn_refund.click(handle_quick_reply, inputs=[btn_refund, chatbot], outputs=[user_input, chatbot])
|
| 175 |
btn_cert.click(handle_quick_reply, inputs=[btn_cert, chatbot], outputs=[user_input, chatbot])
|
| 176 |
|
| 177 |
+
# Run configuration
|
| 178 |
if __name__ == "__main__":
|
| 179 |
+
# Fixed: Injected custom_css string here inside the launch method call to silence user warnings
|
| 180 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, css=custom_css)
|