VectorV17 commited on
Commit
9b75448
·
verified ·
1 Parent(s): 1a04684

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -43
app.py CHANGED
@@ -3,16 +3,15 @@ import datetime
3
  import warnings
4
  import gradio as gr
5
 
6
- # Suppress the community sunset 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, HuggingFaceEndpoint
11
- from langchain_core.prompts import ChatPromptTemplate
12
- from langchain_core.runnables import RunnablePassthrough
13
  from langchain_core.output_parsers import StrOutputParser
14
 
15
- # 1. Fetching the Hugging Face Space security token automatically
16
  hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
17
 
18
  # 2. Setup Vector Store & Embeddings Pipeline (Using ChromaDB)
@@ -28,43 +27,43 @@ simplilearn_faq_data = [
28
  "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)."
29
  ]
30
 
31
- # Create an in-memory Chroma instance to run seamlessly on a basic CPU space
32
  vectorstore = Chroma.from_texts(texts=simplilearn_faq_data, embedding=embeddings)
33
  retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 2})
34
 
35
  # 3. Setup Low Parameter Open-Source LLM Generator via Serverless API
36
  print("Configuring LLM Interface...")
37
  chatModel = HuggingFaceEndpoint(
38
- repo_id="Qwen/Qwen2.5-1.5B-Instruct", # Using low-parameter model to bypass quota limitations
39
  task="text-generation",
40
- max_new_tokens=500, # Expanded token limits to allow descriptive paragraphs
41
- temperature=0.4, # Strictly low to prevent hallucination/falsification
42
  do_sample=False,
43
  huggingfacehub_api_token=hf_token
44
  )
45
 
46
- # 4. Constructing the Chain using LCEL (Eliminates dependency on langchain.chains)
47
- system_prompt = (
48
- "You are the Simplilearn MOOC Support Agent, an advanced, polite, and professional AI learning assistant named Lane. "
49
- "Answer the student's inquiry accurately using ONLY the retrieved context below. "
50
- "If the answer cannot be found in the context or if the user asks an unrelated question (like general medical advice), "
51
- "politely inform them that your system partition handles only Simplilearn academic protocols and advise them to "
52
- "contact support@simplilearn.com for official assistance.\n\n"
53
- "Context:\n{context}"
54
- )
 
 
 
 
55
 
56
- prompt = ChatPromptTemplate.from_messages(
57
- [
58
- ("system", system_prompt),
59
- ("human", "{input}"),
60
- ]
61
- )
62
 
63
- # Helper function to combine document chunks into a single string context
64
  def format_docs(docs):
65
  return "\n\n".join(doc.page_content for doc in docs)
66
 
67
- # The modern LCEL pipeline equivalent to your original create_retrieval_chain
68
  rag_chain = (
69
  {
70
  "context": lambda x: format_docs(retriever.invoke(x["input"])),
@@ -75,7 +74,7 @@ rag_chain = (
75
  | StrOutputParser()
76
  )
77
 
78
- # 5. UI Event Handlers (Gradio 6.0 Dict-based message history format)
79
  def process_chat(message, history):
80
  if not message.strip():
81
  return "", history
@@ -84,25 +83,31 @@ def process_chat(message, history):
84
  history = []
85
 
86
  try:
87
- # Executes using your exact original dictionary key pattern: {"input": msg}
88
  bot_response = rag_chain.invoke({"input": message})
 
 
 
 
89
  except Exception as e:
 
90
  bot_response = (
91
- f"Hello! I encountered a service communication constraint while processing your request. "
92
- f"Local node logs: Completed processing inquiry for '{message}'."
 
 
93
  )
94
 
95
- # Appending messages via the mandatory Gradio 6.x specification
96
  history.append({"role": "user", "content": message})
97
  history.append({"role": "assistant", "content": bot_response})
98
  return "", history
99
 
100
- # Handles automatic prompt submission when clicking dashboard quick-action buttons
101
  def click_preset_button(button_text, history):
102
  _, updated_history = process_chat(button_text, history)
103
  return updated_history
104
 
105
- # 6. Custom CSS UI Styling matching your layout template
106
  custom_css = """
107
  .dashboard-container { background: linear-gradient(135deg, #e1f5fe 0%, #e8f5e9 100%); padding: 20px; border-radius: 12px; min-height: 100vh; }
108
  .about-section { background-color: #002f6c; color: white; padding: 25px; border-radius: 8px; }
@@ -112,7 +117,6 @@ custom_css = """
112
  .preset-btn { background-color: #e0f7fa !important; border: 1px solid #b2ebf2 !important; color: #006064 !important; font-weight: 600; }
113
  """
114
 
115
- # Client-side JavaScript execution string for instant Day/Night toggles
116
  toggle_js = """
117
  function() {
118
  var body = document.querySelector('body');
@@ -124,10 +128,9 @@ function() {
124
  }
125
  """
126
 
127
- # 7. Building the Visual Workspace Layout (Matching Screenshot Setup)
128
  with gr.Blocks(elem_classes=["dashboard-container"]) as demo:
129
 
130
- # Header Row: About Us Introduction & Live Clock/Theme Controller
131
  with gr.Row():
132
  with gr.Column(scale=2, elem_classes=["about-section"]):
133
  gr.Markdown("<div class='about-title'>About Us</div>")
@@ -145,13 +148,10 @@ with gr.Blocks(elem_classes=["dashboard-container"]) as demo:
145
 
146
  gr.Markdown("<br>")
147
 
148
- # Main Core Interface Workspace Row
149
  with gr.Row():
150
- # Chat Framework Engine
151
  with gr.Column(scale=3):
152
  chatbot = gr.Chatbot(label="Simplilearn FAQ Support Stream")
153
 
154
- # Interactive Quick-Action Buttons Layout (Realigned to Simplilearn Scope)
155
  with gr.Row():
156
  preset_refund = gr.Button("What is the course refund policy?", elem_classes=["preset-btn"])
157
  preset_cert = gr.Button("How do I unlock my completion certificate?", elem_classes=["preset-btn"])
@@ -163,19 +163,14 @@ with gr.Blocks(elem_classes=["dashboard-container"]) as demo:
163
  scale=9
164
  )
165
 
166
- # Sidebar Status Panel
167
  with gr.Column(scale=1, elem_classes=["sidebar-panel"]):
168
  gr.Markdown("## Lane AI")
169
  gr.Markdown("### *Your Agentic Learning Assistant*")
170
  gr.Markdown("<br>🎓<br><br>🛡️ **Secure Session Activated**<br>Operational Node: Simplilearn-Chroma-01<br>Processing Hardware: Base CPU Node")
171
 
172
- # Mapping event listeners
173
  msg_input.submit(process_chat, [msg_input, chatbot], [msg_input, chatbot])
174
-
175
- # Mapping quick-action click handlers
176
  preset_refund.click(fn=click_preset_button, inputs=[preset_refund, chatbot], outputs=[chatbot])
177
  preset_cert.click(fn=click_preset_button, inputs=[preset_cert, chatbot], outputs=[chatbot])
178
 
179
- # 8. Launching the interface with Gradio 6.0 parameters
180
  if __name__ == "__main__":
181
  demo.launch(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, HuggingFaceEndpoint
11
+ from langchain_core.prompts import PromptTemplate
 
12
  from langchain_core.output_parsers import StrOutputParser
13
 
14
+ # 1. Fetching the Hugging Face Space security token
15
  hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
16
 
17
  # 2. Setup Vector Store & Embeddings Pipeline (Using ChromaDB)
 
27
  "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)."
28
  ]
29
 
30
+ # Create an in-memory Chroma instance
31
  vectorstore = Chroma.from_texts(texts=simplilearn_faq_data, embedding=embeddings)
32
  retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 2})
33
 
34
  # 3. Setup Low Parameter Open-Source LLM Generator via Serverless API
35
  print("Configuring LLM Interface...")
36
  chatModel = HuggingFaceEndpoint(
37
+ repo_id="Qwen/Qwen2.5-1.5B-Instruct",
38
  task="text-generation",
39
+ max_new_tokens=500,
40
+ temperature=0.3,
41
  do_sample=False,
42
  huggingfacehub_api_token=hf_token
43
  )
44
 
45
+ # 4. Constructing the Chain using standard PromptTemplate (Fixes Data Type Error for Qwen)
46
+ # We use Qwen's native ChatML tags so the model understands System/User/Assistant roles
47
+ template = """<|im_start|>system
48
+ You are the Simplilearn MOOC Support Agent, an advanced, polite, and professional AI learning assistant named Lane.
49
+ Answer the student's inquiry accurately using ONLY the retrieved context below.
50
+ 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.
51
+
52
+ Context:
53
+ {context}<|im_end|>
54
+ <|im_start|>user
55
+ {input}<|im_end|>
56
+ <|im_start|>assistant
57
+ """
58
 
59
+ # Switched from ChatPromptTemplate to standard PromptTemplate
60
+ prompt = PromptTemplate.from_template(template)
 
 
 
 
61
 
62
+ # Helper function to combine document chunks
63
  def format_docs(docs):
64
  return "\n\n".join(doc.page_content for doc in docs)
65
 
66
+ # The modern LCEL pipeline
67
  rag_chain = (
68
  {
69
  "context": lambda x: format_docs(retriever.invoke(x["input"])),
 
74
  | StrOutputParser()
75
  )
76
 
77
+ # 5. UI Event Handlers
78
  def process_chat(message, history):
79
  if not message.strip():
80
  return "", history
 
83
  history = []
84
 
85
  try:
86
+ # Executes the RAG Chain
87
  bot_response = rag_chain.invoke({"input": message})
88
+
89
+ # Clean up the response if Qwen accidentally prints the stop tokens
90
+ bot_response = bot_response.replace("<|im_end|>", "").strip()
91
+
92
  except Exception as e:
93
+ # NOW WE SHOW THE ACTUAL ERROR ON SCREEN!
94
  bot_response = (
95
+ f"⚠️ **Server/API Error Encountered:**\n\n"
96
+ f"`{str(e)}`\n\n"
97
+ f"**Fix required:** If it says '401 Unauthorized', you must go to your Space **Settings -> Variables and secrets** "
98
+ f"and add a New Secret named `HF_TOKEN` containing your Hugging Face Access Token."
99
  )
100
 
101
+ # Appending messages via Gradio 6.x specification
102
  history.append({"role": "user", "content": message})
103
  history.append({"role": "assistant", "content": bot_response})
104
  return "", history
105
 
 
106
  def click_preset_button(button_text, history):
107
  _, updated_history = process_chat(button_text, history)
108
  return updated_history
109
 
110
+ # 6. Custom CSS UI Styling
111
  custom_css = """
112
  .dashboard-container { background: linear-gradient(135deg, #e1f5fe 0%, #e8f5e9 100%); padding: 20px; border-radius: 12px; min-height: 100vh; }
113
  .about-section { background-color: #002f6c; color: white; padding: 25px; border-radius: 8px; }
 
117
  .preset-btn { background-color: #e0f7fa !important; border: 1px solid #b2ebf2 !important; color: #006064 !important; font-weight: 600; }
118
  """
119
 
 
120
  toggle_js = """
121
  function() {
122
  var body = document.querySelector('body');
 
128
  }
129
  """
130
 
131
+ # 7. Building the Visual Workspace Layout
132
  with gr.Blocks(elem_classes=["dashboard-container"]) as demo:
133
 
 
134
  with gr.Row():
135
  with gr.Column(scale=2, elem_classes=["about-section"]):
136
  gr.Markdown("<div class='about-title'>About Us</div>")
 
148
 
149
  gr.Markdown("<br>")
150
 
 
151
  with gr.Row():
 
152
  with gr.Column(scale=3):
153
  chatbot = gr.Chatbot(label="Simplilearn FAQ Support Stream")
154
 
 
155
  with gr.Row():
156
  preset_refund = gr.Button("What is the course refund policy?", elem_classes=["preset-btn"])
157
  preset_cert = gr.Button("How do I unlock my completion certificate?", elem_classes=["preset-btn"])
 
163
  scale=9
164
  )
165
 
 
166
  with gr.Column(scale=1, elem_classes=["sidebar-panel"]):
167
  gr.Markdown("## Lane AI")
168
  gr.Markdown("### *Your Agentic Learning Assistant*")
169
  gr.Markdown("<br>🎓<br><br>🛡️ **Secure Session Activated**<br>Operational Node: Simplilearn-Chroma-01<br>Processing Hardware: Base CPU Node")
170
 
 
171
  msg_input.submit(process_chat, [msg_input, chatbot], [msg_input, chatbot])
 
 
172
  preset_refund.click(fn=click_preset_button, inputs=[preset_refund, chatbot], outputs=[chatbot])
173
  preset_cert.click(fn=click_preset_button, inputs=[preset_cert, chatbot], outputs=[chatbot])
174
 
 
175
  if __name__ == "__main__":
176
  demo.launch(css=custom_css, theme=gr.themes.Default())