Tavily Python SDK

repository·master·Indexed 21 days ago

https://github.com/tavily-ai/tavily-python

A programmatic interface to the Tavily Search API for integrating AI-optimized search capabilities into Python applications. The SDK supports search, extraction, crawling, mapping, and research functionalities, including specialized methods for RAG applications like get_search_context and qna_search. It features both synchronous and asynchronous clients, keyless mode for basic search and extraction, and support for custom HTTP sessions for enterprise environments.

Tokens
4.1K
Snippets
12
Records
12
Agent score
30%

What's inside tavily-python

  1. Inject custom HTTP sessions for enterprise environments

    master

    In enterprise environments using API gateways, you can pass a pre-configured requests.Session (sync) or httpx.AsyncClient (async) to TavilyClient or AsyncTavilyClient instead of an api_key.

    Key Behaviors:

    • If a custom session/client is provided, api_key is optional.
    • Custom session headers take precedence over SDK defaults.
    • Custom session proxies take precedence over SDK proxy settings.
    • Lifecycle: The SDK will not close externally-provided sessions; you are responsible for managing their lifecycle.

    Sync Example:

    import requests
    from tavily import TavilyClient
    
    session = requests.Session()
    session.headers["Authorization"] = "Bearer your-gateway-token"
    
    client = TavilyClient(session=session, api_base_url="https://your-gateway.com/tavily")
    response = client.search("latest AI research")

    Async Example:

    import httpx
    from tavily import AsyncTavilyClient
    
    custom_client = httpx.AsyncClient(headers={"Authorization": "Bearer token"}, base_url="https://your-gateway.com/tavily")
    client = AsyncTavilyClient(client=custom_client)
    response = await client.search("latest AI research")
    import requests
    from tavily import TavilyClient
    
    # Pre-configure a session with your gateway's auth
    session = requests.Session()
    session.headers["Authorization"] = "Bearer your-gateway-token"
    session.headers["X-Subscription-Key"] = "your-subscription-key"
    
    # No Tavily API key needed — auth is handled by the session
    client = TavilyClient(
        session=session,
        api_base_url="https://your-gateway.com/tavily",
    )
    
    response = client.search("latest AI research")
  2. Use Tavily in Keyless Mode

    master

    You can use the SDK without an API key by instantiating TavilyClient() with no arguments. This runs against the public Tavily API and is subject to rate limits.

    Limitations:

    • Supports search() and extract() only.
    • Other methods will raise an error.
    • Rate limits are enforced; if reached, a TavilyKeylessLimitError is raised.

    When a TavilyKeylessLimitError occurs, the exception provides structured fields: code, window, retry_after_seconds, and next_actions to help handle the retry logic.

    from tavily import TavilyClient, TavilyKeylessLimitError
    
    # No API key needed
    client = TavilyClient()
    
    try:
        response = client.search("Who is Leo Messi?")
        print(response)
    except TavilyKeylessLimitError as e:
        # Rate-limit cap reached.
        print(e)
        print("retry after:", e.retry_after_seconds, "seconds")
  3. Configure Session and User Tracking identifiers

    master

    You can attribute requests to specific projects, sessions, users, or clients using optional identifiers. These are sent as HTTP headers:

    • project_id $\rightarrow$ X-Project-ID
    • session_id $\rightarrow$ X-Session-Id
    • human_id $\rightarrow$ X-Human-Id (hashed server-side)
    • client_name $\rightarrow$ X-Client-Name

    Identifiers can be set at client initialization (applied to all requests) or overridden on a per-call basis (per-call wins).

    from tavily import TavilyClient
    
    # Client-level
    client = TavilyClient(
        api_key="tvly-YOUR_API_KEY",
        project_id="my-project",
        session_id="my-session-123",
        human_id="internal-user-id-42",
        client_name="my-app",
    )
    
    # Per-call override
    client.search("hello", project_id="another-project")
    from tavily import TavilyClient
    
    # Client-level — applied to every request
    client = TavilyClient(
        api_key="tvly-YOUR_API_KEY",
        project_id="my-project",
        session_id="my-session-123",
        human_id="internal-user-id-42",
        client_name="my-app",
    )
    
    # Per-call override
    client.search("hello", project_id="another-project")
  4. Search with exact match for specific phrases

    master

    Use the exact_match=True parameter in search() to return only results containing the exact phrase(s) provided inside quotes in your query.

    from tavily import TavilyClient
    
    client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    
    # Use exact_match=True to only return results containing the exact phrase(s) inside quotes
    response = client.search(
        query='"John Smith" CEO Acme Corp',
        exact_match=True
    )
    print(response)
  5. Generate search context for RAG applications

    master

    Use get_search_context(query=...) to generate a single context string from search results. This is designed to be fed directly into Retrieval-Augmented Generation (RAG) applications.

    from tavily import TavilyClient
    
    tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    
    # Step 2. Executing a context search query
    context = tavily_client.get_search_context(query="What happened during the Burning Man floods?")
    
    # Step 3. That's it! You now have a context string that you can feed directly into your RAG Application
    print(context)
  6. Perform Research tasks

    master

    The research() method creates comprehensive research reports with automatic source gathering and analysis.

    Workflow:

    1. Call research() to create a task. It returns a request_id.
    2. Use get_research(request_id) to retrieve the results once the task is processed.

    Parameters for research():

    • input: The research topic.
    • model: The model to use (e.g., pro).
    • citation_format: Format for citations (e.g., apa).
    • stream: If True, returns a generator that yields chunks of the report.

    Example (Polling):

    response = tavily_client.research(input="AI developments", model="pro")
    request_id = response["request_id"]
    result = tavily_client.get_research(request_id)
    print(result['content'])

    Example (Streaming):

    stream = tavily_client.research(input="AI developments", model="pro", stream=True)
    for chunk in stream:
        print(chunk.decode('utf-8'))
    from tavily import TavilyClient
    
    # Step 1. Instantiating your TavilyClient
    tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    
    # Step 2. Creating a research task
    response = tavily_client.research(
        input="Research the latest developments in AI",
        model="pro",
        citation_format="apa"
    )
    
    # Step 3. Retrieving the research results
    request_id = response["request_id"]
    result = tavily_client.get_research(request_id)
    
    # Step 4. Printing the research report
    print(f"Status: {result['status']}")
    print(f"Content: {result['content']}")
    print(f"Sources: {len(result['sources'])} sources found")
  7. Perform a basic Tavily Search

    master

    Use TavilyClient.search() to search the web for a query. To use the full API, provide your API key during instantiation.

    from tavily import TavilyClient
    
    tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    response = tavily_client.search("Who is Leo Messi?")
    print(response)
    from tavily import TavilyClient
    
    # Step 1. Instantiating your TavilyClient
    tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    
    # Step 2. Executing a simple search query
    response = tavily_client.search("Who is Leo Messi?")
    
    # Step 3. That's it! You've done a Tavily Search!
    print(response)
  8. Crawl a website with instructions

    master

    The crawl() method traverses a website's content starting from a base URL.

    Note: Crawl is currently available on an invite-only basis.

    Parameters:

    • url: The starting URL.
    • max_depth: Maximum depth of traversal.
    • limit: Maximum number of pages to crawl.
    • instructions: Text instructions to guide the crawler (e.g., to find specific topics).
    from tavily import TavilyClient
    
    tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    
    start_url = "https://wikipedia.org/wiki/Lemon"
    
    response = tavily_client.crawl(
        url=start_url,
        max_depth=3,
        limit=50,
        instructions="Find all pages on citrus fruits"
    )
    
    for result in response["results"]:
        print(f"URL: {result['url']}")
        print(f"Snippet: {result['raw_content'][:200]}...\n")
    from tavily import TavilyClient
    
    # Step 1. Instantiating your TavilyClient
    tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    
    # Step 2. Defining the starting URL
    start_url = "https://wikipedia.org/wiki/Lemon"
    
    # Step 3. Executing the crawl request with instructions to surface only pages about citrus fruits
    response = tavily_client.crawl(
        url=start_url,
        max_depth=3,
        limit=50,
        instructions="Find all pages on citrus fruits"
    )
    
    # Step 4. Printing pages matching the query
    for result in response["results"]:
        print(f"URL: {result['url']}")
        print(f"Snippet: {result['raw_content'][:200]}...\n")
  9. Extract content from multiple URLs

    master

    Use extract(urls=..., include_images=...) to retrieve raw content from a list of URLs (up to 20 simultaneously).

    Response Structure:

    • results: A list of dictionaries containing url, raw_content, and images.
    • failed_results: A list of URLs that could not be extracted.
    from tavily import TavilyClient
    
    tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    
    urls = [
        "https://en.wikipedia.org/wiki/Artificial_intelligence",
        "https://en.wikipedia.org/wiki/Machine_learning"
    ]
    
    response = tavily_client.extract(urls=urls, include_images=True)
    
    for result in response["results"]:
        print(f"URL: {result['url']}")
        print(f"Raw Content: {result['raw_content']}")
        print(f"Images: {result['images']}\n")
    from tavily import TavilyClient
    
    # Step 1. Instantiating your TavilyClient
    tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    
    # Step 2. Defining the list of URLs to extract content from
    urls = [
        "https://en.wikipedia.org/wiki/Artificial_intelligence",
        "https://en.wikipedia.org/wiki/Machine_learning",
        "https://en.wikipedia.org/wiki/Data_science",
        "https://en.wikipedia.org/wiki/Quantum_computing",
        "https://en.wikipedia.org/wiki/Climate_change"
    ] # You can provide up to 20 URLs simultaneously
    
    # Step 3. Executing the extract request
    response = tavily_client.extract(urls=urls, include_images=True)
    
    # Step 4. Printing the extracted raw content
    for result in response["results"]:
        print(f"URL: {result['url']}")
        print(f"Raw Content: {result['raw_content']}")
        print(f"Images: {result['images']}\n")
    
    # Note that URLs that could not be extracted will be stored in response["failed_results"]
  10. Map a website structure

    master

    The map() method discovers and visualizes the structure of a website starting from a base URL.

    Parameters:

    • url: The starting URL.
    • max_depth: Maximum depth of traversal.
    • limit: Maximum number of pages to map.
    • instructions: Text instructions to focus the mapping on specific content.
    from tavily import TavilyClient
    
    tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    
    start_url = "https://wikipedia.org/wiki/Lemon"
    
    response = tavily_client.map(
        url=start_url,
        max_depth=2,
        limit=30,
        instructions="Find pages on citrus fruits"
    )
    
    for result in response["results"]:
        print(f"URL: {result['url']}")
    from tavily import TavilyClient
    
    # Step 1. Instantiating your TavilyClient
    tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    
    # Step 2. Defining the starting URL
    start_url = "https://wikipedia.org/wiki/Lemon"
    
    # Step 3. Executing the map request with parameters to focus on specific pages
    response = tavily_client.map(
        url=start_url,
        max_depth=2,
        limit=30,
        instructions="Find pages on citrus fruits"
    )
    
    # Step 4. Printing the site structure
    for result in response["results"]:
        print(f"URL: {result['url']}")
  11. Get quick answers with Q&A search

    master

    Use qna_search(query=...) to get accurate and concise answers to questions. This is optimized for use by LLMs.

    from tavily import TavilyClient
    
    tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")
    
    # Step 2. Executing a Q&A search query
    answer = tavily_client.qna_search(query="Who is Leo Messi?")
    
    # Step 3. That's it! Your question has been answered!
    print(answer)