prefect-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.
@@ -0,0 +1,14 @@
1
+ node_modules/
2
+ dist/
3
+ build/
4
+ *.egg-info/
5
+ __pycache__/
6
+ .venv/
7
+ .pytest_cache/
8
+ *.tsbuildinfo
9
+ *.tgz
10
+ *.whl
11
+ .env
12
+ .env.*
13
+ !.env.example
14
+ .DS_Store
@@ -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,120 @@
1
+ Metadata-Version: 2.5
2
+ Name: prefect-specstream
3
+ Version: 0.1.0
4
+ Summary: The live web data engine for Prefect: Search API ($5 per 1,000 searches of up to 10 results, $1 on the fast tier) and Extract API ($0.80 per 1,000 pages) as Prefect tasks with a credentials block.
5
+ Project-URL: Homepage, https://specstream.ai
6
+ Project-URL: Documentation, https://specstream.ai/docs/api
7
+ Project-URL: Repository, https://github.com/specstream/specstream-tools/tree/main/packages/prefect-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
+ Maintainer-email: SpecStream <support@specstream.ai>
12
+ License-Expression: MIT
13
+ License-File: LICENSE
14
+ Keywords: data-pipelines,deep-research,extract-api,live-web,prefect,prefect-collection,prefect-integration,research,search-api,specstream,web-data,web-search
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Topic :: Internet :: WWW/HTTP
21
+ Classifier: Topic :: System :: Distributed Computing
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: httpx>=0.27
25
+ Requires-Dist: prefect<4,>=3.0
26
+ Provides-Extra: test
27
+ Requires-Dist: pytest>=8; extra == 'test'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # prefect-specstream
31
+
32
+ [SpecStream](https://specstream.ai) is the live web data engine for teams and agents. 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 gives Prefect flows a research report flow, tasks and a credentials block:
39
+
40
+ 1. `web_search`: the Search API, `POST /v1/web-search`, $5 per 1,000 searches of up to 10 results, or $1 per 1,000 on the fast tier (`speed="fast"`).
41
+ 2. `extract_pages`: the Extract API, `POST /v1/extract` (web pages, PDF, Word, Excel), $0.80 per 1,000 pages. A page with no text is not charged.
42
+ 3. `research_report`: a flow that researches a question on the live web and returns a written report in Markdown, with the page behind each cited sentence (`POST /v1/research`). A report costs $0.10 (`quick`), $0.30 (`standard`) or $1.00 (`deep`), charged once, when it is delivered.
43
+ 4. `SpecStreamCredentials`: a Prefect block that holds the API key.
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pip install prefect-specstream
49
+ prefect block register -m prefect_specstream
50
+ ```
51
+
52
+ A free account comes with $10 of credit and needs no card: [specstream.ai](https://specstream.ai/signup). Create a key under Agents & API in your SpecStream workspace.
53
+
54
+ ## Save the key once
55
+
56
+ ```python
57
+ from prefect_specstream import SpecStreamCredentials
58
+
59
+ SpecStreamCredentials(api_key="ss_live_...").save("specstream")
60
+ ```
61
+
62
+ Without an `api_key`, the block reads `SPECSTREAM_API_KEY` from the environment.
63
+
64
+ ## Use it in a flow
65
+
66
+ ```python
67
+ from prefect import flow
68
+ from prefect_specstream import SpecStreamCredentials, extract_pages, web_search
69
+
70
+
71
+ @flow
72
+ def read_the_web(question: str):
73
+ credentials = SpecStreamCredentials.load("specstream")
74
+ found = web_search(question, credentials)
75
+ urls = [source["url"] for source in found["sources"][:3]]
76
+ pages = extract_pages(urls, credentials)
77
+ return found, pages
78
+ ```
79
+
80
+ | Task | Arguments | Returns |
81
+ | --- | --- | --- |
82
+ | `web_search` | `query`, `specstream_credentials`, `speed` (`"default"` or `"fast"`), `num`, `passages` | The `data` object of the reply: `sources`, and on the default speed `answer` and `rows` |
83
+ | `extract_pages` | `urls`, `specstream_credentials`, `format` (`"markdown"` or `"text"`) | `{"results": [...]}`, one result per URL. Lists longer than 20 URLs are sent in calls of 20. |
84
+
85
+ ## Get a written report
86
+
87
+ ```python
88
+ from prefect import flow
89
+ from prefect_specstream import SpecStreamCredentials, research_report
90
+
91
+
92
+ @flow
93
+ def weekly_brief():
94
+ credentials = SpecStreamCredentials.load("specstream")
95
+ report = research_report(
96
+ "How do the EU and the US regulate stablecoin reserves in 2026?",
97
+ credentials,
98
+ depth="quick",
99
+ )
100
+ print(report["content"]) # the report in Markdown, with numbered citations
101
+ return report["citations"] # each cited sentence's page, read time and excerpt
102
+ ```
103
+
104
+ `research_report` starts one report, waits until it is written (one to five minutes) and returns `research_id`, `depth`, `price_usd`, `title`, `content`, `citations` and `sources`. You set `depth` in code, so the price of a run is fixed before it starts. A retry in the same hour with the same question and depth returns the report that was already started; it is not bought twice.
105
+
106
+ To start a report in one flow and read it in another, use the tasks:
107
+
108
+ | Task | Arguments | Returns |
109
+ | --- | --- | --- |
110
+ | `start_research` | `question`, `specstream_credentials`, `depth` (`"quick"`, `"standard"` or `"deep"`), `options` | The run, with its `id`, `status` and `price_usd` |
111
+ | `get_research` | `research_id`, `specstream_credentials` | The run, with `report` when it is completed. Costs nothing. |
112
+ | `wait_for_research` | `research_id`, `specstream_credentials`, `wait_seconds`, `poll_seconds` | The completed run. Raises `SpecStreamError` when the run fails or is still running after `wait_seconds`. |
113
+
114
+ A refused call raises `SpecStreamError` with the API's message and `status_code`. The tasks do not retry on their own; add retries with `web_search.with_options(retries=2)`.
115
+
116
+ API reference: https://specstream.ai/docs/api
117
+
118
+ ## License
119
+
120
+ MIT
@@ -0,0 +1,91 @@
1
+ # prefect-specstream
2
+
3
+ [SpecStream](https://specstream.ai) is the live web data engine for teams and agents. 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 gives Prefect flows a research report flow, tasks and a credentials block:
10
+
11
+ 1. `web_search`: the Search API, `POST /v1/web-search`, $5 per 1,000 searches of up to 10 results, or $1 per 1,000 on the fast tier (`speed="fast"`).
12
+ 2. `extract_pages`: the Extract API, `POST /v1/extract` (web pages, PDF, Word, Excel), $0.80 per 1,000 pages. A page with no text is not charged.
13
+ 3. `research_report`: a flow that researches a question on the live web and returns a written report in Markdown, with the page behind each cited sentence (`POST /v1/research`). A report costs $0.10 (`quick`), $0.30 (`standard`) or $1.00 (`deep`), charged once, when it is delivered.
14
+ 4. `SpecStreamCredentials`: a Prefect block that holds the API key.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install prefect-specstream
20
+ prefect block register -m prefect_specstream
21
+ ```
22
+
23
+ A free account comes with $10 of credit and needs no card: [specstream.ai](https://specstream.ai/signup). Create a key under Agents & API in your SpecStream workspace.
24
+
25
+ ## Save the key once
26
+
27
+ ```python
28
+ from prefect_specstream import SpecStreamCredentials
29
+
30
+ SpecStreamCredentials(api_key="ss_live_...").save("specstream")
31
+ ```
32
+
33
+ Without an `api_key`, the block reads `SPECSTREAM_API_KEY` from the environment.
34
+
35
+ ## Use it in a flow
36
+
37
+ ```python
38
+ from prefect import flow
39
+ from prefect_specstream import SpecStreamCredentials, extract_pages, web_search
40
+
41
+
42
+ @flow
43
+ def read_the_web(question: str):
44
+ credentials = SpecStreamCredentials.load("specstream")
45
+ found = web_search(question, credentials)
46
+ urls = [source["url"] for source in found["sources"][:3]]
47
+ pages = extract_pages(urls, credentials)
48
+ return found, pages
49
+ ```
50
+
51
+ | Task | Arguments | Returns |
52
+ | --- | --- | --- |
53
+ | `web_search` | `query`, `specstream_credentials`, `speed` (`"default"` or `"fast"`), `num`, `passages` | The `data` object of the reply: `sources`, and on the default speed `answer` and `rows` |
54
+ | `extract_pages` | `urls`, `specstream_credentials`, `format` (`"markdown"` or `"text"`) | `{"results": [...]}`, one result per URL. Lists longer than 20 URLs are sent in calls of 20. |
55
+
56
+ ## Get a written report
57
+
58
+ ```python
59
+ from prefect import flow
60
+ from prefect_specstream import SpecStreamCredentials, research_report
61
+
62
+
63
+ @flow
64
+ def weekly_brief():
65
+ credentials = SpecStreamCredentials.load("specstream")
66
+ report = research_report(
67
+ "How do the EU and the US regulate stablecoin reserves in 2026?",
68
+ credentials,
69
+ depth="quick",
70
+ )
71
+ print(report["content"]) # the report in Markdown, with numbered citations
72
+ return report["citations"] # each cited sentence's page, read time and excerpt
73
+ ```
74
+
75
+ `research_report` starts one report, waits until it is written (one to five minutes) and returns `research_id`, `depth`, `price_usd`, `title`, `content`, `citations` and `sources`. You set `depth` in code, so the price of a run is fixed before it starts. A retry in the same hour with the same question and depth returns the report that was already started; it is not bought twice.
76
+
77
+ To start a report in one flow and read it in another, use the tasks:
78
+
79
+ | Task | Arguments | Returns |
80
+ | --- | --- | --- |
81
+ | `start_research` | `question`, `specstream_credentials`, `depth` (`"quick"`, `"standard"` or `"deep"`), `options` | The run, with its `id`, `status` and `price_usd` |
82
+ | `get_research` | `research_id`, `specstream_credentials` | The run, with `report` when it is completed. Costs nothing. |
83
+ | `wait_for_research` | `research_id`, `specstream_credentials`, `wait_seconds`, `poll_seconds` | The completed run. Raises `SpecStreamError` when the run fails or is still running after `wait_seconds`. |
84
+
85
+ A refused call raises `SpecStreamError` with the API's message and `status_code`. The tasks do not retry on their own; add retries with `web_search.with_options(retries=2)`.
86
+
87
+ API reference: https://specstream.ai/docs/api
88
+
89
+ ## License
90
+
91
+ MIT
@@ -0,0 +1,19 @@
1
+ """SpecStream as Prefect tasks and a flow: Search API, Extract API and research reports, with a credentials block."""
2
+
3
+ from prefect_specstream._version import __version__
4
+ from prefect_specstream.credentials import SpecStreamClient, SpecStreamCredentials, SpecStreamError
5
+ from prefect_specstream.research import get_research, research_report, start_research, wait_for_research
6
+ from prefect_specstream.tasks import extract_pages, web_search
7
+
8
+ __all__ = [
9
+ "SpecStreamClient",
10
+ "SpecStreamCredentials",
11
+ "SpecStreamError",
12
+ "__version__",
13
+ "extract_pages",
14
+ "get_research",
15
+ "research_report",
16
+ "start_research",
17
+ "wait_for_research",
18
+ "web_search",
19
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,82 @@
1
+ """The SpecStream credentials block and the small HTTP client the tasks share."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ import httpx
9
+ from prefect.blocks.abstract import CredentialsBlock
10
+ from pydantic import Field, SecretStr
11
+
12
+ from prefect_specstream._version import __version__
13
+
14
+ DEFAULT_BASE_URL = "https://api.specstream.ai"
15
+ TIMEOUT_SECONDS = 60.0
16
+ USER_AGENT = f"prefect-specstream/{__version__}"
17
+
18
+
19
+ class SpecStreamError(RuntimeError):
20
+ """A SpecStream call failed. The message is the API error message or the HTTP status.
21
+
22
+ `status_code` is the HTTP status, or None when no request was sent.
23
+ """
24
+
25
+ def __init__(self, message: str, status_code: int | None = None) -> None:
26
+ super().__init__(message)
27
+ self.status_code = status_code
28
+
29
+
30
+ class SpecStreamClient:
31
+ """Calls the SpecStream API with one key. Pass `transport` to replace the network (tests)."""
32
+
33
+ def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, transport: httpx.BaseTransport | None = None) -> None:
34
+ self._api_key = (api_key or "").strip()
35
+ self._base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
36
+ self._transport = transport
37
+
38
+ def call(
39
+ self, method: str, path: str, *, json: dict[str, Any] | None = None, headers: dict[str, str] | None = None
40
+ ) -> dict[str, Any]:
41
+ if not self._api_key:
42
+ raise SpecStreamError("The SpecStream API key is empty. Create a key under Agents & API in your SpecStream workspace.")
43
+ sent = {**(headers or {}), "Authorization": f"Bearer {self._api_key}", "Accept": "application/json", "User-Agent": USER_AGENT}
44
+ with httpx.Client(timeout=TIMEOUT_SECONDS, transport=self._transport) as client:
45
+ response = client.request(method, self._base_url + path, json=json, headers=sent)
46
+ try:
47
+ payload = response.json()
48
+ except ValueError:
49
+ payload = {}
50
+ data = payload.get("data") if isinstance(payload, dict) else None
51
+ error = payload.get("error") if isinstance(payload, dict) else None
52
+ if response.is_error or error or not isinstance(data, dict):
53
+ message = error.get("message") if isinstance(error, dict) else None
54
+ raise SpecStreamError(str(message or f"SpecStream HTTP {response.status_code}"), response.status_code)
55
+ return data
56
+
57
+
58
+ class SpecStreamCredentials(CredentialsBlock):
59
+ """Holds a SpecStream API key for the SpecStream tasks.
60
+
61
+ Example:
62
+ ```python
63
+ from prefect_specstream import SpecStreamCredentials
64
+
65
+ SpecStreamCredentials(api_key="ss_live_...").save("specstream")
66
+ credentials = SpecStreamCredentials.load("specstream")
67
+ ```
68
+ """
69
+
70
+ _block_type_name = "SpecStream Credentials"
71
+ _block_type_slug = "specstream-credentials"
72
+ _documentation_url = "https://specstream.ai/docs/api"
73
+
74
+ api_key: SecretStr = Field(
75
+ default_factory=lambda: SecretStr(os.environ.get("SPECSTREAM_API_KEY", "")),
76
+ description="A SpecStream API key (Agents & API in your SpecStream workspace). Defaults to SPECSTREAM_API_KEY.",
77
+ )
78
+ base_url: str = Field(default=DEFAULT_BASE_URL, description="The SpecStream API address.")
79
+
80
+ def get_client(self, transport: httpx.BaseTransport | None = None) -> SpecStreamClient:
81
+ """A client that calls SpecStream with this key."""
82
+ return SpecStreamClient(self.api_key.get_secret_value(), self.base_url, transport=transport)
File without changes
@@ -0,0 +1,160 @@
1
+ """Research reports as Prefect tasks and one flow: a written answer from the live web, with the
2
+ page behind each cited sentence (`POST /v1/research`)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import hashlib
7
+ import json
8
+ import time
9
+ import urllib.parse
10
+ from typing import Any, Literal
11
+
12
+ from prefect import flow, task
13
+
14
+ from prefect_specstream.credentials import SpecStreamCredentials, SpecStreamError
15
+
16
+ Depth = Literal["quick", "standard", "deep"]
17
+ # What one report costs at each depth, in US dollars. The API's reply (price_usd) is what counts.
18
+ PRICES_USD: dict[str, float] = {"quick": 0.10, "standard": 0.30, "deep": 1.00}
19
+ # A run in one of these states has ended.
20
+ ENDED = frozenset({"completed", "failed", "cancelled", "payment_required"})
21
+ MAX_INPUT_CHARS = 15_000
22
+ # A deep report takes about five minutes, so the default wait is a little longer than that.
23
+ DEFAULT_WAIT_SECONDS = 420.0
24
+ DEFAULT_POLL_SECONDS = 5.0
25
+ _sleep = time.sleep # tests replace this one name, not time.sleep for the whole process
26
+
27
+
28
+ def _path(research_id: str) -> str:
29
+ run_id = (research_id or "").strip()
30
+ if not run_id:
31
+ raise SpecStreamError("Pass the research_id that start_research returned.")
32
+ return "/v1/research/" + urllib.parse.quote(run_id, safe="")
33
+
34
+
35
+ def _idempotency_key(body: dict[str, Any]) -> str:
36
+ # The same question with the same settings in the same hour gets the report it already
37
+ # started, so a retried task never buys the report twice.
38
+ hour = time.strftime("%Y-%m-%dT%H", time.gmtime())
39
+ digest = hashlib.sha256(f"{json.dumps(body, sort_keys=True)}|{hour}".encode()).hexdigest()[:32]
40
+ return f"prefect-research-{digest}"
41
+
42
+
43
+ @task(name="specstream-start-research")
44
+ def start_research(
45
+ question: str,
46
+ specstream_credentials: SpecStreamCredentials,
47
+ depth: Depth = "standard",
48
+ options: dict[str, Any] | None = None,
49
+ ) -> dict[str, Any]:
50
+ """Start a research report (`POST /v1/research`) and return the run, with its `id`.
51
+
52
+ A report costs $0.10 (quick), $0.30 (standard) or $1.00 (deep), charged once, when it is
53
+ delivered. A retry in the same hour with the same question and settings returns the same run.
54
+
55
+ Args:
56
+ question: The question to research, in plain words, 1 to 15,000 characters.
57
+ specstream_credentials: The block that holds the API key.
58
+ depth: "quick", "standard" or "deep".
59
+ options: More fields of the request body, as the API reference names them.
60
+
61
+ Returns:
62
+ The run: `id`, `status`, `depth` and `price_usd`.
63
+ """
64
+ text = (question or "").strip()
65
+ if not text or len(text) > MAX_INPUT_CHARS:
66
+ raise SpecStreamError("Send the question, 1 to 15,000 characters.")
67
+ if depth not in PRICES_USD:
68
+ raise SpecStreamError('depth must be "quick", "standard" or "deep".')
69
+ extra = {key: value for key, value in (options or {}).items() if value not in (None, [], {})}
70
+ body: dict[str, Any] = {**extra, "input": text, "depth": depth}
71
+ return specstream_credentials.get_client().call(
72
+ "POST", "/v1/research", json=body, headers={"Idempotency-Key": _idempotency_key(body)}
73
+ )
74
+
75
+
76
+ @task(name="specstream-get-research")
77
+ def get_research(research_id: str, specstream_credentials: SpecStreamCredentials) -> dict[str, Any]:
78
+ """Read a research run (`GET /v1/research/{id}`). Costs nothing.
79
+
80
+ Returns:
81
+ The run: `status`, and when it is completed `report` with `title`, `content` (Markdown),
82
+ `citations` and `sources`.
83
+ """
84
+ return specstream_credentials.get_client().call("GET", _path(research_id))
85
+
86
+
87
+ @task(name="specstream-wait-for-research")
88
+ def wait_for_research(
89
+ research_id: str,
90
+ specstream_credentials: SpecStreamCredentials,
91
+ wait_seconds: float = DEFAULT_WAIT_SECONDS,
92
+ poll_seconds: float = DEFAULT_POLL_SECONDS,
93
+ ) -> dict[str, Any]:
94
+ """Read a research run until it ends, and return it. Reading costs nothing.
95
+
96
+ Raises:
97
+ SpecStreamError: the run failed, was cancelled, the balance does not hold its price, or
98
+ it is still running after `wait_seconds`. The message carries the research_id, so
99
+ `get_research` can read the run later.
100
+ """
101
+ client = specstream_credentials.get_client()
102
+ path = _path(research_id)
103
+ deadline = time.monotonic() + max(0.0, wait_seconds)
104
+ while True:
105
+ run = client.call("GET", path)
106
+ status = run.get("status")
107
+ if status in ENDED or time.monotonic() >= deadline:
108
+ break
109
+ _sleep(max(0.0, poll_seconds))
110
+ if status == "completed":
111
+ return run
112
+ if status == "payment_required":
113
+ raise SpecStreamError(
114
+ f"The balance does not hold the price of research {research_id}. "
115
+ "Add credit at https://specstream.ai/workspace, then start it again.",
116
+ 402,
117
+ )
118
+ if status in ENDED:
119
+ error = run.get("error")
120
+ detail = error.get("message") if isinstance(error, dict) else error
121
+ raise SpecStreamError(f"Research {research_id} ended as {status}" + (f": {detail}" if detail else "."))
122
+ raise SpecStreamError(
123
+ f"Research {research_id} is still running after {wait_seconds:g} seconds. Read it later with get_research."
124
+ )
125
+
126
+
127
+ @flow(name="specstream-research-report")
128
+ def research_report(
129
+ question: str,
130
+ specstream_credentials: SpecStreamCredentials,
131
+ depth: Depth = "standard",
132
+ wait_seconds: float = DEFAULT_WAIT_SECONDS,
133
+ poll_seconds: float = DEFAULT_POLL_SECONDS,
134
+ options: dict[str, Any] | None = None,
135
+ ) -> dict[str, Any]:
136
+ """Research a question on the live web and return the written report.
137
+
138
+ Use it alone or as a subflow. It starts one report, waits until it is written and returns it.
139
+
140
+ Returns:
141
+ `research_id`, `depth`, `price_usd`, `title`, `content` (the report in Markdown with
142
+ numbered citations), `citations` (each cited sentence's page, read time and excerpt)
143
+ and `sources`.
144
+ """
145
+ started = start_research(question, specstream_credentials, depth=depth, options=options)
146
+ research_id = str(started.get("id") or "")
147
+ run = wait_for_research(research_id, specstream_credentials, wait_seconds=wait_seconds, poll_seconds=poll_seconds)
148
+ report = run.get("report") if isinstance(run.get("report"), dict) else {}
149
+ result: dict[str, Any] = {
150
+ "research_id": research_id,
151
+ "depth": run.get("depth") or depth,
152
+ "price_usd": run.get("price_usd", started.get("price_usd")),
153
+ "title": report.get("title") or "",
154
+ "content": report.get("content") or "",
155
+ "citations": report.get("citations") or [],
156
+ "sources": report.get("sources") or [],
157
+ }
158
+ if report.get("structured") is not None:
159
+ result["structured"] = report["structured"]
160
+ return result
@@ -0,0 +1,77 @@
1
+ """Prefect tasks for the SpecStream Search API and Extract API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal
6
+
7
+ from prefect import task
8
+
9
+ from prefect_specstream.credentials import SpecStreamCredentials, SpecStreamError
10
+
11
+ MAX_QUERY_CHARS = 2000
12
+ MAX_EXTRACT_URLS = 20
13
+
14
+
15
+ @task(name="specstream-web-search")
16
+ def web_search(
17
+ query: str,
18
+ specstream_credentials: SpecStreamCredentials,
19
+ speed: Literal["default", "fast"] = "default",
20
+ num: int | None = None,
21
+ passages: bool = False,
22
+ ) -> dict[str, Any]:
23
+ """Search the live web with SpecStream (`POST /v1/web-search`).
24
+
25
+ Args:
26
+ query: The question or request in everyday words, 1 to 2,000 characters.
27
+ specstream_credentials: The block that holds the API key.
28
+ speed: "default" ($5 per 1,000 searches of up to 10 results, with an answer) or
29
+ "fast" ($1 per 1,000 searches of up to 10 results, ranked sources only).
30
+ num: How many results to return. None leaves the API default (10).
31
+ passages: Add the text of the top pages closest to the request.
32
+
33
+ Returns:
34
+ The `data` object of the reply: `sources`, and on the default speed `answer` and `rows`.
35
+ """
36
+ question = (query or "").strip()[:MAX_QUERY_CHARS]
37
+ if not question:
38
+ raise SpecStreamError("Send the question in query, 1 to 2,000 characters.")
39
+ body: dict[str, Any] = {"q": question}
40
+ if speed == "fast":
41
+ body["speed"] = "fast"
42
+ if num is not None:
43
+ body["num"] = int(num)
44
+ if passages:
45
+ body["passages"] = True
46
+ return specstream_credentials.get_client().call("POST", "/v1/web-search", json=body)
47
+
48
+
49
+ @task(name="specstream-extract-pages")
50
+ def extract_pages(
51
+ urls: list[str],
52
+ specstream_credentials: SpecStreamCredentials,
53
+ format: Literal["markdown", "text"] = "markdown",
54
+ ) -> dict[str, Any]:
55
+ """Read the main text of web pages, PDF, Word and Excel files with SpecStream (`POST /v1/extract`).
56
+
57
+ $0.80 per 1,000 pages; a page with no text is not charged. Up to 20 URLs a call: a longer list
58
+ is sent in calls of 20 and the results are joined in order.
59
+
60
+ Args:
61
+ urls: http or https URLs to read.
62
+ specstream_credentials: The block that holds the API key.
63
+ format: "markdown" (default) or "text".
64
+
65
+ Returns:
66
+ `{"results": [...]}`, one result per URL with its `url`, `status` and text.
67
+ """
68
+ cleaned = [url.strip() for url in urls if url and url.strip()]
69
+ if not cleaned:
70
+ raise SpecStreamError("Send 1 or more http or https URLs.")
71
+ client = specstream_credentials.get_client()
72
+ results: list[Any] = []
73
+ for start in range(0, len(cleaned), MAX_EXTRACT_URLS):
74
+ body = {"urls": cleaned[start : start + MAX_EXTRACT_URLS], "format": "text" if format == "text" else "markdown"}
75
+ data = client.call("POST", "/v1/extract", json=body)
76
+ results.extend(data.get("results") or [])
77
+ return {"results": results}
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "prefect-specstream"
3
+ version = "0.1.0"
4
+ description = "The live web data engine for Prefect: Search API ($5 per 1,000 searches of up to 10 results, $1 on the fast tier) and Extract API ($0.80 per 1,000 pages) as Prefect tasks with a credentials block."
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
+ maintainers = [{ name = "SpecStream", email = "support@specstream.ai" }]
11
+ keywords = ["prefect", "prefect-integration", "prefect-collection", "specstream", "web-search", "research", "deep-research", "search-api", "extract-api", "web-data", "live-web", "data-pipelines"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Developers",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Topic :: Internet :: WWW/HTTP",
19
+ "Topic :: System :: Distributed Computing",
20
+ "Typing :: Typed",
21
+ ]
22
+ dependencies = ["prefect>=3.0,<4", "httpx>=0.27"]
23
+
24
+ [project.optional-dependencies]
25
+ test = ["pytest>=8"]
26
+
27
+ [dependency-groups]
28
+ dev = ["pytest>=8"]
29
+
30
+ [project.entry-points."prefect.collections"]
31
+ prefect_specstream = "prefect_specstream"
32
+
33
+ [project.urls]
34
+ Homepage = "https://specstream.ai"
35
+ Documentation = "https://specstream.ai/docs/api"
36
+ Repository = "https://github.com/specstream/specstream-tools/tree/main/packages/prefect-specstream"
37
+ Issues = "https://github.com/specstream/specstream-tools/issues"
38
+ Pricing = "https://specstream.ai/pricing"
39
+
40
+ [build-system]
41
+ requires = ["hatchling>=1.27,<2"]
42
+ build-backend = "hatchling.build"
43
+
44
+ [tool.hatch.build.targets.wheel]
45
+ packages = ["prefect_specstream"]
46
+
47
+ [tool.hatch.build.targets.sdist]
48
+ include = ["prefect_specstream", "tests", "README.md", "LICENSE"]
49
+
50
+ [tool.pytest.ini_options]
51
+ testpaths = ["tests"]
@@ -0,0 +1,125 @@
1
+ import json
2
+
3
+ import httpx
4
+ import pytest
5
+ from prefect import flow
6
+ from prefect.testing.utilities import prefect_test_harness
7
+
8
+ import prefect_specstream
9
+ from prefect_specstream import SpecStreamCredentials, SpecStreamError, extract_pages, web_search
10
+ from prefect_specstream.credentials import SpecStreamClient
11
+
12
+ SEARCH = {"data": {"kind": "fact", "answer": {"value": "42", "page": "https://a.example"}, "rows": [], "sources": []}}
13
+
14
+
15
+ def extract_reply(request: httpx.Request) -> dict:
16
+ urls = json.loads(request.content)["urls"]
17
+ return {"data": {"results": [{"url": url, "status": "ok", "text": "page"} for url in urls]}}
18
+
19
+
20
+ class Recorder:
21
+ def __init__(self, handler=None):
22
+ self.seen: list[httpx.Request] = []
23
+ self.handler = handler or self.ok
24
+
25
+ @staticmethod
26
+ def ok(request: httpx.Request) -> httpx.Response:
27
+ if request.url.path == "/v1/extract":
28
+ return httpx.Response(200, json=extract_reply(request))
29
+ return httpx.Response(200, json=SEARCH)
30
+
31
+ def __call__(self, request: httpx.Request) -> httpx.Response:
32
+ self.seen.append(request)
33
+ return self.handler(request)
34
+
35
+
36
+ @pytest.fixture
37
+ def recorder(monkeypatch):
38
+ rec = Recorder()
39
+ original = SpecStreamCredentials.get_client
40
+
41
+ def get_client(self, transport=None):
42
+ return original(self, transport=httpx.MockTransport(rec))
43
+
44
+ monkeypatch.setattr(SpecStreamCredentials, "get_client", get_client)
45
+ return rec
46
+
47
+
48
+ def credentials(key="ss_test"):
49
+ return SpecStreamCredentials(api_key=key)
50
+
51
+
52
+ def test_search_posts_the_question_with_the_key(recorder):
53
+ data = web_search.fn(" who won? ", credentials())
54
+ assert data == SEARCH["data"]
55
+ request = recorder.seen[0]
56
+ assert request.method == "POST"
57
+ assert str(request.url) == "https://api.specstream.ai/v1/web-search"
58
+ assert request.headers["Authorization"] == "Bearer ss_test"
59
+ assert request.headers["User-Agent"] == f"prefect-specstream/{prefect_specstream.__version__}"
60
+ assert json.loads(request.content) == {"q": "who won?"}
61
+
62
+
63
+ def test_search_sends_fast_num_and_passages_only_when_asked(recorder):
64
+ web_search.fn("q", credentials(), speed="fast", num=20, passages=True)
65
+ assert json.loads(recorder.seen[0].content) == {"q": "q", "speed": "fast", "num": 20, "passages": True}
66
+
67
+
68
+ def test_search_refuses_an_empty_question_without_a_call(recorder):
69
+ with pytest.raises(SpecStreamError):
70
+ web_search.fn(" ", credentials())
71
+ assert recorder.seen == []
72
+
73
+
74
+ def test_extract_splits_long_lists_in_calls_of_twenty(recorder):
75
+ urls = [f"https://a.example/{i}" for i in range(45)] + ["", " "]
76
+ data = extract_pages.fn(urls, credentials(), format="text")
77
+ assert [len(json.loads(r.content)["urls"]) for r in recorder.seen] == [20, 20, 5]
78
+ assert json.loads(recorder.seen[0].content)["format"] == "text"
79
+ assert [r["url"] for r in data["results"]] == [f"https://a.example/{i}" for i in range(45)]
80
+
81
+
82
+ def test_api_error_message_is_raised_with_its_status(monkeypatch):
83
+ def refuse(request):
84
+ return httpx.Response(402, json={"error": {"message": "Add credit to continue."}})
85
+
86
+ client = SpecStreamClient("ss_test", transport=httpx.MockTransport(refuse))
87
+ with pytest.raises(SpecStreamError) as caught:
88
+ client.call("POST", "/v1/extract", json={"urls": ["https://a.example"]})
89
+ assert str(caught.value) == "Add credit to continue."
90
+ assert caught.value.status_code == 402
91
+
92
+
93
+ def test_empty_key_fails_before_any_call(monkeypatch):
94
+ monkeypatch.delenv("SPECSTREAM_API_KEY", raising=False)
95
+ seen = []
96
+ client = SpecStreamCredentials().get_client(transport=httpx.MockTransport(lambda r: seen.append(r)))
97
+ with pytest.raises(SpecStreamError, match="API key is empty"):
98
+ client.call("POST", "/v1/web-search", json={"q": "x"})
99
+ assert seen == []
100
+
101
+
102
+ def test_key_defaults_to_the_environment_and_stays_secret(monkeypatch):
103
+ monkeypatch.setenv("SPECSTREAM_API_KEY", "ss_env")
104
+ block = SpecStreamCredentials()
105
+ assert block.api_key.get_secret_value() == "ss_env"
106
+ assert "ss_env" not in repr(block)
107
+
108
+
109
+ def test_block_is_registered_for_prefect():
110
+ assert SpecStreamCredentials.get_block_type_slug() == "specstream-credentials"
111
+ assert "api_key" in SpecStreamCredentials.model_json_schema()["properties"]
112
+
113
+
114
+ def test_tasks_run_inside_a_flow(recorder):
115
+ @flow
116
+ def research():
117
+ found = web_search("q", credentials())
118
+ pages = extract_pages(["https://a.example"], credentials())
119
+ return found, pages
120
+
121
+ # A loaded machine starts the local server slowly; the default 30 s fails there.
122
+ with prefect_test_harness(server_startup_timeout=180):
123
+ found, pages = research()
124
+ assert found == SEARCH["data"]
125
+ assert pages["results"][0]["status"] == "ok"
@@ -0,0 +1,136 @@
1
+ import json
2
+
3
+ import httpx
4
+ import pytest
5
+ from prefect.testing.utilities import prefect_test_harness
6
+
7
+ from prefect_specstream import (
8
+ SpecStreamCredentials,
9
+ SpecStreamError,
10
+ get_research,
11
+ research,
12
+ research_report,
13
+ start_research,
14
+ wait_for_research,
15
+ )
16
+
17
+ REPORT = {
18
+ "title": "Stablecoin reserves",
19
+ "content": "The EU asks for full reserves [1].",
20
+ "citations": [{"n": 1, "url": "https://a.example", "excerpt": "full reserves", "supported": True}],
21
+ "sources": [{"n": 1, "url": "https://a.example", "cited": True}],
22
+ }
23
+
24
+
25
+ class Api:
26
+ """A scripted SpecStream: POST starts run r_1, each GET answers the next state in `states`."""
27
+
28
+ def __init__(self, states):
29
+ self.states = list(states)
30
+ self.seen: list[httpx.Request] = []
31
+
32
+ def __call__(self, request: httpx.Request) -> httpx.Response:
33
+ self.seen.append(request)
34
+ if request.method == "POST":
35
+ body = json.loads(request.content)
36
+ return httpx.Response(200, json={"data": {"id": "r_1", "status": "queued", "depth": body["depth"], "price_usd": 0.1}})
37
+ state = self.states.pop(0) if len(self.states) > 1 else self.states[0]
38
+ return httpx.Response(200, json={"data": {"id": "r_1", "depth": "quick", "price_usd": 0.1, **state}})
39
+
40
+
41
+ @pytest.fixture
42
+ def api(monkeypatch):
43
+ original = SpecStreamCredentials.get_client
44
+
45
+ def make(*states):
46
+ scripted = Api(states)
47
+ monkeypatch.setattr(
48
+ SpecStreamCredentials, "get_client", lambda self, transport=None: original(self, transport=httpx.MockTransport(scripted))
49
+ )
50
+ return scripted
51
+
52
+ monkeypatch.setattr(research, "_sleep", lambda seconds: None)
53
+ return make
54
+
55
+
56
+ def credentials():
57
+ return SpecStreamCredentials(api_key="ss_test")
58
+
59
+
60
+ def test_start_posts_the_question_and_depth_with_a_stable_idempotency_key(api):
61
+ scripted = api({"status": "running"})
62
+ first = start_research.fn(" How are reserves regulated? ", credentials(), depth="quick")
63
+ start_research.fn("How are reserves regulated?", credentials(), depth="quick")
64
+ start_research.fn("How are reserves regulated?", credentials(), depth="deep")
65
+ assert first["id"] == "r_1"
66
+ request = scripted.seen[0]
67
+ assert (request.method, str(request.url)) == ("POST", "https://api.specstream.ai/v1/research")
68
+ assert request.headers["Authorization"] == "Bearer ss_test"
69
+ assert json.loads(request.content) == {"input": "How are reserves regulated?", "depth": "quick"}
70
+ keys = [r.headers["Idempotency-Key"] for r in scripted.seen]
71
+ assert keys[0].startswith("prefect-research-")
72
+ assert keys[0] == keys[1] != keys[2]
73
+
74
+
75
+ def test_start_sends_options_but_never_lets_them_replace_the_question_or_depth(api):
76
+ scripted = api({"status": "running"})
77
+ start_research.fn("q", credentials(), depth="quick", options={"language": "fr", "depth": "deep", "empty": None})
78
+ assert json.loads(scripted.seen[0].content) == {"input": "q", "depth": "quick", "language": "fr"}
79
+
80
+
81
+ @pytest.mark.parametrize("question, depth", [(" ", "quick"), ("x" * 15_001, "quick"), ("q", "huge")])
82
+ def test_start_refuses_a_bad_request_without_a_call(api, question, depth):
83
+ scripted = api({"status": "running"})
84
+ with pytest.raises(SpecStreamError):
85
+ start_research.fn(question, credentials(), depth=depth)
86
+ assert scripted.seen == []
87
+
88
+
89
+ def test_get_reads_the_run_by_its_id(api):
90
+ scripted = api({"status": "completed", "report": REPORT})
91
+ run = get_research.fn("r/1", credentials())
92
+ assert run["report"] == REPORT
93
+ assert (scripted.seen[0].method, scripted.seen[0].url.raw_path) == ("GET", b"/v1/research/r%2F1")
94
+ with pytest.raises(SpecStreamError):
95
+ get_research.fn(" ", credentials())
96
+
97
+
98
+ def test_wait_reads_until_the_report_is_written(api):
99
+ scripted = api({"status": "queued"}, {"status": "running"}, {"status": "completed", "report": REPORT})
100
+ run = wait_for_research.fn("r_1", credentials())
101
+ assert run["status"] == "completed"
102
+ assert len(scripted.seen) == 3
103
+
104
+
105
+ def test_wait_raises_with_the_id_when_time_runs_out(api):
106
+ scripted = api({"status": "running"})
107
+ with pytest.raises(SpecStreamError, match="r_1 is still running"):
108
+ wait_for_research.fn("r_1", credentials(), wait_seconds=0)
109
+ assert len(scripted.seen) == 1
110
+
111
+
112
+ def test_wait_raises_when_the_run_fails_or_the_balance_is_short(api):
113
+ api({"status": "failed", "error": {"message": "No page answered."}})
114
+ with pytest.raises(SpecStreamError, match="ended as failed: No page answered."):
115
+ wait_for_research.fn("r_1", credentials())
116
+ api({"status": "payment_required"})
117
+ with pytest.raises(SpecStreamError, match="Add credit") as caught:
118
+ wait_for_research.fn("r_1", credentials())
119
+ assert caught.value.status_code == 402
120
+
121
+
122
+ def test_the_flow_returns_the_written_report(api):
123
+ scripted = api({"status": "running"}, {"status": "completed", "report": REPORT})
124
+ # A loaded machine starts the local server slowly; the default 30 s fails there.
125
+ with prefect_test_harness(server_startup_timeout=180):
126
+ result = research_report("How are reserves regulated?", credentials(), depth="quick")
127
+ assert result == {
128
+ "research_id": "r_1",
129
+ "depth": "quick",
130
+ "price_usd": 0.1,
131
+ "title": "Stablecoin reserves",
132
+ "content": "The EU asks for full reserves [1].",
133
+ "citations": REPORT["citations"],
134
+ "sources": REPORT["sources"],
135
+ }
136
+ assert [r.method for r in scripted.seen] == ["POST", "GET", "GET"]