Repository navigation
Expand file tree
/
Copy pathspecstream_client.py
More file actions
141 lines (116 loc) · 6.05 KB
/
Copy pathspecstream_client.py
File metadata and controls
141 lines (116 loc) · 6.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"""A small SpecStream client, standard library only.
web_search("who makes the X200 forklift", speed="fast") POST /v1/web-search, $1 per 1,000 on the fast tier
extract(["https://example.com/pricing"]) POST /v1/extract, $0.80 per 1,000 pages read
A busy answer (503 or 429 with Retry-After) is sent again after the wait the API names, so a batch
keeps the account's pace. An extract retry carries the same Idempotency-Key, so a page is paid once.
Reads SPECSTREAM_API_KEY, and SPECSTREAM_API_BASE (https://api.specstream.ai by default).
"""
from __future__ import annotations
import json
import os
import time
import urllib.error
import urllib.request
import uuid
USER_AGENT = "temporal-workflow-specstream-agent/1.0"
FAST_USD, DEFAULT_USD, PAGE_USD = 0.001, 0.005, 0.0008
class SpecStreamError(RuntimeError):
def __init__(self, status: int, code: str, message: str):
super().__init__(f"HTTP {status} {code}: {message}")
self.status, self.code, self.message = status, code, message
def api_base() -> str:
return os.environ.get("SPECSTREAM_API_BASE", "https://api.specstream.ai").rstrip("/")
def api_key(key: str | None = None) -> str:
key = key or os.environ.get("SPECSTREAM_API_KEY", "")
if not key:
raise SpecStreamError(401, "missing_api_key", "Set SPECSTREAM_API_KEY. Create a key under Agents & API at https://specstream.ai/workspace")
return key
def _error(status: int, raw: bytes) -> SpecStreamError:
try:
err = json.loads(raw or b"{}").get("error") or {}
except ValueError:
err = {}
if not isinstance(err, dict):
err = {"message": str(err)}
return SpecStreamError(status, str(err.get("code") or err.get("type") or "error"), str(err.get("message") or raw[:200].decode("utf-8", "replace")))
def post(path: str, body: dict, *, key: str | None = None, base: str | None = None, headers: dict | None = None,
retries: int = 4, max_wait: float = 30.0, timeout: float = 120.0, sleep=time.sleep) -> dict:
"""POST a JSON body and return the reply's `data`. Waits and sends again on 503 or 429."""
request_headers = {"Authorization": f"Bearer {api_key(key)}", "Content-Type": "application/json",
"Accept": "application/json", "User-Agent": USER_AGENT, **(headers or {})}
data = json.dumps(body).encode()
for attempt in range(retries + 1):
request = urllib.request.Request((base or api_base()) + path, data=data, headers=request_headers, method="POST")
try:
with urllib.request.urlopen(request, timeout=timeout) as reply:
return json.load(reply).get("data") or {}
except urllib.error.HTTPError as error:
with error:
raw = error.read()
wait = error.headers.get("Retry-After")
if error.code in (429, 503) and attempt < retries:
try:
pause = float(wait) if wait is not None else 2.0 ** attempt
except ValueError:
pause = 2.0 ** attempt
sleep(min(max(pause, 0.0), max_wait))
continue
raise _error(error.code, raw) from None
raise AssertionError("unreachable")
def web_search(q: str, *, speed: str = "fast", num: int | None = None, country: str | None = None,
language: str | None = None, **options) -> dict:
"""One search. speed="fast" is $1 per 1,000 calls of up to 10 results; the default tier is $5 per 1,000."""
body = {"q": q, "speed": speed}
for name, value in (("num", num), ("country", country), ("language", language)):
if value is not None:
body[name] = value
call = {k: options.pop(k) for k in ("key", "base", "retries", "max_wait", "timeout", "sleep") if k in options}
body.update(options)
return post("/v1/web-search", body, **call)
def extract(urls: list[str], *, query: str | None = None, max_chars: int | None = None, fmt: str = "markdown",
idempotency_key: str | None = None, **call) -> dict:
"""Read up to 20 pages as Markdown. $0.80 per 1,000 pages read (status ok)."""
if not 1 <= len(urls) <= 20:
raise ValueError("Send 1 to 20 URLs per extract call.")
body: dict = {"urls": list(urls), "format": fmt}
if query:
body["query"] = query
if max_chars:
body["max_chars"] = max_chars
# One key for every retry of this call: the API replays a paid reply instead of reading again.
headers = {"Idempotency-Key": idempotency_key or uuid.uuid4().hex}
return post("/v1/extract", body, headers=headers, **call)
def sources(data: dict) -> list[dict]:
"""The ranked sources of a search reply, with every field present (None when the page states none)."""
out = []
for rank, source in enumerate(data.get("sources") or [], 1):
if not isinstance(source, dict) or not source.get("url"):
continue
out.append({
"rank": rank,
"url": source["url"],
"title": source.get("title") or "",
"site": source.get("site") or "",
"snippet": source.get("snippet") or "",
"published": source.get("published") or None,
})
return out
def answer(data: dict) -> tuple[str | None, str | None]:
"""The answer value and the page it was read from, or (None, None) when the search has no single answer."""
found = data.get("answer") or {}
return (found.get("value") or None, found.get("page") or None) if isinstance(found, dict) else (None, None)
def pages(data: dict) -> list[dict]:
"""The pages of an extract reply: url, status, title, published, text ('' for a page not read)."""
out = []
for item in data.get("results") or []:
if not isinstance(item, dict):
continue
ok = item.get("status") == "ok"
out.append({
"url": item.get("url") or "",
"status": item.get("status") or "error",
"title": item.get("title") or "",
"published": item.get("published") or None,
"text": (item.get("text") or "") if ok else "",
})
return out