jdesiree commited on
Commit
6740bd5
·
verified ·
1 Parent(s): 1858424

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -55
app.py CHANGED
@@ -99,6 +99,7 @@ class Tool_Decision_Engine:
99
  """Uses LLM to intelligently decide when visualization tools would be beneficial"""
100
 
101
  def __init__(self, llm):
 
102
  self.decision_llm = llm
103
  self.decision_prompt = """Analyze this educational query and determine if creating a graph, chart, or visual representation would significantly enhance learning and understanding.
104
 
@@ -292,10 +293,7 @@ class Educational_Agent:
292
  def __init__(self):
293
  self.llm = Qwen25SmallLLM(model_path="Qwen/Qwen2.5-1.5B-Instruct", use_4bit=True)
294
  self.tool_decision_engine = Tool_Decision_Engine(self.llm)
295
- self.memory = ConversationBufferWindowMemory(
296
- memory_key="chat_history",
297
- return_messages=True,
298
- k=5
299
  )
300
 
301
  def should_use_tools(self, query: str) -> bool:
@@ -315,57 +313,66 @@ class Educational_Agent:
315
  ])
316
 
317
  def process_with_tools(self, query: str) -> str:
318
- """Process query with tools available"""
319
- try:
320
- # Create agent with tools
321
- tools = [Create_Graph_Tool]
322
-
323
- # Use create_react_agent for better control
324
- agent = create_react_agent(
325
- self.llm,
326
- tools,
327
- state_modifier=self.create_prompt_template(has_tools=True)
328
- )
329
-
330
- response = agent.invoke({"messages": [HumanMessage(content=query)]})
331
-
332
- # Extract the final message content
333
- if response and "messages" in response:
334
- final_message = response["messages"][-1]
335
- if hasattr(final_message, 'content'):
336
- return final_message.content
337
- else:
338
- return str(final_message)
339
-
340
- return str(response)
341
-
342
- except Exception as e:
343
- logger.error(f"Error in tool processing: {e}")
344
- return f"I apologize, but I encountered an error while processing your request: {str(e)}"
345
-
346
- def process_without_tools(self, query: str) -> str:
347
- """Process query without tools"""
348
- try:
349
- response = self.llm.invoke(query)
350
- return response
351
- except Exception as e:
352
- logger.error(f"Error in normal processing: {e}")
353
- return f"I apologize, but I encountered an error: {str(e)}"
354
-
355
- def chat(self, message: str) -> str:
356
- """Main chat interface with conditional tool usage"""
357
- try:
358
- # Determine if tools are needed
359
- if self.should_use_tools(message):
360
- logger.info("Query requires visualization - enabling tools")
361
- return self.process_with_tools(message)
362
- else:
363
- logger.info("Query doesn't need tools - responding normally")
364
- return self.process_without_tools(message)
365
-
366
- except Exception as e:
367
- logger.error(f"Error in chat processing: {e}")
368
- return f"I apologize, but I encountered an error: {str(e)}"
 
 
 
 
 
 
 
 
 
369
 
370
  # --- Global Agent Instance ---
371
  agent = None
 
99
  """Uses LLM to intelligently decide when visualization tools would be beneficial"""
100
 
101
  def __init__(self, llm):
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
 
 
293
  def __init__(self):
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:
 
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