dagster-specstream 0.1.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.
- dagster_specstream-0.1.0/.gitignore +68 -0
- dagster_specstream-0.1.0/LICENSE +21 -0
- dagster_specstream-0.1.0/PKG-INFO +100 -0
- dagster_specstream-0.1.0/README.md +71 -0
- dagster_specstream-0.1.0/dagster_specstream/__init__.py +8 -0
- dagster_specstream-0.1.0/dagster_specstream/_api.py +259 -0
- dagster_specstream-0.1.0/dagster_specstream/py.typed +0 -0
- dagster_specstream-0.1.0/dagster_specstream/resource.py +128 -0
- dagster_specstream-0.1.0/pyproject.toml +49 -0
- dagster_specstream-0.1.0/tests/test_dagster_specstream.py +200 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
.venv/
|
|
3
|
+
__pycache__/
|
|
4
|
+
*.py[cod]
|
|
5
|
+
.pytest_cache/
|
|
6
|
+
.mypy_cache/
|
|
7
|
+
.ruff_cache/
|
|
8
|
+
.coverage
|
|
9
|
+
coverage/
|
|
10
|
+
|
|
11
|
+
# Node/frontend
|
|
12
|
+
node_modules/
|
|
13
|
+
build/
|
|
14
|
+
dist/
|
|
15
|
+
playwright-report/
|
|
16
|
+
test-results/
|
|
17
|
+
.react-router/
|
|
18
|
+
|
|
19
|
+
# Runtime/output
|
|
20
|
+
site-*/
|
|
21
|
+
*.log
|
|
22
|
+
*.dump
|
|
23
|
+
/exports/*
|
|
24
|
+
/growth/email/out/
|
|
25
|
+
screenshots/
|
|
26
|
+
|
|
27
|
+
# Secrets
|
|
28
|
+
.env
|
|
29
|
+
.env.*
|
|
30
|
+
!.env.example
|
|
31
|
+
*.pem
|
|
32
|
+
*.key
|
|
33
|
+
|
|
34
|
+
# Editors/OS
|
|
35
|
+
.DS_Store
|
|
36
|
+
.idea/
|
|
37
|
+
.vscode/
|
|
38
|
+
|
|
39
|
+
# Isolated engine verification state
|
|
40
|
+
.engine-local/
|
|
41
|
+
|
|
42
|
+
# Isolated product-hardening verification state
|
|
43
|
+
.hardening-local/
|
|
44
|
+
|
|
45
|
+
# Isolated product-maturation verification state (short Unix socket paths)
|
|
46
|
+
/.maturation-local/
|
|
47
|
+
/.t/
|
|
48
|
+
|
|
49
|
+
.runtime/
|
|
50
|
+
/design/brand/street-world/specstream-street-world.zip
|
|
51
|
+
|
|
52
|
+
/artifacts/launch-validation/
|
|
53
|
+
|
|
54
|
+
/artifacts/launch-package/
|
|
55
|
+
|
|
56
|
+
# Website build output read by the pages (page dates from git)
|
|
57
|
+
apps/website/src/data/lastmod.generated.json
|
|
58
|
+
plugins/openai/ui/harness/harness.js
|
|
59
|
+
apps/workspace/dist-chatgpt/
|
|
60
|
+
marketing/native/*/
|
|
61
|
+
marketing/native/START-HERE.html
|
|
62
|
+
|
|
63
|
+
# the crew board and its runs (ops/crew.py): a database and job scripts, not source
|
|
64
|
+
/var/crew/
|
|
65
|
+
|
|
66
|
+
# Work trees of parallel helpers: full copies of the repo. Searches and git must not walk them
|
|
67
|
+
# (Nov 12: 50 copies inside the repo kept the /home disk at 100% busy).
|
|
68
|
+
.claude/worktrees
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SpecStream SAS
|
|
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,100 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: dagster-specstream
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: SpecStream for Dagster: the live web data engine. A resource for the Search API, the Extract API and Deep Search.
|
|
5
|
+
Project-URL: Homepage, https://specstream.ai
|
|
6
|
+
Project-URL: Documentation, https://specstream.ai/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/specstream/specstream-tools/tree/main/packages/dagster-specstream
|
|
8
|
+
Project-URL: Issues, https://github.com/specstream/specstream-tools/issues
|
|
9
|
+
Project-URL: Pricing, https://specstream.ai/pricing
|
|
10
|
+
Author-email: SpecStream <support@specstream.ai>
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: dagster,dagster-integration,etl,extract,live-web,specstream,web-data,web-search
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Requires-Dist: dagster>=1.8
|
|
26
|
+
Provides-Extra: test
|
|
27
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# dagster-specstream
|
|
31
|
+
|
|
32
|
+
[SpecStream](https://specstream.ai) is the live web data engine. One platform to build, search, extract, enrich, map, and monitor data across the entire web.
|
|
33
|
+
|
|
34
|
+
Ask for any dataset in plain words, and SpecStream builds it from the entire live web: every match found, extracted and enriched into structured records, then monitored for change. It runs through the API and MCP, and inside Sheets, CRMs, Slack, n8n, Zapier and the other tools teams already use.
|
|
35
|
+
|
|
36
|
+
Source URL and read time on every value.
|
|
37
|
+
|
|
38
|
+
This package is the SpecStream integration for Dagster 1.8 and later: one resource, `SpecStreamResource`, for assets and ops.
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install dagster-specstream
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Resource
|
|
45
|
+
|
|
46
|
+
Put your API key (Agents & API in your SpecStream workspace) in `SPECSTREAM_API_KEY` and add the resource to your definitions:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from dagster import Definitions, EnvVar
|
|
50
|
+
from dagster_specstream import SpecStreamResource
|
|
51
|
+
|
|
52
|
+
defs = Definitions(
|
|
53
|
+
assets=[...],
|
|
54
|
+
resources={"specstream": SpecStreamResource(api_key=EnvVar("SPECSTREAM_API_KEY"))},
|
|
55
|
+
)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
A free account comes with $10 of credit and needs no card: [specstream.ai](https://specstream.ai/signup).
|
|
59
|
+
|
|
60
|
+
| Method | API | Price |
|
|
61
|
+
| --- | --- | --- |
|
|
62
|
+
| `web_search(query, speed=..., num=...)` | Search API, `GET /v1/web-search` | $5 per 1,000 searches of up to 10 results; $1 per 1,000 with `speed="fast"` |
|
|
63
|
+
| `extract_pages(urls, format=...)` | Extract API, `POST /v1/extract`, 1 to 20 URLs | $0.80 per 1,000 pages; a page with no text is not charged |
|
|
64
|
+
| `deep_search(context, request, max_results=..., max_price_usd=...)` | Deep Search | 5 cents, 15 cents or $1 per delivered row |
|
|
65
|
+
|
|
66
|
+
Each method returns the API's reply as a dict.
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from dagster import AssetExecutionContext, RetryPolicy, asset
|
|
70
|
+
from dagster_specstream import SpecStreamResource
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@asset
|
|
74
|
+
def release_news(specstream: SpecStreamResource) -> dict:
|
|
75
|
+
return specstream.web_search("Dagster latest release", speed="fast")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@asset
|
|
79
|
+
def release_page(release_news: dict, specstream: SpecStreamResource) -> dict:
|
|
80
|
+
return specstream.extract_pages(release_news["sources"][0]["url"])
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@asset(retry_policy=RetryPolicy(max_retries=3))
|
|
84
|
+
def orchestrators(context: AssetExecutionContext, specstream: SpecStreamResource) -> list[dict]:
|
|
85
|
+
result = specstream.deep_search(
|
|
86
|
+
context,
|
|
87
|
+
"Open-source workflow orchestrators with their website and license",
|
|
88
|
+
max_results=25,
|
|
89
|
+
max_price_usd=5,
|
|
90
|
+
)
|
|
91
|
+
return result["rows"]
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`deep_search` starts a run only when its quoted maximum is at or below `max_price_usd`; otherwise nothing runs and the step fails with the price, without a retry. The idempotency key comes from the run (the first run's id when a run is re-executed), the asset and the partition, so a retry or a re-execution continues the same list and never buys it twice. Pass `idempotency_key` to choose it yourself. When the list is still running after `wait_seconds` (420 by default), the step asks Dagster to retry it (`retries_while_running`, 3 by default) and the retry picks the list up. The result holds `list_id`, `status`, `list_link`, `row_count` and `rows`; each row carries `source_url` and `checked_at`.
|
|
95
|
+
|
|
96
|
+
`find_list(request, max_results=..., max_price_usd=..., idempotency_key=...)` is the same call without Dagster's handling: it returns every status, `needs_edit` and `over_maximum` included.
|
|
97
|
+
|
|
98
|
+
## License
|
|
99
|
+
|
|
100
|
+
MIT
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# dagster-specstream
|
|
2
|
+
|
|
3
|
+
[SpecStream](https://specstream.ai) is the live web data engine. One platform to build, search, extract, enrich, map, and monitor data across the entire web.
|
|
4
|
+
|
|
5
|
+
Ask for any dataset in plain words, and SpecStream builds it from the entire live web: every match found, extracted and enriched into structured records, then monitored for change. It runs through the API and MCP, and inside Sheets, CRMs, Slack, n8n, Zapier and the other tools teams already use.
|
|
6
|
+
|
|
7
|
+
Source URL and read time on every value.
|
|
8
|
+
|
|
9
|
+
This package is the SpecStream integration for Dagster 1.8 and later: one resource, `SpecStreamResource`, for assets and ops.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install dagster-specstream
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Resource
|
|
16
|
+
|
|
17
|
+
Put your API key (Agents & API in your SpecStream workspace) in `SPECSTREAM_API_KEY` and add the resource to your definitions:
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from dagster import Definitions, EnvVar
|
|
21
|
+
from dagster_specstream import SpecStreamResource
|
|
22
|
+
|
|
23
|
+
defs = Definitions(
|
|
24
|
+
assets=[...],
|
|
25
|
+
resources={"specstream": SpecStreamResource(api_key=EnvVar("SPECSTREAM_API_KEY"))},
|
|
26
|
+
)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
A free account comes with $10 of credit and needs no card: [specstream.ai](https://specstream.ai/signup).
|
|
30
|
+
|
|
31
|
+
| Method | API | Price |
|
|
32
|
+
| --- | --- | --- |
|
|
33
|
+
| `web_search(query, speed=..., num=...)` | Search API, `GET /v1/web-search` | $5 per 1,000 searches of up to 10 results; $1 per 1,000 with `speed="fast"` |
|
|
34
|
+
| `extract_pages(urls, format=...)` | Extract API, `POST /v1/extract`, 1 to 20 URLs | $0.80 per 1,000 pages; a page with no text is not charged |
|
|
35
|
+
| `deep_search(context, request, max_results=..., max_price_usd=...)` | Deep Search | 5 cents, 15 cents or $1 per delivered row |
|
|
36
|
+
|
|
37
|
+
Each method returns the API's reply as a dict.
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from dagster import AssetExecutionContext, RetryPolicy, asset
|
|
41
|
+
from dagster_specstream import SpecStreamResource
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@asset
|
|
45
|
+
def release_news(specstream: SpecStreamResource) -> dict:
|
|
46
|
+
return specstream.web_search("Dagster latest release", speed="fast")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@asset
|
|
50
|
+
def release_page(release_news: dict, specstream: SpecStreamResource) -> dict:
|
|
51
|
+
return specstream.extract_pages(release_news["sources"][0]["url"])
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@asset(retry_policy=RetryPolicy(max_retries=3))
|
|
55
|
+
def orchestrators(context: AssetExecutionContext, specstream: SpecStreamResource) -> list[dict]:
|
|
56
|
+
result = specstream.deep_search(
|
|
57
|
+
context,
|
|
58
|
+
"Open-source workflow orchestrators with their website and license",
|
|
59
|
+
max_results=25,
|
|
60
|
+
max_price_usd=5,
|
|
61
|
+
)
|
|
62
|
+
return result["rows"]
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`deep_search` starts a run only when its quoted maximum is at or below `max_price_usd`; otherwise nothing runs and the step fails with the price, without a retry. The idempotency key comes from the run (the first run's id when a run is re-executed), the asset and the partition, so a retry or a re-execution continues the same list and never buys it twice. Pass `idempotency_key` to choose it yourself. When the list is still running after `wait_seconds` (420 by default), the step asks Dagster to retry it (`retries_while_running`, 3 by default) and the retry picks the list up. The result holds `list_id`, `status`, `list_link`, `row_count` and `rows`; each row carries `source_url` and `checked_at`.
|
|
66
|
+
|
|
67
|
+
`find_list(request, max_results=..., max_price_usd=..., idempotency_key=...)` is the same call without Dagster's handling: it returns every status, `needs_edit` and `over_maximum` included.
|
|
68
|
+
|
|
69
|
+
## License
|
|
70
|
+
|
|
71
|
+
MIT
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""SpecStream for Dagster: a resource for the Search API, the Extract API and Deep Search."""
|
|
2
|
+
|
|
3
|
+
from dagster_specstream._api import SpecStreamAPI, SpecStreamError
|
|
4
|
+
from dagster_specstream.resource import SpecStreamResource, run_key
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
|
|
8
|
+
__all__ = ["SpecStreamAPI", "SpecStreamError", "SpecStreamResource", "__version__", "run_key"]
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""The SpecStream REST calls the resource makes: search, extract, and a Deep Search list run within a maximum price."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Any, Callable
|
|
12
|
+
|
|
13
|
+
DEFAULT_BASE_URL = "https://api.specstream.ai"
|
|
14
|
+
USER_AGENT = "dagster-specstream/0.1.0"
|
|
15
|
+
# A list runs for up to about five minutes, so a task waits a little longer than that by default.
|
|
16
|
+
DEFAULT_WAIT_SECONDS = 420.0
|
|
17
|
+
FINISHED = {"completed", "partial"}
|
|
18
|
+
STOPPED = {"failed", "cancelled", "canceled", "expired"}
|
|
19
|
+
# Fields every row carries; a column with the same name is renamed so it can't overwrite them.
|
|
20
|
+
RESERVED = {"list_id", "list_link", "position", "source_url", "checked_at"}
|
|
21
|
+
SPEEDS = {"default", "fast"}
|
|
22
|
+
|
|
23
|
+
Opener = Callable[[urllib.request.Request, float], Any]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _urlopen(request: urllib.request.Request, timeout: float) -> Any:
|
|
27
|
+
return urllib.request.urlopen(request, timeout=timeout)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SpecStreamError(RuntimeError):
|
|
31
|
+
"""SpecStream refused a call or answered with something this package can't read."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _dollars(cents: int) -> str:
|
|
35
|
+
return f"${cents / 100:.2f}"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def list_link(find_id: str) -> str:
|
|
39
|
+
return f"https://specstream.ai/workspace/collections/{urllib.parse.quote(find_id, safe='')}"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def flatten_row(find_id: str, record: dict[str, Any], flat: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
43
|
+
"""One row as flat fields: each column's label holds what the list shows, and each value's page
|
|
44
|
+
(<field>_source) plus the page that put the row in the list (source_url, checked_at)."""
|
|
45
|
+
flat = flat or {}
|
|
46
|
+
sources = {k: v for k, v in flat.items() if k.endswith("_source") and k[: -len("_source")] in flat}
|
|
47
|
+
row: dict[str, Any] = {"list_id": find_id, "position": record.get("ordinal")}
|
|
48
|
+
for cell in record.get("details") or record.get("cells") or []:
|
|
49
|
+
label = str(cell.get("label") or cell.get("column_id") or "").strip()
|
|
50
|
+
if not label:
|
|
51
|
+
continue
|
|
52
|
+
if label in RESERVED or label in sources:
|
|
53
|
+
label = f"{label} (column)"
|
|
54
|
+
if cell.get("absence"):
|
|
55
|
+
value: Any = ""
|
|
56
|
+
elif cell.get("display") is not None:
|
|
57
|
+
value = cell["display"]
|
|
58
|
+
else:
|
|
59
|
+
value = cell.get("value") if cell.get("value") is not None else ""
|
|
60
|
+
row[label] = value
|
|
61
|
+
row.update(sources)
|
|
62
|
+
row["source_url"] = flat.get("source_url") or ""
|
|
63
|
+
row["checked_at"] = flat.get("checked_at") or ""
|
|
64
|
+
row["list_link"] = list_link(find_id)
|
|
65
|
+
return row
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass
|
|
69
|
+
class SpecStreamAPI:
|
|
70
|
+
api_key: str
|
|
71
|
+
base_url: str = DEFAULT_BASE_URL
|
|
72
|
+
timeout: float = 150.0
|
|
73
|
+
opener: Opener | None = None
|
|
74
|
+
sleep: Callable[[float], None] = time.sleep
|
|
75
|
+
clock: Callable[[], float] = time.monotonic
|
|
76
|
+
|
|
77
|
+
def request(self, method: str, path: str, body: dict[str, Any] | None = None, *, allow_404: bool = False) -> dict[str, Any] | None:
|
|
78
|
+
key = (self.api_key or "").strip()
|
|
79
|
+
if not key:
|
|
80
|
+
raise SpecStreamError(
|
|
81
|
+
"The SpecStream connection has no API key. Put the key in the connection's API key (password) field; "
|
|
82
|
+
"create one under Agents & API in your SpecStream workspace."
|
|
83
|
+
)
|
|
84
|
+
request = urllib.request.Request(
|
|
85
|
+
(self.base_url or DEFAULT_BASE_URL).rstrip("/") + path,
|
|
86
|
+
data=None if body is None else json.dumps(body).encode(),
|
|
87
|
+
method=method,
|
|
88
|
+
headers={
|
|
89
|
+
"Authorization": key if key.lower().startswith("bearer ") else f"Bearer {key}",
|
|
90
|
+
"Accept": "application/json",
|
|
91
|
+
"Content-Type": "application/json",
|
|
92
|
+
"User-Agent": USER_AGENT,
|
|
93
|
+
},
|
|
94
|
+
)
|
|
95
|
+
open_ = self.opener or _urlopen
|
|
96
|
+
try:
|
|
97
|
+
response = open_(request, self.timeout)
|
|
98
|
+
try:
|
|
99
|
+
raw = response.read()
|
|
100
|
+
finally:
|
|
101
|
+
response.close()
|
|
102
|
+
except urllib.error.HTTPError as error:
|
|
103
|
+
if allow_404 and error.code == 404:
|
|
104
|
+
return None
|
|
105
|
+
raise SpecStreamError(_error_message(error)) from None
|
|
106
|
+
except urllib.error.URLError as error:
|
|
107
|
+
raise SpecStreamError(f"Couldn't reach SpecStream: {error.reason}") from None
|
|
108
|
+
try:
|
|
109
|
+
payload = json.loads(raw or b"{}")
|
|
110
|
+
except ValueError:
|
|
111
|
+
payload = None
|
|
112
|
+
if not isinstance(payload, dict) or not isinstance(payload.get("data"), dict):
|
|
113
|
+
raise SpecStreamError("SpecStream returned a response this package couldn't read.")
|
|
114
|
+
return payload["data"]
|
|
115
|
+
|
|
116
|
+
def web_search(
|
|
117
|
+
self,
|
|
118
|
+
q: str,
|
|
119
|
+
*,
|
|
120
|
+
passages: bool = False,
|
|
121
|
+
speed: str = "default",
|
|
122
|
+
num: int | None = None,
|
|
123
|
+
news: bool = False,
|
|
124
|
+
country: str | None = None,
|
|
125
|
+
language: str | None = None,
|
|
126
|
+
) -> dict[str, Any]:
|
|
127
|
+
"""GET /v1/web-search: $5 per 1,000 searches of up to 10 results, $1 per 1,000 with speed="fast"."""
|
|
128
|
+
query = (q or "").strip()
|
|
129
|
+
if not query or len(query) > 2000:
|
|
130
|
+
raise ValueError("q must be between 1 and 2,000 characters.")
|
|
131
|
+
if speed not in SPEEDS:
|
|
132
|
+
raise ValueError('speed must be "default" or "fast".')
|
|
133
|
+
params: dict[str, str] = {"q": query}
|
|
134
|
+
if passages:
|
|
135
|
+
params["passages"] = "true"
|
|
136
|
+
if speed != "default":
|
|
137
|
+
params["speed"] = speed
|
|
138
|
+
if num is not None:
|
|
139
|
+
if not 1 <= int(num) <= 200:
|
|
140
|
+
raise ValueError("num must be between 1 and 200.")
|
|
141
|
+
params["num"] = str(int(num))
|
|
142
|
+
if news:
|
|
143
|
+
params["news"] = "true"
|
|
144
|
+
if country:
|
|
145
|
+
params["country"] = country
|
|
146
|
+
if language:
|
|
147
|
+
params["language"] = language
|
|
148
|
+
return self.request("GET", f"/v1/web-search?{urllib.parse.urlencode(params)}") or {}
|
|
149
|
+
|
|
150
|
+
def extract_pages(self, urls: list[str], *, format: str = "markdown") -> dict[str, Any]:
|
|
151
|
+
"""POST /v1/extract: the main text of 1 to 20 URLs, $0.80 per 1,000 pages; a page with no text is free."""
|
|
152
|
+
cleaned = [str(u or "").strip() for u in (urls or []) if str(u or "").strip()]
|
|
153
|
+
if not 1 <= len(cleaned) <= 20:
|
|
154
|
+
raise ValueError("Provide 1 to 20 http or https URLs.")
|
|
155
|
+
fmt = "text" if format == "text" else "markdown"
|
|
156
|
+
return self.request("POST", "/v1/extract", {"urls": cleaned, "format": fmt}) or {}
|
|
157
|
+
|
|
158
|
+
def results(self, find_id: str) -> dict[str, Any]:
|
|
159
|
+
"""Every row found so far for a list, following the pages."""
|
|
160
|
+
rows: list[dict[str, Any]] = []
|
|
161
|
+
cursor: str | None = None
|
|
162
|
+
status = "running"
|
|
163
|
+
while True:
|
|
164
|
+
query = {"limit": "100", **({"cursor": cursor} if cursor else {})}
|
|
165
|
+
page = self.request("GET", f"/v1/finds/{urllib.parse.quote(find_id, safe='')}/rows?{urllib.parse.urlencode(query)}") or {}
|
|
166
|
+
status = page.get("status") or status
|
|
167
|
+
flat = {str(item.get("id")): item for item in page.get("flat_rows") or []}
|
|
168
|
+
rows.extend(
|
|
169
|
+
flatten_row(find_id, record, flat.get(f"{find_id}:{record.get('entity_id')}")) for record in page.get("rows") or []
|
|
170
|
+
)
|
|
171
|
+
cursor = page.get("next_cursor")
|
|
172
|
+
if not cursor:
|
|
173
|
+
break
|
|
174
|
+
return {"list_id": find_id, "status": status, "list_link": list_link(find_id), "row_count": len(rows), "rows": rows}
|
|
175
|
+
|
|
176
|
+
def find_list(
|
|
177
|
+
self,
|
|
178
|
+
request: str,
|
|
179
|
+
*,
|
|
180
|
+
max_results: int,
|
|
181
|
+
max_price_usd: float,
|
|
182
|
+
idempotency_key: str,
|
|
183
|
+
wait_seconds: float = DEFAULT_WAIT_SECONDS,
|
|
184
|
+
poll_interval: float = 5.0,
|
|
185
|
+
locale: str = "en-US",
|
|
186
|
+
) -> dict[str, Any]:
|
|
187
|
+
"""A Deep Search list. The same idempotency_key returns the run it already started, so a retried
|
|
188
|
+
task never buys the list twice. Nothing runs when the quote is above max_price_usd."""
|
|
189
|
+
q = (request or "").strip()
|
|
190
|
+
if not q:
|
|
191
|
+
raise ValueError("Describe the list to find.")
|
|
192
|
+
if not isinstance(max_results, int) or max_results < 1:
|
|
193
|
+
raise ValueError("max_results must be 1 or more.")
|
|
194
|
+
max_cents = round(float(max_price_usd) * 100)
|
|
195
|
+
if max_cents <= 0:
|
|
196
|
+
raise ValueError("max_price_usd must be greater than 0.")
|
|
197
|
+
if not idempotency_key:
|
|
198
|
+
raise ValueError("idempotency_key is required.")
|
|
199
|
+
|
|
200
|
+
existing = self.request("GET", f"/v1/capacity/requests/{urllib.parse.quote(idempotency_key, safe='')}", allow_404=True)
|
|
201
|
+
if existing and existing.get("find_id"):
|
|
202
|
+
find_id = existing["find_id"]
|
|
203
|
+
maximum_cents = int(existing.get("maximum_cents") or max_cents)
|
|
204
|
+
else:
|
|
205
|
+
reading = self.request("POST", "/v1/parse", {"q": q, "locale": locale}) or {}
|
|
206
|
+
if reading.get("status") != "runnable":
|
|
207
|
+
read_as = reading.get("canonical_sentence") or q
|
|
208
|
+
return {
|
|
209
|
+
"status": "needs_edit",
|
|
210
|
+
"request": q,
|
|
211
|
+
"message": f'SpecStream needs a clearer request before it can price it. It read: "{read_as}". Add the place or what every row must meet.',
|
|
212
|
+
}
|
|
213
|
+
quote = (
|
|
214
|
+
self.request("POST", "/v1/capacity/quotes", {"ast_hash": reading["ast_hash"], "operation": "find", "requested_units": max_results})
|
|
215
|
+
or {}
|
|
216
|
+
)
|
|
217
|
+
maximum_cents = int(quote.get("maximum_cents") or 0)
|
|
218
|
+
if maximum_cents > max_cents:
|
|
219
|
+
return {
|
|
220
|
+
"status": "over_maximum",
|
|
221
|
+
"request": q,
|
|
222
|
+
"maximum_price_usd": maximum_cents / 100,
|
|
223
|
+
"message": f"Nothing ran: this list can cost up to {_dollars(maximum_cents)}, above the maximum of {_dollars(max_cents)}. Ask for fewer results or raise max_price_usd.",
|
|
224
|
+
}
|
|
225
|
+
run = (
|
|
226
|
+
self.request(
|
|
227
|
+
"POST",
|
|
228
|
+
"/v1/capacity/executions",
|
|
229
|
+
{
|
|
230
|
+
"quote_id": quote["quote_id"],
|
|
231
|
+
"quote_hash": quote["quote_hash"],
|
|
232
|
+
"confirm_max_cents": maximum_cents,
|
|
233
|
+
"idempotency_key": idempotency_key,
|
|
234
|
+
},
|
|
235
|
+
)
|
|
236
|
+
or {}
|
|
237
|
+
)
|
|
238
|
+
find_id = run["find_id"]
|
|
239
|
+
|
|
240
|
+
deadline = self.clock() + max(0.0, wait_seconds)
|
|
241
|
+
while True:
|
|
242
|
+
result = self.results(find_id)
|
|
243
|
+
if result["status"] in FINISHED | STOPPED or self.clock() >= deadline:
|
|
244
|
+
break
|
|
245
|
+
self.sleep(poll_interval)
|
|
246
|
+
result.update({"request": q, "maximum_price_usd": maximum_cents / 100})
|
|
247
|
+
if result["status"] not in FINISHED | STOPPED:
|
|
248
|
+
result["message"] = "Still running. A retry of this task continues the same list; open list_link to see it."
|
|
249
|
+
return result
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _error_message(error: urllib.error.HTTPError) -> str:
|
|
253
|
+
try:
|
|
254
|
+
payload = json.loads(error.read() or b"{}")
|
|
255
|
+
except ValueError:
|
|
256
|
+
payload = {}
|
|
257
|
+
detail = payload.get("error") if isinstance(payload, dict) else None
|
|
258
|
+
message = detail.get("message") if isinstance(detail, dict) else detail if isinstance(detail, str) else None
|
|
259
|
+
return f"SpecStream answered {error.code}: {message or error.reason}"
|
|
File without changes
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""The SpecStream resource: the Search API, the Extract API and Deep Search for Dagster assets and ops."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from dagster import ConfigurableResource, Failure, MetadataValue, RetryRequested
|
|
9
|
+
from pydantic import Field
|
|
10
|
+
|
|
11
|
+
from dagster_specstream._api import DEFAULT_BASE_URL, DEFAULT_WAIT_SECONDS, FINISHED, STOPPED, SpecStreamAPI
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def run_key(context: Any, name: str | None = None) -> str:
|
|
15
|
+
"""An idempotency key for a Deep Search list started from this step.
|
|
16
|
+
|
|
17
|
+
It stays the same when the step is retried and when the run is re-executed (it uses the first
|
|
18
|
+
run's id), so the list is bought once. A partitioned asset gets one key per partition.
|
|
19
|
+
"""
|
|
20
|
+
run = getattr(context, "run", None)
|
|
21
|
+
run_id = (getattr(run, "root_run_id", None) or getattr(run, "run_id", None) or "").strip()
|
|
22
|
+
if not run_id:
|
|
23
|
+
raise ValueError("Give deep_search an idempotency_key: this context has no run id.")
|
|
24
|
+
step = name
|
|
25
|
+
if step is None:
|
|
26
|
+
try:
|
|
27
|
+
step = context.asset_key.to_user_string()
|
|
28
|
+
except Exception: # an op, or an asset with more than one output
|
|
29
|
+
step = getattr(getattr(context, "op_def", None), "name", None) or "step"
|
|
30
|
+
partition = ""
|
|
31
|
+
if getattr(context, "has_partition_key", False):
|
|
32
|
+
partition = str(context.partition_key)
|
|
33
|
+
digest = hashlib.sha256(f"{run_id}|{step}|{partition}".encode()).hexdigest()[:32]
|
|
34
|
+
return f"dagster-{digest}"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class SpecStreamResource(ConfigurableResource):
|
|
38
|
+
"""Calls the SpecStream API with your key.
|
|
39
|
+
|
|
40
|
+
Example:
|
|
41
|
+
resources={"specstream": SpecStreamResource(api_key=EnvVar("SPECSTREAM_API_KEY"))}
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
api_key: str = Field(description="Your SpecStream API key (Agents & API in your SpecStream workspace).")
|
|
45
|
+
base_url: str = Field(default=DEFAULT_BASE_URL, description="The API address. Change it only for a proxy.")
|
|
46
|
+
timeout: float = Field(default=150.0, description="Seconds to wait for one API call.")
|
|
47
|
+
|
|
48
|
+
def get_client(self) -> SpecStreamAPI:
|
|
49
|
+
return SpecStreamAPI(api_key=self.api_key, base_url=self.base_url or DEFAULT_BASE_URL, timeout=self.timeout)
|
|
50
|
+
|
|
51
|
+
def web_search(
|
|
52
|
+
self,
|
|
53
|
+
query: str,
|
|
54
|
+
*,
|
|
55
|
+
passages: bool = False,
|
|
56
|
+
speed: str = "default",
|
|
57
|
+
num: int | None = None,
|
|
58
|
+
news: bool = False,
|
|
59
|
+
country: str | None = None,
|
|
60
|
+
language: str | None = None,
|
|
61
|
+
) -> dict[str, Any]:
|
|
62
|
+
"""Search API, GET /v1/web-search: the answer, rows and ranked sources.
|
|
63
|
+
|
|
64
|
+
$5 per 1,000 searches of up to 10 results; $1 per 1,000 with speed="fast".
|
|
65
|
+
"""
|
|
66
|
+
return self.get_client().web_search(
|
|
67
|
+
query, passages=passages, speed=speed, num=num, news=news, country=country, language=language
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def extract_pages(self, urls: str | list[str], *, format: str = "markdown") -> dict[str, Any]:
|
|
71
|
+
"""Extract API, POST /v1/extract: the main text of 1 to 20 pages.
|
|
72
|
+
|
|
73
|
+
$0.80 per 1,000 pages; a page with no text is not charged.
|
|
74
|
+
"""
|
|
75
|
+
if isinstance(urls, str):
|
|
76
|
+
urls = [urls]
|
|
77
|
+
return self.get_client().extract_pages(list(urls), format=format)
|
|
78
|
+
|
|
79
|
+
def find_list(self, request: str, **kwargs: Any) -> dict[str, Any]:
|
|
80
|
+
"""Deep Search without Dagster's handling: returns every status, including needs_edit and over_maximum."""
|
|
81
|
+
return self.get_client().find_list(request, **kwargs)
|
|
82
|
+
|
|
83
|
+
def deep_search(
|
|
84
|
+
self,
|
|
85
|
+
context: Any,
|
|
86
|
+
request: str,
|
|
87
|
+
*,
|
|
88
|
+
max_results: int,
|
|
89
|
+
max_price_usd: float,
|
|
90
|
+
idempotency_key: str | None = None,
|
|
91
|
+
wait_seconds: float = DEFAULT_WAIT_SECONDS,
|
|
92
|
+
poll_interval: float = 5.0,
|
|
93
|
+
locale: str = "en-US",
|
|
94
|
+
retries_while_running: int = 3,
|
|
95
|
+
seconds_between_retries: float = 60.0,
|
|
96
|
+
) -> dict[str, Any]:
|
|
97
|
+
"""Deep Search: a list built from the live web, in structured rows. 5 cents, 15 cents or $1 per delivered row.
|
|
98
|
+
|
|
99
|
+
Nothing runs when the quoted maximum is above max_price_usd: the step fails with the price.
|
|
100
|
+
A retry or a re-execution of the same step continues the same list and never buys it twice.
|
|
101
|
+
When the list is still running after wait_seconds, the step asks Dagster to retry it
|
|
102
|
+
(retries_while_running times), and the retry picks the list up.
|
|
103
|
+
"""
|
|
104
|
+
key = idempotency_key or run_key(context)
|
|
105
|
+
result = self.get_client().find_list(
|
|
106
|
+
request,
|
|
107
|
+
max_results=max_results,
|
|
108
|
+
max_price_usd=max_price_usd,
|
|
109
|
+
idempotency_key=key,
|
|
110
|
+
wait_seconds=wait_seconds,
|
|
111
|
+
poll_interval=poll_interval,
|
|
112
|
+
locale=locale,
|
|
113
|
+
)
|
|
114
|
+
status = result.get("status")
|
|
115
|
+
if status in {"needs_edit", "over_maximum"}:
|
|
116
|
+
raise Failure(description=result["message"], allow_retries=False)
|
|
117
|
+
link = result.get("list_link") or ""
|
|
118
|
+
if status in STOPPED:
|
|
119
|
+
raise Failure(
|
|
120
|
+
description=f"The list {link} stopped with status {status}.",
|
|
121
|
+
metadata={"list_link": MetadataValue.url(link)} if link else None,
|
|
122
|
+
)
|
|
123
|
+
if status not in FINISHED:
|
|
124
|
+
raise RetryRequested(max_retries=retries_while_running, seconds_to_wait=seconds_between_retries)
|
|
125
|
+
log = getattr(context, "log", None)
|
|
126
|
+
if log is not None:
|
|
127
|
+
log.info(f"SpecStream list {result.get('list_id')}: {result.get('row_count')} rows ({status}) {link}")
|
|
128
|
+
return result
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "dagster-specstream"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "SpecStream for Dagster: the live web data engine. A resource for the Search API, the Extract API and Deep Search."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [{ name = "SpecStream", email = "support@specstream.ai" }]
|
|
10
|
+
keywords = ["dagster", "dagster-integration", "specstream", "web-search", "web-data", "live-web", "extract", "etl"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 4 - Beta",
|
|
13
|
+
"Intended Audience :: Developers",
|
|
14
|
+
"Operating System :: OS Independent",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
17
|
+
"Programming Language :: Python :: 3.10",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
]
|
|
23
|
+
dependencies = ["dagster>=1.8"]
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
test = ["pytest>=8"]
|
|
27
|
+
|
|
28
|
+
[dependency-groups]
|
|
29
|
+
dev = ["pytest>=8"]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://specstream.ai"
|
|
33
|
+
Documentation = "https://specstream.ai/docs"
|
|
34
|
+
Repository = "https://github.com/specstream/specstream-tools/tree/main/packages/dagster-specstream"
|
|
35
|
+
Issues = "https://github.com/specstream/specstream-tools/issues"
|
|
36
|
+
Pricing = "https://specstream.ai/pricing"
|
|
37
|
+
|
|
38
|
+
[build-system]
|
|
39
|
+
requires = ["hatchling>=1.27,<2"]
|
|
40
|
+
build-backend = "hatchling.build"
|
|
41
|
+
|
|
42
|
+
[tool.hatch.build.targets.wheel]
|
|
43
|
+
packages = ["dagster_specstream"]
|
|
44
|
+
|
|
45
|
+
[tool.hatch.build.targets.sdist]
|
|
46
|
+
include = ["dagster_specstream", "tests", "README.md", "LICENSE"]
|
|
47
|
+
|
|
48
|
+
[tool.pytest.ini_options]
|
|
49
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
import urllib.error
|
|
4
|
+
import urllib.parse
|
|
5
|
+
from types import SimpleNamespace
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from dagster import (
|
|
9
|
+
AssetExecutionContext,
|
|
10
|
+
Definitions,
|
|
11
|
+
EnvVar,
|
|
12
|
+
Failure,
|
|
13
|
+
RetryRequested,
|
|
14
|
+
StaticPartitionsDefinition,
|
|
15
|
+
asset,
|
|
16
|
+
build_asset_context,
|
|
17
|
+
materialize,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
from dagster_specstream import SpecStreamError, SpecStreamResource, _api, run_key
|
|
21
|
+
|
|
22
|
+
FIND_ID = "fnd_test123"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class FakeAPI:
|
|
26
|
+
"""Stands in for the network: answers each call by its method and path, and records it."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, routes):
|
|
29
|
+
self.routes = routes
|
|
30
|
+
self.requests = []
|
|
31
|
+
|
|
32
|
+
def __call__(self, request, timeout):
|
|
33
|
+
self.requests.append(request)
|
|
34
|
+
url = urllib.parse.urlparse(request.full_url)
|
|
35
|
+
for (method, prefix), reply in self.routes.items():
|
|
36
|
+
if request.get_method() == method and url.path.startswith(prefix):
|
|
37
|
+
if callable(reply):
|
|
38
|
+
reply = reply(request)
|
|
39
|
+
if isinstance(reply, Exception):
|
|
40
|
+
raise reply
|
|
41
|
+
return io.BytesIO(json.dumps({"data": reply}).encode())
|
|
42
|
+
raise AssertionError(f"unexpected call {request.get_method()} {url.path}")
|
|
43
|
+
|
|
44
|
+
def calls(self, method, prefix):
|
|
45
|
+
return [r for r in self.requests if r.get_method() == method and urllib.parse.urlparse(r.full_url).path.startswith(prefix)]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _not_found(request):
|
|
49
|
+
return urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, io.BytesIO(b"{}"))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _rows(status="completed"):
|
|
53
|
+
return {
|
|
54
|
+
"status": status,
|
|
55
|
+
"rows": [{"ordinal": 1, "entity_id": "e1", "details": [{"label": "name", "value": "Dagster"}]}],
|
|
56
|
+
"flat_rows": [{"id": f"{FIND_ID}:e1", "source_url": "https://dagster.io", "checked_at": "2026-11-12T10:00:00Z"}],
|
|
57
|
+
"next_cursor": None,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _deep_routes(status="completed", quote_cents=250):
|
|
62
|
+
return {
|
|
63
|
+
("GET", "/v1/capacity/requests/"): _not_found,
|
|
64
|
+
("POST", "/v1/parse"): {"status": "runnable", "ast_hash": "h1"},
|
|
65
|
+
("POST", "/v1/capacity/quotes"): {"quote_id": "q1", "quote_hash": "qh", "maximum_cents": quote_cents},
|
|
66
|
+
("POST", "/v1/capacity/executions"): {"find_id": FIND_ID},
|
|
67
|
+
("GET", f"/v1/finds/{FIND_ID}/rows"): _rows(status),
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@pytest.fixture
|
|
72
|
+
def fake(monkeypatch):
|
|
73
|
+
def install(routes):
|
|
74
|
+
api = FakeAPI(routes)
|
|
75
|
+
monkeypatch.setattr(_api, "_urlopen", api)
|
|
76
|
+
return api
|
|
77
|
+
|
|
78
|
+
return install
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_web_search_sends_query_speed_key_and_user_agent(fake):
|
|
82
|
+
api = fake({("GET", "/v1/web-search"): {"query": "q", "sources": [{"url": "https://a.example"}]}})
|
|
83
|
+
out = SpecStreamResource(api_key="ss_test").web_search("dagster release", speed="fast", num=5)
|
|
84
|
+
assert out["sources"][0]["url"] == "https://a.example"
|
|
85
|
+
request = api.requests[0]
|
|
86
|
+
url = urllib.parse.urlparse(request.full_url)
|
|
87
|
+
assert (url.netloc, url.path) == ("api.specstream.ai", "/v1/web-search")
|
|
88
|
+
assert urllib.parse.parse_qs(url.query) == {"q": ["dagster release"], "speed": ["fast"], "num": ["5"]}
|
|
89
|
+
assert request.get_header("Authorization") == "Bearer ss_test"
|
|
90
|
+
assert request.get_header("User-agent") == "dagster-specstream/0.1.0"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_extract_takes_one_url_or_a_list(fake):
|
|
94
|
+
api = fake({("POST", "/v1/extract"): {"pages": []}})
|
|
95
|
+
resource = SpecStreamResource(api_key="ss_test", base_url="http://localhost:9000/")
|
|
96
|
+
resource.extract_pages("https://dagster.io")
|
|
97
|
+
resource.extract_pages(["https://a.example", "https://b.example"], format="text")
|
|
98
|
+
bodies = [json.loads(r.data) for r in api.requests]
|
|
99
|
+
assert bodies == [
|
|
100
|
+
{"urls": ["https://dagster.io"], "format": "markdown"},
|
|
101
|
+
{"urls": ["https://a.example", "https://b.example"], "format": "text"},
|
|
102
|
+
]
|
|
103
|
+
assert api.requests[0].full_url == "http://localhost:9000/v1/extract"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_bad_input_and_missing_key_fail_without_a_call(fake):
|
|
107
|
+
api = fake({})
|
|
108
|
+
with pytest.raises(ValueError, match="speed"):
|
|
109
|
+
SpecStreamResource(api_key="ss_test").web_search("x", speed="turbo")
|
|
110
|
+
with pytest.raises(SpecStreamError, match="no API key"):
|
|
111
|
+
SpecStreamResource(api_key=" ").web_search("x")
|
|
112
|
+
assert api.requests == []
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_api_error_carries_the_message(fake):
|
|
116
|
+
def refused(request):
|
|
117
|
+
return urllib.error.HTTPError(request.full_url, 401, "Unauthorized", {}, io.BytesIO(b'{"error": {"message": "Invalid API key"}}'))
|
|
118
|
+
|
|
119
|
+
fake({("GET", "/v1/web-search"): refused})
|
|
120
|
+
with pytest.raises(SpecStreamError, match="401: Invalid API key"):
|
|
121
|
+
SpecStreamResource(api_key="ss_bad").web_search("x")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def test_asset_runs_a_deep_search_with_the_run_key(fake, monkeypatch):
|
|
125
|
+
api = fake(_deep_routes())
|
|
126
|
+
monkeypatch.setenv("SPECSTREAM_API_KEY", "ss_env")
|
|
127
|
+
|
|
128
|
+
@asset
|
|
129
|
+
def orchestrators(context: AssetExecutionContext, specstream: SpecStreamResource) -> list:
|
|
130
|
+
return specstream.deep_search(context, "Open-source workflow orchestrators", max_results=10, max_price_usd=5)["rows"]
|
|
131
|
+
|
|
132
|
+
defs = Definitions(assets=[orchestrators], resources={"specstream": SpecStreamResource(api_key=EnvVar("SPECSTREAM_API_KEY"))})
|
|
133
|
+
result = materialize([orchestrators], resources=defs.resources)
|
|
134
|
+
assert result.success
|
|
135
|
+
rows = result.output_for_node("orchestrators")
|
|
136
|
+
assert rows[0]["name"] == "Dagster"
|
|
137
|
+
assert rows[0]["source_url"] == "https://dagster.io"
|
|
138
|
+
assert rows[0]["list_link"].endswith(FIND_ID)
|
|
139
|
+
execution = json.loads(api.calls("POST", "/v1/capacity/executions")[0].data)
|
|
140
|
+
assert execution["confirm_max_cents"] == 250
|
|
141
|
+
assert execution["idempotency_key"].startswith("dagster-")
|
|
142
|
+
assert all(r.get_header("Authorization") == "Bearer ss_env" for r in api.requests)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def test_over_the_maximum_nothing_runs_and_the_step_fails_once(fake):
|
|
146
|
+
api = fake(_deep_routes(quote_cents=900))
|
|
147
|
+
with pytest.raises(Failure, match=r"up to \$9.00, above the maximum of \$5.00") as caught:
|
|
148
|
+
SpecStreamResource(api_key="ss_test").deep_search(build_asset_context(), "x", max_results=10, max_price_usd=5, idempotency_key="k1")
|
|
149
|
+
assert caught.value.allow_retries is False
|
|
150
|
+
assert api.calls("POST", "/v1/capacity/executions") == []
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def test_a_retry_continues_the_list_it_already_started(fake):
|
|
154
|
+
routes = _deep_routes()
|
|
155
|
+
routes[("GET", "/v1/capacity/requests/")] = {"find_id": FIND_ID, "maximum_cents": 250}
|
|
156
|
+
api = fake(routes)
|
|
157
|
+
out = SpecStreamResource(api_key="ss_test").deep_search(build_asset_context(), "x", max_results=10, max_price_usd=5, idempotency_key="k1")
|
|
158
|
+
assert out["row_count"] == 1
|
|
159
|
+
assert api.calls("POST", "/v1/parse") == []
|
|
160
|
+
assert api.calls("POST", "/v1/capacity/executions") == []
|
|
161
|
+
assert api.calls("GET", "/v1/capacity/requests/")[0].full_url.endswith("/v1/capacity/requests/k1")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def test_a_list_still_running_asks_dagster_to_retry(fake):
|
|
165
|
+
fake(_deep_routes(status="running"))
|
|
166
|
+
with pytest.raises(RetryRequested) as caught:
|
|
167
|
+
SpecStreamResource(api_key="ss_test").deep_search(
|
|
168
|
+
build_asset_context(), "x", max_results=10, max_price_usd=5, idempotency_key="k1", wait_seconds=0, retries_while_running=4
|
|
169
|
+
)
|
|
170
|
+
assert caught.value.max_retries == 4
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def test_a_stopped_list_fails_with_its_link(fake):
|
|
174
|
+
fake(_deep_routes(status="failed"))
|
|
175
|
+
with pytest.raises(Failure, match=f"{FIND_ID} stopped with status failed"):
|
|
176
|
+
SpecStreamResource(api_key="ss_test").deep_search(build_asset_context(), "x", max_results=10, max_price_usd=5, idempotency_key="k1")
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def test_run_key_holds_across_re_execution_and_splits_by_partition_and_step():
|
|
180
|
+
first = SimpleNamespace(run=SimpleNamespace(root_run_id=None, run_id="run-1"), asset_key=SimpleNamespace(to_user_string=lambda: "a"))
|
|
181
|
+
again = SimpleNamespace(run=SimpleNamespace(root_run_id="run-1", run_id="run-2"), asset_key=SimpleNamespace(to_user_string=lambda: "a"))
|
|
182
|
+
assert run_key(first) == run_key(again)
|
|
183
|
+
assert run_key(first) != run_key(first, name="other")
|
|
184
|
+
|
|
185
|
+
us = SimpleNamespace(run=SimpleNamespace(root_run_id="run-1", run_id="run-2"), has_partition_key=True, partition_key="us")
|
|
186
|
+
fr = SimpleNamespace(run=SimpleNamespace(root_run_id="run-1", run_id="run-2"), has_partition_key=True, partition_key="fr")
|
|
187
|
+
assert run_key(us, name="a") != run_key(fr, name="a")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def test_run_key_reads_a_real_partitioned_asset_context():
|
|
191
|
+
seen = []
|
|
192
|
+
|
|
193
|
+
@asset(partitions_def=StaticPartitionsDefinition(["us", "fr"]))
|
|
194
|
+
def regional(context: AssetExecutionContext) -> None:
|
|
195
|
+
seen.append(run_key(context))
|
|
196
|
+
|
|
197
|
+
assert materialize([regional], partition_key="us").success
|
|
198
|
+
assert materialize([regional], partition_key="fr").success
|
|
199
|
+
assert all(key.startswith("dagster-") for key in seen)
|
|
200
|
+
assert len(set(seen)) == 2
|