Spaces:
Runtime error
Runtime error
File size: 5,597 Bytes
4826e54 |
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 |
import os
from dotenv import load_dotenv
from langchain_tavily import TavilySearch
# Load environment variables
load_dotenv()
def test_tavily_search():
"""Test the Tavily search functionality independently"""
print("π Testing Tavily Search Tool...")
print("="*50)
# Check if API key is available
api_key = os.getenv("TAVILY_API_KEY")
if not api_key:
print("β Error: TAVILY_API_KEY not found in environment variables")
print("Please add TAVILY_API_KEY to your .env file")
return
print(f"β
API Key found: {api_key[:10]}...{api_key[-4:]}")
try:
# Initialize Tavily search
print("\nπ Initializing Tavily search...")
tavily_search = TavilySearch(
api_key=api_key,
max_results=2,
topic="general",
search_depth="basic",
include_answer=True,
include_raw_content=False,
include_images=False
)
print("β
Tavily search initialized successfully")
# Test search query
test_query = "latest portugal won"
print(f"\nπ Searching for: '{test_query}'")
# Perform the search
results = tavily_search.invoke({"query": test_query})
print(f"\nπ Results type: {type(results)}")
print(
f"π Results length: {len(results) if hasattr(results, '__len__') else 'N/A'}")
# Display results
print("\nπ° Raw Results:")
print("-" * 30)
print(results)
print("-" * 30)
# Process and format results
if isinstance(results, list) and results:
print(f"\nβ
Found {len(results)} results")
formatted_news = f"π° Latest News about '{test_query}':\n\n"
for i, result in enumerate(results, 1):
print(f"\nπ Processing result {i}:")
print(f" Type: {type(result)}")
if isinstance(result, dict):
print(f" Keys: {list(result.keys())}")
title = result.get('title', 'No title')
content = result.get('content', 'No content available')
url = result.get('url', 'No URL')
formatted_news += f"{i}. **{title}**\n"
formatted_news += f" Summary: {content[:200]}...\n"
formatted_news += f" Source: {url}\n\n"
else:
# Handle case where result is a string
formatted_news += f"{i}. {str(result)[:300]}...\n\n"
print(f"\nπ Formatted Output:")
print("="*50)
print(formatted_news)
print("="*50)
else:
print(f"β No results found or unexpected result format")
print(f"Results: {results}")
except Exception as e:
print(f"β Error during search: {e}")
print(f"Error type: {type(e)}")
import traceback
print(f"Full traceback:\n{traceback.format_exc()}")
def test_tavily_raw():
"""Test the raw Tavily search functionality"""
print("π Testing Raw Tavily Search...")
print("="*50)
# Check if API key is available
api_key = os.getenv("TAVILY_API_KEY")
if not api_key:
print("β Error: TAVILY_API_KEY not found in environment variables")
return False
try:
# Initialize Tavily search
tavily_search = TavilySearch(
api_key=api_key,
max_results=2,
topic="general",
search_depth="basic",
include_answer=True,
include_raw_content=False,
include_images=False
)
# Test search query
test_query = "latest portugal won"
print(f"π Searching for: '{test_query}'")
# Perform the search
results = tavily_search.invoke({"query": test_query})
print(f"β
Raw search successful!")
print(f"π Results type: {type(results)}")
if isinstance(results, dict) and 'results' in results:
print(f"π Number of results: {len(results['results'])}")
return True
return False
except Exception as e:
print(f"β Raw search failed: {e}")
return False
def test_tools_function():
"""Test our get_latest_news function from tools.py"""
print("\nπ§ Testing get_latest_news Function...")
print("="*50)
try:
# Import our function
from tools import get_latest_news
# Test the function
test_query = "portugal won"
print(f"π Testing with query: '{test_query}'")
result = get_latest_news(test_query)
print("β
Function executed successfully!")
print("\nπ° Function Output:")
print("-" * 50)
print(result)
print("-" * 50)
return True
except Exception as e:
print(f"β Function test failed: {e}")
import traceback
print(f"Full traceback:\n{traceback.format_exc()}")
return False
if __name__ == "__main__":
print("π§ͺ Running Tavily Tests...\n")
# Test 1: Raw Tavily
raw_success = test_tavily_raw()
# Test 2: Our function
if raw_success:
function_success = test_tools_function()
if function_success:
print("\nπ All tests passed! The news search tool is working correctly.")
else:
print("\nβ οΈ Raw search works but our function has issues.")
else:
print("\nβ Raw search failed - check your API key and connection.")
|