specstream-client 1.3.3__tar.gz → 1.5.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.
- {specstream_client-1.3.3 → specstream_client-1.5.0}/PKG-INFO +118 -6
- {specstream_client-1.3.3 → specstream_client-1.5.0}/README.md +117 -5
- {specstream_client-1.3.3 → specstream_client-1.5.0}/pyproject.toml +1 -1
- {specstream_client-1.3.3 → specstream_client-1.5.0}/specstream_client/__init__.py +3 -1
- specstream_client-1.5.0/specstream_client/browser.py +224 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/specstream_client/cli.py +2 -1
- {specstream_client-1.3.3 → specstream_client-1.5.0}/specstream_client/client.py +213 -3
- {specstream_client-1.3.3 → specstream_client-1.5.0}/specstream_client/lifecycle_commands.py +128 -1
- specstream_client-1.5.0/specstream_client/monitors.py +387 -0
- specstream_client-1.5.0/tests/test_browser.py +229 -0
- specstream_client-1.5.0/tests/test_monitors.py +285 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/.gitignore +0 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/LICENSE +0 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/specstream_client/__main__.py +0 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/specstream_client/authorization.py +0 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/specstream_client/families.py +0 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/specstream_client/py.typed +0 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/tests/__init__.py +0 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/tests/test_cli.py +0 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/tests/test_client.py +0 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/tests/test_convergence.py +0 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/tests/test_http_boundary.py +0 -0
- {specstream_client-1.3.3 → specstream_client-1.5.0}/tests/test_m16_exports.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: specstream-client
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.5.0
|
|
4
4
|
Summary: Python client for building lead lists and company lists from the live web. Every match comes with its source, priced before it runs.
|
|
5
5
|
Project-URL: Homepage, https://specstream.ai
|
|
6
6
|
Project-URL: Documentation, https://specstream.ai/docs/sdk
|
|
@@ -42,7 +42,7 @@ The client has no dependencies and needs Python 3.12 or newer. It uses the same
|
|
|
42
42
|
pip install specstream-client
|
|
43
43
|
```
|
|
44
44
|
|
|
45
|
-
The package installs the import name `
|
|
45
|
+
The package installs the import name `specstream_client` and the command `specstream`.
|
|
46
46
|
|
|
47
47
|
Create an API key under **Agents & API** in your SpecStream workspace and keep it in the environment:
|
|
48
48
|
|
|
@@ -52,7 +52,7 @@ export SPECSTREAM_API_KEY="ss_live_..."
|
|
|
52
52
|
|
|
53
53
|
## Search the web
|
|
54
54
|
|
|
55
|
-
`web_search` calls the [Search API](https://specstream.ai/docs/search-api), `GET /v1/web-search`, at $5 per 1,000 searches of up to 10 results.
|
|
55
|
+
`web_search` calls the [Search API](https://specstream.ai/docs/search-api), `GET /v1/web-search`, at $5 per 1,000 searches of up to 10 results, or $1 on the fast tier.
|
|
56
56
|
|
|
57
57
|
```python
|
|
58
58
|
import os
|
|
@@ -82,7 +82,7 @@ for page in extract["results"][:1]:
|
|
|
82
82
|
|
|
83
83
|
## Drop-in for the API you already call
|
|
84
84
|
|
|
85
|
-
SpecStream answers calls written for these search APIs at its own address, in each API's own reply shape. To switch, change the base address and the key. Each search call is one Search API web search on your SpecStream key: $0.
|
|
85
|
+
SpecStream answers calls written for these search APIs at its own address, in each API's own reply shape. To switch, change the base address and the key. Each search call is one Search API web search on your SpecStream key. A drop-in call runs the fast search: $0.001 for up to 10 results ($1 per 1,000 searches), and each 10 results more in the same call add $0.0012. A call that asks for an answer or the API's thorough mode runs the default search: $0.005 for up to 10 results, and $0.006 for each 10 more.
|
|
86
86
|
|
|
87
87
|
| API you call | Base address you have | SpecStream address | Where the SpecStream key goes |
|
|
88
88
|
| --- | --- | --- | --- |
|
|
@@ -106,7 +106,7 @@ tavily = TavilyClient(api_key=os.environ["SPECSTREAM_API_KEY"], api_base_url="ht
|
|
|
106
106
|
exa = Exa(api_key=os.environ["SPECSTREAM_API_KEY"], base_url="https://api.specstream.ai/exa")
|
|
107
107
|
```
|
|
108
108
|
|
|
109
|
-
- A
|
|
109
|
+
- A call that names no result count returns 10 results, at $0.001 on the fast search. Brave's own default is 20: send `count=20` for 20 results at $0.0022.
|
|
110
110
|
- A Firecrawl `/v2/scrape` call is one Extract API page at $0.0008. The Firecrawl JavaScript SDK works with this address; the Firecrawl Python SDK does not yet.
|
|
111
111
|
- Each route's request and reply fields: [specstream.ai/agents.md](https://specstream.ai/agents.md). Create a key under **Agents & API** at [specstream.ai/workspace](https://specstream.ai/workspace). New accounts start with $10 of credit, no card.
|
|
112
112
|
|
|
@@ -151,11 +151,123 @@ If the response is lost, `get_capacity_request(saved_request_key)` returns the s
|
|
|
151
151
|
|
|
152
152
|
`authorize_capacity_work` refuses to send anything unless the quote, its signature, the maximum and the key are all present.
|
|
153
153
|
|
|
154
|
+
## Keep a list current on a schedule
|
|
155
|
+
|
|
156
|
+
A monitor checks a list again on the live web every hour, day, week or month ("month" is every 30 days).
|
|
157
|
+
Each check is a refresh: half the row rate for a row that changed or is new, and 1 cent for a row that comes back unchanged.
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
monitor = client.monitor_list(
|
|
161
|
+
find_id,
|
|
162
|
+
every="week",
|
|
163
|
+
max_price_per_run_usd=2,
|
|
164
|
+
max_price_per_month_usd=8,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
if monitor["status"] == "saved":
|
|
168
|
+
print(monitor["monitor_id"], monitor["next_run_at"])
|
|
169
|
+
else:
|
|
170
|
+
print(monitor["message"]) # "over_maximum": one check costs more than max_price_per_run_usd, nothing was saved
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
The client prices one check before it saves anything.
|
|
174
|
+
When one check can cost more than `max_price_per_run_usd`, nothing is saved.
|
|
175
|
+
`max_price_per_month_usd` is the most the monitor spends in one UTC calendar month, checks run on demand included.
|
|
176
|
+
Without it, the limit is `max_price_per_run_usd` times the checks in 31 days.
|
|
177
|
+
The first check runs one interval after the current hour began, and the monitor ends a year after it, unless you set `first_run_at=` and `ends_at=` (a `datetime` with a time zone or an ISO 8601 string).
|
|
178
|
+
The same call again in the same hour returns the monitor already saved, not a second one.
|
|
179
|
+
|
|
180
|
+
| Call | What it does | Cost |
|
|
181
|
+
| --- | --- | --- |
|
|
182
|
+
| `monitor_list(list_id, ...)` | Prices one check of the list and saves the schedule within your limits | Each check, within the limits |
|
|
183
|
+
| `monitors()` | Every monitor of the account, with its state, next check and last list | Free |
|
|
184
|
+
| `monitor_runs(monitor_id)` | The recent checks, newest first: when, the outcome, the reason and the list each one made | Free |
|
|
185
|
+
| `run_monitor_now(monitor_id)` | One check now, inside the monitor's limits. The regular times stay as they are | One check |
|
|
186
|
+
| `pause_monitor(monitor_id)`, `resume_monitor(monitor_id)` | Stops and starts the checks. A missed check is never bought later | Free |
|
|
187
|
+
| `delete_monitor(monitor_id)` | Ends the monitor. The lists it made stay yours | Free |
|
|
188
|
+
| `revisit(list_id)` | Each record of a refreshed list: still matches, no longer matches, unresolved or unavailable | Free |
|
|
189
|
+
|
|
190
|
+
A blocked or missed check is not an unchanged result, and it is not bought later.
|
|
191
|
+
For a calendar schedule (for example Mondays at 9:00 in your time zone), call `create_capacity_schedule` with the API's own fields, including `calendar_schedule`; `list_capacity_schedules`, `update_capacity_schedule`, `list_capacity_occurrences` and `run_capacity_schedule_now` are there too.
|
|
192
|
+
|
|
193
|
+
### Send new and changed records to a webhook
|
|
194
|
+
|
|
195
|
+
```python
|
|
196
|
+
delivery = client.set_monitor_delivery(monitor["monitor_id"], webhook="https://example.com/hooks/specstream")
|
|
197
|
+
signing_secret = delivery["webhook_secret"] # shown once: store it, never log it
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
`set_monitor_delivery` also takes `slack=` (a channel of your connected Slack workspace), `send_to=` (a connected tool) and `notify=` (SpecStream notifications). Nothing runs when you set it.
|
|
201
|
+
Slack and webhook delivery need a plan that includes deliveries.
|
|
202
|
+
|
|
203
|
+
Each delivery is a JSON POST with the headers `Specstream-Event-Id` and `Specstream-Signature: t=<unix time>,v1=<hex>`.
|
|
204
|
+
Check it before you trust the body, and use the event id to drop repeats:
|
|
205
|
+
|
|
206
|
+
```python
|
|
207
|
+
import json
|
|
208
|
+
import os
|
|
209
|
+
from specstream_client import verify_webhook
|
|
210
|
+
|
|
211
|
+
# In your web endpoint, with the raw request body
|
|
212
|
+
verify_webhook(
|
|
213
|
+
secret=os.environ["SPECSTREAM_WEBHOOK_SECRET"],
|
|
214
|
+
signature=request.headers["Specstream-Signature"],
|
|
215
|
+
body=raw_body,
|
|
216
|
+
) # raises SpecstreamError when the signature is wrong or older than 5 minutes
|
|
217
|
+
event = json.loads(raw_body)
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
## Drive a real browser
|
|
221
|
+
|
|
222
|
+
For a page that needs a real browser, `open_browser` starts a Chromium on SpecStream.
|
|
223
|
+
You drive it one step at a time, and `browser_read` returns the page's text as it stands after its JavaScript ran.
|
|
224
|
+
|
|
225
|
+
```python
|
|
226
|
+
with client.browser(timeout_s=120) as session:
|
|
227
|
+
client.browser_navigate(session["id"], "https://example.com")
|
|
228
|
+
print(client.browser_read(session["id"])) # Markdown; "text" for plain text
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
A session costs $0.10 an hour, charged by the second, plus $1 per 1,000 steps (0.1¢ a step).
|
|
232
|
+
An open session is charged until `timeout_s` passes, so close it: the `with` block does, also when a step fails.
|
|
233
|
+
|
|
234
|
+
| Call | What it does |
|
|
235
|
+
| --- | --- |
|
|
236
|
+
| `open_browser(timeout_s=..., allowed_domains=[...], ...)` | Opens a browser and returns the session, with its `id` and `connect_url` |
|
|
237
|
+
| `browser_navigate(session_id, url)` | Opens the address |
|
|
238
|
+
| `browser_read(session_id, format="markdown")` | The page's text, in Markdown or plain text |
|
|
239
|
+
| `browser_snapshot(session_id)` | The page's links, buttons and fields, each with a reference |
|
|
240
|
+
| `browser_step(session_id, tool, arguments)` | Any step of Playwright MCP by its name: `browser_click`, `browser_type`, `browser_take_screenshot` and the others |
|
|
241
|
+
| `browser_session(session_id)`, `browser_sessions(status="running")` | One session or the account's sessions, with seconds, steps and charge. Free |
|
|
242
|
+
| `browser_downloads(session_id)` | The files the browser downloaded, as the bytes of one zip, until ten minutes after the session ends. Free |
|
|
243
|
+
| `close_browser(session_id)` | Ends the session and returns it with `charged_usd` |
|
|
244
|
+
|
|
245
|
+
A page the browser may not open (a private address, a site that opted out, a host outside `allowed_domains`) is not an exception for a step: the answer's `error` holds the code `blocked` and the reason. `browser_read` raises `SpecstreamError` in that case.
|
|
246
|
+
|
|
247
|
+
Your own Playwright, Puppeteer, browser-use or Stagehand code can drive the same browser over the Chrome DevTools Protocol:
|
|
248
|
+
|
|
249
|
+
```python
|
|
250
|
+
from playwright.sync_api import sync_playwright
|
|
251
|
+
|
|
252
|
+
session = client.open_browser(timeout_s=300, idempotency_key="job-42")
|
|
253
|
+
try:
|
|
254
|
+
with sync_playwright() as p:
|
|
255
|
+
browser = p.chromium.connect_over_cdp(session["connect_url"])
|
|
256
|
+
context = browser.contexts[0] if browser.contexts else browser.new_context()
|
|
257
|
+
page = context.new_page()
|
|
258
|
+
page.goto("https://example.com")
|
|
259
|
+
print(page.title())
|
|
260
|
+
finally:
|
|
261
|
+
print(client.close_browser(session["id"])["charged_usd"])
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
With `idempotency_key`, the same call again answers with the same session and opens no second one.
|
|
265
|
+
|
|
154
266
|
## More than a first request
|
|
155
267
|
|
|
156
268
|
- `quote_capacity_work` also prices `extend` (more results), `add_facts` and `refresh` (a recheck, at half price) on a finished run. Pass the original `parent_find_id`.
|
|
157
269
|
- `spec_options(kind)` lists the facts you can ask for, per kind of thing. `edit_spec` changes a request without rereading it.
|
|
158
|
-
- `create_capacity_schedule` keeps
|
|
270
|
+
- `create_capacity_schedule` keeps any request up to date, hourly to yearly, inside per-run and per-period limits.
|
|
159
271
|
- `export` and `download_export` give CSV, XLSX, JSON or HTML. `create_customer_webhook` sends signed events.
|
|
160
272
|
- Projects, members, shares and starred items have their own methods.
|
|
161
273
|
|
|
@@ -15,7 +15,7 @@ The client has no dependencies and needs Python 3.12 or newer. It uses the same
|
|
|
15
15
|
pip install specstream-client
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
The package installs the import name `
|
|
18
|
+
The package installs the import name `specstream_client` and the command `specstream`.
|
|
19
19
|
|
|
20
20
|
Create an API key under **Agents & API** in your SpecStream workspace and keep it in the environment:
|
|
21
21
|
|
|
@@ -25,7 +25,7 @@ export SPECSTREAM_API_KEY="ss_live_..."
|
|
|
25
25
|
|
|
26
26
|
## Search the web
|
|
27
27
|
|
|
28
|
-
`web_search` calls the [Search API](https://specstream.ai/docs/search-api), `GET /v1/web-search`, at $5 per 1,000 searches of up to 10 results.
|
|
28
|
+
`web_search` calls the [Search API](https://specstream.ai/docs/search-api), `GET /v1/web-search`, at $5 per 1,000 searches of up to 10 results, or $1 on the fast tier.
|
|
29
29
|
|
|
30
30
|
```python
|
|
31
31
|
import os
|
|
@@ -55,7 +55,7 @@ for page in extract["results"][:1]:
|
|
|
55
55
|
|
|
56
56
|
## Drop-in for the API you already call
|
|
57
57
|
|
|
58
|
-
SpecStream answers calls written for these search APIs at its own address, in each API's own reply shape. To switch, change the base address and the key. Each search call is one Search API web search on your SpecStream key: $0.
|
|
58
|
+
SpecStream answers calls written for these search APIs at its own address, in each API's own reply shape. To switch, change the base address and the key. Each search call is one Search API web search on your SpecStream key. A drop-in call runs the fast search: $0.001 for up to 10 results ($1 per 1,000 searches), and each 10 results more in the same call add $0.0012. A call that asks for an answer or the API's thorough mode runs the default search: $0.005 for up to 10 results, and $0.006 for each 10 more.
|
|
59
59
|
|
|
60
60
|
| API you call | Base address you have | SpecStream address | Where the SpecStream key goes |
|
|
61
61
|
| --- | --- | --- | --- |
|
|
@@ -79,7 +79,7 @@ tavily = TavilyClient(api_key=os.environ["SPECSTREAM_API_KEY"], api_base_url="ht
|
|
|
79
79
|
exa = Exa(api_key=os.environ["SPECSTREAM_API_KEY"], base_url="https://api.specstream.ai/exa")
|
|
80
80
|
```
|
|
81
81
|
|
|
82
|
-
- A
|
|
82
|
+
- A call that names no result count returns 10 results, at $0.001 on the fast search. Brave's own default is 20: send `count=20` for 20 results at $0.0022.
|
|
83
83
|
- A Firecrawl `/v2/scrape` call is one Extract API page at $0.0008. The Firecrawl JavaScript SDK works with this address; the Firecrawl Python SDK does not yet.
|
|
84
84
|
- Each route's request and reply fields: [specstream.ai/agents.md](https://specstream.ai/agents.md). Create a key under **Agents & API** at [specstream.ai/workspace](https://specstream.ai/workspace). New accounts start with $10 of credit, no card.
|
|
85
85
|
|
|
@@ -124,11 +124,123 @@ If the response is lost, `get_capacity_request(saved_request_key)` returns the s
|
|
|
124
124
|
|
|
125
125
|
`authorize_capacity_work` refuses to send anything unless the quote, its signature, the maximum and the key are all present.
|
|
126
126
|
|
|
127
|
+
## Keep a list current on a schedule
|
|
128
|
+
|
|
129
|
+
A monitor checks a list again on the live web every hour, day, week or month ("month" is every 30 days).
|
|
130
|
+
Each check is a refresh: half the row rate for a row that changed or is new, and 1 cent for a row that comes back unchanged.
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
monitor = client.monitor_list(
|
|
134
|
+
find_id,
|
|
135
|
+
every="week",
|
|
136
|
+
max_price_per_run_usd=2,
|
|
137
|
+
max_price_per_month_usd=8,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
if monitor["status"] == "saved":
|
|
141
|
+
print(monitor["monitor_id"], monitor["next_run_at"])
|
|
142
|
+
else:
|
|
143
|
+
print(monitor["message"]) # "over_maximum": one check costs more than max_price_per_run_usd, nothing was saved
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The client prices one check before it saves anything.
|
|
147
|
+
When one check can cost more than `max_price_per_run_usd`, nothing is saved.
|
|
148
|
+
`max_price_per_month_usd` is the most the monitor spends in one UTC calendar month, checks run on demand included.
|
|
149
|
+
Without it, the limit is `max_price_per_run_usd` times the checks in 31 days.
|
|
150
|
+
The first check runs one interval after the current hour began, and the monitor ends a year after it, unless you set `first_run_at=` and `ends_at=` (a `datetime` with a time zone or an ISO 8601 string).
|
|
151
|
+
The same call again in the same hour returns the monitor already saved, not a second one.
|
|
152
|
+
|
|
153
|
+
| Call | What it does | Cost |
|
|
154
|
+
| --- | --- | --- |
|
|
155
|
+
| `monitor_list(list_id, ...)` | Prices one check of the list and saves the schedule within your limits | Each check, within the limits |
|
|
156
|
+
| `monitors()` | Every monitor of the account, with its state, next check and last list | Free |
|
|
157
|
+
| `monitor_runs(monitor_id)` | The recent checks, newest first: when, the outcome, the reason and the list each one made | Free |
|
|
158
|
+
| `run_monitor_now(monitor_id)` | One check now, inside the monitor's limits. The regular times stay as they are | One check |
|
|
159
|
+
| `pause_monitor(monitor_id)`, `resume_monitor(monitor_id)` | Stops and starts the checks. A missed check is never bought later | Free |
|
|
160
|
+
| `delete_monitor(monitor_id)` | Ends the monitor. The lists it made stay yours | Free |
|
|
161
|
+
| `revisit(list_id)` | Each record of a refreshed list: still matches, no longer matches, unresolved or unavailable | Free |
|
|
162
|
+
|
|
163
|
+
A blocked or missed check is not an unchanged result, and it is not bought later.
|
|
164
|
+
For a calendar schedule (for example Mondays at 9:00 in your time zone), call `create_capacity_schedule` with the API's own fields, including `calendar_schedule`; `list_capacity_schedules`, `update_capacity_schedule`, `list_capacity_occurrences` and `run_capacity_schedule_now` are there too.
|
|
165
|
+
|
|
166
|
+
### Send new and changed records to a webhook
|
|
167
|
+
|
|
168
|
+
```python
|
|
169
|
+
delivery = client.set_monitor_delivery(monitor["monitor_id"], webhook="https://example.com/hooks/specstream")
|
|
170
|
+
signing_secret = delivery["webhook_secret"] # shown once: store it, never log it
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`set_monitor_delivery` also takes `slack=` (a channel of your connected Slack workspace), `send_to=` (a connected tool) and `notify=` (SpecStream notifications). Nothing runs when you set it.
|
|
174
|
+
Slack and webhook delivery need a plan that includes deliveries.
|
|
175
|
+
|
|
176
|
+
Each delivery is a JSON POST with the headers `Specstream-Event-Id` and `Specstream-Signature: t=<unix time>,v1=<hex>`.
|
|
177
|
+
Check it before you trust the body, and use the event id to drop repeats:
|
|
178
|
+
|
|
179
|
+
```python
|
|
180
|
+
import json
|
|
181
|
+
import os
|
|
182
|
+
from specstream_client import verify_webhook
|
|
183
|
+
|
|
184
|
+
# In your web endpoint, with the raw request body
|
|
185
|
+
verify_webhook(
|
|
186
|
+
secret=os.environ["SPECSTREAM_WEBHOOK_SECRET"],
|
|
187
|
+
signature=request.headers["Specstream-Signature"],
|
|
188
|
+
body=raw_body,
|
|
189
|
+
) # raises SpecstreamError when the signature is wrong or older than 5 minutes
|
|
190
|
+
event = json.loads(raw_body)
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
## Drive a real browser
|
|
194
|
+
|
|
195
|
+
For a page that needs a real browser, `open_browser` starts a Chromium on SpecStream.
|
|
196
|
+
You drive it one step at a time, and `browser_read` returns the page's text as it stands after its JavaScript ran.
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
with client.browser(timeout_s=120) as session:
|
|
200
|
+
client.browser_navigate(session["id"], "https://example.com")
|
|
201
|
+
print(client.browser_read(session["id"])) # Markdown; "text" for plain text
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
A session costs $0.10 an hour, charged by the second, plus $1 per 1,000 steps (0.1¢ a step).
|
|
205
|
+
An open session is charged until `timeout_s` passes, so close it: the `with` block does, also when a step fails.
|
|
206
|
+
|
|
207
|
+
| Call | What it does |
|
|
208
|
+
| --- | --- |
|
|
209
|
+
| `open_browser(timeout_s=..., allowed_domains=[...], ...)` | Opens a browser and returns the session, with its `id` and `connect_url` |
|
|
210
|
+
| `browser_navigate(session_id, url)` | Opens the address |
|
|
211
|
+
| `browser_read(session_id, format="markdown")` | The page's text, in Markdown or plain text |
|
|
212
|
+
| `browser_snapshot(session_id)` | The page's links, buttons and fields, each with a reference |
|
|
213
|
+
| `browser_step(session_id, tool, arguments)` | Any step of Playwright MCP by its name: `browser_click`, `browser_type`, `browser_take_screenshot` and the others |
|
|
214
|
+
| `browser_session(session_id)`, `browser_sessions(status="running")` | One session or the account's sessions, with seconds, steps and charge. Free |
|
|
215
|
+
| `browser_downloads(session_id)` | The files the browser downloaded, as the bytes of one zip, until ten minutes after the session ends. Free |
|
|
216
|
+
| `close_browser(session_id)` | Ends the session and returns it with `charged_usd` |
|
|
217
|
+
|
|
218
|
+
A page the browser may not open (a private address, a site that opted out, a host outside `allowed_domains`) is not an exception for a step: the answer's `error` holds the code `blocked` and the reason. `browser_read` raises `SpecstreamError` in that case.
|
|
219
|
+
|
|
220
|
+
Your own Playwright, Puppeteer, browser-use or Stagehand code can drive the same browser over the Chrome DevTools Protocol:
|
|
221
|
+
|
|
222
|
+
```python
|
|
223
|
+
from playwright.sync_api import sync_playwright
|
|
224
|
+
|
|
225
|
+
session = client.open_browser(timeout_s=300, idempotency_key="job-42")
|
|
226
|
+
try:
|
|
227
|
+
with sync_playwright() as p:
|
|
228
|
+
browser = p.chromium.connect_over_cdp(session["connect_url"])
|
|
229
|
+
context = browser.contexts[0] if browser.contexts else browser.new_context()
|
|
230
|
+
page = context.new_page()
|
|
231
|
+
page.goto("https://example.com")
|
|
232
|
+
print(page.title())
|
|
233
|
+
finally:
|
|
234
|
+
print(client.close_browser(session["id"])["charged_usd"])
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
With `idempotency_key`, the same call again answers with the same session and opens no second one.
|
|
238
|
+
|
|
127
239
|
## More than a first request
|
|
128
240
|
|
|
129
241
|
- `quote_capacity_work` also prices `extend` (more results), `add_facts` and `refresh` (a recheck, at half price) on a finished run. Pass the original `parent_find_id`.
|
|
130
242
|
- `spec_options(kind)` lists the facts you can ask for, per kind of thing. `edit_spec` changes a request without rereading it.
|
|
131
|
-
- `create_capacity_schedule` keeps
|
|
243
|
+
- `create_capacity_schedule` keeps any request up to date, hourly to yearly, inside per-run and per-period limits.
|
|
132
244
|
- `export` and `download_export` give CSV, XLSX, JSON or HTML. `create_customer_webhook` sends signed events.
|
|
133
245
|
- Projects, members, shares and starred items have their own methods.
|
|
134
246
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "specstream-client"
|
|
3
|
-
version = "1.
|
|
3
|
+
version = "1.5.0"
|
|
4
4
|
description = "Python client for building lead lists and company lists from the live web. Every match comes with its source, priced before it runs."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.12"
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from specstream_client.client import DEFAULT_BASE_URL, Client, SpecstreamError
|
|
4
4
|
from specstream_client.families import FAMILIES, FAMILY_SET, assert_family
|
|
5
|
+
from specstream_client.monitors import verify_webhook
|
|
5
6
|
|
|
6
7
|
__all__ = [
|
|
7
8
|
"Client",
|
|
@@ -10,5 +11,6 @@ __all__ = [
|
|
|
10
11
|
"FAMILY_SET",
|
|
11
12
|
"SpecstreamError",
|
|
12
13
|
"assert_family",
|
|
14
|
+
"verify_webhook",
|
|
13
15
|
]
|
|
14
|
-
__version__ = "1.
|
|
16
|
+
__version__ = "1.5.0"
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Browser sessions: a real Chromium on SpecStream that your code drives.
|
|
2
|
+
|
|
3
|
+
A session is charged for each second it runs and for each step, until it is
|
|
4
|
+
closed or its timeout_s passes. Drive it step by step with browser_step (the
|
|
5
|
+
tools of Playwright MCP by name, plus browser_read for the page's text), or
|
|
6
|
+
connect Playwright, Puppeteer, browser-use or Stagehand to its connect_url over
|
|
7
|
+
the Chrome DevTools Protocol.
|
|
8
|
+
Client includes BrowserMixin, so these are methods of Client.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import copy
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.request
|
|
16
|
+
from collections.abc import Callable, Iterator
|
|
17
|
+
from contextlib import contextmanager
|
|
18
|
+
from typing import Any
|
|
19
|
+
from urllib.parse import quote as quote_path
|
|
20
|
+
from urllib.parse import urlencode, urljoin
|
|
21
|
+
|
|
22
|
+
SESSIONS_PATH = "/v1/browser/sessions"
|
|
23
|
+
SESSION_STATES = ("starting", "running", "ended")
|
|
24
|
+
READ_FORMATS = ("markdown", "text")
|
|
25
|
+
IDEMPOTENCY_KEY_MAX = 128
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class BrowserMixin:
|
|
29
|
+
"""Browser session calls of Client. They need Client's _request, _headers and _opener."""
|
|
30
|
+
|
|
31
|
+
_request: Callable[..., dict[str, Any]]
|
|
32
|
+
_headers: Callable[[], dict[str, str]]
|
|
33
|
+
_opener: Callable[..., Any]
|
|
34
|
+
base_url: str
|
|
35
|
+
timeout: float
|
|
36
|
+
|
|
37
|
+
def open_browser(
|
|
38
|
+
self,
|
|
39
|
+
*,
|
|
40
|
+
timeout_s: int | None = None,
|
|
41
|
+
idle_timeout_s: int | None = None,
|
|
42
|
+
keep_alive: bool | None = None,
|
|
43
|
+
headless: bool | None = None,
|
|
44
|
+
viewport: dict[str, int] | None = None,
|
|
45
|
+
allowed_domains: list[str] | None = None,
|
|
46
|
+
block_media: bool | None = None,
|
|
47
|
+
metadata: dict[str, Any] | None = None,
|
|
48
|
+
idempotency_key: str | None = None,
|
|
49
|
+
) -> dict[str, Any]:
|
|
50
|
+
"""POST /v1/browser/sessions: open a browser and return the running session.
|
|
51
|
+
|
|
52
|
+
The session holds its id, its connect_url (the Chrome DevTools Protocol
|
|
53
|
+
address) and its price. Charges start now: call close_browser when you
|
|
54
|
+
are done. timeout_s is the most seconds the session runs (60 to 3,600,
|
|
55
|
+
default 300). allowed_domains limits the hosts the browser may open.
|
|
56
|
+
A setting you leave out takes the API's default. With idempotency_key,
|
|
57
|
+
the same call again answers with the same session and opens no second one.
|
|
58
|
+
"""
|
|
59
|
+
settings = {
|
|
60
|
+
"timeout_s": timeout_s,
|
|
61
|
+
"idle_timeout_s": idle_timeout_s,
|
|
62
|
+
"keep_alive": keep_alive,
|
|
63
|
+
"headless": headless,
|
|
64
|
+
"viewport": viewport,
|
|
65
|
+
"allowed_domains": allowed_domains,
|
|
66
|
+
"block_media": block_media,
|
|
67
|
+
"metadata": metadata,
|
|
68
|
+
}
|
|
69
|
+
body = {name: value for name, value in settings.items() if value is not None}
|
|
70
|
+
if idempotency_key is None:
|
|
71
|
+
return self._request("POST", SESSIONS_PATH, body)
|
|
72
|
+
key = str(idempotency_key).strip()
|
|
73
|
+
if not key or len(key) > IDEMPOTENCY_KEY_MAX:
|
|
74
|
+
raise ValueError(f"idempotency_key must hold 1 to {IDEMPOTENCY_KEY_MAX} characters")
|
|
75
|
+
# A copy of the client whose requests carry the key: _request stays as it is,
|
|
76
|
+
# with its errors and its one retry after Retry-After.
|
|
77
|
+
keyed = copy.copy(self)
|
|
78
|
+
send = self._opener
|
|
79
|
+
|
|
80
|
+
def with_key(request: urllib.request.Request, timeout: float) -> Any:
|
|
81
|
+
request.add_header("Idempotency-Key", key)
|
|
82
|
+
return send(request, timeout)
|
|
83
|
+
|
|
84
|
+
keyed._opener = with_key
|
|
85
|
+
return keyed._request("POST", SESSIONS_PATH, body)
|
|
86
|
+
|
|
87
|
+
def browser_sessions(
|
|
88
|
+
self,
|
|
89
|
+
*,
|
|
90
|
+
status: str | None = None,
|
|
91
|
+
limit: int | None = None,
|
|
92
|
+
cursor: str | None = None,
|
|
93
|
+
) -> dict[str, Any]:
|
|
94
|
+
"""GET /v1/browser/sessions: the account's sessions, newest first.
|
|
95
|
+
|
|
96
|
+
Returns {"sessions": [...], "next_cursor": ...}. status is "starting",
|
|
97
|
+
"running" or "ended". Pass next_cursor as cursor for the next page.
|
|
98
|
+
"""
|
|
99
|
+
if status is not None and status not in SESSION_STATES:
|
|
100
|
+
raise ValueError('status must be "starting", "running" or "ended"')
|
|
101
|
+
query = {
|
|
102
|
+
name: value
|
|
103
|
+
for name, value in (("status", status), ("limit", limit), ("cursor", cursor))
|
|
104
|
+
if value is not None
|
|
105
|
+
}
|
|
106
|
+
path = SESSIONS_PATH + (f"?{urlencode(query)}" if query else "")
|
|
107
|
+
return self._request("GET", path, None)
|
|
108
|
+
|
|
109
|
+
def browser_session(self, session_id: str) -> dict[str, Any]:
|
|
110
|
+
"""GET /v1/browser/sessions/{id}: status, why it ended, seconds, steps and charge."""
|
|
111
|
+
return self._request("GET", _session_path(session_id), None)
|
|
112
|
+
|
|
113
|
+
def close_browser(self, session_id: str) -> dict[str, Any]:
|
|
114
|
+
"""POST /v1/browser/sessions/{id}/release: end the session and settle its charge.
|
|
115
|
+
|
|
116
|
+
Returns the ended session with charged_usd. A repeat call answers the same.
|
|
117
|
+
"""
|
|
118
|
+
return self._request("POST", _session_path(session_id) + "/release", {})
|
|
119
|
+
|
|
120
|
+
def browser_step(
|
|
121
|
+
self, session_id: str, tool: str, arguments: dict[str, Any] | None = None
|
|
122
|
+
) -> dict[str, Any]:
|
|
123
|
+
"""POST /v1/browser/sessions/{id}/actions: run one step in the browser.
|
|
124
|
+
|
|
125
|
+
tool is a Playwright MCP tool by its name (browser_navigate,
|
|
126
|
+
browser_snapshot, browser_click, browser_type, browser_take_screenshot
|
|
127
|
+
and the others) or browser_read. Returns the step's result, the page's
|
|
128
|
+
url and title, and price_usd. A page the browser may not open does not
|
|
129
|
+
raise: the answer's error holds code "blocked" and the reason.
|
|
130
|
+
"""
|
|
131
|
+
name = str(tool or "").strip()
|
|
132
|
+
if not name.startswith("browser_"):
|
|
133
|
+
raise ValueError('tool is a step name that starts with "browser_"')
|
|
134
|
+
body = {"tool": name, "arguments": dict(arguments or {})}
|
|
135
|
+
return self._request("POST", _session_path(session_id) + "/actions", body)
|
|
136
|
+
|
|
137
|
+
def browser_navigate(self, session_id: str, url: str) -> dict[str, Any]:
|
|
138
|
+
"""One step: open the address in the session's browser."""
|
|
139
|
+
address = str(url or "").strip()
|
|
140
|
+
if not address:
|
|
141
|
+
raise ValueError("Give the url to open")
|
|
142
|
+
return self.browser_step(session_id, "browser_navigate", {"url": address})
|
|
143
|
+
|
|
144
|
+
def browser_snapshot(self, session_id: str) -> dict[str, Any]:
|
|
145
|
+
"""One step: the page's links, buttons and fields, each with a reference to act on."""
|
|
146
|
+
return self.browser_step(session_id, "browser_snapshot")
|
|
147
|
+
|
|
148
|
+
def browser_read(self, session_id: str, format: str = "markdown") -> str:
|
|
149
|
+
"""One step: the page's text as it stands after its JavaScript ran.
|
|
150
|
+
|
|
151
|
+
format is "markdown" or "text". Raises SpecstreamError when the step
|
|
152
|
+
answers with an error, for example a page the browser may not open.
|
|
153
|
+
"""
|
|
154
|
+
if format not in READ_FORMATS:
|
|
155
|
+
raise ValueError('format must be "markdown" or "text"')
|
|
156
|
+
step = self.browser_step(session_id, "browser_read", {"format": format})
|
|
157
|
+
failure = step.get("error")
|
|
158
|
+
if failure:
|
|
159
|
+
from specstream_client.client import SpecstreamError
|
|
160
|
+
|
|
161
|
+
message = failure.get("message") if isinstance(failure, dict) else None
|
|
162
|
+
raise SpecstreamError(f"browser_read failed: {message or failure}", body=step)
|
|
163
|
+
return step_text(step)
|
|
164
|
+
|
|
165
|
+
def browser_downloads(self, session_id: str) -> bytes:
|
|
166
|
+
"""GET /v1/browser/sessions/{id}/downloads: the files the browser downloaded, as one zip.
|
|
167
|
+
|
|
168
|
+
They are kept until ten minutes after the session ends.
|
|
169
|
+
"""
|
|
170
|
+
from specstream_client.client import SpecstreamError
|
|
171
|
+
|
|
172
|
+
path = _session_path(session_id) + "/downloads"
|
|
173
|
+
request = urllib.request.Request(
|
|
174
|
+
urljoin(self.base_url, path.lstrip("/")), method="GET", headers=self._headers()
|
|
175
|
+
)
|
|
176
|
+
try:
|
|
177
|
+
with self._opener(request, self.timeout) as response:
|
|
178
|
+
status = getattr(response, "status", 200)
|
|
179
|
+
content = response.read()
|
|
180
|
+
except urllib.error.HTTPError as exc:
|
|
181
|
+
raise SpecstreamError(
|
|
182
|
+
f"GET {path} failed with HTTP {exc.code}", status=exc.code
|
|
183
|
+
) from exc
|
|
184
|
+
except (urllib.error.URLError, OSError) as exc:
|
|
185
|
+
raise SpecstreamError(f"GET {path} transport failed") from exc
|
|
186
|
+
if not 200 <= status < 300:
|
|
187
|
+
raise SpecstreamError(f"GET {path} failed with HTTP {status}", status=status)
|
|
188
|
+
return bytes(content)
|
|
189
|
+
|
|
190
|
+
@contextmanager
|
|
191
|
+
def browser(self, **settings: Any) -> Iterator[dict[str, Any]]:
|
|
192
|
+
"""Open a browser for a with block and close it at the end, also after an error.
|
|
193
|
+
|
|
194
|
+
Takes the arguments of open_browser and yields the session.
|
|
195
|
+
"""
|
|
196
|
+
session = self.open_browser(**settings)
|
|
197
|
+
try:
|
|
198
|
+
yield session
|
|
199
|
+
finally:
|
|
200
|
+
self.close_browser(session["id"])
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def step_text(step: dict[str, Any]) -> str:
|
|
204
|
+
"""The text parts of a step's result, joined."""
|
|
205
|
+
parts = step.get("result")
|
|
206
|
+
if not isinstance(parts, list):
|
|
207
|
+
return ""
|
|
208
|
+
return "\n".join(
|
|
209
|
+
part["text"]
|
|
210
|
+
for part in parts
|
|
211
|
+
if isinstance(part, dict)
|
|
212
|
+
and part.get("type") == "text"
|
|
213
|
+
and isinstance(part.get("text"), str)
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _session_path(session_id: str) -> str:
|
|
218
|
+
value = str(session_id or "").strip()
|
|
219
|
+
if not value:
|
|
220
|
+
raise ValueError("Give the session's id, from open_browser")
|
|
221
|
+
return f"{SESSIONS_PATH}/{quote_path(value, safe='')}"
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
__all__ = ["BrowserMixin", "step_text"]
|
|
@@ -75,7 +75,8 @@ def _parser() -> argparse.ArgumentParser:
|
|
|
75
75
|
options["action"] = argparse.BooleanOptionalAction
|
|
76
76
|
else:
|
|
77
77
|
options["type"] = int if kind == "integer" else str
|
|
78
|
-
|
|
78
|
+
flag = "--" + parameter.rstrip("_").replace("_", "-")
|
|
79
|
+
command.add_argument(flag, dest=parameter, **options)
|
|
79
80
|
return parser
|
|
80
81
|
|
|
81
82
|
|