Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Tavily Python
https://github.com/tavily-ai/tavily-python
Admin
A python wrapper for Tavily search API
Tokens:
67,742
Snippets:
333
Trust Score:
8.7
License:
MIT
Update:
2 weeks ago
Context
Chat
Benchmark
89.63
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Usage example for get_max_items_from_list Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/utils.md Example call with a list of dicts and a custom max_tokens value. ```python from tavily.utils import get_max_items_from_list context = get_max_items_from_list( [{"url": "https://a.com", "content": "..."}], max_tokens=2000, ) ``` -------------------------------- ### Usage example for get_total_tokens_from_string Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/utils.md Example calls with default and custom encoding, printing token counts. ```python from tavily.utils import get_total_tokens_from_string n = get_total_tokens_from_string("Hello world") # uses gpt-3.5-turbo n2 = get_total_tokens_from_string("Hello world", "gpt-4") print(n, n2) ``` -------------------------------- ### Map a website with instructions using TavilyClient.map Source: https://github.com/tavily-ai/tavily-python/blob/master/README.md Use TavilyClient.map to discover and visualize a website's structure starting from a base URL. The example sets max_depth=2, limit=30, and instructions to focus on citrus fruit pages, then prints each result URL. ```python 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']}") ``` -------------------------------- ### qna_search() usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Example call to the deprecated qna_search() method. Prints the answer string returned by the method. ```python answer = client.qna_search("Who is Leo Messi?") print(answer) ``` -------------------------------- ### get_search_context() async usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Example call to async get_search_context() with a query. ```python context = await client.get_search_context("What happened during the Burning Man floods?") ``` -------------------------------- ### qna_search() async usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Example call to the async qna_search() method. Returns the answer string for the given query. ```python answer = await client.qna_search("Who is Leo Messi?") ``` -------------------------------- ### Install tavily-python with pip Source: https://github.com/tavily-ai/tavily-python/blob/master/README.md Install the Tavily Python SDK from PyPI using pip. ```bash pip install tavily-python ``` -------------------------------- ### map() usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Calls client.map() with a starting URL, max_depth=2, and limit=30, then iterates over the results to print each URL. The response is a dict with a 'results' key. ```python response = client.map("https://wikipedia.org/wiki/Lemon", max_depth=2, limit=30) for result in response["results"]: print(result["url"]) ``` -------------------------------- ### feedback() usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Example of calling the async feedback() method with request_id, agent_score, and comment. ```python await client.feedback(request_id="req-1", agent_score=0.8, comment="good") ``` -------------------------------- ### Get a quick answer to a question Source: https://github.com/tavily-ai/tavily-python/blob/master/README.md Uses qna_search to get accurate and concise answers to questions in one line of code. Perfect for usage by LLMs. ```python from tavily import TavilyClient # Step 1. Instantiating your 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) ``` -------------------------------- ### get_company_info() error handling example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Example of catching UsageLimitExceededError when calling get_company_info(). Demonstrates handling rate limiting errors. ```python try: await client.get_company_info("Nvidia") except UsageLimitExceededError as e: print("rate limited:", e) ``` -------------------------------- ### crawl() error handling example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Demonstrates catching KeylessUnsupportedEndpointError when calling crawl. The example imports the exception and prints the error message. ```python from tavily import KeylessUnsupportedEndpointError try: await client.crawl("https://wikipedia.org") except KeylessUnsupportedEndpointError as e: print(e) ``` -------------------------------- ### crawl() usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Shows how to call the async crawl method with a URL, max_depth=2, and limit=10. ```python response = await client.crawl("https://wikipedia.org/wiki/Lemon", max_depth=2, limit=10) ``` -------------------------------- ### crawl() usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Shows how to instantiate TavilyClient with an API key and call crawl() with url, max_depth, limit, and instructions. Iterates over results to print each URL and the first 200 characters of raw_content. ```python client = TavilyClient(api_key="tvly-YOUR_API_KEY") response = client.crawl("https://wikipedia.org/wiki/Lemon", max_depth=3, limit=50, instructions="Find all pages on citrus fruits") for result in response["results"]: print(result["url"], result["raw_content"][:200]) ``` -------------------------------- ### Basic async search example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Shows how to perform an async search with the AsyncTavilyClient. Requires an API key. The response is a dict with a 'results' key. The client must be closed after use. ```python import asyncio from tavily import AsyncTavilyClient async def main(): client = AsyncTavilyClient(api_key="tvly-YOUR_API_KEY") response = await client.search("Who is Leo Messi?", search_depth="advanced", max_results=5) print(response["results"]) await client.close() asyncio.run(main()) ``` -------------------------------- ### map() async usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Example call to async map() with max_depth=1. ```python result = await client.map("https://wikipedia.org", max_depth=1) ``` -------------------------------- ### extract() usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Shows how to call extract() with a single URL and include_images=True, then iterate over results and print URL and first 100 characters of raw_content, plus failed results. ```python response = client.extract("https://en.wikipedia.org/wiki/Artificial_intelligence", include_images=True) for result in response["results"]: print(result["url"], result["raw_content"][:100]) print("failed:", response["failed_results"]) ``` -------------------------------- ### extract() usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Shows how to call the async extract method with a single URL, extract_depth='basic', and format='markdown'. The response dict contains 'results' and 'failed_results' keys; the example prints their lengths. ```python response = await client.extract("https://tavily.com", extract_depth="basic", format="markdown") print(len(response["results"]), len(response["failed_results"])) ``` -------------------------------- ### get_company_info() async usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Example call to get_company_info() with custom search_depth and max_results. Iterates over the returned results and prints each title and score. ```python results = await client.get_company_info("Nvidia", search_depth="advanced", max_results=7) for r in results: print(r["title"], r["score"]) ``` -------------------------------- ### crawl() Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Asynchronously crawls a website starting from a given URL with configurable depth, breadth, and filtering options. Raises KeylessUnsupportedEndpointError when keyless. ```APIDOC ## `crawl()` ### Description Asynchronously crawls a website starting from a given URL with configurable depth, breadth, and filtering options. Raises KeylessUnsupportedEndpointError when keyless. ### Method `crawl` ### Endpoint `client.crawl()` ### Parameters - **url** (str) - Required - The starting URL to crawl - **max_depth** (int) - Optional - Maximum depth to crawl - **max_breadth** (int) - Optional - Maximum breadth to crawl - **limit** (int) - Optional - Limit on number of pages - **instructions** (str) - Optional - Instructions for the crawl - **select_paths** (Sequence[str]) - Optional - Paths to select - **select_domains** (Sequence[str]) - Optional - Domains to select - **exclude_paths** (Sequence[str]) - Optional - Paths to exclude - **exclude_domains** (Sequence[str]) - Optional - Domains to exclude - **allow_external** (bool) - Optional - Allow external links - **extract_depth** (Literal["basic", "advanced"]) - Optional - Depth of extraction - **include_images** (bool) - Optional - Include images - **format** (Literal["markdown", "text"]) - Optional - Output format - **timeout** (float) - Optional - Timeout in seconds (default: 150) - **include_favicon** (bool) - Optional - Include favicon - **include_usage** (bool) - Optional - Include usage information - **chunks_per_source** (int) - Optional - Number of chunks per source - **kwargs** - Optional - Accept custom arguments ### Request Example ```python response = await client.crawl("https://wikipedia.org/wiki/Lemon", max_depth=2, limit=10) ``` ### Response #### Success Response - **results** (list) - Crawled results - **failed_results** (list) - Failed results #### Response Example ```python response = await client.crawl("https://wikipedia.org/wiki/Lemon", max_depth=2, limit=10) ``` ### Errors - **KeylessUnsupportedEndpointError** - Raised when keyless ``` -------------------------------- ### Async search error handling example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Demonstrates keyless mode and error handling for async search. Catches BadRequestError and TimeoutError. Note that keyless mode does not raise KeylessUnsupportedEndpointError. ```python from tavily import AsyncTavilyClient, BadRequestError, TimeoutError async def run(): client = AsyncTavilyClient() # keyless try: await client.search("hello", time_range="month") except (BadRequestError, TimeoutError) as e: print("search failed:", e) asyncio.run(run()) ``` -------------------------------- ### get_research() usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Example of calling the async get_research() method and printing the credits from the usage dict. ```python result = await client.get_research(request_id, include_usage=True) print(result.get("usage", {}).get("credits")) ``` -------------------------------- ### Handling TavilyKeylessLimitError Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/errors.md Example of catching TavilyKeylessLimitError when using a keyless TavilyClient. Prints the human-readable message and the error attributes. ```python from tavily import TavilyClient, TavilyKeylessLimitError client = TavilyClient() # keyless try: client.search("Who is Leo Messi?") except TavilyKeylessLimitError as e: print(e) # human-readable message print(e.code, e.window, e.retry_after_seconds, e.next_actions) ``` -------------------------------- ### feedback() error handling example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Example of catching ForbiddenError when calling feedback() with a timeout. ```python try: await client.feedback(request_id="req-1", timeout=5) except ForbiddenError as e: print("forbidden:", e) ``` -------------------------------- ### Example usage of get_search_context() Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Calls the deprecated method with a query and max_tokens=4000, then prints the returned JSON string. The output is a JSON list of {'url': str, 'content': str} dicts trimmed to max_tokens. ```python context = client.get_search_context("What happened during the Burning Man floods?", max_tokens=4000) print(context) ``` -------------------------------- ### Catching KeylessUnsupportedEndpointError Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/errors.md Example of catching the exception when calling a non-keyless method (e.g., 'crawl') with a keyless client. The error's 'method' attribute is printed to show which method failed. ```python from tavily import TavilyClient, KeylessUnsupportedEndpointError client = TavilyClient() # keyless try: client.crawl("https://wikipedia.org") except KeylessUnsupportedEndpointError as e: print(e.method, "is not available in keyless mode.") ``` -------------------------------- ### feedback() usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Searches for a query, then submits feedback using the request ID, an agent score, per-result scores, used IDs, and the delivered response. The response_delivered string is the final answer produced using the results. ```python response = client.search("What happened in the latest Burning Man floods?") client.feedback( request_id=response["request_id"], agent_score=0.7, urls_scores=[{"id": response["results"][0]["id"], "agent_score": 0.9}], used_ids=[response["results"][0]["id"]], response_delivered="Heavy rain flooded the Burning Man site.", ) ``` -------------------------------- ### extract() error handling example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Demonstrates catching InvalidAPIKeyError when calling extract with a list of URLs and a timeout of 10 seconds. The example includes a non-URL string to show error handling. ```python try: await client.extract(["https://a.com", "not-a-url"], timeout=10) except InvalidAPIKeyError as e: print("auth failed:", e) ``` -------------------------------- ### map() Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Maps a website by traversing links from a starting URL. Returns a dictionary containing the mapping results, including a list of URLs. ```APIDOC ## map() ### Description Maps a website by traversing links from a starting URL. Returns a dictionary containing the mapping results, including a list of URLs. ### Method `map` ### Signature ```python def map(self, url: str, max_depth: int = None, max_breadth: int = None, limit: int = None, instructions: str = None, select_paths: Sequence[str] = None, select_domains: Sequence[str] = None, exclude_paths: Sequence[str] = None, exclude_domains: Sequence[str] = None, allow_external: bool = None, include_images: bool = None, timeout: float = 150, include_usage: bool = None, **kwargs ) -> dict: ``` ### Parameters - `url` (str) - Required - Starting URL. - `max_depth` (int) - Optional - Traversal bound. - `max_breadth` (int) - Optional - Traversal bound. - `limit` (int) - Optional - Traversal bound. - `instructions` (str) - Optional - Natural-language mapping focus. - `select_paths` (Sequence[str]) - Optional - Path filter. - `select_domains` (Sequence[str]) - Optional - Domain filter. - `exclude_paths` (Sequence[str]) - Optional - Path filter. - `exclude_domains` (Sequence[str]) - Optional - Domain filter. - `allow_external` (bool) - Optional - Allow leaving the starting domain. - `include_images` (bool) - Optional - Include images. - `timeout` (float) - Optional - Timeout, not capped. Default: 150. - `include_usage` (bool) - Optional - Credit usage. - `**kwargs` (any) - Optional - Extra body fields / header overrides. ### Returns `dict` - Map JSON (results expose `url` per README). ### Throws - `KeylessUnsupportedEndpointError` when keyless. - SDK errors / `TimeoutError`. ### Example ```python response = client.map("https://wikipedia.org/wiki/Lemon", max_depth=2, limit=30) for result in response["results"]: print(result["url"]) ``` ``` -------------------------------- ### Catching TavilyClient errors Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/errors.md Example of how to catch various TavilyClient errors in consumer code, including keyless-specific errors and timeout errors. ```APIDOC ## Catching TavilyClient errors ### Description Example of how to catch various TavilyClient errors in consumer code, including keyless-specific errors and timeout errors. ### Method TRY-CATCH ### Endpoint `client.search("hello")` ### Errors - **KeylessUnsupportedEndpointError** - Raised in keyless mode for unsupported methods (before network). - **TavilyKeylessLimitError** - Subclass of `UsageLimitExceededError` for keyless rate-limit envelope. - **UsageLimitExceededError** - HTTP 429. - **InvalidAPIKeyError** - HTTP 401. - **ForbiddenError** - HTTP 403/432/433. - **BadRequestError** - HTTP 400. - **TimeoutError** - Request timed out (import from `tavily.errors`). ### Example ```python from tavily import ( TavilyClient, BadRequestError, ForbiddenError, InvalidAPIKeyError, UsageLimitExceededError, TavilyKeylessLimitError, KeylessUnsupportedEndpointError, ) from tavily.errors import TimeoutError # NOT the builtin client = TavilyClient(api_key="tvly-...") try: response = client.search("hello") except KeylessUnsupportedEndpointError: ... # keyless mode + unsupported method (raised sync, before network) except TavilyKeylessLimitError: ... # keyless rate-limit envelope (subclass of UsageLimitExceededError) except UsageLimitExceededError: ... # HTTP 429 except InvalidAPIKeyError: ... # HTTP 401 except ForbiddenError: ... # HTTP 403/432/433 except BadRequestError: ... # HTTP 400 except TimeoutError: ... # request timed out ``` ``` -------------------------------- ### crawl() Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Crawls a website starting from a given URL, following links up to specified depth and breadth limits. Returns a dictionary containing crawl results with URLs and raw content. ```APIDOC ## `crawl()` ### Description Crawls a website starting from a given URL, following links up to specified depth and breadth limits. Returns a dictionary containing crawl results with URLs and raw content. ### Method `crawl()` ### Endpoint `TavilyClient.crawl()` ### Parameters - **url** (`str`) - Required - Starting URL. - **max_depth** (`int`) - Optional - Traversal depth. - **max_breadth** (`int`) - Optional - Pages per level. - **limit** (`int`) - Optional - Total pages. - **instructions** (`str`) - Optional - Natural-language crawl focus. - **select_paths** (`Sequence[str]`) - Optional - Only follow these paths. - **select_domains** (`Sequence[str]`) - Optional - Only follow these domains. - **exclude_paths** (`Sequence[str]`) - Optional - Skip these paths. - **exclude_domains** (`Sequence[str]`) - Optional - Skip these domains. - **allow_external** (`bool`) - Optional - Allow leaving the starting domain. - **include_images** (`bool`) - Optional - Include images. - **extract_depth** (`Literal["basic", "advanced"]`) - Optional - Per-page extraction depth. - **format** (`Literal["markdown", "text"]`) - Optional - Page content format. - **timeout** (`float`) - Optional - Timeout in seconds (default 150). - **include_favicon** (`bool`) - Optional - Include favicons. - **include_usage** (`bool`) - Optional - Credit usage. - **chunks_per_source** (`int`) - Optional - Max chunks per page. - **kwargs** (any) - Optional - Extra body fields / header overrides. ### Request Example ```python client = TavilyClient(api_key="tvly-YOUR_API_KEY") response = client.crawl("https://wikipedia.org/wiki/Lemon", max_depth=3, limit=50, instructions="Find all pages on citrus fruits") ``` ### Response #### Success Response Returns a dictionary with crawl results. Each result exposes `url` and `raw_content`. #### Response Example ```python for result in response["results"]: print(result["url"], result["raw_content"][:200]) ``` ### Errors - `KeylessUnsupportedEndpointError` - Raised when no API key is provided. - `TimeoutError` - Raised on timeout. - Other SDK errors may occur. ``` -------------------------------- ### Get and print full Search API response Source: https://github.com/tavily-ai/tavily-python/blob/master/README.md Instantiates a TavilyClient and performs a simple search query, then prints the full response object. Replace 'tvly-YOUR_API_KEY' with your actual API key. ```python 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) ``` -------------------------------- ### get_research() usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Calls get_research with a request ID and include_usage=True, then prints the status and credit usage. The usage dict is available when requested and present in the response. ```python result = client.get_research(request_id, include_usage=True) print(result["status"], result.get("usage", {}).get("credits")) ``` -------------------------------- ### Crawl a website with instructions using TavilyClient.crawl Source: https://github.com/tavily-ai/tavily-python/blob/master/README.md Use this snippet to crawl a website starting from a base URL with the Tavily Crawl API, which is currently invite-only. It sets max_depth=3, limit=50, and instructions to surface only pages about citrus fruits, then prints each result's URL and a 200-character snippet of raw content. ```python 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") ``` -------------------------------- ### Create a research task and retrieve results with TavilyClient.research Source: https://github.com/tavily-ai/tavily-python/blob/master/README.md Use TavilyClient.research to create a research task and retrieve the results. The example uses model='pro' and citation_format='apa', then fetches the report with get_research and prints status, content, and source count. ```python 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") ``` -------------------------------- ### research() non-streaming usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Example call to research() with stream=False (default). Returns a task dict; the example accesses the 'request_id' key from the response. ```python response = client.research("Research the latest developments in AI", model="pro", citation_format="apa") request_id = response["request_id"] ``` -------------------------------- ### Instantiate TavilyClient with API key and keyless mode Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Shows two ways to create a TavilyClient: with an API key for full functionality, or without any arguments for keyless mode where only search and extract are available. ```python from tavily import TavilyClient client = TavilyClient(api_key="tvly-YOUR_API_KEY") # keyed keyless = TavilyClient() # keyless — search/extract only ``` -------------------------------- ### AsyncTavilyClient constructor Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/configuration.md Constructor options for the AsyncTavilyClient. Configure API key, proxy, base URL, headers, and optional injected HTTP client. ```APIDOC ## AsyncTavilyClient constructor ### Description Constructor options for the AsyncTavilyClient. Configure API key, proxy, base URL, headers, and optional injected HTTP client. ### Parameters - **api_key** (Optional[str]) - Optional - API key. Defaults to env `TAVILY_API_KEY` or `None`. - **company_info_tags** (Sequence[str]) - Optional - Topics searched concurrently by `get_company_info()`. Default: `("news", "general", "finance")`. - **proxies** (Optional[dict[str, str]]) - Optional - Proxy configuration. Defaults to env `TAVILY_HTTP_PROXY` / `TAVILY_HTTPS_PROXY`. Converted to scheme-keyed `httpx.AsyncHTTPTransport` mounts; only applied when no external `client` given. - **api_base_url** (Optional[str]) - Optional - Base URL. Default: `"https://api.tavily.com"`. Passed as `base_url` to the internal `httpx.AsyncClient`. - **client_source** (Optional[str]) - Optional - `X-Client-Source` header. Default: `"tavily-python"` (keyless: `"tavily-python-keyless"`). - **project_id** (Optional[str]) - Optional - `X-Project-ID` header. Defaults to env `TAVILY_PROJECT`. - **org_id** (Optional[str]) - Optional - `X-Tavily-Orgid` header. Defaults to env `TAVILY_ORG_ID`. - **session_id** (Optional[str]) - Optional - `X-Session-Id` header. - **human_id** (Optional[str]) - Optional - `X-Human-Id` header. - **client_name** (Optional[str]) - Optional - `X-Client-Name` header. - **client** (Optional[httpx.AsyncClient]) - Optional - Injected client (gateway auth). Makes `api_key` optional; existing headers win; `base_url` set only if empty; never closed by the SDK. ``` -------------------------------- ### TavilyClient Constructor Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/configuration.md Configuration options for instantiating a TavilyClient. These options control authentication, proxy settings, API base URL, and custom headers. ```APIDOC ## TavilyClient Constructor ### Description Configuration options for instantiating a TavilyClient. These options control authentication, proxy settings, API base URL, and custom headers. ### Constructor `TavilyClient(api_key=None, proxies=None, api_base_url=None, client_source=None, project_id=None, org_id=None, session_id=None, human_id=None, client_name=None, session=None)` ### Parameters - **api_key** (Optional[str]) - Optional - Key for `Authorization: Bearer`. `None`/`""` with no `session` ⇒ keyless mode. Defaults to env `TAVILY_API_KEY`. - **proxies** (Optional[dict[str, str]]) - Optional - `{"http": url, "https": url}`; empty dict/values ignored; existing session proxies win. Defaults to env `TAVILY_HTTP_PROXY` / `TAVILY_HTTPS_PROXY`. - **api_base_url** (Optional[str]) - Optional - Prefix for all endpoint paths. Defaults to `"https://api.tavily.com"`. - **client_source** (Optional[str]) - Optional - `X-Client-Source` header value. Defaults to `"tavily-python"` (keyless: `"tavily-python-keyless"`). - **project_id** (Optional[str]) - Optional - `X-Project-ID` header. Defaults to env `TAVILY_PROJECT`. - **org_id** (Optional[str]) - Optional - `X-Tavily-Orgid` header. Defaults to env `TAVILY_ORG_ID`. - **session_id** (Optional[str]) - Optional - `X-Session-Id` header. - **human_id** (Optional[str]) - Optional - `X-Human-Id` header (hashed server-side). - **client_name** (Optional[str]) - Optional - `X-Client-Name` header. - **session** (Optional[requests.Session]) - Optional - Injected session (gateway auth). Makes `api_key` optional; existing session headers/proxies take precedence; SDK sets only missing headers; never closes it. Defaults to new `requests.Session()`. ### Default Headers ```python { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}", # only when api_key set "X-Tavily-Access-Mode": "keyless", # only in keyless mode "X-Client-Source": "tavily-python" or "tavily-python-keyless", "X-Project-ID": ..., "X-Tavily-Orgid": ..., # only when set "X-Session-Id": ..., "X-Human-Id": ..., "X-Client-Name": ..., # only when set } ``` ``` -------------------------------- ### Behavior demonstration of get_max_items_from_list Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/utils.md Shows greedy inclusion until budget is exceeded; result length may be 0 or 1. ```python # Behavior: items are included greedily until the budget is exceeded items = [{"url": f"https://{i}.com", "content": "x" * 500} for i in range(5)] result = get_max_items_from_list(items, max_tokens=300) print(len(result)) # 0 or 1 depending on token counts — prefix stops at the budget ``` -------------------------------- ### research() streaming usage example Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Example call to research() with stream=True. Iterates over the generator, decoding each chunk as UTF-8. The response is closed via finally when exhausted. Catches exceptions and prints 'stream failed:' with the error. ```python stream = client.research("Research the latest developments in AI", model="pro", stream=True) try: for chunk in stream: print(chunk.decode('utf-8')) except Exception as e: print("stream failed:", e) ``` -------------------------------- ### TavilyClient.__init__ Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Creates a synchronous Tavily API client. Supports keyed and keyless modes, custom proxies, base URL, headers, and an optional requests.Session. ```APIDOC ## [CONSTRUCTOR] TavilyClient.__init__ ### Description Initializes a TavilyClient instance with optional API key, proxies, base URL, client source, project/org/session identifiers, and a custom requests.Session. ### Method Constructor ### Endpoint `TavilyClient(api_key=None, proxies=None, api_base_url=None, client_source=None, project_id=None, org_id=None, session_id=None, human_id=None, client_name=None, session=None)` ### Parameters #### Constructor Parameters - **api_key** (Optional[str]) - Optional - API key; defaults to env `TAVILY_API_KEY`; `None`/`""` with no session enables keyless mode. - **proxies** (Optional[dict[str, str]]) - Optional - HTTP/HTTPS proxies; defaults to env `TAVILY_HTTP_PROXY`/`TAVILY_HTTPS_PROXY`; args override env; existing session proxies take precedence. - **api_base_url** (Optional[str]) - Optional - Base URL for all endpoints; defaults to `"https://api.tavily.com"`. - **client_source** (Optional[str]) - Optional - Value for `X-Client-Source` header; defaults to `"tavily-python"` (keyless: `"tavily-python-keyless"`). - **project_id** (Optional[str]) - Optional - Value for `X-Project-ID` header; defaults to env `TAVILY_PROJECT`. - **org_id** (Optional[str]) - Optional - Value for `X-Tavily-Orgid` header; defaults to env `TAVILY_ORG_ID`. - **session_id** (Optional[str]) - Optional - Value for `X-Session-Id` header. - **human_id** (Optional[str]) - Optional - Value for `X-Human-Id` header (hashed server-side). - **client_name** (Optional[str]) - Optional - Value for `X-Client-Name` header. - **session** (Optional[requests.Session]) - Optional - Gateway session; if provided, `api_key` is optional; existing headers/proxies take precedence; never closed by the SDK. ### Request Example ```python from tavily import TavilyClient client = TavilyClient(api_key="tvly-YOUR_API_KEY") # keyed keyless = TavilyClient() # keyless — search/extract only ``` ```python import requests session = requests.Session() session.headers["Authorization"] = "Bearer your-gateway-token" TavilyClient(session=session, api_base_url="https://your-gateway.com/tavily") ``` ### Response #### Success Response - **client** (TavilyClient) - The initialized client instance. #### Response Example ```python client = TavilyClient(api_key="tvly-YOUR_API_KEY") ``` ``` -------------------------------- ### GET /research/{request_id} Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/endpoints.md Retrieves the results of a research task by its request ID. Optionally includes usage information. ```APIDOC ## [GET] {base_url}/research/{request_id} ### Description Retrieves the results of a research task by its request ID. Optionally includes usage information. ### Method GET ### Endpoint {base_url}/research/{request_id} ### Parameters #### Path Parameters - `request_id` (str) - Required - The ID of the research task #### Query Parameters - `include_usage` (bool) - Optional - Whether to include usage information (only sent when not None) ### Response #### Success Response (200 or 202) - Research results JSON dict #### Response Example { "results": "..." } ``` -------------------------------- ### qna_search() (deprecated) Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Performs a question-answering search and returns the answer string. This method is deprecated and forwards to _search with forced parameters. ```APIDOC ## qna_search() (deprecated) ### Description Performs a question-answering search and returns the answer string. This method is deprecated and forwards to _search with forced parameters. ### Method qna_search ### Signature ```python def qna_search(self, query: str, search_depth: Literal["basic", "advanced", "fast", "ultra-fast"] = "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: float = 60, country: str = None, include_favicon: bool = None, **kwargs, # Accept custom arguments ) -> str: ``` ### Parameters - **query** (str) - Required - Search query. - **search_depth** (Literal["basic", "advanced", "fast", "ultra-fast"]) - Optional - Default: "advanced". - **topic** (Literal["general", "news", "finance"]) - Optional - Default: "general". - **days** (int) - Optional - Default: 7. - **max_results** (int) - Optional - Default: 5. - **include_domains** (Sequence[str]) - Optional - Default: None. - **exclude_domains** (Sequence[str]) - Optional - Default: None. - **timeout** (float) - Optional - Default: 60. - **country** (str) - Optional - Default: None. - **include_favicon** (bool) - Optional - Default: None. - **kwargs** - Optional - Forwarded to _search, which forces include_answer=True, include_raw_content=False, include_images=False. ### Returns str - response_dict.get("answer", "") ### Throws - KeylessUnsupportedEndpointError when keyless - DeprecationWarning - SDK error mapping / TimeoutError ### Example ```python answer = client.qna_search("Who is Leo Messi?") print(answer) ``` ``` -------------------------------- ### qna_search() async method signature (deprecated) Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Async version of the deprecated qna_search() method. Accepts the same parameters and defaults as the sync version and returns a string (the answer field). Throws KeylessUnsupportedEndpointError when keyless and emits a DeprecationWarning. ```python async def qna_search(self, query: str, search_depth: Literal["basic", "advanced", "fast", "ultra-fast"] = "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: float = 60, country: str = None, include_favicon: bool = None, **kwargs, # Accept custom arguments ) -> str: ``` -------------------------------- ### GET /research/{request_id} Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/endpoints.md Retrieves the results of a research task. Supports the public method: get_research. Keyless access is not allowed. Timeout is passthrough. ```APIDOC ## GET /research/{request_id} ### Description Retrieves the results of a research task. Supports the public method: get_research. Keyless access is not allowed. Timeout is passthrough. ### Method GET ### Endpoint /research/{request_id} ### Parameters #### Path Parameters - **request_id** (string) - Required - The ID of the research request. ### Response #### Success Response (200) - **results** (object) - Research results. #### Response Example { "results": {} } ``` -------------------------------- ### Basic search with API key Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/tavily-client.md Creates a TavilyClient with an API key and performs a search with search_depth='advanced' and max_results=5, then prints the 'results' key from the response. ```python client = TavilyClient(api_key="tvly-YOUR_API_KEY") response = client.search("Who is Leo Messi?", search_depth="advanced", max_results=5) print(response["results"]) ``` -------------------------------- ### Default headers dict for TavilyClient Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/configuration.md Shows the resulting default headers stored in self.headers after constructing TavilyClient. Headers like Authorization, X-Tavily-Access-Mode, X-Project-ID, X-Tavily-Orgid, X-Session-Id, X-Human-Id, and X-Client-Name are only included when their corresponding options are set or when in keyless mode. ```python { "Content-Type": "application/json", "Authorization": f"Bearer {api_key}", # only when api_key set "X-Tavily-Access-Mode": "keyless", # only in keyless mode "X-Client-Source": "tavily-python" or "tavily-python-keyless", "X-Project-ID": ..., "X-Tavily-Orgid": ..., # only when set "X-Session-Id": ..., "X-Human-Id": ..., "X-Client-Name": ..., # only when set } ``` -------------------------------- ### Instantiate AsyncTavilyClient with API key Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Creates an AsyncTavilyClient using a Tavily API key. The key can also be provided via the TAVILY_API_KEY environment variable. ```python from tavily import AsyncTavilyClient client = AsyncTavilyClient(api_key="tvly-YOUR_API_KEY") ``` -------------------------------- ### Instantiate AsyncTavilyClient with custom httpx client Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Creates an AsyncTavilyClient using a pre-configured httpx.AsyncClient, e.g., for a gateway. When a client is provided, api_key is optional and existing headers take precedence. ```python import httpx custom = httpx.AsyncClient(headers={"Authorization": "Bearer your-gateway-token"}, base_url="https://your-gateway.com/tavily") client = AsyncTavilyClient(client=custom) ``` -------------------------------- ### Stream research results with TavilyClient.research stream=True Source: https://github.com/tavily-ai/tavily-python/blob/master/README.md Create a streaming research task by setting stream=True in research(). The example processes the stream as it arrives, decoding each chunk as UTF-8. ```python from tavily import TavilyClient # Step 1. Instantiating your TavilyClient tavily_client = TavilyClient(api_key="tvly-YOUR_API_KEY") # Step 2. Creating a streaming research task stream = tavily_client.research( input="Research the latest developments in AI", model="pro", stream=True ) # Step 3. Processing the stream as it arrives for chunk in stream: print(chunk.decode('utf-8')) ``` -------------------------------- ### qna_search() (deprecated) Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Asynchronously performs a question-and-answer search and returns the answer as a string. This method is deprecated and emits a DeprecationWarning. ```APIDOC ## [ASYNC] qna_search() ### Description Asynchronously performs a question-and-answer search and returns the answer as a string. This method is deprecated and emits a DeprecationWarning. ### Method Async method ### Endpoint `qna_search()` ### Parameters #### Query Parameters - `query` (str) - Required - The search query. - `search_depth` (Literal["basic", "advanced", "fast", "ultra-fast"]) - Optional - Default: "advanced" - Search depth. - `topic` (Literal["general", "news", "finance"]) - Optional - Default: "general" - Topic filter. - `days` (int) - Optional - Default: 7 - Number of days to search. - `max_results` (int) - Optional - Default: 5 - Maximum number of results. - `include_domains` (Sequence[str]) - Optional - Domains to include. - `exclude_domains` (Sequence[str]) - Optional - Domains to exclude. - `timeout` (float) - Optional - Default: 60 - Timeout in seconds. - `country` (str) - Optional - Country code. - `include_favicon` (bool) - Optional - Whether to include favicons. - `**kwargs` - Optional - Additional custom arguments. ### Request Example ```python answer = await client.qna_search("Who is Leo Messi?") ``` ### Response #### Success Response - Returns `str` - The answer field. #### Error Handling - Throws `KeylessUnsupportedEndpointError` when keyless. - Emits `DeprecationWarning`. ``` -------------------------------- ### Await research() for non-streaming response Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/api-reference/async-tavily-client.md Calls research() with stream=False (default) and awaits the result to get a parsed JSON dict containing request_id. Use this for a single research task response. ```python response = await client.research("Research the latest developments in AI", model="pro") request_id = response["request_id"] ``` -------------------------------- ### POST {base_url}/crawl Source: https://github.com/tavily-ai/tavily-python/blob/master/_autodocs/endpoints.md Crawls a website starting from the given URL, following links up to the specified depth and breadth. Returns a JSON dictionary containing the crawled content. ```APIDOC ## POST {base_url}/crawl ### Description Crawls a website starting from the given URL, following links up to the specified depth and breadth. Returns a JSON dictionary containing the crawled content. ### Method POST ### Endpoint {base_url}/crawl ### Parameters #### Request Body - **url** (str) - Required - The starting URL to crawl. - **max_depth** (int) - Optional - Maximum depth of the crawl. - **max_breadth** (int) - Optional - Maximum breadth of the crawl. - **limit** (int) - Optional - Maximum number of pages to crawl. - **instructions** (str) - Optional - Instructions for the crawler. - **select_paths** (list[str]) - Optional - Paths to select. - **select_domains** (list[str]) - Optional - Domains to select. - **exclude_paths** (list[str]) - Optional - Paths to exclude. - **exclude_domains** (list[str]) - Optional - Domains to exclude. - **allow_external** (bool) - Optional - Whether to allow external links. - **include_images** (bool) - Optional - Whether to include images. - **extract_depth** (Literal["basic","advanced"]) - Optional - Depth of extraction. - **format** (Literal["markdown","text"]) - Optional - Output format. - **timeout** (float) - Optional - Timeout in seconds. - **include_favicon** (bool) - Optional - Whether to include favicon. - **include_usage** (bool) - Optional - Whether to include usage information. - **chunks_per_source** (int) - Optional - Number of chunks per source. ### Response #### Success Response (200) - Returns a crawl JSON dict. #### Response Example { "crawl": "JSON dict" } ```