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

# Image Generations

export const OpenAIImageGeneration = ({model}) => {
  const curlExample = `curl --location 'https://aiandgpu.com/sp/v1/images/generations' \\
--header 'Authorization: Bearer <YOUR_API_KEY>' \\
--header 'Content-Type: application/json' \\
--header 'Idempotency-Key: img-20260922-001' \\
--data '{
  "model": "${model}",
  "prompt": "a red fox in a snowy forest, cinematic light",
  "n": 1,
  "size": "1024x1024"
}'`;
  const pythonExample = `import uuid
import requests

api_key = "<YOUR_API_KEY>"
base_url = "https://aiandgpu.com"

create_response = requests.post(
    f"{base_url}/sp/v1/images/generations",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "Idempotency-Key": f"img-{uuid.uuid4()}",
    },
    json={
        "model": "${model}",
        "prompt": "a red fox in a snowy forest, cinematic light",
        "n": 1,
        "size": "1024x1024",
    },
)
create_response.raise_for_status()
print(create_response.json())`;
  const jsExample = `const { randomUUID } = require("node:crypto");

const apiKey = "<YOUR_API_KEY>";
const baseUrl = "https://aiandgpu.com";

async function main() {
  const createResponse = await fetch(\`\${baseUrl}/sp/v1/images/generations\`, {
    method: "POST",
    headers: {
      Authorization: \`Bearer \${apiKey}\`,
      "Content-Type": "application/json",
      "Idempotency-Key": \`img-\${randomUUID()}\`,
    },
    body: JSON.stringify({
      model: "${model}",
      prompt: "a red fox in a snowy forest, cinematic light",
      n: 1,
      size: "1024x1024",
    }),
  });

  console.log(await createResponse.json());
}

main().catch(console.error);`;
  const goExample = `package main

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

func main() {
\tapiKey := "<YOUR_API_KEY>"
\tbaseURL := "https://aiandgpu.com"

\tbody, _ := json.Marshal(map[string]any{
\t\t"model":  "${model}",
\t\t"prompt": "a red fox in a snowy forest, cinematic light",
\t\t"n":      1,
\t\t"size":   "1024x1024",
\t})

\treq, _ := http.NewRequest("POST", baseURL+"/sp/v1/images/generations", bytes.NewReader(body))
\treq.Header.Set("Authorization", "Bearer "+apiKey)
\treq.Header.Set("Content-Type", "application/json")
\treq.Header.Set("Idempotency-Key", "img-20260922-001")

\tres, _ := http.DefaultClient.Do(req)
\tdefer res.Body.Close()
\tcreateBody, _ := io.ReadAll(res.Body)

\tvar task map[string]any
\tjson.Unmarshal(createBody, &task)

\tresult, _ := json.MarshalIndent(task, "", "  ")
\tfmt.Println(string(result))
}`;
  const javaExample = `import okhttp3.*;

OkHttpClient client = new OkHttpClient();
String apiKey = "<YOUR_API_KEY>";
String baseUrl = "https://aiandgpu.com";

RequestBody body = RequestBody.create("""
{
  "model": "${model}",
  "prompt": "a red fox in a snowy forest, cinematic light",
  "n": 1,
  "size": "1024x1024"
}
""", MediaType.parse("application/json"));

Request createRequest = new Request.Builder()
    .url(baseUrl + "/sp/v1/images/generations")
    .header("Authorization", "Bearer " + apiKey)
    .header("Content-Type", "application/json")
    .header("Idempotency-Key", "img-20260922-001")
    .post(body)
    .build();

try (Response response = client.newCall(createRequest).execute()) {
    System.out.println(response.body().string());
}`;
  const phpExample = `<?php

$apiKey = "<YOUR_API_KEY>";

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "https://aiandgpu.com/sp/v1/images/generations",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => json_encode([
        "model" => "${model}",
        "prompt" => "a red fox in a snowy forest, cinematic light",
        "n" => 1,
        "size" => "1024x1024",
    ]),
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . $apiKey,
        "Content-Type: application/json",
        "Idempotency-Key: img-20260922-001",
    ],
]);

$response = curl_exec($curl);
curl_close($curl);

echo $response;`;
  const csharpExample = `using System.Net.Http;
using System.Text;

var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer <YOUR_API_KEY>");
client.DefaultRequestHeaders.Add("Idempotency-Key", "img-20260922-001");

var json = """
{
  "model": "${model}",
  "prompt": "a red fox in a snowy forest, cinematic light",
  "n": 1,
  "size": "1024x1024"
}
""";

var response = await client.PostAsync(
    "https://aiandgpu.com/sp/v1/images/generations",
    new StringContent(json, Encoding.UTF8, "application/json")
);

var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);`;
  const imageToImageCurlExample = `curl --location 'https://aiandgpu.com/sp/v1/images/generations' \\
--header 'Authorization: Bearer <YOUR_API_KEY>' \\
--header 'Content-Type: application/json' \\
--header 'Idempotency-Key: img-20260922-002' \\
--data '{
  "model": "${model}",
  "prompt": "Replace the background with snowy mountains while keeping the person unchanged",
  "image_urls": ["https://cdn.example.com/input.png"],
  "mask_url": "https://cdn.example.com/mask.png",
  "n": 1,
  "size": "1024x1024",
  "quality": "high",
  "input_fidelity": "high"
}'`;
  const imageToImagePythonExample = `import uuid
import requests

api_key = "<YOUR_API_KEY>"
base_url = "https://aiandgpu.com"

create_response = requests.post(
    f"{base_url}/sp/v1/images/generations",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "Idempotency-Key": f"img-{uuid.uuid4()}",
    },
    json={
        "model": "${model}",
        "prompt": "Replace the background with snowy mountains while keeping the person unchanged",
        "image_urls": ["https://cdn.example.com/input.png"],
        "mask_url": "https://cdn.example.com/mask.png",
        "n": 1,
        "size": "1024x1024",
        "quality": "high",
        "input_fidelity": "high",
    },
)
create_response.raise_for_status()
print(create_response.json())`;
  const imageToImageJsExample = `const { randomUUID } = require("node:crypto");

const apiKey = "<YOUR_API_KEY>";
const baseUrl = "https://aiandgpu.com";

async function main() {
  const createResponse = await fetch(\`\${baseUrl}/sp/v1/images/generations\`, {
    method: "POST",
    headers: {
      Authorization: \`Bearer \${apiKey}\`,
      "Content-Type": "application/json",
      "Idempotency-Key": \`img-\${randomUUID()}\`,
    },
    body: JSON.stringify({
      model: "${model}",
      prompt: "Replace the background with snowy mountains while keeping the person unchanged",
      image_urls: ["https://cdn.example.com/input.png"],
      mask_url: "https://cdn.example.com/mask.png",
      n: 1,
      size: "1024x1024",
      quality: "high",
      input_fidelity: "high",
    }),
  });

  console.log(await createResponse.json());
}

main().catch(console.error);`;
  const imageToImageGoExample = `package main

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

func main() {
\tapiKey := "<YOUR_API_KEY>"
\tbaseURL := "https://aiandgpu.com"

\tbody, _ := json.Marshal(map[string]any{
\t\t"model":          "${model}",
\t\t"prompt":         "Replace the background with snowy mountains while keeping the person unchanged",
\t\t"image_urls":     []string{"https://cdn.example.com/input.png"},
\t\t"mask_url":       "https://cdn.example.com/mask.png",
\t\t"n":              1,
\t\t"size":           "1024x1024",
\t\t"quality":        "high",
\t\t"input_fidelity": "high",
\t})

\treq, _ := http.NewRequest("POST", baseURL+"/sp/v1/images/generations", bytes.NewReader(body))
\treq.Header.Set("Authorization", "Bearer "+apiKey)
\treq.Header.Set("Content-Type", "application/json")
\treq.Header.Set("Idempotency-Key", "img-20260922-002")

\tres, _ := http.DefaultClient.Do(req)
\tdefer res.Body.Close()
\tcreateBody, _ := io.ReadAll(res.Body)

\tvar task map[string]any
\tjson.Unmarshal(createBody, &task)

\tresult, _ := json.MarshalIndent(task, "", "  ")
\tfmt.Println(string(result))
}`;
  const imageToImageJavaExample = `import okhttp3.*;

OkHttpClient client = new OkHttpClient();
String apiKey = "<YOUR_API_KEY>";
String baseUrl = "https://aiandgpu.com";

RequestBody body = RequestBody.create("""
{
  "model": "${model}",
  "prompt": "Replace the background with snowy mountains while keeping the person unchanged",
  "image_urls": ["https://cdn.example.com/input.png"],
  "mask_url": "https://cdn.example.com/mask.png",
  "n": 1,
  "size": "1024x1024",
  "quality": "high",
  "input_fidelity": "high"
}
""", MediaType.parse("application/json"));

Request createRequest = new Request.Builder()
    .url(baseUrl + "/sp/v1/images/generations")
    .header("Authorization", "Bearer " + apiKey)
    .header("Content-Type", "application/json")
    .header("Idempotency-Key", "img-20260922-002")
    .post(body)
    .build();

try (Response response = client.newCall(createRequest).execute()) {
    System.out.println(response.body().string());
}`;
  const imageToImagePhpExample = `<?php

$apiKey = "<YOUR_API_KEY>";

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "https://aiandgpu.com/sp/v1/images/generations",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => json_encode([
        "model" => "${model}",
        "prompt" => "Replace the background with snowy mountains while keeping the person unchanged",
        "image_urls" => ["https://cdn.example.com/input.png"],
        "mask_url" => "https://cdn.example.com/mask.png",
        "n" => 1,
        "size" => "1024x1024",
        "quality" => "high",
        "input_fidelity" => "high",
    ]),
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . $apiKey,
        "Content-Type: application/json",
        "Idempotency-Key: img-20260922-002",
    ],
]);

$response = curl_exec($curl);
curl_close($curl);

echo $response;`;
  const imageToImageCsharpExample = `using System.Net.Http;
using System.Text;

var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer <YOUR_API_KEY>");
client.DefaultRequestHeaders.Add("Idempotency-Key", "img-20260922-002");

var json = """
{
  "model": "${model}",
  "prompt": "Replace the background with snowy mountains while keeping the person unchanged",
  "image_urls": ["https://cdn.example.com/input.png"],
  "mask_url": "https://cdn.example.com/mask.png",
  "n": 1,
  "size": "1024x1024",
  "quality": "high",
  "input_fidelity": "high"
}
""";

var response = await client.PostAsync(
    "https://aiandgpu.com/sp/v1/images/generations",
    new StringContent(json, Encoding.UTF8, "application/json")
);

var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);`;
  return <>
            <h2>Request Examples</h2>

            <h3>Text to image</h3>
            <CodeGroup>
                <CodeBlock language="shellscript" filename="cURL">
                    {curlExample}
                </CodeBlock>
                <CodeBlock language="python" filename="Python">
                    {pythonExample}
                </CodeBlock>
                <CodeBlock language="javascript" filename="JavaScript">
                    {jsExample}
                </CodeBlock>
                <CodeBlock language="go" filename="Go">
                    {goExample}
                </CodeBlock>
                <CodeBlock language="java" filename="Java">
                    {javaExample}
                </CodeBlock>
                <CodeBlock language="php" filename="PHP">
                    {phpExample}
                </CodeBlock>
                <CodeBlock language="csharp" filename="C#">
                    {csharpExample}
                </CodeBlock>
            </CodeGroup>

            <h3>Image to image</h3>
            <CodeGroup>
                <CodeBlock language="shellscript" filename="cURL">
                    {imageToImageCurlExample}
                </CodeBlock>
                <CodeBlock language="python" filename="Python">
                    {imageToImagePythonExample}
                </CodeBlock>
                <CodeBlock language="javascript" filename="JavaScript">
                    {imageToImageJsExample}
                </CodeBlock>
                <CodeBlock language="go" filename="Go">
                    {imageToImageGoExample}
                </CodeBlock>
                <CodeBlock language="java" filename="Java">
                    {imageToImageJavaExample}
                </CodeBlock>
                <CodeBlock language="php" filename="PHP">
                    {imageToImagePhpExample}
                </CodeBlock>
                <CodeBlock language="csharp" filename="C#">
                    {imageToImageCsharpExample}
                </CodeBlock>
            </CodeGroup>
        </>;
};

## Authorization

* **Auth Type**: `Bearer Auth` (In: `header`)
* **Format**: `Authorization: Bearer <YOUR_API_KEY>`
* **Description**: Use `Bearer <YOUR_API_KEY>`. Format: `Authorization: Bearer sk-xxxxxx.`
* **API Key**: where <strong>API Key</strong> is your <a href="https://developer.aiandgpu.com" target="_blank" rel="noopener noreferrer">AGCloud API KEY</a>

Create an image generation task with `POST /sp/v1/images/generations`. The response returns a task ID that you can use with the [query task](/api-reference/openAI/gpt-image-2/query-task-sp) endpoint.

The same create endpoint supports both text-to-image and image-to-image flows:

* Omit `image_urls` to generate an image from `prompt`.
* Provide one or more `image_urls` to generate or edit images from references.

<OpenAIImageGeneration model="sp-gpt-image-2" />

## Headers

| Header | Required | Description |
| :- | :- | :- |
| `Authorization` | ✅ | `Bearer <API_KEY>` |
| `Content-Type` | ✅ | Must be `application/json`. |
| `Idempotency-Key` | - | Idempotency key for safe retries. If omitted, the server generates one and returns it in the response header. |

`Idempotency-Key` must match `^[A-Za-z0-9._:-]{1,128}$`.

Use a new idempotency key for each new task. If a request times out and you retry the same task, reuse the same key with the exact same request body. Reusing a key with a different body returns `409 idempotency_conflict`.

## Request Parameters

Only `model` and `prompt` are strictly required. Other fields are handled according to model capability; unsupported combinations may create a task that later reaches `failed` with details in `error`.

| Field | Type | Required | Default | Description |
| :- | :- | :- | :- | :- |
| `model` | string | ✅ | - | Model ID enabled for your account, for example `sp-gpt-image-2`. |
| `prompt` | string | ✅ | - | Image generation or editing prompt. Cannot be empty. |
| `image_urls` | string\[] | - | - | Reference images. Each item supports a public HTTPS URL or a base64 image Data URL. Non-empty values enable image-to-image or image editing behavior. |
| `mask_url` | string | - | - | Mask image for inpainting. Usually used together with `image_urls`; supports the same URL formats. |
| `n` | integer | - | `1` | Number of images to generate. Usually `1` to `4`. |
| `size` | string | - | - | Output size, for example `1024x1024` or `2048x2048`. Supported values depend on the model. |
| `quality` | string | - | - | Quality tier. Supported values depend on the model. |
| `response_format` | string | - | - | Response format option. Supported values depend on the model. |
| `background` | string | - | - | Background option. Supported values depend on the model. |
| `input_fidelity` | string | - | - | Reference image fidelity tier. Supported values depend on the model. |
| `output_format` | string | - | - | Output image format. Supported values depend on the model. |
| `output_compression` | integer | - | - | Output compression level, usually `0` to `100`. Only applies when supported by the selected output format and model. |
| `user` | string | - | - | Your application-side end-user identifier. |
| `extra` | object | - | - | Extension parameters. |
| `copy` | object | - | - | Reserved marketing-copy object. May include `headline`, `subheadline`, `selling_points`, `activity_time`, and `cta`. |
| `brand` | object | - | - | Reserved brand object. May include `logo_url`, `primary_color`, and `secondary_color`. |

## Base64 Reference Images

`image_urls` and `mask_url` can contain base64 image Data URLs in this format:

```text theme={null}
data:image/<subtype>;base64,<base64 data>
```

| Item | Rule |
| :- | :- |
| Image subtype | Supports `png`, `jpeg`, `jpg`, `webp`, and `gif`; case-insensitive. |
| Separator | Must use `;base64,`. |
| Encoding | Must use standard base64 with `+`, `/`, and `=`. URL-safe base64 is not supported. |
| Whitespace | Line breaks and spaces in the base64 payload are ignored. |
| Size limit | Each decoded image must be no larger than `180 MB`; the whole HTTP request body must be no larger than `256 MB`. |

## Create Response

Creation succeeds with `202 Accepted`. The response header contains the idempotency key used for this request.

```http theme={null}
Idempotency-Key: img-20260922-001
```

<CodeGroup>
  ```json 202 - Accepted theme={null}
  {
    "id": "gen_5a1b2c3d4e5f60718293a4b5c6d7e8f9",
    "object": "image.generation",
    "status": "queued",
    "model": "sp-gpt-image-2",
    "created": 1786000000
  }
  ```
</CodeGroup>

| Field | Type | Description |
| :- | :- | :- |
| `id` | string | Task ID used to query the result. |
| `object` | string | Always `image.generation`. |
| `status` | string | Usually `queued` immediately after creation. |
| `model` | string | Model ID used for the task. |
| `created` | integer | Creation time as Unix seconds. |

## Error Responses

Non-2xx responses use a unified error format:

```json theme={null}
{
  "error": {
    "type": "api_error",
    "code": "invalid_parameter",
    "message": "field 'model' is required"
  }
}
```

| HTTP Status | Code | Description |
| :- | :- | :- |
| `400` | `invalid_parameter` | Invalid request parameters, such as missing `model` or `prompt`, or an invalid JSON body. |
| `400` | `invalid_idempotency_key` | Invalid `Idempotency-Key` format. |
| `401` | `invalid_api_key` | API key is missing or invalid. |
| `402` | `insufficient_balance` | Account balance or quota is insufficient. |
| `403` | `model_access_denied` | Current API key cannot access the requested model. |
| `403` | `model_disabled` | The model is currently disabled. |
| `404` | `model_not_found` | The model does not exist or is not enabled for the account. |
| `409` | `idempotency_conflict` | The same `Idempotency-Key` was used with a different request body. |
| `500` | `task_store_error` | Internal task storage error. |
| `503` | `service_unavailable` | Service is temporarily unavailable. Retry later. |

## Recommended Flow

1. Generate a new `Idempotency-Key` on the client.
2. Call `POST /sp/v1/images/generations` to create a task.
3. Store the returned `id`.
4. Poll `GET /sp/v1/images/generations/{id}` on the [query task](/api-reference/openAI/gpt-image-2/query-task-sp) page until `status` is terminal.


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