Skip to content

AsyncTavilyClient

Base classes

Name Children Inherits
WebSearchProvider
searchly.base
Protocol for web search providers.
NewsSearchProvider
searchly.base
Protocol for news search providers.

â‹” Inheritance diagram

graph TD
  1633453573["client.AsyncTavilyClient"]
  4037333726["base.WebSearchProvider"]
  1073422405["typing.Protocol"]
  3481597255["typing.Generic"]
  2751680898["builtins.object"]
  2831882376["base.NewsSearchProvider"]
  4037333726 --> 1633453573
  1073422405 --> 4037333726
  3481597255 --> 1073422405
  2751680898 --> 3481597255
  2831882376 --> 1633453573
  1073422405 --> 2831882376

🛈 DocStrings

Bases: WebSearchProvider, NewsSearchProvider

Async client for Tavily API.

Note: Tavily does not support country/language filtering directly. These parameters are accepted for protocol compatibility but are ignored. News search is implemented via the topic="news" parameter.

Source code in src/searchly/providers/tavily_provider/client.py
class AsyncTavilyClient(WebSearchProvider, NewsSearchProvider):
    """Async client for Tavily API.

    Note: Tavily does not support country/language filtering directly.
    These parameters are accepted for protocol compatibility but are ignored.
    News search is implemented via the topic="news" parameter.
    """

    def __init__(self, *, api_key: str | None = None):
        """Initialize Tavily client.

        Args:
            api_key: Tavily API key. Defaults to TAVILY_API_KEY env var.
        """
        api_key = api_key or os.getenv("TAVILY_API_KEY")
        if not api_key:
            raise MissingAPIKeyError

        self.api_key = api_key
        self.headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}
        self.base_url = "https://api.tavily.com"
        self.timeout = 180

    def _client_creator(self) -> httpx2.AsyncClient:
        return httpx2.AsyncClient(
            headers=self.headers, base_url=self.base_url, timeout=self.timeout
        )

    async def _search(
        self,
        query: str,
        *,
        search_depth: SearchDepth = "basic",
        topic: str = "general",
        days: int = 3,
        max_results: int = 10,
        include_domains: Sequence[str] | None = None,
        exclude_domains: Sequence[str] | None = None,
        **kwargs: Any,
    ) -> dict[str, Any]:
        """Internal search method to send the request to the API."""
        data: dict[str, Any] = {
            "query": query,
            "search_depth": search_depth,
            "topic": topic,
            "days": days,
            "max_results": max_results,
            "include_domains": include_domains,
            "exclude_domains": exclude_domains,
            "include_answer": False,
            "include_raw_content": False,
            "include_images": False,
            **kwargs,
        }

        async with self._client_creator() as client:
            response = await client.post("/search", content=anyenv.dump_json(data))

        if response.status_code == 200:  # noqa: PLR2004
            return response.json()
        if response.status_code == 429:  # noqa: PLR2004
            detail = "Too many requests."
            with contextlib.suppress(Exception):
                detail = response.json()["detail"]["error"]
            raise UsageLimitExceededError(detail)
        if response.status_code == 401:  # noqa: PLR2004
            raise InvalidAPIKeyError
        response.raise_for_status()
        return response.json()

    async def web_search(
        self,
        query: str,
        *,
        max_results: int = 10,
        country: CountryCode | None = None,
        language: LanguageCode | None = None,
        search_depth: SearchDepth = "basic",
        days: int = 3,
        include_domains: Sequence[str] | None = None,
        exclude_domains: Sequence[str] | None = None,
        **kwargs: Any,
    ) -> WebSearchResponse:
        """Execute a web search query.

        Args:
            query: Search query string.
            max_results: Maximum number of results to return.
            country: Ignored (Tavily does not support country filtering).
            language: Ignored (Tavily does not support language filtering).
            search_depth: Search depth ("basic" or "advanced").
            days: Number of days back to search.
            include_domains: List of domains to include.
            exclude_domains: List of domains to exclude.
            **kwargs: Additional Tavily-specific options.

        Returns:
            Unified web search response.
        """
        response = await self._search(
            query,
            search_depth=search_depth,
            topic="general",
            days=days,
            max_results=max_results,
            include_domains=include_domains,
            exclude_domains=exclude_domains,
            **kwargs,
        )

        results = [
            WebSearchResult(
                title=item.get("title", ""),
                url=item.get("url", ""),
                snippet=item.get("content", ""),
            )
            for item in response.get("results", [])
        ]
        return WebSearchResponse(results=results[:max_results])

    async def news_search(
        self,
        query: str,
        *,
        max_results: int = 10,
        country: CountryCode | None = None,
        language: LanguageCode | None = None,
        search_depth: SearchDepth = "basic",
        days: int = 3,
        include_domains: Sequence[str] | None = None,
        exclude_domains: Sequence[str] | None = None,
        **kwargs: Any,
    ) -> NewsSearchResponse:
        """Execute a news search query.

        Args:
            query: Search query string.
            max_results: Maximum number of results to return.
            country: Ignored (Tavily does not support country filtering).
            language: Ignored (Tavily does not support language filtering).
            search_depth: Search depth ("basic" or "advanced").
            days: Number of days back to search.
            include_domains: List of domains to include.
            exclude_domains: List of domains to exclude.
            **kwargs: Additional Tavily-specific options.

        Returns:
            Unified news search response.
        """
        response = await self._search(
            query,
            search_depth=search_depth,
            topic="news",
            days=days,
            max_results=max_results,
            include_domains=include_domains,
            exclude_domains=exclude_domains,
            **kwargs,
        )

        results = [
            NewsSearchResult(
                title=item.get("title", ""),
                url=item.get("url", ""),
                snippet=item.get("content", ""),
                published=item.get("published_date"),
            )
            for item in response.get("results", [])
        ]
        return NewsSearchResponse(results=results[:max_results])

__init__

__init__(*, api_key: str | None = None)

Initialize Tavily client.

Parameters:

Name Type Description Default
api_key str | None

Tavily API key. Defaults to TAVILY_API_KEY env var.

None
Source code in src/searchly/providers/tavily_provider/client.py
def __init__(self, *, api_key: str | None = None):
    """Initialize Tavily client.

    Args:
        api_key: Tavily API key. Defaults to TAVILY_API_KEY env var.
    """
    api_key = api_key or os.getenv("TAVILY_API_KEY")
    if not api_key:
        raise MissingAPIKeyError

    self.api_key = api_key
    self.headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}
    self.base_url = "https://api.tavily.com"
    self.timeout = 180
news_search(
    query: str,
    *,
    max_results: int = 10,
    country: CountryCode | None = None,
    language: LanguageCode | None = None,
    search_depth: SearchDepth = "basic",
    days: int = 3,
    include_domains: Sequence[str] | None = None,
    exclude_domains: Sequence[str] | None = None,
    **kwargs: Any,
) -> NewsSearchResponse

Execute a news search query.

Parameters:

Name Type Description Default
query str

Search query string.

required
max_results int

Maximum number of results to return.

10
country CountryCode | None

Ignored (Tavily does not support country filtering).

None
language LanguageCode | None

Ignored (Tavily does not support language filtering).

None
search_depth SearchDepth

Search depth ("basic" or "advanced").

'basic'
days int

Number of days back to search.

3
include_domains Sequence[str] | None

List of domains to include.

None
exclude_domains Sequence[str] | None

List of domains to exclude.

None
**kwargs Any

Additional Tavily-specific options.

{}

Returns:

Type Description
NewsSearchResponse

Unified news search response.

Source code in src/searchly/providers/tavily_provider/client.py
async def news_search(
    self,
    query: str,
    *,
    max_results: int = 10,
    country: CountryCode | None = None,
    language: LanguageCode | None = None,
    search_depth: SearchDepth = "basic",
    days: int = 3,
    include_domains: Sequence[str] | None = None,
    exclude_domains: Sequence[str] | None = None,
    **kwargs: Any,
) -> NewsSearchResponse:
    """Execute a news search query.

    Args:
        query: Search query string.
        max_results: Maximum number of results to return.
        country: Ignored (Tavily does not support country filtering).
        language: Ignored (Tavily does not support language filtering).
        search_depth: Search depth ("basic" or "advanced").
        days: Number of days back to search.
        include_domains: List of domains to include.
        exclude_domains: List of domains to exclude.
        **kwargs: Additional Tavily-specific options.

    Returns:
        Unified news search response.
    """
    response = await self._search(
        query,
        search_depth=search_depth,
        topic="news",
        days=days,
        max_results=max_results,
        include_domains=include_domains,
        exclude_domains=exclude_domains,
        **kwargs,
    )

    results = [
        NewsSearchResult(
            title=item.get("title", ""),
            url=item.get("url", ""),
            snippet=item.get("content", ""),
            published=item.get("published_date"),
        )
        for item in response.get("results", [])
    ]
    return NewsSearchResponse(results=results[:max_results])
web_search(
    query: str,
    *,
    max_results: int = 10,
    country: CountryCode | None = None,
    language: LanguageCode | None = None,
    search_depth: SearchDepth = "basic",
    days: int = 3,
    include_domains: Sequence[str] | None = None,
    exclude_domains: Sequence[str] | None = None,
    **kwargs: Any,
) -> WebSearchResponse

Execute a web search query.

Parameters:

Name Type Description Default
query str

Search query string.

required
max_results int

Maximum number of results to return.

10
country CountryCode | None

Ignored (Tavily does not support country filtering).

None
language LanguageCode | None

Ignored (Tavily does not support language filtering).

None
search_depth SearchDepth

Search depth ("basic" or "advanced").

'basic'
days int

Number of days back to search.

3
include_domains Sequence[str] | None

List of domains to include.

None
exclude_domains Sequence[str] | None

List of domains to exclude.

None
**kwargs Any

Additional Tavily-specific options.

{}

Returns:

Type Description
WebSearchResponse

Unified web search response.

Source code in src/searchly/providers/tavily_provider/client.py
async def web_search(
    self,
    query: str,
    *,
    max_results: int = 10,
    country: CountryCode | None = None,
    language: LanguageCode | None = None,
    search_depth: SearchDepth = "basic",
    days: int = 3,
    include_domains: Sequence[str] | None = None,
    exclude_domains: Sequence[str] | None = None,
    **kwargs: Any,
) -> WebSearchResponse:
    """Execute a web search query.

    Args:
        query: Search query string.
        max_results: Maximum number of results to return.
        country: Ignored (Tavily does not support country filtering).
        language: Ignored (Tavily does not support language filtering).
        search_depth: Search depth ("basic" or "advanced").
        days: Number of days back to search.
        include_domains: List of domains to include.
        exclude_domains: List of domains to exclude.
        **kwargs: Additional Tavily-specific options.

    Returns:
        Unified web search response.
    """
    response = await self._search(
        query,
        search_depth=search_depth,
        topic="general",
        days=days,
        max_results=max_results,
        include_domains=include_domains,
        exclude_domains=exclude_domains,
        **kwargs,
    )

    results = [
        WebSearchResult(
            title=item.get("title", ""),
            url=item.get("url", ""),
            snippet=item.get("content", ""),
        )
        for item in response.get("results", [])
    ]
    return WebSearchResponse(results=results[:max_results])

:fa-brands-github: Show source on GitHub