Nexari-Research commited on
Commit
cace612
·
verified ·
1 Parent(s): 1ea07d4

Update tools_engine.py

Browse files
Files changed (1) hide show
  1. tools_engine.py +36 -42
tools_engine.py CHANGED
@@ -1,76 +1,70 @@
1
  """
2
- Nexari Tools Engine (Neural Network Edition)
3
  Author: Piyush
4
- Description: Uses a Zero-Shot Classification Model to detect intent intelligently.
5
  """
6
 
7
  from duckduckgo_search import DDGS
8
  import wikipedia
9
  from transformers import pipeline
10
 
11
- print(">>> Tools: Loading Intent Classification Model (Neural Network)...")
12
- # Hum ek lightweight model use kar rahe hain jo CPU par fast chale
13
- # "typeform/distilbert-base-uncased-mnli" is fast and accurate for intents
14
  intent_classifier = pipeline("zero-shot-classification", model="typeform/distilbert-base-uncased-mnli")
15
 
16
  def analyze_intent(user_text):
17
  """
18
- Uses Neural Network to decide if the user wants to Search, Chat, or Calculate.
19
- Returns: 'internet_search' or 'general_chat'
20
  """
21
- # Candidates labels defines what the AI looks for
22
  candidate_labels = ["internet search", "general conversation", "coding request", "mathematical calculation"]
23
 
24
- # Run Classification
25
- result = intent_classifier(user_text, candidate_labels)
26
-
27
- # Top prediction nikalo
28
- top_intent = result['labels'][0]
29
- confidence = result['scores'][0]
30
-
31
- print(f">>> Intent Detected: {top_intent} (Confidence: {confidence:.2f})")
32
-
33
- # Agar confidence 40% se zyada hai tabhi action lo
34
- if confidence > 0.4:
35
- return top_intent
36
  return "general_chat"
37
 
38
- def get_internet_context(user_text):
39
  """
40
- Fetches data only if the Neural Network detects 'internet search' intent.
 
41
  """
42
-
43
- # === STEP 1: NEURAL INTENT CHECK ===
44
- intent = analyze_intent(user_text)
45
-
46
- # Agar AI ko lagta hai ki ye search nahi hai, to khali laut jao
47
- if intent != "internet search":
48
- return ""
49
-
50
- # === STEP 2: PERFORM SEARCH ===
51
  try:
52
- # Query Cleaning: Common phrases hatao taaki search accurate ho
53
- clean_query = user_text
54
- remove_phrases = ["search for", "google", "find", "tell me about", "what is", "do you know", "latest info on"]
55
  for phrase in remove_phrases:
56
- clean_query = clean_query.lower().replace(phrase, "")
57
 
58
  clean_query = clean_query.strip()
59
- if len(clean_query) < 2: return "" # Bahut choti query ignore karo
 
 
 
60
 
61
- print(f">>> Tool: Searching for '{clean_query}'...")
62
  results = DDGS().text(clean_query, max_results=3)
63
 
64
  if results:
65
  search_summary = "\n".join([f"- {r['title']}: {r['body']}" for r in results])
66
  return (
67
  f"### REAL-TIME INTERNET DATA ###\n"
68
- f"Intent Detected: Web Search\n"
 
69
  f"Results:\n{search_summary}\n\n"
70
- f"INSTRUCTION: Use the above search results to answer the user's question."
71
  )
 
 
72
 
73
  except Exception as e:
74
- print(f"Tool Error: {e}")
75
-
76
- return ""
 
1
  """
2
+ Nexari Tools Engine (Optimized)
3
  Author: Piyush
4
+ Description: Efficient Neural Intent Detection & Direct Search Execution.
5
  """
6
 
7
  from duckduckgo_search import DDGS
8
  import wikipedia
9
  from transformers import pipeline
10
 
11
+ print(">>> Tools: Loading Intent Classification Model...")
12
+ # Load model once into memory
 
13
  intent_classifier = pipeline("zero-shot-classification", model="typeform/distilbert-base-uncased-mnli")
14
 
15
  def analyze_intent(user_text):
16
  """
17
+ Decides the intent: 'internet search', 'coding request', or 'general conversation'.
 
18
  """
 
19
  candidate_labels = ["internet search", "general conversation", "coding request", "mathematical calculation"]
20
 
21
+ try:
22
+ result = intent_classifier(user_text, candidate_labels)
23
+ top_intent = result['labels'][0]
24
+ confidence = result['scores'][0]
25
+
26
+ print(f">>> Intent: {top_intent} ({confidence:.2f})")
27
+
28
+ if confidence > 0.4:
29
+ return top_intent
30
+ except Exception as e:
31
+ print(f"Intent Error: {e}")
32
+
33
  return "general_chat"
34
 
35
+ def perform_web_search(user_text):
36
  """
37
+ Directly executes search without re-analyzing intent.
38
+ Called specifically when app.py decides to search.
39
  """
 
 
 
 
 
 
 
 
 
40
  try:
41
+ # Query Cleaning
42
+ clean_query = user_text.lower()
43
+ remove_phrases = ["search for", "google", "find", "tell me about", "what is", "do you know", "latest info on", "news about"]
44
  for phrase in remove_phrases:
45
+ clean_query = clean_query.replace(phrase, "")
46
 
47
  clean_query = clean_query.strip()
48
+
49
+ # Fallback if query is empty
50
+ if len(clean_query) < 2:
51
+ clean_query = user_text
52
 
53
+ print(f">>> Tool: Searching DuckDuckGo for '{clean_query}'...")
54
  results = DDGS().text(clean_query, max_results=3)
55
 
56
  if results:
57
  search_summary = "\n".join([f"- {r['title']}: {r['body']}" for r in results])
58
  return (
59
  f"### REAL-TIME INTERNET DATA ###\n"
60
+ f"Source: DuckDuckGo Web Search\n"
61
+ f"Topic: {clean_query}\n"
62
  f"Results:\n{search_summary}\n\n"
63
+ f"INSTRUCTION: Use the above results to answer. If results are irrelevant, rely on your memory."
64
  )
65
+ else:
66
+ return "" # No results found
67
 
68
  except Exception as e:
69
+ print(f"Search Tool Error: {e}")
70
+ return ""