keenable-haystack 0.1.2__tar.gz → 0.2.0__tar.gz
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_haystack-0.1.2 → keenable_haystack-0.2.0}/PKG-INFO +28 -10
- {keenable_haystack-0.1.2 → keenable_haystack-0.2.0}/README.md +26 -8
- {keenable_haystack-0.1.2 → keenable_haystack-0.2.0}/haystack_integrations/components/fetchers/keenable/fetcher.py +57 -16
- {keenable_haystack-0.1.2 → keenable_haystack-0.2.0}/haystack_integrations/components/websearch/keenable/_client.py +48 -18
- {keenable_haystack-0.1.2 → keenable_haystack-0.2.0}/haystack_integrations/components/websearch/keenable/web_search.py +90 -12
- {keenable_haystack-0.1.2 → keenable_haystack-0.2.0}/pyproject.toml +1 -1
- {keenable_haystack-0.1.2 → keenable_haystack-0.2.0}/.gitignore +0 -0
- {keenable_haystack-0.1.2 → keenable_haystack-0.2.0}/LICENSE +0 -0
- {keenable_haystack-0.1.2 → keenable_haystack-0.2.0}/haystack_integrations/components/fetchers/keenable/__init__.py +0 -0
- {keenable_haystack-0.1.2 → keenable_haystack-0.2.0}/haystack_integrations/components/websearch/keenable/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: keenable-haystack
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Keenable web-search and page-fetch components for Haystack. Keyless by default.
|
|
5
5
|
Project-URL: Homepage, https://keenable.ai
|
|
6
6
|
Project-URL: Documentation, https://docs.keenable.ai
|
|
@@ -34,7 +34,8 @@ Description-Content-Type: text/markdown
|
|
|
34
34
|
so you don't need a separate `LinkContentFetcher` + `HTMLToDocument` step).
|
|
35
35
|
|
|
36
36
|
**Keyless by default**: with no API key the keyless public endpoints are used.
|
|
37
|
-
Provide a key to use the authenticated endpoints
|
|
37
|
+
Provide a key to use the authenticated endpoints: a key lifts the keyless hourly
|
|
38
|
+
cap; the per-second rate limit stays.
|
|
38
39
|
|
|
39
40
|
## Install
|
|
40
41
|
|
|
@@ -48,7 +49,7 @@ pip install keenable-haystack
|
|
|
48
49
|
from haystack_integrations.components.websearch.keenable import KeenableWebSearch
|
|
49
50
|
from haystack_integrations.components.fetchers.keenable import KeenableFetcher
|
|
50
51
|
|
|
51
|
-
# No key -> keyless public endpoints. Set KEENABLE_API_KEY to lift
|
|
52
|
+
# No key -> keyless public endpoints. Set KEENABLE_API_KEY to lift the hourly cap.
|
|
52
53
|
websearch = KeenableWebSearch(top_k=5)
|
|
53
54
|
hits = websearch.run(query="latest developments in AI agents")
|
|
54
55
|
print(hits["links"])
|
|
@@ -70,10 +71,24 @@ pipe.add_component("prompt", PromptBuilder(template="Answer using:\n{{ documents
|
|
|
70
71
|
pipe.connect("search.documents", "prompt.documents")
|
|
71
72
|
```
|
|
72
73
|
|
|
74
|
+
`top_k` (constructor, 1 to 50) is sent to the API as `max_results`; fewer results
|
|
75
|
+
come back if fewer pages match, and leaving it unset uses the API's default count.
|
|
76
|
+
|
|
73
77
|
`KeenableWebSearch.run` accepts optional per-query filters (`site`,
|
|
74
|
-
`published_after/before`, `acquired_after/before`,
|
|
75
|
-
`
|
|
76
|
-
|
|
78
|
+
`exclude_domains`, `published_after/before`, `acquired_after/before`,
|
|
79
|
+
`query_time`, `mode`, `objective`); blank values are not sent.
|
|
80
|
+
|
|
81
|
+
- `exclude_domains` is a list of host names to leave out; each also excludes its
|
|
82
|
+
subdomains (`"yahoo.com"` covers `finance.yahoo.com`).
|
|
83
|
+
- `published_after/before` and `acquired_after/before` take a date (`YYYY-MM-DD`),
|
|
84
|
+
an ISO 8601 timestamp, or a relative offset such as `7d`. Use `published_after`
|
|
85
|
+
for recent results.
|
|
86
|
+
- `query_time` searches the index as it stood at a moment: pages acquired after it
|
|
87
|
+
are left out. It sets no lower bound, so it is not a recency filter. It takes an
|
|
88
|
+
ISO 8601 timestamp, a `YYYY-MM-DD` date, a Unix epoch, or an offset such as `7d`.
|
|
89
|
+
|
|
90
|
+
`objective` (optional, at most 1,000 characters) says what the search is for (what the
|
|
91
|
+
query leaves out, what earlier searches found); pass it for multi-step or ambiguous questions. Keenable ranks results by `query` and `objective` together; retrieval reads only `query`, so put the words that matter in `query`. The objective is sent to Keenable together with the query, so keep retrieved private content out of it (or do not expose `objective` to the model).
|
|
77
92
|
|
|
78
93
|
## Configuration
|
|
79
94
|
|
|
@@ -84,9 +99,12 @@ trims it client-side.
|
|
|
84
99
|
enforced; plain `http` only for loopback). The endpoint is never a component
|
|
85
100
|
argument the model can set, so it cannot be used to redirect requests.
|
|
86
101
|
|
|
87
|
-
`KeenableFetcher`
|
|
88
|
-
client-side before sending, and
|
|
89
|
-
|
|
102
|
+
`KeenableFetcher` sends URLs in batches of up to 20 per request, rejects
|
|
103
|
+
non-`http(s)` schemes and private/internal hosts client-side before sending, and
|
|
104
|
+
(like `LinkContentFetcher`) skips failed URLs by default — set
|
|
105
|
+
`raise_on_failure=True` to surface errors instead. Each Document's `meta` carries
|
|
106
|
+
the page fields Keenable returns (`url`, `title`, `description`, `author`,
|
|
107
|
+
`image`, `favicon`, ...).
|
|
90
108
|
|
|
91
109
|
## License
|
|
92
110
|
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
so you don't need a separate `LinkContentFetcher` + `HTMLToDocument` step).
|
|
12
12
|
|
|
13
13
|
**Keyless by default**: with no API key the keyless public endpoints are used.
|
|
14
|
-
Provide a key to use the authenticated endpoints
|
|
14
|
+
Provide a key to use the authenticated endpoints: a key lifts the keyless hourly
|
|
15
|
+
cap; the per-second rate limit stays.
|
|
15
16
|
|
|
16
17
|
## Install
|
|
17
18
|
|
|
@@ -25,7 +26,7 @@ pip install keenable-haystack
|
|
|
25
26
|
from haystack_integrations.components.websearch.keenable import KeenableWebSearch
|
|
26
27
|
from haystack_integrations.components.fetchers.keenable import KeenableFetcher
|
|
27
28
|
|
|
28
|
-
# No key -> keyless public endpoints. Set KEENABLE_API_KEY to lift
|
|
29
|
+
# No key -> keyless public endpoints. Set KEENABLE_API_KEY to lift the hourly cap.
|
|
29
30
|
websearch = KeenableWebSearch(top_k=5)
|
|
30
31
|
hits = websearch.run(query="latest developments in AI agents")
|
|
31
32
|
print(hits["links"])
|
|
@@ -47,10 +48,24 @@ pipe.add_component("prompt", PromptBuilder(template="Answer using:\n{{ documents
|
|
|
47
48
|
pipe.connect("search.documents", "prompt.documents")
|
|
48
49
|
```
|
|
49
50
|
|
|
51
|
+
`top_k` (constructor, 1 to 50) is sent to the API as `max_results`; fewer results
|
|
52
|
+
come back if fewer pages match, and leaving it unset uses the API's default count.
|
|
53
|
+
|
|
50
54
|
`KeenableWebSearch.run` accepts optional per-query filters (`site`,
|
|
51
|
-
`published_after/before`, `acquired_after/before`,
|
|
52
|
-
`
|
|
53
|
-
|
|
55
|
+
`exclude_domains`, `published_after/before`, `acquired_after/before`,
|
|
56
|
+
`query_time`, `mode`, `objective`); blank values are not sent.
|
|
57
|
+
|
|
58
|
+
- `exclude_domains` is a list of host names to leave out; each also excludes its
|
|
59
|
+
subdomains (`"yahoo.com"` covers `finance.yahoo.com`).
|
|
60
|
+
- `published_after/before` and `acquired_after/before` take a date (`YYYY-MM-DD`),
|
|
61
|
+
an ISO 8601 timestamp, or a relative offset such as `7d`. Use `published_after`
|
|
62
|
+
for recent results.
|
|
63
|
+
- `query_time` searches the index as it stood at a moment: pages acquired after it
|
|
64
|
+
are left out. It sets no lower bound, so it is not a recency filter. It takes an
|
|
65
|
+
ISO 8601 timestamp, a `YYYY-MM-DD` date, a Unix epoch, or an offset such as `7d`.
|
|
66
|
+
|
|
67
|
+
`objective` (optional, at most 1,000 characters) says what the search is for (what the
|
|
68
|
+
query leaves out, what earlier searches found); pass it for multi-step or ambiguous questions. Keenable ranks results by `query` and `objective` together; retrieval reads only `query`, so put the words that matter in `query`. The objective is sent to Keenable together with the query, so keep retrieved private content out of it (or do not expose `objective` to the model).
|
|
54
69
|
|
|
55
70
|
## Configuration
|
|
56
71
|
|
|
@@ -61,9 +76,12 @@ trims it client-side.
|
|
|
61
76
|
enforced; plain `http` only for loopback). The endpoint is never a component
|
|
62
77
|
argument the model can set, so it cannot be used to redirect requests.
|
|
63
78
|
|
|
64
|
-
`KeenableFetcher`
|
|
65
|
-
client-side before sending, and
|
|
66
|
-
|
|
79
|
+
`KeenableFetcher` sends URLs in batches of up to 20 per request, rejects
|
|
80
|
+
non-`http(s)` schemes and private/internal hosts client-side before sending, and
|
|
81
|
+
(like `LinkContentFetcher`) skips failed URLs by default — set
|
|
82
|
+
`raise_on_failure=True` to surface errors instead. Each Document's `meta` carries
|
|
83
|
+
the page fields Keenable returns (`url`, `title`, `description`, `author`,
|
|
84
|
+
`image`, `favicon`, ...).
|
|
67
85
|
|
|
68
86
|
## License
|
|
69
87
|
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import logging
|
|
6
|
-
from typing import Any, Optional
|
|
6
|
+
from typing import Any, Optional, Union
|
|
7
7
|
|
|
8
8
|
from haystack import Document, component, default_from_dict, default_to_dict
|
|
9
9
|
from haystack.utils import Secret, deserialize_secrets_inplace
|
|
@@ -11,8 +11,10 @@ from haystack.utils import Secret, deserialize_secrets_inplace
|
|
|
11
11
|
# The transport lives in the websearch leaf package so it is defined once; the
|
|
12
12
|
# fetcher reuses it (keyed/keyless selection, attribution headers, SSRF guard).
|
|
13
13
|
from haystack_integrations.components.websearch.keenable._client import (
|
|
14
|
+
FETCH_BATCH_SIZE,
|
|
14
15
|
KeenableError,
|
|
15
|
-
|
|
16
|
+
fetch_page_error,
|
|
17
|
+
keenable_fetch,
|
|
16
18
|
normalize_key,
|
|
17
19
|
reject_private_fetch_target,
|
|
18
20
|
)
|
|
@@ -26,15 +28,18 @@ class KeenableFetcher:
|
|
|
26
28
|
|
|
27
29
|
Given a list of URLs, returns one ``Document`` per successfully fetched page
|
|
28
30
|
(``content`` is the page's main content as markdown; ``meta`` carries
|
|
29
|
-
``url``, ``title`` and
|
|
31
|
+
``url``, ``title`` and the other fields Keenable returns for the page, such
|
|
32
|
+
as ``description``, ``author``, ``image`` and ``favicon``). Pairs with
|
|
30
33
|
:class:`KeenableWebSearch` — discover URLs with search, then read full pages
|
|
31
34
|
here. Unlike Haystack's ``LinkContentFetcher`` + ``HTMLToDocument`` two-step,
|
|
32
35
|
Keenable returns clean extracted markdown, so this is a single component that
|
|
33
36
|
returns Documents directly.
|
|
34
37
|
|
|
35
|
-
Keyless by default (
|
|
36
|
-
``KEENABLE_API_KEY``) switches to
|
|
37
|
-
|
|
38
|
+
Keyless by default (``POST /v1/fetch/public``); an ``api_key`` (or
|
|
39
|
+
``KEENABLE_API_KEY``) switches to ``POST /v1/fetch``, which lifts the keyless
|
|
40
|
+
hourly cap (the per-second limit stays). URLs are sent in batches of up to 20
|
|
41
|
+
per request. Non-http(s) and private/internal URLs are rejected client-side
|
|
42
|
+
before sending.
|
|
38
43
|
|
|
39
44
|
### Usage
|
|
40
45
|
|
|
@@ -82,14 +87,30 @@ class KeenableFetcher:
|
|
|
82
87
|
deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"])
|
|
83
88
|
return default_from_dict(cls, data)
|
|
84
89
|
|
|
85
|
-
|
|
90
|
+
@staticmethod
|
|
91
|
+
def _check_url(url: str) -> None:
|
|
86
92
|
if not url.lower().startswith(("http://", "https://")):
|
|
87
93
|
msg = f"Refusing to fetch a non-http(s) URL: {url!r}"
|
|
88
94
|
raise KeenableError(msg)
|
|
89
95
|
reject_private_fetch_target(url)
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
96
|
+
|
|
97
|
+
def _fetch_batch(
|
|
98
|
+
self, urls: list[str], api_key: Optional[str]
|
|
99
|
+
) -> list[Union[Document, Exception]]:
|
|
100
|
+
"""Fetch distinct ``urls`` in one request; one Document or error per URL."""
|
|
101
|
+
outcomes: list[Union[Document, Exception]] = []
|
|
102
|
+
for page in keenable_fetch(urls, api_key, self.timeout):
|
|
103
|
+
error = fetch_page_error(page, api_key)
|
|
104
|
+
if error is not None:
|
|
105
|
+
outcomes.append(error)
|
|
106
|
+
else:
|
|
107
|
+
outcomes.append(Document(content=page.get("content") or "", meta=dict(page)))
|
|
108
|
+
return outcomes
|
|
109
|
+
|
|
110
|
+
def _fail(self, url: str, error: Exception) -> None:
|
|
111
|
+
if self.raise_on_failure:
|
|
112
|
+
raise error
|
|
113
|
+
logger.warning("Keenable could not fetch %r; skipping (%s).", url, error)
|
|
93
114
|
|
|
94
115
|
@component.output_types(documents=list[Document])
|
|
95
116
|
def run(self, urls: list[str]) -> dict[str, Any]:
|
|
@@ -97,15 +118,35 @@ class KeenableFetcher:
|
|
|
97
118
|
|
|
98
119
|
:param urls: The URLs to fetch.
|
|
99
120
|
:returns: A dict with ``documents`` (``list[Document]``), one per page
|
|
100
|
-
fetched successfully
|
|
121
|
+
fetched successfully, in the order of ``urls``.
|
|
101
122
|
"""
|
|
102
123
|
api_key = normalize_key(self.api_key.resolve_value())
|
|
103
|
-
|
|
124
|
+
|
|
125
|
+
valid: list[str] = []
|
|
104
126
|
for url in urls:
|
|
105
127
|
try:
|
|
106
|
-
|
|
128
|
+
self._check_url(url)
|
|
107
129
|
except Exception as e: # noqa: BLE001 - contract: one bad URL must not fail the batch
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
130
|
+
self._fail(url, e)
|
|
131
|
+
else:
|
|
132
|
+
valid.append(url)
|
|
133
|
+
|
|
134
|
+
# The API wants each URL once per request; a repeated URL is fetched once
|
|
135
|
+
# and still yields one Document per occurrence.
|
|
136
|
+
distinct = list(dict.fromkeys(valid))
|
|
137
|
+
outcomes: dict[str, Union[Document, Exception]] = {}
|
|
138
|
+
for i in range(0, len(distinct), FETCH_BATCH_SIZE):
|
|
139
|
+
batch = distinct[i : i + FETCH_BATCH_SIZE]
|
|
140
|
+
try:
|
|
141
|
+
outcomes.update(zip(batch, self._fetch_batch(batch, api_key)))
|
|
142
|
+
except Exception as e: # noqa: BLE001 - a failed request skips its URLs, not the run
|
|
143
|
+
outcomes.update((url, e) for url in batch)
|
|
144
|
+
|
|
145
|
+
documents: list[Document] = []
|
|
146
|
+
for url in valid:
|
|
147
|
+
outcome = outcomes[url]
|
|
148
|
+
if isinstance(outcome, Document):
|
|
149
|
+
documents.append(outcome)
|
|
150
|
+
else:
|
|
151
|
+
self._fail(url, outcome)
|
|
111
152
|
return {"documents": documents}
|
|
@@ -159,6 +159,17 @@ def _redact(text: str, api_key: str | None) -> str:
|
|
|
159
159
|
return text.replace(api_key, "***") if api_key else text
|
|
160
160
|
|
|
161
161
|
|
|
162
|
+
def _api_error(status: int, detail: str, api_key: str | None) -> KeenableError:
|
|
163
|
+
"""Build the readable :class:`KeenableError` for an API error status."""
|
|
164
|
+
detail = _redact(detail[:200], api_key)
|
|
165
|
+
label = {
|
|
166
|
+
401: "Keenable authentication failed (401)",
|
|
167
|
+
402: "Keenable: insufficient credits (402)",
|
|
168
|
+
429: "Keenable rate limit exceeded (429)",
|
|
169
|
+
}.get(status, f"Keenable API error ({status})")
|
|
170
|
+
return KeenableError(f"{label}: {detail}" if detail else label)
|
|
171
|
+
|
|
172
|
+
|
|
162
173
|
def _raise_for_status(response: requests.Response, api_key: str | None) -> None:
|
|
163
174
|
"""Map a non-2xx Keenable response to a readable :class:`KeenableError`."""
|
|
164
175
|
if response.ok:
|
|
@@ -170,13 +181,7 @@ def _raise_for_status(response: requests.Response, api_key: str | None) -> None:
|
|
|
170
181
|
detail = str(body.get("message") or body.get("error") or body.get("detail") or "")
|
|
171
182
|
except ValueError:
|
|
172
183
|
detail = (response.text or "").strip()
|
|
173
|
-
|
|
174
|
-
label = {
|
|
175
|
-
401: "Keenable authentication failed (401)",
|
|
176
|
-
402: "Keenable: insufficient credits (402)",
|
|
177
|
-
429: "Keenable rate limit exceeded (429)",
|
|
178
|
-
}.get(response.status_code, f"Keenable API error ({response.status_code})")
|
|
179
|
-
raise KeenableError(f"{label}: {detail}" if detail else label)
|
|
184
|
+
raise _api_error(response.status_code, detail, api_key)
|
|
180
185
|
|
|
181
186
|
|
|
182
187
|
def _decode(response: requests.Response, api_key: str | None) -> dict[str, Any]:
|
|
@@ -219,14 +224,39 @@ def keenable_post(
|
|
|
219
224
|
return _decode(response, api_key)
|
|
220
225
|
|
|
221
226
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
227
|
+
# POST /v1/fetch takes up to this many URLs per call, and a call counts as one
|
|
228
|
+
# request toward the rate limit however many URLs it carries.
|
|
229
|
+
FETCH_BATCH_SIZE = 20
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def keenable_fetch(urls: list[str], api_key: str | None, timeout: float) -> list[dict[str, Any]]:
|
|
233
|
+
"""Read pages with ``POST /v1/fetch``, or ``POST /v1/fetch/public`` without a key.
|
|
234
|
+
|
|
235
|
+
Returns one result dict per URL, in request order. A page that could not be
|
|
236
|
+
read comes back as a dict with an ``error`` field; pass it to
|
|
237
|
+
:func:`fetch_page_error`. ``urls`` must be distinct and at most
|
|
238
|
+
:data:`FETCH_BATCH_SIZE` long (the API's limits).
|
|
239
|
+
"""
|
|
240
|
+
data = keenable_post("/v1/fetch/public", "/v1/fetch", {"urls": urls}, api_key, timeout)
|
|
241
|
+
results = data.get("results")
|
|
242
|
+
if (
|
|
243
|
+
not isinstance(results, list)
|
|
244
|
+
or len(results) != len(urls)
|
|
245
|
+
or not all(isinstance(page, dict) for page in results)
|
|
246
|
+
):
|
|
247
|
+
msg = f"Unexpected response from the Keenable fetch API: {_redact(repr(data)[:200], api_key)}"
|
|
248
|
+
raise KeenableError(msg)
|
|
249
|
+
return results
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def fetch_page_error(page: dict[str, Any], api_key: str | None) -> KeenableError | None:
|
|
253
|
+
"""The :class:`KeenableError` for a page the fetch API could not read, else ``None``."""
|
|
254
|
+
error = page.get("error")
|
|
255
|
+
if not error:
|
|
256
|
+
return None
|
|
257
|
+
if isinstance(error, dict):
|
|
258
|
+
status = error.get("status")
|
|
259
|
+
status = status if isinstance(status, int) else 500
|
|
260
|
+
detail = str(error.get("message") or error.get("error") or "")
|
|
261
|
+
return _api_error(status, detail, api_key)
|
|
262
|
+
return _api_error(500, str(error), api_key)
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from typing import Any, Optional
|
|
5
|
+
from typing import Any, Optional, Union
|
|
6
6
|
|
|
7
7
|
from haystack import Document, component, default_from_dict, default_to_dict
|
|
8
8
|
from haystack.utils import Secret, deserialize_secrets_inplace
|
|
@@ -14,6 +14,10 @@ from haystack_integrations.components.websearch.keenable._client import (
|
|
|
14
14
|
normalize_key,
|
|
15
15
|
)
|
|
16
16
|
|
|
17
|
+
MAX_OBJECTIVE_CHARS = 1000
|
|
18
|
+
MAX_RESULTS_LIMIT = 50
|
|
19
|
+
MAX_EXCLUDE_DOMAINS = 2000
|
|
20
|
+
|
|
17
21
|
|
|
18
22
|
@component
|
|
19
23
|
class KeenableWebSearch:
|
|
@@ -28,7 +32,8 @@ class KeenableWebSearch:
|
|
|
28
32
|
Keyless by default: with no API key the keyless public endpoint
|
|
29
33
|
(``/v1/search/public``) is used. Provide an API key (the ``api_key`` argument
|
|
30
34
|
or the ``KEENABLE_API_KEY`` environment variable) to use the authenticated
|
|
31
|
-
endpoint (``/v1/search``)
|
|
35
|
+
endpoint (``/v1/search``); a key lifts the keyless hourly cap, while the
|
|
36
|
+
per-second limit stays.
|
|
32
37
|
|
|
33
38
|
The API endpoint is read from ``KEENABLE_API_URL`` (HTTPS enforced), never a
|
|
34
39
|
``run`` argument, so the search cannot be redirected to an arbitrary host.
|
|
@@ -38,7 +43,7 @@ class KeenableWebSearch:
|
|
|
38
43
|
```python
|
|
39
44
|
from haystack_integrations.components.websearch.keenable import KeenableWebSearch
|
|
40
45
|
|
|
41
|
-
# No key -> keyless public endpoint. Set KEENABLE_API_KEY to lift
|
|
46
|
+
# No key -> keyless public endpoint. Set KEENABLE_API_KEY to lift the hourly cap.
|
|
42
47
|
websearch = KeenableWebSearch(top_k=5)
|
|
43
48
|
result = websearch.run(query="latest developments in AI agents")
|
|
44
49
|
print(result["documents"])
|
|
@@ -58,8 +63,9 @@ class KeenableWebSearch:
|
|
|
58
63
|
"""
|
|
59
64
|
:param api_key: Keenable API key. Falls back to ``KEENABLE_API_KEY``; when
|
|
60
65
|
absent (or blank) the keyless public endpoint is used.
|
|
61
|
-
:param top_k:
|
|
62
|
-
|
|
66
|
+
:param top_k: Maximum number of results, 1 to 50, sent to the API as
|
|
67
|
+
``max_results``. Fewer come back if fewer pages match. ``None`` uses
|
|
68
|
+
the API's default count.
|
|
63
69
|
:param mode: Default search mode, ``"pro"`` (default). Overridable per run.
|
|
64
70
|
:param site: Default single-domain restriction, e.g. ``"github.com"``.
|
|
65
71
|
Overridable per run.
|
|
@@ -68,8 +74,12 @@ class KeenableWebSearch:
|
|
|
68
74
|
if timeout <= 0:
|
|
69
75
|
msg = f"timeout must be a positive number of seconds, got {timeout!r}"
|
|
70
76
|
raise ValueError(msg)
|
|
71
|
-
if top_k is not None and
|
|
72
|
-
|
|
77
|
+
if top_k is not None and (
|
|
78
|
+
isinstance(top_k, bool)
|
|
79
|
+
or not isinstance(top_k, int)
|
|
80
|
+
or not 1 <= top_k <= MAX_RESULTS_LIMIT
|
|
81
|
+
):
|
|
82
|
+
msg = f"top_k must be None or an integer from 1 to {MAX_RESULTS_LIMIT}, got {top_k!r}"
|
|
73
83
|
raise ValueError(msg)
|
|
74
84
|
self.api_key = api_key
|
|
75
85
|
self.top_k = top_k
|
|
@@ -102,16 +112,39 @@ class KeenableWebSearch:
|
|
|
102
112
|
acquired_after: Optional[str] = None,
|
|
103
113
|
acquired_before: Optional[str] = None,
|
|
104
114
|
mode: Optional[str] = None,
|
|
115
|
+
objective: Optional[str] = None,
|
|
116
|
+
exclude_domains: Optional[list[str]] = None,
|
|
117
|
+
query_time: Optional[str] = None,
|
|
105
118
|
) -> dict[str, Any]:
|
|
106
119
|
"""Run a Keenable web search.
|
|
107
120
|
|
|
108
121
|
:param query: The search query.
|
|
109
122
|
:param site: Restrict results to a single domain (overrides the default).
|
|
110
|
-
:param published_after: Only pages published
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
:param
|
|
123
|
+
:param published_after: Only pages published after this moment: a date
|
|
124
|
+
(YYYY-MM-DD), an ISO 8601 timestamp, or a relative offset such as
|
|
125
|
+
``7d`` or ``24h``. This is the filter for recent results.
|
|
126
|
+
:param published_before: Only pages published before this moment (same
|
|
127
|
+
formats as ``published_after``).
|
|
128
|
+
:param acquired_after: Only pages indexed after this moment (same formats
|
|
129
|
+
as ``published_after``).
|
|
130
|
+
:param acquired_before: Only pages indexed before this moment.
|
|
114
131
|
:param mode: Override the default search mode for this query.
|
|
132
|
+
:param objective: Optional. Use for multi-step or ambiguous searches; omit for simple
|
|
133
|
+
lookups. In one to three plain sentences, say what the search is
|
|
134
|
+
for, what the query leaves out (who, where, when, which sources
|
|
135
|
+
count) and what earlier searches found. Don't restate the question
|
|
136
|
+
or include personal or confidential details. At most 1,000
|
|
137
|
+
characters.
|
|
138
|
+
:param exclude_domains: Never return results from these hosts. Each entry
|
|
139
|
+
is a host name and also covers its subdomains (``"yahoo.com"`` excludes
|
|
140
|
+
``finance.yahoo.com``). At most 2,000 entries; blank entries are dropped
|
|
141
|
+
and an empty list is not sent. Fewer results may come back.
|
|
142
|
+
:param query_time: Leave empty for a normal search. Searches the index as it
|
|
143
|
+
stood at this moment: pages acquired after it are left out. It sets no
|
|
144
|
+
lower bound, so it is not a recency filter; for recent results use
|
|
145
|
+
``published_after``. Accepts an ISO 8601 timestamp, a YYYY-MM-DD date,
|
|
146
|
+
a Unix epoch, or an offset back from now such as ``7d`` (units ``min``,
|
|
147
|
+
``h``, ``d``, ``w``, ``mo``, ``y``).
|
|
115
148
|
:returns: A dict with ``documents`` (``list[Document]``) and ``links``
|
|
116
149
|
(``list[str]``).
|
|
117
150
|
"""
|
|
@@ -119,15 +152,34 @@ class KeenableWebSearch:
|
|
|
119
152
|
api_key = normalize_key(self.api_key.resolve_value())
|
|
120
153
|
|
|
121
154
|
payload: dict[str, Any] = {"query": query, "mode": effective_mode}
|
|
155
|
+
if self.top_k is not None:
|
|
156
|
+
payload["max_results"] = self.top_k
|
|
122
157
|
for field, value in (
|
|
123
158
|
("site", site or self.site),
|
|
124
159
|
("published_after", published_after),
|
|
125
160
|
("published_before", published_before),
|
|
126
161
|
("acquired_after", acquired_after),
|
|
127
162
|
("acquired_before", acquired_before),
|
|
163
|
+
("query_time", query_time),
|
|
128
164
|
):
|
|
165
|
+
# Blank values are not sent.
|
|
166
|
+
value = value.strip() if isinstance(value, str) else value
|
|
129
167
|
if value:
|
|
130
168
|
payload[field] = value
|
|
169
|
+
domains = _clean_domains(exclude_domains)
|
|
170
|
+
if domains:
|
|
171
|
+
payload["exclude_domains"] = domains
|
|
172
|
+
# Ranking uses query and objective together; retrieval reads only the
|
|
173
|
+
# query. Blank values are not sent.
|
|
174
|
+
if objective and objective.strip():
|
|
175
|
+
objective = objective.strip()
|
|
176
|
+
if len(objective) > MAX_OBJECTIVE_CHARS:
|
|
177
|
+
msg = (
|
|
178
|
+
f"objective is {len(objective)} characters; the limit is "
|
|
179
|
+
f"{MAX_OBJECTIVE_CHARS}. Shorten it to two or three sentences."
|
|
180
|
+
)
|
|
181
|
+
raise KeenableError(msg)
|
|
182
|
+
payload["objective"] = objective
|
|
131
183
|
|
|
132
184
|
data = keenable_post("/v1/search/public", "/v1/search", payload, api_key, self.timeout)
|
|
133
185
|
results = data.get("results")
|
|
@@ -137,6 +189,8 @@ class KeenableWebSearch:
|
|
|
137
189
|
msg = f"Unexpected response from the Keenable search API: {_redact(repr(data)[:200], api_key)}"
|
|
138
190
|
raise KeenableError(msg)
|
|
139
191
|
|
|
192
|
+
# The API honors max_results; the slice only guards against a server
|
|
193
|
+
# that returns more than asked.
|
|
140
194
|
if self.top_k is not None:
|
|
141
195
|
results = results[: self.top_k]
|
|
142
196
|
|
|
@@ -145,10 +199,34 @@ class KeenableWebSearch:
|
|
|
145
199
|
for result in results:
|
|
146
200
|
if not isinstance(result, dict):
|
|
147
201
|
continue
|
|
148
|
-
|
|
202
|
+
# `snippet` carries the page text; `description` is usually empty, so
|
|
203
|
+
# reading it first would leave content as the bare title.
|
|
204
|
+
content = (
|
|
205
|
+
result.get("snippet")
|
|
206
|
+
or result.get("description")
|
|
207
|
+
or result.get("title")
|
|
208
|
+
or ""
|
|
209
|
+
)
|
|
149
210
|
documents.append(Document(content=content, meta=dict(result)))
|
|
150
211
|
link = result.get("url")
|
|
151
212
|
if link:
|
|
152
213
|
links.append(link)
|
|
153
214
|
|
|
154
215
|
return {"documents": documents, "links": links}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _clean_domains(domains: Union[list[str], str, None]) -> list[str]:
|
|
219
|
+
"""Strip ``exclude_domains`` entries and drop blanks; enforce the API's size limit.
|
|
220
|
+
|
|
221
|
+
A bare string (as a model calling the component as a tool may send) counts as
|
|
222
|
+
one host, not a sequence of characters.
|
|
223
|
+
"""
|
|
224
|
+
if not domains:
|
|
225
|
+
return []
|
|
226
|
+
if isinstance(domains, str):
|
|
227
|
+
domains = [domains]
|
|
228
|
+
cleaned = [d.strip() for d in domains if isinstance(d, str) and d.strip()]
|
|
229
|
+
if len(cleaned) > MAX_EXCLUDE_DOMAINS:
|
|
230
|
+
msg = f"exclude_domains has {len(cleaned)} entries; the limit is {MAX_EXCLUDE_DOMAINS}."
|
|
231
|
+
raise KeenableError(msg)
|
|
232
|
+
return cleaned
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "keenable-haystack"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "Keenable web-search and page-fetch components for Haystack. Keyless by default."
|
|
9
9
|
authors = [{ name = "Keenable", email = "hello@keenable.ai" }]
|
|
10
10
|
maintainers = [{ name = "keenableai" }]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|