Lesson 3 · Building multimodal applications
Image generation and cross-modal
Hosted image models, Stable Diffusion, image-to-image, and cross-modal reasoning (text→image, image→text, image→audio).
Step 1 of 6
Enhance prompt
A language model rewrites a thin request such as "red shoe" into a prompt with subject, style, lighting and framing the image model responds to.
Never block the user request on generation, and never trust the model to filter its own output.
Image generation and cross-modal
Image generation models (hosted APIs such as OpenAI's GPT Image models, plus Stable Diffusion, Midjourney and Flux) produce images from text prompts. Names change quickly: OpenAI removed DALL-E 2 and DALL-E 3 from its API on 12 May 2026, so check your provider's current model list. Cross-modal systems go further: image-to-image (style transfer, editing), image-to-text (captioning, VQA), text-to-audio, audio-to-image. The unifying idea: a shared latent space where different modalities can be mapped and transformed.
For AI engineers, image generation enables: product visualisation, marketing assets, data augmentation, UI prototyping, and creative tools. Cross-modal enables: 'describe this image', 'generate a similar image', 'edit this region'.
Why this matters
Generative image AI is a $10B+ market. E-commerce (product photos), marketing (ad creative), gaming (asset generation), design (prototyping) all use it. Engineers who can build reliable image-generation pipelines (prompt engineering for images, safety filters, consistent style, batch generation) are in high demand. The production challenges: latency (often tens of seconds per image), cost (priced per image or per image token, and it varies by model, size and quality; see /pricing), safety (NSFW filtering), and consistency (same prompt → different images).
Image generation pipeline
Text prompt → prompt enhancement (LLM rewrites for image model) → image model (hosted API or self-hosted Stable Diffusion) → safety filter → post-process (upscale, crop) → store → return URL. For editing: input image + edit prompt → image-to-image model → output. For batch: queue + worker pool + caching of identical prompts.
Production image generation
import base64
import hashlib
from openai import OpenAI
client = OpenAI()
# Model names change often; check your provider's model list (as of 28 October 2026). Replace <...-model> with a model id from that list.
# OpenAI retired its DALL-E models from the API on 12 May 2026; use a current GPT Image
# model id (see developers.openai.com/api/docs/deprecations and the models list).
IMAGE_MODEL = "<image-model>"
def generate_image(prompt: str, size: str = "1024x1024", quality: str = "auto") -> dict:
"""Generate an image with prompt enhancement, caching and safety."""
# 1. Enhance prompt with LLM for better image model results
enhanced = client.chat.completions.create(
model="<small-model>",
messages=[
{"role": "system", "content": "Enhance this image prompt for an image model. Be specific about style, lighting, composition. Refuse NSFW requests."},
{"role": "user", "content": prompt},
],
).choices[0].message.content
# 2. Safety check on enhanced prompt
if is_unsafe(enhanced):
return {"error": "Prompt rejected by safety filter"}
# 3. Cache key — same prompt + size = same image
cache_key = hashlib.sha256(f"{enhanced}|{size}|{quality}".encode()).hexdigest()
if cached := image_cache.get(cache_key):
return {"url": cached, "cached": True}
# 4. Generate (a hosted image model, or SD via Replicate). Valid sizes and
# quality values depend on the model; check its page.
response = client.images.generate(
model=IMAGE_MODEL,
prompt=enhanced,
size=size,
quality=quality,
n=1,
)
# GPT Image models return base64 image data, not a URL.
image_bytes = base64.b64decode(response.data[0].b64_json)
# 5. Safety filter on output
if is_image_unsafe(image_bytes):
return {"error": "Generated image rejected by safety filter"}
# 6. Store, cache the URL and return
url = store_image(image_bytes) # e.g. upload to object storage
image_cache.set(cache_key, url, ttl=3600)
return {"url": url, "cached": False}
def edit_image(input_url: str, edit_prompt: str, mask: str = None) -> dict:
"""Image-to-image editing."""
response = client.images.edit(
model=IMAGE_MODEL,
image=open(input_url, "rb"),
mask=open(mask, "rb") if mask else None,
prompt=edit_prompt,
n=1,
size="1024x1024",
)
return {"url": store_image(base64.b64decode(response.data[0].b64_json))}Experiment: image generation trade-offs
Compare kinds of image model on cost, latency and quality. Model names and per-image prices change often (OpenAI removed DALL-E 2 and 3 from its API on 12 May 2026), so this compares kinds of option rather than named models. The quality scores and latencies are illustrative; check /pricing and your provider's price list, and measure your own prompts.
What to observe
No single model wins everywhere. High-quality hosted modes suit photorealism but cost more per image. A self-hosted open model is cheapest at high, steady volume. Hosted open models are worth comparing on prompt adherence. CRITICAL: image generation models are BAD at text labels, diagrams, and schematics — use a diagramming tool, not image gen, for those. Always prompt-enhance with an LLM and cache.
Production image generation
Production: LLM prompt enhancement (raw user prompts are weak), safety filters on input AND output, caching (same prompt = same image), async queue for batch generation, cost budgets per user, watermarking/safety for user-facing, and consistency controls (seed pinning for reproducible images). For e-commerce product photos, use fine-tuned models, not general image gen.
Challenge
Your marketing team uses image generation for ad creative. The same prompt produces wildly different images each time, making brand consistency impossible. How do you enforce consistency? (Hint: seed pinning + style reference + prompt templates.)
Production checklist
Production checklist
0 of 10 checked
Knowledge check
You need consistent brand-style images. What enforces consistency best?
Complete
You can now build production image-generation systems. This completes the Building multimodal applications series.
Mark this chapter as complete
Track your progress and unlock the next chapter.