keenable 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
keenable/__init__.py ADDED
@@ -0,0 +1,44 @@
1
+ """Keenable: web search and page fetch for AI agents.
2
+
3
+ Keyless by default. ``Keenable()`` works with no account; an API key only lifts
4
+ the hourly rate limit.
5
+
6
+ from keenable import Keenable
7
+
8
+ keenable = Keenable()
9
+ results = keenable.search("fastest inference providers 2026")
10
+ context = results.to_context()
11
+ """
12
+
13
+ from .client import DEFAULT_BASE_URL, AsyncKeenable, Keenable
14
+ from .errors import (
15
+ KeenableAPIError,
16
+ KeenableAuthError,
17
+ KeenableConnectionError,
18
+ KeenableError,
19
+ KeenableInvalidRequestError,
20
+ KeenableRateLimitError,
21
+ )
22
+ from .models import Page, SearchResponse, SearchResult
23
+ from .tools import FETCH_TOOL, SEARCH_TOOL, TOOLS, run_tool_call
24
+
25
+ __all__ = [
26
+ "AsyncKeenable",
27
+ "DEFAULT_BASE_URL",
28
+ "FETCH_TOOL",
29
+ "Keenable",
30
+ "KeenableAPIError",
31
+ "KeenableAuthError",
32
+ "KeenableConnectionError",
33
+ "KeenableError",
34
+ "KeenableInvalidRequestError",
35
+ "KeenableRateLimitError",
36
+ "Page",
37
+ "SEARCH_TOOL",
38
+ "SearchResponse",
39
+ "SearchResult",
40
+ "TOOLS",
41
+ "run_tool_call",
42
+ ]
43
+
44
+ __version__ = "0.1.0"
keenable/client.py ADDED
@@ -0,0 +1,401 @@
1
+ """Sync and async clients for the Keenable API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ipaddress
6
+ import os
7
+ from typing import Any
8
+ from urllib.parse import urlsplit
9
+
10
+ import httpx
11
+
12
+ from .errors import (
13
+ KeenableAPIError,
14
+ KeenableAuthError,
15
+ KeenableConnectionError,
16
+ KeenableInvalidRequestError,
17
+ KeenableRateLimitError,
18
+ )
19
+ from .models import Page, SearchResponse
20
+
21
+ __all__ = ["Keenable", "AsyncKeenable"]
22
+
23
+ try: # pragma: no cover - trivial
24
+ from importlib import metadata
25
+
26
+ _VERSION = metadata.version("keenable")
27
+ except Exception: # pragma: no cover - source checkouts
28
+ _VERSION = "unknown"
29
+
30
+ DEFAULT_BASE_URL = "https://api.keenable.ai"
31
+ DEFAULT_TIMEOUT = 30.0
32
+
33
+ # Keyless endpoints. A key is not a prerequisite for any call: it only lifts
34
+ # the hourly rate limit, so the client picks the endpoint by key presence.
35
+ _SEARCH_PUBLIC = "/v1/search/public"
36
+ _SEARCH_KEYED = "/v1/search"
37
+ _FETCH_PUBLIC = "/v1/fetch/public"
38
+ _FETCH_KEYED = "/v1/fetch"
39
+
40
+
41
+ def _resolve_base_url(base_url: str | None) -> str:
42
+ """Resolve and validate the API base URL, enforcing HTTPS off-localhost."""
43
+ base = (base_url or os.environ.get("KEENABLE_API_URL") or DEFAULT_BASE_URL).rstrip(
44
+ "/"
45
+ )
46
+ parsed = urlsplit(base)
47
+ if parsed.hostname:
48
+ if parsed.scheme == "https":
49
+ return base
50
+ if parsed.scheme == "http" and parsed.hostname in {
51
+ "localhost",
52
+ "127.0.0.1",
53
+ "::1",
54
+ }:
55
+ return base
56
+ raise KeenableInvalidRequestError(
57
+ f"base_url must be an https:// URL with a host, got {base!r}"
58
+ )
59
+
60
+
61
+ def _reject_private_fetch_target(url: str) -> None:
62
+ """Refuse obviously internal fetch targets before a request leaves the host.
63
+
64
+ The backend enforces this too, but stopping here keeps an internal hostname
65
+ out of an outbound request in the first place.
66
+ """
67
+ if not url.lower().startswith(("http://", "https://")):
68
+ raise KeenableInvalidRequestError(f"fetch() needs an http(s) URL, got {url!r}")
69
+
70
+ host = (urlsplit(url).hostname or "").strip().lower()
71
+ if not host:
72
+ raise KeenableInvalidRequestError(f"fetch() URL has no host: {url!r}")
73
+ if host in {"localhost", "metadata.google.internal"}:
74
+ raise KeenableInvalidRequestError(f"refusing to fetch internal host {host!r}")
75
+ try:
76
+ ip = ipaddress.ip_address(host)
77
+ except ValueError:
78
+ return # A hostname; the backend's SSRF guard is the backstop.
79
+ if (
80
+ ip.is_loopback
81
+ or ip.is_private
82
+ or ip.is_link_local
83
+ or ip.is_reserved
84
+ or ip.is_multicast
85
+ or ip.is_unspecified
86
+ ):
87
+ raise KeenableInvalidRequestError(f"refusing to fetch private address {host!r}")
88
+
89
+
90
+ def _search_payload(
91
+ query: str,
92
+ mode: str | None,
93
+ site: str | None,
94
+ published_after: str | None,
95
+ published_before: str | None,
96
+ acquired_after: str | None,
97
+ acquired_before: str | None,
98
+ snippet_max_length: int | None,
99
+ ) -> dict[str, Any]:
100
+ if not query or not query.strip():
101
+ raise KeenableInvalidRequestError("search() needs a non-empty query")
102
+
103
+ payload: dict[str, Any] = {"query": query, "mode": mode or "pro"}
104
+ optional = (
105
+ ("site", site),
106
+ ("published_after", published_after),
107
+ ("published_before", published_before),
108
+ ("acquired_after", acquired_after),
109
+ ("acquired_before", acquired_before),
110
+ ("snippet_max_length", snippet_max_length),
111
+ )
112
+ for name, value in optional:
113
+ if value is not None:
114
+ payload[name] = value
115
+ return payload
116
+
117
+
118
+ def _raise_for_status(response: httpx.Response) -> None:
119
+ """Turn a non-2xx response into the most specific SDK error available."""
120
+ if response.is_success:
121
+ return
122
+
123
+ detail = ""
124
+ try:
125
+ body = response.json()
126
+ if isinstance(body, dict):
127
+ detail = str(
128
+ body.get("message") or body.get("error") or body.get("detail") or ""
129
+ )
130
+ except ValueError:
131
+ detail = (response.text or "").strip()
132
+
133
+ status = response.status_code
134
+ label = {
135
+ 401: "Keenable authentication failed (401)",
136
+ 403: "Keenable authentication failed (403)",
137
+ 402: "Keenable: insufficient credits (402)",
138
+ 429: "Keenable rate limit exceeded (429)",
139
+ }.get(status, f"Keenable API error ({status})")
140
+ message = f"{label}: {detail}" if detail else label
141
+
142
+ if status in (401, 403):
143
+ raise KeenableAuthError(message, status, detail or None)
144
+ if status == 429:
145
+ raise KeenableRateLimitError(message, status, detail or None)
146
+ raise KeenableAPIError(message, status, detail or None)
147
+
148
+
149
+ def _decode(response: httpx.Response) -> dict[str, Any]:
150
+ _raise_for_status(response)
151
+ try:
152
+ data = response.json()
153
+ except ValueError as exc:
154
+ snippet = (response.text or "")[:200]
155
+ raise KeenableAPIError(
156
+ f"Keenable API returned a non-JSON response: {snippet!r}",
157
+ response.status_code,
158
+ ) from exc
159
+ if not isinstance(data, dict):
160
+ raise KeenableAPIError(
161
+ f"Unexpected response from the Keenable API: {data!r}",
162
+ response.status_code,
163
+ )
164
+ return data
165
+
166
+
167
+ class _BaseClient:
168
+ """Shared configuration for the sync and async clients."""
169
+
170
+ _sdk_flavor = "python"
171
+
172
+ def __init__(
173
+ self,
174
+ api_key: str | None = None,
175
+ *,
176
+ base_url: str | None = None,
177
+ timeout: float = DEFAULT_TIMEOUT,
178
+ ) -> None:
179
+ key = api_key if api_key is not None else os.environ.get("KEENABLE_API_KEY")
180
+ self._api_key = (key or "").strip() or None
181
+ self._base_url = _resolve_base_url(base_url)
182
+ self._timeout = timeout
183
+
184
+ @property
185
+ def keyless(self) -> bool:
186
+ """True when no API key is configured and the public tier is in use."""
187
+ return self._api_key is None
188
+
189
+ def _headers(self) -> dict[str, str]:
190
+ headers = {
191
+ "User-Agent": f"keenable-{self._sdk_flavor}/{_VERSION}",
192
+ "X-Keenable-Title": "Keenable SDK (Python)",
193
+ }
194
+ if self._api_key is not None:
195
+ headers["X-API-Key"] = self._api_key
196
+ return headers
197
+
198
+ def _search_url(self) -> str:
199
+ path = _SEARCH_PUBLIC if self._api_key is None else _SEARCH_KEYED
200
+ return f"{self._base_url}{path}"
201
+
202
+ def _fetch_url(self) -> str:
203
+ path = _FETCH_PUBLIC if self._api_key is None else _FETCH_KEYED
204
+ return f"{self._base_url}{path}"
205
+
206
+
207
+ class Keenable(_BaseClient):
208
+ """Synchronous client for the Keenable web search API.
209
+
210
+ Keyless by default: with no API key the client calls the public endpoints,
211
+ which are rate limited per hour. Pass ``api_key`` (or set
212
+ ``KEENABLE_API_KEY``) to lift that limit. Create a key at
213
+ https://keenable.ai/console.
214
+
215
+ Example:
216
+ >>> from keenable import Keenable
217
+ >>> keenable = Keenable()
218
+ >>> results = keenable.search("cerebras inference benchmarks")
219
+ >>> print(results.to_context())
220
+
221
+ The client can be reused across calls and is safe to keep for the lifetime
222
+ of your process. Use it as a context manager (or call :meth:`close`) to
223
+ release the underlying connection pool.
224
+ """
225
+
226
+ def __init__(
227
+ self,
228
+ api_key: str | None = None,
229
+ *,
230
+ base_url: str | None = None,
231
+ timeout: float = DEFAULT_TIMEOUT,
232
+ client: httpx.Client | None = None,
233
+ ) -> None:
234
+ super().__init__(api_key, base_url=base_url, timeout=timeout)
235
+ self._client = client or httpx.Client(timeout=timeout)
236
+ self._owns_client = client is None
237
+
238
+ def __enter__(self) -> Keenable:
239
+ return self
240
+
241
+ def __exit__(self, *exc_info: Any) -> None:
242
+ self.close()
243
+
244
+ def close(self) -> None:
245
+ """Close the underlying HTTP connection pool."""
246
+ if self._owns_client:
247
+ self._client.close()
248
+
249
+ def search(
250
+ self,
251
+ query: str,
252
+ *,
253
+ mode: str | None = None,
254
+ site: str | None = None,
255
+ published_after: str | None = None,
256
+ published_before: str | None = None,
257
+ acquired_after: str | None = None,
258
+ acquired_before: str | None = None,
259
+ snippet_max_length: int | None = None,
260
+ ) -> SearchResponse:
261
+ """Search the web and return ranked results with page text.
262
+
263
+ Args:
264
+ query: What to look for. Describe the ideal page in natural
265
+ language ("blog post comparing React and Vue performance")
266
+ rather than typing keywords; the index is semantic.
267
+ mode: Search mode. ``"pro"`` (the default) does deeper retrieval.
268
+ site: Restrict results to one domain, e.g. ``"arxiv.org"``.
269
+ published_after: Keep pages published on or after ``YYYY-MM-DD``.
270
+ published_before: Keep pages published on or before ``YYYY-MM-DD``.
271
+ acquired_after: Keep pages Keenable indexed on or after
272
+ ``YYYY-MM-DD``. Use this for "what is new since ..." queries,
273
+ where the publication date is unreliable or missing.
274
+ acquired_before: Keep pages indexed on or before ``YYYY-MM-DD``.
275
+ snippet_max_length: Cap the characters of page text per result.
276
+
277
+ Returns:
278
+ A :class:`SearchResponse`; iterate it for results or call
279
+ :meth:`SearchResponse.to_context` to build a prompt block.
280
+ """
281
+ payload = _search_payload(
282
+ query,
283
+ mode,
284
+ site,
285
+ published_after,
286
+ published_before,
287
+ acquired_after,
288
+ acquired_before,
289
+ snippet_max_length,
290
+ )
291
+ try:
292
+ response = self._client.post(
293
+ self._search_url(), json=payload, headers=self._headers()
294
+ )
295
+ except httpx.HTTPError as exc:
296
+ raise KeenableConnectionError(
297
+ f"could not reach the Keenable API: {exc!r}"
298
+ ) from exc
299
+ return SearchResponse._from_json(_decode(response), query)
300
+
301
+ def fetch(self, url: str) -> Page:
302
+ """Fetch one URL and return its main content as markdown.
303
+
304
+ Use this after :meth:`search` when a snippet is not enough and the
305
+ model needs the full page.
306
+ """
307
+ _reject_private_fetch_target(url)
308
+ try:
309
+ response = self._client.get(
310
+ self._fetch_url(), params={"url": url}, headers=self._headers()
311
+ )
312
+ except httpx.HTTPError as exc:
313
+ raise KeenableConnectionError(
314
+ f"could not reach the Keenable API: {exc!r}"
315
+ ) from exc
316
+ return Page._from_json(_decode(response), url)
317
+
318
+
319
+ class AsyncKeenable(_BaseClient):
320
+ """Asynchronous client for the Keenable web search API.
321
+
322
+ Mirrors :class:`Keenable` with awaitable methods.
323
+
324
+ Example:
325
+ >>> import asyncio
326
+ >>> from keenable import AsyncKeenable
327
+ >>> async def main():
328
+ ... async with AsyncKeenable() as keenable:
329
+ ... results = await keenable.search("wafer scale engine")
330
+ ... print(results.to_context())
331
+ >>> asyncio.run(main())
332
+ """
333
+
334
+ def __init__(
335
+ self,
336
+ api_key: str | None = None,
337
+ *,
338
+ base_url: str | None = None,
339
+ timeout: float = DEFAULT_TIMEOUT,
340
+ client: httpx.AsyncClient | None = None,
341
+ ) -> None:
342
+ super().__init__(api_key, base_url=base_url, timeout=timeout)
343
+ self._client = client or httpx.AsyncClient(timeout=timeout)
344
+ self._owns_client = client is None
345
+
346
+ async def __aenter__(self) -> AsyncKeenable:
347
+ return self
348
+
349
+ async def __aexit__(self, *exc_info: Any) -> None:
350
+ await self.aclose()
351
+
352
+ async def aclose(self) -> None:
353
+ """Close the underlying HTTP connection pool."""
354
+ if self._owns_client:
355
+ await self._client.aclose()
356
+
357
+ async def search(
358
+ self,
359
+ query: str,
360
+ *,
361
+ mode: str | None = None,
362
+ site: str | None = None,
363
+ published_after: str | None = None,
364
+ published_before: str | None = None,
365
+ acquired_after: str | None = None,
366
+ acquired_before: str | None = None,
367
+ snippet_max_length: int | None = None,
368
+ ) -> SearchResponse:
369
+ """Search the web. See :meth:`Keenable.search` for the arguments."""
370
+ payload = _search_payload(
371
+ query,
372
+ mode,
373
+ site,
374
+ published_after,
375
+ published_before,
376
+ acquired_after,
377
+ acquired_before,
378
+ snippet_max_length,
379
+ )
380
+ try:
381
+ response = await self._client.post(
382
+ self._search_url(), json=payload, headers=self._headers()
383
+ )
384
+ except httpx.HTTPError as exc:
385
+ raise KeenableConnectionError(
386
+ f"could not reach the Keenable API: {exc!r}"
387
+ ) from exc
388
+ return SearchResponse._from_json(_decode(response), query)
389
+
390
+ async def fetch(self, url: str) -> Page:
391
+ """Fetch one URL as markdown. See :meth:`Keenable.fetch`."""
392
+ _reject_private_fetch_target(url)
393
+ try:
394
+ response = await self._client.get(
395
+ self._fetch_url(), params={"url": url}, headers=self._headers()
396
+ )
397
+ except httpx.HTTPError as exc:
398
+ raise KeenableConnectionError(
399
+ f"could not reach the Keenable API: {exc!r}"
400
+ ) from exc
401
+ return Page._from_json(_decode(response), url)
keenable/errors.py ADDED
@@ -0,0 +1,40 @@
1
+ """Exceptions raised by the Keenable SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class KeenableError(Exception):
7
+ """Base class for every error raised by this SDK."""
8
+
9
+
10
+ class KeenableConnectionError(KeenableError):
11
+ """The Keenable API could not be reached (DNS, TLS, timeout, ...)."""
12
+
13
+
14
+ class KeenableAPIError(KeenableError):
15
+ """The Keenable API returned a non-2xx response.
16
+
17
+ ``status_code`` is the HTTP status and ``body`` the decoded error message
18
+ from the API when it sent one.
19
+ """
20
+
21
+ def __init__(self, message: str, status_code: int, body: str | None = None):
22
+ super().__init__(message)
23
+ self.status_code = status_code
24
+ self.body = body
25
+
26
+
27
+ class KeenableAuthError(KeenableAPIError):
28
+ """The API key was rejected (HTTP 401/403)."""
29
+
30
+
31
+ class KeenableRateLimitError(KeenableAPIError):
32
+ """The rate limit was exceeded (HTTP 429).
33
+
34
+ Keyless requests share a lower hourly cap. Setting ``KEENABLE_API_KEY``
35
+ lifts it; a key is never required to make a request.
36
+ """
37
+
38
+
39
+ class KeenableInvalidRequestError(KeenableError):
40
+ """The arguments passed to the SDK are invalid; no request was sent."""
keenable/models.py ADDED
@@ -0,0 +1,158 @@
1
+ """Typed results returned by the Keenable API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+ # Default budget for `to_context()`. Roughly 3k tokens: large enough that a
10
+ # handful of results keep their substance, small enough to sit in front of a
11
+ # user question without crowding out the rest of the prompt.
12
+ DEFAULT_CONTEXT_MAX_CHARS = 12_000
13
+
14
+
15
+ def _str_or_none(value: Any) -> str | None:
16
+ """Return a non-empty string, or None for anything else (incl. "")."""
17
+ if isinstance(value, str) and value.strip():
18
+ return value
19
+ return None
20
+
21
+
22
+ @dataclass
23
+ class SearchResult:
24
+ """A single web page returned by :meth:`Keenable.search`."""
25
+
26
+ title: str
27
+ url: str
28
+ snippet: str
29
+ """Page text extracted for this query. This is the field to put in a
30
+ prompt: it carries the actual content, unlike ``description``."""
31
+
32
+ description: str | None = None
33
+ """The page's meta description. Often absent; prefer ``snippet``."""
34
+
35
+ published_at: str | None = None
36
+ """ISO-8601 timestamp of publication, when the page exposes one."""
37
+
38
+ acquired_at: str | None = None
39
+ """ISO-8601 timestamp of when Keenable indexed the page."""
40
+
41
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
42
+ """The unmodified JSON object, so new API fields are reachable before this
43
+ SDK models them."""
44
+
45
+ @classmethod
46
+ def _from_json(cls, data: dict[str, Any]) -> SearchResult:
47
+ return cls(
48
+ title=str(data.get("title") or ""),
49
+ url=str(data.get("url") or ""),
50
+ snippet=str(data.get("snippet") or ""),
51
+ description=_str_or_none(data.get("description")),
52
+ published_at=_str_or_none(data.get("published_at")),
53
+ acquired_at=_str_or_none(data.get("acquired_at")),
54
+ raw=data,
55
+ )
56
+
57
+
58
+ @dataclass
59
+ class SearchResponse:
60
+ """The result set for one :meth:`Keenable.search` call."""
61
+
62
+ query: str
63
+ results: list[SearchResult]
64
+ mode: str | None = None
65
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
66
+
67
+ def __iter__(self) -> Iterator[SearchResult]:
68
+ return iter(self.results)
69
+
70
+ def __len__(self) -> int:
71
+ return len(self.results)
72
+
73
+ def __getitem__(self, index: int) -> SearchResult:
74
+ return self.results[index]
75
+
76
+ @classmethod
77
+ def _from_json(cls, data: dict[str, Any], query: str) -> SearchResponse:
78
+ raw_results = data.get("results")
79
+ results = (
80
+ [SearchResult._from_json(r) for r in raw_results if isinstance(r, dict)]
81
+ if isinstance(raw_results, list)
82
+ else []
83
+ )
84
+ return cls(
85
+ query=str(data.get("query") or query),
86
+ results=results,
87
+ mode=_str_or_none(data.get("mode")),
88
+ raw=data,
89
+ )
90
+
91
+ def to_context(
92
+ self,
93
+ max_chars: int = DEFAULT_CONTEXT_MAX_CHARS,
94
+ max_results: int | None = None,
95
+ include_dates: bool = True,
96
+ ) -> str:
97
+ """Render the results as a numbered, citable block for a prompt.
98
+
99
+ Each result becomes a ``[n] title (url)`` header followed by its
100
+ snippet, which lets the model cite sources by number and lets you map
101
+ those numbers back to URLs. Results are added whole until ``max_chars``
102
+ is reached, so a truncated context never ends mid-sentence.
103
+
104
+ Args:
105
+ max_chars: Approximate character budget for the whole block.
106
+ max_results: Keep at most this many results before the budget is
107
+ applied.
108
+ include_dates: Append the publication date to each header when the
109
+ page exposes one. Useful when recency matters to the answer.
110
+ """
111
+ blocks: list[str] = []
112
+ used = 0
113
+ selected = self.results if max_results is None else self.results[:max_results]
114
+
115
+ for index, result in enumerate(selected, start=1):
116
+ header = f"[{index}] {result.title} ({result.url})"
117
+ if include_dates and result.published_at:
118
+ header += f" - published {result.published_at}"
119
+ body = result.snippet or result.description or ""
120
+ block = f"{header}\n{body}".strip()
121
+
122
+ # +2 for the blank line between blocks. Stop rather than truncate:
123
+ # a half-sentence source reads as corrupted context to the model.
124
+ cost = len(block) + (2 if blocks else 0)
125
+ if blocks and used + cost > max_chars:
126
+ break
127
+ blocks.append(block)
128
+ used += cost
129
+
130
+ return "\n\n".join(blocks)
131
+
132
+
133
+ @dataclass
134
+ class Page:
135
+ """A web page fetched by :meth:`Keenable.fetch`, extracted as markdown."""
136
+
137
+ url: str
138
+ title: str
139
+ content: str
140
+ """The page's main content as markdown, with navigation and boilerplate
141
+ stripped."""
142
+
143
+ description: str | None = None
144
+ author: str | None = None
145
+ published_at: str | None = None
146
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
147
+
148
+ @classmethod
149
+ def _from_json(cls, data: dict[str, Any], url: str) -> Page:
150
+ return cls(
151
+ url=str(data.get("url") or url),
152
+ title=str(data.get("title") or ""),
153
+ content=str(data.get("content") or ""),
154
+ description=_str_or_none(data.get("description")),
155
+ author=_str_or_none(data.get("author")),
156
+ published_at=_str_or_none(data.get("published_at")),
157
+ raw=data,
158
+ )
keenable/tools.py ADDED
@@ -0,0 +1,160 @@
1
+ """Ready-made tool definitions for OpenAI-compatible tool calling.
2
+
3
+ Every major inference API (Cerebras, OpenAI, and anything speaking the same
4
+ schema) takes tools in this shape, so these constants can be passed straight
5
+ into a ``chat.completions.create(tools=...)`` call:
6
+
7
+ from keenable import Keenable, TOOLS, run_tool_call
8
+
9
+ tools = TOOLS # search + fetch
10
+ ...
11
+ output = run_tool_call(keenable, tool_call.function.name,
12
+ tool_call.function.arguments)
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from typing import Any
19
+
20
+ from .client import AsyncKeenable, Keenable
21
+ from .errors import KeenableInvalidRequestError
22
+
23
+ __all__ = ["SEARCH_TOOL", "FETCH_TOOL", "TOOLS", "run_tool_call", "arun_tool_call"]
24
+
25
+ SEARCH_TOOL: dict[str, Any] = {
26
+ "type": "function",
27
+ "function": {
28
+ "name": "keenable_search",
29
+ "description": (
30
+ "Search the web for current information. Returns ranked pages with "
31
+ "their title, URL and extracted page text. Use this whenever the "
32
+ "answer depends on recent events or facts you are unsure about."
33
+ ),
34
+ "parameters": {
35
+ "type": "object",
36
+ "properties": {
37
+ "query": {
38
+ "type": "string",
39
+ "description": (
40
+ "What to look for, described in natural language "
41
+ "rather than keywords."
42
+ ),
43
+ },
44
+ "site": {
45
+ "type": "string",
46
+ "description": (
47
+ "Optional. Restrict results to one domain, e.g. 'arxiv.org'."
48
+ ),
49
+ },
50
+ "published_after": {
51
+ "type": "string",
52
+ "description": (
53
+ "Optional. Only pages published on or after this date "
54
+ "(YYYY-MM-DD)."
55
+ ),
56
+ },
57
+ },
58
+ "required": ["query"],
59
+ },
60
+ },
61
+ }
62
+
63
+ FETCH_TOOL: dict[str, Any] = {
64
+ "type": "function",
65
+ "function": {
66
+ "name": "keenable_fetch",
67
+ "description": (
68
+ "Fetch one web page and return its main content as markdown. Use "
69
+ "after keenable_search when a search snippet is not enough."
70
+ ),
71
+ "parameters": {
72
+ "type": "object",
73
+ "properties": {
74
+ "url": {
75
+ "type": "string",
76
+ "description": "The URL of the page to read.",
77
+ },
78
+ },
79
+ "required": ["url"],
80
+ },
81
+ },
82
+ }
83
+
84
+ TOOLS: list[dict[str, Any]] = [SEARCH_TOOL, FETCH_TOOL]
85
+
86
+
87
+ def _parse_arguments(arguments: str | dict[str, Any]) -> dict[str, Any]:
88
+ """Accept the model's raw JSON string or an already-decoded dict."""
89
+ if isinstance(arguments, dict):
90
+ return arguments
91
+ try:
92
+ parsed = json.loads(arguments or "{}")
93
+ except json.JSONDecodeError as exc:
94
+ raise KeenableInvalidRequestError(
95
+ f"tool call arguments are not valid JSON: {arguments!r}"
96
+ ) from exc
97
+ if not isinstance(parsed, dict):
98
+ raise KeenableInvalidRequestError(
99
+ f"tool call arguments must be a JSON object, got {parsed!r}"
100
+ )
101
+ return parsed
102
+
103
+
104
+ def _search_kwargs(args: dict[str, Any]) -> dict[str, Any]:
105
+ """Keep only the arguments the tool schema exposes to the model."""
106
+ allowed = ("site", "published_after")
107
+ return {name: args[name] for name in allowed if args.get(name)}
108
+
109
+
110
+ def run_tool_call(
111
+ client: Keenable,
112
+ name: str,
113
+ arguments: str | dict[str, Any],
114
+ ) -> str:
115
+ """Execute one tool call and return the string to send back as the result.
116
+
117
+ Args:
118
+ client: The :class:`Keenable` client to run the call against.
119
+ name: The tool name the model chose (``keenable_search`` or
120
+ ``keenable_fetch``).
121
+ arguments: The model's arguments, as the raw JSON string from the API
122
+ or an already-decoded dict.
123
+
124
+ Returns:
125
+ Text ready to be attached to a ``role="tool"`` message.
126
+ """
127
+ args = _parse_arguments(arguments)
128
+ if name == "keenable_search":
129
+ query = args.get("query")
130
+ if not isinstance(query, str) or not query.strip():
131
+ raise KeenableInvalidRequestError("keenable_search needs a 'query'")
132
+ return client.search(query, **_search_kwargs(args)).to_context()
133
+ if name == "keenable_fetch":
134
+ url = args.get("url")
135
+ if not isinstance(url, str) or not url.strip():
136
+ raise KeenableInvalidRequestError("keenable_fetch needs a 'url'")
137
+ return client.fetch(url).content
138
+ raise KeenableInvalidRequestError(f"unknown Keenable tool: {name!r}")
139
+
140
+
141
+ async def arun_tool_call(
142
+ client: AsyncKeenable,
143
+ name: str,
144
+ arguments: str | dict[str, Any],
145
+ ) -> str:
146
+ """Async counterpart of :func:`run_tool_call`."""
147
+ args = _parse_arguments(arguments)
148
+ if name == "keenable_search":
149
+ query = args.get("query")
150
+ if not isinstance(query, str) or not query.strip():
151
+ raise KeenableInvalidRequestError("keenable_search needs a 'query'")
152
+ response = await client.search(query, **_search_kwargs(args))
153
+ return response.to_context()
154
+ if name == "keenable_fetch":
155
+ url = args.get("url")
156
+ if not isinstance(url, str) or not url.strip():
157
+ raise KeenableInvalidRequestError("keenable_fetch needs a 'url'")
158
+ page = await client.fetch(url)
159
+ return page.content
160
+ raise KeenableInvalidRequestError(f"unknown Keenable tool: {name!r}")
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.5
2
+ Name: keenable
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the Keenable web search API, built for AI agents
5
+ Project-URL: Homepage, https://keenable.ai
6
+ Project-URL: Documentation, https://github.com/keenableai/keenable-sdk#readme
7
+ Project-URL: Repository, https://github.com/keenableai/keenable-sdk
8
+ Project-URL: Issues, https://github.com/keenableai/keenable-sdk/issues
9
+ Author-email: Keenable <support@keenable.ai>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,grounding,keenable,llm,rag,search,web-search
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.9
24
+ Requires-Dist: httpx>=0.27
25
+ Description-Content-Type: text/markdown
26
+
27
+ # keenable
28
+
29
+ Official Python SDK for [Keenable](https://keenable.ai), a web search API built
30
+ for AI agents: ranked results that come back with the page text already
31
+ extracted, plus a fetch endpoint that returns any URL as clean markdown.
32
+
33
+ **Keyless by default.** Every call works with no account and no key. An optional
34
+ `KEENABLE_API_KEY` only lifts the hourly rate limit.
35
+
36
+ ```bash
37
+ pip install keenable
38
+ ```
39
+
40
+ ## Search
41
+
42
+ ```python
43
+ from keenable import Keenable
44
+
45
+ keenable = Keenable() # or Keenable("keen_...") / set KEENABLE_API_KEY
46
+
47
+ results = keenable.search("how wafer scale chips avoid the memory bottleneck")
48
+
49
+ for result in results:
50
+ print(result.title, result.url)
51
+ print(result.snippet)
52
+ ```
53
+
54
+ Results carry the page text in `snippet`. (`description` is the page's meta
55
+ description and is empty for most pages, so build prompts from `snippet`.)
56
+
57
+ Filters are optional and combine freely:
58
+
59
+ ```python
60
+ results = keenable.search(
61
+ "post-training quantization results",
62
+ site="arxiv.org",
63
+ published_after="2026-01-01",
64
+ snippet_max_length=500,
65
+ )
66
+ ```
67
+
68
+ | Argument | What it does |
69
+ |---|---|
70
+ | `site` | Restrict to one domain, e.g. `"arxiv.org"` |
71
+ | `published_after` / `published_before` | Filter by publication date (`YYYY-MM-DD`) |
72
+ | `acquired_after` / `acquired_before` | Filter by when Keenable indexed the page |
73
+ | `snippet_max_length` | Cap the page text returned per result |
74
+ | `mode` | Search mode; `"pro"` (default) does deeper retrieval |
75
+
76
+ ## Ground a model in one line
77
+
78
+ `to_context()` renders the result set as a numbered, citable block you can drop
79
+ straight into a prompt:
80
+
81
+ ```python
82
+ context = keenable.search("cerebras inference benchmarks").to_context()
83
+
84
+ prompt = f"Answer using only these sources, citing them by number.\n\n{context}\n\nQuestion: ..."
85
+ ```
86
+
87
+ It emits `[1] Title (url)` headers followed by the page text, adds results whole
88
+ until the character budget is reached (`max_chars=12000` by default), and never
89
+ truncates a source mid-sentence.
90
+
91
+ ## Read a full page
92
+
93
+ ```python
94
+ page = keenable.fetch("https://cerebras.ai/chip")
95
+ print(page.title)
96
+ print(page.content) # markdown, boilerplate stripped
97
+ ```
98
+
99
+ ## Tool calling
100
+
101
+ The SDK ships OpenAI-compatible tool definitions, so any inference API that
102
+ speaks that schema can call Keenable directly:
103
+
104
+ ```python
105
+ from keenable import Keenable, TOOLS, run_tool_call
106
+
107
+ keenable = Keenable()
108
+ response = client.chat.completions.create(model=..., messages=messages, tools=TOOLS)
109
+
110
+ for call in response.choices[0].message.tool_calls or []:
111
+ messages.append(
112
+ {
113
+ "role": "tool",
114
+ "tool_call_id": call.id,
115
+ "content": run_tool_call(
116
+ keenable, call.function.name, call.function.arguments
117
+ ),
118
+ }
119
+ )
120
+ ```
121
+
122
+ `TOOLS` exposes `keenable_search` and `keenable_fetch`; `run_tool_call` executes
123
+ whichever the model picked and returns text ready for the `tool` message.
124
+
125
+ ## Async
126
+
127
+ `AsyncKeenable` mirrors the sync client:
128
+
129
+ ```python
130
+ import asyncio
131
+ from keenable import AsyncKeenable
132
+
133
+
134
+ async def main():
135
+ async with AsyncKeenable() as keenable:
136
+ results = await keenable.search("wafer scale engine")
137
+ print(results.to_context())
138
+
139
+
140
+ asyncio.run(main())
141
+ ```
142
+
143
+ ## Errors
144
+
145
+ All errors subclass `KeenableError`:
146
+
147
+ | Exception | When |
148
+ |---|---|
149
+ | `KeenableRateLimitError` | HTTP 429. Set `KEENABLE_API_KEY` to lift the keyless cap |
150
+ | `KeenableAuthError` | HTTP 401/403, the key was rejected |
151
+ | `KeenableAPIError` | Any other non-2xx response; carries `status_code` |
152
+ | `KeenableConnectionError` | The API could not be reached |
153
+ | `KeenableInvalidRequestError` | Bad arguments; no request was sent |
154
+
155
+ ## Configuration
156
+
157
+ | Variable | Default | Purpose |
158
+ |---|---|---|
159
+ | `KEENABLE_API_KEY` | unset | Lifts the hourly rate limit. Create one at [keenable.ai/console](https://keenable.ai/console) |
160
+ | `KEENABLE_API_URL` | `https://api.keenable.ai` | Override the API base URL |
161
+
162
+ ## License
163
+
164
+ MIT
@@ -0,0 +1,9 @@
1
+ keenable/__init__.py,sha256=_c5WPBIN6wpyYfZL69gpXaw_zYnonXzO38eoI6g8ZgU,1076
2
+ keenable/client.py,sha256=R6e3yQpbKkD5AJeF2zeiKLiQPt_p6KRnRSzdJLQrHD0,13536
3
+ keenable/errors.py,sha256=7R2EqlsKbscRJsLl40MLXxTZFNkrejXlt3mg6eiiZhA,1153
4
+ keenable/models.py,sha256=Wc4J7jIV3BuBDRpNQaXO1kQpB6qIRi1bwkdhxE6yGLU,5511
5
+ keenable/tools.py,sha256=GavCXdlEGlKJoBClE0tvHZ-IHiQGnjLWhF-Y2lxJzEM,5633
6
+ keenable-0.1.0.dist-info/METADATA,sha256=PWyX0QvoDxdBmlPWLsAE13y0FXz0G9uno4XFy3M9s8Y,5079
7
+ keenable-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
8
+ keenable-0.1.0.dist-info/licenses/LICENSE,sha256=EZtgxOtuBfSwLWl3m9_IuFTRWnHGDj_0fCcfSbR4hM4,1065
9
+ keenable-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Keenable
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.