# 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())