temporal-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.
@@ -0,0 +1,19 @@
1
+ """SpecStream for Temporal: live web search and page reading as durable Activities."""
2
+
3
+ from ._api import DEFAULT_BASE_URL, SpecStreamClient, SpecStreamError
4
+ from .activities import EXTRACT, WEB_SEARCH, ExtractInput, SpecStreamActivities, WebSearchInput
5
+ from .plugin import PLUGIN_NAME, SpecStreamPlugin
6
+
7
+ __all__ = [
8
+ "DEFAULT_BASE_URL",
9
+ "EXTRACT",
10
+ "PLUGIN_NAME",
11
+ "WEB_SEARCH",
12
+ "ExtractInput",
13
+ "SpecStreamActivities",
14
+ "SpecStreamClient",
15
+ "SpecStreamError",
16
+ "SpecStreamPlugin",
17
+ "WebSearchInput",
18
+ ]
19
+ __version__ = "0.1.0"
@@ -0,0 +1,118 @@
1
+ """The SpecStream REST calls behind the Activities, over httpx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ import httpx
9
+
10
+ DEFAULT_BASE_URL = "https://api.specstream.ai"
11
+ USER_AGENT = "temporal-specstream/0.1.0"
12
+ KEY_HELP = (
13
+ "Pass api_key to SpecStreamPlugin or set SPECSTREAM_API_KEY on the Worker. "
14
+ "Create a key under Agents & API in your SpecStream workspace."
15
+ )
16
+ # A later attempt can succeed: the request timed out or was rate limited.
17
+ RETRYABLE_STATUS = frozenset({408, 425, 429})
18
+
19
+
20
+ class SpecStreamError(RuntimeError):
21
+ """SpecStream refused a call, or could not be reached.
22
+
23
+ ``retryable`` says whether the same call can succeed later.
24
+ """
25
+
26
+ def __init__(self, message: str, *, status: int | None = None, retryable: bool = False) -> None:
27
+ super().__init__(message)
28
+ self.status = status
29
+ self.retryable = retryable
30
+
31
+
32
+ def is_retryable(status: int) -> bool:
33
+ """True for a status that a later attempt can turn into an answer."""
34
+ return status in RETRYABLE_STATUS or status >= 500
35
+
36
+
37
+ class SpecStreamClient:
38
+ """A small async client for the Search API and the Extract API.
39
+
40
+ ``transport`` replaces the network in tests. Each call opens and closes its own
41
+ connection, so one client is safe on any event loop a Worker runs.
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ api_key: str | None = None,
47
+ *,
48
+ base_url: str = DEFAULT_BASE_URL,
49
+ timeout: float = 60.0,
50
+ transport: httpx.AsyncBaseTransport | None = None,
51
+ ) -> None:
52
+ self._api_key = api_key
53
+ self._base_url = base_url.rstrip("/")
54
+ self._timeout = timeout
55
+ self._transport = transport
56
+
57
+ def _key(self) -> str:
58
+ key = (self._api_key or os.environ.get("SPECSTREAM_API_KEY") or "").strip()
59
+ if not key:
60
+ raise SpecStreamError(KEY_HELP)
61
+ return key if key.lower().startswith("bearer ") else f"Bearer {key}"
62
+
63
+ async def request(
64
+ self,
65
+ method: str,
66
+ path: str,
67
+ *,
68
+ params: dict[str, str] | None = None,
69
+ body: dict[str, Any] | None = None,
70
+ ) -> dict[str, Any]:
71
+ """One call. Raises :class:`SpecStreamError`; the message never holds the key."""
72
+ headers = {"Authorization": self._key(), "Accept": "application/json", "User-Agent": USER_AGENT}
73
+ try:
74
+ async with httpx.AsyncClient(
75
+ base_url=self._base_url, timeout=self._timeout, transport=self._transport
76
+ ) as http:
77
+ response = await http.request(method, path, params=params, json=body, headers=headers)
78
+ except httpx.HTTPError as error:
79
+ raise SpecStreamError(f"Couldn't reach SpecStream: {type(error).__name__}", retryable=True) from None
80
+ try:
81
+ payload = response.json()
82
+ except ValueError:
83
+ payload = None
84
+ status = response.status_code
85
+ if status >= 400:
86
+ raise SpecStreamError(
87
+ f"SpecStream answered {status}: {_message(payload)}", status=status, retryable=is_retryable(status)
88
+ )
89
+ if not isinstance(payload, dict):
90
+ raise SpecStreamError("SpecStream returned a response this package couldn't read.", retryable=True)
91
+ return payload
92
+
93
+ async def web_search(self, q: str, *, speed: str = "default", passages: bool = False) -> dict[str, Any]:
94
+ """Search the live web with ``GET /v1/web-search``."""
95
+ query = (q or "").strip()
96
+ if not 1 <= len(query) <= 2000:
97
+ raise SpecStreamError("q must be between 1 and 2,000 characters.")
98
+ params = {"q": query, "speed": "fast" if speed == "fast" else "default"}
99
+ if passages:
100
+ params["passages"] = "true"
101
+ return await self.request("GET", "/v1/web-search", params=params)
102
+
103
+ async def extract(self, urls: list[str], *, format: str = "text") -> dict[str, Any]:
104
+ """Read the main text of 1 to 20 URLs with ``POST /v1/extract``."""
105
+ cleaned = [str(u or "").strip() for u in (urls or []) if str(u or "").strip()]
106
+ if not 1 <= len(cleaned) <= 20:
107
+ raise SpecStreamError("Give 1 to 20 http or https URLs.")
108
+ body = {"urls": cleaned, "format": "markdown" if format == "markdown" else "text"}
109
+ return await self.request("POST", "/v1/extract", body=body)
110
+
111
+
112
+ def _message(payload: Any) -> str:
113
+ detail = payload.get("error") if isinstance(payload, dict) else None
114
+ if isinstance(detail, dict):
115
+ return str(detail.get("message") or "request refused")
116
+ if isinstance(detail, str):
117
+ return detail
118
+ return "request refused"
@@ -0,0 +1,73 @@
1
+ """SpecStream as Temporal Activities: search the live web and read pages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from temporalio import activity
9
+ from temporalio.exceptions import ApplicationError
10
+
11
+ from ._api import SpecStreamClient, SpecStreamError
12
+
13
+ WEB_SEARCH = "specstream.web_search"
14
+ EXTRACT = "specstream.extract"
15
+ ERROR_TYPE = "SpecStreamError"
16
+
17
+
18
+ @dataclass
19
+ class WebSearchInput:
20
+ """What to search for.
21
+
22
+ ``speed="fast"`` answers sooner at the fast price. ``passages=True`` adds the
23
+ passages of each page that answer the query.
24
+ """
25
+
26
+ q: str
27
+ speed: str = "default"
28
+ passages: bool = False
29
+
30
+
31
+ @dataclass
32
+ class ExtractInput:
33
+ """The pages to read: 1 to 20 URLs, as ``text`` or ``markdown``."""
34
+
35
+ urls: list[str] = field(default_factory=list)
36
+ format: str = "text"
37
+
38
+
39
+ def _failure(error: SpecStreamError) -> ApplicationError:
40
+ """A refusal stops the Activity; what a later attempt can fix is left to the retry policy."""
41
+ return ApplicationError(str(error), type=ERROR_TYPE, non_retryable=not error.retryable)
42
+
43
+
44
+ class SpecStreamActivities:
45
+ """The Activities, bound to one client.
46
+
47
+ A Workflow calls them by method reference or by name::
48
+
49
+ await workflow.execute_activity(
50
+ SpecStreamActivities.web_search,
51
+ WebSearchInput(q="..."),
52
+ start_to_close_timeout=timedelta(seconds=60),
53
+ )
54
+ """
55
+
56
+ def __init__(self, client: SpecStreamClient) -> None:
57
+ self._client = client
58
+
59
+ @activity.defn(name=WEB_SEARCH)
60
+ async def web_search(self, input: WebSearchInput) -> dict[str, Any]:
61
+ """Search the live web. Returns the Search API's answer as it is."""
62
+ try:
63
+ return await self._client.web_search(input.q, speed=input.speed, passages=input.passages)
64
+ except SpecStreamError as error:
65
+ raise _failure(error) from None
66
+
67
+ @activity.defn(name=EXTRACT)
68
+ async def extract(self, input: ExtractInput) -> dict[str, Any]:
69
+ """Read the text of up to 20 pages. Returns the Extract API's answer as it is."""
70
+ try:
71
+ return await self._client.extract(input.urls, format=input.format)
72
+ except SpecStreamError as error:
73
+ raise _failure(error) from None
@@ -0,0 +1,51 @@
1
+ """The Temporal Plugin that puts the SpecStream Activities on a Worker."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+
7
+ import httpx
8
+ from temporalio.plugin import SimplePlugin
9
+ from temporalio.worker import WorkflowRunner
10
+ from temporalio.worker.workflow_sandbox import SandboxedWorkflowRunner
11
+
12
+ from ._api import DEFAULT_BASE_URL, SpecStreamClient
13
+ from .activities import SpecStreamActivities
14
+
15
+ PLUGIN_NAME = "specstream.SpecStreamPlugin"
16
+ # Workflow code imports the inputs from this package; the sandbox takes these modules as they
17
+ # are instead of loading them again for every Workflow run.
18
+ PASSTHROUGH = ("temporal_specstream", "httpx")
19
+
20
+
21
+ def _runner(runner: WorkflowRunner | None) -> WorkflowRunner:
22
+ if runner is None:
23
+ raise ValueError("No WorkflowRunner provided to the SpecStream plugin.")
24
+ if isinstance(runner, SandboxedWorkflowRunner):
25
+ return dataclasses.replace(runner, restrictions=runner.restrictions.with_passthrough_modules(*PASSTHROUGH))
26
+ return runner
27
+
28
+
29
+ class SpecStreamPlugin(SimplePlugin):
30
+ """Registers ``specstream.web_search`` and ``specstream.extract`` on a Worker.
31
+
32
+ Give it to the Client (``Client.connect(..., plugins=[SpecStreamPlugin()])``): a Worker
33
+ made from that Client gets the Activities. The key is read from ``api_key`` or, on each
34
+ call, from ``SPECSTREAM_API_KEY``. It stays on the Worker and never enters Workflow history.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ api_key: str | None = None,
40
+ *,
41
+ base_url: str = DEFAULT_BASE_URL,
42
+ timeout: float = 60.0,
43
+ transport: httpx.AsyncBaseTransport | None = None,
44
+ ) -> None:
45
+ client = SpecStreamClient(api_key, base_url=base_url, timeout=timeout, transport=transport)
46
+ self.specstream = SpecStreamActivities(client)
47
+ super().__init__(
48
+ PLUGIN_NAME,
49
+ activities=[self.specstream.web_search, self.specstream.extract],
50
+ workflow_runner=_runner,
51
+ )
File without changes
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.5
2
+ Name: temporal-specstream
3
+ Version: 0.1.0
4
+ Summary: SpecStream for Temporal: live web search and page reading as durable Activities, in one Plugin.
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/temporal-specstream
8
+ Project-URL: Issues, https://github.com/specstream/specstream-tools/issues
9
+ Project-URL: Changelog, https://github.com/specstream/specstream-tools/blob/main/packages/temporal-specstream/CHANGELOG.md
10
+ Project-URL: Pricing, https://specstream.ai/pricing
11
+ Author-email: SpecStream <support@specstream.ai>
12
+ License-Expression: MIT
13
+ License-File: LICENSE
14
+ Keywords: activities,agents,extract-api,live-web,plugin,search-api,specstream,temporal,temporalio,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 :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: httpx>=0.27
25
+ Requires-Dist: temporalio<2,>=1.19
26
+ Provides-Extra: test
27
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
28
+ Requires-Dist: pytest>=8; extra == 'test'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # temporal-specstream
32
+
33
+ SpecStream for [Temporal](https://temporal.io): live web search and page reading as durable Activities, in one Plugin.
34
+
35
+ A Workflow that searches the web or reads a page gets Temporal's guarantees for that call: a timeout, retries with backoff, and a result that is recorded once and replayed, so a Workflow that restarts does not pay for the same search twice.
36
+
37
+ The Plugin registers two Activities:
38
+
39
+ 1. Search API: `specstream.web_search` calls `GET /v1/web-search`, $5 per 1,000 searches of up to 10 results, or $1 on the fast tier. The most accurate web search API in the world (scores and method: https://specstream.ai/benchmarks).
40
+ 2. Extract API: `specstream.extract` calls `POST /v1/extract`, up to 20 URLs a call (web pages, PDF, Word, Excel), $0.80 per 1,000 pages. A page with no text is not charged.
41
+
42
+ Deep Search, structured rows priced per row, is not in this package yet.
43
+
44
+ ## Install
45
+
46
+ ```bash
47
+ pip install temporal-specstream
48
+ ```
49
+
50
+ It needs Python 3.11 or later and `temporalio` 1.19 or later.
51
+ A free account comes with $2 of credit and needs no card: [specstream.ai](https://specstream.ai/signup).
52
+ Create a key under Agents & API in the workspace and set it on the Worker as `SPECSTREAM_API_KEY`.
53
+
54
+ ## Use it
55
+
56
+ Give the Plugin to the Client. A Worker made from that Client has the Activities.
57
+
58
+ ```python
59
+ import asyncio
60
+ from datetime import timedelta
61
+
62
+ from temporalio import workflow
63
+ from temporalio.client import Client
64
+ from temporalio.worker import Worker
65
+
66
+ from temporal_specstream import ExtractInput, SpecStreamActivities, SpecStreamPlugin, WebSearchInput
67
+
68
+
69
+ @workflow.defn
70
+ class ResearchWorkflow:
71
+ @workflow.run
72
+ async def run(self, question: str) -> dict:
73
+ found = await workflow.execute_activity(
74
+ SpecStreamActivities.web_search,
75
+ WebSearchInput(q=question),
76
+ start_to_close_timeout=timedelta(seconds=60),
77
+ )
78
+ urls = [source["url"] for source in found.get("sources", [])[:3]]
79
+ pages = await workflow.execute_activity(
80
+ SpecStreamActivities.extract,
81
+ ExtractInput(urls=urls),
82
+ start_to_close_timeout=timedelta(seconds=120),
83
+ )
84
+ return {"answer": found.get("answer"), "pages": pages}
85
+
86
+
87
+ async def main() -> None:
88
+ client = await Client.connect("localhost:7233", plugins=[SpecStreamPlugin()])
89
+ async with Worker(client, task_queue="research", workflows=[ResearchWorkflow]):
90
+ print(await client.execute_workflow(
91
+ ResearchWorkflow.run, "Temporal Python SDK plugins", id="research-1", task_queue="research"
92
+ ))
93
+
94
+
95
+ asyncio.run(main())
96
+ ```
97
+
98
+ A Workflow written in another language calls the same Activities by name, `specstream.web_search` and `specstream.extract`, on the task queue of a Python Worker that has the Plugin.
99
+
100
+ ## Activities
101
+
102
+ | Activity | Input | Returns |
103
+ | --- | --- | --- |
104
+ | `specstream.web_search` | `WebSearchInput(q, speed="default", passages=False)`. `speed="fast"` answers sooner at the fast price. `passages=True` adds the passages of the top pages. | The Search API's answer: `kind`, `answer`, `rows`, `sources` and, with passages, `passages`. |
105
+ | `specstream.extract` | `ExtractInput(urls, format="text")`. 1 to 20 URLs, as `text` or `markdown`. | The Extract API's answer: the main text, title and published date of each page. |
106
+
107
+ ## Failures and retries
108
+
109
+ - A request that SpecStream refuses (a wrong key, a wrong argument, no credit left) raises an `ApplicationError` of type `SpecStreamError` that is not retried, so the Workflow sees it at once.
110
+ - A rate limit (429), a server error (5xx) or a network error raises a retryable `ApplicationError`. The Activity's retry policy decides how many attempts follow.
111
+
112
+ ## The key
113
+
114
+ `SpecStreamPlugin(api_key=...)` takes the key, or each call reads `SPECSTREAM_API_KEY` from the Worker's environment.
115
+ The key stays on the Worker. It is never an Activity input, so it never enters Workflow history.
116
+
117
+ ## Options
118
+
119
+ `SpecStreamPlugin(api_key=None, base_url="https://api.specstream.ai", timeout=60.0, transport=None)`.
120
+ `transport` is an `httpx` transport that replaces the network, for tests.
121
+
122
+ ## License
123
+
124
+ MIT
@@ -0,0 +1,9 @@
1
+ temporal_specstream/__init__.py,sha256=9bGxtc-x3BClt6DAEd-swcnVNblkwCEPdnJ-5l3eSUY,558
2
+ temporal_specstream/_api.py,sha256=Zhn1rasX7ep6Iu4ir4_fQs_yWvi-NTvo2kSm8TxB1Ao,4638
3
+ temporal_specstream/activities.py,sha256=UCVzLJ7Ua2Uiuw8SllvHlK5R8uOV67LT-ksnXDwDEHg,2293
4
+ temporal_specstream/plugin.py,sha256=qc6MJjLzSeOiCENas77rqt9HwwBAmkaE6PsNShoo4Ww,1974
5
+ temporal_specstream/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ temporal_specstream-0.1.0.dist-info/METADATA,sha256=h_sYt9RjsjUL-G_Ejfh4ZRPngcXMX4j5J_xbK1tVv98,5612
7
+ temporal_specstream-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ temporal_specstream-0.1.0.dist-info/licenses/LICENSE,sha256=lvzGtfzsxc8Xe1_0sabdiWTcSDiSg3jqaFKV9x3F4oo,1071
9
+ temporal_specstream-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.