Batch and fine-tuning API

# Webhooks

Gridline can call your HTTPS endpoint when a batch or fine-tuning job ends, so you can fetch its results without polling. Deliveries use the same event body and signatures as OpenAI's webhooks.

## Overview

1. Create an endpoint with `POST /gridline/webhook_endpoints`: your HTTPS URL and the events you want. The answer includes a signing secret (`whsec_…`) once; store it securely.
2. When a job ends, Gridline sends your URL a POST with the event: its type and the batch's or job's id.
3. Your endpoint checks the signature, answers with a 2xx within 10 seconds, and fetches the batch or job by its id.

The routes are under Gridline's base URL, with a Gridline token as the API key (see the [quickstart](https://gridlinegpu.com/docs#access) for the token):

```
https://api.gridlinegpu.com/openai/v1
```

| Method | Path | What it does |
| --- | --- | --- |
| `POST` | `/gridline/webhook_endpoints` | Create an endpoint. The answer includes its signing secret, once. |
| `GET` | `/gridline/webhook_endpoints` | List your endpoints (without their secrets). |
| `GET` | `/gridline/webhook_endpoints/{endpoint_id}` | Retrieve one endpoint. |
| `DELETE` | `/gridline/webhook_endpoints/{endpoint_id}` | Delete an endpoint. Its pending deliveries stop and its delivery history is deleted. |
| `POST` | `/gridline/webhook_endpoints/{endpoint_id}/rotate_secret` | Replace the signing secret. The answer includes the new secret, once. |
| `GET` | `/gridline/webhook_endpoints/{endpoint_id}/deliveries` | The endpoint's most recent deliveries, newest first, with each one's status and attempts. |

These are Gridline's own routes (OpenAI sets up webhooks in its dashboard, not its API), so call them over plain HTTP.

## Create an endpoint

A JSON body with `url` and, optionally, `event_types`. Leave `event_types` out to receive all 7 events. With `httpx`, which the OpenAI SDK installs:

```
import os
import httpx

API = "https://api.gridlinegpu.com/openai/v1"
headers = {"Authorization": f"Bearer {os.environ['GRIDLINE_TOKEN']}"}

response = httpx.post(
    f"{API}/gridline/webhook_endpoints",
    headers=headers,
    json={
        "url": "https://example.com/hooks/gridline",
        "event_types": ["batch.completed", "batch.failed", "fine_tuning.job.succeeded", "fine_tuning.job.failed"],
    },
)
response.raise_for_status()
endpoint = response.json()
secret = endpoint["secret"]  # shown once: store it in your secret manager
```

With curl:

```
curl https://api.gridlinegpu.com/openai/v1/gridline/webhook_endpoints \
  -H "Authorization: Bearer $GRIDLINE_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/hooks/gridline", "event_types": ["batch.completed"]}'
```

The answer is the endpoint:

```
{"id": "whep_5f0c...", "object": "gridline.webhook_endpoint",
 "url": "https://example.com/hooks/gridline",
 "event_types": ["batch.completed", "batch.failed", "fine_tuning.job.succeeded", "fine_tuning.job.failed"],
 "created_at": 1795000000,
 "secret": "whsec_...",
 "previous_secret_expires_at": null}
```

- `secret` appears only in this answer and in a rotation's answer. Listing or retrieving an endpoint never shows it. If you lose it, [rotate it](https://gridlinegpu.com/docs/webhooks#rotate).
- The URL must use `https` and name a public internet host: no IP address, no user name or password, and no local or internal name such as `localhost` or a `.internal` host. It is at most 2048 characters. Each delivery checks every address the host resolves to; a private, loopback, link-local or cloud metadata address is refused.
- Up to 5 endpoints per account. Each endpoint receives its own copy of every event it subscribes to.
- An endpoint receives events for jobs that end after it was created, not for earlier ones.

## Events

The same event types as OpenAI's webhooks for batches and fine-tuning:

| Type | Sent when |
| --- | --- |
| `batch.completed` | A batch completed. Its output and error files are ready. |
| `batch.failed` | A batch failed. |
| `batch.cancelled` | A batch was cancelled. |
| `batch.expired` | A batch's completion window ended before it finished. |
| `fine_tuning.job.succeeded` | A fine-tuning job succeeded. Its ft: model is ready. |
| `fine_tuning.job.failed` | A fine-tuning job failed. |
| `fine_tuning.job.cancelled` | A fine-tuning job was cancelled. |

## What Gridline sends

Each delivery is a `POST` to your URL, usually within about 10 seconds of the job's end, with the same body as OpenAI's webhook events:

```
{"id": "evt_0123456789abcdef0123456789abcdef", "object": "event", "created_at": 1795000000, "type": "batch.completed", "data": {"id": "batch_0123456789abcdef0123456789abcdef"}}
```

- `created_at` is when the job ended (Unix seconds). `data.id` is the batch or fine-tuning job: fetch it with `client.batches.retrieve` or `client.fine_tuning.jobs.retrieve` for its status and files. The body holds nothing else.
- Headers: `content-type: application/json`, `user-agent: Gridline-Webhooks/1.0`, and the Standard Webhooks headers `webhook-id`, `webhook-timestamp` and `webhook-signature`.
- `webhook-id` is the same on every attempt of one delivery. The same event can arrive more than once, so deduplicate on `webhook-id`.
- `webhook-timestamp` is the attempt's time (Unix seconds), so a retry carries a fresh timestamp and signature.

## Verify a delivery

Deliveries are signed per Standard Webhooks, as OpenAI's are, so the OpenAI Python SDK's `client.webhooks.unwrap(body, headers, secret=…)` checks the signature and the timestamp and returns the parsed event. Pass the raw body, exactly as received. A Flask receiver:

```
import os
from flask import Flask, request
from openai import OpenAI

app = Flask(__name__)
client = OpenAI(base_url="https://api.gridlinegpu.com/openai/v1", api_key=os.environ["GRIDLINE_TOKEN"])
SECRET = os.environ["GRIDLINE_WEBHOOK_SECRET"]  # the whsec_... secret from create
seen = set()  # use your database in production

@app.post("/hooks/gridline")
def gridline_hook():
    try:
        event = client.webhooks.unwrap(request.get_data(as_text=True), request.headers, secret=SECRET)
    except Exception:
        return "invalid signature", 400
    delivery = request.headers["webhook-id"]
    if delivery in seen:
        return "", 204
    if event.type == "batch.completed":
        batch = client.batches.retrieve(event.data.id)
        ...  # queue the download; answer within 10 seconds
    seen.add(delivery)  # only once handled: a failed attempt is retried, not skipped
    return "", 204
```

Without the SDK: the signature is `v1,` and the base64 HMAC-SHA256 of `webhook-id.webhook-timestamp.body`, keyed with the base64-decoded part of the secret after `whsec_`. `webhook-signature` can hold more than one, space-separated (after a rotation); accept the delivery when any one matches, and refuse a timestamp more than a few minutes from your clock:

```
import base64, hashlib, hmac, time

def verify(body: bytes, headers, secret: str) -> bool:
    if abs(time.time() - int(headers["webhook-timestamp"])) > 300:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{headers['webhook-id']}.{headers['webhook-timestamp']}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    return any(
        hmac.compare_digest(expected, part.removeprefix("v1,"))
        for part in headers["webhook-signature"].split()
    )
```

## Answers and retries

- Answer with any 2xx status within 10 seconds. Gridline reads at most a few kilobytes of your answer and discards it.
- Any other status, a timeout, a connection error or a redirect (redirects are never followed) is retried, up to 8 attempts over about 72 hours. Gridline waits 5 seconds, 5 minutes, 1 hour, 6 hours, 18 hours, 24 hours and 24 hours between attempts, each give or take 10%. After the last attempt the delivery is `failed`.
- Do slow work after you answer: queue it, answer 2xx, then download the batch's output or use the new model.

## Manage endpoints

```
# List your endpoints
curl https://api.gridlinegpu.com/openai/v1/gridline/webhook_endpoints -H "Authorization: Bearer $GRIDLINE_TOKEN"

# Delete one
curl -X DELETE https://api.gridlinegpu.com/openai/v1/gridline/webhook_endpoints/whep_... -H "Authorization: Bearer $GRIDLINE_TOKEN"
```

A list answers `{"object": "list", "data": [...]}` with every endpoint; a delete answers `{"id": "whep_...", "object": "gridline.webhook_endpoint", "deleted": true}`. Deleting an endpoint stops its pending deliveries.

### Rotate a secret

`POST /gridline/webhook_endpoints/{endpoint_id}/rotate_secret` answers the endpoint with a new `secret`, shown once. For the next 24 hours deliveries are signed with both the new and the old secret (`previous_secret_expires_at` says until when), so you can switch your receiver over without missing one. Rotating again ends the earlier secret at once: only the last old secret keeps signing.

### See deliveries

`GET /gridline/webhook_endpoints/{endpoint_id}/deliveries` lists the endpoint's most recent deliveries, newest first (20 by default; `?limit=` from 1 to 100):

```
{"id": "wh_9a1e...", "object": "gridline.webhook_delivery",
 "event_id": "evt_0123...", "type": "batch.completed", "data": {"id": "batch_0123..."},
 "status": "pending", "attempts": 2, "last_status_code": 503, "last_error": "http_status",
 "next_attempt_at": 1795003605, "delivered_at": null, "created_at": 1795000000}
```

`status` is `pending`, `delivering`, `delivered` or `failed`. `last_error` is one of these words:

| last_error | Meaning |
| --- | --- |
| `http_status` | Your endpoint answered with a status other than 2xx (see last_status_code). |
| `redirect_refused` | Your endpoint answered with a redirect (3xx). Redirects are not followed. |
| `timeout` | No complete answer within 10 seconds. |
| `dns_failed` | The host name did not resolve. |
| `connect_failed` | The connection was refused, reset or unreachable. |
| `tls_failed` | The TLS handshake or the certificate check failed. |
| `address_refused` | The host name resolved to a private, loopback, link-local or reserved address. |
| `network_error` | Another network error. |
| `attempt_failed` | Gridline could not make the attempt. It is retried. |
| `lease_expired` | The last attempt did not finish on Gridline's side. |

## Errors

Errors are OpenAI-shaped: `error.message`, `error.type`, `error.param` and `error.code`. Creating an endpoint:

| Status | Code | Param | Message |
| --- | --- | --- | --- |
| 400 | `invalid_request` | `url` | url is an https URL of at most 2048 characters. |
| 400 | `invalid_request` | `url` | url is not a valid URL. |
| 400 | `invalid_request` | `url` | url must use https. |
| 400 | `invalid_request` | `url` | url must not carry a user name or password. |
| 400 | `invalid_request` | `url` | url must name a host, not an IP address. |
| 400 | `invalid_request` | `url` | url must name a public internet host. |
| 400 | `invalid_request` | `event_types` | event_types is a non-empty list of: batch.completed, batch.failed, batch.cancelled, batch.expired, fine_tuning.job.succeeded, fine_tuning.job.failed, fine_tuning.job.cancelled. |
| 400 | `invalid_request` | `(the parameter)` | Unknown parameter: <name>. |
| 400 | `invalid_request` | `-` | The body is a JSON object. |
| 400 | `limit_exceeded` | `-` | This account has the most webhook endpoints (5); delete one first. |
| 404 | `not_found` | `endpoint_id` | No such webhook endpoint. |
| 400 | `invalid_value` | `limit` | limit must be an integer from 1 to 100. |

The last two rows are the other routes': an endpoint that is not yours, or does not exist, is not found.

## Limits

- Up to 5 endpoints per account.
- 10 seconds per attempt; up to 8 attempts over about 72 hours.
- Up to 2,000 deliveries per account, all endpoints together, each kept 7 days. While an account holds that many, new job ends wait, and one still not queued 24 hours after it happened may not be delivered.
- Events cover the batches you create with `POST /batches` and your fine-tuning jobs.

## Your data

- A delivery carries only the event's id, type and time and the batch's or job's id: never its input, output, files or model.
- Gridline stores each endpoint's URL, its event types and its secret (encrypted). Each delivery's record keeps the status code and the error word of its last attempt, never your answer's body or headers, for 7 days.
- Deleting an endpoint deletes its delivery records.

---

Source: https://gridlinegpu.com/docs/webhooks
