temporal-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.
- temporal_specstream-0.1.0/.gitignore +69 -0
- temporal_specstream-0.1.0/CHANGELOG.md +7 -0
- temporal_specstream-0.1.0/LICENSE +21 -0
- temporal_specstream-0.1.0/PKG-INFO +124 -0
- temporal_specstream-0.1.0/README.md +94 -0
- temporal_specstream-0.1.0/examples/research_workflow.py +53 -0
- temporal_specstream-0.1.0/pyproject.toml +50 -0
- temporal_specstream-0.1.0/temporal_specstream/__init__.py +19 -0
- temporal_specstream-0.1.0/temporal_specstream/_api.py +118 -0
- temporal_specstream-0.1.0/temporal_specstream/activities.py +73 -0
- temporal_specstream-0.1.0/temporal_specstream/plugin.py +51 -0
- temporal_specstream-0.1.0/temporal_specstream/py.typed +0 -0
- temporal_specstream-0.1.0/tests/test_temporal_specstream.py +204 -0
|
@@ -0,0 +1,69 @@
|
|
|
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/
|
|
69
|
+
listings/highlevel/video/*.mp4
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- `SpecStreamPlugin`: registers the `specstream.web_search` and `specstream.extract` Activities on a Worker.
|
|
6
|
+
- A refused request (a bad key, a bad argument, no credit) fails the Activity at once.
|
|
7
|
+
A rate limit, a server error or a network error is left to the Activity's retry policy.
|
|
@@ -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,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,94 @@
|
|
|
1
|
+
# temporal-specstream
|
|
2
|
+
|
|
3
|
+
SpecStream for [Temporal](https://temporal.io): live web search and page reading as durable Activities, in one Plugin.
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
The Plugin registers two Activities:
|
|
8
|
+
|
|
9
|
+
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).
|
|
10
|
+
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.
|
|
11
|
+
|
|
12
|
+
Deep Search, structured rows priced per row, is not in this package yet.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install temporal-specstream
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
It needs Python 3.11 or later and `temporalio` 1.19 or later.
|
|
21
|
+
A free account comes with $2 of credit and needs no card: [specstream.ai](https://specstream.ai/signup).
|
|
22
|
+
Create a key under Agents & API in the workspace and set it on the Worker as `SPECSTREAM_API_KEY`.
|
|
23
|
+
|
|
24
|
+
## Use it
|
|
25
|
+
|
|
26
|
+
Give the Plugin to the Client. A Worker made from that Client has the Activities.
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
import asyncio
|
|
30
|
+
from datetime import timedelta
|
|
31
|
+
|
|
32
|
+
from temporalio import workflow
|
|
33
|
+
from temporalio.client import Client
|
|
34
|
+
from temporalio.worker import Worker
|
|
35
|
+
|
|
36
|
+
from temporal_specstream import ExtractInput, SpecStreamActivities, SpecStreamPlugin, WebSearchInput
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@workflow.defn
|
|
40
|
+
class ResearchWorkflow:
|
|
41
|
+
@workflow.run
|
|
42
|
+
async def run(self, question: str) -> dict:
|
|
43
|
+
found = await workflow.execute_activity(
|
|
44
|
+
SpecStreamActivities.web_search,
|
|
45
|
+
WebSearchInput(q=question),
|
|
46
|
+
start_to_close_timeout=timedelta(seconds=60),
|
|
47
|
+
)
|
|
48
|
+
urls = [source["url"] for source in found.get("sources", [])[:3]]
|
|
49
|
+
pages = await workflow.execute_activity(
|
|
50
|
+
SpecStreamActivities.extract,
|
|
51
|
+
ExtractInput(urls=urls),
|
|
52
|
+
start_to_close_timeout=timedelta(seconds=120),
|
|
53
|
+
)
|
|
54
|
+
return {"answer": found.get("answer"), "pages": pages}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def main() -> None:
|
|
58
|
+
client = await Client.connect("localhost:7233", plugins=[SpecStreamPlugin()])
|
|
59
|
+
async with Worker(client, task_queue="research", workflows=[ResearchWorkflow]):
|
|
60
|
+
print(await client.execute_workflow(
|
|
61
|
+
ResearchWorkflow.run, "Temporal Python SDK plugins", id="research-1", task_queue="research"
|
|
62
|
+
))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
asyncio.run(main())
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
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.
|
|
69
|
+
|
|
70
|
+
## Activities
|
|
71
|
+
|
|
72
|
+
| Activity | Input | Returns |
|
|
73
|
+
| --- | --- | --- |
|
|
74
|
+
| `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`. |
|
|
75
|
+
| `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. |
|
|
76
|
+
|
|
77
|
+
## Failures and retries
|
|
78
|
+
|
|
79
|
+
- 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.
|
|
80
|
+
- 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.
|
|
81
|
+
|
|
82
|
+
## The key
|
|
83
|
+
|
|
84
|
+
`SpecStreamPlugin(api_key=...)` takes the key, or each call reads `SPECSTREAM_API_KEY` from the Worker's environment.
|
|
85
|
+
The key stays on the Worker. It is never an Activity input, so it never enters Workflow history.
|
|
86
|
+
|
|
87
|
+
## Options
|
|
88
|
+
|
|
89
|
+
`SpecStreamPlugin(api_key=None, base_url="https://api.specstream.ai", timeout=60.0, transport=None)`.
|
|
90
|
+
`transport` is an `httpx` transport that replaces the network, for tests.
|
|
91
|
+
|
|
92
|
+
## License
|
|
93
|
+
|
|
94
|
+
MIT
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Search the live web, then read the first pages, as one durable Workflow.
|
|
2
|
+
|
|
3
|
+
pip install temporal-specstream
|
|
4
|
+
temporal server start-dev
|
|
5
|
+
SPECSTREAM_API_KEY=... python research_workflow.py "who maintains the Temporal Python SDK"
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import sys
|
|
12
|
+
from datetime import timedelta
|
|
13
|
+
|
|
14
|
+
from temporalio import workflow
|
|
15
|
+
from temporalio.client import Client
|
|
16
|
+
from temporalio.worker import Worker
|
|
17
|
+
|
|
18
|
+
from temporal_specstream import ExtractInput, SpecStreamActivities, SpecStreamPlugin, WebSearchInput
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@workflow.defn
|
|
22
|
+
class ResearchWorkflow:
|
|
23
|
+
@workflow.run
|
|
24
|
+
async def run(self, question: str) -> dict:
|
|
25
|
+
found = await workflow.execute_activity(
|
|
26
|
+
SpecStreamActivities.web_search,
|
|
27
|
+
WebSearchInput(q=question),
|
|
28
|
+
start_to_close_timeout=timedelta(seconds=60),
|
|
29
|
+
)
|
|
30
|
+
urls = [item["url"] for item in found.get("sources", [])[:3] if item.get("url")]
|
|
31
|
+
if not urls:
|
|
32
|
+
return {"search": found, "pages": {}}
|
|
33
|
+
pages = await workflow.execute_activity(
|
|
34
|
+
SpecStreamActivities.extract,
|
|
35
|
+
ExtractInput(urls=urls),
|
|
36
|
+
start_to_close_timeout=timedelta(seconds=120),
|
|
37
|
+
)
|
|
38
|
+
return {"search": found, "pages": pages}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
async def main(question: str) -> None:
|
|
42
|
+
client = await Client.connect("localhost:7233", plugins=[SpecStreamPlugin()])
|
|
43
|
+
async with Worker(client, task_queue="specstream-research", workflows=[ResearchWorkflow]):
|
|
44
|
+
result = await client.execute_workflow(
|
|
45
|
+
ResearchWorkflow.run, question, id="specstream-research", task_queue="specstream-research"
|
|
46
|
+
)
|
|
47
|
+
print(result["search"].get("answer"))
|
|
48
|
+
for item in result["search"].get("sources", []):
|
|
49
|
+
print(item.get("url"))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if __name__ == "__main__":
|
|
53
|
+
asyncio.run(main(" ".join(sys.argv[1:]) or "Temporal Python SDK plugins"))
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "temporal-specstream"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "SpecStream for Temporal: live web search and page reading as durable Activities, in one Plugin."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.11"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [{ name = "SpecStream", email = "support@specstream.ai" }]
|
|
10
|
+
keywords = ["temporal", "temporalio", "plugin", "activities", "specstream", "agents", "web-search", "search-api", "extract-api", "web-data", "live-web"]
|
|
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
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
18
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
dependencies = ["temporalio>=1.19,<2", "httpx>=0.27"]
|
|
22
|
+
|
|
23
|
+
[project.optional-dependencies]
|
|
24
|
+
test = ["pytest>=8", "pytest-asyncio>=0.24"]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://specstream.ai"
|
|
28
|
+
Documentation = "https://specstream.ai/docs/api"
|
|
29
|
+
Repository = "https://github.com/specstream/specstream-tools/tree/main/packages/temporal-specstream"
|
|
30
|
+
Issues = "https://github.com/specstream/specstream-tools/issues"
|
|
31
|
+
Changelog = "https://github.com/specstream/specstream-tools/blob/main/packages/temporal-specstream/CHANGELOG.md"
|
|
32
|
+
Pricing = "https://specstream.ai/pricing"
|
|
33
|
+
|
|
34
|
+
[build-system]
|
|
35
|
+
requires = ["hatchling>=1.27,<2"]
|
|
36
|
+
build-backend = "hatchling.build"
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.wheel]
|
|
39
|
+
packages = ["temporal_specstream"]
|
|
40
|
+
|
|
41
|
+
[tool.hatch.build.targets.sdist]
|
|
42
|
+
include = ["temporal_specstream", "examples", "tests", "README.md", "CHANGELOG.md", "LICENSE"]
|
|
43
|
+
|
|
44
|
+
[tool.ruff]
|
|
45
|
+
line-length = 120
|
|
46
|
+
|
|
47
|
+
[tool.pytest.ini_options]
|
|
48
|
+
testpaths = ["tests"]
|
|
49
|
+
asyncio_mode = "auto"
|
|
50
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
@@ -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,204 @@
|
|
|
1
|
+
"""The Activities against a scripted SpecStream, and the Plugin on a real Worker.
|
|
2
|
+
|
|
3
|
+
No test calls SpecStream: an httpx.MockTransport answers every request.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import uuid
|
|
10
|
+
from datetime import timedelta
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
import pytest
|
|
14
|
+
from temporalio import workflow
|
|
15
|
+
from temporalio.client import WorkflowFailureError
|
|
16
|
+
from temporalio.common import RetryPolicy
|
|
17
|
+
from temporalio.exceptions import ActivityError, ApplicationError
|
|
18
|
+
from temporalio.testing import ActivityEnvironment, WorkflowEnvironment
|
|
19
|
+
from temporalio.worker import Worker
|
|
20
|
+
|
|
21
|
+
from temporal_specstream import (
|
|
22
|
+
EXTRACT,
|
|
23
|
+
PLUGIN_NAME,
|
|
24
|
+
WEB_SEARCH,
|
|
25
|
+
ExtractInput,
|
|
26
|
+
SpecStreamActivities,
|
|
27
|
+
SpecStreamPlugin,
|
|
28
|
+
WebSearchInput,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
SEARCH_ANSWER = {
|
|
32
|
+
"kind": "answer",
|
|
33
|
+
"answer": "Lyon has three roasters.",
|
|
34
|
+
"rows": [],
|
|
35
|
+
"sources": [{"url": "https://example.org/a", "cited": True}],
|
|
36
|
+
}
|
|
37
|
+
EXTRACT_ANSWER = {"pages": [{"url": "https://example.org/a", "title": "A", "text": "Roasters of Lyon"}]}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Script:
|
|
41
|
+
"""Answers each request with the next scripted reply and keeps what was asked."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, *replies: httpx.Response | Exception) -> None:
|
|
44
|
+
self.replies = list(replies)
|
|
45
|
+
self.requests: list[httpx.Request] = []
|
|
46
|
+
|
|
47
|
+
def __call__(self, request: httpx.Request) -> httpx.Response:
|
|
48
|
+
self.requests.append(request)
|
|
49
|
+
reply = self.replies.pop(0) if len(self.replies) > 1 else self.replies[0]
|
|
50
|
+
if isinstance(reply, Exception):
|
|
51
|
+
raise reply
|
|
52
|
+
return reply
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def transport(self) -> httpx.MockTransport:
|
|
56
|
+
return httpx.MockTransport(self)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def plugin(script: Script, api_key: str | None = "fixture-key") -> SpecStreamPlugin:
|
|
60
|
+
return SpecStreamPlugin(api_key, transport=script.transport)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def test_web_search_sends_the_query_and_returns_the_answer() -> None:
|
|
64
|
+
script = Script(httpx.Response(200, json=SEARCH_ANSWER))
|
|
65
|
+
found = await ActivityEnvironment().run(
|
|
66
|
+
plugin(script).specstream.web_search, WebSearchInput(q=" roasters in Lyon ", speed="fast", passages=True)
|
|
67
|
+
)
|
|
68
|
+
assert found == SEARCH_ANSWER
|
|
69
|
+
request = script.requests[0]
|
|
70
|
+
assert (request.method, request.url.path) == ("GET", "/v1/web-search")
|
|
71
|
+
assert dict(request.url.params) == {"q": "roasters in Lyon", "speed": "fast", "passages": "true"}
|
|
72
|
+
assert request.url.host == "api.specstream.ai"
|
|
73
|
+
assert request.headers["authorization"] == "Bearer fixture-key"
|
|
74
|
+
assert request.headers["user-agent"].startswith("temporal-specstream/")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
async def test_extract_posts_the_urls() -> None:
|
|
78
|
+
script = Script(httpx.Response(200, json=EXTRACT_ANSWER))
|
|
79
|
+
pages = await ActivityEnvironment().run(
|
|
80
|
+
plugin(script).specstream.extract, ExtractInput(urls=["https://example.org/a", " "], format="markdown")
|
|
81
|
+
)
|
|
82
|
+
assert pages == EXTRACT_ANSWER
|
|
83
|
+
request = script.requests[0]
|
|
84
|
+
assert (request.method, request.url.path) == ("POST", "/v1/extract")
|
|
85
|
+
assert json.loads(request.content) == {"urls": ["https://example.org/a"], "format": "markdown"}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
async def test_the_key_comes_from_the_environment_on_each_call(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
89
|
+
script = Script(httpx.Response(200, json=SEARCH_ANSWER))
|
|
90
|
+
activities = plugin(script, api_key=None).specstream
|
|
91
|
+
monkeypatch.delenv("SPECSTREAM_API_KEY", raising=False)
|
|
92
|
+
with pytest.raises(ApplicationError) as missing:
|
|
93
|
+
await ActivityEnvironment().run(activities.web_search, WebSearchInput(q="x"))
|
|
94
|
+
assert missing.value.non_retryable and "SPECSTREAM_API_KEY" in str(missing.value)
|
|
95
|
+
assert script.requests == []
|
|
96
|
+
monkeypatch.setenv("SPECSTREAM_API_KEY", "env-key")
|
|
97
|
+
await ActivityEnvironment().run(activities.web_search, WebSearchInput(q="x"))
|
|
98
|
+
assert script.requests[0].headers["authorization"] == "Bearer env-key"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@pytest.mark.parametrize("status", [401, 422])
|
|
102
|
+
async def test_a_refusal_is_not_retried(status: int) -> None:
|
|
103
|
+
script = Script(httpx.Response(status, json={"error": {"message": "refused for a reason"}}))
|
|
104
|
+
with pytest.raises(ApplicationError) as failure:
|
|
105
|
+
await ActivityEnvironment().run(plugin(script).specstream.web_search, WebSearchInput(q="x"))
|
|
106
|
+
assert failure.value.non_retryable
|
|
107
|
+
assert failure.value.type == "SpecStreamError"
|
|
108
|
+
assert failure.value.message == f"SpecStream answered {status}: refused for a reason"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@pytest.mark.parametrize("reply", [httpx.Response(429, json={"error": "slow down"}), httpx.Response(503, text="down")])
|
|
112
|
+
async def test_a_rate_limit_or_a_server_error_can_be_retried(reply: httpx.Response) -> None:
|
|
113
|
+
with pytest.raises(ApplicationError) as failure:
|
|
114
|
+
await ActivityEnvironment().run(plugin(Script(reply)).specstream.extract, ExtractInput(urls=["https://a.io"]))
|
|
115
|
+
assert not failure.value.non_retryable
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
async def test_a_network_error_can_be_retried_and_does_not_show_the_key() -> None:
|
|
119
|
+
script = Script(httpx.ConnectError("no route with Bearer fixture-key"))
|
|
120
|
+
with pytest.raises(ApplicationError) as failure:
|
|
121
|
+
await ActivityEnvironment().run(plugin(script).specstream.web_search, WebSearchInput(q="x"))
|
|
122
|
+
assert not failure.value.non_retryable
|
|
123
|
+
assert "fixture-key" not in str(failure.value)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@pytest.mark.parametrize("urls", [[], ["https://example.org/x"] * 21])
|
|
127
|
+
async def test_extract_refuses_a_wrong_number_of_urls_before_any_call(urls: list[str]) -> None:
|
|
128
|
+
script = Script(httpx.Response(200, json=EXTRACT_ANSWER))
|
|
129
|
+
with pytest.raises(ApplicationError) as failure:
|
|
130
|
+
await ActivityEnvironment().run(plugin(script).specstream.extract, ExtractInput(urls=urls))
|
|
131
|
+
assert failure.value.non_retryable and script.requests == []
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def test_the_plugin_is_named_and_registers_both_activities() -> None:
|
|
135
|
+
made = plugin(Script(httpx.Response(200, json={})))
|
|
136
|
+
assert made.name() == PLUGIN_NAME == "specstream.SpecStreamPlugin"
|
|
137
|
+
assert (WEB_SEARCH, EXTRACT) == ("specstream.web_search", "specstream.extract")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@workflow.defn
|
|
141
|
+
class ResearchWorkflow:
|
|
142
|
+
@workflow.run
|
|
143
|
+
async def run(self, question: str) -> dict:
|
|
144
|
+
found = await workflow.execute_activity(
|
|
145
|
+
SpecStreamActivities.web_search,
|
|
146
|
+
WebSearchInput(q=question),
|
|
147
|
+
start_to_close_timeout=timedelta(seconds=30),
|
|
148
|
+
retry_policy=RetryPolicy(initial_interval=timedelta(milliseconds=10), maximum_attempts=3),
|
|
149
|
+
)
|
|
150
|
+
# By name, as a Workflow in another language calls it.
|
|
151
|
+
pages = await workflow.execute_activity(
|
|
152
|
+
"specstream.extract",
|
|
153
|
+
ExtractInput(urls=[source["url"] for source in found["sources"]]),
|
|
154
|
+
start_to_close_timeout=timedelta(seconds=30),
|
|
155
|
+
)
|
|
156
|
+
return {"answer": found["answer"], "pages": pages}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@pytest.fixture
|
|
160
|
+
async def env():
|
|
161
|
+
async with await WorkflowEnvironment.start_time_skipping() as started:
|
|
162
|
+
yield started
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
async def _worker_client(env: WorkflowEnvironment, made: SpecStreamPlugin):
|
|
166
|
+
config = env.client.config()
|
|
167
|
+
config["plugins"] = [made]
|
|
168
|
+
return type(env.client)(**config)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
async def test_a_workflow_runs_both_activities_through_the_plugin_and_retries_a_server_error(env) -> None:
|
|
172
|
+
def answer(request: httpx.Request) -> httpx.Response:
|
|
173
|
+
return httpx.Response(200, json=EXTRACT_ANSWER if request.url.path == "/v1/extract" else SEARCH_ANSWER)
|
|
174
|
+
|
|
175
|
+
calls: list[str] = []
|
|
176
|
+
|
|
177
|
+
def flaky(request: httpx.Request) -> httpx.Response:
|
|
178
|
+
calls.append(request.url.path)
|
|
179
|
+
if calls == ["/v1/web-search"]:
|
|
180
|
+
return httpx.Response(503, text="down")
|
|
181
|
+
return answer(request)
|
|
182
|
+
|
|
183
|
+
made = SpecStreamPlugin("fixture-key", transport=httpx.MockTransport(flaky))
|
|
184
|
+
client = await _worker_client(env, made)
|
|
185
|
+
queue = f"q-{uuid.uuid4()}"
|
|
186
|
+
# The Worker names no activity: the Plugin brings them. The sandbox stays on.
|
|
187
|
+
async with Worker(client, task_queue=queue, workflows=[ResearchWorkflow]):
|
|
188
|
+
result = await client.execute_workflow(
|
|
189
|
+
ResearchWorkflow.run, "roasters in Lyon", id=f"w-{uuid.uuid4()}", task_queue=queue
|
|
190
|
+
)
|
|
191
|
+
assert result == {"answer": "Lyon has three roasters.", "pages": EXTRACT_ANSWER}
|
|
192
|
+
assert calls == ["/v1/web-search", "/v1/web-search", "/v1/extract"]
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
async def test_a_refusal_fails_the_workflow_after_one_attempt(env) -> None:
|
|
196
|
+
script = Script(httpx.Response(401, json={"error": {"message": "unknown key"}}))
|
|
197
|
+
client = await _worker_client(env, plugin(script))
|
|
198
|
+
queue = f"q-{uuid.uuid4()}"
|
|
199
|
+
async with Worker(client, task_queue=queue, workflows=[ResearchWorkflow]):
|
|
200
|
+
with pytest.raises(WorkflowFailureError) as failure:
|
|
201
|
+
await client.execute_workflow(ResearchWorkflow.run, "x", id=f"w-{uuid.uuid4()}", task_queue=queue)
|
|
202
|
+
assert isinstance(failure.value.cause, ActivityError)
|
|
203
|
+
assert "SpecStream answered 401: unknown key" in str(failure.value.cause.cause)
|
|
204
|
+
assert len(script.requests) == 1
|