Spaces:
Runtime error
Runtime error
File size: 6,327 Bytes
0b2427a 8ac8a9d 0b2427a | 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 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | """Search tools for web research using Tavily API."""
from typing import Dict, List, Optional
from tavily import TavilyClient # type: ignore[import-untyped]
from src.utils.config import get_settings
from src.utils.logging import setup_logger
logger = setup_logger(__name__)
class TavilySearchTool:
"""
Wrapper for Tavily search API optimized for research agents.
Tavily is designed for AI agents and provides clean, structured
results ideal for LLM consumption.
"""
def __init__(self, api_key: Optional[str] = None):
"""
Initialize Tavily search tool.
Args:
api_key: Optional Tavily API key (uses config if None)
"""
settings = get_settings()
self.api_key = api_key or settings.tavily_api_key
self.client = TavilyClient(api_key=self.api_key)
logger.info("Tavily search tool initialized")
async def search(
self,
query: str,
max_results: int = 5,
search_depth: str = "advanced",
include_domains: Optional[List[str]] = None,
exclude_domains: Optional[List[str]] = None,
) -> Dict:
"""
Perform web search using Tavily.
Args:
query: Search query
max_results: Maximum number of results to return
search_depth: "basic" or "advanced" (advanced is more comprehensive)
include_domains: Optional list of domains to include
exclude_domains: Optional list of domains to exclude
Returns:
Dictionary with search results:
- results: List of search results
- query: Original query
- answer: Tavily's AI-generated answer (if available)
"""
try:
logger.info(f"Tavily search: {query}")
response = self.client.search(
query=query,
max_results=max_results,
search_depth=search_depth,
include_domains=include_domains,
exclude_domains=exclude_domains,
)
logger.info(f"Tavily returned {len(response.get('results', []))} results")
return response
except Exception as e:
logger.error(f"Tavily search failed: {e}")
raise
async def get_company_info(
self,
company_name: str,
max_results: int = 10,
) -> Dict:
"""
Get comprehensive company information.
Args:
company_name: Company name to research
max_results: Maximum results to retrieve
Returns:
Search results focused on company information
"""
query = f"{company_name} company overview products services business model"
return await self.search(
query=query,
max_results=max_results,
search_depth="advanced",
)
async def get_competitor_info(
self,
company_name: str,
industry: Optional[str] = None,
max_results: int = 10,
) -> Dict:
"""
Find competitors for a given company.
Args:
company_name: Company name
industry: Optional industry context
max_results: Maximum results
Returns:
Search results about competitors
"""
industry_context = f"in {industry}" if industry else ""
query = f"{company_name} competitors alternatives {industry_context}"
return await self.search(
query=query,
max_results=max_results,
search_depth="advanced",
)
async def get_market_trends(
self,
industry: str,
year: Optional[str] = "2025",
max_results: int = 8,
) -> Dict:
"""
Get market trends for an industry.
Args:
industry: Industry name
year: Year for trends (default: 2025)
max_results: Maximum results
Returns:
Search results about market trends
"""
query = f"{industry} market trends {year} growth forecast opportunities"
return await self.search(
query=query,
max_results=max_results,
search_depth="advanced",
)
def format_results_for_llm(self, search_response: Dict) -> str:
"""
Format search results for LLM consumption.
Args:
search_response: Tavily search response
Returns:
Formatted string with search results
"""
results = search_response.get("results", [])
if not results:
return "No search results found."
formatted = []
for i, result in enumerate(results, 1):
title = result.get("title", "No title")
url = result.get("url", "")
content = result.get("content", "No content")
score = result.get("score", 0)
formatted.append(
f"[{i}] {title}\n"
f"URL: {url}\n"
f"Relevance: {score:.2f}\n"
f"Content: {content}\n"
)
# Add AI answer if available
if answer := search_response.get("answer"):
formatted.insert(0, f"AI Summary: {answer}\n\n")
return "\n".join(formatted)
class WikipediaSearchTool:
"""
Wikipedia search for factual company/product information.
Note: This is a simple wrapper. For production, consider using
the wikipedia-api library for more robust access.
"""
def __init__(self):
"""Initialize Wikipedia search tool."""
logger.info("Wikipedia search tool initialized")
async def search(self, query: str, max_results: int = 3) -> Dict:
"""
Search Wikipedia (placeholder for now).
Args:
query: Search query
max_results: Maximum results
Returns:
Search results dictionary
"""
# TODO: Implement actual Wikipedia API integration
# For now, we'll use Tavily which can search Wikipedia
logger.info(f"Wikipedia search: {query}")
return {
"query": query,
"results": [],
"note": "Wikipedia integration pending - using Tavily for now",
}
|