Skip to content

AsyncKagiClient

Base classes

Name Children Inherits
HttpSessionMixin
searchly.http
Gives a provider one `anyenv.HttpSession`, opened on first use.
WebSearchProvider
searchly.base
Protocol for web search providers.

⋔ Inheritance diagram

graph TD
  4207035597["client.AsyncKagiClient"]
  1226828128["http.HttpSessionMixin"]
  2751680898["builtins.object"]
  4037333726["base.WebSearchProvider"]
  1073422405["typing.Protocol"]
  3481597255["typing.Generic"]
  1226828128 --> 4207035597
  2751680898 --> 1226828128
  4037333726 --> 4207035597
  1073422405 --> 4037333726
  3481597255 --> 1073422405
  2751680898 --> 3481597255

🛈 DocStrings

Bases: HttpSessionMixin, WebSearchProvider

Async client for Kagi API.

Note: Kagi Search API requires API billing to be set up at https://kagi.com/settings/billing_api

Source code in src/searchly/providers/kagi_provider/client.py
class AsyncKagiClient(HttpSessionMixin, WebSearchProvider):
    """Async client for Kagi API.

    Note: Kagi Search API requires API billing to be set up at
    https://kagi.com/settings/billing_api
    """

    def __init__(
        self,
        *,
        api_key: str | None = None,
        base_url: str = "https://kagi.com/api/v0",
    ):
        """Initialize Kagi client.

        Args:
            api_key: Kagi API key. Defaults to KAGI_API_KEY env var.
            base_url: Base URL for the API.
        """
        self.api_key = api_key or os.getenv("KAGI_API_KEY")
        if not self.api_key:
            msg = "No API key provided. Set KAGI_API_KEY env var or pass api_key"
            raise ValueError(msg)

        self.base_url = base_url
        self.headers = {"Authorization": f"Bot {self.api_key}"}

    async def web_search(
        self,
        query: str,
        *,
        max_results: int = 10,
        country: CountryCode | None = None,
        language: LanguageCode | None = None,
        **kwargs: Any,
    ) -> WebSearchResponse:
        """Execute a web search query.

        Args:
            query: Search query string.
            max_results: Maximum number of results to return.
            country: Country code (not used - Kagi inherits account settings).
            language: Language code (not used - Kagi inherits account settings).
            **kwargs: Additional Kagi-specific options.

        Returns:
            Unified web search response.

        Note:
            Kagi Search API inherits personalization settings from your account,
            including blocked/promoted sites and regional preferences.
        """
        # country/language not documented in Kagi API - settings inherited from account
        _ = country, language

        params: dict[str, Any] = {"q": query, "limit": max_results, **kwargs}

        url = f"{self.base_url}/search"
        session = await self._session()
        data = await session.get_json(url, params=params, headers=self.headers, return_type=dict)

        # Filter to search results (t=0), excluding related searches (t=1)
        results = [
            WebSearchResult(
                title=item.get("title") or "",
                url=item.get("url") or "",
                snippet=item.get("snippet") or "",
            )
            for item in data.get("data", [])
            if item.get("t") == 0 and item.get("url")
        ]
        return WebSearchResponse(results=results[:max_results])

    async def summarize(
        self,
        url: str | None = None,
        text: str | None = None,
        *,
        engine: SummaryEngine = "cecil",
        summary_type: SummaryType = "summary",
        target_language: str | None = None,
        cache: bool = True,
    ) -> str:
        """Get an AI-generated summary using the Kagi Universal Summarizer.

        Args:
            url: URL to summarize. Exclusive with text.
            text: Text to summarize. Exclusive with url.
            engine: Summarization engine (cecil, agnes, or muriel).
            summary_type: Type of summary (summary or takeaway).
            target_language: Target language code for translation (e.g., "EN", "DE").
            cache: Whether to allow cached requests/responses.

        Returns:
            Generated summary text.

        Raises:
            ValueError: If neither url nor text is provided, or both are provided.
        """
        if url and text:
            msg = "Provide either url or text, not both"
            raise ValueError(msg)
        if not url and not text:
            msg = "Either url or text must be provided"
            raise ValueError(msg)

        params: dict[str, Any] = {
            "engine": engine,
            "summary_type": summary_type,
            "cache": str(cache).lower(),
        }

        if url:
            params["url"] = url
        if text:
            params["text"] = text
        if target_language:
            params["target_language"] = target_language

        endpoint = f"{self.base_url}/summarize"
        session = await self._session()
        data = await session.get_json(
            endpoint, params=params, headers=self.headers, return_type=dict
        )
        return data.get("data", {}).get("output", "")

__init__

__init__(*, api_key: str | None = None, base_url: str = 'https://kagi.com/api/v0')

Initialize Kagi client.

Parameters:

Name Type Description Default
api_key str | None

Kagi API key. Defaults to KAGI_API_KEY env var.

None
base_url str

Base URL for the API.

'https://kagi.com/api/v0'
Source code in src/searchly/providers/kagi_provider/client.py
def __init__(
    self,
    *,
    api_key: str | None = None,
    base_url: str = "https://kagi.com/api/v0",
):
    """Initialize Kagi client.

    Args:
        api_key: Kagi API key. Defaults to KAGI_API_KEY env var.
        base_url: Base URL for the API.
    """
    self.api_key = api_key or os.getenv("KAGI_API_KEY")
    if not self.api_key:
        msg = "No API key provided. Set KAGI_API_KEY env var or pass api_key"
        raise ValueError(msg)

    self.base_url = base_url
    self.headers = {"Authorization": f"Bot {self.api_key}"}

summarize async

summarize(
    url: str | None = None,
    text: str | None = None,
    *,
    engine: SummaryEngine = "cecil",
    summary_type: SummaryType = "summary",
    target_language: str | None = None,
    cache: bool = True,
) -> str

Get an AI-generated summary using the Kagi Universal Summarizer.

Parameters:

Name Type Description Default
url str | None

URL to summarize. Exclusive with text.

None
text str | None

Text to summarize. Exclusive with url.

None
engine SummaryEngine

Summarization engine (cecil, agnes, or muriel).

'cecil'
summary_type SummaryType

Type of summary (summary or takeaway).

'summary'
target_language str | None

Target language code for translation (e.g., "EN", "DE").

None
cache bool

Whether to allow cached requests/responses.

True

Returns:

Type Description
str

Generated summary text.

Raises:

Type Description
ValueError

If neither url nor text is provided, or both are provided.

Source code in src/searchly/providers/kagi_provider/client.py
async def summarize(
    self,
    url: str | None = None,
    text: str | None = None,
    *,
    engine: SummaryEngine = "cecil",
    summary_type: SummaryType = "summary",
    target_language: str | None = None,
    cache: bool = True,
) -> str:
    """Get an AI-generated summary using the Kagi Universal Summarizer.

    Args:
        url: URL to summarize. Exclusive with text.
        text: Text to summarize. Exclusive with url.
        engine: Summarization engine (cecil, agnes, or muriel).
        summary_type: Type of summary (summary or takeaway).
        target_language: Target language code for translation (e.g., "EN", "DE").
        cache: Whether to allow cached requests/responses.

    Returns:
        Generated summary text.

    Raises:
        ValueError: If neither url nor text is provided, or both are provided.
    """
    if url and text:
        msg = "Provide either url or text, not both"
        raise ValueError(msg)
    if not url and not text:
        msg = "Either url or text must be provided"
        raise ValueError(msg)

    params: dict[str, Any] = {
        "engine": engine,
        "summary_type": summary_type,
        "cache": str(cache).lower(),
    }

    if url:
        params["url"] = url
    if text:
        params["text"] = text
    if target_language:
        params["target_language"] = target_language

    endpoint = f"{self.base_url}/summarize"
    session = await self._session()
    data = await session.get_json(
        endpoint, params=params, headers=self.headers, return_type=dict
    )
    return data.get("data", {}).get("output", "")
web_search(
    query: str,
    *,
    max_results: int = 10,
    country: CountryCode | None = None,
    language: LanguageCode | 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

Country code (not used - Kagi inherits account settings).

None
language LanguageCode | None

Language code (not used - Kagi inherits account settings).

None
**kwargs Any

Additional Kagi-specific options.

{}

Returns:

Type Description
WebSearchResponse

Unified web search response.

Note

Kagi Search API inherits personalization settings from your account, including blocked/promoted sites and regional preferences.

Source code in src/searchly/providers/kagi_provider/client.py
async def web_search(
    self,
    query: str,
    *,
    max_results: int = 10,
    country: CountryCode | None = None,
    language: LanguageCode | None = None,
    **kwargs: Any,
) -> WebSearchResponse:
    """Execute a web search query.

    Args:
        query: Search query string.
        max_results: Maximum number of results to return.
        country: Country code (not used - Kagi inherits account settings).
        language: Language code (not used - Kagi inherits account settings).
        **kwargs: Additional Kagi-specific options.

    Returns:
        Unified web search response.

    Note:
        Kagi Search API inherits personalization settings from your account,
        including blocked/promoted sites and regional preferences.
    """
    # country/language not documented in Kagi API - settings inherited from account
    _ = country, language

    params: dict[str, Any] = {"q": query, "limit": max_results, **kwargs}

    url = f"{self.base_url}/search"
    session = await self._session()
    data = await session.get_json(url, params=params, headers=self.headers, return_type=dict)

    # Filter to search results (t=0), excluding related searches (t=1)
    results = [
        WebSearchResult(
            title=item.get("title") or "",
            url=item.get("url") or "",
            snippet=item.get("snippet") or "",
        )
        for item in data.get("data", [])
        if item.get("t") == 0 and item.get("url")
    ]
    return WebSearchResponse(results=results[:max_results])

:fa-brands-github: Show source on GitHub