Create tavily_search.py
Browse files- tavily_search.py +47 -0
tavily_search.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def perform_web_search(query: str, max_results: int = 5, include_domains=None, exclude_domains=None) -> str:
|
| 2 |
+
"""Perform web search using Tavily with default parameters"""
|
| 3 |
+
if not tavily_client:
|
| 4 |
+
return "Web search is not available. Please set the TAVILY_API_KEY environment variable."
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
# Use Tavily defaults with advanced search depth for better results
|
| 8 |
+
search_params = {
|
| 9 |
+
"search_depth": "advanced",
|
| 10 |
+
"max_results": min(max(1, max_results), 20)
|
| 11 |
+
}
|
| 12 |
+
if include_domains is not None:
|
| 13 |
+
search_params["include_domains"] = include_domains
|
| 14 |
+
if exclude_domains is not None:
|
| 15 |
+
search_params["exclude_domains"] = exclude_domains
|
| 16 |
+
|
| 17 |
+
response = tavily_client.search(query, **search_params)
|
| 18 |
+
|
| 19 |
+
search_results = []
|
| 20 |
+
for result in response.get('results', []):
|
| 21 |
+
title = result.get('title', 'No title')
|
| 22 |
+
url = result.get('url', 'No URL')
|
| 23 |
+
content = result.get('content', 'No content')
|
| 24 |
+
search_results.append(f"Title: {title}\nURL: {url}\nContent: {content}\n")
|
| 25 |
+
|
| 26 |
+
if search_results:
|
| 27 |
+
return "Web Search Results:\n\n" + "\n---\n".join(search_results)
|
| 28 |
+
else:
|
| 29 |
+
return "No search results found."
|
| 30 |
+
|
| 31 |
+
except Exception as e:
|
| 32 |
+
return f"Search error: {str(e)}"
|
| 33 |
+
|
| 34 |
+
def enhance_query_with_search(query: str, enable_search: bool) -> str:
|
| 35 |
+
"""Enhance the query with web search results if search is enabled"""
|
| 36 |
+
if not enable_search or not tavily_client:
|
| 37 |
+
return query
|
| 38 |
+
|
| 39 |
+
# Perform search to get relevant information
|
| 40 |
+
search_results = perform_web_search(query)
|
| 41 |
+
|
| 42 |
+
# Combine original query with search results
|
| 43 |
+
enhanced_query = f"""Original Query: {query}
|
| 44 |
+
{search_results}
|
| 45 |
+
Please use the search results above to help create the requested application with the most up-to-date information and best practices."""
|
| 46 |
+
|
| 47 |
+
return enhanced_query
|