File size: 3,030 Bytes
7e2816d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# jade/web_search.py - Tavily Web Search Handler
import os
import logging

logger = logging.getLogger("JadeWebSearch")

class WebSearchHandler:
    """Handler para busca web em tempo real usando Tavily API."""
    
    def __init__(self):
        self.api_key = os.getenv("TAVILY_API_KEY")
        self.client = None
        
        if self.api_key:
            try:
                from tavily import TavilyClient
                self.client = TavilyClient(api_key=self.api_key)
                logger.info("✅ Tavily WebSearch inicializado com sucesso.")
            except ImportError:
                logger.warning("⚠️ tavily-python não instalado. Web search desabilitado.")
        else:
            logger.warning("⚠️ TAVILY_API_KEY não encontrada. Web search desabilitado.")
    
    def search(self, query: str, max_results: int = 3) -> str:
        """

        Busca na web e retorna contexto formatado para a IA.

        

        Args:

            query: Termo de busca

            max_results: Número máximo de resultados

            

        Returns:

            String formatada com os resultados da busca

        """
        if not self.client:
            return ""
        
        try:
            logger.info(f"🔍 [WebSearch] Buscando: '{query}'")
            
            response = self.client.search(
                query=query,
                search_depth="basic",  # "basic" é mais rápido, "advanced" mais completo
                max_results=max_results,
                include_answer=True,  # Tavily já gera um resumo
                include_raw_content=False  # Não precisamos do HTML cru
            )
            
            # Monta contexto formatado
            context_parts = []
            
            # Resposta resumida do Tavily (se disponível)
            if response.get("answer"):
                context_parts.append(f"📝 Resumo: {response['answer']}")
            
            # Resultados individuais
            results = response.get("results", [])
            if results:
                context_parts.append("\n📰 Fontes encontradas:")
                for i, result in enumerate(results[:max_results], 1):
                    title = result.get("title", "Sem título")
                    url = result.get("url", "")
                    content = result.get("content", "")[:500]  # Limita tamanho
                    context_parts.append(f"\n{i}. **{title}**\n   URL: {url}\n   {content}")
            
            context = "\n".join(context_parts)
            logger.info(f"🔍 [WebSearch] Encontrados {len(results)} resultados.")
            
            return context
            
        except Exception as e:
            logger.error(f"❌ Erro na busca Tavily: {e}")
            return f"Erro ao buscar na web: {str(e)}"
    
    def is_available(self) -> bool:
        """Verifica se o serviço de busca está disponível."""
        return self.client is not None