browserwhale 0.1.0b1__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.
- browserwhale/__init__.py +109 -0
- browserwhale/_client.py +457 -0
- browserwhale/_errors.py +129 -0
- browserwhale/_types.py +244 -0
- browserwhale/py.typed +0 -0
- browserwhale-0.1.0b1.dist-info/METADATA +129 -0
- browserwhale-0.1.0b1.dist-info/RECORD +10 -0
- browserwhale-0.1.0b1.dist-info/WHEEL +4 -0
- browserwhale-0.1.0b1.dist-info/licenses/LICENSE +202 -0
- browserwhale-0.1.0b1.dist-info/licenses/NOTICE +4 -0
browserwhale/__init__.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Python client for the hosted Browserwhale API.
|
|
2
|
+
|
|
3
|
+
>>> from browserwhale import Whale
|
|
4
|
+
>>> task = Whale().run(url="https://example.com", goal="Find the page's main heading.")
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from ._client import (
|
|
8
|
+
Response,
|
|
9
|
+
ServerSentEvent,
|
|
10
|
+
StreamResponse,
|
|
11
|
+
StreamTransport,
|
|
12
|
+
Tasks,
|
|
13
|
+
Transport,
|
|
14
|
+
Whale,
|
|
15
|
+
urllib_stream_transport,
|
|
16
|
+
urllib_transport,
|
|
17
|
+
)
|
|
18
|
+
from ._errors import (
|
|
19
|
+
APIConnectionError,
|
|
20
|
+
ApiError,
|
|
21
|
+
AuthenticationError,
|
|
22
|
+
ConflictError,
|
|
23
|
+
InternalServerError,
|
|
24
|
+
InvalidRequestError,
|
|
25
|
+
NotFoundError,
|
|
26
|
+
PermissionDeniedError,
|
|
27
|
+
RateLimitError,
|
|
28
|
+
TaskFailedError,
|
|
29
|
+
WaitTimeoutError,
|
|
30
|
+
WhaleError,
|
|
31
|
+
)
|
|
32
|
+
from ._types import (
|
|
33
|
+
CreateTaskParams,
|
|
34
|
+
JsonSchema,
|
|
35
|
+
JsonValue,
|
|
36
|
+
ModelProvider,
|
|
37
|
+
SkillId,
|
|
38
|
+
StoredDataMode,
|
|
39
|
+
StepEvent,
|
|
40
|
+
StatusEvent,
|
|
41
|
+
DoneEvent,
|
|
42
|
+
Task,
|
|
43
|
+
TaskEvent,
|
|
44
|
+
TaskCause,
|
|
45
|
+
TaskChangeEvidence,
|
|
46
|
+
TaskConfirmation,
|
|
47
|
+
TaskEvidence,
|
|
48
|
+
TaskLimitation,
|
|
49
|
+
TaskLimits,
|
|
50
|
+
TaskList,
|
|
51
|
+
TaskModel,
|
|
52
|
+
TaskResult,
|
|
53
|
+
TaskStatus,
|
|
54
|
+
TaskStep,
|
|
55
|
+
TaskUsage,
|
|
56
|
+
TaskValueEvidence,
|
|
57
|
+
Usage,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
__version__ = "0.1.0b1"
|
|
61
|
+
|
|
62
|
+
__all__ = [
|
|
63
|
+
"Whale",
|
|
64
|
+
"Tasks",
|
|
65
|
+
"Transport",
|
|
66
|
+
"Response",
|
|
67
|
+
"urllib_transport",
|
|
68
|
+
"StreamTransport",
|
|
69
|
+
"StreamResponse",
|
|
70
|
+
"ServerSentEvent",
|
|
71
|
+
"urllib_stream_transport",
|
|
72
|
+
"WhaleError",
|
|
73
|
+
"ApiError",
|
|
74
|
+
"InvalidRequestError",
|
|
75
|
+
"AuthenticationError",
|
|
76
|
+
"PermissionDeniedError",
|
|
77
|
+
"NotFoundError",
|
|
78
|
+
"ConflictError",
|
|
79
|
+
"RateLimitError",
|
|
80
|
+
"InternalServerError",
|
|
81
|
+
"APIConnectionError",
|
|
82
|
+
"TaskFailedError",
|
|
83
|
+
"WaitTimeoutError",
|
|
84
|
+
"Task",
|
|
85
|
+
"TaskStatus",
|
|
86
|
+
"TaskCause",
|
|
87
|
+
"TaskConfirmation",
|
|
88
|
+
"TaskEvidence",
|
|
89
|
+
"TaskValueEvidence",
|
|
90
|
+
"TaskChangeEvidence",
|
|
91
|
+
"TaskResult",
|
|
92
|
+
"TaskLimitation",
|
|
93
|
+
"TaskStep",
|
|
94
|
+
"TaskEvent",
|
|
95
|
+
"StepEvent",
|
|
96
|
+
"StatusEvent",
|
|
97
|
+
"DoneEvent",
|
|
98
|
+
"SkillId",
|
|
99
|
+
"StoredDataMode",
|
|
100
|
+
"TaskUsage",
|
|
101
|
+
"Usage",
|
|
102
|
+
"TaskLimits",
|
|
103
|
+
"TaskList",
|
|
104
|
+
"CreateTaskParams",
|
|
105
|
+
"TaskModel",
|
|
106
|
+
"ModelProvider",
|
|
107
|
+
"JsonSchema",
|
|
108
|
+
"JsonValue",
|
|
109
|
+
]
|
browserwhale/_client.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import random
|
|
6
|
+
import time
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
import uuid
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Union, cast
|
|
13
|
+
|
|
14
|
+
from ._errors import (
|
|
15
|
+
APIConnectionError,
|
|
16
|
+
ApiError,
|
|
17
|
+
RateLimitError,
|
|
18
|
+
TaskFailedError,
|
|
19
|
+
WaitTimeoutError,
|
|
20
|
+
WhaleError,
|
|
21
|
+
error_from_response,
|
|
22
|
+
)
|
|
23
|
+
from ._types import (
|
|
24
|
+
ACTIVE_STATUSES,
|
|
25
|
+
CreateTaskParams,
|
|
26
|
+
JsonSchema,
|
|
27
|
+
JsonValue,
|
|
28
|
+
SkillId,
|
|
29
|
+
StoredDataMode,
|
|
30
|
+
Task,
|
|
31
|
+
TaskEvent,
|
|
32
|
+
TaskLimits,
|
|
33
|
+
TaskList,
|
|
34
|
+
TaskModel,
|
|
35
|
+
TaskStep,
|
|
36
|
+
Usage,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
MAX_WAIT_SECONDS = 30
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Response:
|
|
44
|
+
status: int
|
|
45
|
+
#: Lower-case header names.
|
|
46
|
+
headers: Dict[str, str]
|
|
47
|
+
body: bytes
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
#: Sends one request: ``(method, url, headers, body, timeout_seconds) -> Response``.
|
|
51
|
+
#: Raises ``OSError`` (or a subclass) when no response arrives.
|
|
52
|
+
Transport = Callable[[str, str, Dict[str, str], Optional[bytes], float], Response]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def urllib_transport(
|
|
56
|
+
method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float
|
|
57
|
+
) -> Response:
|
|
58
|
+
"""The default transport: the standard library's ``urllib``, no dependencies."""
|
|
59
|
+
request = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
60
|
+
try:
|
|
61
|
+
with urllib.request.urlopen(request, timeout=timeout) as reply:
|
|
62
|
+
return Response(
|
|
63
|
+
reply.status, {k.lower(): v for k, v in reply.headers.items()}, reply.read()
|
|
64
|
+
)
|
|
65
|
+
except urllib.error.HTTPError as error:
|
|
66
|
+
return Response(
|
|
67
|
+
error.code, {k.lower(): v for k, v in error.headers.items()}, error.read()
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class StreamResponse:
|
|
73
|
+
"""An open response whose body is read line by line (``text/event-stream``)."""
|
|
74
|
+
|
|
75
|
+
status: int
|
|
76
|
+
#: Lower-case header names.
|
|
77
|
+
headers: Dict[str, str]
|
|
78
|
+
#: The body's lines, line ends included; reading may raise ``OSError``.
|
|
79
|
+
lines: Iterable[bytes]
|
|
80
|
+
close: Callable[[], None]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
#: Opens one streaming GET: ``(url, headers, timeout_seconds) -> StreamResponse``, where
|
|
84
|
+
#: the timeout applies to each read. Raises ``OSError`` (or a subclass) when no response arrives.
|
|
85
|
+
StreamTransport = Callable[[str, Dict[str, str], float], StreamResponse]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def urllib_stream_transport(url: str, headers: Dict[str, str], timeout: float) -> StreamResponse:
|
|
89
|
+
"""The default stream transport: the standard library's ``urllib``."""
|
|
90
|
+
request = urllib.request.Request(url, headers=headers, method="GET")
|
|
91
|
+
try:
|
|
92
|
+
reply = urllib.request.urlopen(request, timeout=timeout)
|
|
93
|
+
except urllib.error.HTTPError as error:
|
|
94
|
+
body = error.read()
|
|
95
|
+
error.close()
|
|
96
|
+
return StreamResponse(
|
|
97
|
+
error.code, {k.lower(): v for k, v in error.headers.items()}, [body], lambda: None
|
|
98
|
+
)
|
|
99
|
+
return StreamResponse(
|
|
100
|
+
reply.status, {k.lower(): v for k, v in reply.headers.items()}, iter(reply.readline, b""),
|
|
101
|
+
reply.close,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass
|
|
106
|
+
class ServerSentEvent:
|
|
107
|
+
event: str
|
|
108
|
+
data: str
|
|
109
|
+
id: Optional[str] = None
|
|
110
|
+
retry: Optional[int] = None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def parse_event_stream(lines: Iterable[bytes]) -> Iterator[ServerSentEvent]:
|
|
114
|
+
"""Parses ``text/event-stream`` lines into events (``event``, ``data``, ``id``, ``retry``, comments)."""
|
|
115
|
+
event: Optional[str] = None
|
|
116
|
+
data: List[str] = []
|
|
117
|
+
event_id: Optional[str] = None
|
|
118
|
+
retry: Optional[int] = None
|
|
119
|
+
for raw in lines:
|
|
120
|
+
for line in raw.decode("utf-8").splitlines() or [""]:
|
|
121
|
+
if line == "":
|
|
122
|
+
if data or retry is not None:
|
|
123
|
+
yield ServerSentEvent(
|
|
124
|
+
event or "message" if data else "", "\n".join(data), event_id, retry
|
|
125
|
+
)
|
|
126
|
+
event, data, event_id, retry = None, [], None, None
|
|
127
|
+
continue
|
|
128
|
+
if line.startswith(":"):
|
|
129
|
+
continue
|
|
130
|
+
field, _, value = line.partition(":")
|
|
131
|
+
if value.startswith(" "):
|
|
132
|
+
value = value[1:]
|
|
133
|
+
if field == "event":
|
|
134
|
+
event = value
|
|
135
|
+
elif field == "data":
|
|
136
|
+
data.append(value)
|
|
137
|
+
elif field == "id" and "\0" not in value:
|
|
138
|
+
event_id = value
|
|
139
|
+
elif field == "retry" and value.isdigit():
|
|
140
|
+
retry = int(value)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _retryable(error: ApiError) -> bool:
|
|
144
|
+
return error.status == 429 or error.status >= 500
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _backoff(attempt: int) -> float:
|
|
148
|
+
return min(8.0, 0.5 * 2**attempt) * (0.5 + random.random() / 2)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class Whale:
|
|
152
|
+
"""Client for the hosted Browserwhale API.
|
|
153
|
+
|
|
154
|
+
``api_key`` and ``base_url`` default to ``BROWSERWHALE_API_KEY`` and
|
|
155
|
+
``BROWSERWHALE_BASE_URL``. Requests after a 429, a 5xx or a network
|
|
156
|
+
failure are retried ``max_retries`` times, reusing the same
|
|
157
|
+
``Idempotency-Key``. ``timeout`` is per request, excluding long-poll waits.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
def __init__(
|
|
161
|
+
self,
|
|
162
|
+
api_key: Optional[str] = None,
|
|
163
|
+
base_url: Optional[str] = None,
|
|
164
|
+
*,
|
|
165
|
+
max_retries: int = 2,
|
|
166
|
+
timeout: float = 60.0,
|
|
167
|
+
transport: Optional[Transport] = None,
|
|
168
|
+
stream_transport: Optional[StreamTransport] = None,
|
|
169
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
170
|
+
) -> None:
|
|
171
|
+
api_key = api_key or os.environ.get("BROWSERWHALE_API_KEY")
|
|
172
|
+
base_url = base_url or os.environ.get("BROWSERWHALE_BASE_URL")
|
|
173
|
+
if not api_key:
|
|
174
|
+
raise WhaleError("Missing api_key (or BROWSERWHALE_API_KEY).")
|
|
175
|
+
if not base_url:
|
|
176
|
+
raise WhaleError("Missing base_url (or BROWSERWHALE_BASE_URL).")
|
|
177
|
+
self._api_key = api_key
|
|
178
|
+
self._base_url = base_url.rstrip("/")
|
|
179
|
+
self._max_retries = max_retries
|
|
180
|
+
self._timeout = timeout
|
|
181
|
+
self._transport = transport or urllib_transport
|
|
182
|
+
self._stream_transport = stream_transport or urllib_stream_transport
|
|
183
|
+
self._sleep = sleep
|
|
184
|
+
self.tasks = Tasks(self)
|
|
185
|
+
|
|
186
|
+
def usage(self, *, month: Optional[str] = None) -> Usage:
|
|
187
|
+
"""This key's usage and cost for a calendar month (``YYYY-MM``, UTC); the current month by default."""
|
|
188
|
+
return cast(Usage, self._request("GET", "/v1/usage", query={"month": month}))
|
|
189
|
+
|
|
190
|
+
def run(
|
|
191
|
+
self,
|
|
192
|
+
url: Optional[str],
|
|
193
|
+
goal: str,
|
|
194
|
+
*,
|
|
195
|
+
session_id: Optional[str] = None,
|
|
196
|
+
output_schema: Optional[JsonSchema] = None,
|
|
197
|
+
variables: Optional[Dict[str, JsonValue]] = None,
|
|
198
|
+
limits: Optional[TaskLimits] = None,
|
|
199
|
+
metadata: Optional[Dict[str, JsonValue]] = None,
|
|
200
|
+
webhook_url: Optional[str] = None,
|
|
201
|
+
notes: Optional[str] = None,
|
|
202
|
+
skills: Union[str, List[SkillId], None] = None,
|
|
203
|
+
cache: Optional[StoredDataMode] = None,
|
|
204
|
+
site_context: Optional[StoredDataMode] = None,
|
|
205
|
+
vision: Optional[str] = None,
|
|
206
|
+
model: Optional[TaskModel] = None,
|
|
207
|
+
on_progress: Optional[Callable[[TaskStep], None]] = None,
|
|
208
|
+
idempotency_key: Optional[str] = None,
|
|
209
|
+
timeout: float = 15 * 60,
|
|
210
|
+
) -> Task:
|
|
211
|
+
"""Creates a task and waits until it finishes.
|
|
212
|
+
|
|
213
|
+
Returns the task when it is ``completed``; raises ``TaskFailedError``
|
|
214
|
+
(carrying the task) for any other final status and
|
|
215
|
+
``WaitTimeoutError`` after ``timeout`` seconds. With ``session_id`` the
|
|
216
|
+
task runs in that open session, and ``url`` may be ``None`` to continue
|
|
217
|
+
on the page the previous task ended on. ``notes``, ``skills``,
|
|
218
|
+
``cache``, ``site_context`` and ``vision`` are the opt-in features, off
|
|
219
|
+
by default. ``model`` runs the task with your own model provider key,
|
|
220
|
+
which the service never stores. With ``on_progress`` the client follows the task's live
|
|
221
|
+
events and calls it with each new step; otherwise it long-polls.
|
|
222
|
+
Interrupting it (``KeyboardInterrupt``) cancels the task; ``timeout``
|
|
223
|
+
only stops waiting.
|
|
224
|
+
"""
|
|
225
|
+
params: CreateTaskParams = {"goal": goal}
|
|
226
|
+
if url is not None:
|
|
227
|
+
params["url"] = url
|
|
228
|
+
if session_id is not None:
|
|
229
|
+
params["session_id"] = session_id
|
|
230
|
+
if output_schema is not None:
|
|
231
|
+
params["output_schema"] = output_schema
|
|
232
|
+
if variables is not None:
|
|
233
|
+
params["variables"] = variables
|
|
234
|
+
if limits is not None:
|
|
235
|
+
params["limits"] = limits
|
|
236
|
+
if metadata is not None:
|
|
237
|
+
params["metadata"] = metadata
|
|
238
|
+
if webhook_url is not None:
|
|
239
|
+
params["webhook_url"] = webhook_url
|
|
240
|
+
if notes is not None:
|
|
241
|
+
params["notes"] = notes
|
|
242
|
+
if skills is not None:
|
|
243
|
+
params["skills"] = cast(Any, skills)
|
|
244
|
+
if cache is not None:
|
|
245
|
+
params["cache"] = cache
|
|
246
|
+
if site_context is not None:
|
|
247
|
+
params["site_context"] = site_context
|
|
248
|
+
if vision is not None:
|
|
249
|
+
params["vision"] = cast(Any, vision)
|
|
250
|
+
if model is not None:
|
|
251
|
+
params["model"] = model
|
|
252
|
+
deadline = time.monotonic() + timeout
|
|
253
|
+
task = self.tasks.create(params, idempotency_key=idempotency_key)
|
|
254
|
+
try:
|
|
255
|
+
if on_progress is not None and task["status"] in ACTIVE_STATUSES:
|
|
256
|
+
for event in self.tasks._events(task["id"], None, deadline):
|
|
257
|
+
if event["type"] == "step":
|
|
258
|
+
on_progress(event["step"])
|
|
259
|
+
elif event["type"] == "done":
|
|
260
|
+
task = event["task"]
|
|
261
|
+
while task["status"] in ACTIVE_STATUSES:
|
|
262
|
+
remaining = deadline - time.monotonic()
|
|
263
|
+
if remaining <= 0:
|
|
264
|
+
raise WaitTimeoutError(task["id"], timeout)
|
|
265
|
+
task = self.tasks.get(
|
|
266
|
+
task["id"], wait=min(MAX_WAIT_SECONDS, max(1, int(remaining))))
|
|
267
|
+
except KeyboardInterrupt:
|
|
268
|
+
# The caller gave up on the task, so it should not keep running (and costing).
|
|
269
|
+
try:
|
|
270
|
+
self.tasks.cancel(task["id"])
|
|
271
|
+
except Exception: # noqa: BLE001 - the interrupt is what the caller sees
|
|
272
|
+
pass
|
|
273
|
+
raise
|
|
274
|
+
if task["status"] != "completed":
|
|
275
|
+
raise TaskFailedError(task)
|
|
276
|
+
return task
|
|
277
|
+
|
|
278
|
+
def _open_stream(self, path: str, last_event_id: Optional[str]) -> StreamResponse:
|
|
279
|
+
"""Opens an event stream, retrying like ``_request`` until the response starts."""
|
|
280
|
+
headers = {
|
|
281
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
282
|
+
"Accept": "text/event-stream",
|
|
283
|
+
"User-Agent": "browserwhale-python/0.1.0b1",
|
|
284
|
+
}
|
|
285
|
+
if last_event_id:
|
|
286
|
+
headers["Last-Event-ID"] = last_event_id
|
|
287
|
+
attempt = 0
|
|
288
|
+
while True:
|
|
289
|
+
try:
|
|
290
|
+
response = self._stream_transport(self._base_url + path, headers, self._timeout)
|
|
291
|
+
except OSError as error:
|
|
292
|
+
if attempt < self._max_retries:
|
|
293
|
+
self._sleep(_backoff(attempt))
|
|
294
|
+
attempt += 1
|
|
295
|
+
continue
|
|
296
|
+
raise APIConnectionError(f"Request failed: GET {path}") from error
|
|
297
|
+
if 200 <= response.status < 300:
|
|
298
|
+
return response
|
|
299
|
+
try:
|
|
300
|
+
body = b"".join(response.lines)
|
|
301
|
+
parsed = json.loads(body) if body else None
|
|
302
|
+
except (ValueError, OSError):
|
|
303
|
+
parsed = None
|
|
304
|
+
finally:
|
|
305
|
+
response.close()
|
|
306
|
+
error = error_from_response(response.status, parsed, response.headers)
|
|
307
|
+
if _retryable(error) and attempt < self._max_retries:
|
|
308
|
+
retry_after = error.retry_after if isinstance(error, RateLimitError) else None
|
|
309
|
+
self._sleep(min(retry_after, 60) if retry_after is not None else _backoff(attempt))
|
|
310
|
+
attempt += 1
|
|
311
|
+
continue
|
|
312
|
+
raise error
|
|
313
|
+
|
|
314
|
+
def _request(
|
|
315
|
+
self,
|
|
316
|
+
method: str,
|
|
317
|
+
path: str,
|
|
318
|
+
*,
|
|
319
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
320
|
+
body: Any = None,
|
|
321
|
+
idempotency_key: Optional[str] = None,
|
|
322
|
+
extra_timeout: float = 0,
|
|
323
|
+
) -> Any:
|
|
324
|
+
url = self._base_url + path
|
|
325
|
+
params = {k: v for k, v in (query or {}).items() if v is not None}
|
|
326
|
+
if params:
|
|
327
|
+
url += "?" + urllib.parse.urlencode(params)
|
|
328
|
+
headers = {
|
|
329
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
330
|
+
"Accept": "application/json",
|
|
331
|
+
"User-Agent": "browserwhale-python/0.1.0b1",
|
|
332
|
+
}
|
|
333
|
+
data = None
|
|
334
|
+
if body is not None:
|
|
335
|
+
headers["Content-Type"] = "application/json"
|
|
336
|
+
data = json.dumps(body).encode()
|
|
337
|
+
if idempotency_key:
|
|
338
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
339
|
+
attempt = 0
|
|
340
|
+
while True:
|
|
341
|
+
try:
|
|
342
|
+
response = self._transport(
|
|
343
|
+
method, url, headers, data, self._timeout + extra_timeout
|
|
344
|
+
)
|
|
345
|
+
except OSError as error:
|
|
346
|
+
if attempt < self._max_retries:
|
|
347
|
+
self._sleep(_backoff(attempt))
|
|
348
|
+
attempt += 1
|
|
349
|
+
continue
|
|
350
|
+
raise APIConnectionError(f"Request failed: {method} {path}") from error
|
|
351
|
+
try:
|
|
352
|
+
parsed = json.loads(response.body) if response.body else None
|
|
353
|
+
except ValueError:
|
|
354
|
+
parsed = None
|
|
355
|
+
if 200 <= response.status < 300:
|
|
356
|
+
return parsed
|
|
357
|
+
error = error_from_response(response.status, parsed, response.headers)
|
|
358
|
+
if _retryable(error) and attempt < self._max_retries:
|
|
359
|
+
retry_after = error.retry_after if isinstance(error, RateLimitError) else None
|
|
360
|
+
self._sleep(min(retry_after, 60) if retry_after is not None else _backoff(attempt))
|
|
361
|
+
attempt += 1
|
|
362
|
+
continue
|
|
363
|
+
raise error
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
class Tasks:
|
|
367
|
+
"""Lower-level task operations, one per endpoint."""
|
|
368
|
+
|
|
369
|
+
def __init__(self, client: Whale) -> None:
|
|
370
|
+
self._client = client
|
|
371
|
+
|
|
372
|
+
def create(self, params: CreateTaskParams, *, idempotency_key: Optional[str] = None) -> Task:
|
|
373
|
+
"""Always sends an ``Idempotency-Key``, so automatic retries cannot create duplicates."""
|
|
374
|
+
return cast(
|
|
375
|
+
Task,
|
|
376
|
+
self._client._request(
|
|
377
|
+
"POST",
|
|
378
|
+
"/v1/tasks",
|
|
379
|
+
body=params,
|
|
380
|
+
idempotency_key=idempotency_key or str(uuid.uuid4()),
|
|
381
|
+
),
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
def get(self, task_id: str, *, wait: Optional[float] = None) -> Task:
|
|
385
|
+
"""With ``wait`` (seconds, max 30) the server holds the request until the task finishes."""
|
|
386
|
+
return cast(
|
|
387
|
+
Task,
|
|
388
|
+
self._client._request(
|
|
389
|
+
"GET",
|
|
390
|
+
f"/v1/tasks/{urllib.parse.quote(task_id, safe='')}",
|
|
391
|
+
query={"wait": wait},
|
|
392
|
+
extra_timeout=wait or 0,
|
|
393
|
+
),
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
def events(self, task_id: str, *, last_event_id: Optional[str] = None) -> Iterator[TaskEvent]:
|
|
397
|
+
"""The task's live events: each new ``step``, each ``status`` change, then
|
|
398
|
+
``done`` with the finished task, after which the iterator ends.
|
|
399
|
+
|
|
400
|
+
Each stream lasts under a minute; the iterator reconnects on its own and
|
|
401
|
+
resumes after the last step it saw (``Last-Event-ID``). A connection that
|
|
402
|
+
drops more than ``max_retries`` times in a row raises ``APIConnectionError``.
|
|
403
|
+
"""
|
|
404
|
+
return self._events(task_id, last_event_id, None)
|
|
405
|
+
|
|
406
|
+
def _events(
|
|
407
|
+
self, task_id: str, last_event_id: Optional[str], deadline: Optional[float]
|
|
408
|
+
) -> Iterator[TaskEvent]:
|
|
409
|
+
client = self._client
|
|
410
|
+
path = f"/v1/tasks/{urllib.parse.quote(task_id, safe='')}/events"
|
|
411
|
+
reconnect = 1.0
|
|
412
|
+
failures = 0
|
|
413
|
+
while True:
|
|
414
|
+
response = client._open_stream(path, last_event_id)
|
|
415
|
+
try:
|
|
416
|
+
for event in parse_event_stream(response.lines):
|
|
417
|
+
if event.retry is not None:
|
|
418
|
+
reconnect = event.retry / 1000
|
|
419
|
+
if event.id is not None:
|
|
420
|
+
last_event_id = event.id
|
|
421
|
+
if not event.data:
|
|
422
|
+
continue
|
|
423
|
+
failures = 0
|
|
424
|
+
data = json.loads(event.data)
|
|
425
|
+
if event.event == "step":
|
|
426
|
+
yield {"type": "step", "step": data}
|
|
427
|
+
elif event.event == "status":
|
|
428
|
+
yield {"type": "status", "status": data["status"]}
|
|
429
|
+
elif event.event == "done":
|
|
430
|
+
yield {"type": "done", "task": data}
|
|
431
|
+
return
|
|
432
|
+
except OSError as error:
|
|
433
|
+
# A dropped connection: reconnect below, unless it keeps failing.
|
|
434
|
+
failures += 1
|
|
435
|
+
if failures > client._max_retries:
|
|
436
|
+
raise APIConnectionError(f"Event stream failed: task {task_id}") from error
|
|
437
|
+
finally:
|
|
438
|
+
response.close()
|
|
439
|
+
if deadline is not None and time.monotonic() >= deadline:
|
|
440
|
+
return
|
|
441
|
+
client._sleep(reconnect)
|
|
442
|
+
|
|
443
|
+
def list(self, *, limit: Optional[int] = None, cursor: Optional[str] = None) -> TaskList:
|
|
444
|
+
"""Newest first. Pass ``next_cursor`` from the previous page as ``cursor``."""
|
|
445
|
+
return cast(
|
|
446
|
+
TaskList,
|
|
447
|
+
self._client._request("GET", "/v1/tasks", query={"limit": limit, "cursor": cursor}),
|
|
448
|
+
)
|
|
449
|
+
|
|
450
|
+
def cancel(self, task_id: str) -> Task:
|
|
451
|
+
"""Idempotent: cancelling a finished task returns it unchanged."""
|
|
452
|
+
return cast(
|
|
453
|
+
Task,
|
|
454
|
+
self._client._request(
|
|
455
|
+
"POST", f"/v1/tasks/{urllib.parse.quote(task_id, safe='')}/cancel"
|
|
456
|
+
),
|
|
457
|
+
)
|
browserwhale/_errors.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Mapping, Optional
|
|
4
|
+
|
|
5
|
+
from ._types import Task
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class WhaleError(Exception):
|
|
9
|
+
"""Base class for every error the client raises."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ApiError(WhaleError):
|
|
13
|
+
"""The API answered with an error object."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
status: int,
|
|
18
|
+
type: str,
|
|
19
|
+
message: str,
|
|
20
|
+
param: Optional[str] = None,
|
|
21
|
+
request_id: Optional[str] = None,
|
|
22
|
+
) -> None:
|
|
23
|
+
super().__init__(message)
|
|
24
|
+
self.status = status
|
|
25
|
+
self.type = type
|
|
26
|
+
self.message = message
|
|
27
|
+
self.param = param
|
|
28
|
+
self.request_id = request_id
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class InvalidRequestError(ApiError):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class AuthenticationError(ApiError):
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class PermissionDeniedError(ApiError):
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class NotFoundError(ApiError):
|
|
44
|
+
pass
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ConflictError(ApiError):
|
|
48
|
+
"""For example, an ``Idempotency-Key`` reused with a different body."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class RateLimitError(ApiError):
|
|
52
|
+
"""HTTP 429. ``retry_after`` is in seconds; ``code`` says which limit was reached."""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
status: int,
|
|
57
|
+
message: str,
|
|
58
|
+
retry_after: Optional[float],
|
|
59
|
+
request_id: Optional[str] = None,
|
|
60
|
+
code: Optional[str] = None,
|
|
61
|
+
) -> None:
|
|
62
|
+
super().__init__(status, "rate_limited", message, None, request_id)
|
|
63
|
+
self.retry_after = retry_after
|
|
64
|
+
#: ``rate_limit_exceeded`` or ``concurrency_limit_exceeded``; None from older servers.
|
|
65
|
+
self.code = code
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class InternalServerError(ApiError):
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class APIConnectionError(WhaleError):
|
|
73
|
+
"""The request never produced an HTTP response (network failure or request timeout)."""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class TaskFailedError(WhaleError):
|
|
77
|
+
"""The task finished without completing; ``task`` keeps its partial results and limitations."""
|
|
78
|
+
|
|
79
|
+
def __init__(self, task: Task) -> None:
|
|
80
|
+
reasons = " ".join(item["reason"] for item in task["limitations"])
|
|
81
|
+
cause = f" ({task['cause']})" if task.get("cause") else ""
|
|
82
|
+
super().__init__(
|
|
83
|
+
f"Task {task['id']} ended {task['status']}{cause}: {reasons or 'no completed result.'}"
|
|
84
|
+
)
|
|
85
|
+
self.task = task
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class WaitTimeoutError(WhaleError):
|
|
89
|
+
"""``run()`` stopped waiting; the task may still be running on the server."""
|
|
90
|
+
|
|
91
|
+
def __init__(self, task_id: Optional[str], timeout: float) -> None:
|
|
92
|
+
suffix = f" for task {task_id}; it may still be running" if task_id else ""
|
|
93
|
+
super().__init__(f"Gave up waiting after {timeout:g} s{suffix}.")
|
|
94
|
+
self.task_id = task_id
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
_BY_TYPE = {
|
|
98
|
+
"invalid_request": InvalidRequestError,
|
|
99
|
+
"authentication": AuthenticationError,
|
|
100
|
+
"permission": PermissionDeniedError,
|
|
101
|
+
"not_found": NotFoundError,
|
|
102
|
+
"conflict": ConflictError,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def error_from_response(status: int, body: Any, headers: Mapping[str, str]) -> ApiError:
|
|
107
|
+
error = body.get("error") if isinstance(body, dict) else None
|
|
108
|
+
error = error if isinstance(error, dict) else {}
|
|
109
|
+
message = error.get("message") or f"HTTP {status}"
|
|
110
|
+
request_id = headers.get("request-id")
|
|
111
|
+
kind = error.get("type") or ("internal" if status >= 500 else "invalid_request")
|
|
112
|
+
if kind == "rate_limited":
|
|
113
|
+
raw = headers.get("retry-after")
|
|
114
|
+
try:
|
|
115
|
+
retry_after: Optional[float] = float(raw) if raw is not None else None
|
|
116
|
+
except ValueError:
|
|
117
|
+
retry_after = None
|
|
118
|
+
code = error.get("code")
|
|
119
|
+
return RateLimitError(
|
|
120
|
+
status,
|
|
121
|
+
message,
|
|
122
|
+
retry_after,
|
|
123
|
+
request_id,
|
|
124
|
+
code if code in ("rate_limit_exceeded", "concurrency_limit_exceeded") else None,
|
|
125
|
+
)
|
|
126
|
+
cls = _BY_TYPE.get(kind)
|
|
127
|
+
if cls is None:
|
|
128
|
+
return InternalServerError(status, "internal", message, error.get("param"), request_id)
|
|
129
|
+
return cls(status, kind, message, error.get("param"), request_id)
|
browserwhale/_types.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Field names match the HTTP API (snake_case); see ``api/openapi.json``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, List, Literal, Optional, TypedDict, Union
|
|
6
|
+
|
|
7
|
+
TaskStatus = Literal["queued", "running", "completed", "partial", "failed", "cancelled"]
|
|
8
|
+
TaskCause = Literal[
|
|
9
|
+
"site_blocked",
|
|
10
|
+
"unavailable",
|
|
11
|
+
"limit_reached",
|
|
12
|
+
"could_not_complete",
|
|
13
|
+
"needs_confirmation",
|
|
14
|
+
"cancelled",
|
|
15
|
+
"internal_error",
|
|
16
|
+
]
|
|
17
|
+
JsonValue = Union[str, int, float, bool, None, List[Any], Dict[str, Any]]
|
|
18
|
+
JsonSchema = Dict[str, Any]
|
|
19
|
+
|
|
20
|
+
# The statuses a task can still leave. Anything else is final, so a status added
|
|
21
|
+
# to the API after this client was published stops the wait instead of polling.
|
|
22
|
+
ACTIVE_STATUSES = frozenset({"queued", "running"})
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TaskResult(TypedDict):
|
|
26
|
+
"""One part of the request: its goal, whether it was done, and its data."""
|
|
27
|
+
|
|
28
|
+
goal: str
|
|
29
|
+
status: Literal["completed", "incomplete"]
|
|
30
|
+
data: JsonValue
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TaskLimitation(TypedDict):
|
|
34
|
+
"""A part of the request that was not done, and why, in plain language."""
|
|
35
|
+
|
|
36
|
+
requirement: str
|
|
37
|
+
reason: str
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class TaskValueEvidence(TypedDict):
|
|
41
|
+
"""Where a value of the output was read."""
|
|
42
|
+
|
|
43
|
+
#: Its place in ``output``, such as ``items[0].price``; "" for the whole output.
|
|
44
|
+
path: str
|
|
45
|
+
url: str
|
|
46
|
+
#: The page's text the value was read from.
|
|
47
|
+
quote: str
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _TaskChangeEvidence(TypedDict):
|
|
51
|
+
action: str
|
|
52
|
+
url: str
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class TaskChangeEvidence(_TaskChangeEvidence, total=False):
|
|
56
|
+
"""A change the task made on the site, and the site's HTTP answer when known."""
|
|
57
|
+
|
|
58
|
+
status: int
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
TaskEvidence = Union[TaskValueEvidence, TaskChangeEvidence]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class TaskConfirmation(TypedDict):
|
|
65
|
+
"""An act the task stopped before, for you to confirm."""
|
|
66
|
+
|
|
67
|
+
#: The part of the request it was for.
|
|
68
|
+
requirement: str
|
|
69
|
+
#: What was about to happen, such as ``Clicking 'Place order'``.
|
|
70
|
+
action: str
|
|
71
|
+
#: What it would do, completing "it would ...", such as ``place an order``.
|
|
72
|
+
effect: str
|
|
73
|
+
kind: Literal[
|
|
74
|
+
"purchase",
|
|
75
|
+
"payment",
|
|
76
|
+
"binding",
|
|
77
|
+
"delete",
|
|
78
|
+
"account",
|
|
79
|
+
"subscription",
|
|
80
|
+
"booking",
|
|
81
|
+
"application",
|
|
82
|
+
"message",
|
|
83
|
+
"submission",
|
|
84
|
+
"caller_data",
|
|
85
|
+
]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class TaskStep(TypedDict):
|
|
89
|
+
"""One plain-language step, such as ``Clicking "Sort by price"``."""
|
|
90
|
+
|
|
91
|
+
n: int
|
|
92
|
+
description: str
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class TaskUsage(TypedDict):
|
|
96
|
+
steps: int
|
|
97
|
+
model_calls: int
|
|
98
|
+
input_tokens: int
|
|
99
|
+
output_tokens: int
|
|
100
|
+
duration_ms: int
|
|
101
|
+
cost_usd: Optional[float]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class Task(TypedDict):
|
|
105
|
+
id: str
|
|
106
|
+
status: TaskStatus
|
|
107
|
+
#: Set whenever a finished task is not ``completed``.
|
|
108
|
+
cause: Optional[TaskCause]
|
|
109
|
+
#: Present only when ``completed``; valid against the output schema if one was given.
|
|
110
|
+
output: JsonValue
|
|
111
|
+
results: List[TaskResult]
|
|
112
|
+
limitations: List[TaskLimitation]
|
|
113
|
+
final_url: Optional[str]
|
|
114
|
+
#: Set when the task stopped before an act that needs your confirmation
|
|
115
|
+
#: (cause ``needs_confirmation``), such as placing an order.
|
|
116
|
+
confirmation: Optional[TaskConfirmation]
|
|
117
|
+
#: Where each value was read, and each change made with the site's answer.
|
|
118
|
+
evidence: List[TaskEvidence]
|
|
119
|
+
#: What the agent did, in plain language; grows while the task runs.
|
|
120
|
+
steps: List[TaskStep]
|
|
121
|
+
usage: Optional[TaskUsage]
|
|
122
|
+
created_at: str
|
|
123
|
+
started_at: Optional[str]
|
|
124
|
+
finished_at: Optional[str]
|
|
125
|
+
metadata: Dict[str, JsonValue]
|
|
126
|
+
#: Where the ``task.finished`` webhook is sent, if set at creation.
|
|
127
|
+
webhook_url: Optional[str]
|
|
128
|
+
#: The schedule that created this task, if any.
|
|
129
|
+
schedule_id: Optional[str]
|
|
130
|
+
#: The session the task ran in, if any.
|
|
131
|
+
session_id: Optional[str]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class TaskLimits(TypedDict, total=False):
|
|
135
|
+
timeout_seconds: int
|
|
136
|
+
max_steps: int
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
#: General know-how the agent can use; see ``CreateTaskParams.skills``.
|
|
140
|
+
SkillId = Literal["shopping", "admin", "forms", "media"]
|
|
141
|
+
#: ``read-only`` uses what earlier tasks saved and never saves.
|
|
142
|
+
StoredDataMode = Literal["read-write", "read-only"]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
#: The model providers you can bring your own key for.
|
|
146
|
+
ModelProvider = Literal["openai", "openai-compatible", "azure", "anthropic", "google"]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class _TaskModelRequired(TypedDict):
|
|
150
|
+
#: ``openai-compatible`` is any endpoint that speaks the OpenAI Chat Completions API.
|
|
151
|
+
provider: ModelProvider
|
|
152
|
+
#: The model to use, as your provider names it (Azure: the deployment name).
|
|
153
|
+
name: str
|
|
154
|
+
#: Your API key for the provider. Read it from your own environment; never hard-code it.
|
|
155
|
+
api_key: str
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class TaskModel(_TaskModelRequired, total=False):
|
|
159
|
+
"""Your own model for a task.
|
|
160
|
+
|
|
161
|
+
The key is used only to run that task: it is kept encrypted until the task
|
|
162
|
+
starts, and never stored, logged or returned.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
#: Your provider's https endpoint. Required for ``openai-compatible`` and ``azure``.
|
|
166
|
+
base_url: str
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class CreateTaskParams(TypedDict, total=False):
|
|
170
|
+
"""The body of ``POST /v1/tasks``: ``goal``, and ``url`` unless a later task of a session."""
|
|
171
|
+
|
|
172
|
+
url: str
|
|
173
|
+
goal: str
|
|
174
|
+
#: Run the task in this open session, after its earlier tasks.
|
|
175
|
+
session_id: str
|
|
176
|
+
output_schema: JsonSchema
|
|
177
|
+
#: Values the agent may enter on the site, such as an email address. Never logged.
|
|
178
|
+
variables: Dict[str, JsonValue]
|
|
179
|
+
limits: TaskLimits
|
|
180
|
+
metadata: Dict[str, JsonValue]
|
|
181
|
+
#: Public http(s) URL that gets a signed ``task.finished`` event when the task finishes.
|
|
182
|
+
webhook_url: str
|
|
183
|
+
# Opt-in features, all off by default.
|
|
184
|
+
#: Your own notes for the site, such as the steps you usually take. Never logged;
|
|
185
|
+
#: deleted when the task finishes.
|
|
186
|
+
notes: str
|
|
187
|
+
#: General know-how for the kind of work: ``"auto"`` or up to three skill names.
|
|
188
|
+
skills: Union[Literal["auto"], List[SkillId]]
|
|
189
|
+
#: Reuse the steps of an earlier completed task of yours with the same request.
|
|
190
|
+
cache: StoredDataMode
|
|
191
|
+
#: Remember how a website works between your tasks.
|
|
192
|
+
site_context: StoredDataMode
|
|
193
|
+
#: Also look at the screen when part of a page is drawn rather than described.
|
|
194
|
+
vision: Literal["fallback"]
|
|
195
|
+
#: Run the task with your own model provider key; required when the service holds none.
|
|
196
|
+
model: TaskModel
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class Usage(TypedDict):
|
|
200
|
+
"""One API key's usage and cost for a calendar month (UTC)."""
|
|
201
|
+
|
|
202
|
+
month: str
|
|
203
|
+
tasks: int
|
|
204
|
+
#: Finished tasks that count towards cost: not ones that never started or failed with ``internal_error``.
|
|
205
|
+
billable_tasks: int
|
|
206
|
+
unfinished_tasks: int
|
|
207
|
+
model_calls: int
|
|
208
|
+
input_tokens: int
|
|
209
|
+
output_tokens: int
|
|
210
|
+
browser_seconds: float
|
|
211
|
+
charged_usd: float
|
|
212
|
+
#: Held for unfinished tasks until they finish; counts towards the spending limit.
|
|
213
|
+
reserved_usd: float
|
|
214
|
+
#: Creates that would pass this monthly limit are refused with ``PermissionDeniedError``.
|
|
215
|
+
spend_limit_usd: Optional[float]
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class StepEvent(TypedDict):
|
|
219
|
+
"""A new step of the task's plain-language log."""
|
|
220
|
+
|
|
221
|
+
type: Literal["step"]
|
|
222
|
+
step: TaskStep
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class StatusEvent(TypedDict):
|
|
226
|
+
type: Literal["status"]
|
|
227
|
+
status: TaskStatus
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class DoneEvent(TypedDict):
|
|
231
|
+
"""The task finished; the last event of ``Tasks.events``."""
|
|
232
|
+
|
|
233
|
+
type: Literal["done"]
|
|
234
|
+
task: Task
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
#: One live event of a task (``GET /v1/tasks/{id}/events``).
|
|
238
|
+
TaskEvent = Union[StepEvent, StatusEvent, DoneEvent]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class TaskList(TypedDict):
|
|
242
|
+
data: List[Task]
|
|
243
|
+
has_more: bool
|
|
244
|
+
next_cursor: Optional[str]
|
browserwhale/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: browserwhale
|
|
3
|
+
Version: 0.1.0b1
|
|
4
|
+
Summary: Python client for the hosted Browserwhale web agent API.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
License-File: NOTICE
|
|
8
|
+
Keywords: agent,api,automation,browser,sdk,web-agent
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# browserwhale (Python)
|
|
15
|
+
|
|
16
|
+
Python client for the hosted Browserwhale API: give it a URL and a goal in
|
|
17
|
+
plain language, and a web agent does the task in a real, disposable browser.
|
|
18
|
+
|
|
19
|
+
Install it with `pip install --pre browserwhale` (beta). Python 3.9 or later, no
|
|
20
|
+
dependencies (it uses the standard library).
|
|
21
|
+
|
|
22
|
+
## Run a task
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from browserwhale import Whale
|
|
26
|
+
|
|
27
|
+
whale = Whale() # BROWSERWHALE_API_KEY and BROWSERWHALE_BASE_URL
|
|
28
|
+
|
|
29
|
+
task = whale.run(
|
|
30
|
+
url="https://example.com",
|
|
31
|
+
goal="Find the page's main heading.",
|
|
32
|
+
output_schema={"type": "object", "properties": {"heading": {"type": "string"}}},
|
|
33
|
+
)
|
|
34
|
+
print(task["output"]) # {'heading': 'Example Domain'}
|
|
35
|
+
for step in task["steps"]:
|
|
36
|
+
print(step["n"], step["description"]) # 1 Opening the website
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`run()` creates the task, waits until it finishes and returns the task
|
|
40
|
+
when it is `completed`. Tasks are plain dicts typed with `TypedDict`
|
|
41
|
+
(`Task`), with the API's snake_case field names.
|
|
42
|
+
|
|
43
|
+
To run a task in an open session (see the API docs, "Sessions"),
|
|
44
|
+
pass `session_id=`; a later task in it may pass `url=None` to continue on the
|
|
45
|
+
current page. This client does not open or close sessions yet; use the HTTP
|
|
46
|
+
API for that.
|
|
47
|
+
|
|
48
|
+
## Live progress
|
|
49
|
+
|
|
50
|
+
Pass `on_progress` to see each step as it happens:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
task = whale.run(
|
|
54
|
+
url="https://example.com",
|
|
55
|
+
goal="Find the page's main heading.",
|
|
56
|
+
on_progress=lambda step: print(f"Step {step['n']} · {step['description']}"),
|
|
57
|
+
)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
For more control, `whale.tasks.events(task_id)` yields every `step`, each
|
|
61
|
+
`status` change and finally `done` with the task. It reconnects on its own,
|
|
62
|
+
resuming after the last step it saw:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
for event in whale.tasks.events(task["id"]):
|
|
66
|
+
if event["type"] == "step":
|
|
67
|
+
print(event["step"]["description"])
|
|
68
|
+
elif event["type"] == "done":
|
|
69
|
+
print(event["task"]["status"])
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Opt-in features
|
|
73
|
+
|
|
74
|
+
All off by default:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
task = whale.run(
|
|
78
|
+
url="https://shop.example",
|
|
79
|
+
goal="Add the cheapest kettle to the cart.",
|
|
80
|
+
notes="The catalogue is under Shop > Kitchen.", # your own steps or hints
|
|
81
|
+
skills="auto", # or ["shopping"]
|
|
82
|
+
vision="fallback", # look at the screen for drawn content such as seat maps
|
|
83
|
+
cache="read-write", # reuse an earlier completed run of the same request
|
|
84
|
+
site_context="read-write", # remember how the site works between your tasks
|
|
85
|
+
)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`cache` and `site_context` keep data between the tasks of one API key (never
|
|
89
|
+
shared with another key, even in the same team), and only servers that store
|
|
90
|
+
task data accept them.
|
|
91
|
+
|
|
92
|
+
## Tasks that do not complete
|
|
93
|
+
|
|
94
|
+
Any other final status raises `TaskFailedError`; its `task` keeps the partial
|
|
95
|
+
`results`, the `limitations` with plain reasons, and the `cause`
|
|
96
|
+
(`site_blocked`, `unavailable`, `limit_reached`, `could_not_complete`,
|
|
97
|
+
`cancelled`, `internal_error`). `run(timeout=...)` (seconds, default 15
|
|
98
|
+
minutes) raises `WaitTimeoutError` when it stops waiting; the task may still
|
|
99
|
+
be running. Interrupting `run()` (Ctrl+C) cancels the task.
|
|
100
|
+
|
|
101
|
+
## Errors
|
|
102
|
+
|
|
103
|
+
| Error | When |
|
|
104
|
+
|---|---|
|
|
105
|
+
| `AuthenticationError` | Missing or invalid API key (401). |
|
|
106
|
+
| `InvalidRequestError` | The request failed validation (400, 413, 422); `param` names the field. |
|
|
107
|
+
| `NotFoundError` | No such task for this key (404). |
|
|
108
|
+
| `ConflictError` | An idempotency key reused with a different body (409). |
|
|
109
|
+
| `RateLimitError` | Rate limit or concurrent-task cap reached (429). `retry_after` is in seconds; `code` is `rate_limit_exceeded` or `concurrency_limit_exceeded`. |
|
|
110
|
+
| `InternalServerError` | A server error (5xx). |
|
|
111
|
+
| `APIConnectionError` | No response: a network failure or request timeout. |
|
|
112
|
+
|
|
113
|
+
All derive from `WhaleError`; the HTTP ones from `ApiError` (`status`, `type`,
|
|
114
|
+
`param`, `request_id`). The client retries 429, 5xx and network failures
|
|
115
|
+
(`max_retries`, default 2), honouring `Retry-After`. Every create carries an
|
|
116
|
+
`Idempotency-Key`, reused across retries, so a retried create never starts a
|
|
117
|
+
second task.
|
|
118
|
+
|
|
119
|
+
## Usage and cost
|
|
120
|
+
|
|
121
|
+
`whale.usage(month="2026-11")` returns the key's tasks, model calls, tokens,
|
|
122
|
+
browser time and cost for a calendar month (UTC; the current month by
|
|
123
|
+
default). Tasks that never started or failed with `internal_error` cost
|
|
124
|
+
nothing.
|
|
125
|
+
|
|
126
|
+
## Lower-level control
|
|
127
|
+
|
|
128
|
+
`whale.tasks.create(params)`, `get(id, wait=30)`, `list(limit=, cursor=)`,
|
|
129
|
+
`events(id)` and `cancel(id)` map one-to-one to the REST endpoints.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
browserwhale/__init__.py,sha256=JS2NFbC7LxtY7ej5oKiuLwyQCqpa94YLb0Cg2OvZiw4,2059
|
|
2
|
+
browserwhale/_client.py,sha256=V7fzkNsaUGAIOoUtKGkYwLisLxU220cEdqNNQ8GpCA0,17727
|
|
3
|
+
browserwhale/_errors.py,sha256=5qMfDWHLzjRHJ-Tm9Js4u7chdl6CKnNkCz98TagRoxQ,3851
|
|
4
|
+
browserwhale/_types.py,sha256=ROcLgjfMfkJJ5VMjixth5Dz8j6PeBLdO1yN04BKJJiI,7436
|
|
5
|
+
browserwhale/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
browserwhale-0.1.0b1.dist-info/METADATA,sha256=Y1fbCuStQh6niOPiiqeHaOXdA9IuvPKrDiBGD4UreS0,4742
|
|
7
|
+
browserwhale-0.1.0b1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
browserwhale-0.1.0b1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
9
|
+
browserwhale-0.1.0b1.dist-info/licenses/NOTICE,sha256=nzKmdMYe8AX61m4y6RLtcSWQBuApyYNbQmRDwbNW3YI,118
|
|
10
|
+
browserwhale-0.1.0b1.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|