# Image generation

> Generate and edit images with one request, choose size, aspect ratio and quality per model, get a signed link or the bytes, and read what each image cost.

`POST /images/generations` creates images from a prompt, and edits images when you send source images with it. The request is OpenAI Images compatible, so the OpenAI SDKs' `images.generate` works against it, and the same API key, project budget, key limit and request logs apply as for chat. Field by field reference: [POST /images/generations](https://www.getlykia.com/en/docs/api-reference/images-generations).

## Generate an image

**cURL**

```bash
curl https://api.getlykia.com/v1/images/generations \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-image-2",
    "prompt": "A watercolor lighthouse on a cliff at dawn",
    "size": "1024x1024",
    "quality": "medium",
    "user": "tenant-42",
    "metadata": { "feature": "blog-covers" }
  }'
```

**Python**

```python
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

result = client.images.generate(
    model="openai/gpt-image-2",
    prompt="A watercolor lighthouse on a cliff at dawn",
    size="1024x1024",
    quality="medium",
    user="tenant-42",
    extra_body={"metadata": {"feature": "blog-covers"}},
)
for image in result.data:
    # A signed link to the original file; it works for one hour
    print(image.url)
print("cost (USD):", result.usage.cost)
```

**TypeScript**

```typescript
const response = await fetch("https://api.getlykia.com/v1/images/generations", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.LYKIA_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "openai/gpt-image-2",
    prompt: "A watercolor lighthouse on a cliff at dawn",
    size: "1024x1024",
    quality: "medium",
    user: "tenant-42",
    metadata: { feature: "blog-covers" },
  }),
});
if (!response.ok) throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);

const result = (await response.json()) as {
  id: string;
  data: { url?: string; expires_at?: string; mime_type?: string }[];
  usage: { cost: number };
};
for (const image of result.data) console.log(image.url, "valid until", image.expires_at);
console.log("cost (USD):", result.usage.cost, "header:", response.headers.get("X-Lykia-Cost"));
```

**Go**

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	payload, _ := json.Marshal(map[string]any{
		"model":    "openai/gpt-image-2",
		"prompt":   "A watercolor lighthouse on a cliff at dawn",
		"size":     "1024x1024",
		"quality":  "medium",
		"user":     "tenant-42",
		"metadata": map[string]string{"feature": "blog-covers"},
	})

	req, err := http.NewRequest(http.MethodPost, "https://api.getlykia.com/v1/images/generations", bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LYKIA_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("Lykia returned %d: %s", resp.StatusCode, body))
	}

	var result struct {
		Data []struct {
			URL       string `json:"url"`
			ExpiresAt string `json:"expires_at"`
		} `json:"data"`
		Usage struct {
			Cost float64 `json:"cost"`
		} `json:"usage"`
	}
	if err := json.Unmarshal(body, &result); err != nil {
		panic(err)
	}
	for _, image := range result.Data {
		fmt.Println(image.URL, "valid until", image.ExpiresAt)
	}
	fmt.Println("cost (USD):", result.Usage.Cost)
}
```

The response lists one item per image under `data`. Each item has a `url`: a signed link to the original file, valid for one hour. Download the file or show it within that hour. The link points to Lykia's storage, never to the provider, and the file is the provider's original bytes, not re-encoded, so any provenance marks the provider embeds stay intact.

**Request**

cURL

```bash
curl https://api.getlykia.com/v1/images/generations \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-image-2",
    "prompt": "A watercolor lighthouse on a cliff at dawn",
    "size": "1024x1024",
    "quality": "medium",
    "user": "tenant-42",
    "metadata": { "feature": "blog-covers" }
  }'
```

Python

```python
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

result = client.images.generate(
    model="openai/gpt-image-2",
    prompt="A watercolor lighthouse on a cliff at dawn",
    size="1024x1024",
    quality="medium",
    user="tenant-42",
    extra_body={"metadata": {"feature": "blog-covers"}},
)
for image in result.data:
    # A signed link to the original file; it works for one hour
    print(image.url)
print("cost (USD):", result.usage.cost)
```

TypeScript

```typescript
const response = await fetch("https://api.getlykia.com/v1/images/generations", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.LYKIA_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "openai/gpt-image-2",
    prompt: "A watercolor lighthouse on a cliff at dawn",
    size: "1024x1024",
    quality: "medium",
    user: "tenant-42",
    metadata: { feature: "blog-covers" },
  }),
});
if (!response.ok) throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);

const result = (await response.json()) as {
  id: string;
  data: { url?: string; expires_at?: string; mime_type?: string }[];
  usage: { cost: number };
};
for (const image of result.data) console.log(image.url, "valid until", image.expires_at);
console.log("cost (USD):", result.usage.cost, "header:", response.headers.get("X-Lykia-Cost"));
```

Go

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	payload, _ := json.Marshal(map[string]any{
		"model":    "openai/gpt-image-2",
		"prompt":   "A watercolor lighthouse on a cliff at dawn",
		"size":     "1024x1024",
		"quality":  "medium",
		"user":     "tenant-42",
		"metadata": map[string]string{"feature": "blog-covers"},
	})

	req, err := http.NewRequest(http.MethodPost, "https://api.getlykia.com/v1/images/generations", bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LYKIA_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	if resp.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("Lykia returned %d: %s", resp.StatusCode, body))
	}

	var result struct {
		Data []struct {
			URL       string `json:"url"`
			ExpiresAt string `json:"expires_at"`
		} `json:"data"`
		Usage struct {
			Cost float64 `json:"cost"`
		} `json:"usage"`
	}
	if err := json.Unmarshal(body, &result); err != nil {
		panic(err)
	}
	for _, image := range result.Data {
		fmt.Println(image.URL, "valid until", image.ExpiresAt)
	}
	fmt.Println("cost (USD):", result.Usage.Cost)
}
```

**Response (200)**

```json
{
    "id": "gen-1795463382-brqoiL7tycyIA73O",
    "object": "image.generation",
    "created": 1795463382,
    "model": "openai/gpt-image-2",
    "provider": "openai",
    "data": [
        {
            "mime_type": "image/png",
            "width": 1024,
            "height": 1024,
            "url": "https://files.example.com/media/gen-1795463382-brqoiL7tycyIA73O/0.png?X-Amz-Expires=3600&X-Amz-Signature=5f0c9e…",
            "expires_at": "2026-11-23T20:49:42.898Z"
        }
    ],
    "usage": {
        "images": 1,
        "cost": 0.05425,
        "is_byok": false,
        "cost_details": {
            "upstream_cost": 0.05425,
            "platform_fee": 0,
            "is_byok": false
        },
        "units": {
            "input_text_tokens": 50,
            "input_image_tokens": 0,
            "output_image_tokens": 1800
        }
    }
}
```

`usage.cost` is what the request cost in USD, the same amount as the `X-Lykia-Cost` response header. The request id is in `X-Generation-Id` and in the response's `id`; look the record up later with [`GET /generation`](https://www.getlykia.com/en/docs/api-reference/generation).

## Get the bytes instead of a link

Pass `response_format: "b64_json"` to receive each image inline as base64 in `data[].b64_json`, together with its `mime_type`. Nothing needs to be downloaded afterwards:

**Python**

```python
import base64
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

result = client.images.generate(
    model="openai/gpt-image-2",
    prompt="A flat icon of a paper plane",
    response_format="b64_json",
)
image = result.data[0]
with open("paper-plane.png", "wb") as f:
    f.write(base64.b64decode(image.b64_json))
print("saved paper-plane.png, cost (USD):", result.usage.cost)
```

**TypeScript**

```typescript
import { writeFile } from "node:fs/promises";

const response = await fetch("https://api.getlykia.com/v1/images/generations", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.LYKIA_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({ model: "openai/gpt-image-2", prompt: "A flat icon of a paper plane", response_format: "b64_json" }),
});
if (!response.ok) throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);

const result = (await response.json()) as { data: { b64_json: string; mime_type?: string }[]; usage: { cost: number } };
await writeFile("paper-plane.png", Buffer.from(result.data[0].b64_json, "base64"));
console.log("saved paper-plane.png, cost (USD):", result.usage.cost);
```

When Lykia's storage is not available, `b64_json` is the default and asking for `url` returns `400` with the code `storage_not_configured`.

## Edit with reference images

Send the images to work from in `images`, and describe the change in `prompt`. Depending on the model the images are edited, combined or used as references. Each item can be:

- a public `https://` URL,
- a data URI: `data:image/png;base64,…`,
- `{ "url": "…" }` or `{ "image_url": { "url": "…" } }`,
- `{ "b64_json": "…", "mime_type": "image/png" }`.

**cURL**

```bash
curl https://api.getlykia.com/v1/images/generations \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-image-2",
    "prompt": "Place this product on a white marble table in soft morning light",
    "images": ["https://example.com/product.png"],
    "size": "1536x1024"
  }'
```

**Python**

```python
import base64
import os

import requests

# A local file goes in as a data URI; a public https URL works as it is
with open("logo.png", "rb") as f:
    logo = "data:image/png;base64," + base64.b64encode(f.read()).decode()

response = requests.post(
    "https://api.getlykia.com/v1/images/generations",
    headers={"Authorization": f"Bearer {os.environ['LYKIA_API_KEY']}"},
    json={
        "model": "openai/gpt-image-2",
        "prompt": "Put the logo from the second image on the product in the first image",
        "images": ["https://example.com/product.png", logo],
    },
    timeout=300,
)
response.raise_for_status()
result = response.json()
print(result["data"][0]["url"])
print("cost (USD):", result["usage"]["cost"])
```

**TypeScript**

```typescript
import { readFile } from "node:fs/promises";

// A local file goes in as a data URI; a public https URL works as it is
const logo = `data:image/png;base64,${(await readFile("logo.png")).toString("base64")}`;

const response = await fetch("https://api.getlykia.com/v1/images/generations", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.LYKIA_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "openai/gpt-image-2",
    prompt: "Put the logo from the second image on the product in the first image",
    images: ["https://example.com/product.png", logo],
  }),
});
if (!response.ok) throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);

const result = (await response.json()) as { data: { url?: string }[]; usage: { cost: number } };
console.log(result.data[0].url);
console.log("cost (USD):", result.usage.cost);
```

How many source images a model takes is its `maxInputImages` capability (see below); a request with more returns `400`. Models that support inpainting also accept a `mask` in the same forms. Lykia does not keep the images you send.

## Size, aspect ratio, resolution and quality

Image models do not all describe their output the same way. Some take an exact `size` such as `1024x1536`, some an `aspect_ratio` such as `16:9`, some a `resolution` tier such as `2K`, and some several of these. Lykia passes the value you send to the provider in the provider's own terms and never drops it silently: a value the model does not support returns `400` with `metadata.param` naming the field, before anything is spent.

Read what a model accepts from the catalog. Image models are not in the default [`GET /models`](https://www.getlykia.com/en/docs/api-reference/models) list; ask for them with `?kind=image`, and look at `media.capabilities` on each item:

| Capability       | Meaning                                                                                                                 |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `sizes`          | The exact `size` values the model accepts.                                                                              |
| `sizeRule`       | Custom sizes are allowed within these bounds: `multipleOf`, `minEdge`, `maxEdge`, `maxRatio`, `minPixels`, `maxPixels`. |
| `aspectRatios`   | The `aspect_ratio` values.                                                                                              |
| `resolutions`    | The `resolution` tiers.                                                                                                 |
| `qualities`      | The `quality` values.                                                                                                   |
| `maxN`           | The most images per request (`n`).                                                                                      |
| `maxInputImages` | The most source images in `images`.                                                                                     |
| `mask`           | Whether `mask` is accepted.                                                                                             |
| `seed`           | Whether `seed` is accepted.                                                                                             |
| `outputFormats`  | The `output_format` values (`png`, `jpeg`, `webp`, and `svg` for vector models).                                        |

The same information is shown on each model's page in the [model catalog](https://www.getlykia.com/en/models).

## Provider-specific options

Options that only one provider has go in `provider_options`, for example a background setting or a style strength. Each model lists the options it allows in `media.capabilities.providerOptions`, with their type and range. An option that is not on the list returns `400` with `metadata.param` set to `provider_options.<name>`; nothing unlisted is passed on.

## Cost

Media models are priced per unit rather than per token. The unit depends on the model and is in `media.pricing` in the catalog:

- **Per image**, often with tiers by size, resolution or quality.
- **Per megapixel** of output (and sometimes of input), for models that price by pixels.
- **Per token**, for models whose provider bills image tokens. Lykia charges the tokens the provider reports.

Some models add a charge per source image or per request with a style reference; these show up as extra tiers and `surcharges`. Before the request runs, Lykia reserves the highest amount it can cost; afterwards it charges what the provider reports, never more than the reservation. A combination of options that has no price yet returns `400` (`unsupported_input`, "not priced yet") with Lykia credits and is not sent to the provider; with your own provider key it goes through.

With your own provider key (BYOK) the provider bills you and Lykia charges no credits for the image, as for chat. See [Bring your own provider keys](https://www.getlykia.com/en/docs/guides/byok).

## Slow providers

Some providers create images asynchronously. Lykia waits for the result within the request, up to a time it sets per model. If the image is not ready by then, Lykia tries to cancel it and returns `408` with the code `timeout`; you are not charged for it.

## Presets

`model` can be a preset such as `@image`, defined in the dashboard with its model and defaults (`size`, `aspect_ratio`, `quality`, `resolution`). See [Model presets](https://www.getlykia.com/en/docs/guides/model-presets).

## Errors

| Code                      | Status | When                                                                                                                                                         |
| ------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `unsupported_input`       | `400`  | A value the model does not support, an option outside `provider_options`, or an option combination that is not priced yet. `metadata.param` names the field. |
| `bad_request`             | `400`  | A field is malformed or out of range, for example `n` above the model's limit. `metadata.param` names the field.                                             |
| `unsupported_model`       | `400`  | The model does not generate images.                                                                                                                          |
| `storage_not_configured`  | `400`  | `response_format: "url"` while Lykia's storage is not available.                                                                                             |
| `platform_sales_disabled` | `403`  | The model's provider is not offered on Lykia credits yet. Add your own key for that provider to the project.                                                 |
| `timeout`                 | `408`  | An asynchronous provider did not finish in time. Not charged.                                                                                                |
| `provider_busy`           | `429`  | Lykia's connection to the provider is at its limit of requests at once. Retry after `Retry-After`.                                                           |

The error body and the rest of the status codes are described in [Errors](https://www.getlykia.com/en/docs/guides/errors).
