Use Gemini's imageConfig with AI Proxy in Kong AI Gateway

Deployment Platform
Tags
#ai
Minimum Version
Kong Gateway - 3.13
TL;DR

Configure the AI Proxy plugin with the Gemini provider and gemini-3-pro-image-preview model, then pass imageConfig parameters via generationConfig in your image generation requests.

Prerequisites

This is a Konnect tutorial and requires a Konnect personal access token.

  1. Create a new personal access token by opening the Konnect PAT page and selecting Generate Token.

  2. Export your token to an environment variable:

     export KONNECT_TOKEN='YOUR_KONNECT_PAT'
    
  3. Run the quickstart script to automatically provision a Control Plane and Data Plane, and configure your environment:

     curl -Ls https://get.konghq.com/quickstart | bash -s -- -k $KONNECT_TOKEN --deck-output
    

    This sets up a Konnect Control Plane named quickstart, provisions a local Data Plane, and prints out the following environment variable exports:

     export DECK_KONNECT_TOKEN=$KONNECT_TOKEN
     export DECK_KONNECT_CONTROL_PLANE_NAME=quickstart
     export KONNECT_CONTROL_PLANE_URL=https://us.api.konghq.com
     export KONNECT_PROXY_URL='http://localhost:8000'
    

    Copy and paste these into your terminal to configure your session.

This tutorial requires Kong Gateway Enterprise. If you don’t have Kong Gateway set up yet, you can use the quickstart script with an enterprise license to get an instance of Kong Gateway running almost instantly.

  1. Export your license to an environment variable:

     export KONG_LICENSE_DATA='LICENSE-CONTENTS-GO-HERE'
    
  2. Run the quickstart script:

    curl -Ls https://get.konghq.com/quickstart | bash -s -- -e KONG_LICENSE_DATA 
    

    Once Kong Gateway is ready, you will see the following message:

     Kong Gateway Ready
    

decK is a CLI tool for managing Kong Gateway declaratively with state files. To complete this tutorial, install decK version 1.43 or later.

This guide uses deck gateway apply, which directly applies entity configuration to your Gateway instance. We recommend upgrading your decK installation to take advantage of this tool.

You can check your current decK version with deck version.

For this tutorial, you’ll need Kong Gateway entities, like Gateway Services and Routes, pre-configured. These entities are essential for Kong Gateway to function but installing them isn’t the focus of this guide. Follow these steps to pre-configure them:

  1. Run the following command:

    echo '
    _format_version: "3.0"
    services:
      - name: example-service
        url: http://httpbin.konghq.com/anything
    routes:
      - name: example-route
        paths:
        - "/anything"
        service:
          name: example-service
    ' | deck gateway apply -
    

To learn more about entities, you can read our entities documentation.

Before you begin, you must get the following credentials from Google Cloud:

  • Service Account Key: A JSON key file for a service account with Vertex AI permissions
  • Project ID: Your Google Cloud project identifier
  • API Endpoint: The global Vertex AI API endpoint https://aiplatform.googleapis.com

After creating the key, convert the contents of modelarmor-admin-key.json into a single-line JSON string. Escape all necessary characters — quotes (") and newlines (\n) — so that it becomes a valid one-line JSON string. Then export your credentials as environment variables:

export DECK_GCP_SERVICE_ACCOUNT_JSON="<single-line-escaped-json>"
export DECK_GCP_SERVICE_ACCOUNT_JSON="your-service-account-json"
export DECK_GCP_PROJECT_ID="your-project-id"

To complete this tutorial, you’ll need Python (version 3.7 or later) and pip installed on your machine. You can verify it by running:

python3
python3 -m pip --version

Install the OpenAI SDK the requests library:

pip install openai requests

Configure the plugin

Configure AI Proxy to use the gemini-3-pro-image-preview model for image generation via Vertex AI:

echo '
_format_version: "3.0"
plugins:
  - name: ai-proxy
    config:
      genai_category: image/generation
      route_type: image/v1/images/generations
      logging:
        log_payloads: false
        log_statistics: true
      model:
        provider: gemini
        name: gemini-3-pro-image-preview
        options:
          gemini:
            api_endpoint: aiplatform.googleapis.com
            project_id: "${{ env "DECK_GCP_PROJECT_ID" }}"
            location_id: global
      auth:
        allow_override: false
        gcp_use_service_account: true
        gcp_service_account_json: "${{ env "DECK_GCP_SERVICE_ACCOUNT_JSON" }}"
' | deck gateway apply -

Use imageConfig with image generation

Gemini 3 models support image generation with configurable parameters via imageConfig. This feature allows you to control the aspect ratio and resolution of generated images. For more information, see Gemini Image Generation.

The imageConfig supports the following parameters:

  • aspectRatio (string): Controls the aspect ratio of the generated image. Supported values include 1:1, 4:3, 16:9, and others.
  • imageSize (string): Controls the resolution of the generated image. Accepted values include 1k, 2k, and 4k.

Kong Gateway now supports passing generationConfig parameters through to Gemini. Any parameters within reasonable size limits will be forwarded to the Gemini API, allowing you to use Gemini-specific features like imageConfig.

Create a Python script to generate images with different configurations:

cat << 'EOF' > generate-images.py
#!/usr/bin/env python3
"""Generate images with Gemini 3 via Kong AI Gateway using imageConfig"""
import requests
import base64
BASE_URL = "http://localhost:8000/anything"
print("Generating images with Gemini 3 imageConfig")
print("=" * 50)
# Example 1: 4:3 aspect ratio, 1k resolution
print("\n=== Example 1: 4:3 Aspect Ratio, 1k Size ===")
try:
    response = requests.post(
        BASE_URL,
        headers={"Content-Type": "application/json"},
        json={
            "model": "gemini-3-pro-image-preview",
            "prompt": "Generate a simple red circle on white background",
            "n": 1,
            "generationConfig": {
                "imageConfig": {
                    "aspectRatio": "4:3",
                    "imageSize": "1k"
                }
            }
        }
    )
    response.raise_for_status()
    data = response.json()
    print(f"✓ Image generated (4:3, 1k)")
    image_data = data['data'][0]
    if 'url' in image_data:
        img_response = requests.get(image_data['url'])
        with open("circle_4x3_1k.png", "wb") as f:
            f.write(img_response.content)
        print(f"Saved to circle_4x3_1k.png")
    elif 'b64_json' in image_data:
        image_bytes = base64.b64decode(image_data['b64_json'])
        with open("circle_4x3_1k.png", "wb") as f:
            f.write(image_bytes)
        print(f"Saved to circle_4x3_1k.png")
except Exception as e:
    print(f"Failed: {e}")
# Example 2: 16:9 aspect ratio, 2k resolution
print("\n=== Example 2: 16:9 Aspect Ratio, 2k Size ===")
try:
    response = requests.post(
        BASE_URL,
        headers={"Content-Type": "application/json"},
        json={
            "model": "gemini-3-pro-image-preview",
            "prompt": "A minimalist landscape with mountains and a sunset",
            "n": 1,
            "generationConfig": {
                "imageConfig": {
                    "aspectRatio": "16:9",
                    "imageSize": "2k"
                }
            }
        }
    )
    response.raise_for_status()
    data = response.json()
    print(f"✓ Image generated (16:9, 2k)")
    image_data = data['data'][0]
    if 'url' in image_data:
        img_response = requests.get(image_data['url'])
        with open("landscape_16x9_2k.png", "wb") as f:
            f.write(img_response.content)
        print(f"Saved to landscape_16x9_2k.png")
    elif 'b64_json' in image_data:
        image_bytes = base64.b64decode(image_data['b64_json'])
        with open("landscape_16x9_2k.png", "wb") as f:
            f.write(image_bytes)
        print(f"Saved to landscape_16x9_2k.png")
except Exception as e:
    print(f"Failed: {e}")
# Example 3: 1:1 aspect ratio, 4k resolution
print("\n=== Example 3: 1:1 Aspect Ratio, 4k Size ===")
try:
    response = requests.post(
        BASE_URL,
        headers={"Content-Type": "application/json"},
        json={
            "model": "gemini-3-pro-image-preview",
            "prompt": "A 24px by 24px green capital letter 'A' with a subtle shadow on white background",
            "n": 1,
            "generationConfig": {
                "imageConfig": {
                    "aspectRatio": "1:1",
                    "imageSize": "4k"
                }
            }
        }
    )
    response.raise_for_status()
    data = response.json()
    print(f"✓ Image generated (1:1, 4k)")
    image_data = data['data'][0]
    if 'url' in image_data:
        img_response = requests.get(image_data['url'])
        with open("letter_a_1x1_4k.png", "wb") as f:
            f.write(img_response.content)
        print(f"Saved to letter_a_1x1_4k.png")
    elif 'b64_json' in image_data:
        image_bytes = base64.b64decode(image_data['b64_json'])
        with open("letter_a_1x1_4k.png", "wb") as f:
            f.write(image_bytes)
        print(f"Saved to letter_a_1x1_4k.png")
except Exception as e:
    print(f"Failed: {e}")
print("\n" + "=" * 50)
print("Complete")
EOF

This script demonstrates three different image generation configurations:

  1. 4:3 aspect ratio with 1k resolution: Generates a simple shape with standard definition.
  2. 16:9 aspect ratio with 2k resolution: Produces a widescreen landscape with higher resolution.
  3. 1:1 aspect ratio with 4k resolution: Creates a square image with maximum resolution.

The script uses the OpenAI Images API format (/v1/images/generations endpoint) with the generationConfig parameter to pass Gemini-specific configuration. Kong AI Gateway forwards these parameters to Vertex AI and returns the generated images as either URLs or base64-encoded data. The script handles both response formats and saves the images locally.

Run the script:

python3 generate-images.py

Example output:

Generating images with Gemini 3 imageConfig
==================================================

=== Example 1: 4:3 Aspect Ratio, 1k Size ===
✓ Image generated (4:3, 1k)
Saved to circle_4x3_1k.png

=== Example 2: 16:9 Aspect Ratio, 2k Size ===
✓ Image generated (16:9, 2k)
Saved to landscape_16x9_2k.png

=== Example 3: 1:1 Aspect Ratio, 4k Size ===
✓ Image generated (1:1, 4k)
Saved to letter_a_1x1_4k.png

==================================================
Complete

Open the generated images:

open circle_4x3_1k.png
open landscape_16x9_2k.png
open letter_a_1x1_4k.png

The script generates three images with different aspect ratios and resolutions, demonstrating how imageConfig controls the output dimensions and quality. All generated images are saved to the current directory.

Cleanup

If you created a new control plane and want to conserve your free trial credits or avoid unnecessary charges, delete the new control plane used in this tutorial.

curl -Ls https://get.konghq.com/quickstart | bash -s -- -d

FAQs

The imageConfig feature requires Kong Gateway 3.13 or later.

Gemini 3 supports aspect ratios including 1:1 (square), 4:3, and 16:9. Refer to the Gemini documentation for a complete list of supported ratios.

The imageSize parameter accepts values like 1k, 2k, and 4k. Higher values produce higher resolution images but may increase generation time.

Something wrong?

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!