AshokGakr commited on
Commit
030d0f7
Β·
verified Β·
1 Parent(s): c75c014

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -46
app.py CHANGED
@@ -507,7 +507,7 @@ async def generate_reply_stream(
507
  tool_results: List[str] = []
508
  last_tool_name: Optional[str] = None
509
  prompt_lower = prompt.lower()
510
- force_tool = any(kw in prompt_lower for kw in [
511
  "latest", "today", "current", "price", "news", "up to date", "up-to-date",
512
  "search the web", "search web", "search online", "look up", "lookup",
513
  "use tool", "use the tool", "web_search", "web search"
@@ -534,30 +534,6 @@ async def generate_reply_stream(
534
  }
535
  print(f"😊 Emotion: {emotion_info['primary_emotion']} (Tone: {emotion_info['emotional_tone']})")
536
 
537
- # Force tool execution for time-sensitive queries (fallback if model doesn't call tool)
538
- if force_tool and not tool_results and tool_calls < max_tool_calls:
539
- tool_calls += 1
540
- query = prompt[:100]
541
- print(f"🧰 Forced tool execution for freshness: web_search('{query}')")
542
- try:
543
- from tools import execute_tool
544
- tool_output = execute_tool("web_search", {"query": query})
545
- except Exception:
546
- tool_output = None
547
- if not tool_output:
548
- try:
549
- tool_output = web_search(query)
550
- except Exception as e:
551
- tool_output = f"Search error: {e}"
552
-
553
- if tool_output is None:
554
- tool_output = "Tool 'web_search' failed or is unavailable."
555
-
556
- last_tool_name = "web_search"
557
- tool_results.append(f"TOOL {tool_calls} (web_search):\n{tool_output}")
558
- print(f"βœ… Forced tool completed (call {tool_calls}/{max_tool_calls})")
559
- continue
560
-
561
  # ==== ENHANCED LFM2.5 GENERATION WITH EMOTIONAL INTELLIGENCE ====
562
  try:
563
  tools_json = [
@@ -580,18 +556,18 @@ async def generate_reply_stream(
580
 
581
  # Build system message with emotional intelligence + tool calling (short + strict)
582
  system_message = f"""You are GAKR AI, a helpful assistant.
583
- Use web_search for any request needing current/latest/today/price/news info.
584
- If a tool is needed, call it before answering.
 
 
585
 
586
  List of tools: <|tool_list_start|>{tools_json_str}<|tool_list_end|>
587
 
588
  Tool call format:
589
  <|tool_call_start|>[web_search(query="...")]<|tool_call_end|>
590
 
 
591
  If no tool is needed, respond normally.
592
-
593
- Detected intent: {intent_info['intent_label']} ({intent_info['broad_category']})
594
- Detected emotion: {emotion_info['primary_emotion']} ({emotion_info['emotional_tone']})
595
  """
596
 
597
  # Build context
@@ -610,17 +586,8 @@ Detected emotion: {emotion_info['primary_emotion']} ({emotion_info['emotional_to
610
 
611
  ADDITIONAL CONTEXT:
612
  {context}
613
-
614
- USER ANALYSIS:
615
- - Detected Intent: {intent_info['intent_label']} (confidence: {intent_info['confidence']:.1%})
616
- - Detected Emotion: {emotion_info['primary_emotion']} (tone: {emotion_info['emotional_tone']})
617
- - Emotional Confidence: {emotion_info['primary_confidence']:.1%}
618
-
619
- Please provide a helpful response that:
620
- 1. Addresses the specific intent ({intent_info['intent_label']})
621
- 2. Appropriately responds to the emotional tone ({emotion_info['emotional_tone']})
622
- 3. Incorporates relevant information from the context
623
- 4. Provides practical, helpful assistance"""
624
 
625
  # Create messages for LFM2.5 chat template
626
  # LFM2.5 uses ChatML format: <|im_start|>role\ncontent<|im_end|>
@@ -633,11 +600,19 @@ Please provide a helpful response that:
633
  print(f"🧰 Tools JSON: {tools_json_str}")
634
 
635
  # Apply chat template to format the messages
636
- formatted_prompt = lfm_tokenizer.apply_chat_template(
637
- messages,
638
- tokenize=False, # Don't tokenize yet
639
- add_generation_prompt=True,
640
- )
 
 
 
 
 
 
 
 
641
 
642
  print(f"πŸ” Formatted prompt length: {len(formatted_prompt)} characters")
643
  print(f"πŸ” Sample formatted prompt: {formatted_prompt[:200]}...")
@@ -771,6 +746,25 @@ Please provide a helpful response that:
771
  if isinstance(tc, dict) and "name" in tc and "args" in tc:
772
  return tc
773
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
774
  return None
775
 
776
  for new_text in streamer:
@@ -796,6 +790,8 @@ Please provide a helpful response that:
796
 
797
  # If it doesn't look like a tool call, begin streaming
798
  if (not stripped.startswith("{")) or (len(stripped) > 400):
 
 
799
  if not debug_buffer_logged:
800
  preview = stripped[:300].replace("\n", " ")
801
  print(f"πŸ§ͺ No tool call detected. Starting stream. Buffer preview: {preview}...")
 
507
  tool_results: List[str] = []
508
  last_tool_name: Optional[str] = None
509
  prompt_lower = prompt.lower()
510
+ tool_required = any(kw in prompt_lower for kw in [
511
  "latest", "today", "current", "price", "news", "up to date", "up-to-date",
512
  "search the web", "search web", "search online", "look up", "lookup",
513
  "use tool", "use the tool", "web_search", "web search"
 
534
  }
535
  print(f"😊 Emotion: {emotion_info['primary_emotion']} (Tone: {emotion_info['emotional_tone']})")
536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
  # ==== ENHANCED LFM2.5 GENERATION WITH EMOTIONAL INTELLIGENCE ====
538
  try:
539
  tools_json = [
 
556
 
557
  # Build system message with emotional intelligence + tool calling (short + strict)
558
  system_message = f"""You are GAKR AI, a helpful assistant.
559
+
560
+ Rules:
561
+ - For any request requiring fresh data (latest/current/today/price/news or user asks to search web), you MUST call web_search before answering.
562
+ - When a tool is required, your first response MUST be ONLY the tool call (no extra text).
563
 
564
  List of tools: <|tool_list_start|>{tools_json_str}<|tool_list_end|>
565
 
566
  Tool call format:
567
  <|tool_call_start|>[web_search(query="...")]<|tool_call_end|>
568
 
569
+ After tool results are returned, answer normally using them.
570
  If no tool is needed, respond normally.
 
 
 
571
  """
572
 
573
  # Build context
 
586
 
587
  ADDITIONAL CONTEXT:
588
  {context}
589
+ Incorporates relevant information from the context
590
+ Provides practical, helpful assistance"""
 
 
 
 
 
 
 
 
 
591
 
592
  # Create messages for LFM2.5 chat template
593
  # LFM2.5 uses ChatML format: <|im_start|>role\ncontent<|im_end|>
 
600
  print(f"🧰 Tools JSON: {tools_json_str}")
601
 
602
  # Apply chat template to format the messages
603
+ try:
604
+ formatted_prompt = lfm_tokenizer.apply_chat_template(
605
+ messages,
606
+ tools=tools_json,
607
+ tokenize=False, # Don't tokenize yet
608
+ add_generation_prompt=True,
609
+ )
610
+ except TypeError:
611
+ formatted_prompt = lfm_tokenizer.apply_chat_template(
612
+ messages,
613
+ tokenize=False, # Don't tokenize yet
614
+ add_generation_prompt=True,
615
+ )
616
 
617
  print(f"πŸ” Formatted prompt length: {len(formatted_prompt)} characters")
618
  print(f"πŸ” Sample formatted prompt: {formatted_prompt[:200]}...")
 
746
  if isinstance(tc, dict) and "name" in tc and "args" in tc:
747
  return tc
748
 
749
+ # 3) Bare Pythonic call without special tokens (fallback)
750
+ stripped = text.strip()
751
+ raw = stripped
752
+ if raw.startswith("[") and raw.endswith("]"):
753
+ raw = raw[1:-1].strip()
754
+ if raw.startswith("web_search(") and raw.endswith(")"):
755
+ args_str = raw[len("web_search("):-1].strip()
756
+ args: Dict[str, Any] = {}
757
+ mq = re.search(r'query\s*=\s*\"(.*?)\"|query\s*=\s*\'(.*?)\'', args_str)
758
+ if mq:
759
+ args["query"] = mq.group(1) or mq.group(2) or ""
760
+ else:
761
+ mpos = re.match(r'^\"(.*)\"$|^\'(.*)\'$', args_str)
762
+ if mpos:
763
+ pos = mpos.group(1) or mpos.group(2)
764
+ if pos is not None:
765
+ args["query"] = pos
766
+ return {"name": "web_search", "args": args}
767
+
768
  return None
769
 
770
  for new_text in streamer:
 
790
 
791
  # If it doesn't look like a tool call, begin streaming
792
  if (not stripped.startswith("{")) or (len(stripped) > 400):
793
+ if tool_required and not tool_results:
794
+ print("⚠️ Tool required but model did not call tool. Proceeding without tool.")
795
  if not debug_buffer_logged:
796
  preview = stripped[:300].replace("\n", " ")
797
  print(f"πŸ§ͺ No tool call detected. Starting stream. Buffer preview: {preview}...")