Quickstart
This guide runs one task with the TypeScript SDK. It takes a few minutes, most of which is the task itself: a real browser loads and reads the page.
Prefer Python? See Python at the end.
1. Install
npm install @browserwhale/sdk
The SDK needs Node.js 22 or later. Add zod if you want typed output schemas.
2. Configure
The client reads its settings from environment variables. Keep your keys out of source code:
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
Tasks run on your own model provider account. A task without model takes
your key and model name from these variables; the key is used only for that
task and never stored. Other providers have their own:
| Provider | Variables |
|---|---|
| OpenAI | OPENAI_API_KEY, OPENAI_MODEL, optional OPENAI_BASE_URL |
| Anthropic | ANTHROPIC_API_KEY, ANTHROPIC_MODEL, optional ANTHROPIC_BASE_URL |
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 SDK never picks a model for you.
You can also pass the API key to the constructor: new Whale({ apiKey }).
Keys are sent as
Authorization: Bearer <key>.
3. Run a task
import { Whale } from "@browserwhale/sdk";
const whale = new Whale();
const task = await whale.run({
url: "https://example.com",
task: "Find the page's main heading.",
});
console.log(task.output);
console.log(task.steps); // [{ n: 1, description: "Opening …" }, …]To choose the model in code instead, pass model with a task (or once, as
new Whale({ model })); a task's own model wins. See
Your model key for the fields:
await whale.run({
url: "https://example.com",
task: "Find the page's main heading.",
model: {
provider: "openai",
name: "gpt-5.4-mini",
api_key: process.env.OPENAI_API_KEY!,
},
});
whale.run() creates the task, long-polls GET /v1/tasks/:id?wait=30 until it
finishes, and resolves with the task object when the
status is completed.
Without a schema, task.output is JSON, usually an object, whose keys are
chosen for the request; they may vary between runs. Ask for structured output
when you need a fixed shape.
4. Ask for structured output
Pass a zod schema as output. The SDK converts it to JSON Schema, sends it as
output, and parses task.output with it, so a completed task's
output is typed:
import { z } from "zod";
const task = await whale.run({
url: "https://example.com",
task: "Find the page's main heading.",
output: z.object({ heading: z.string() }),
});
console.log(task.output.heading);
You can also pass a plain JSON Schema object as output. When a value
the schema asks for couldn't be found, the task ends partial, with what was
found in results.
5. Handle tasks that do not complete
run() resolves only for completed tasks. A task that ends partial,
failed or cancelled throws TaskFailedError, which carries the full task,
so you keep what was found:
import { TaskFailedError, Whale } from "@browserwhale/sdk";
try {
const result = await whale.run({ url, task });
use(result.output);
} catch (error) {
if (!(error instanceof TaskFailedError)) throw error;
const { status, cause, results, limitations } = error.task;
// status: "partial" | "failed" | "cancelled"
// limitations: [{ requirement, reason }] in plain language
review(status, cause, results, limitations);
}
See causes for what each one means.
Errors
| Error | When |
|---|---|
TaskFailedError |
The task finished without completing. error.task holds the task object. |
TimeoutError |
run() stopped waiting (after timeoutMs, default 15 minutes). The task may still be running; error.taskId identifies it. |
AuthenticationError |
The API key is missing or invalid (HTTP 401). |
InvalidRequestError |
The request failed validation (HTTP 400, 413 or 422). param names the field. |
RateLimitError |
Rate limit or concurrent-task cap reached (HTTP 429). retryAfter is in seconds; code is rate_limit_exceeded, concurrency_limit_exceeded or quota_exceeded (the month's tasks are used up; not retried). |
NotFoundError |
No such task for this key (HTTP 404). |
ConflictError |
An idempotency key was reused with a different request (HTTP 409). |
InternalServerError |
A server error (HTTP 5xx). |
ConnectionError |
No HTTP response: a network failure or request timeout. |
All of them extend WhaleError; the HTTP ones extend ApiError, with
status, type and param.
The SDK retries 429, 5xx and network failures (maxRetries, default 2). Every
create carries an Idempotency-Key, reused across retries, so a retried create
never starts a second task. Pass idempotency_key to run() to choose it.
Follow progress
Pass onProgress to see each step as it happens, in plain language:
await whale.run({
url,
task,
onProgress: (step) => console.log(`Step ${step.n} · ${step.description}`),
});
whale.tasks.events(id) yields the same steps, each status change and the
finished task; see Follow a task's progress.
Stop waiting or cancel
run() accepts an AbortSignal. Aborting it stops waiting and cancels the
task, which then ends with status cancelled:
const controller = new AbortController();
setTimeout(() => controller.abort(), 120_000);
await whale.run({ url, task, signal: controller.signal });
timeoutMs (default 15 minutes) only stops waiting: the task keeps running,
and TimeoutError.taskId lets you collect it later. To stop a task you
created with whale.tasks.create(), call whale.tasks.cancel(id). In
Python, interrupting run() (Ctrl+C) cancels the task the same way.
Lower-level control
whale.tasks.create(), get(id, { wait }), list({ limit, cursor }),
events(id) and cancel(id) map one-to-one to the REST endpoints.
Use them to create a task now and collect its result later, or to read
partial results without exceptions.
Python
The Python client has the same calls, with the API's snake_case names. It needs Python 3.9 or later and nothing else. Like the TypeScript SDK, it is not published yet.
pip install browserwhale
from browserwhale import TaskFailedError, Whale
whale = Whale() # reads BROWSERWHALE_API_KEY and your model's variables
try:
task = whale.run(
url="https://example.com",
task="Find the page's main heading.",
output={"type": "object", "properties": {"heading": {"type": "string"}}},
)
print(task["output"])
except TaskFailedError as error:
print(error.task["status"], error.task["limitations"])Pass on_progress=print (or any function) to run() to follow the steps as
they happen, and model={...} to choose the model in code (Whale(model=...)
for every task). whale.tasks.create(), get(id, wait=30), list(), events(id)
and cancel(id) map to the endpoints. Errors are typed as in the TypeScript
SDK: AuthenticationError, InvalidRequestError, RateLimitError (with
retry_after and code), TaskFailedError and so on.