> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tinyfish.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# TinyAgent Endpoints

> Choose the right TinyAgent run endpoint based on sync, async, batch, or streaming needs

TinyFish Web Agent offers four ways to run automations. Each endpoint serves a different need. Pick the one that matches how you want to handle the request and response. Exact request/response schemas: [Agent Reference](https://docs.tinyfish.ai/tinyagent/api/agent).

## The Four Endpoints

| Endpoint | Pattern | Best For |
| - | - | - |
| `/run` | Synchronous | Quick tasks, simple integrations |
| `/run-async` | Start then check | Long tasks, one task at a time |
| `/run-batch` | Start many then check | Many URLs or goals in one call |
| `/run-sse` | Live updates | Real-time progress, user-facing apps |

***

## Synchronous: `/run`

**Pattern:** Send request → Wait → Get result

The simplest approach. You call the API, it blocks until the automation completes, then returns the result.

```typescript theme={null}
import { TinyFish } from "@tiny-fish/sdk";

const client = new TinyFish();

const run = await client.agent.run({
  url: "https://example.com",
  goal: "Extract the page title",
});

console.log(run.result); // Your data
```

> [!WARNING]
>
> Runs created via `/run` **cannot be cancelled**. The request blocks until the automation completes, so there is no window to issue a cancellation. If you need the ability to cancel runs, use `/run-async`, `/run-batch`, or `/run-sse` instead.

> [tab] When to use
>
> * Tasks that complete in under 30 seconds
> * Simple scripts and one-off automations
> * When you don't need progress updates

> [tab] When to avoid
>
> * Long-running tasks (risk of timeout)
> * User-facing apps (no progress feedback)
> * Multiple URLs or goals (blocks other requests)
> * When you need the ability to cancel a run

***

## Asynchronous: `/run-async`

**Pattern:** Send request → Get run ID → Poll for result

The request returns immediately with a `run_id`. You then poll a separate endpoint to check status and get the result when ready.

**1. Start the automation**

```typescript theme={null}
import { TinyFish } from "@tiny-fish/sdk";

const client = new TinyFish();

const queued = await client.agent.queue({
  url: "https://example.com",
  goal: "Extract all product data",
});

if (queued.error) {
  throw new Error(`Failed to queue run: ${queued.error.message}`);
}

const runId = queued.run_id;
```

**2. Poll for the result**

```typescript theme={null}
const run = await client.runs.get(runId);
// run.status: PENDING, RUNNING, COMPLETED, FAILED, or CANCELLED
// run.result: Your data (when COMPLETED)
```

**3. Cancel a run (optional)**

If you need to stop a run before it completes, send a POST to the cancel endpoint:

```typescript theme={null}
await fetch(`https://agent.tinyfish.ai/v1/runs/${runId}/cancel`, {
  method: "POST",
  headers: { "X-API-Key": process.env.TINYFISH_API_KEY ?? "" },
});
```

> [!NOTE]
>
> Learn more about run statuses and lifecycle in [Runs](https://docs.tinyfish.ai/tinyagent/explanation/runs.md).

> [tab] When to use
>
> * Long-running automations (30+ seconds)
> * One task at a time, fire-and-forget
> * When you need to track a run separately

> [tab] When to avoid
>
> * When you need real-time progress updates
> * Simple, quick extractions (adds complexity)
> * Many URLs or goals at once — use `/run-batch` instead

***

## Batch: `/run-batch`

**Pattern:** Send many requests in one call → Get run IDs → Poll each result

Starts multiple automations (1–100 runs) asynchronously in a single call instead of issuing one request per URL or goal. There's no dedicated SDK batch method yet — call the REST endpoint directly, or use the CLI.

```bash cURL theme={null}
curl -X POST "https://agent.tinyfish.ai/v1/automation/run-batch" \
  -H "X-API-Key: $TINYFISH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "runs": [
      { "url": "https://example.com/a", "goal": "Extract the price" },
      { "url": "https://example.com/b", "goal": "Extract the price" }
    ]
  }'
```

```bash CLI theme={null}
# runs.csv columns: url,goal
tinyfish agent batch run --input runs.csv
```

```json theme={null}
{ "run_ids": ["run_1", "run_2"], "error": null }
```

Poll each `run_id` individually with `GET /v1/runs/{id}`, the same way you would for `/run-async`. For a handful of runs you want started right away without the batch envelope, concurrent `client.agent.queue()` calls (`Promise.all()` / `asyncio.gather()`) work just as well — see [Concurrent Requests](https://docs.tinyfish.ai/examples/bulk-requests-sync.md) and [Async Bulk Requests](https://docs.tinyfish.ai/examples/bulk-requests-async.md).

> [tab] When to use
>
> * Many URLs or goals submitted together
> * You want one request/response pair instead of N
> * Batch processing pipelines

> [tab] When to avoid
>
> * A single task — use `/run` or `/run-async`
> * When you need real-time progress updates

***

## Streaming: `/run-sse`

**Pattern:** Send request → Receive event stream → Process events as they arrive

Uses [Server-Sent Events (SSE)](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) to push updates to you in real-time. You'll receive events for each action the browser takes, plus a streaming URL you can embed in an iframe to watch the automation live.

**1. Start the automation and read events**

```typescript theme={null}
import { TinyFish, EventType } from "@tiny-fish/sdk";

const client = new TinyFish();

const stream = await client.agent.stream({
  url: "https://example.com",
  goal: "Extract all product data",
});

for await (const event of stream) {
  console.log(event.type, event);
}
```

### Event Types

| Event | Description |
| - | - |
| `STARTED` | Automation has begun, includes `run_id` |
| `STREAMING_URL` | URL to watch the browser live (valid 24hrs) |
| `PROGRESS` | Browser action taken (click, type, scroll, etc.) |
| `HEARTBEAT` | Connection keep-alive (no action needed) |
| `COMPLETE` | Automation finished, includes `status` and `result` |

### Cancelling an SSE Run

You can cancel a streaming run using the `run_id` from the `STARTED` event. The `onStarted` callback fires while you consume the stream, so capture `run_id` there and trigger the cancel from a separate context (here, a deadline timer):

```typescript theme={null}
let runId: string | undefined;

const stream = await client.agent.stream(
  { url: "https://example.com", goal: "Extract all product data" },
  { onStarted: (e) => { runId = e.run_id; } },
);

// Cancel from another context while the stream is being consumed.
const deadline = setTimeout(() => {
  if (runId) {
    fetch(`https://agent.tinyfish.ai/v1/runs/${runId}/cancel`, {
      method: "POST",
      headers: { "X-API-Key": process.env.TINYFISH_API_KEY ?? "" },
    });
  }
}, 30000);

for await (const event of stream) {
  console.log(event);
}
clearTimeout(deadline);
```

### Handling Events

Use this pattern to process each event type as the automation progresses.

```typescript theme={null}
import { TinyFish, EventType, RunStatus } from "@tiny-fish/sdk";

const client = new TinyFish();

const stream = await client.agent.stream(
  { url: "https://example.com", goal: "Extract all product data" },
  {
    onStarted: (e) => console.log(`Run started: ${e.run_id}`),
    onStreamingUrl: (e) => console.log(`Watch live: ${e.streaming_url}`),
    onProgress: (e) => console.log(`Action: ${e.purpose}`),
    onComplete: (e) => {
      if (e.status === RunStatus.COMPLETED) {
        console.log("Result:", e.result);
      } else {
        console.error(e.error?.message || "Automation failed");
      }
    },
  },
);

for await (const event of stream) {
  // Callbacks fire automatically during iteration
}
```

> [tab] When to use
>
> * User-facing apps (show progress)
> * When you want to watch the browser live
> * Debugging and development
> * Long tasks where you want visibility

> [tab] When to avoid
>
> * Batch processing (complexity overhead)
> * Backend jobs that don't need progress

***

## Common Request Options

`/run`, `/run-async`, and `/run-sse` accept this request body directly; `/run-batch` wraps an array of these same bodies under `runs` (see [Batch: `/run-batch`](#batch-run-batch)). Beyond the required `url` and `goal`, these optional fields apply to every run, whether sent directly or inside a batch:

| Field | Type | Description |
| - | - | - |
| `agent_config.max_steps` | number | Maximum tool-call steps before the agent stops (in **beta** — join the beta to use it). 1–500, defaults to 150. See [Agent Modes & Limits](https://docs.tinyfish.ai/tinyagent/explanation/agent-modes.md#max-steps). |
| `agent_config.max_duration_seconds` | number | Maximum wall-clock seconds before the agent stops. Defaults to no limit. See [Agent Modes & Limits](https://docs.tinyfish.ai/tinyagent/explanation/agent-modes.md#max-duration). |
| `agent_config.mode` | string | Agent behavior mode. `strict` (in **beta** — join the beta to use it) enables fail-fast for test automation. See [Agent Modes & Limits](https://docs.tinyfish.ai/tinyagent/explanation/agent-modes.md#default-vs-strict-mode). |
| `capture_config` | object | Toggle which data to capture during the run (`screenshots`, `html`, `recording`, etc.). `html: true` is required for per-step HTML snapshots. |
| `webhook_url` | string | HTTPS URL to receive run lifecycle notifications. Must use HTTPS. |

```json theme={null}
{
  "url": "https://example.com",
  "goal": "Extract all product data",
  "agent_config": {
    "max_steps": 50,
    "max_duration_seconds": 300
  },
  "capture_config": { "html": true },
  "webhook_url": "https://your-app.example.com/webhooks/tinyfish"
}
```

For the complete field list with types and defaults, see [Common Request Body](https://docs.tinyfish.ai/tinyagent/api/agent#common-request-body) in the Agent Reference. For authenticated runs and runtime browser modes, see [Browser Profiles](https://docs.tinyfish.ai/key-concepts/browser-profiles.md) and the [TinyProfiles API](https://docs.tinyfish.ai/tinyagent/api/profiles/tinyprofile.md).

***

## Quick Decision Guide

**1. Need real-time progress updates?**

**Yes** → Use `/run-sse`

**2. Submitting multiple URLs or goals at once?**

**Yes** → Use `/run-batch`

**3. Task takes longer than 30 seconds?**

**Yes** → Use `/run-async` + polling

**4. Simple, quick, single task?**

Use `/run` (synchronous)

***

## Comparison Table

| Feature | `/run` | `/run-async` | `/run-batch` | `/run-sse` |
| - | - | - | - | - |
| Response type | Final result | Run ID | Run IDs | Event stream |
| Progress updates | No | No (poll status) | No (poll status) | Yes |
| Streaming URL | In response | Poll to get | Poll to get | In events |
| Cancellable | No | Yes | Yes (per run) | Yes |
| Best for | Quick tasks | One long task | Many tasks at once | Real-time UI |
| Complexity | Low | Medium | Medium | Medium |

***

## Related

> [card] [Agent Reference](https://docs.tinyfish.ai/tinyagent/api/agent)
>
> Exact request and response schema for every Agent endpoint

> [card] [Runs](https://docs.tinyfish.ai/tinyagent/explanation/runs.md)
>
> Understand the automation lifecycle


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.