# Replicate

Running models on [Replicate](https://replicate.com) from the back end: a
prediction now and waited for, one that streams its output as it is made,
or one kept as a row and followed by a job until it ends, across restarts,
with Replicate's webhook to hear it sooner. Files in and out. An
[extension](../extensions/README.md): ordinary Mote in
`extensions/replicate/`. Back to the [map](README.md).

```mote
use "pkg:replicate/replicate.mote"

// A picture made for someone: begun now, told when it is done (a job polls; the webhook is quicker).
server fn paint(prompt: string): string requires signedIn limit 10 per hour
  let me = auth.me()?
  let run = replicateStart("acme/art:5c7d5dc6dd8bf75c1acaa8565735e7986bc5b66206b55cca93cb72c9bf15ccaa", {prompt}, `art:${me?.id}`, "")?
  return run.id

fn replicateDone(r: ReplicateRun): bool
  let made = replicateFiles(r.output)
  if r.status == "succeeded" && made.length > 0
    let picture = replicateDownload(made[0], 20000000)?
    Art.add({run: r.id, owner: r.purpose.slice(4), picture: files.keep(picture, "art.png")?})?
  return true
```

```toml
[packages]
replicate = "../mote/extensions/replicate"
```

```sh
REPLICATE_KEY=r8_… REPLICATE_WEBHOOK=https://studio.example/replicate/webhook REPLICATE_SECRET=whsec_… bun dist/server/main.js
```

**None of this has met the real Replicate.** It was written from
Replicate's HTTP API reference and run against a stand-in that speaks its
shape (`tests/svc_standin.mjs replicate`); the steps to check it with a
real token are [below](#checking-it-against-replicate).

## The settings

| | |
|---|---|
| `REPLICATE_KEY` | The API token, `r8_…`. A [secret](back-end.md#secrets). |
| `REPLICATE_WEBHOOK` | The whole address Replicate posts a prediction's end to. Unset: no webhook, polling alone. |
| `REPLICATE_SECRET` | The webhooks' signing secret (`whsec_…`, from `GET /v1/webhooks/default/secret`). Read with `env`, so a program that only polls need not set it; with `REPLICATE_WEBHOOK` and without it, every webhook is refused. |
| `REPLICATE_API` | Another address for the API (a stand-in). |

## A model, and its version

A model is said with its version: `"owner/name:<version id>"` (or the id
alone), so that an input gives what it gave when the program was written.
`"owner/name"` alone runs an official model's current version
(`POST /v1/models/{owner}/{name}/predictions`). The input is JSON, the
model's own fields (its page at Replicate lists them).

## The calls

| Call | |
|---|---|
| `replicatePredict(model, input, wait)` | Begins one: a `ReplicatePrediction` (`id`, `status`, `output`, `error`, `logs`, `stream`, `seconds`). `wait`: seconds Replicate may hold the answer until it is done (`Prefer: wait`, 60 at most; 0 answers at once). |
| `replicateGet(id)` · `replicateCancel(id)` | It again; cancelled (a kept run is told). |
| `replicateWait(p, most)` | Asks again (after 1 s, 2, 4, then every 5) until it ends, `most` seconds at most: it, when it succeeded; else a failure. |
| `replicateRun(model, input, most)` | The two together: for a model that takes seconds. |
| `replicateStreamTo(p, to, event)` | For a model that streams (a language model): each piece of output is `emitTo(to, event, piece)` (`on piece(text: string)` in that person's page; `""` for nobody), and all of it is given at the end. Read from the prediction's `urls.stream` as server-sent events (`output`, `error`, `done`). |
| `replicateUpload(data, name, type)` | Sends a file (`POST /v1/files`, as a part named `content`): give the model its `url`. |
| `replicateDownload(address, most)` | The bytes of a file a model made, `most` at most: only at Replicate's own hosts (`replicate.delivery`, `api.replicate.com`), so an output cannot point the back end anywhere else. |
| `replicateFiles(output)` | The file addresses in an output: itself, or the texts of a list. |

**A request to begin a prediction is not tried again.** Replicate does not
say it keeps an idempotency key, and a try that reached it would be a
second prediction, paid for. A GET is tried again on 429 and 5xx.

## A run that outlives the call

`replicateStart(model, input, purpose, key)` begins a prediction and keeps
it as a `ReplicateRun` row (`id`, `key`, `purpose`, `status`, `output`,
`error`, `seconds`, `told`), in the same turn as queuing `job fn
replicateFollow`, which asks after it (2 s, 4 s, … a minute at most between,
for a day) until it ends. The webhook, where there is one, says it sooner.
Either way, once it has ended the program is told **once**:

```text
fn replicateDone(r: ReplicateRun): bool
```

- `purpose` is the program's own word for what it is for (`art:u1`):
  `replicateRuns(purpose)` lists them, the newest first.
- `key` names the run: `replicateStart` with a key that a kept run has is
  that run, and nothing is asked of Replicate. That is what makes a person
  pressing twice, or a `job fn` run twice, one prediction.
- A restart loses nothing: the job is in the database, and is run by the
  next back end.
- A failure of `replicateDone` is a job that is tried again.
- Runs are kept a month.

## The webhook

`POST /replicate/webhook`: signed as [Standard
Webhooks](https://www.standardwebhooks.com) sign (`webhook-id`,
`webhook-timestamp`, `webhook-signature` of `v1,<base64>`s, each the
HMAC-SHA256 of `<id>.<timestamp>.<body>` under the secret's bytes), checked
by [`webhook.check(req, "replicate", …)`](back-end.md#webhooks): compared in
constant time, five minutes either way. Only a prediction kept as a run
is changed by it; one already told is answered `again: true`.

## When it fails

| Kind | |
|---|---|
| `"invalid"` | Replicate did not take it: its `detail` (`- input: prompt is required`). |
| `"auth"` | The token is wrong. |
| `"limited"`, `"replicate"`, `"offline"` | Too many; Replicate broke; it did not answer. |
| `"failed"` | The model ran and failed: `The model failed: <its error>`; `err.data.logs` is the end of its log. |
| `"canceled"` | It was cancelled. |
| `"timeout"` | `replicateWait` waited `most` seconds: it goes on at Replicate (`err.data.id`; `replicateCancel` stops it). |

## Checking it against Replicate

1. A token from replicate.com/account/api-tokens is `REPLICATE_KEY`.
2. `replicateRun("<an image model>:<its version>", {prompt: "a lamp"}, 60)`:
   the output is a list of `https://replicate.delivery/…` addresses, and
   `replicateDownload` gives a PNG.
3. A language model that streams: `replicateStreamTo(p, me.id, "piece")`
   shows the words in the page as they come.
4. `curl -s -H "Authorization: Bearer $REPLICATE_KEY"
   https://api.replicate.com/v1/webhooks/default/secret` gives the secret;
   with `REPLICATE_WEBHOOK` at an address Replicate can reach (a tunnel),
   `replicateStart` is told by the webhook before the job's next ask.
5. Compare each answer's fields with `replicateOf` (`id`, `model`,
   `version`, `status`, `input`, `output`, `error`, `logs`, `urls.stream`,
   `metrics.predict_time`).

Recorded in `tests/expect/real_svc_replicate.txt` (`tests/all.sh
real_svc_replicate`): a run waited for, one polled, an official model by
name, a failure, a refusal, a stream, a kept run told by the webhook and
begun twice with one key, a cancel, a forged webhook, files in and out and
an address that is not Replicate's; then the extension's own `mote test`.
