Metadata-Version: 2.5
Name: browserwhale
Version: 0.1.0b3
Summary: Python client for the hosted Browserwhale web agent API.
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: agent,api,automation,browser,sdk,web-agent
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# browserwhale (Python)

Python client for the hosted Browserwhale API: give it a URL and a task in
plain language, and a web agent does the task in a real, disposable browser.

Not published yet: it will go to PyPI as `browserwhale` with the npm packages
(#86). Python 3.9 or later, no dependencies (it uses the standard library).

## Run a task

Set your keys in the environment, out of source code:

```sh
export BROWSERWHALE_API_KEY="bw_…"
export OPENAI_API_KEY="sk-…"               # your own model provider key
export OPENAI_MODEL="gpt-5.4-mini"         # the model to use
```

```python
from browserwhale import Whale

whale = Whale()  # reads BROWSERWHALE_API_KEY

task = whale.run(
    url="https://example.com",
    task="Find the page's main heading.",
    output={"type": "object", "properties": {"heading": {"type": "string"}}},
)
print(task["output"])  # {'heading': 'Example Domain'}
for step in task["steps"]:
    print(step["n"], step["description"])  # 1 Opening the website
```

Tasks run on your own model provider account. A task without `model` takes
your key and model name from the environment, the same variables the
`browserwhale` package reads:

| Provider | Variables |
|---|---|
| OpenAI | `OPENAI_API_KEY`, `OPENAI_MODEL`, optional `OPENAI_BASE_URL` |
| Anthropic | `ANTHROPIC_API_KEY`, `ANTHROPIC_MODEL`, optional `ANTHROPIC_BASE_URL` |
| Google | `GEMINI_API_KEY` (or `GOOGLE_API_KEY`), `GEMINI_MODEL`, optional `GEMINI_BASE_URL` |
| Azure OpenAI | `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_DEPLOYMENT`, `AZURE_OPENAI_ENDPOINT` |

When keys for several providers are set, `BROWSERWHALE_PROVIDER` picks one;
otherwise the order is OpenAI, Anthropic, Google, then Azure. A key without
its model name is an error: the client never picks a model for you. The key
is used only for that task and never stored, logged or returned.

To choose the model in code instead, pass `model` with a task, or once as a
client default with `Whale(model=...)`; a task's own `model` wins:

```python
import os

task = whale.run(
    url="https://example.com",
    task="Find the page's main heading.",
    model={
        "provider": "openai",  # or openai-compatible, azure, anthropic, google
        "name": "gpt-5.4-mini",
        "api_key": os.environ["OPENAI_API_KEY"],
    },
)
```

`base_url` sets your provider's `https` endpoint (required for
`openai-compatible` and `azure`). `Whale(model=False)` sends no model from
the environment. `model_from_environment(os.environ)` returns the model the
client would read.

`run()` creates the task, waits until it finishes and returns the task
when it is `completed`. Tasks are plain dicts typed with `TypedDict`
(`Task`), with the API's snake_case field names.

## Live progress

Pass `on_progress` to see each step as it happens:

```python
task = whale.run(
    url="https://example.com",
    task="Find the page's main heading.",
    on_progress=lambda step: print(f"Step {step['n']} · {step['description']}"),
)
```

For more control, `whale.tasks.events(task_id)` yields every `step`, each
`status` change and finally `done` with the task. It reconnects on its own,
resuming after the last step it saw:

```python
for event in whale.tasks.events(task["id"]):
    if event["type"] == "step":
        print(event["step"]["description"])
    elif event["type"] == "done":
        print(event["task"]["status"])
```

## Answering a question

Before a step that needs your go-ahead, a task can ask one yes/no question.
Pass `on_confirm` to answer it; return `True` to carry out the step, `False`
to end the task without it:

```python
task = whale.run(
    url="https://admin.example.com/users",
    task="Remove the user Jordan Ortiz.",
    on_confirm=lambda confirmation, task: input(confirmation["question"] + " [y/N] ") == "y",
)
```

Without `on_confirm`, `run()` creates the task with
`confirmations="decline"`, so it never waits on an answer. A task created
with `whale.tasks.create` that waits has the status
`waiting_for_confirmation` and a `confirmation`; answer it with
`whale.tasks.confirm(task_id, task["confirmation"]["id"], "yes")` or `"no"`
before `confirmation["expires_at"]` (5 minutes). No answer counts as no, and
a yes doesn't carry out a step the page changed under while you decided.

## Opt-in features

All off by default:

```python
task = whale.run(
    url="https://shop.example",
    task="Add the cheapest kettle to the cart.",
    skills="auto",  # or ["shopping"]
    vision=False,  # never look at the screen (on by default, for drawn content such as seat maps)
    cache="read-write",  # reuse an earlier completed run of the same request
)
```

`cache` keeps data between the tasks of one API key (never
shared with another key), and only servers that store
task data accept them.

## Tasks that do not complete

Any other final status raises `TaskFailedError`; its `task` keeps the partial
`results`, the `limitations` with plain reasons, and the `cause`
(`site_blocked`, `unavailable`, `limit_reached`, `could_not_complete`,
`cancelled`, `model_error`, `internal_error`). `run(timeout=...)` (seconds, default 15
minutes) raises `WaitTimeoutError` when it stops waiting; the task may still
be running. Interrupting `run()` (Ctrl+C) cancels the task.

## Errors

| Error                 | When                                                                                                                                           |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `AuthenticationError` | Missing or invalid API key (401).                                                                                                              |
| `InvalidRequestError` | The request failed validation (400, 413, 422); `param` names the field.                                                                        |
| `NotFoundError`       | No such task for this key (404).                                                                                                               |
| `ConflictError`       | An idempotency key reused with a different body (409).                                                                                         |
| `RateLimitError`      | Rate limit or concurrent-task cap reached (429). `retry_after` is in seconds; `code` is `rate_limit_exceeded`, `concurrency_limit_exceeded` or `quota_exceeded` (the month's tasks are used up; not retried). |
| `InternalServerError` | A server error (5xx).                                                                                                                          |
| `APIConnectionError`  | No response: a network failure or request timeout.                                                                                             |

All derive from `WhaleError`; the HTTP ones from `ApiError` (`status`, `type`,
`param`, `request_id`). The client retries 429, 5xx and network failures
(`max_retries`, default 2), honouring `Retry-After`. Every create carries an
`Idempotency-Key`, reused across retries, so a retried create never starts a
second task.

## Usage and cost

`whale.usage(month="2026-11")` returns the key's tasks, model calls, tokens,
browser time and cost for a calendar month (UTC; the current month by
default). Tasks that never started or failed with `internal_error` cost
nothing.

## Lower-level control

`whale.tasks.create(params)`, `get(id, wait=30)`, `list(limit=, cursor=)`,
`events(id)` and `cancel(id)` map one-to-one to the REST endpoints.

## Development

```bash
python3 -m unittest discover -s packages/sdk-python/tests      # unit and contract tests
pnpm test:api                                          # also runs them against the local API
```

`tests/test_client.py` checks the types against `api/openapi.json`, so a
contract change that the client misses fails. `tests/test_live_api.py` runs
against a server started by `test/integration/python-sdk.pg.test.ts`.
