# Create images

> Generate images from a prompt, or edit images you send with it. OpenAI Images compatible, with signed links or base64 output and the cost in usage.

`POST https://api.getlykia.com/v1/images/generations`

Generates images, or edits the images you send in `images`. The request and response follow OpenAI's Images API, so `images.generate` in the OpenAI SDKs works against this endpoint. Keys, project budgets, key limits, presets, tags and request records work as for [`POST /chat/completions`](https://www.getlykia.com/en/docs/api-reference/chat-completions). Walkthrough: [Image generation](https://www.getlykia.com/en/docs/guides/image-generation).

## Request body

- `model` (string, required) — An image model id (for example `openai/gpt-image-2`), or a preset as `@name` whose model makes images (for example `@image`). List image models with `GET /models?kind=image`.
- `prompt` (string, required) — What to draw, or how to change the images in `images`.
- `n` (integer) — How many images, from 1 to the model's `maxN`.
- `size` (string) — Exact size such as `1024x1024`, for models that take one (`sizes`, `sizeRule`).
- `aspect_ratio` (string) — Such as `16:9`, for models that take one (`aspectRatios`).
- `resolution` (string) — A resolution tier such as `2K` (`resolutions`).
- `quality` (string) — A quality level such as `high` (`qualities`).
- `seed` (integer) — For repeatable results, on models that support it.
- `output_format` (string) — `png`, `jpeg`, `webp` or `svg`, as the model allows (`outputFormats`).
- `images` (array) — Up to 16 source images for editing or as references (the model's `maxInputImages` decides): a public `https://` URL, a `data:<type>;base64,…` URI, `{ "url" }`, `{ "image_url": { "url" } }` or `{ "b64_json", "mime_type" }`.
- `mask` (string | object) — A mask for inpainting, in the same forms, on models with `mask`.
- `response_format` (string) — `url` (default) for a signed link, or `b64_json` for the bytes inline. When Lykia's storage is not available the default is `b64_json`.
- `provider_options` (object) — Provider-specific options from the model's allow-list (`providerOptions`). Anything else returns `400`.
- `models` (string\[]) — Fallback models, as in chat.
- `provider` (object) — Provider preferences: `order`, `only`, `ignore`, `allow_fallbacks`. See [Provider routing](https://www.getlykia.com/en/docs/guides/provider-routing).
- `user` (string) and `metadata` (object) — Tags stored with the request record and never sent to the provider. See [Tags and usage breakdown](https://www.getlykia.com/en/docs/guides/tags-and-usage).

Values the model does not support are rejected with `400` and the field's name in `metadata.param`, never dropped.

## Example

**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
        }
    }
}
```

## Response

- `id` (string) — The request id (also in the `X-Generation-Id` header).
- `object` (string) — Always `image.generation`.
- `created` (integer) — Unix time.
- `model` (string) — The model that made the images; with a preset, the real model.
- `provider` (string) — The provider that served the request.
- `data` (array) — One item per image.
  - `url` (string) — A signed link to the original file in Lykia's storage, valid for one hour (`response_format: "url"`).
  - `b64_json` (string) — The image bytes in base64 (`response_format: "b64_json"`).
  - `mime_type` (string) — For example `image/png`.
  - `width`, `height` (integer) — When known.
  - `revised_prompt` (string) — When the provider rewrote the prompt.
  - `expires_at` (string) — When `url` stops working (ISO 8601).
- `usage` (object) — `images` (the number of images), `cost` in USD, `is_byok`, `cost_details` (`upstream_cost`, `platform_fee`, `is_byok`) and `units` (what was billed, such as images, megapixels or tokens by type).

Headers: `X-Generation-Id`, `X-Lykia-Cost` (the cost in USD) and `X-Lykia-Preset` when `model` was a preset.

## Errors

| Status | Code                      | When                                                                                                                                                                          |
| ------ | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`  | `unsupported_input`       | An unsupported value or `provider_options` entry (`metadata.param`), or an option combination that is not priced yet ("not priced yet"; it works with your own provider key). |
| `400`  | `bad_request`             | A malformed or out-of-range field, such as `n` above `maxN` (`metadata.param`).                                                                                               |
| `400`  | `unsupported_model`       | The model does not make images.                                                                                                                                               |
| `400`  | `storage_not_configured`  | `response_format: "url"` while Lykia's storage is not available.                                                                                                              |
| `402`  | `insufficient_credits`    | The balance, key limit or project budget cannot cover the reservation.                                                                                                        |
| `403`  | `platform_sales_disabled` | The provider is not offered on Lykia credits yet; add your own key for it.                                                                                                    |
| `403`  | `byok_only_no_key`        | The project only allows its own provider keys and has none for this model.                                                                                                    |
| `408`  | `timeout`                 | An asynchronous provider did not finish in time (`provider_code: image_wait_exceeded`). Not charged.                                                                          |
| `429`  | `provider_busy`           | Lykia's connection to the provider is at its limit of requests at once; retry after `Retry-After`.                                                                            |

Other codes are as in [Errors](https://www.getlykia.com/en/docs/guides/errors). A provider that charges for a rejected request (for example on content grounds) is reported with `metadata.billed_by_provider: true`, and that cost is charged.
