Spaces:
Sleeping
Sleeping
Joachim M. Vis commited on
Upload 3 files
Browse filesFiles changed (2)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""
Example script demonstrating how to use the EnhancedWebSearchTool for GAIA assessment questions.
This script shows how to use the EnhancedWebSearchTool to search for information
related to specific GAIA assessment questions.
"""
import os
import sys
import logging
import json
from typing import Dict, Any, List
# Add the parent directory to the path so we can import the agent module
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from agent.tool_registry import create_default_registry, unified_search
from tools.web_tools import create_enhanced_web_search
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("enhanced_web_search_example")
def main():
"""Run the enhanced web search example."""
# Check required environment variables
required_vars = ["PERPLEXITY_API_KEY"]
missing_vars = [var for var in required_vars if not os.environ.get(var)]
if missing_vars:
logger.error(f"Missing required environment variables: {', '.join(missing_vars)}")
logger.error("Please set these environment variables before running the example.")
sys.exit(1)
# Create the registry
logger.info("Creating tool registry...")
registry = create_default_registry()
# GAIA assessment questions
questions = [
"How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)?",
"Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?",
"On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?",
"Who won the Malko Competition for Young Conductors in 2021?"
]
# Search for each question
for i, question in enumerate(questions):
logger.info(f"\n\nQuestion {i+1}: {question}")
# Search using unified_search
logger.info("Searching using unified_search...")
results = unified_search(registry, question)
# Print the results
if results and results.get("results"):
logger.info(f"Found {len(results['results'])} results")
logger.info(f"Providers used: {results.get('metadata', {}).get('providers_used', [])}")
# Print the top result
if results["results"]:
top_result = results["results"][0]
logger.info("\nTop result:")
logger.info(f"Title: {top_result.get('title', 'N/A')}")
logger.info(f"Source: {top_result.get('source', 'N/A')}")
logger.info(f"Relevance score: {top_result.get('relevance_score', 'N/A')}")
logger.info(f"Snippet: {top_result.get('snippet', 'N/A')}")
# If we have Perplexity content, print it
perplexity_content = results.get("metadata", {}).get("perplexity_content")
if perplexity_content:
logger.info("\nPerplexity content:")
logger.info(perplexity_content[:500] + "..." if len(perplexity_content) > 500 else perplexity_content)
else:
logger.warning("No results found")
logger.info("\nExample completed successfully!")
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373#!/usr/bin/env python
"""
Unified Search Example
This script demonstrates how to use all three search tools:
1. BrowserSearchTool for direct browser-based searches
2. LibrarySearchTool for searches using imported libraries
3. ApiSearchTool for searches using external API services
The example includes:
- Importing and initializing each tool
- Example queries for each tool type (academic, complex reasoning, simple factual)
- Demonstrating how to use them individually and together
- Showing how to interpret and process the results
"""
import os
import json
import logging
from typing import Dict, Any, List, Optional
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("unified_search_example")
# Import the tool registry and search tools
from agent.tool_registry import ToolRegistry, create_default_registry
from tools.web_tools import (
LibrarySearchTool,
ApiSearchTool,
create_library_search,
create_api_search
)
from tools.multimodal_tools import BrowserSearchTool, create_browser_search_tool
def print_section(title: str) -> None:
"""Print a section title with formatting."""
print("\n" + "=" * 80)
print(f" {title} ".center(80, "="))
print("=" * 80 + "\n")
def print_results(results: List[Dict[str, Any]], max_snippet_length: int = 150) -> None:
"""
Print search results in a readable format.
Args:
results: List of search result dictionaries
max_snippet_length: Maximum length for snippet display
"""
if not results:
print("No results found.")
return
for i, result in enumerate(results):
print(f"Result {i+1}:")
print(f" Title: {result.get('title', 'No title')}")
print(f" Link: {result.get('link', 'No link')}")
# Format snippet for display
snippet = result.get('snippet', 'No snippet')
if len(snippet) > max_snippet_length:
snippet = snippet[:max_snippet_length] + "..."
print(f" Snippet: {snippet}")
# Print source and relevance if available
if 'source' in result:
print(f" Source: {result['source']}")
if 'relevance_score' in result:
print(f" Relevance: {result['relevance_score']}")
print()
def example_browser_search() -> None:
"""
Demonstrate the BrowserSearchTool for direct browser-based searches.
This tool is useful for:
- Visual content that needs to be seen directly
- Interactive exploration of search results
- Searching specific websites with their native interfaces
"""
print_section("BrowserSearchTool Example")
# Initialize the BrowserSearchTool
browser_tool = create_browser_search_tool()
print("BrowserSearchTool initialized")
# Example 1: General web search
print("\n1. General web search (Google):")
query = "latest advancements in quantum computing"
results = browser_tool.search(query, site="google")
print_results(results)
print("To use these results, you would use the browser_action tool to open the URL and interact with the search results directly.")
# Example 2: Academic search on arXiv
print("\n2. Academic search on arXiv:")
academic_query = "transformer models in natural language processing"
results = browser_tool.search(academic_query, site="arxiv")
print_results(results)
print("The browser_action tool would allow you to view papers, download PDFs, and explore citations.")
# Example 3: Wikipedia search for factual information
print("\n3. Wikipedia search for factual information:")
factual_query = "history of artificial intelligence"
results = browser_tool.search(factual_query, site="wikipedia")
print_results(results)
print("Using browser_action would let you navigate through Wikipedia articles and follow links to related topics.")
# Example 4: Direct URL visit
print("\n4. Direct URL visit:")
url = "https://arxiv.org/abs/2303.08774" # Example arXiv paper
result = browser_tool.direct_visit(url)
print(f"Title: {result.get('title')}")
print(f"Link: {result.get('link')}")
print(f"Instructions: {result.get('instructions')}")
def example_library_search() -> None:
"""
Demonstrate the LibrarySearchTool for searches using imported libraries.
This tool is useful for:
- Programmatic searches without requiring a browser
- Automatically routing between general and academic sources
- Getting structured results that can be processed programmatically
"""
print_section("LibrarySearchTool Example")
# Initialize the LibrarySearchTool
library_tool = create_library_search()
print("LibrarySearchTool initialized")
# Example 1: General factual query (routes to DuckDuckGo)
print("\n1. General factual query (routes to DuckDuckGo):")
factual_query = "population of Tokyo in 2023"
print(f"Query: '{factual_query}'")
print("Analyzing query type...")
is_academic = library_tool._is_academic_query(factual_query)
print(f"Is academic query? {is_academic}")
print("Routing to appropriate search provider...")
results = library_tool.search(factual_query)
print_results(results)
# Example 2: Academic query (routes to arXiv)
print("\n2. Academic query (routes to arXiv):")
academic_query = "recent papers on large language models"
print(f"Query: '{academic_query}'")
print("Analyzing query type...")
is_academic = library_tool._is_academic_query(academic_query)
print(f"Is academic query? {is_academic}")
print("Routing to appropriate search provider...")
results = library_tool.search(academic_query)
print_results(results)
# Example 3: Processing and analyzing results
print("\n3. Processing and analyzing results:")
query = "climate change impacts"
results = library_tool.search(query)
# Demonstrate how to extract and use specific information
if results:
# Count sources
sources = {}
for result in results:
source = result.get('source', 'unknown')
sources[source] = sources.get(source, 0) + 1
print(f"Query: '{query}'")
print(f"Total results: {len(results)}")
print(f"Results by source: {sources}")
# Find highest relevance result
if any('relevance_score' in r for r in results):
most_relevant = max(results, key=lambda r: r.get('relevance_score', 0))
print(f"Most relevant result: {most_relevant.get('title')} (Score: {most_relevant.get('relevance_score')})")
# Extract all unique domains from results
domains = set()
for result in results:
link = result.get('link', '')
if link.startswith('http'):
from urllib.parse import urlparse
domain = urlparse(link).netloc
domains.add(domain)
print(f"Unique domains in results: {domains}")
def example_api_search() -> None:
"""
Demonstrate the ApiSearchTool for searches using external API services.
This tool is useful for:
- Complex reasoning queries that benefit from AI-powered search
- Getting high-quality, synthesized results for complex topics
- Accessing real-time information from search engines
Note: Requires API keys for Perplexity and/or Serper
"""
print_section("ApiSearchTool Example")
# Check if API keys are available
perplexity_key = os.environ.get("PERPLEXITY_API_KEY")
serper_key = os.environ.get("SERPER_API_KEY")
if not perplexity_key and not serper_key:
print("Warning: No API keys found for Perplexity or Serper.")
print("Set PERPLEXITY_API_KEY and/or SERPER_API_KEY environment variables to use ApiSearchTool.")
print("Continuing with limited functionality...\n")
# Initialize the ApiSearchTool
api_tool = create_api_search()
print("ApiSearchTool initialized")
# Example 1: Complex reasoning query (routes to Perplexity if available)
print("\n1. Complex reasoning query (routes to Perplexity if available):")
complex_query = "Explain the implications of quantum computing on modern cryptography"
print(f"Query: '{complex_query}'")
print("Analyzing query complexity...")
is_complex = api_tool._is_complex_query(complex_query)
print(f"Is complex query? {is_complex}")
print("Routing to appropriate API service...")
try:
results = api_tool.search(complex_query)
print_results(results)
# Show how to access full content if available
if results and 'full_content' in results[0]:
print("Full content is available for this result.")
print("First 200 characters of full content:")
print(results[0]['full_content'][:200] + "...")
except Exception as e:
print(f"Error: {str(e)}")
print("This may be due to missing API keys or API service issues.")
# Example 2: Simple factual query (routes to Serper if available)
print("\n2. Simple factual query (routes to Serper if available):")
factual_query = "height of Mount Everest"
print(f"Query: '{factual_query}'")
print("Analyzing query complexity...")
is_complex = api_tool._is_complex_query(factual_query)
print(f"Is complex query? {is_complex}")
print("Routing to appropriate API service...")
try:
results = api_tool.search(factual_query)
print_results(results)
except Exception as e:
print(f"Error: {str(e)}")
print("This may be due to missing API keys or API service issues.")
# Example 3: Working with citations (if available from Perplexity)
print("\n3. Working with citations (if available from Perplexity):")
citation_query = "recent breakthroughs in fusion energy research"
try:
results = api_tool.search(citation_query)
for result in results:
if 'citations' in result:
print(f"Result includes {len(result['citations'])} citations:")
for i, citation in enumerate(result['citations'][:3]): # Show first 3 citations
print(f" Citation {i+1}: {citation.get('title', 'No title')} - {citation.get('url', 'No URL')}")
except Exception as e:
print(f"Error: {str(e)}")
print("This may be due to missing API keys or API service issues.")
def example_unified_search() -> None:
"""
Demonstrate how to use all three search tools together through the tool registry.
This example shows:
- How to use the tool registry to access all search tools
- How to choose the right tool based on query type
- How to combine results from multiple tools
"""
print_section("Unified Search Example")
# Create a tool registry with all search tools
registry = create_default_registry()
print("Tool registry created with the following search tools:")
search_tools = [tool for tool in registry.list_tools() if 'search' in tool]
for tool in search_tools:
print(f"- {tool}")
# Example 1: Using the registry to execute specific tools
print("\n1. Using the registry to execute specific tools:")
query = "renewable energy technologies"
print(f"\nQuery: '{query}'")
print("Executing with different search tools:")
# Try different search tools and compare results
results_by_tool = {}
for tool_name in ['duckduckgo_search', 'library_search', 'enhanced_web_search']:
if registry.get_tool(tool_name):
try:
print(f"\nExecuting {tool_name}...")
results = registry.execute_tool(tool_name, query=query)
results_by_tool[tool_name] = results
print(f"Got {len(results)} results from {tool_name}")
except Exception as e:
print(f"Error with {tool_name}: {str(e)}")
# Example 2: Using the unified_search function from tool_registry
print("\n2. Using the unified_search function:")
from agent.tool_registry import unified_search
query = "impact of artificial intelligence on healthcare"
print(f"\nQuery: '{query}'")
print("Executing unified_search...")
try:
unified_results = unified_search(registry, query)
print(f"Got results from the following providers: {unified_results['metadata']['providers_used']}")
print(f"Total results: {len(unified_results['results'])}")
print("\nTop 2 results:")
print_results(unified_results['results'][:2])
# Show execution times
print("Execution times:")
for provider, time in unified_results['metadata']['execution_times'].items():
print(f"- {provider}: {time:.2f} seconds")
except Exception as e:
print(f"Error with unified_search: {str(e)}")
# Example 3: Combining and ranking results from multiple tools
print("\n3. Combining and ranking results from multiple tools:")
# Function to combine results from multiple tools
def combine_and_rank_results(results_by_tool):
all_results = []
for tool, results in results_by_tool.items():
# Add tool name to each result if not already present
for result in results:
if 'source' not in result:
result['source'] = tool
all_results.append(result)
# Sort by relevance score if available
if all_results and 'relevance_score' in all_results[0]:
all_results.sort(key=lambda x: x.get('relevance_score', 0), reverse=True)
return all_results
combined_results = combine_and_rank_results(results_by_tool)
print(f"Combined {len(combined_results)} results from {len(results_by_tool)} tools")
print("\nTop 3 results after combining and ranking:")
print_results(combined_results[:3])
def main():
"""Run all examples."""
print_section("Unified Search Examples")
print("This script demonstrates how to use all three search tools:")
print("1. BrowserSearchTool - For direct browser-based searches")
print("2. LibrarySearchTool - For searches using imported libraries")
print("3. ApiSearchTool - For searches using external API services")
# Run individual examples
example_browser_search()
example_library_search()
example_api_search()
example_unified_search()
print_section("Conclusion")
print("This example demonstrated how to use all three search tools:")
print("1. BrowserSearchTool - Best for visual content and interactive exploration")
print("2. LibrarySearchTool - Best for programmatic searches without API keys")
print("3. ApiSearchTool - Best for complex reasoning queries with high-quality results")
print("\nThese tools can be used individually or together through the tool registry.")
print("Choose the right tool based on your specific search needs and available resources.")
if __name__ == "__main__":
main()examples/enhanced_web_search_example.pyAdded+84
examples/unified_search_example.pyAdded+373