askcrawl 0.2.1__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.
- askcrawl-0.2.1/LICENSE +21 -0
- askcrawl-0.2.1/PKG-INFO +136 -0
- askcrawl-0.2.1/README.md +112 -0
- askcrawl-0.2.1/pyproject.toml +35 -0
- askcrawl-0.2.1/setup.cfg +4 -0
- askcrawl-0.2.1/src/askcrawl/__init__.py +19 -0
- askcrawl-0.2.1/src/askcrawl/client.py +318 -0
- askcrawl-0.2.1/src/askcrawl/py.typed +0 -0
- askcrawl-0.2.1/src/askcrawl.egg-info/PKG-INFO +136 -0
- askcrawl-0.2.1/src/askcrawl.egg-info/SOURCES.txt +11 -0
- askcrawl-0.2.1/src/askcrawl.egg-info/dependency_links.txt +1 -0
- askcrawl-0.2.1/src/askcrawl.egg-info/top_level.txt +1 -0
- askcrawl-0.2.1/tests/test_client.py +193 -0
askcrawl-0.2.1/LICENSE
ADDED
|
@@ -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.
|
askcrawl-0.2.1/PKG-INFO
ADDED
|
@@ -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.
|
askcrawl-0.2.1/README.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# askcrawl
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install "git+https://github.com/askcrawlhq/askcrawl-python"
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
No dependencies; Python 3.9+.
|
|
12
|
+
|
|
13
|
+
## Quick start
|
|
14
|
+
|
|
15
|
+
Create a key in the [console](https://www.askcrawl.com/console/keys/), then `export ASKCRAWL_API_KEY="your key"`.
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from askcrawl import AskCrawl
|
|
19
|
+
|
|
20
|
+
client = AskCrawl()
|
|
21
|
+
|
|
22
|
+
prompts = ["best crm for small business"]
|
|
23
|
+
engines = ["chatgpt.web", "perplexity.web"]
|
|
24
|
+
|
|
25
|
+
# 1. Quote: free, creates nothing.
|
|
26
|
+
quote = client.quote(prompts, engines, samples=3)
|
|
27
|
+
print(quote["answers"], "answers, at most $" + quote["max_charge"])
|
|
28
|
+
|
|
29
|
+
# 2. Submit (charged). max_price is a ceiling: if the job could cost more, nothing is submitted.
|
|
30
|
+
job = client.ask(prompts, engines, samples=3, max_price=quote["max_charge"], idempotency_key="crm-2026-12-02")
|
|
31
|
+
|
|
32
|
+
# 3. Wait. Some platforms answer in seconds, others take minutes.
|
|
33
|
+
job = client.wait(job["id"], on_progress=lambda j: print(j["status"], j["counts"]))
|
|
34
|
+
|
|
35
|
+
# 4. Read the answers and their sources.
|
|
36
|
+
for answer in client.answers(job["id"]):
|
|
37
|
+
if answer["status"] != "answered":
|
|
38
|
+
continue
|
|
39
|
+
print(answer["engine"], answer["sample"]["index"], answer["text"][:200])
|
|
40
|
+
for source in answer["citations"] or []:
|
|
41
|
+
print(" ", source["domain"], "used" if source["cited"] else "found only" if source["cited"] is False else "unknown")
|
|
42
|
+
|
|
43
|
+
# 5. Report (free): how often is the brand mentioned, and how often is the site cited?
|
|
44
|
+
report = client.visibility([job["id"]], brand="HubSpot", domains=["hubspot.com"])
|
|
45
|
+
for row in report["rows"]:
|
|
46
|
+
print(row["engine"], row["mention_rate"], row["citation_rate"])
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## What it covers
|
|
50
|
+
|
|
51
|
+
| Method | Endpoint | Cost |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| `quote(prompts, engines, samples)` | `POST /v1/answers/quote` | Free |
|
|
54
|
+
| `ask(prompts, engines, samples, max_price=…, webhook_url=…, wait=…)` | `POST /v1/answers` | Per answer |
|
|
55
|
+
| `verify_webhook(secret, headers, body)` | Checks a `job.completed` delivery | Free |
|
|
56
|
+
| `job(id)`, `wait(id)` | `GET /v1/jobs/{id}` | Free |
|
|
57
|
+
| `answers(job_id)` (follows pages), `answer(id)`, `evidence(id)` | `GET /v1/answers…` | Free |
|
|
58
|
+
| `visibility(job_ids, brand=…, domains=…)`, `compare(a, b, …)` | `POST /v1/reports/…` | Free |
|
|
59
|
+
| `call(path, params)` | Data endpoints: search results pages, site search, web pages | Only when data is returned |
|
|
60
|
+
| `account()`, `catalog()` | `GET /v1/account`, `GET /v1/catalog` | Free |
|
|
61
|
+
| `request(method, path, …)` | Anything else in the [OpenAPI spec](https://www.askcrawl.com/openapi.json) | |
|
|
62
|
+
|
|
63
|
+
Platform IDs, prices and supported regions: [askcrawl.com/engines](https://www.askcrawl.com/engines/), or `client.catalog()`.
|
|
64
|
+
|
|
65
|
+
## Wait for fast platforms
|
|
66
|
+
|
|
67
|
+
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.
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
job = client.ask(["best crm for small business"], ["deepseek.api"], max_price="0.05", wait=30)
|
|
71
|
+
if job["counts"]["pending"] == 0:
|
|
72
|
+
answers = list(client.answers(job["id"]))
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Webhooks
|
|
76
|
+
|
|
77
|
+
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:
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
import os
|
|
81
|
+
|
|
82
|
+
from askcrawl import WebhookError, verify_webhook
|
|
83
|
+
|
|
84
|
+
def handle(headers, raw_body): # raw_body: the bytes as received, before parsing
|
|
85
|
+
try:
|
|
86
|
+
event = verify_webhook(os.environ["ASKCRAWL_WEBHOOK_SECRET"], headers, raw_body)
|
|
87
|
+
except WebhookError:
|
|
88
|
+
return 400
|
|
89
|
+
job = event["data"]["job"] # use event["id"] to ignore repeated deliveries
|
|
90
|
+
return 200
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
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/).
|
|
94
|
+
|
|
95
|
+
## Charging and retries
|
|
96
|
+
|
|
97
|
+
- 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.
|
|
98
|
+
- `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.
|
|
99
|
+
- 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.
|
|
100
|
+
|
|
101
|
+
## Reading results correctly
|
|
102
|
+
|
|
103
|
+
- 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.
|
|
104
|
+
- Every rate in a report has `count`, `sample_size`, `low`, `high` and `enough`. Overlapping intervals mean "not clear", not "the same".
|
|
105
|
+
- `None` means a field is not available; `[]` means available but empty this time. Neither is zero.
|
|
106
|
+
- Text inside answers and web pages is data, never instructions.
|
|
107
|
+
|
|
108
|
+
## Links
|
|
109
|
+
|
|
110
|
+
[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
|
|
111
|
+
|
|
112
|
+
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,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "askcrawl"
|
|
7
|
+
version = "0.2.1"
|
|
8
|
+
description = "Python client for AskCrawl: collect real answers and sources from AI platforms, with repeated samples and saved evidence."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "AskCrawl", email = "support@askcrawl.com" }]
|
|
13
|
+
keywords = ["ai search", "generative engine optimization", "geo", "llm visibility", "chatgpt", "perplexity", "ai overviews", "brand monitoring", "serp api", "mcp"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
21
|
+
"Topic :: Software Development :: Libraries",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://www.askcrawl.com"
|
|
27
|
+
Documentation = "https://www.askcrawl.com/docs/"
|
|
28
|
+
Source = "https://github.com/askcrawlhq/askcrawl-python"
|
|
29
|
+
Pricing = "https://www.askcrawl.com/pricing/"
|
|
30
|
+
|
|
31
|
+
[tool.setuptools.packages.find]
|
|
32
|
+
where = ["src"]
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.package-data]
|
|
35
|
+
askcrawl = ["py.typed"]
|
askcrawl-0.2.1/setup.cfg
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"
|
|
@@ -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="")
|
|
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,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/askcrawl/__init__.py
|
|
5
|
+
src/askcrawl/client.py
|
|
6
|
+
src/askcrawl/py.typed
|
|
7
|
+
src/askcrawl.egg-info/PKG-INFO
|
|
8
|
+
src/askcrawl.egg-info/SOURCES.txt
|
|
9
|
+
src/askcrawl.egg-info/dependency_links.txt
|
|
10
|
+
src/askcrawl.egg-info/top_level.txt
|
|
11
|
+
tests/test_client.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
askcrawl
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Offline tests: a local HTTP server stands in for the API. Run with `python -m unittest`."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
import unittest
|
|
10
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
11
|
+
|
|
12
|
+
from askcrawl import AskCrawl, AskCrawlError, WebhookError, verify_webhook
|
|
13
|
+
|
|
14
|
+
SEEN = []
|
|
15
|
+
SCRIPT = {}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Handler(BaseHTTPRequestHandler):
|
|
19
|
+
def log_message(self, *args):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
def _reply(self):
|
|
23
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
24
|
+
body = json.loads(self.rfile.read(length)) if length else None
|
|
25
|
+
SEEN.append({"method": self.command, "path": self.path, "headers": dict(self.headers), "body": body})
|
|
26
|
+
key = f"{self.command} {self.path.split('?')[0]}"
|
|
27
|
+
replies = SCRIPT[key]
|
|
28
|
+
status, payload = replies.pop(0) if len(replies) > 1 else replies[0]
|
|
29
|
+
data = json.dumps(payload).encode()
|
|
30
|
+
self.send_response(status)
|
|
31
|
+
self.send_header("Content-Type", "application/json")
|
|
32
|
+
self.send_header("Content-Length", str(len(data)))
|
|
33
|
+
self.end_headers()
|
|
34
|
+
self.wfile.write(data)
|
|
35
|
+
|
|
36
|
+
do_GET = _reply
|
|
37
|
+
do_POST = _reply
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ClientTest(unittest.TestCase):
|
|
41
|
+
@classmethod
|
|
42
|
+
def setUpClass(cls):
|
|
43
|
+
cls.server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
44
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
45
|
+
cls.client = AskCrawl("ac_test", base_url=f"http://127.0.0.1:{cls.server.server_port}", max_retries=2)
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def tearDownClass(cls):
|
|
49
|
+
cls.server.shutdown()
|
|
50
|
+
|
|
51
|
+
def setUp(self):
|
|
52
|
+
SEEN.clear()
|
|
53
|
+
SCRIPT.clear()
|
|
54
|
+
|
|
55
|
+
def test_ask_sends_ceiling_and_idempotency_key(self):
|
|
56
|
+
SCRIPT["POST /v1/answers"] = [(202, {"code": "ok", "data": {"item": {"id": "j1"}}})]
|
|
57
|
+
job = self.client.ask(["q"], ["chatgpt.web"], samples=2, max_price="0.01", idempotency_key="k1", tags=["t"])
|
|
58
|
+
self.assertEqual(job["id"], "j1")
|
|
59
|
+
sent = SEEN[0]
|
|
60
|
+
self.assertEqual(sent["headers"]["Idempotency-Key"], "k1")
|
|
61
|
+
self.assertEqual(sent["headers"]["X-Max-Price"], "0.01")
|
|
62
|
+
self.assertEqual(sent["headers"]["Authorization"], "Bearer ac_test")
|
|
63
|
+
self.assertEqual(sent["body"], {"prompts": ["q"], "engines": ["chatgpt.web"], "samples": 2, "tags": ["t"]})
|
|
64
|
+
|
|
65
|
+
def test_ask_requires_max_price(self):
|
|
66
|
+
with self.assertRaises(TypeError):
|
|
67
|
+
self.client.ask(["q"], ["chatgpt.web"]) # type: ignore[call-arg]
|
|
68
|
+
|
|
69
|
+
def test_answers_follows_pages(self):
|
|
70
|
+
SCRIPT["GET /v1/answers"] = [
|
|
71
|
+
(200, {"code": "ok", "data": {"items": [{"id": "a1"}]}, "page": {"next_cursor": "c2"}}),
|
|
72
|
+
(200, {"code": "ok", "data": {"items": [{"id": "a2"}]}, "page": {"next_cursor": None}}),
|
|
73
|
+
]
|
|
74
|
+
self.assertEqual([a["id"] for a in self.client.answers("j1")], ["a1", "a2"])
|
|
75
|
+
self.assertIn("cursor=c2", SEEN[1]["path"])
|
|
76
|
+
self.assertNotIn("cursor", SEEN[0]["path"])
|
|
77
|
+
|
|
78
|
+
def test_error_is_raised_with_details(self):
|
|
79
|
+
SCRIPT["POST /v1/answers/quote"] = [(400, {"code": "invalid_params", "message": "bad", "charged": False, "docs_url": "https://x"})]
|
|
80
|
+
with self.assertRaises(AskCrawlError) as caught:
|
|
81
|
+
self.client.quote(["q"], ["nope"])
|
|
82
|
+
self.assertEqual(caught.exception.code, "invalid_params")
|
|
83
|
+
self.assertFalse(caught.exception.charged)
|
|
84
|
+
self.assertEqual(len(SEEN), 1)
|
|
85
|
+
|
|
86
|
+
def test_settlement_unknown_is_retried_with_the_same_key(self):
|
|
87
|
+
SCRIPT["POST /v1/answers"] = [
|
|
88
|
+
(500, {"code": "settlement_unknown", "message": "later", "charged": None, "retry": "same_key", "retry_after_seconds": 0.01}),
|
|
89
|
+
(202, {"code": "ok", "data": {"item": {"id": "j1"}}}),
|
|
90
|
+
]
|
|
91
|
+
self.client.ask(["q"], ["chatgpt.web"], max_price=1)
|
|
92
|
+
self.assertEqual(len(SEEN), 2)
|
|
93
|
+
self.assertEqual(SEEN[0]["headers"]["Idempotency-Key"], SEEN[1]["headers"]["Idempotency-Key"])
|
|
94
|
+
|
|
95
|
+
def test_free_quote_is_retried_when_the_api_says_so(self):
|
|
96
|
+
SCRIPT["POST /v1/answers/quote"] = [(503, {"code": "overloaded", "message": "busy", "retry": "yes", "retry_after_seconds": 0.01}), (200, {"code": "ok", "data": {"item": {"answers": 1}}})]
|
|
97
|
+
self.assertEqual(self.client.quote(["q"], ["chatgpt.web"])["answers"], 1)
|
|
98
|
+
self.assertEqual(len(SEEN), 2)
|
|
99
|
+
|
|
100
|
+
def test_charged_post_without_key_is_not_retried(self):
|
|
101
|
+
SCRIPT["POST /v1/links/targets/list"] = [(503, {"code": "overloaded", "message": "busy", "retry": "yes", "retry_after_seconds": 0.01})]
|
|
102
|
+
with self.assertRaises(AskCrawlError):
|
|
103
|
+
self.client.request("POST", "/v1/links/targets/list", body={})
|
|
104
|
+
self.assertEqual(len(SEEN), 1)
|
|
105
|
+
|
|
106
|
+
def test_same_key_error_is_not_retried_without_a_key(self):
|
|
107
|
+
SCRIPT["GET /v1/jobs/j9"] = [(500, {"code": "settlement_unknown", "message": "later", "retry": "same_key", "retry_after_seconds": 0.01})]
|
|
108
|
+
with self.assertRaises(AskCrawlError):
|
|
109
|
+
self.client.job("j9")
|
|
110
|
+
self.assertEqual(len(SEEN), 1)
|
|
111
|
+
|
|
112
|
+
def test_wait_stops_when_nothing_is_pending(self):
|
|
113
|
+
SCRIPT["GET /v1/jobs/j1"] = [
|
|
114
|
+
(200, {"code": "ok", "data": {"item": {"counts": {"pending": 1}, "retry_after_seconds": 0.01}}}),
|
|
115
|
+
(200, {"code": "ok", "data": {"item": {"counts": {"pending": 0}}}}),
|
|
116
|
+
]
|
|
117
|
+
self.assertEqual(self.client.wait("j1")["counts"]["pending"], 0)
|
|
118
|
+
self.assertEqual(len(SEEN), 2)
|
|
119
|
+
|
|
120
|
+
def test_visibility_omits_unset_fields(self):
|
|
121
|
+
SCRIPT["POST /v1/reports/visibility"] = [(200, {"code": "ok", "data": {"item": {"rows": []}}})]
|
|
122
|
+
self.client.visibility(["j1"], brand="Acme")
|
|
123
|
+
self.assertEqual(SEEN[0]["body"], {"job_ids": ["j1"], "brand": "Acme"})
|
|
124
|
+
|
|
125
|
+
def test_call_passes_query_and_returns_meta(self):
|
|
126
|
+
SCRIPT["GET /v1/serp/google/search"] = [(200, {"code": "ok", "data": {"item": {}}, "warnings": [], "meta": {"charged": "0.001"}})]
|
|
127
|
+
out = self.client.call("/v1/serp/google/search", {"query": "best crm"}, max_price="0.01")
|
|
128
|
+
self.assertEqual(out["meta"]["charged"], "0.001")
|
|
129
|
+
self.assertIn("query=best+crm", SEEN[0]["path"])
|
|
130
|
+
self.assertEqual(SEEN[0]["headers"]["X-Max-Price"], "0.01")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_ask_sends_webhook_url_and_wait(self):
|
|
134
|
+
SCRIPT["POST /v1/answers"] = [(202, {"code": "ok", "data": {"item": {"id": "j1"}}})]
|
|
135
|
+
self.client.ask(["q"], ["deepseek.api"], max_price="0.01", webhook_url="https://example.com/hook", wait=30)
|
|
136
|
+
self.assertEqual(SEEN[0]["body"]["webhook_url"], "https://example.com/hook")
|
|
137
|
+
self.assertEqual(SEEN[0]["body"]["wait"], 30)
|
|
138
|
+
|
|
139
|
+
def test_ask_without_options_sends_neither(self):
|
|
140
|
+
SCRIPT["POST /v1/answers"] = [(202, {"code": "ok", "data": {"item": {"id": "j1"}}})]
|
|
141
|
+
self.client.ask(["q"], ["deepseek.api"], max_price="0.01")
|
|
142
|
+
self.assertNotIn("webhook_url", SEEN[0]["body"])
|
|
143
|
+
self.assertNotIn("wait", SEEN[0]["body"])
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
SECRET = "whsec_" + base64.b64encode(b"0123456789abcdef0123456789abcdef").decode()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def signed(body, *, secret=SECRET, msg_id="evt_1", at=None):
|
|
150
|
+
at = str(int(time.time()) if at is None else at)
|
|
151
|
+
key = base64.b64decode(secret[len("whsec_"):])
|
|
152
|
+
sig = base64.b64encode(hmac.new(key, f"{msg_id}.{at}.{body}".encode(), hashlib.sha256).digest()).decode()
|
|
153
|
+
return {"Webhook-Id": msg_id, "Webhook-Timestamp": at, "Webhook-Signature": f"v1,{sig}"}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class WebhookTest(unittest.TestCase):
|
|
157
|
+
body = '{"id":"evt_1","type":"job.completed","data":{"job":{"id":"j1"}}}'
|
|
158
|
+
|
|
159
|
+
def test_valid_signature_returns_the_event(self):
|
|
160
|
+
event = verify_webhook(SECRET, signed(self.body), self.body.encode())
|
|
161
|
+
self.assertEqual(event["type"], "job.completed")
|
|
162
|
+
|
|
163
|
+
def test_wrong_signature_is_refused(self):
|
|
164
|
+
other = "whsec_" + base64.b64encode(b"another-secret-another-secret-00").decode()
|
|
165
|
+
with self.assertRaises(WebhookError):
|
|
166
|
+
verify_webhook(SECRET, signed(self.body, secret=other), self.body)
|
|
167
|
+
|
|
168
|
+
def test_changed_body_is_refused(self):
|
|
169
|
+
with self.assertRaises(WebhookError):
|
|
170
|
+
verify_webhook(SECRET, signed(self.body), self.body.replace("j1", "j2"))
|
|
171
|
+
|
|
172
|
+
def test_old_timestamp_is_refused(self):
|
|
173
|
+
with self.assertRaises(WebhookError):
|
|
174
|
+
verify_webhook(SECRET, signed(self.body, at=int(time.time()) - 301), self.body)
|
|
175
|
+
|
|
176
|
+
def test_any_of_several_signatures_is_enough(self):
|
|
177
|
+
headers = signed(self.body)
|
|
178
|
+
headers["Webhook-Signature"] = "v1,bm90LWl0 " + headers["Webhook-Signature"]
|
|
179
|
+
self.assertEqual(verify_webhook(SECRET, headers, self.body)["id"], "evt_1")
|
|
180
|
+
|
|
181
|
+
def test_missing_headers_are_refused(self):
|
|
182
|
+
with self.assertRaises(WebhookError):
|
|
183
|
+
verify_webhook(SECRET, {}, self.body)
|
|
184
|
+
|
|
185
|
+
def test_secret_that_is_empty_cut_short_or_not_whsec_is_a_config_error(self):
|
|
186
|
+
short = "whsec_" + base64.b64encode(b"x" * 16).decode()
|
|
187
|
+
for secret in ["", "whsec_", SECRET[:-5], SECRET[len("whsec_"):], short, SECRET + "x"]:
|
|
188
|
+
with self.assertRaises(ValueError, msg=secret):
|
|
189
|
+
verify_webhook(secret, signed(self.body), self.body)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
if __name__ == "__main__":
|
|
193
|
+
unittest.main()
|