# Botify Agent: HTML Executor

**ID:** `html_code_executor`

Execute a JavaScript function on HTML from SiteCrawler crawls.


    Execute custom JavaScript extraction functions on HTML content from SiteCrawler.

    This agent is optimized for batch processing - when processing multiple URLs,
    they are sent to javascript executor together for better performance.

    The JavaScript function should be in the format 'function() { ... }' and has
    access to a `document` object for DOM traversal (querySelector, querySelectorAll, etc.).

    If no crawl is specified (analysis_slug in config), the last successful crawl is used.
    Temporary uploaded URLs on https://app.botify.com/:organization/:project/o/storage/tmp
    are resolved from project storage and do not require a crawl.

    Each input URL may carry a list of quality control expectations. When set,
    the agent evaluates them against the extracted JSON result and reports, per
    item, whether all expectations passed and the details of any failures.
    

## Authentication

All endpoints require a **Bearer token** in the `Authorization` header.

```
Authorization: Bearer <your-token>
```

## Calling this agent

This agent supports the following processing modes:

| Mode | Type | Description |
|------|------|-------------|
| **Process** | Synchronous | Single-item processing. Best for real-time requests with immediate response. |
| **Batch Process** | Synchronous | Process multiple items in a single request for efficiency. |
| **Async Process** | Asynchronous | Single-item processing for long-running tasks that exceed timeout limits. |
| **Async Batch Process** | Asynchronous | Large-scale batch jobs with background processing. |

# Synchronous Processing

Synchronous calls block until the result is ready. Use these for quick operations where you need immediate results.

## Single Item Processing

Process a single input and receive the result immediately.

```
POST https://agents.botify.com/{org}/{project}/html_code_executor/process
```

### Request body

```json
{
  "item": {
    "url": "<url>"
  },
  "config": {
    "function": "<function>"
  }
}
```

### Response

Returns a single processed item (HTTP 200).

### cURL example

```bash
curl -X POST "https://agents.botify.com/{org}/{project}/html_code_executor/process" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "item": {
    "url": "<url>"
  },
  "config": {
    "function": "<function>"
  }
}'
```

## Batch Processing

Process multiple inputs in a single synchronous request. More efficient than making individual calls. Items are processed concurrently on the server.

```
POST https://agents.botify.com/{org}/{project}/html_code_executor/batch_process
```

### Request body

```json
{
  "items": [
    {
      "url": "<url>"
    }
  ],
  "config": {
    "function": "<function>"
  }
}
```

### Response

Returns an array of results. Each element is either a successful processed item (`"status": "success"`) or an error (`"status": "error"`).

### cURL example

```bash
curl -X POST "https://agents.botify.com/{org}/{project}/html_code_executor/batch_process" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "items": [
    {
      "url": "<url>"
    }
  ],
  "config": {
    "function": "<function>"
  }
}'
```

### When to use synchronous calls

- Processing completes within timeout limits (typically 30 seconds)
- You need immediate results for user-facing features
- Small to medium batch sizes (up to ~100 items)

# Asynchronous Processing

Asynchronous calls return immediately with a batch ID. You then poll for results using the `async_batches/` endpoints.

### Async processing flow

1. **Submit job** -- `POST` to `async_process` or `async_batch_process`
2. **Receive batch ID** -- response contains `batch_id`
3. **Poll status** -- `HEAD` request to check readiness (lightweight, no body)
4. **Get results** -- `GET` request to retrieve processed results

## Async Single Item

Submit a single item for background processing. Use the `/single` endpoint to retrieve the result.

```
POST https://agents.botify.com/{org}/{project}/html_code_executor/async_process
```

### Request body

```json
{
  "item": {
    "url": "<url>"
  },
  "config": {
    "function": "<function>"
  }
}
```

### cURL example

```bash
# Step 1: Submit the job
curl -X POST "https://agents.botify.com/{org}/{project}/html_code_executor/async_process" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "item": {
    "url": "<url>"
  },
  "config": {
    "function": "<function>"
  }
}'

# Response: { "batch_id": "abc123" }

# Step 2: Check if batch is ready (HEAD request -- lightweight check)
curl -I -X HEAD "https://agents.botify.com/{org}/{project}/html_code_executor/async_batches/abc123" \
  -H "Authorization: Bearer $TOKEN"
# Returns 200 if ready, 204 if still processing

# Step 3: Get the result (for single-item async)
curl -X GET "https://agents.botify.com/{org}/{project}/html_code_executor/async_batches/abc123/single" \
  -H "Authorization: Bearer $TOKEN"
# Returns 200 with result, 202 if still processing, 404 if batch not found
```

## Async Batch Processing

Submit multiple items for background processing. The request body uses **JSONL** (newline-delimited JSON) format.

```
POST https://agents.botify.com/{org}/{project}/html_code_executor/async_batch_process
```

### Request body (JSONL, `Content-Type: text/plain`)

The first line contains `config` and `batch_config`. Each subsequent line is an item with a unique `id`.

```
{"config": {"function": "<function>"}, "batch_config": {}}
{"id": "item_1", "item": {"url": "<url>"}}
```

### Response

Returns a JSON object with `batch_id`, `status`, and a `Location` header.

### cURL example

```bash
# Step 1: Submit the batch job
curl -X POST "https://agents.botify.com/{org}/{project}/html_code_executor/async_batch_process" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: text/plain" \
  -d '{"config": {"function": "<function>"}, "batch_config": {}}\n{"id": "item_1", "item": {"url": "<url>"}}'

# Response: { "batch_id": "xyz789" }

# Step 2: Check if batch is ready (HEAD request)
curl -I -X HEAD "https://agents.botify.com/{org}/{project}/html_code_executor/async_batches/xyz789" \
  -H "Authorization: Bearer $TOKEN"
# Returns 200 if ready, 204 if still processing

# Step 3: Get all results
curl -X GET "https://agents.botify.com/{org}/{project}/html_code_executor/async_batches/xyz789" \
  -H "Authorization: Bearer $TOKEN"
```

## Checking Batch Status

Use a lightweight `HEAD` request to check if your batch is ready without transferring data.

```
HEAD https://agents.botify.com/{org}/{project}/html_code_executor/async_batches/{batch_id}
```

```bash
curl -I -X HEAD "https://agents.botify.com/{org}/{project}/html_code_executor/async_batches/{batch_id}" \
  -H "Authorization: Bearer $TOKEN"

# Response headers indicate status:
# HTTP/1.1 200 OK        -> Batch is complete, results ready
# HTTP/1.1 204 No Content -> Still processing
# HTTP/1.1 404 Not Found -> Batch does not exist
```

## Retrieving Results

Once the batch is ready, fetch results using the appropriate endpoint.

```bash
# For async_process (single item) -- use /single endpoint
curl -X GET "https://agents.botify.com/{org}/{project}/html_code_executor/async_batches/{batch_id}/single" \
  -H "Authorization: Bearer $TOKEN"

# For async_batch_process (multiple items) -- use base endpoint
curl -X GET "https://agents.botify.com/{org}/{project}/html_code_executor/async_batches/{batch_id}" \
  -H "Authorization: Bearer $TOKEN"
# Returns streaming JSONL where each line is a processed item or error
```

### Async response codes

| Code | Endpoint | Meaning | Action |
|------|----------|---------|--------|
| 200 | `HEAD` / `GET` | Batch complete, results ready | Read results from response body |
| 204 | `HEAD` | Still processing | Continue polling |
| 202 | `GET /single` | Still processing | Continue polling |
| 400 | `GET /single` | All items failed (client error) | Check error in response body |
| 404 | `HEAD` / `GET` | Batch does not exist | Verify `batch_id` is correct |

> **HEAD vs GET:** Use `HEAD` requests for lightweight status checks (no response body). Use `GET` only when ready to retrieve results to minimize bandwidth.

### When to use asynchronous calls

- Processing takes longer than 30 seconds
- Large batch sizes (100+ items)
- Background processing where immediate results aren't required
- Integration with job queues or workflow systems

## Python Example

A complete Python example showing both synchronous and asynchronous patterns.

```python
import requests
import time

API_TOKEN = "your_api_token"
BASE_URL = "https://agents.botify.com/{organization}/{project}"
AGENT = "html_code_executor"

headers = {
    "Authorization": f"Bearer {API_TOKEN}",
    "Content-Type": "application/json"
}

single_payload = {
  "item": {
    "url": "<url>"
  },
  "config": {
    "function": "<function>"
  }
}


def process_sync(payload: dict) -> dict:
    """Synchronous single-item processing."""
    response = requests.post(
        f"{BASE_URL}/{AGENT}/process",
        headers=headers,
        json=payload
    )
    response.raise_for_status()
    return response.json()


def process_async(
    payload: dict,
    poll_interval: int = 5,
    max_retries: int = 60
) -> dict:
    """Asynchronous single-item processing with polling."""
    # Submit job
    response = requests.post(
        f"{BASE_URL}/{AGENT}/async_process",
        headers=headers,
        json=payload
    )
    batch_id = response.json()["batch_id"]

    # Poll for results using HEAD (lightweight check)
    for _ in range(max_retries):
        status = requests.head(
            f"{BASE_URL}/{AGENT}/async_batches/{batch_id}",
            headers=headers
        )

        if status.status_code == 200:
            result = requests.get(
                f"{BASE_URL}/{AGENT}/async_batches/{batch_id}/single",
                headers=headers
            )
            return result.json()
        elif status.status_code == 204:
            time.sleep(poll_interval)
        else:
            raise Exception(f"Unexpected status: {status.status_code}")

    raise Exception("Max retries exceeded")


def process_async_batch(
    items: list,
    config: dict | None = None,
    poll_interval: int = 5
) -> dict:
    """Asynchronous batch processing with polling."""
    import json as _json

    # Build JSONL payload: first line is config, subsequent lines are items
    lines = [_json.dumps({"config": config or {}, "batch_config": {}})]
    for i, item in enumerate(items):
        lines.append(_json.dumps({"id": f"item_{i}", "item": item}))
    body = "\n".join(lines)

    # Submit batch (JSONL, text/plain)
    response = requests.post(
        f"{BASE_URL}/{AGENT}/async_batch_process",
        headers={**headers, "Content-Type": "text/plain"},
        data=body
    )
    batch_id = response.json()["batch_id"]

    # Poll until ready
    while True:
        status = requests.head(
            f"{BASE_URL}/{AGENT}/async_batches/{batch_id}",
            headers=headers
        )

        if status.status_code == 200:
            results = requests.get(
                f"{BASE_URL}/{AGENT}/async_batches/{batch_id}",
                headers=headers
            )
            return results.json()

        time.sleep(poll_interval)


# Example usage
# result = process_sync(single_payload)
# result = process_async(single_payload)
# results = process_async_batch([{"input": "item1"}, {"input": "item2"}])
```

## Billing

Fixed cost per item requested. The code runs against HTML you have already supplied, inside Botify, so nothing further is billed.

These usage SKUs can be charged on a call.

| SKU | Credits | Description |
| --- | ------- | ----------- |
| Tool call | 1 per request | Charged once per successful item. |


## Schemas

### Item

```json
{
  "type": "object",
  "properties": {
    "url": {
      "description": "URL to execute the JavaScript function on. Temporary uploaded URLs on https://app.botify.com/:organization/:project/o/storage/tmp are allowed.",
      "title": "URL",
      "type": "string"
    },
    "expectations": {
      "default": [],
      "description": "Quality control expectations the extracted result must satisfy. When provided, the agent evaluates them against the extracted JSON and reports any failures.",
      "items": {
        "$ref": "#/$defs/Expectation"
      },
      "title": "Expectations",
      "type": "array"
    }
  },
  "required": [
    "url"
  ],
  "$defs": {
    "ArrayItemMatch": {
      "description": "A sub-object pattern that at least one array item must match.\n\nThe mapping ``fields`` is keyed by the sub-object's attribute names\n(e.g. ``{\"review_text\": \"great\", \"review_rating\": 5}``). Keys not\nlisted here are not checked.\n\nFor convenience, a bare sub-object is accepted as a shorthand for\n``fields``: ``{\"name\": \"Ann\u00e9e\", \"value\": \"1982\"}`` is normalised to\n``{\"fields\": {\"name\": \"Ann\u00e9e\", \"value\": \"1982\"}}``. To match an array of\n*scalars* (e.g. a list of URLs), pass the scalar directly in\n``expected_array_items`` rather than an :class:`ArrayItemMatch`.",
      "properties": {
        "fields": {
          "additionalProperties": true,
          "description": "Sub-object fields to match (subset, no exhaustivity required)",
          "title": "Fields",
          "type": "object"
        },
        "instructions": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Free-form note describing how to locate this item in the page. Never used by the evaluator \u2014 purely informational.",
          "title": "Instructions"
        }
      },
      "title": "ArrayItemMatch",
      "type": "object"
    },
    "Expectation": {
      "description": "An expectation about a single field of the extracted JSON.\n\nExactly one of ``expected_value`` (for scalar fields),\n``expected_array_items`` (for array-item patterns) or\n``expected_length`` (for the length of an array field) must be set. The\n``operator`` is only meaningful for scalar and length expectations.",
      "properties": {
        "field": {
          "description": "Name of the extracted JSON field to check. Supports dotted paths for nested objects (e.g. ``dimensions.width``).",
          "title": "Field",
          "type": "string"
        },
        "operator": {
          "default": "equals",
          "description": "Predicate applied between the actual value and ``expected_value`` (scalar expectations) or between the array length and ``expected_length`` (length expectations). Defaults to ``equals``. Length expectations support only ``equals`` / ``gt`` / ``gte`` / ``lt`` / ``lte``.",
          "enum": [
            "equals",
            "contains",
            "matches_regex",
            "gt",
            "gte",
            "lt",
            "lte"
          ],
          "title": "Operator",
          "type": "string"
        },
        "expected_value": {
          "anyOf": [
            {},
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Expected scalar value (set when the field is a scalar)",
          "title": "Expected Value"
        },
        "expected_array_items": {
          "anyOf": [
            {
              "items": {
                "anyOf": [
                  {
                    "$ref": "#/$defs/ArrayItemMatch"
                  },
                  {
                    "type": "string"
                  },
                  {
                    "type": "integer"
                  },
                  {
                    "type": "number"
                  },
                  {
                    "type": "boolean"
                  }
                ]
              },
              "type": "array"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Patterns to match against array items (set when the field is an array). Each pattern is either a scalar \u2014 the array must contain an item equal to it (use this for arrays of strings or numbers, e.g. image URLs) \u2014 or a sub-object of fields, in which case at least one array item must match all the listed fields. For each pattern, at least one item must match.",
          "title": "Expected Array Items"
        },
        "expected_length": {
          "anyOf": [
            {
              "type": "integer"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Expected number of items of an array field (set to assert on the array length). Combined with ``operator`` (equals / gt / gte / lt / lte).",
          "title": "Expected Length"
        },
        "instructions": {
          "anyOf": [
            {
              "type": "string"
            },
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "Free-form note describing how to locate this field on the page. Never used by the evaluator \u2014 purely informational.",
          "title": "Instructions"
        }
      },
      "required": [
        "field"
      ],
      "title": "Expectation",
      "type": "object"
    }
  }
}
```

### Config

```json
{
  "type": "object",
  "properties": {
    "function": {
      "description": "JavaScript function to execute on the HTML. Should be in the format 'function() { ... }' and return the extracted data.",
      "title": "JavaScript Function",
      "type": "string"
    }
  },
  "required": [
    "function"
  ]
}
```

### Response

```json
{
  "$defs": {
    "ExpectationFailure": {
      "description": "A single expectation that did not hold against the extracted JSON.",
      "properties": {
        "attribute": {
          "description": "The (possibly dotted) field that failed",
          "title": "Attribute",
          "type": "string"
        },
        "expected": {
          "anyOf": [
            {},
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "What was expected (scalar value or array patterns)",
          "title": "Expected"
        },
        "result": {
          "anyOf": [
            {},
            {
              "type": "null"
            }
          ],
          "default": null,
          "description": "The value actually extracted (None when absent/null)",
          "title": "Result"
        },
        "message": {
          "description": "Human-readable error message",
          "title": "Message",
          "type": "string"
        }
      },
      "required": [
        "attribute",
        "message"
      ],
      "title": "ExpectationFailure",
      "type": "object"
    }
  },
  "description": "Output from HTML executor agent.",
  "properties": {
    "url": {
      "description": "The URL that was processed",
      "title": "Url",
      "type": "string"
    },
    "crawl": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Crawl Slug from SiteCrawler",
      "title": "Crawl"
    },
    "url_found": {
      "anyOf": [
        {
          "type": "boolean"
        },
        {
          "type": "null"
        }
      ],
      "default": false,
      "description": "Whether the URL was found in the crawl index",
      "title": "Url Found"
    },
    "result": {
      "anyOf": [
        {},
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Result of executing the function on the HTML",
      "title": "Result"
    },
    "error": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "Error if function execution failed",
      "title": "Error"
    },
    "quality_control_passed": {
      "anyOf": [
        {
          "type": "boolean"
        },
        {
          "type": "null"
        }
      ],
      "default": null,
      "description": "True when every expectation holds against the extracted result, False when at least one fails, None when no expectations were provided.",
      "title": "Quality Control Passed"
    },
    "quality_control_failures": {
      "default": [],
      "description": "One entry per failed expectation (empty when passed or when no expectations were provided).",
      "items": {
        "$ref": "#/$defs/ExpectationFailure"
      },
      "title": "Quality Control Failures",
      "type": "array"
    }
  },
  "required": [
    "url"
  ],
  "title": "HTMLExecutorProcessedItem",
  "type": "object"
}
```

## Best Practices

**Use exponential backoff for polling.** Start with short intervals (1-2 seconds) and increase the delay between polls to reduce API load.

**Set reasonable timeouts.** For synchronous calls, configure your HTTP client with appropriate timeout values (30-60 seconds).

**Handle rate limits gracefully.** Implement retry logic with backoff when you receive 429 (Too Many Requests) responses.

**Batch when possible.** Use batch endpoints to reduce the number of API calls and improve throughput.
