File size: 5,634 Bytes
a7dc9f8
 
 
 
 
 
 
42c7e2d
a7dc9f8
 
 
 
 
 
 
 
 
 
 
 
 
42c7e2d
 
38d119d
42c7e2d
a7dc9f8
42c7e2d
38d119d
42c7e2d
a7dc9f8
 
 
42c7e2d
38d119d
42c7e2d
a7dc9f8
42c7e2d
 
a7dc9f8
 
42c7e2d
a7dc9f8
42c7e2d
 
 
 
a7dc9f8
 
 
42c7e2d
 
a7dc9f8
42c7e2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38d119d
a7dc9f8
 
 
42c7e2d
 
 
a7dc9f8
42c7e2d
 
 
 
a7dc9f8
 
42c7e2d
 
 
 
 
 
 
 
 
a7dc9f8
42c7e2d
a7dc9f8
42c7e2d
 
 
 
a7dc9f8
42c7e2d
a7dc9f8
 
 
42c7e2d
 
 
 
a7dc9f8
 
42c7e2d
 
 
 
 
 
fae8f67
 
a7dc9f8
42c7e2d
 
 
 
 
 
fae8f67
a7dc9f8
 
42c7e2d
d00b6e8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# plugins/web_search_plugin.py
import requests
from datetime import datetime

class WebSearchPlugin:
    def __init__(self, max_results=3):
        self.max_results = max_results
        self.tavily_api_key = "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"  # Paste your key here
    
    @classmethod
    def hooks(cls):
        instance = cls()
        return {
            'post_chat': instance.enhance_with_search
        }
    
    def enhance_with_search(self, data):
        """Check if user wants to search the web."""
        user_input = data.get('input', '').lower()
        
        search_triggers = ['search', 'look up', 'find online', 'google', 'check the web', 
                          'current', 'latest', 'what is happening', 'news about', 'recent',
                          'what happened', 'breaking']
        
        if any(trigger in user_input for trigger in search_triggers):
            query = self._extract_query(user_input)
            print(f"🌐 Tavily searching: {query}")
            
            results = self._search_tavily(query)
            
            if results:
                formatted = self._format_results(results)
                search_section = f"\n\n{'='*60}\n🌐 WEB SEARCH RESULTS: {query}\n{'='*60}\n{formatted}\n{'='*60}\n\n"
                data['response'] = search_section + data.get('response', '')
                print(f"βœ… Added {len(results)} Tavily results to response")
            else:
                data['response'] = f"\n\n🌐 No results found for '{query}'\n\n" + data.get('response', '')
                print("⚠️ No Tavily results")
    
    def _extract_query(self, user_input):
        """Extract clean query from user input."""
        query = user_input
        remove_words = ['search', 'look up', 'find online', 'google', 'check the web', 
                       'for', 'about', 'recent', 'latest', 'current', 'what is', 'what happened',
                       'news about', 'breaking']
        for word in remove_words:
            query = query.replace(word, '')
        return query.strip()
    
    def _search_tavily(self, query):
        """Search using Tavily AI - optimized for LLMs."""
        try:
            headers = {'Content-Type': 'application/json'}
            payload = {
                'api_key': self.tavily_api_key,
                'query': query,
                'search_depth': 'basic',  # 'basic' is faster, 'advanced' is more thorough
                'include_answer': True,   # Get AI-generated answer too
                'include_raw_content': False,
                'max_results': self.max_results,
                'include_domains': [],    # Optionally filter to specific sites
                'exclude_domains': []     # Optionally exclude sites
            }
            
            response = requests.post(
                'https://api.tavily.com/search',
                json=payload,
                headers=headers,
                timeout=15
            )
            
            if response.status_code != 200:
                print(f"⚠️ Tavily API error: {response.status_code} - {response.text}")
                return None
            
            data = response.json()
            results = []
            
            # Tavily often provides a direct answer
            if data.get('answer'):
                print(f"πŸ’‘ Tavily AI Answer: {data['answer'][:100]}...")
                results.append({
                    'title': 'πŸ€– AI Summary',
                    'snippet': data['answer'],
                    'url': '',
                    'score': 1.0
                })
            
            # Add search results
            for item in data.get('results', [])[:self.max_results]:
                results.append({
                    'title': item.get('title', 'No title'),
                    'snippet': item.get('content', 'No description')[:500],  # Tavily gives good content
                    'url': item.get('url', ''),
                    'score': item.get('score', 0),
                    'published_date': item.get('published_date', '')
                })
            
            print(f"βœ… Tavily returned {len(results)} results")
            return results if results else None
            
        except requests.exceptions.Timeout:
            print("⏱️ Tavily request timed out")
            return None
        except Exception as e:
            print(f"❌ Tavily search failed: {e}")
            return None
    
    def _format_results(self, results):
        """Format Tavily results for display."""
        if not results:
            return "No results found."
        
        formatted = ""
        for i, result in enumerate(results, 1):
            # Special formatting for AI summary
            if result['title'] == 'πŸ€– AI Summary':
                formatted += f"\n{result['title']}\n{result['snippet']}\n\n"
                formatted += "-" * 60 + "\n"
                continue
            
            formatted += f"\n[{i}] {result['title']}\n"
            formatted += f"    {result['snippet']}\n"
            if result['url']:
                formatted += f"    πŸ”— {result['url']}\n"
            if result.get('published_date'):
                formatted += f"    πŸ“… {result['published_date']}\n"
            if result.get('score'):
                formatted += f"    ⭐ Relevance: {result['score']:.2f}\n"
        
        return formatted

def register(orchestrator):
    print("πŸ”Œ Registering Tavily Web Search Plugin (1000 free searches/month)")
    orchestrator.add_plugin('web_search', WebSearchPlugin(max_results=3).hooks())