CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-tavily-python

Python wrapper for the Tavily API with search, extract, crawl, and map capabilities

Overview
Eval results
Files

search.mddocs/

Search Operations

Comprehensive web search functionality with advanced filtering, topic specialization, and optimized output formats for different use cases including RAG applications and Q&A systems.

Capabilities

General Web Search

Performs comprehensive web searches with extensive customization options for depth, scope, content inclusion, and result filtering.

def search(
    query: str,
    search_depth: Literal["basic", "advanced"] = None,
    topic: Literal["general", "news", "finance"] = None,
    time_range: Literal["day", "week", "month", "year"] = None,
    start_date: str = None,
    end_date: str = None,
    days: int = None,
    max_results: int = None,
    include_domains: Sequence[str] = None,
    exclude_domains: Sequence[str] = None,
    include_answer: Union[bool, Literal["basic", "advanced"]] = None,
    include_raw_content: Union[bool, Literal["markdown", "text"]] = None,
    include_images: bool = None,
    timeout: int = 60,
    country: str = None,
    auto_parameters: bool = None,
    include_favicon: bool = None,
    **kwargs
) -> dict:
    """
    Perform a comprehensive web search with extensive customization options.

    Parameters:
    - query: Search query string
    - search_depth: Search thoroughness ("basic" for fast results, "advanced" for comprehensive)
    - topic: Domain specialization for better results
    - time_range: Restrict results to recent timeframe
    - start_date/end_date: Custom date range (YYYY-MM-DD format)
    - days: Number of days back to search
    - max_results: Maximum number of results to return
    - include_domains: Only search within these domains
    - exclude_domains: Exclude these domains from search
    - include_answer: Include AI-generated answer summary
    - include_raw_content: Include full page content in specified format
    - include_images: Include image URLs in results
    - timeout: Request timeout in seconds (max 120)
    - country: Geographic search constraint (ISO country code)
    - auto_parameters: Enable automatic parameter optimization
    - include_favicon: Include website favicon URLs

    Returns:
    Dict containing:
    - query: Original search query
    - results: List of search result objects
    - answer: AI-generated answer (if requested)
    - images: List of image URLs (if requested)
    - response_time: Query processing time
    """

Usage Examples:

# Basic search
results = client.search("climate change impacts")

# Advanced search with filtering
results = client.search(
    query="renewable energy trends",
    search_depth="advanced",
    topic="general",
    days=30,
    max_results=10,
    include_domains=["nature.com", "science.org"],
    include_answer="advanced",
    include_raw_content="markdown"
)

# News-focused search
news_results = client.search(
    query="latest AI developments",
    topic="news",
    time_range="week",
    include_images=True
)

RAG Context Generation

Optimized search specifically designed for RAG applications, returning token-limited JSON context suitable for language model consumption.

def get_search_context(
    query: str,
    search_depth: Literal["basic", "advanced"] = "basic",
    topic: Literal["general", "news", "finance"] = "general",
    days: int = 7,
    max_results: int = 5,
    include_domains: Sequence[str] = None,
    exclude_domains: Sequence[str] = None,
    max_tokens: int = 4000,
    timeout: int = 60,
    country: str = None,
    include_favicon: bool = None,
    **kwargs
) -> str:
    """
    Generate search context optimized for RAG applications.

    Parameters:
    - query: Search query for context generation
    - search_depth: Search thoroughness level
    - topic: Domain specialization
    - days: How many days back to search
    - max_results: Maximum search results to process
    - include_domains: Only search within these domains
    - exclude_domains: Exclude these domains
    - max_tokens: Maximum tokens in returned context (based on OpenAI encoding)
    - timeout: Request timeout in seconds
    - country: Geographic search constraint
    - include_favicon: Include favicon URLs

    Returns:
    JSON string containing search context up to token limit with:
    - url: Source URL
    - content: Relevant content excerpt
    """

Usage Examples:

# Generate context for RAG
context = client.get_search_context(
    query="What are the benefits of solar energy?",
    max_tokens=2000,
    days=30
)

# Domain-specific context
finance_context = client.get_search_context(
    query="stock market trends 2024",
    topic="finance",
    include_domains=["bloomberg.com", "reuters.com"],
    max_tokens=3000
)

Question-Answer Search

Specialized search optimized for direct question answering, returning concise answers rather than raw search results.

def qna_search(
    query: str,
    search_depth: Literal["basic", "advanced"] = "advanced",
    topic: Literal["general", "news", "finance"] = "general",
    days: int = 7,
    max_results: int = 5,
    include_domains: Sequence[str] = None,
    exclude_domains: Sequence[str] = None,
    timeout: int = 60,
    country: str = None,
    include_favicon: bool = None,
    **kwargs
) -> str:
    """
    Perform search optimized for question answering.

    Parameters:
    - query: Question to answer
    - search_depth: Search thoroughness (defaults to "advanced" for best answers)
    - topic: Domain specialization
    - days: How many days back to search
    - max_results: Maximum results to analyze
    - include_domains: Only search within these domains
    - exclude_domains: Exclude these domains
    - timeout: Request timeout in seconds
    - country: Geographic search constraint
    - include_favicon: Include favicon URLs

    Returns:
    String containing direct answer to the question
    """

Usage Examples:

# Direct question answering
answer = client.qna_search("What is the capital of France?")
print(answer)  # "Paris"

# Complex question with domain focus
answer = client.qna_search(
    query="How do neural networks learn?",
    topic="general",
    include_domains=["arxiv.org", "nature.com"]
)

Company Information Search

Specialized search for gathering comprehensive company information by searching across multiple topic areas (news, general, finance) and ranking results by relevance.

def get_company_info(
    query: str,
    search_depth: Literal["basic", "advanced"] = "advanced",
    max_results: int = 5,
    timeout: int = 60,
    country: str = None
) -> Sequence[dict]:
    """
    Search for comprehensive company information across multiple domains.

    Parameters:
    - query: Company name or related search term
    - search_depth: Search thoroughness level
    - max_results: Maximum results to return
    - timeout: Request timeout in seconds
    - country: Geographic search constraint

    Returns:
    List of search result dictionaries sorted by relevance score, containing:
    - title: Result title
    - url: Source URL
    - content: Content excerpt
    - score: Relevance score
    """

Usage Examples:

# Get company information
company_info = client.get_company_info("Tesla Inc")
for result in company_info:
    print(f"Score: {result['score']}")
    print(f"Title: {result['title']}")
    print(f"URL: {result['url']}")
    print(f"Content: {result['content'][:200]}...")

# Focused company search
startup_info = client.get_company_info(
    query="OpenAI company",
    max_results=3,
    country="US"
)

Common Parameters Reference

Search Depth Options

  • "basic": Fast search with essential results
  • "advanced": Comprehensive search with detailed analysis

Topic Specialization

  • "general": Broad web search across all domains
  • "news": Focus on news and current events
  • "finance": Financial and business information focus

Time Constraints

  • time_range: Predefined ranges ("day", "week", "month", "year")
  • start_date/end_date: Custom date range (YYYY-MM-DD)
  • days: Number of days back from current date

Content Inclusion

  • include_answer: AI summary (boolean or "basic"/"advanced")
  • include_raw_content: Full page content ("markdown" or "text")
  • include_images: Image URLs in results

Domain Filtering

  • include_domains: Whitelist specific domains
  • exclude_domains: Blacklist specific domains

Error Handling

Search operations can raise various exceptions:

from tavily import TavilyClient, InvalidAPIKeyError, UsageLimitExceededError, TimeoutError

try:
    results = client.search("query", timeout=30)
except TimeoutError as e:
    print(f"Search timed out after {e.timeout} seconds")
except UsageLimitExceededError:
    print("API usage limit exceeded")
except InvalidAPIKeyError:
    print("Invalid API key")

Install with Tessl CLI

npx tessl i tessl/pypi-tavily-python

docs

async.md

content.md

hybrid-rag.md

index.md

mapping.md

search.md

tile.json