Skip to main content

Image generation

Generate images from natural language prompts and remove backgrounds from existing images.

Why Use AI Image Generation

Your application needs custom imagery: a hero illustration that matches a user's prompt, an avatar based on a description, a product mock-up for an e-commerce listing, or a clean cut-out for a profile photo. Using a stock library is too generic, and integrating with each model provider directly means juggling API keys, request shapes, polling logic, and storage.

Squid AI Image gives you a single backend API for several image models and a built-in background removal endpoint:

Backend code
const url = await this.squid.ai().image().generate('a pirate ship at sunset, oil painting style', {
modelName: 'dall-e-3',
size: '1024x1024',
quality: 'hd',
});

Overview

Squid AI Image wraps three families of image models behind a single client:

  • OpenAI DALL-E 3 for general-purpose photorealistic and stylized images
  • Stability AI Stable Diffusion Core for style presets, aspect ratio control, and background removal
  • Black Forest Labs Flux Pro / Flux Kontext Pro for high-quality generation with explicit width/height control

The Squid backend authenticates the request, looks up the right provider API key from your application configuration, calls the upstream model, and returns a URL to the generated image.

When to use AI Image

Use CaseRecommendation
Generate a one-off image from a text promptgenerate() with the model that fits your style needs
Strip the background from an uploaded photoremoveBackground()
Show generated images inside an AI agentAttach an AI function that calls generate() and returns the URL
Long-term storage of generated assetsUpload the returned image to Squid storage

How it works

  1. You call this.squid.ai().image().generate(prompt, options) from a backend service
  2. Squid validates the model and options, then routes the call to the matching provider (OpenAI, Stability, or Black Forest Labs)
  3. The provider generates the image and returns a URL
  4. The Squid backend returns that URL to your code
  5. The URL is temporary. If you need to keep the image, download it and re-upload to Squid storage or your own bucket.

Quick Start

Prerequisites

  • A Squid backend project initialized with squid init
  • The @squidcloud/backend package (TypeScript) or squidcloud-backend package (Python)
  • The relevant AI provider enabled in the Squid Console (OpenAI, Stability AI, or Black Forest Labs, depending on which model you call)

Step 1: Wrap the call in an executable

Image generation requires admin access, so it must run on the backend. Wrap it in an executable so a client can trigger it without leaking API keys.

Backend code
import { executable, SquidService } from '@squidcloud/backend';
import { AiGenerateImageOptions } from '@squidcloud/client';

export class ImageService extends SquidService {
@executable()
async generateImage(prompt: string): Promise<string> {
this.assertIsAuthenticated();

const options: AiGenerateImageOptions = {
modelName: 'dall-e-3',
quality: 'standard',
size: '1024x1024',
};

return this.squid.ai().image().generate(prompt, options);
}
}

Step 2: Run or deploy the backend

squid start

To deploy to the cloud, see deploying your backend.

Step 3: Call from the client

Client code
const imageUrl = await squid.executeFunction('generateImage', 'a friendly squid mascot, vector art');
document.querySelector<HTMLImageElement>('#preview')!.src = imageUrl;

Authentication and Configuration

Image methods require an authenticated Squid client with admin access. Both generate() and removeBackground() reject calls that do not originate from a backend or admin context.

The two recommended patterns are:

  1. Wrap calls in executables, as shown in Quick Start. This is the standard pattern for client-triggered image generation. See executables.
  2. Call from a privileged backend service, such as a trigger, scheduler, or webhook.

The provider API keys (OpenAI, Stability, Flux) live in your Squid Console application configuration. Squid looks the right key up at request time based on the modelName you pass.

Core Concepts

Supported models

AiGenerateImageOptions is a discriminated union on modelName. The field determines which option set is valid and which provider is called:

ModelProviderOptions type
dall-e-3OpenAIDallEOptions
stable-diffusion-coreStability AIStableDiffusionCoreOptions
flux-pro-1.1Black Forest LabsFluxOptions
flux-kontext-proBlack Forest LabsFluxOptions

DALL-E 3 options

FieldTypeRequiredDescription
modelName'dall-e-3'YesSelects the DALL-E 3 model
quality'hd' | 'standard'NoImage quality. Defaults to 'standard'.
size'1024x1024' | '1792x1024' | '1024x1792'NoOutput dimensions. Defaults to '1024x1024'.
numberOfImagesToGenerate1NoDALL-E 3 only supports a single image per call

Stable Diffusion Core options

FieldTypeRequiredDescription
modelName'stable-diffusion-core'YesSelects the Stable Diffusion Core model
aspectRatiostringNoOne of '16:9', '1:1', '21:9', '2:3', '3:2', '4:5', '5:4', '9:16', '9:21'. Defaults to '1:1'.
negativePromptstringNoDescribe what to exclude from the image
seednumberNoSet a fixed seed for reproducible output
stylePresetstringNoOne of 'analog-film', 'anime', 'cinematic', 'comic-book', 'digital-art', 'enhance', 'fantasy-art', 'isometric', 'line-art', 'low-poly', 'modeling-compound', 'neon-punk', 'origami', 'photographic', 'pixel-art', 'tile-texture'
outputFormat'jpeg' | 'png' | 'webp'NoOutput image format. Defaults to 'png'.

Flux options

FieldTypeRequiredDescription
modelName'flux-pro-1.1' | 'flux-kontext-pro'YesSelects which Flux model to use
widthnumberNoMultiple of 32, between 256 and 1440. Defaults to 1024.
heightnumberNoMultiple of 32, between 256 and 1440. Defaults to 768.
prompt_upsamplingbooleanNoWhen true, the provider rewrites the prompt for more creative output
seednumberNoInteger seed for reproducible output
safety_tolerancenumberNoInteger between 1 (strictest) and 5 (most permissive)

Return value

generate() returns a Promise<string> (TypeScript) or str (Python). The string is a URL pointing at the generated image. The URL is temporary, with provider-specific lifetimes:

  • DALL-E: OpenAI hosted URL, valid for roughly one hour
  • Stable Diffusion Core: signed URL pointing at Squid storage; the underlying file is retained for one day
  • Flux: signed URL hosted by Black Forest Labs

If you need long-lived access to the image, download it from the URL and re-upload it to your own Squid storage bucket.

Background removal

removeBackground() accepts an image file and returns a URL pointing at the same image with the background stripped out. It always uses Stable Diffusion under the hood (you do not pick a model). Stability AI must be enabled on your application for this method to work.

MethodTypeScript signaturePython signature
removeBackground(file: File) => Promise<string>(image_data: bytes, filename: str = "image.png", content_type: str = "image/png") -> str

Code Examples

Generate with Stable Diffusion using a style preset

Backend code
import { executable, SquidService } from '@squidcloud/backend';

export class ImageService extends SquidService {
@executable()
async generateAnimePoster(subject: string): Promise<string> {
this.assertIsAuthenticated();

return this.squid.ai().image().generate(subject, {
modelName: 'stable-diffusion-core',
stylePreset: 'anime',
aspectRatio: '2:3',
outputFormat: 'png',
negativePrompt: 'low quality, blurry, watermark',
});
}
}

Generate with Flux at a specific resolution

Backend code
const url = await this.squid.ai().image().generate('a glass terrarium with bonsai trees', {
modelName: 'flux-pro-1.1',
width: 1024,
height: 1024,
safety_tolerance: 2,
seed: 42, // Deterministic output
});

Generate, then persist the result to Squid storage

The provider URL is temporary. If you want to keep the image around, download it and re-upload it to a Squid storage bucket.

Backend code
import { executable, SquidService } from '@squidcloud/backend';

export class GalleryService extends SquidService {
@executable()
async generateAndStore(prompt: string): Promise<{ url: string }> {
this.assertIsAuthenticated();

const tempUrl = await this.squid.ai().image().generate(prompt, {
modelName: 'dall-e-3',
size: '1024x1024',
quality: 'hd',
});

// Download the image bytes from the temporary URL.
const response = await fetch(tempUrl);
if (!response.ok) {
throw new Error(`Failed to download generated image: ${response.status}`);
}
const arrayBuffer = await response.arrayBuffer();

// Upload to Squid storage so the image is available long-term.
const storage = this.squid.storage('gallery');
const fileName = `${crypto.randomUUID()}.png`;
const file = new File([arrayBuffer], fileName, { type: 'image/png' });
await storage.uploadFile('generated', file);

const { url } = await storage.getDownloadUrl(`generated/${fileName}`);
return { url };
}
}

Remove background from a client upload

Backend code
import { executable, SquidFile, SquidService } from '@squidcloud/backend';

export class ImageService extends SquidService {
@executable()
async stripBackground(image: SquidFile): Promise<string> {
this.assertIsAuthenticated();

if (!image.mimetype.startsWith('image/')) {
throw new Error('Only image files are accepted');
}

const file = new File([image.data], image.originalName, { type: image.mimetype });
return this.squid.ai().image().removeBackground(file);
}
}

Error Handling

Common errors

ErrorCauseSolution
UNAUTHORIZEDImage method called from a non-admin context (e.g. browser without backend wrapping)Wrap the call in an executable or call from backend code
Unsupported image model namemodelName is not in the supported listUse one of dall-e-3, stable-diffusion-core, flux-pro-1.1, flux-kontext-pro
Invalid width: <n> (Flux)Width is not an integer between 256 and 1440 or not a multiple of 32Round to the nearest valid value
Invalid height: <n> (Flux)Height is not an integer between 256 and 1440 or not a multiple of 32Round to the nearest valid value
Invalid safety tolerance (Flux)safety_tolerance is not an integer between 1 and 5Use a value in [1, 5]
Image generation timed out (Flux)The provider job did not finish within the polling windowRetry, or fall back to another model
Method not implemented (background removal)Background removal was attempted with a non-Stability providerCall removeBackground() directly. It always uses Stable Diffusion regardless of context.
MUST_PROVIDE_FILEremoveBackground() was called without a filePass a non-empty File (TypeScript) or bytes (Python)

Validate input early

Reject obviously bad input in your executable rather than waiting for the upstream provider to fail:

Backend code
@executable()
async safeGenerate(prompt: string): Promise<string> {
this.assertIsAuthenticated();

if (!prompt || prompt.length < 3) {
throw new Error('Prompt must be at least 3 characters');
}
if (prompt.length > 1000) {
throw new Error('Prompt must be 1000 characters or less');
}

return this.squid.ai().image().generate(prompt, {
modelName: 'dall-e-3',
});
}

Best Practices

  1. Always wrap image calls in executables. Image methods require admin access, so they cannot be called directly from a browser.
  2. Pick a model that matches the use case. DALL-E 3 is a strong default for general-purpose images. Stable Diffusion Core wins when you need style presets or aspect ratio control. Flux gives explicit width/height control and reproducible seeds.
  3. Persist images you care about. Provider URLs expire. Download and re-upload to Squid storage for long-term hosting.
  4. Reject bad input early. Validate prompt length and file type before calling the model.
  5. Apply rate limiting to image executables. Image generation is one of the most expensive AI operations and is a common target for abuse.
  6. Cache by prompt + options. Identical prompts with the same seed produce identical results in Flux and Stable Diffusion. Cache by a hash of (prompt, options) to save quota.

See Also

  • Executables - Wrap image calls so they can be called from a client
  • AI agent - Build an AI agent that can generate images via an AI function
  • Storage - Persist generated images for long-term access
  • Rate and quota limiting - Protect image executables from abuse