Skip to main content

Overview

The generateImage() function generates images from text prompts using image generation models. It supports generating multiple images, different sizes, and both base64 and URL outputs.

Function signature

export async function generateImage(
    params: GenerateImageParams
): Promise<ImageGenerateResult>

export type GenerateImageParams = ImageGenerateOptions & {
    model: ImageModel;
};

Parameters

model
ImageModel
required
The image generation model instance to use.
prompt
string
required
The text description of the image to generate. Must not be empty.
n
number
Number of images to generate. Defaults to 1.
size
string
Image dimensions. Format and available sizes depend on the provider.Common sizes:
  • '1024x1024' (square)
  • '1792x1024' (landscape)
  • '1024x1792' (portrait)
providerOptions
ImageProviderOptions
Provider-specific options, namespaced by provider name (e.g. { openai: { quality: 'hd' } }).

Return value

Returns a Promise<ImageGenerateResult> with the following properties:
images
GeneratedImage[]
Array of generated images. Length matches the n parameter.

Examples

Basic image generation

import { generateImage } from '@core-ai/core-ai';
import { createOpenAI } from '@core-ai/openai';

const openai = createOpenAI();

const result = await generateImage({
  model: openai.imageModel('gpt-image-1'),
  prompt: 'A serene landscape with mountains and a lake at sunset'
});

console.log(result.images[0].url);
// Save or display the image URL

Generate multiple images

const result = await generateImage({
  model: openai.imageModel('gpt-image-1'),
  prompt: 'A cute robot playing guitar',
  n: 4 // Generate 4 variations
});

console.log(`Generated ${result.images.length} images`);
result.images.forEach((image, i) => {
  console.log(`Image ${i + 1}: ${image.url}`);
});

Custom size

const result = await generateImage({
  model: openai.imageModel('gpt-image-1'),
  prompt: 'A futuristic city skyline',
  size: '1792x1024' // Wide landscape format
});

console.log('Generated landscape image:', result.images[0].url);

Get base64 image data

const result = await generateImage({
  model: openai.imageModel('gpt-image-1'),
  prompt: 'A detailed illustration of a dragon',
  providerOptions: {
    openai: { responseFormat: 'b64_json' },
  }
});

const base64Data = result.images[0].base64;
if (base64Data) {
  // Save to file
  const fs = await import('fs/promises');
  const buffer = Buffer.from(base64Data, 'base64');
  await fs.writeFile('dragon.png', buffer);
}

Check revised prompt

const result = await generateImage({
  model: openai.imageModel('gpt-image-1'),
  prompt: 'cat'
});

if (result.images[0].revisedPrompt) {
  console.log('Original:', 'cat');
  console.log('Revised:', result.images[0].revisedPrompt);
  // Revised might be: "A fluffy orange tabby cat sitting on a windowsill..."
}

Save image to file

import { writeFile } from 'fs/promises';

const result = await generateImage({
  model: openai.imageModel('gpt-image-1'),
  prompt: 'Abstract art with vibrant colors'
});

const imageUrl = result.images[0].url;
if (imageUrl) {
  // Download and save
  const response = await fetch(imageUrl);
  const buffer = await response.arrayBuffer();
  await writeFile('abstract-art.png', Buffer.from(buffer));
  console.log('Image saved!');
}

Generate with style instructions

const result = await generateImage({
  model: openai.imageModel('gpt-image-1'),
  prompt: 'A portrait of a wise old wizard, oil painting style, ' +
          'detailed brushstrokes, warm lighting, fantasy art'
});

console.log(result.images[0].url);

Error handling

import { ValidationError } from '@core-ai/core-ai';

try {
  const result = await generateImage({
    model: openai.imageModel('gpt-image-1'),
    prompt: '' // Empty prompt
  });
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Image generation failed:', error.message);
    // Output: "prompt must not be empty"
  }
}

Generate portrait and landscape variants

const prompt = 'A magical forest with glowing mushrooms';

const [portrait, landscape, square] = await Promise.all([
  generateImage({
    model: openai.imageModel('gpt-image-1'),
    prompt,
    size: '1024x1792' // Portrait
  }),
  generateImage({
    model: openai.imageModel('gpt-image-1'),
    prompt,
    size: '1792x1024' // Landscape
  }),
  generateImage({
    model: openai.imageModel('gpt-image-1'),
    prompt,
    size: '1024x1024' // Square
  })
]);

console.log('Portrait:', portrait.images[0].url);
console.log('Landscape:', landscape.images[0].url);
console.log('Square:', square.images[0].url);

Model Support

Different providers expose image generation models through imageModel():
import { createOpenAI } from '@core-ai/openai';
const openai = createOpenAI();

const gptImage = openai.imageModel('gpt-image-1');

const result = await generateImage({
  model: gptImage,
  prompt: 'A beautiful sunset'
});

Important notes

Check revisedPrompt when you want to inspect how the provider expanded or filtered your original prompt.
For best results, be specific and descriptive in your prompts. Include details about style, composition, lighting, colors, and mood.

Provider-specific options

OpenAI

const result = await generateImage({
  model: openai.imageModel('gpt-image-1'),
  prompt: 'A cat',
  providerOptions: {
    openai: {
      quality: 'hd',
      style: 'vivid',
      responseFormat: 'url',
    },
  }
});

Common use cases

  1. Content Creation: Generate illustrations for articles and blog posts
  2. Marketing: Create social media graphics and ad visuals
  3. Product Design: Visualize product concepts and variations
  4. Game Development: Generate concept art and textures
  5. Education: Create visual aids and diagrams
  6. Personal Projects: Generate artwork for presentations or creative projects

Best practices

  1. Be Specific: Detailed prompts produce better results
  2. Iterate: Generate multiple variations to find the best result
  3. Use Style Keywords: Include art style, medium, and technique terms
  4. Check Revised Prompts: Inspect provider prompt rewrites when outputs differ from your original request
  5. Handle Errors: Prompts may be rejected for safety reasons

Errors

Throws ValidationError if:
  • Prompt is empty
May also throw:
  • ProviderError if the provider returns an error during image generation
  • Model encounters an error during generation
  • Prompt violates content policy
import { CoreAIError, ProviderError } from '@core-ai/core-ai';

try {
  const result = await generateImage({
    model: openai.imageModel('gpt-image-1'),
    prompt: 'inappropriate content'
  });
} catch (error) {
  if (error instanceof ProviderError) {
    console.error('Provider error:', error.provider, error.statusCode);
  } else if (error instanceof CoreAIError) {
    console.error('Generation failed:', error.message);
  }
}