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

# Image jobs

> Run an image edit or generation in the background. Poll for the pictures or cancel unfinished work.

Send `Prefer: respond-async` with [an edit](https://docs.sharemy.ai/api-reference/image-edits.md) or [a generation](https://docs.sharemy.ai/api-reference/image-generations.md). You can also set the `async` field. Use `"async": true` in JSON or `-F async=true` in a multipart form. The JSON string `"true"` also works. Generations accept JSON or multipart fields. Edits take multipart uploads.

## Start a job

The API checks the request fields before it returns HTTP 202. Save the relative path in `Location`. Wait the number of seconds in `Retry-After` before your first poll.

```http theme={null}
HTTP/1.1 202 Accepted
Location: /v1/jobs/job_69ba81e5-6a67-4cd5-a28b-2e023337b936
Retry-After: 2
Content-Type: application/json

{"id":"job_69ba81e5-6a67-4cd5-a28b-2e023337b936","object":"job","status":"queued","created":1764547200,"endpoint":"/v1/images/edits"}
```

You can disconnect after submission. The job keeps one of your account's four concurrent slots until it finishes. You can poll and cancel even when all four slots are in use. If result storage is unavailable at submission, you get `503 storage_unavailable`.

## Poll for the result

Send `GET /v1/jobs/{id}` with a token from the account that submitted the job. Each successful lookup returns HTTP 200. Read `status` to decide what to do next.

| `status` | What to do |
| - | - |
| `queued` | Wait for a machine. Read `Retry-After` (2 seconds) before polling again. |
| `running` | A machine has the job. Wait for `Retry-After` before polling again. A job can return to `queued` if it needs another machine. |
| `succeeded` | Read `result`. It has the same `created` and `data` shape as the synchronous endpoint. Decode each `result.data[].b64_json` to get a PNG. |
| `failed` | Read `error.code`, `error.message`, `error.type` and `error.param`. A refusal such as `no_provider` can arrive here after a 202. Any held credits are refunded. |
| `cancelled` | Stop polling. The job was cancelled and its hold refunded. |

Finished jobs include `completed_at`. Both timestamps use Unix seconds. A successful job lookup with a result includes the cost and balance headers from the job's quote. A network restart marks unfinished jobs `failed` with `error.code` set to `interrupted`. You can submit a new request. You aren't charged for the interrupted job.

## Polling example

These examples submit one generation, wait for each `Retry-After`, and save the finished PNG. Use the same loop with the `Location` from an edit.

```bash curl theme={null}
set -eo pipefail
origin=https://sharemy.ai
auth="Authorization: Bearer $SHAREMYAI_API_KEY"
headers=$(mktemp)
body=$(mktemp)
trap 'rm -f "$headers" "$body"' EXIT

header() {
  awk -v name="$1:" 'tolower($1) == name { sub(/\r$/, "", $2); print $2 }' "$headers"
}

curl -fsS -D "$headers" -o "$body" "$origin/v1/images/generations" \
  -H "$auth" -H 'Prefer: respond-async' -H 'Content-Type: application/json' \
  -d '{"model":"flux2-klein","prompt":"A lighthouse at dusk"}'
url="$origin$(header location)"

while true; do
  sleep "$(header retry-after)"
  curl -fsS -D "$headers" -o "$body" -H "$auth" "$url"
  case "$(jq -r '.status' "$body")" in
    queued|running) continue ;;
    succeeded) jq -er '.result.data[0].b64_json' "$body" | base64 --decode > lighthouse.png; break ;;
    *) jq -c '{status, error}' "$body" >&2; exit 1 ;;
  esac
done
```

```python Python theme={null}
import base64, os, time
from pathlib import Path
import httpx
from openai import OpenAI

key = os.environ["SHAREMYAI_API_KEY"]
origin = "https://sharemy.ai"
client = OpenAI(api_key=key, base_url=origin + "/v1")
receipt = client.images.with_raw_response.generate(
    model="flux2-klein",
    prompt="A lighthouse at dusk",
    extra_headers={"Prefer": "respond-async"},
)
url = origin + receipt.headers["Location"]
delay = int(receipt.headers["Retry-After"])

with httpx.Client(headers={"Authorization": f"Bearer {key}"}) as http:
    while True:
        time.sleep(delay)
        response = http.get(url)
        response.raise_for_status()
        job = response.json()
        if job["status"] in ("queued", "running"):
            delay = int(response.headers["Retry-After"])
            continue
        if job["status"] != "succeeded":
            raise RuntimeError(job.get("error", job["status"]))
        png = job["result"]["data"][0]["b64_json"]
        Path("lighthouse.png").write_bytes(base64.b64decode(png))
        break
```

```javascript Node theme={null}
import fs from "node:fs";
import { setTimeout as sleep } from "node:timers/promises";
import OpenAI from "openai";

const apiKey = process.env.SHAREMYAI_API_KEY;
const origin = "https://sharemy.ai";
const client = new OpenAI({ apiKey, baseURL: origin + "/v1" });
const receipt = await client.images.generate(
  { model: "flux2-klein", prompt: "A lighthouse at dusk" },
  { headers: { Prefer: "respond-async" } },
).asResponse();
const url = new URL(receipt.headers.get("Location"), origin);
let delay = Number(receipt.headers.get("Retry-After"));

while (true) {
  await sleep(delay * 1000);
  const response = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` } });
  const job = await response.json();
  if (!response.ok) throw new Error(job.error.message);
  if (["queued", "running"].includes(job.status)) {
    delay = Number(response.headers.get("Retry-After"));
    continue;
  }
  if (job.status !== "succeeded") throw new Error(job.error?.message ?? job.status);
  fs.writeFileSync("lighthouse.png", Buffer.from(job.result.data[0].b64_json, "base64"));
  break;
}
```

## Cancel a job

Send `POST /v1/jobs/{id}/cancel` with the same account's token. You can leave the body empty.

```bash theme={null}
curl -X POST "https://sharemy.ai/v1/jobs/$JOB_ID/cancel" \
  -H "Authorization: Bearer $SHAREMYAI_API_KEY"
```

If the job is unfinished, you get HTTP 200 with `status: "cancelled"` and the full hold goes back to your balance. If it has already finished, you get its current state. Cancelling a successful job returns its result and leaves the charge in place.

## Ownership and expiry

You have one hour from `completed_at` to retrieve a finished job. After that, polling or cancelling returns `404 job_expired` to your account. An unknown id or another account's id returns `404 not_found`, even if that job has expired. Both errors name `id` in `error.param`.


## OpenAPI

````yaml api-reference/openapi.json GET /v1/jobs/{id}
openapi: 3.1.0
info:
  title: ShareMyAI API
  version: 1.0.0
  description: >-
    OpenAI-shaped endpoints that run jobs on shared GPUs. Closing the connection
    cancels an unfinished synchronous job and returns its held credits. CORS
    allows any origin, echoes requested preflight headers and exposes Location,
    the request id, concurrency, retry, cost, balance, token cap and sample rate
    headers.
servers:
  - url: https://sharemy.ai
    description: ShareMyAI
security:
  - bearerAuth: []
tags:
  - name: Models
  - name: Chat
  - name: Images
  - name: Jobs
  - name: Audio
paths:
  /v1/jobs/{id}:
    get:
      tags:
        - Jobs
      summary: Get an image job
      description: >-
        Poll with a token from the submitting account. Wait for Retry-After
        while the job is queued or running.
      operationId: getImageJob
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
          example: job_69ba81e5-6a67-4cd5-a28b-2e023337b936
      responses:
        '200':
          description: >-
            The current state. Check status even on HTTP 200. A successful job
            includes result and a failed job includes error.
          headers:
            x-request-id:
              $ref: '#/components/headers/x-request-id'
            x-ratelimit-limit-concurrent:
              $ref: '#/components/headers/x-ratelimit-limit-concurrent'
            x-ratelimit-remaining-concurrent:
              $ref: '#/components/headers/x-ratelimit-remaining-concurrent'
            X-ShareMyAI-Cost-Credits:
              $ref: '#/components/headers/X-ShareMyAI-Cost-Credits'
            X-ShareMyAI-Balance-Credits:
              $ref: '#/components/headers/X-ShareMyAI-Balance-Credits'
            Retry-After:
              $ref: '#/components/headers/Retry-After'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ImageJob'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Suspended'
        '404':
          $ref: '#/components/responses/JobNotFound'
        '405':
          $ref: '#/components/responses/MethodNotAllowed'
        '499':
          $ref: '#/components/responses/JobRequestAborted'
        '502':
          $ref: '#/components/responses/JobReadError'
      x-codeSamples:
        - lang: bash
          label: curl
          source: |-
            curl "https://sharemy.ai/v1/jobs/$JOB_ID" \
              -H "Authorization: Bearer $SHAREMYAI_API_KEY"
        - lang: python
          label: Python
          source: >-
            import os

            import httpx


            url = f"https://sharemy.ai/v1/jobs/{os.environ['JOB_ID']}"

            response = httpx.get(url, headers={"Authorization": "Bearer " +
            os.environ["SHAREMYAI_API_KEY"]})

            response.raise_for_status()

            print(response.json()["status"])
        - lang: javascript
          label: Node
          source: |-
            const url = `https://sharemy.ai/v1/jobs/${process.env.JOB_ID}`;
            const response = await fetch(url, {
              headers: { Authorization: `Bearer ${process.env.SHAREMYAI_API_KEY}` },
            });
            const job = await response.json();
            if (!response.ok) throw new Error(job.error.message);
            console.log(job.status);
components:
  headers:
    x-request-id:
      description: Identifier for this API response.
      schema:
        type: string
    x-ratelimit-limit-concurrent:
      description: Job slots per account across all tokens.
      schema:
        type: integer
        const: 4
    x-ratelimit-remaining-concurrent:
      description: Free account slots when headers are sent.
      schema:
        type: integer
        minimum: 0
        maximum: 4
    X-ShareMyAI-Cost-Credits:
      description: >-
        Quoted price in credits when a job was accepted. For a Janus batch, the
        total for completed pictures.
      schema:
        type: number
    X-ShareMyAI-Balance-Credits:
      description: >-
        Balance in credits after the hold, from the last successful quote on a
        Janus batch.
      schema:
        type: number
    Retry-After:
      description: >-
        Seconds to wait. 2 on async submission and unfinished polls, 1 on a 429,
        and 30 on HTTP 503 no_provider.
      schema:
        type: integer
    X-ShareMyAI-Max-Tokens:
      description: Only on chat requests whose output budget was capped.
      schema:
        type: integer
        const: 4096
    Allow:
      description: Methods available for the requested path, including OPTIONS.
      schema:
        type: string
  schemas:
    ImageJob:
      type: object
      required:
        - id
        - object
        - created
        - endpoint
        - status
      properties:
        id:
          type: string
          description: Job id returned at submission.
        object:
          type: string
          const: job
        created:
          type: integer
          description: Unix time in seconds.
        endpoint:
          type: string
          enum:
            - /v1/images/generations
            - /v1/images/edits
        status:
          type: string
          enum:
            - queued
            - running
            - succeeded
            - failed
            - cancelled
        completed_at:
          type: integer
          description: >-
            Unix time in seconds when the job finished. The job expires one hour
            later.
        result:
          description: Only on success. The response from the original image endpoint.
          anyOf:
            - $ref: '#/components/schemas/ImagesResponse'
            - $ref: '#/components/schemas/ImageEditResponse'
        error:
          $ref: '#/components/schemas/ErrorDetail'
          description: >-
            Only on failure. An interrupted job was refunded after a network
            restart.
      allOf:
        - if:
            properties:
              status:
                enum:
                  - succeeded
                  - failed
                  - cancelled
          then:
            required:
              - completed_at
          else:
            properties:
              completed_at: false
        - if:
            properties:
              status:
                const: failed
          then:
            required:
              - error
          else:
            properties:
              error: false
        - if:
            properties:
              status:
                const: succeeded
          then:
            required:
              - result
            if:
              properties:
                endpoint:
                  const: /v1/images/edits
            then:
              properties:
                result:
                  $ref: '#/components/schemas/ImageEditResponse'
            else:
              properties:
                result:
                  $ref: '#/components/schemas/ImagesResponse'
          else:
            properties:
              result: false
    ImagesResponse:
      type: object
      required:
        - created
        - data
      properties:
        created:
          type: integer
          description: Unix time in seconds.
        data:
          type: array
          items:
            type: object
            properties:
              b64_json:
                type: string
                description: A PNG file, base64-encoded.
              revised_prompt:
                type: 'null'
                description: 'Always null: prompts are used as sent.'
              seed:
                type:
                  - integer
                  - 'null'
                description: >-
                  The seed the picture was drawn with, when the model reports
                  one.
            required:
              - b64_json
              - revised_prompt
              - seed
    ImageEditResponse:
      type: object
      required:
        - created
        - data
      properties:
        created:
          type: integer
          description: Unix time in seconds.
        data:
          type: array
          minItems: 1
          maxItems: 1
          items:
            type: object
            required:
              - b64_json
            properties:
              b64_json:
                type: string
                contentEncoding: base64
                contentMediaType: image/png
                description: The full-resolution edited picture.
    ErrorDetail:
      type: object
      required:
        - message
        - type
        - param
        - code
      properties:
        message:
          type: string
          description: What went wrong, for a person to read.
        type:
          type: string
          description: >-
            402 uses insufficient_quota, other 4xx errors use
            invalid_request_error, and 5xx errors use api_error.
          enum:
            - invalid_request_error
            - insufficient_quota
            - api_error
        param:
          type:
            - string
            - 'null'
          description: The request field at fault, when there is one.
        code:
          type:
            - string
            - 'null'
          description: A stable code. The Errors and limits page lists them all.
          examples:
            - model_not_found
        price_credits:
          type: number
          description: Job price in credits on an insufficient_quota error.
        balance_credits:
          type: number
          description: Account balance in credits on an insufficient_quota error.
      if:
        properties:
          code:
            const: insufficient_quota
      then:
        required:
          - price_credits
          - balance_credits
    Error:
      type: object
      required:
        - error
      properties:
        error:
          $ref: '#/components/schemas/ErrorDetail'
  responses:
    Unauthorized:
      description: >-
        The message distinguishes a missing token, a key without the smai_
        prefix and an unknown or revoked ShareMyAI token.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              message: >-
                Send your API token as Authorization: Bearer smai_…. Create one
                at https://sharemy.ai, account panel, API tokens.
              type: invalid_request_error
              param: null
              code: invalid_api_key
      headers:
        x-request-id:
          $ref: '#/components/headers/x-request-id'
        x-ratelimit-limit-concurrent:
          $ref: '#/components/headers/x-ratelimit-limit-concurrent'
        x-ratelimit-remaining-concurrent:
          $ref: '#/components/headers/x-ratelimit-remaining-concurrent'
    Suspended:
      description: The account is suspended.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
          example:
            error:
              message: >-
                This account is suspended. If you think that is a mistake,
                contact us.
              type: invalid_request_error
              param: null
              code: account_suspended
      headers:
        x-request-id:
          $ref: '#/components/headers/x-request-id'
        x-ratelimit-limit-concurrent:
          $ref: '#/components/headers/x-ratelimit-limit-concurrent'
        x-ratelimit-remaining-concurrent:
          $ref: '#/components/headers/x-ratelimit-remaining-concurrent'
        X-ShareMyAI-Cost-Credits:
          $ref: '#/components/headers/X-ShareMyAI-Cost-Credits'
        X-ShareMyAI-Balance-Credits:
          $ref: '#/components/headers/X-ShareMyAI-Balance-Credits'
        X-ShareMyAI-Max-Tokens:
          $ref: '#/components/headers/X-ShareMyAI-Max-Tokens'
    JobNotFound:
      description: >-
        not_found for an unknown id or another account's job. job_expired for
        your own job at least one hour after completion. Both name id in
        error.param.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
      headers:
        x-request-id:
          $ref: '#/components/headers/x-request-id'
        x-ratelimit-limit-concurrent:
          $ref: '#/components/headers/x-ratelimit-limit-concurrent'
        x-ratelimit-remaining-concurrent:
          $ref: '#/components/headers/x-ratelimit-remaining-concurrent'
    MethodNotAllowed:
      description: The path exists. Use a method listed in Allow (method_not_allowed).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
      headers:
        x-request-id:
          $ref: '#/components/headers/x-request-id'
        x-ratelimit-limit-concurrent:
          $ref: '#/components/headers/x-ratelimit-limit-concurrent'
        x-ratelimit-remaining-concurrent:
          $ref: '#/components/headers/x-ratelimit-remaining-concurrent'
        Allow:
          $ref: '#/components/headers/Allow'
    JobRequestAborted:
      description: The lookup or cancel request was already disconnected (cancelled).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
      headers:
        x-request-id:
          $ref: '#/components/headers/x-request-id'
        x-ratelimit-limit-concurrent:
          $ref: '#/components/headers/x-ratelimit-limit-concurrent'
        x-ratelimit-remaining-concurrent:
          $ref: '#/components/headers/x-ratelimit-remaining-concurrent'
    JobReadError:
      description: The job or its stored result could not be read (network_error).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
      headers:
        x-request-id:
          $ref: '#/components/headers/x-request-id'
        x-ratelimit-limit-concurrent:
          $ref: '#/components/headers/x-ratelimit-limit-concurrent'
        x-ratelimit-remaining-concurrent:
          $ref: '#/components/headers/x-ratelimit-remaining-concurrent'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >-
        An API token from the account panel on sharemy.ai. Tokens start with
        `smai_`.

````

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