prefect-specstream 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- prefect_specstream/__init__.py +19 -0
- prefect_specstream/_version.py +1 -0
- prefect_specstream/credentials.py +82 -0
- prefect_specstream/py.typed +0 -0
- prefect_specstream/research.py +160 -0
- prefect_specstream/tasks.py +77 -0
- prefect_specstream-0.1.0.dist-info/METADATA +120 -0
- prefect_specstream-0.1.0.dist-info/RECORD +11 -0
- prefect_specstream-0.1.0.dist-info/WHEEL +4 -0
- prefect_specstream-0.1.0.dist-info/entry_points.txt +2 -0
- prefect_specstream-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -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,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,11 @@
|
|
|
1
|
+
prefect_specstream/__init__.py,sha256=Fz6ca0xA1P3cxmejaujlbQDmCLt5O4jYt-hngQggFHc,678
|
|
2
|
+
prefect_specstream/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
3
|
+
prefect_specstream/credentials.py,sha256=A4gMG9PuKXW8RpWfw1aVgIVLv-ka0Q2A3IkuLbd6HNc,3474
|
|
4
|
+
prefect_specstream/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
prefect_specstream/research.py,sha256=F2LPS4X2wxn_td1J-YefKGRDkHoiVMPa1pVUWLRQtXg,6760
|
|
6
|
+
prefect_specstream/tasks.py,sha256=q7nBqi79_73zCyCBFMY21LMm9mPZq04w3O1IEMwajOo,2959
|
|
7
|
+
prefect_specstream-0.1.0.dist-info/METADATA,sha256=XY4xbnbaKRzR8eH7P8OI22j66K0M6RygllbMhKcHcG0,5891
|
|
8
|
+
prefect_specstream-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
prefect_specstream-0.1.0.dist-info/entry_points.txt,sha256=jUTelQK0nRE5ZtQyG-3_SxBLRO_Hj_a28fj8DS98dsw,62
|
|
10
|
+
prefect_specstream-0.1.0.dist-info/licenses/LICENSE,sha256=lvzGtfzsxc8Xe1_0sabdiWTcSDiSg3jqaFKV9x3F4oo,1071
|
|
11
|
+
prefect_specstream-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|