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

# Image Generation

> This guide will walk you through integrating image generation models into your application using Nscale's API. With our serverless architecture, you can focus on building your application without worrying about infrastructure management.

## Prerequisites

1. **Service Token:** Sign up on the Nscale platform to create your [**service token**](/docs/manage/service-tokens).
2. **Model Selection:** Choose an image generation model from Nscale's [model library](/docs/ai-services/models).
   * Example: FLUX.1 \[schnell] `black-forest-labs/FLUX.1-schnell`

## Step 1: Set up your environment

Before making requests, ensure you have the necessary tools installed for your language of choice:

For Python:
Install openai library

```bash theme={null}
pip install openai
```

For Typescript:
Install openai library

```bash theme={null}
npm install openai
```

For cURL:
Ensure cURL is installed on your system (it's usually pre-installed on most Unix-based systems).

## Step 2: Sending an image generation request

Let's walk through an example where we generate an image based on a text prompt.

**Request structure**

Each request to the Nscale Image Generation API endpoint should include the following:

1. Headers:
   * `"Authorization": "Bearer <SERVICE-TOKEN>"`
   * `"Content-Type": "application/json"`
2. Payload:
   * `"model"`: `"<model id e.g., black-forest-labs/FLUX.1-schnell>"`
   * `"prompt"`: `"<text description of the desired image>"`
   * `"size"`: `"<image size, defaults to 512x512>"`
   * `"n"`: `"<number of images to generate, defaults to 1>"`

Example use case: Generate a landscape at sunset

<CodeGroup>
  ```python Python theme={null}
  import os
  import openai

  nscale_service_token = os.getenv("NSCALE_SERVICE_TOKEN")
  nscale_base_url = "https://inference.api.nscale.com/v1"

  client = openai.OpenAI(
      api_key=nscale_service_token,
      base_url=nscale_base_url
  )

  response = client.images.generate(
      model="black-forest-labs/FLUX.1-schnell",
      prompt="A serene mountain landscape at sunset with a lake reflecting the orange sky",
      size="1024x1024",  # Optional
      n=1  # Optional
  )

  print(response.data[0].b64_json)
  ```

  ```typescript TypeScript theme={null}
  import OpenAI from 'openai';

  const nscaleServiceToken = process.env.NSCALE_SERVICE_TOKEN;
  const nscaleBaseUrl = "https://inference.api.nscale.com/v1";

  const client = new OpenAI({
      apiKey: nscaleServiceToken,
      baseURL: nscaleBaseUrl
  });

  const response = await client.images.generate({
      model: "black-forest-labs/FLUX.1-schnell",
      prompt: "A serene mountain landscape at sunset with a lake reflecting the orange sky",
      size: "1024x1024",  // Optional
      n: 1  // Optional
  });

  console.log(response.data[0].b64_json);
  ```

  ```bash cURL theme={null}
  curl https://inference.api.nscale.com/v1/images/generations \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $NSCALE_SERVICE_TOKEN" \
    -d '{
      "model": "black-forest-labs/FLUX.1-schnell",
      "prompt": "A serene mountain landscape at sunset with a lake reflecting the orange sky",
      "size": "1024x1024",
      "n": 1
    }'
  ```
</CodeGroup>

## Step 3: Understanding the Response

The response from the image generation API contains:

* A base64-encoded image in the `b64_json` field
* A timestamp of when the image was created
* The response is returned as a single object, with an array of generated images in the `data` field

Here's the output from the example request:

<img src="https://mintcdn.com/nscale/eHooAh3A-xA3WCln/images/image-generation-example.jpg?fit=max&auto=format&n=eHooAh3A-xA3WCln&q=85&s=0142bdfe7cce10032fa316368da41d76" alt="Example request generated image" width="1024" height="1024" data-path="images/image-generation-example.jpg" />

## Step 4: Using the CLI for Image Generation

You can also use the Nscale CLI to generate images. This is a convenient way to test models or build command-line applications.

### Prerequisites

* Ensure you have the [Nscale CLI installed](/docs/cli/overview)

### Examples

Here are some examples of using the CLI for image generation:

```bash theme={null}
# Generate an image with default settings
nscale images generate "A sunset over mountains" -t $NSCALE_SERVICE_TOKEN -m black-forest-labs/FLUX.1-schnell

# Generate an image with custom size
nscale images generate "A futuristic city" -z 1024x1024 -t $NSCALE_SERVICE_TOKEN -m black-forest-labs/FLUX.1-schnell

# Generate and automatically open the image
nscale images generate "A cat playing piano" -x -t $NSCALE_SERVICE_TOKEN -m black-forest-labs/FLUX.1-schnell

# Generate with ASCII preview
nscale images generate "An abstract painting" -p -t $NSCALE_SERVICE_TOKEN -m black-forest-labs/FLUX.1-schnell

# Generate with custom output location
nscale images generate "A forest landscape" -o ./my-image.png -t $NSCALE_SERVICE_TOKEN -m black-forest-labs/FLUX.1-schnell

# Use service token from environment variable
export NSCALE_SERVICE_TOKEN=your_service_token
nscale images generate "A sunset over mountains" -m black-forest-labs/FLUX.1-schnell
```

For more details on CLI usage, refer to the [CLI documentation](/docs/cli/overview).

## Step 5: Monitoring and scaling

Nscale handles scaling automatically based on traffic patterns—no manual intervention needed! Use the Nscale Console to monitor:

* API usage by model
* Spend breakdowns

For custom models or high-throughput applications on dedicated endpoints, contact Nscale Support.

## Troubleshooting

Common status codes and their meanings:

| Status | Description                           | Response Format                             |
| ------ | ------------------------------------- | ------------------------------------------- |
| 200    | Success                               | `application/json` response with image data |
| 401    | Invalid service token or unauthorized | Error object                                |
| 404    | Model not found or unavailable        | Error object                                |
| 429    | Insufficient credit                   | Error object                                |
| 500    | Internal server error                 | Error object                                |
| 503    | Service temporarily unavailable       | Error object                                |

### Success Response Format (200)

```json theme={null}
{
  "created": 1677652288,
  "data": [
    {
      "b64_json": "iVBORw0KGgoAAAANSUhEUgAA..."
    }
  ]
}
```

### Error Response Format

```json theme={null}
{
  "error": {
    "code": "TOO_MANY_REQUESTS",
    "message": "You have insufficient credit to run this request",
    "param": null,
    "error_type": "INSUFFICIENT_CREDIT"
  }
}
```

For the extensive list of error codes and handling, see the [error code page](https://nscale.mintlify.app/docs/faqs/error-codes)

## Available Models

For a complete list of available image generation models and their pricing, please refer to our [models page](/docs/ai-services/models).

<Card title="Contact Support" icon="headset" iconType="solid" href="mailto:helpdesk@nscale.com">
  Need assistance? Get help from our support team
</Card>
