askcrawl 0.2.1__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.
- askcrawl/__init__.py +19 -0
- askcrawl/client.py +318 -0
- askcrawl/py.typed +0 -0
- askcrawl-0.2.1.dist-info/METADATA +136 -0
- askcrawl-0.2.1.dist-info/RECORD +8 -0
- askcrawl-0.2.1.dist-info/WHEEL +5 -0
- askcrawl-0.2.1.dist-info/licenses/LICENSE +21 -0
- askcrawl-0.2.1.dist-info/top_level.txt +1 -0
askcrawl/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Python client for AskCrawl, the AI answer data API.
|
|
2
|
+
|
|
3
|
+
from askcrawl import AskCrawl
|
|
4
|
+
|
|
5
|
+
client = AskCrawl() # reads ASKCRAWL_API_KEY
|
|
6
|
+
quote = client.quote(["best crm for small business"], ["chatgpt.web", "perplexity.web"], samples=3)
|
|
7
|
+
job = client.ask(["best crm for small business"], ["chatgpt.web", "perplexity.web"], samples=3,
|
|
8
|
+
max_price=quote["max_charge"])
|
|
9
|
+
job = client.wait(job["id"])
|
|
10
|
+
for answer in client.answers(job["id"]):
|
|
11
|
+
print(answer["engine"], answer["status"], answer["text"])
|
|
12
|
+
|
|
13
|
+
Docs: https://www.askcrawl.com/docs/
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from .client import AskCrawl, AskCrawlError, WebhookError, verify_webhook
|
|
17
|
+
|
|
18
|
+
__all__ = ["AskCrawl", "AskCrawlError", "WebhookError", "verify_webhook"]
|
|
19
|
+
__version__ = "0.2.1"
|
askcrawl/client.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""The AskCrawl client. Standard library only."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import hashlib
|
|
7
|
+
import hmac
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import time
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.parse
|
|
14
|
+
import urllib.request
|
|
15
|
+
import uuid
|
|
16
|
+
from typing import Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Union
|
|
17
|
+
|
|
18
|
+
DEFAULT_BASE_URL = "https://api.askcrawl.com"
|
|
19
|
+
Money = Union[str, int, float]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AskCrawlError(Exception):
|
|
23
|
+
"""An error returned by the API.
|
|
24
|
+
|
|
25
|
+
``charged`` is False for every error except ``settlement_unknown``, where billing is not known yet:
|
|
26
|
+
send the same request again with the same idempotency key, never a new one.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, status: int, payload: Dict[str, Any]):
|
|
30
|
+
self.status = status
|
|
31
|
+
self.code: str = payload.get("code", "unknown")
|
|
32
|
+
self.message: str = payload.get("message", "")
|
|
33
|
+
self.charged = payload.get("charged")
|
|
34
|
+
self.retry = payload.get("retry")
|
|
35
|
+
self.retry_after_seconds = payload.get("retry_after_seconds")
|
|
36
|
+
self.request_id = payload.get("request_id")
|
|
37
|
+
self.docs_url = payload.get("docs_url")
|
|
38
|
+
self.payload = payload
|
|
39
|
+
super().__init__(f"{self.code}: {self.message}" + (f" ({self.docs_url})" if self.docs_url else ""))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class AskCrawl:
|
|
43
|
+
"""A client for https://api.askcrawl.com.
|
|
44
|
+
|
|
45
|
+
Only ``ask`` and data endpoint ``call`` s spend money. Both send a price ceiling and an idempotency key,
|
|
46
|
+
so a retry never runs or charges twice.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
api_key: Optional[str] = None,
|
|
52
|
+
*,
|
|
53
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
54
|
+
timeout: float = 60.0,
|
|
55
|
+
max_retries: int = 3,
|
|
56
|
+
source: Optional[str] = None,
|
|
57
|
+
):
|
|
58
|
+
self.api_key = api_key or os.environ.get("ASKCRAWL_API_KEY")
|
|
59
|
+
if not self.api_key:
|
|
60
|
+
raise ValueError("Pass api_key or set ASKCRAWL_API_KEY. Create a key at https://www.askcrawl.com/console/keys/")
|
|
61
|
+
self.base_url = base_url.rstrip("/")
|
|
62
|
+
self.timeout = timeout
|
|
63
|
+
self.max_retries = max_retries
|
|
64
|
+
self.source = source
|
|
65
|
+
|
|
66
|
+
# ---- low level -------------------------------------------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
def request(
|
|
69
|
+
self,
|
|
70
|
+
method: str,
|
|
71
|
+
path: str,
|
|
72
|
+
*,
|
|
73
|
+
query: Optional[Dict[str, Any]] = None,
|
|
74
|
+
body: Optional[Dict[str, Any]] = None,
|
|
75
|
+
headers: Optional[Dict[str, str]] = None,
|
|
76
|
+
safe: bool = False,
|
|
77
|
+
timeout: Optional[float] = None,
|
|
78
|
+
) -> Dict[str, Any]:
|
|
79
|
+
"""Send one request and return the whole response (``code``, ``request_id``, ``data`` and ``page``).
|
|
80
|
+
|
|
81
|
+
Follows the error's ``retry`` hint, but only for requests that are safe to repeat: a GET, a free request
|
|
82
|
+
(``safe=True``), or one with an Idempotency-Key. ``same_key`` errors are retried only with an Idempotency-Key.
|
|
83
|
+
"""
|
|
84
|
+
url = self.base_url + path
|
|
85
|
+
if query:
|
|
86
|
+
url += "?" + urllib.parse.urlencode({k: _text(v) for k, v in query.items() if v is not None})
|
|
87
|
+
sent = {"Authorization": f"Bearer {self.api_key}", "Accept": "application/json", "User-Agent": "askcrawl-python/0.2.1"}
|
|
88
|
+
if self.source:
|
|
89
|
+
sent["X-Source"] = self.source
|
|
90
|
+
if body is not None:
|
|
91
|
+
sent["Content-Type"] = "application/json"
|
|
92
|
+
sent.update(headers or {})
|
|
93
|
+
data = None if body is None else json.dumps(body).encode()
|
|
94
|
+
keyed = "Idempotency-Key" in sent
|
|
95
|
+
repeatable = method == "GET" or safe or keyed
|
|
96
|
+
|
|
97
|
+
attempt = 0
|
|
98
|
+
while True:
|
|
99
|
+
attempt += 1
|
|
100
|
+
try:
|
|
101
|
+
with urllib.request.urlopen(urllib.request.Request(url, data=data, method=method, headers=sent), timeout=timeout or self.timeout) as response:
|
|
102
|
+
return json.load(response)
|
|
103
|
+
except urllib.error.HTTPError as error:
|
|
104
|
+
try:
|
|
105
|
+
payload = json.load(error)
|
|
106
|
+
except ValueError:
|
|
107
|
+
payload = {"code": "http_error", "message": f"HTTP {error.code}", "retry": "yes" if error.code >= 500 else "no"}
|
|
108
|
+
finally:
|
|
109
|
+
error.close()
|
|
110
|
+
failure = AskCrawlError(error.code, payload)
|
|
111
|
+
can_retry = (failure.retry == "yes" and repeatable) or (failure.retry == "same_key" and keyed)
|
|
112
|
+
if not can_retry or attempt > self.max_retries:
|
|
113
|
+
raise failure from None
|
|
114
|
+
time.sleep(failure.retry_after_seconds or 2 ** attempt)
|
|
115
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError):
|
|
116
|
+
if not repeatable or attempt > self.max_retries:
|
|
117
|
+
raise
|
|
118
|
+
time.sleep(2 ** attempt)
|
|
119
|
+
|
|
120
|
+
def _item(self, method: str, path: str, **kwargs: Any) -> Dict[str, Any]:
|
|
121
|
+
return self.request(method, path, **kwargs)["data"]["item"]
|
|
122
|
+
|
|
123
|
+
# ---- AI answers ------------------------------------------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
def quote(self, prompts: List[str], engines: List[str], samples: int = 1, **options: Any) -> Dict[str, Any]:
|
|
126
|
+
"""The maximum cost of a job. Free: creates nothing and holds nothing."""
|
|
127
|
+
return self._item("POST", "/v1/answers/quote", body={"prompts": prompts, "engines": engines, "samples": samples, **options}, safe=True)
|
|
128
|
+
|
|
129
|
+
def ask(
|
|
130
|
+
self,
|
|
131
|
+
prompts: List[str],
|
|
132
|
+
engines: List[str],
|
|
133
|
+
samples: int = 1,
|
|
134
|
+
*,
|
|
135
|
+
max_price: Money,
|
|
136
|
+
idempotency_key: Optional[str] = None,
|
|
137
|
+
webhook_url: Optional[str] = None,
|
|
138
|
+
wait: Optional[int] = None,
|
|
139
|
+
**options: Any,
|
|
140
|
+
) -> Dict[str, Any]:
|
|
141
|
+
"""Submit a collection job (charged). Returns the job at once, before any answer is collected.
|
|
142
|
+
|
|
143
|
+
``max_price`` is required: if the job could cost more, nothing is submitted or charged.
|
|
144
|
+
Pass your own ``idempotency_key`` to make retries across restarts safe. A submitted job cannot be cancelled.
|
|
145
|
+
``webhook_url``: a public https URL that gets a signed ``job.completed`` event when the job ends (check it with
|
|
146
|
+
``verify_webhook``). ``wait``: up to 50 seconds to hold the reply until the job ends; if it ends in time the
|
|
147
|
+
returned job is finished, otherwise check it later as usual.
|
|
148
|
+
Other options (``country``, ``region``, ``tier``, ``prompt_set``, ``tags`` …) go straight into the request body.
|
|
149
|
+
"""
|
|
150
|
+
headers = {"Idempotency-Key": idempotency_key or f"askcrawl-python-{uuid.uuid4()}", "X-Max-Price": _text(max_price)}
|
|
151
|
+
body: Dict[str, Any] = {"prompts": prompts, "engines": engines, "samples": samples, **options}
|
|
152
|
+
if webhook_url is not None:
|
|
153
|
+
body["webhook_url"] = webhook_url
|
|
154
|
+
timeout = None
|
|
155
|
+
if wait is not None:
|
|
156
|
+
body["wait"] = wait
|
|
157
|
+
timeout = max(self.timeout, wait + 15)
|
|
158
|
+
return self._item("POST", "/v1/answers", body=body, headers=headers, timeout=timeout)
|
|
159
|
+
|
|
160
|
+
def job(self, job_id: str) -> Dict[str, Any]:
|
|
161
|
+
"""A job's status, counts, held and charged amounts."""
|
|
162
|
+
return self._item("GET", f"/v1/jobs/{_seg(job_id)}")
|
|
163
|
+
|
|
164
|
+
def wait(
|
|
165
|
+
self,
|
|
166
|
+
job_id: str,
|
|
167
|
+
*,
|
|
168
|
+
timeout: Optional[float] = None,
|
|
169
|
+
on_progress: Optional[Callable[[Dict[str, Any]], None]] = None,
|
|
170
|
+
) -> Dict[str, Any]:
|
|
171
|
+
"""Check the job until no answer is pending, waiting ``retry_after_seconds`` between checks."""
|
|
172
|
+
started = time.monotonic()
|
|
173
|
+
while True:
|
|
174
|
+
job = self.job(job_id)
|
|
175
|
+
if on_progress:
|
|
176
|
+
on_progress(job)
|
|
177
|
+
if job["counts"]["pending"] == 0:
|
|
178
|
+
return job
|
|
179
|
+
pause = job.get("retry_after_seconds") or 15
|
|
180
|
+
if timeout is not None and time.monotonic() - started + pause > timeout:
|
|
181
|
+
raise TimeoutError(f"job {job_id} still has {job['counts']['pending']} pending answers")
|
|
182
|
+
time.sleep(pause)
|
|
183
|
+
|
|
184
|
+
def answers(self, job_id: str) -> Iterator[Dict[str, Any]]:
|
|
185
|
+
"""Every answer of a job, following the pages. Finished answers can be read while the job is running."""
|
|
186
|
+
return self._pages("/v1/answers", {"job_id": job_id})
|
|
187
|
+
|
|
188
|
+
def answer(self, answer_id: str) -> Dict[str, Any]:
|
|
189
|
+
"""One full answer with its sources and capture conditions."""
|
|
190
|
+
return self._item("GET", f"/v1/answers/{_seg(answer_id)}")
|
|
191
|
+
|
|
192
|
+
def evidence(self, answer_id: str) -> Dict[str, Any]:
|
|
193
|
+
"""Download links for an answer's evidence. They expire after a short time; ask again for fresh ones."""
|
|
194
|
+
return self._item("GET", f"/v1/answers/{_seg(answer_id)}/evidence")
|
|
195
|
+
|
|
196
|
+
# ---- reports (free) ------------------------------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
def visibility(
|
|
199
|
+
self,
|
|
200
|
+
job_ids: Iterable[str],
|
|
201
|
+
*,
|
|
202
|
+
brand: Optional[str] = None,
|
|
203
|
+
aliases: Optional[List[str]] = None,
|
|
204
|
+
exclude: Optional[List[str]] = None,
|
|
205
|
+
domains: Optional[List[str]] = None,
|
|
206
|
+
**options: Any,
|
|
207
|
+
) -> Dict[str, Any]:
|
|
208
|
+
"""Brand mention and domain citation rates with 95% intervals, one row per platform and capture conditions."""
|
|
209
|
+
body: Dict[str, Any] = {"job_ids": list(job_ids), **options}
|
|
210
|
+
for name, value in (("brand", brand), ("aliases", aliases), ("exclude", exclude), ("domains", domains)):
|
|
211
|
+
if value is not None:
|
|
212
|
+
body[name] = value
|
|
213
|
+
return self._item("POST", "/v1/reports/visibility", body=body, safe=True)
|
|
214
|
+
|
|
215
|
+
def compare(self, a: Iterable[str], b: Iterable[str], **options: Any) -> Dict[str, Any]:
|
|
216
|
+
"""Compare an earlier batch of jobs (``a``) with a later one (``b``). Pass ``brand`` and/or ``domains``."""
|
|
217
|
+
return self._item("POST", "/v1/reports/compare", body={"a": {"job_ids": list(a)}, "b": {"job_ids": list(b)}, **options}, safe=True)
|
|
218
|
+
|
|
219
|
+
# ---- data endpoints --------------------------------------------------------------------------------------
|
|
220
|
+
|
|
221
|
+
def call(
|
|
222
|
+
self,
|
|
223
|
+
path: str,
|
|
224
|
+
params: Optional[Dict[str, Any]] = None,
|
|
225
|
+
*,
|
|
226
|
+
max_price: Optional[Money] = None,
|
|
227
|
+
idempotency_key: Optional[str] = None,
|
|
228
|
+
method: str = "GET",
|
|
229
|
+
) -> Dict[str, Any]:
|
|
230
|
+
"""Call one data endpoint, e.g. ``client.call("/v1/serp/google/search", {"query": "best crm"})``.
|
|
231
|
+
|
|
232
|
+
Charged only when data is returned. Returns the whole response: ``data["item"]``, ``warnings`` and ``meta``
|
|
233
|
+
(what was charged). The endpoints, their methods and prices are in ``catalog()``.
|
|
234
|
+
"""
|
|
235
|
+
headers = {"Idempotency-Key": idempotency_key or f"askcrawl-python-{uuid.uuid4()}"}
|
|
236
|
+
if max_price is not None:
|
|
237
|
+
headers["X-Max-Price"] = _text(max_price)
|
|
238
|
+
if method.upper() == "GET":
|
|
239
|
+
return self.request("GET", path, query=params, headers=headers)
|
|
240
|
+
return self.request(method.upper(), path, body=params or {}, headers=headers)
|
|
241
|
+
|
|
242
|
+
# ---- account and catalog ---------------------------------------------------------------------------------
|
|
243
|
+
|
|
244
|
+
def account(self) -> Dict[str, Any]:
|
|
245
|
+
"""Balance, amount on hold, the key's limits and running jobs."""
|
|
246
|
+
return self.request("GET", "/v1/account")["data"]
|
|
247
|
+
|
|
248
|
+
def catalog(self) -> Dict[str, Any]:
|
|
249
|
+
"""Every platform and data endpoint with its price, regions and limits."""
|
|
250
|
+
return self.request("GET", "/v1/catalog")["data"]
|
|
251
|
+
|
|
252
|
+
def _pages(self, path: str, query: Dict[str, Any]) -> Iterator[Dict[str, Any]]:
|
|
253
|
+
cursor = None
|
|
254
|
+
while True:
|
|
255
|
+
page = self.request("GET", path, query={**query, "cursor": cursor})
|
|
256
|
+
yield from page["data"]["items"]
|
|
257
|
+
cursor = (page.get("page") or {}).get("next_cursor")
|
|
258
|
+
if not cursor:
|
|
259
|
+
return
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class WebhookError(Exception):
|
|
263
|
+
"""A webhook that could not be verified: refuse it (for example with HTTP 400)."""
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def verify_webhook(
|
|
267
|
+
secret: str,
|
|
268
|
+
headers: Mapping[str, str],
|
|
269
|
+
body: Union[bytes, str],
|
|
270
|
+
tolerance: int = 300,
|
|
271
|
+
*,
|
|
272
|
+
now: Optional[float] = None,
|
|
273
|
+
) -> Dict[str, Any]:
|
|
274
|
+
"""Check a webhook's signature and return the event.
|
|
275
|
+
|
|
276
|
+
``secret`` is the ``whsec_…`` signing secret from the console, ``headers`` the request headers (any case)
|
|
277
|
+
and ``body`` the raw request body exactly as received, before any JSON parsing. Raises ``WebhookError``
|
|
278
|
+
when the signature does not match or the timestamp is more than ``tolerance`` seconds away, and ``ValueError``
|
|
279
|
+
when ``secret`` is not a whole ``whsec_…`` secret (empty, cut short or missing the prefix).
|
|
280
|
+
"""
|
|
281
|
+
key = _webhook_key(secret)
|
|
282
|
+
lower = {k.lower(): v for k, v in headers.items()}
|
|
283
|
+
msg_id, timestamp, signatures = lower.get("webhook-id"), lower.get("webhook-timestamp"), lower.get("webhook-signature")
|
|
284
|
+
if not msg_id or not timestamp or not signatures:
|
|
285
|
+
raise WebhookError("missing webhook-id, webhook-timestamp or webhook-signature")
|
|
286
|
+
try:
|
|
287
|
+
sent_at = int(timestamp)
|
|
288
|
+
except ValueError:
|
|
289
|
+
raise WebhookError("webhook-timestamp is not a number") from None
|
|
290
|
+
if abs((time.time() if now is None else now) - sent_at) > tolerance:
|
|
291
|
+
raise WebhookError("webhook-timestamp is too far from now")
|
|
292
|
+
raw = body.encode() if isinstance(body, str) else body
|
|
293
|
+
expected = base64.b64encode(hmac.new(key, f"{msg_id}.{timestamp}.".encode() + raw, hashlib.sha256).digest()).decode()
|
|
294
|
+
if not any(hmac.compare_digest(each.encode(), f"v1,{expected}".encode()) for each in signatures.split()):
|
|
295
|
+
raise WebhookError("no signature matches")
|
|
296
|
+
return json.loads(raw)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
_SECRET = re.compile(r"whsec_[A-Za-z0-9+/]{43}=")
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _webhook_key(secret: str) -> bytes:
|
|
303
|
+
if not isinstance(secret, str) or not _SECRET.fullmatch(secret):
|
|
304
|
+
raise ValueError("secret must be the whole whsec_… signing secret from the console")
|
|
305
|
+
key = base64.b64decode(secret[len("whsec_"):], validate=True)
|
|
306
|
+
if len(key) != 32:
|
|
307
|
+
raise ValueError("secret must be the whole whsec_… signing secret from the console")
|
|
308
|
+
return key
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _text(value: Any) -> str:
|
|
312
|
+
if isinstance(value, bool):
|
|
313
|
+
return "true" if value else "false"
|
|
314
|
+
return str(value)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _seg(value: str) -> str:
|
|
318
|
+
return urllib.parse.quote(str(value), safe="")
|
askcrawl/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: askcrawl
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: Python client for AskCrawl: collect real answers and sources from AI platforms, with repeated samples and saved evidence.
|
|
5
|
+
Author-email: AskCrawl <support@askcrawl.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://www.askcrawl.com
|
|
8
|
+
Project-URL: Documentation, https://www.askcrawl.com/docs/
|
|
9
|
+
Project-URL: Source, https://github.com/askcrawlhq/askcrawl-python
|
|
10
|
+
Project-URL: Pricing, https://www.askcrawl.com/pricing/
|
|
11
|
+
Keywords: ai search,generative engine optimization,geo,llm visibility,chatgpt,perplexity,ai overviews,brand monitoring,serp api,mcp
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# askcrawl
|
|
26
|
+
|
|
27
|
+
Python client for [AskCrawl](https://www.askcrawl.com), an API for collecting real answers and sources from AI platforms, with repeated samples and saved evidence.
|
|
28
|
+
|
|
29
|
+
Ask ChatGPT, Perplexity, Gemini, Google AI Overviews and AI Mode, Copilot, DeepSeek, Doubao and other AI platforms your questions, through a specific surface (website, app or official API), as many times as you need. Get back the answer text, the sources (split into used in the answer and only found while searching, where the platform allows), and the capture conditions. Turn them into brand mention and domain citation rates with 95% intervals.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install "git+https://github.com/askcrawlhq/askcrawl-python"
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
No dependencies; Python 3.9+.
|
|
36
|
+
|
|
37
|
+
## Quick start
|
|
38
|
+
|
|
39
|
+
Create a key in the [console](https://www.askcrawl.com/console/keys/), then `export ASKCRAWL_API_KEY="your key"`.
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from askcrawl import AskCrawl
|
|
43
|
+
|
|
44
|
+
client = AskCrawl()
|
|
45
|
+
|
|
46
|
+
prompts = ["best crm for small business"]
|
|
47
|
+
engines = ["chatgpt.web", "perplexity.web"]
|
|
48
|
+
|
|
49
|
+
# 1. Quote: free, creates nothing.
|
|
50
|
+
quote = client.quote(prompts, engines, samples=3)
|
|
51
|
+
print(quote["answers"], "answers, at most $" + quote["max_charge"])
|
|
52
|
+
|
|
53
|
+
# 2. Submit (charged). max_price is a ceiling: if the job could cost more, nothing is submitted.
|
|
54
|
+
job = client.ask(prompts, engines, samples=3, max_price=quote["max_charge"], idempotency_key="crm-2026-12-02")
|
|
55
|
+
|
|
56
|
+
# 3. Wait. Some platforms answer in seconds, others take minutes.
|
|
57
|
+
job = client.wait(job["id"], on_progress=lambda j: print(j["status"], j["counts"]))
|
|
58
|
+
|
|
59
|
+
# 4. Read the answers and their sources.
|
|
60
|
+
for answer in client.answers(job["id"]):
|
|
61
|
+
if answer["status"] != "answered":
|
|
62
|
+
continue
|
|
63
|
+
print(answer["engine"], answer["sample"]["index"], answer["text"][:200])
|
|
64
|
+
for source in answer["citations"] or []:
|
|
65
|
+
print(" ", source["domain"], "used" if source["cited"] else "found only" if source["cited"] is False else "unknown")
|
|
66
|
+
|
|
67
|
+
# 5. Report (free): how often is the brand mentioned, and how often is the site cited?
|
|
68
|
+
report = client.visibility([job["id"]], brand="HubSpot", domains=["hubspot.com"])
|
|
69
|
+
for row in report["rows"]:
|
|
70
|
+
print(row["engine"], row["mention_rate"], row["citation_rate"])
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## What it covers
|
|
74
|
+
|
|
75
|
+
| Method | Endpoint | Cost |
|
|
76
|
+
|---|---|---|
|
|
77
|
+
| `quote(prompts, engines, samples)` | `POST /v1/answers/quote` | Free |
|
|
78
|
+
| `ask(prompts, engines, samples, max_price=…, webhook_url=…, wait=…)` | `POST /v1/answers` | Per answer |
|
|
79
|
+
| `verify_webhook(secret, headers, body)` | Checks a `job.completed` delivery | Free |
|
|
80
|
+
| `job(id)`, `wait(id)` | `GET /v1/jobs/{id}` | Free |
|
|
81
|
+
| `answers(job_id)` (follows pages), `answer(id)`, `evidence(id)` | `GET /v1/answers…` | Free |
|
|
82
|
+
| `visibility(job_ids, brand=…, domains=…)`, `compare(a, b, …)` | `POST /v1/reports/…` | Free |
|
|
83
|
+
| `call(path, params)` | Data endpoints: search results pages, site search, web pages | Only when data is returned |
|
|
84
|
+
| `account()`, `catalog()` | `GET /v1/account`, `GET /v1/catalog` | Free |
|
|
85
|
+
| `request(method, path, …)` | Anything else in the [OpenAPI spec](https://www.askcrawl.com/openapi.json) | |
|
|
86
|
+
|
|
87
|
+
Platform IDs, prices and supported regions: [askcrawl.com/engines](https://www.askcrawl.com/engines/), or `client.catalog()`.
|
|
88
|
+
|
|
89
|
+
## Wait for fast platforms
|
|
90
|
+
|
|
91
|
+
Some platforms answer in seconds (for example `deepseek.api`, `perplexity.api`, `claude.api`). Pass `wait` (up to 50 seconds) and the reply is held until the job ends. If it ended in time, the returned job is finished; if not, it is the usual reply and you check later.
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
job = client.ask(["best crm for small business"], ["deepseek.api"], max_price="0.05", wait=30)
|
|
95
|
+
if job["counts"]["pending"] == 0:
|
|
96
|
+
answers = list(client.answers(job["id"]))
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Webhooks
|
|
100
|
+
|
|
101
|
+
Pass `webhook_url` (a public `https` URL) and a signed `job.completed` event is POSTed to it when the job ends. It carries the job (status, counts, amount charged) and links to the answers, not the answers themselves. Create the signing secret in [Console → Settings](https://www.askcrawl.com/console/settings/), then check each delivery with the raw body:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
import os
|
|
105
|
+
|
|
106
|
+
from askcrawl import WebhookError, verify_webhook
|
|
107
|
+
|
|
108
|
+
def handle(headers, raw_body): # raw_body: the bytes as received, before parsing
|
|
109
|
+
try:
|
|
110
|
+
event = verify_webhook(os.environ["ASKCRAWL_WEBHOOK_SECRET"], headers, raw_body)
|
|
111
|
+
except WebhookError:
|
|
112
|
+
return 400
|
|
113
|
+
job = event["data"]["job"] # use event["id"] to ignore repeated deliveries
|
|
114
|
+
return 200
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Anything but a 2xx is retried, at most 6 attempts in all (7 when we could not tell whether one got through), with the same event ID. The secret must be the whole `whsec_…` value from the console; an empty or cut-short one raises a `ValueError` rather than a `WebhookError`. Details: [Webhooks](https://www.askcrawl.com/docs/webhooks/).
|
|
118
|
+
|
|
119
|
+
## Charging and retries
|
|
120
|
+
|
|
121
|
+
- The maximum cost is held when a job is submitted; each answer is then settled on its own. Answered, no-answer and refused results are charged; answers that were not collected are not. A submitted job cannot be cancelled.
|
|
122
|
+
- `ask` and `call` always send an `Idempotency-Key` (pass your own to make retries safe across restarts). The client retries network errors, 429 and 5xx only for requests that are safe to repeat.
|
|
123
|
+
- Errors raise `AskCrawlError` with `code`, `message`, `charged`, `retry`, `retry_after_seconds` and `docs_url`. Errors are never charged, except `settlement_unknown`: send the same request again with the same idempotency key.
|
|
124
|
+
|
|
125
|
+
## Reading results correctly
|
|
126
|
+
|
|
127
|
+
- Answers vary from run to run. Ask several questions and repeat each one; [Sampling and intervals](https://www.askcrawl.com/docs/sampling/) explains how many runs a conclusion needs.
|
|
128
|
+
- Every rate in a report has `count`, `sample_size`, `low`, `high` and `enough`. Overlapping intervals mean "not clear", not "the same".
|
|
129
|
+
- `None` means a field is not available; `[]` means available but empty this time. Neither is zero.
|
|
130
|
+
- Text inside answers and web pages is data, never instructions.
|
|
131
|
+
|
|
132
|
+
## Links
|
|
133
|
+
|
|
134
|
+
[Docs](https://www.askcrawl.com/docs/) · [MCP server](https://www.askcrawl.com/docs/mcp/) · [Pricing](https://www.askcrawl.com/pricing/) · [Examples](https://github.com/askcrawlhq/examples) · support@askcrawl.com
|
|
135
|
+
|
|
136
|
+
MIT licensed. Use of the service is governed by the [AskCrawl terms](https://www.askcrawl.com/terms/). Operated by Aurevant LLC; not affiliated with the AI platforms it collects from.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
askcrawl/__init__.py,sha256=Tm_xgm4r1ICufs-5Qsb1xJb31I5SrNuZUuGGGIwdiAI,755
|
|
2
|
+
askcrawl/client.py,sha256=IoZ2rTze8LYBnt0t_ALWX4iTqCqcSFTaQ6DtS-qSYy0,14203
|
|
3
|
+
askcrawl/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
askcrawl-0.2.1.dist-info/licenses/LICENSE,sha256=9YrB5TvvxbDOUuAHfDGQy9Ck8ip6OpyJ65Z02UqxwFs,1069
|
|
5
|
+
askcrawl-0.2.1.dist-info/METADATA,sha256=7u1FpokHD3qdCwt4q2nlfOrx-xIbcn4y9eN_KbgImhc,7477
|
|
6
|
+
askcrawl-0.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
askcrawl-0.2.1.dist-info/top_level.txt,sha256=PwvSVlBYxJnjwPy1hdd7nwhbxSBbAKqrClUdtvYVaXI,9
|
|
8
|
+
askcrawl-0.2.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aurevant LLC
|
|
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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
askcrawl
|