Spaces:
Running
Running
File size: 2,152 Bytes
b02630d 6c86ca6 b02630d d76cab0 b02630d 6c86ca6 d76cab0 b02630d 43b5bb7 6c86ca6 43b5bb7 d76cab0 714f42f 6c86ca6 714f42f 6c86ca6 d76cab0 6c86ca6 d76cab0 6c86ca6 d76cab0 714f42f 6c86ca6 d76cab0 6c86ca6 | 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 | import os
from typing import List, Dict
import requests
from config.config import Config
class SearchTool:
"""Tavily web search wrapper with content extraction."""
def __init__(self) -> None:
self.api_key = os.getenv("TAVILY_API_KEY") or Config.TAVILY_API_KEY
if not self.api_key:
print("β οΈ WARNING: TAVILY_API_KEY not found!")
# Don't raise error, allow graceful degradation
self.api_key = None
def search(self, query: str, num_results: int = 5) -> List[Dict]:
"""
Search using Tavily API.
Returns results with title, url, content (snippet from Tavily).
"""
if not self.api_key:
print("β Tavily search skipped - no API key")
return []
url = "https://api.tavily.com/search"
payload = {
"api_key": self.api_key,
"query": query,
"max_results": num_results,
"include_answer": True, # Get Tavily's AI answer
"include_raw_content": False,
"search_depth": "advanced" # Better results
}
print(f"π Tavily searching for: {query[:50]}...")
try:
resp = requests.post(url, json=payload, timeout=30)
resp.raise_for_status()
data = resp.json()
results = data.get("results", [])
# Add Tavily's answer as metadata if available
tavily_answer = data.get("answer", "")
if tavily_answer and results:
results[0]["tavily_answer"] = tavily_answer
print(f" β
Tavily AI answer: {tavily_answer[:100]}...")
print(f" β
Tavily returned {len(results)} results")
if results:
print(f" π First result: {results[0].get('title', 'N/A')}")
return results
except requests.exceptions.RequestException as e:
print(f"β Tavily search error: {e}")
return []
except ValueError as e:
print(f"β Tavily JSON error: {e}")
return []
|