File size: 1,154 Bytes
bf25842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from typing import Optional, Dict, List
try:
    from tavily import TavilyClient
    TAVILY_AVAILABLE = True
except ImportError:
    TavilyClient = None
    TAVILY_AVAILABLE = False

class WebSearchService:
    def __init__(self):
        self.client = None
        api_key = os.getenv("TAVILY_API_KEY")
        if api_key and TAVILY_AVAILABLE:
            self.client = TavilyClient(api_key=api_key)

    def search(self, query: str, max_results: int = 5) -> Optional[List[Dict]]:
        """
        Perform a web search using Tavily.
        Returns list of results with title, url, content.
        """
        if not self.client:
            print("⚠️ Tavily API key not configured.")
            return []

        try:
            response = self.client.search(
                query=query,
                max_results=max_results,
                include_answer=True,
                include_raw_content=False
            )
            return response.get("results", [])
        except Exception as e:
            print(f"❌ Web search failed: {e}")
            return []

# Global instance
web_search_service = WebSearchService()