Quick Start

This guide provides a rapid introduction to performing your first web search using the Tavily Python SDK. By the end of this page, you will have a working Python script that queries the internet and prints structured, LLM-ready context.

Step 1: Initialize the Client

First, import the TavilyClient. If you have correctly set your TAVILY_API_KEY environment variable (as covered in the Installation guide), you can initialize the client without any arguments.

from tavily import TavilyClient

# The SDK automatically detects the TAVILY_API_KEY environment variable.
tavily_client = TavilyClient()

# Alternatively, you can pass it explicitly (not recommended for production code):
# tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY")

The most common operation is the .search() method. Let's ask a question that requires up-to-date knowledge.

# Execute a basic search query
response = tavily_client.search("What are the latest breakthroughs in solid-state batteries?")

Step 3: Understand the Response

The .search() method returns a Python dictionary containing metadata and an array of results. Each result represents a distinct webpage that Tavily has parsed.

import json

# Print the raw response metadata
print(f"Response Time: {response.get('response_time')} seconds")
print(f"Total Results: {len(response.get('results', []))}\n")

# Iterate through the returned web sources
for index, result in enumerate(response.get("results", [])):
    print(f"--- Source {index + 1} ---")
    print(f"Title:   {result['title']}")
    print(f"URL:     {result['url']}")
    print(f"Score:   {result['score']}")
    # The 'content' field contains the clean, extracted text snippet
    print(f"Content: {result['content'][:250]}...\n")

What makes this different from a standard search engine?

Notice the content field in the output. Instead of a standard 160-character meta description meant for human eyes, Tavily returns a dense, fact-rich snippet extracted directly from the webpage's body. This is specifically optimized to be injected into an LLM's prompt window to provide context.

Step 4: Graceful Error Handling

When building production systems, you should anticipate network issues or rate limits. The Tavily SDK provides custom exceptions you can catch.

from tavily.errors import UsageLimitExceededError, InvalidAPIKeyError

try:
    response = tavily_client.search("Who won the last Super Bowl?")
    print("Success!")
except InvalidAPIKeyError:
    print("Error: Your API key is invalid or revoked. Check your dashboard.")
except UsageLimitExceededError:
    print("Error: You have run out of API credits or hit a rate limit.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Next Steps

You've successfully made your first request! From here, you can: