jdesiree commited on
Commit
84d5953
·
verified ·
1 Parent(s): 566d0c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -87
app.py CHANGED
@@ -15,7 +15,7 @@ from langchain_core.tools import tool
15
  from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
16
  from langchain_core.prompts import ChatPromptTemplate
17
  from langchain_core.runnables import RunnableBranch
18
- from langgraph.prebuilt import create_react_agent
19
  from langchain.memory import ConversationBufferWindowMemory
20
  from typing import Optional, List, Any, Type
21
  from pydantic import BaseModel, Field
@@ -102,30 +102,24 @@ class Tool_Decision_Engine:
102
  self.conversation_history = []
103
  self.decision_llm = llm
104
  self.decision_prompt = """Analyze this educational query and determine if creating a graph, chart, or visual representation would significantly enhance learning and understanding.
105
-
106
  Query: "{query}"
107
-
108
  Consider these factors:
109
  1. Would visualization make a concept clearer or easier to understand?
110
  2. Does the topic involve data, relationships, comparisons, or trends?
111
  3. Could a graph help illustrate abstract concepts concretely?
112
  4. For practice questions, would including visual elements be educational?
113
-
114
  Examples that BENEFIT from visualization:
115
  - Explaining mathematical functions or statistical concepts
116
  - Creating practice questions that involve data interpretation
117
  - Teaching about scientific trends or relationships
118
  - Comparing quantities, performance, or outcomes
119
  - Illustrating economic principles or business metrics
120
-
121
  Examples that do NOT need visualization:
122
  - Simple definitions or explanations
123
  - General conversation or greetings
124
  - Text-based study strategies
125
  - Qualitative discussions without data
126
-
127
  Answer with exactly: YES or NO
128
-
129
  Decision:"""
130
 
131
  def should_use_visualization(self, query: str) -> bool:
@@ -152,13 +146,11 @@ Decision:"""
152
 
153
  # --- System Prompt ---
154
  SYSTEM_PROMPT = """You are Mimir, an expert multi-concept tutor designed to facilitate genuine learning and understanding. Your primary mission is to guide students through the learning process rather than providing direct answers to academic work.
155
-
156
  ## Core Educational Principles
157
  - Provide comprehensive, educational responses that help students truly understand concepts
158
  - Use minimal formatting, with markdown bolding reserved for **key terms** only
159
  - Prioritize teaching methodology over answer delivery
160
  - Foster critical thinking and independent problem-solving skills
161
-
162
  ## Tone and Communication Style
163
  - Maintain an engaging, friendly tone appropriate for high school students
164
  - Write at a reading level that is accessible yet intellectually stimulating
@@ -168,16 +160,13 @@ SYSTEM_PROMPT = """You are Mimir, an expert multi-concept tutor designed to faci
168
  - Skip flattery and respond directly to questions
169
  - Do not use emojis or actions in asterisks unless specifically requested
170
  - Present critiques and corrections kindly as educational opportunities
171
-
172
  ## Academic Integrity Approach
173
  You recognize that students may seek direct answers to homework, assignments, or test questions. Rather than providing complete solutions or making accusations about intent, you should:
174
-
175
  - **Guide through processes**: Break down problems into conceptual components and teach underlying principles
176
  - **Ask clarifying questions**: Understand what the student already knows and where their confusion lies
177
  - **Provide similar examples**: Work through analogous problems that demonstrate the same concepts without directly solving their specific assignment
178
  - **Encourage original thinking**: Help students develop their own reasoning and analytical skills
179
  - **Suggest study strategies**: Recommend effective learning approaches for the subject matter
180
-
181
  ## Visual Learning Enhancement
182
  You have the ability to create graphs and charts to enhance your explanations. Use this capability proactively when:
183
  - Explaining mathematical concepts (functions, distributions, relationships)
@@ -187,15 +176,12 @@ You have the ability to create graphs and charts to enhance your explanations. U
187
  - Illustrating economic principles, business metrics, or financial concepts
188
  - Showing survey results, demographic data, or research findings
189
  - Demonstrating any concept where visualization aids comprehension
190
-
191
  **Important**: Only use the graph tool when visualization would genuinely help explain a concept. For general conversation, explanations, or questions that don't involve data or relationships, respond normally without tools.
192
-
193
  ## Response Guidelines
194
  - **For math problems**: Explain concepts, provide formula derivations, and guide through problem-solving steps without computing final numerical answers
195
  - **For multiple-choice questions**: Discuss the concepts being tested and help students understand how to analyze options rather than identifying the correct choice
196
  - **For essays or written work**: Discuss research strategies, organizational techniques, and critical thinking approaches rather than providing content or thesis statements
197
  - **For factual questions**: Provide educational context and encourage students to synthesize information rather than stating direct answers
198
-
199
  ## Communication Guidelines
200
  - Maintain a supportive, non-judgmental tone in all interactions
201
  - Assume positive intent while redirecting toward genuine learning
@@ -203,7 +189,6 @@ You have the ability to create graphs and charts to enhance your explanations. U
203
  - Celebrate understanding and progress in the learning process
204
  - Encourage students to explain their thinking and reasoning
205
  - Provide honest, accurate feedback even when it may not be what the student wants to hear
206
-
207
  Your goal is to be an educational partner who empowers students to succeed through understanding, not a service that completes their work for them."""
208
 
209
  # --- LLM Class Unchanged ---
@@ -225,17 +210,19 @@ class Qwen25SmallLLM:
225
  bnb_4bit_quant_type="nf4",
226
  llm_int8_threshold=0.0,
227
  llm_int8_skip_modules=["lm_head"]
228
- )
229
-
230
- # Try quantized load
231
- self.model = AutoModelForCausalLM.from_pretrained(
232
- model_path,
233
- quantization_config=quant_config,
234
- device_map="auto",
235
- torch_dtype=torch.bfloat16,
236
- trust_remote_code=True,
237
- low_cpu_mem_usage=True
238
- )
 
 
239
 
240
  except Exception as e:
241
  logger.warning(f"Quantized load failed, falling back: {e}")
@@ -294,7 +281,6 @@ class Educational_Agent:
294
  self.llm = Qwen25SmallLLM(model_path="Qwen/Qwen2.5-1.5B-Instruct", use_4bit=True)
295
  self.tool_decision_engine = Tool_Decision_Engine(self.llm)
296
  self.conversation_history = []
297
- )
298
 
299
  def should_use_tools(self, query: str) -> bool:
300
  """Use LLM reasoning to determine if tools are needed"""
@@ -313,66 +299,81 @@ class Educational_Agent:
313
  ])
314
 
315
  def process_with_tools(self, query: str) -> str:
316
- """Process query with tools available using traditional agent"""
317
- try:
318
- # Create agent with tools using traditional approach
319
- tools = [Create_Graph_Tool]
320
-
321
- # Create memory for this agent instance
322
- memory = ConversationBufferWindowMemory(
323
- memory_key="chat_history",
324
- return_messages=True
325
- )
326
-
327
- # Add conversation history to memory
328
- for exchange in self.conversation_history:
329
- if exchange.startswith("User: "):
330
- memory.chat_memory.add_user_message(exchange[6:])
331
- elif exchange.startswith("Assistant: "):
332
- memory.chat_memory.add_ai_message(exchange[11:])
333
-
334
- # Use traditional agent with better prompting
335
- agent = initialize_agent(
336
- tools=tools,
337
- llm=self.llm,
338
- agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
339
- memory=memory,
340
- verbose=True,
341
- handle_parsing_errors=True,
342
- agent_kwargs={
343
- "prefix": SYSTEM_PROMPT + "\n\nYou have access to graph creation tools. Use them when visualization would genuinely help explain concepts. Think carefully about whether a tool is needed before using it.\n\n"
344
- }
345
- )
346
-
347
- response = agent.run(query)
348
-
349
- # Store the exchange
350
- self.conversation_history.append(f"User: {query}")
351
- self.conversation_history.append(f"Assistant: {response}")
352
-
353
- return response
354
-
355
- except Exception as e:
356
- logger.error(f"Error in tool processing: {e}")
357
- return f"I apologize, but I encountered an error while processing your request: {str(e)}"
358
 
359
  def process_without_tools(self, query: str) -> str:
360
- """Process query without tools"""
361
- try:
362
- # Include recent conversation in prompt
363
- context = "\n".join(self.conversation_history[-8:]) if self.conversation_history else ""
364
- full_prompt = f"Recent conversation:\n{context}\n\nCurrent query: {query}" if context else query
365
-
366
- response = self.llm.invoke(full_prompt)
367
-
368
- # Store the exchange
369
- self.conversation_history.append(f"User: {query}")
370
- self.conversation_history.append(f"Assistant: {response}")
371
-
372
- return response
373
- except Exception as e:
374
- logger.error(f"Error in normal processing: {e}")
375
- return f"I apologize, but I encountered an error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
 
377
  # --- Global Agent Instance ---
378
  agent = None
@@ -632,7 +633,7 @@ if __name__ == "__main__":
632
 
633
  # Step 2: Warm up the model
634
  logger.info("Warming up model...")
635
- warmup_agent()
636
 
637
  interface = create_interface()
638
  interface.queue()
 
15
  from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
16
  from langchain_core.prompts import ChatPromptTemplate
17
  from langchain_core.runnables import RunnableBranch
18
+ from langchain.agents import initialize_agent, AgentType
19
  from langchain.memory import ConversationBufferWindowMemory
20
  from typing import Optional, List, Any, Type
21
  from pydantic import BaseModel, Field
 
102
  self.conversation_history = []
103
  self.decision_llm = llm
104
  self.decision_prompt = """Analyze this educational query and determine if creating a graph, chart, or visual representation would significantly enhance learning and understanding.
 
105
  Query: "{query}"
 
106
  Consider these factors:
107
  1. Would visualization make a concept clearer or easier to understand?
108
  2. Does the topic involve data, relationships, comparisons, or trends?
109
  3. Could a graph help illustrate abstract concepts concretely?
110
  4. For practice questions, would including visual elements be educational?
 
111
  Examples that BENEFIT from visualization:
112
  - Explaining mathematical functions or statistical concepts
113
  - Creating practice questions that involve data interpretation
114
  - Teaching about scientific trends or relationships
115
  - Comparing quantities, performance, or outcomes
116
  - Illustrating economic principles or business metrics
 
117
  Examples that do NOT need visualization:
118
  - Simple definitions or explanations
119
  - General conversation or greetings
120
  - Text-based study strategies
121
  - Qualitative discussions without data
 
122
  Answer with exactly: YES or NO
 
123
  Decision:"""
124
 
125
  def should_use_visualization(self, query: str) -> bool:
 
146
 
147
  # --- System Prompt ---
148
  SYSTEM_PROMPT = """You are Mimir, an expert multi-concept tutor designed to facilitate genuine learning and understanding. Your primary mission is to guide students through the learning process rather than providing direct answers to academic work.
 
149
  ## Core Educational Principles
150
  - Provide comprehensive, educational responses that help students truly understand concepts
151
  - Use minimal formatting, with markdown bolding reserved for **key terms** only
152
  - Prioritize teaching methodology over answer delivery
153
  - Foster critical thinking and independent problem-solving skills
 
154
  ## Tone and Communication Style
155
  - Maintain an engaging, friendly tone appropriate for high school students
156
  - Write at a reading level that is accessible yet intellectually stimulating
 
160
  - Skip flattery and respond directly to questions
161
  - Do not use emojis or actions in asterisks unless specifically requested
162
  - Present critiques and corrections kindly as educational opportunities
 
163
  ## Academic Integrity Approach
164
  You recognize that students may seek direct answers to homework, assignments, or test questions. Rather than providing complete solutions or making accusations about intent, you should:
 
165
  - **Guide through processes**: Break down problems into conceptual components and teach underlying principles
166
  - **Ask clarifying questions**: Understand what the student already knows and where their confusion lies
167
  - **Provide similar examples**: Work through analogous problems that demonstrate the same concepts without directly solving their specific assignment
168
  - **Encourage original thinking**: Help students develop their own reasoning and analytical skills
169
  - **Suggest study strategies**: Recommend effective learning approaches for the subject matter
 
170
  ## Visual Learning Enhancement
171
  You have the ability to create graphs and charts to enhance your explanations. Use this capability proactively when:
172
  - Explaining mathematical concepts (functions, distributions, relationships)
 
176
  - Illustrating economic principles, business metrics, or financial concepts
177
  - Showing survey results, demographic data, or research findings
178
  - Demonstrating any concept where visualization aids comprehension
 
179
  **Important**: Only use the graph tool when visualization would genuinely help explain a concept. For general conversation, explanations, or questions that don't involve data or relationships, respond normally without tools.
 
180
  ## Response Guidelines
181
  - **For math problems**: Explain concepts, provide formula derivations, and guide through problem-solving steps without computing final numerical answers
182
  - **For multiple-choice questions**: Discuss the concepts being tested and help students understand how to analyze options rather than identifying the correct choice
183
  - **For essays or written work**: Discuss research strategies, organizational techniques, and critical thinking approaches rather than providing content or thesis statements
184
  - **For factual questions**: Provide educational context and encourage students to synthesize information rather than stating direct answers
 
185
  ## Communication Guidelines
186
  - Maintain a supportive, non-judgmental tone in all interactions
187
  - Assume positive intent while redirecting toward genuine learning
 
189
  - Celebrate understanding and progress in the learning process
190
  - Encourage students to explain their thinking and reasoning
191
  - Provide honest, accurate feedback even when it may not be what the student wants to hear
 
192
  Your goal is to be an educational partner who empowers students to succeed through understanding, not a service that completes their work for them."""
193
 
194
  # --- LLM Class Unchanged ---
 
210
  bnb_4bit_quant_type="nf4",
211
  llm_int8_threshold=0.0,
212
  llm_int8_skip_modules=["lm_head"]
213
+ )
214
+
215
+ # Try quantized load
216
+ self.model = AutoModelForCausalLM.from_pretrained(
217
+ model_path,
218
+ quantization_config=quant_config,
219
+ device_map="auto",
220
+ torch_dtype=torch.bfloat16,
221
+ trust_remote_code=True,
222
+ low_cpu_mem_usage=True
223
+ )
224
+ else:
225
+ self._load_fallback_model(model_path)
226
 
227
  except Exception as e:
228
  logger.warning(f"Quantized load failed, falling back: {e}")
 
281
  self.llm = Qwen25SmallLLM(model_path="Qwen/Qwen2.5-1.5B-Instruct", use_4bit=True)
282
  self.tool_decision_engine = Tool_Decision_Engine(self.llm)
283
  self.conversation_history = []
 
284
 
285
  def should_use_tools(self, query: str) -> bool:
286
  """Use LLM reasoning to determine if tools are needed"""
 
299
  ])
300
 
301
  def process_with_tools(self, query: str) -> str:
302
+ """Process query with tools available using traditional agent"""
303
+ try:
304
+ # Create agent with tools using traditional approach
305
+ tools = [Create_Graph_Tool]
306
+
307
+ # Create memory for this agent instance
308
+ memory = ConversationBufferWindowMemory(
309
+ memory_key="chat_history",
310
+ return_messages=True
311
+ )
312
+
313
+ # Add conversation history to memory
314
+ for exchange in self.conversation_history:
315
+ if exchange.startswith("User: "):
316
+ memory.chat_memory.add_user_message(exchange[6:])
317
+ elif exchange.startswith("Assistant: "):
318
+ memory.chat_memory.add_ai_message(exchange[11:])
319
+
320
+ # Use traditional agent with better prompting
321
+ agent = initialize_agent(
322
+ tools=tools,
323
+ llm=self.llm,
324
+ agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
325
+ memory=memory,
326
+ verbose=True,
327
+ handle_parsing_errors=True,
328
+ agent_kwargs={
329
+ "prefix": SYSTEM_PROMPT + "\n\nYou have access to graph creation tools. Use them when visualization would genuinely help explain concepts. Think carefully about whether a tool is needed before using it.\n\n"
330
+ }
331
+ )
332
+
333
+ response = agent.run(query)
334
+
335
+ # Store the exchange
336
+ self.conversation_history.append(f"User: {query}")
337
+ self.conversation_history.append(f"Assistant: {response}")
338
+
339
+ return response
340
+
341
+ except Exception as e:
342
+ logger.error(f"Error in tool processing: {e}")
343
+ return f"I apologize, but I encountered an error while processing your request: {str(e)}"
344
 
345
  def process_without_tools(self, query: str) -> str:
346
+ """Process query without tools"""
347
+ try:
348
+ # Include recent conversation in prompt
349
+ context = "\n".join(self.conversation_history[-8:]) if self.conversation_history else ""
350
+ full_prompt = f"Recent conversation:\n{context}\n\nCurrent query: {query}" if context else query
351
+
352
+ response = self.llm.invoke(full_prompt)
353
+
354
+ # Store the exchange
355
+ self.conversation_history.append(f"User: {query}")
356
+ self.conversation_history.append(f"Assistant: {response}")
357
+
358
+ return response
359
+ except Exception as e:
360
+ logger.error(f"Error in normal processing: {e}")
361
+ return f"I apologize, but I encountered an error: {str(e)}"
362
+
363
+ def chat(self, message: str) -> str:
364
+ """Main chat interface with conditional tool usage"""
365
+ try:
366
+ # Determine if tools are needed
367
+ if self.should_use_tools(message):
368
+ logger.info("Query requires visualization - enabling tools")
369
+ return self.process_with_tools(message)
370
+ else:
371
+ logger.info("Query doesn't need tools - responding normally")
372
+ return self.process_without_tools(message)
373
+
374
+ except Exception as e:
375
+ logger.error(f"Error in chat processing: {e}")
376
+ return f"I apologize, but I encountered an error: {str(e)}"
377
 
378
  # --- Global Agent Instance ---
379
  agent = None
 
633
 
634
  # Step 2: Warm up the model
635
  logger.info("Warming up model...")
636
+ warmup_agent() # Comment out temporarily to avoid hanging
637
 
638
  interface = create_interface()
639
  interface.queue()