Nexari-Research commited on
Commit
aebecbc
·
verified ·
1 Parent(s): 853b07e

Update tools_engine.py

Browse files
Files changed (1) hide show
  1. tools_engine.py +62 -35
tools_engine.py CHANGED
@@ -1,74 +1,101 @@
1
  """
2
- Nexari Tools Engine (Smart Override Edition)
3
  Author: Piyush
4
- Description: Prevents silly mistakes on short messages by using a 'Hardcoded Logic Layer' before the Neural Network.
 
 
 
 
5
  """
6
 
7
  from duckduckgo_search import DDGS
8
  from transformers import pipeline
 
9
 
10
  print(">>> Tools: Loading Intent Classification Model...")
 
11
  intent_classifier = pipeline("zero-shot-classification", model="typeform/distilbert-base-uncased-mnli")
12
 
13
  def analyze_intent(user_text):
14
  """
15
- Decides intent with a Safety Layer for short greetings to prevent hallucination.
 
 
 
 
16
  """
 
 
 
17
  text_lower = user_text.lower().strip()
18
-
19
- # === LAYER 1: HARDCODED SAFETY (The Fix for 'Hi' -> Searching) ===
20
- # Agar user bas hello bol raha hai, to AI brain mat lagao. Direct chat karo.
21
- direct_chat_triggers = ["hi", "hello", "hey", "hlo", "hola", "namaste", "what is your name", "who are you"]
22
-
23
- # Agar input EXACTLY inme se ek hai, ya start hota hai
 
24
  if text_lower in direct_chat_triggers or any(text_lower.startswith(t + " ") for t in direct_chat_triggers):
25
- print(f">>> Brain Override: Detected Greeting/Identity -> Force 'general conversation'")
26
- return "general conversation"
27
 
28
- # === LAYER 2: NEURAL NETWORK DECISION ===
29
  candidate_labels = [
30
- "internet search",
31
- "general conversation",
32
- "coding request",
33
  "checking time"
34
  ]
35
-
36
  try:
37
  result = intent_classifier(user_text, candidate_labels)
38
- top_intent = result['labels'][0]
39
  confidence = result['scores'][0]
40
-
41
- print(f">>> Brain: Detected '{top_intent}' ({confidence:.2f})")
42
-
43
- # Confidence Threshold badha diya (0.4 -> 0.5) taaki ghalat search na kare
44
  if confidence > 0.5:
45
- return top_intent
 
 
 
 
 
 
 
46
  except Exception as e:
47
  print(f"Intent Error: {e}")
48
-
49
- return "general conversation"
50
 
51
- def perform_web_search(user_text):
 
 
52
  """
53
- Executes search only when triggered.
54
  """
55
  try:
56
  clean_query = user_text.lower()
57
- remove_phrases = ["search for", "google", "find", "tell me about", "latest info on", "news about"]
58
  for phrase in remove_phrases:
59
  clean_query = clean_query.replace(phrase, "")
60
-
61
  clean_query = clean_query.strip()
62
- if len(clean_query) < 2: clean_query = user_text
 
63
 
64
  print(f">>> Action: Searching Web for '{clean_query}'...")
65
- results = DDGS().text(clean_query, max_results=3)
66
-
67
  if results:
68
- summary = "\n".join([f"- {r['title']}: {r['body']}" for r in results])
69
- return f"### WEB DATA ###\n{summary}\nINSTRUCTION: Answer based on this data."
 
 
 
 
 
 
 
 
70
  return ""
71
-
72
  except Exception as e:
73
  print(f"Search Error: {e}")
74
- return ""
 
1
  """
2
+ Nexari Tools Engine (UPDATED)
3
  Author: Piyush
4
+ Improvements:
5
+ - Canonical intent labels returned
6
+ - More robust greeting detection
7
+ - Safer web search formatting
8
+ - Defensive error handling
9
  """
10
 
11
  from duckduckgo_search import DDGS
12
  from transformers import pipeline
13
+ import re
14
 
15
  print(">>> Tools: Loading Intent Classification Model...")
16
+ # zero-shot pipeline; if heavy, Docker predownload already handles it
17
  intent_classifier = pipeline("zero-shot-classification", model="typeform/distilbert-base-uncased-mnli")
18
 
19
  def analyze_intent(user_text):
20
  """
21
+ Returns canonical intent labels:
22
+ - "internet_search"
23
+ - "coding_request"
24
+ - "checking_time"
25
+ - "general"
26
  """
27
+ if not user_text:
28
+ return "general"
29
+
30
  text_lower = user_text.lower().strip()
31
+
32
+ # === HARDCODED SAFETY (Greeting/Identity) ===
33
+ direct_chat_triggers = [
34
+ "hi", "hello", "hey", "hlo", "hola", "namaste",
35
+ "what is your name", "who are you", "who r you", "your name"
36
+ ]
37
+ # exact match or common short greeting at start
38
  if text_lower in direct_chat_triggers or any(text_lower.startswith(t + " ") for t in direct_chat_triggers):
39
+ print(f">>> Brain Override: Detected Greeting/Identity -> Force 'general'")
40
+ return "general"
41
 
42
+ # === ZERO-SHOT PASSES ===
43
  candidate_labels = [
44
+ "internet search",
45
+ "general conversation",
46
+ "coding request",
47
  "checking time"
48
  ]
49
+
50
  try:
51
  result = intent_classifier(user_text, candidate_labels)
52
+ top_label = result['labels'][0]
53
  confidence = result['scores'][0]
54
+ print(f">>> Brain: Detected '{top_label}' ({confidence:.2f})")
55
+
 
 
56
  if confidence > 0.5:
57
+ # map to canonical labels
58
+ mapping = {
59
+ "internet search": "internet_search",
60
+ "general conversation": "general",
61
+ "coding request": "coding_request",
62
+ "checking time": "checking_time"
63
+ }
64
+ return mapping.get(top_label, "general")
65
  except Exception as e:
66
  print(f"Intent Error: {e}")
 
 
67
 
68
+ return "general"
69
+
70
+ def perform_web_search(user_text, max_results=3):
71
  """
72
+ Execute a brief web search and return a compact summary.
73
  """
74
  try:
75
  clean_query = user_text.lower()
76
+ remove_phrases = ["search for", "google", "find", "tell me about", "latest info on", "news about", "lookup"]
77
  for phrase in remove_phrases:
78
  clean_query = clean_query.replace(phrase, "")
79
+
80
  clean_query = clean_query.strip()
81
+ if len(clean_query) < 2:
82
+ clean_query = user_text
83
 
84
  print(f">>> Action: Searching Web for '{clean_query}'...")
85
+ results = list(DDGS().text(clean_query, max_results=max_results))
86
+
87
  if results:
88
+ parts = []
89
+ for r in results:
90
+ title = r.get('title', '').strip()
91
+ body = re.sub(r'\s+', ' ', r.get('body', '').strip())
92
+ # keep short
93
+ if len(body) > 250:
94
+ body = body[:250].rsplit(' ', 1)[0] + "..."
95
+ parts.append(f"- {title}: {body}")
96
+ summary = "\n".join(parts)
97
+ return f"### WEB DATA (short) ###\n{summary}\nINSTRUCTION: Use this to inform the answer; prefer concise synthesis."
98
  return ""
 
99
  except Exception as e:
100
  print(f"Search Error: {e}")
101
+ return ""