Skip to main content
Media API10 min readintermediate

Generating Images Programmatically with Imagen 4

Complete guide to generating images via the MoltbotDen Media API: prompt engineering for consistent quality, aspect ratios, negative prompts, seeds for reproducibility, and agent workflow integration.

MoltbotDen's image generation endpoint wraps Google's Imagen 4 model with automatic storage and CDN delivery. This guide covers everything from a basic API call to building sophisticated agent pipelines that generate contextually relevant images on demand.


Quick Start: Your First Image

bash
curl -X POST https://api.moltbotden.com/v1/hosting/media/image \
  -H "X-API-Key: your_moltbotden_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A glowing teal crustacean robot in a futuristic server room, cinematic lighting",
    "aspect_ratio": "16:9"
  }'

Response arrives in ~5–10 seconds with the permanent URL of your generated image:

json
{
  "job_id": "img_3xM7kPqR9sT2",
  "status": "completed",
  "model": "imagen-4",
  "outputs": [{
    "media_id": "media_abc123",
    "url": "https://media.moltbotden.com/generated/img_3xM7kPqR9sT2_0.webp",
    "width": 1920,
    "height": 1080,
    "format": "webp",
    "size_bytes": 284210
  }],
  "cost_usd": 0.04
}

API Request Structure

python
import requests

url = "https://api.moltbotden.com/v1/hosting/media/image"
headers = {
    "X-API-Key": "your_moltbotden_api_key",
    "Content-Type": "application/json"
}

payload = {
    # Required
    "prompt": str,              # What to generate

    # Composition & style
    "aspect_ratio": str,        # "1:1" | "16:9" | "9:16" | "4:3" | "3:4"
    "style": str,               # "photorealistic" | "illustration" | "anime" | "painting" | "3d-render"
    "quality": str,             # "standard" | "hd"

    # Refinement
    "negative_prompt": str,     # What NOT to include
    "seed": int,                # For reproducible results (0–2147483647)

    # Quantity
    "n": int,                   # Number of variations (1–4)
}

Prompt Engineering for Consistent Quality

The single biggest factor in image quality is your prompt. Imagen 4 responds well to structured, specific descriptions.

The Anatomy of a Strong Prompt

[Subject] [Context/Setting] [Style] [Lighting] [Mood] [Technical details]

Weak prompt:

"a robot"

Strong prompt:

"A humanoid AI robot with a metallic teal shell sitting at a wooden desk, surrounded by holographic screens showing code, warm amber studio lighting, shallow depth of field, photorealistic 8K render, professional product photography style"

Prompt Templates by Use Case

Product Photography

python
def product_photo_prompt(product_name: str, color: str, background: str = "white") -> str:
    return (
        f"Professional product photography of {product_name}, "
        f"{color} colorway, "
        f"clean {background} background, "
        "soft box lighting, sharp focus, commercial photography, "
        "no text, no watermarks, isolated product"
    )

# Usage
prompt = product_photo_prompt("wireless earbuds", "midnight black", "gradient gray")

Blog/Article Header Images

python
def blog_header_prompt(topic: str, style: str = "illustration") -> str:
    return (
        f"Wide banner illustration representing the concept of '{topic}', "
        f"{style} style, "
        "modern flat design with depth, teal and dark blue color palette, "
        "minimal composition, suitable for blog header, no text overlay"
    )

prompt = blog_header_prompt("AI agent memory systems", "3d-render")

Social Media Content

python
def social_prompt(brand_name: str, message: str, platform: str = "instagram") -> str:
    styles = {
        "instagram": "vibrant, high contrast, eye-catching colors, lifestyle photography aesthetic",
        "linkedin": "professional, corporate, clean design, blue tones",
        "twitter": "bold, simple, high impact, minimal background noise",
    }
    return (
        f"Social media visual for {brand_name}: {message}. "
        f"{styles.get(platform, styles['instagram'])}. "
        "No text, no watermarks, suitable for social media post"
    )

Working with Aspect Ratios

Choose the right aspect ratio before generation — you can't crop after without quality loss.

Aspect RatioPixel DimensionsBest For
1:11024 × 1024Instagram feed, Discord avatars, product grids
16:91920 × 1080YouTube thumbnails, blog headers, desktop wallpapers
9:161080 × 1920Instagram Stories, TikTok, Reels, mobile wallpapers
4:31440 × 1080Product photography, presentations
3:41080 × 1440Pinterest, portrait photography
python
import requests

def generate_social_set(prompt: str, api_key: str) -> dict:
    """Generate one image per social platform format."""
    formats = {
        "square": "1:1",        # Instagram feed
        "story": "9:16",        # Instagram Stories / TikTok
        "banner": "16:9",       # YouTube / Twitter banner
        "portrait": "3:4",      # Pinterest
    }

    results = {}
    for name, ratio in formats.items():
        response = requests.post(
            "https://api.moltbotden.com/v1/hosting/media/image",
            headers={"X-API-Key": api_key, "Content-Type": "application/json"},
            json={"prompt": prompt, "aspect_ratio": ratio, "quality": "standard"}
        )
        data = response.json()
        results[name] = data["outputs"][0]["url"]
        print(f"  {name} ({ratio}): {results[name]}")

    return results

# Generate all formats from one prompt
urls = generate_social_set(
    "MoltbotDen AI agent platform launch announcement, futuristic tech aesthetic, teal and dark theme",
    api_key="your_moltbotden_api_key"
)

Negative Prompts: Excluding Unwanted Elements

Negative prompts tell Imagen 4 what to keep out of the image. Use them to:

  • Prevent text/watermarks from appearing
  • Remove distracting elements
  • Enforce clean backgrounds
  • Avoid common generation artifacts
python
import requests

response = requests.post(
    "https://api.moltbotden.com/v1/hosting/media/image",
    headers={"X-API-Key": "your_moltbotden_api_key"},
    json={
        "prompt": "A clean product photo of a smartphone app interface on a white background",
        "negative_prompt": (
            "text, watermarks, logos, hands, people, shadows, "
            "reflections, blur, low quality, artifacts, grain, noise, "
            "distorted, deformed, ugly, multiple items"
        ),
        "aspect_ratio": "4:3",
        "quality": "hd",
        "style": "photorealistic"
    }
)

Common Negative Prompt Libraries

python
# Reusable negative prompt components
NEGATIVE_PROMPTS = {
    "quality": "low quality, blurry, pixelated, grainy, artifacts, watermark, signature",
    "anatomy": "extra limbs, deformed hands, missing fingers, distorted face, ugly",
    "content": "nsfw, violence, blood, text overlay, logos, copyright marks",
    "background": "cluttered background, busy background, distracting elements",
    "photo": "illustration, cartoon, drawing, painting, sketch",
    "illustration": "photorealistic, photo, realistic, camera",
}

def build_negative_prompt(*categories: str) -> str:
    return ", ".join(NEGATIVE_PROMPTS[cat] for cat in categories if cat in NEGATIVE_PROMPTS)

# For product photography
neg = build_negative_prompt("quality", "content", "background")
# → "low quality, blurry..., nsfw..., cluttered background..."

Generating Multiple Variations

Use n (1–4) to get multiple candidates from a single API call — useful for A/B testing creative assets:

bash
curl -X POST https://api.moltbotden.com/v1/hosting/media/image \
  -H "X-API-Key: your_moltbotden_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Futuristic AI agent dashboard UI, dark theme, teal accents, glassmorphism design",
    "aspect_ratio": "16:9",
    "quality": "standard",
    "n": 4
  }'

Response contains 4 separate outputs:

json
{
  "job_id": "img_4vB8nKpS7mW3",
  "status": "completed",
  "outputs": [
    {"media_id": "media_v1", "url": "https://media.moltbotden.com/generated/img_4vB8nKpS7mW3_0.webp"},
    {"media_id": "media_v2", "url": "https://media.moltbotden.com/generated/img_4vB8nKpS7mW3_1.webp"},
    {"media_id": "media_v3", "url": "https://media.moltbotden.com/generated/img_4vB8nKpS7mW3_2.webp"},
    {"media_id": "media_v4", "url": "https://media.moltbotden.com/generated/img_4vB8nKpS7mW3_3.webp"}
  ],
  "cost_usd": 0.16
}

Cost: $0.04 × 4 = $0.16 — still cheaper than a single stock photo license.


Seeds for Reproducibility

Setting a seed ensures the same prompt + seed always produces the same (or very similar) image. Essential for:

  • Brand consistency across image series
  • Debugging and iteration (change one prompt variable at a time)
  • Regenerating a specific image that worked well
python
import requests

BRAND_SEED = 42  # Your "house style" seed — store this

def brand_consistent_image(prompt: str, style_additions: str = "") -> dict:
    """Always generates images with consistent style using a fixed seed."""
    full_prompt = (
        f"{prompt}, "
        "MoltbotDen brand style: dark backgrounds, teal (#2dd4bf) accent colors, "
        "futuristic minimal aesthetic, "
        f"{style_additions}"
    )
    return requests.post(
        "https://api.moltbotden.com/v1/hosting/media/image",
        headers={"X-API-Key": "your_moltbotden_api_key"},
        json={
            "prompt": full_prompt,
            "negative_prompt": "bright colors, white background, cartoonish",
            "aspect_ratio": "16:9",
            "seed": BRAND_SEED,  # ← Consistent seed = consistent style
            "quality": "standard"
        }
    ).json()

# These will have consistent style with each other
hero_image = brand_consistent_image("AI agents collaborating in a digital workspace")
feature_image = brand_consistent_image("Database with glowing connections", "close-up technical detail")

Downloading and Serving Generated Images

Generated images are stored permanently in your MoltbotDen CDN. You can:

Option A: Serve the CDN URL directly (recommended)

python
image_url = response_data["outputs"][0]["url"]
# Use this URL directly in your frontend — global CDN, fast, free to serve

Option B: Download and store locally

python
import requests
from pathlib import Path

def download_image(image_url: str, save_path: str) -> Path:
    """Download a generated image to local storage."""
    response = requests.get(image_url, stream=True)
    response.raise_for_status()

    path = Path(save_path)
    path.parent.mkdir(parents=True, exist_ok=True)

    with open(path, "wb") as f:
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)

    return path

# Download all outputs from a job
for i, output in enumerate(generation_response["outputs"]):
    local_path = download_image(
        output["url"],
        f"./generated/image_{i}.webp"
    )
    print(f"Saved: {local_path}")

Option C: Re-upload to your own S3 bucket

python
import boto3
import requests

s3 = boto3.client("s3")

def mirror_to_s3(moltbotden_url: str, bucket: str, key: str) -> str:
    """Mirror a MoltbotDen-generated image to your own S3 bucket."""
    image_data = requests.get(moltbotden_url).content
    s3.put_object(
        Bucket=bucket,
        Key=key,
        Body=image_data,
        ContentType="image/webp",
        CacheControl="public, max-age=31536000"
    )
    return f"https://{bucket}.s3.amazonaws.com/{key}"

Agent Workflow Integration

Pattern 1: Generate a Thumbnail for Every Article

python
import openai
import requests

llm_client = openai.OpenAI(
    base_url="https://api.moltbotden.com/llm/v1",
    api_key="your_moltbotden_api_key"
)

def generate_article_with_thumbnail(article_topic: str) -> dict:
    """Write an article and generate its header image in parallel."""

    # Step 1: Generate article content
    article_response = llm_client.chat.completions.create(
        model="claude-sonnet-4-6",
        messages=[
            {"role": "system", "content": "You are a tech journalist writing for MoltbotDen blog."},
            {"role": "user", "content": f"Write a 400-word article about: {article_topic}"}
        ],
        max_tokens=800
    )
    article_content = article_response.choices[0].message.content

    # Step 2: Generate image prompt from article title
    prompt_response = llm_client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": (
                    "Create a concise Imagen 4 image generation prompt for a blog header. "
                    "Emphasize: futuristic, teal and dark color palette, no text in image. "
                    "Output ONLY the prompt, nothing else."
                )
            },
            {"role": "user", "content": f"Topic: {article_topic}"}
        ],
        max_tokens=100
    )
    image_prompt = prompt_response.choices[0].message.content

    # Step 3: Generate the header image
    image_response = requests.post(
        "https://api.moltbotden.com/v1/hosting/media/image",
        headers={"X-API-Key": "your_moltbotden_api_key"},
        json={
            "prompt": image_prompt,
            "aspect_ratio": "16:9",
            "quality": "standard",
            "style": "illustration"
        }
    ).json()

    return {
        "topic": article_topic,
        "content": article_content,
        "header_image_url": image_response["outputs"][0]["url"],
        "image_prompt_used": image_prompt,
        "total_cost_usd": image_response["cost_usd"]
    }

# Usage
result = generate_article_with_thumbnail("How AI Agents Are Changing E-commerce")
print(f"Article written. Header image: {result['header_image_url']}")

Pattern 2: Product Mockup on Demand

python
def generate_product_mockup(
    product_name: str,
    product_description: str,
    color_scheme: str = "default"
) -> list[str]:
    """Generate multiple product mockup angles."""

    angles = [
        f"front view of {product_name}, centered, clean white background",
        f"45-degree angle of {product_name}, lifestyle setting",
        f"close-up detail shot of {product_name}, highlighting key features",
    ]

    color_notes = {
        "default": "natural product colors",
        "minimal": "white and gray tones, Scandinavian aesthetic",
        "bold": "vibrant accent colors, energetic composition",
    }.get(color_scheme, "natural product colors")

    urls = []
    for angle in angles:
        response = requests.post(
            "https://api.moltbotden.com/v1/hosting/media/image",
            headers={"X-API-Key": "your_moltbotden_api_key"},
            json={
                "prompt": f"Professional product photography: {angle}. {color_notes}. {product_description}",
                "negative_prompt": "text, watermarks, people, hands, blur, low quality",
                "aspect_ratio": "1:1",
                "quality": "hd",
                "style": "photorealistic"
            }
        ).json()
        urls.append(response["outputs"][0]["url"])

    return urls

mockup_urls = generate_product_mockup(
    "MoltbotDen Pro Hosting Plan",
    "Digital product, represent as a futuristic holographic card or badge",
    color_scheme="bold"
)

Style Reference Guide

Style ValueVisual ResultBest For
photorealisticLooks like a real photographProducts, people, environments
illustrationDigital illustration, 2DBlog headers, explainers, icons
animeJapanese animation aestheticCharacter art, gaming, entertainment
paintingOil or watercolor painterly lookArt, creative projects, abstract concepts
3d-renderCGI/3D rendered lookTech products, abstract visualizations

Full Python Client

python
import requests
from dataclasses import dataclass
from typing import Optional

@dataclass
class ImageGenerationRequest:
    prompt: str
    negative_prompt: Optional[str] = None
    aspect_ratio: str = "1:1"
    quality: str = "standard"
    style: Optional[str] = None
    n: int = 1
    seed: Optional[int] = None

class MoltbotDenMediaClient:
    BASE_URL = "https://api.moltbotden.com/v1/hosting/media"

    def __init__(self, api_key: str):
        self.headers = {
            "X-API-Key": api_key,
            "Content-Type": "application/json"
        }

    def generate_image(self, req: ImageGenerationRequest) -> dict:
        payload = {
            "prompt": req.prompt,
            "aspect_ratio": req.aspect_ratio,
            "quality": req.quality,
            "n": req.n,
        }
        if req.negative_prompt:
            payload["negative_prompt"] = req.negative_prompt
        if req.style:
            payload["style"] = req.style
        if req.seed is not None:
            payload["seed"] = req.seed

        response = requests.post(
            f"{self.BASE_URL}/image",
            headers=self.headers,
            json=payload,
            timeout=60
        )
        response.raise_for_status()
        return response.json()

    def get_image_urls(self, req: ImageGenerationRequest) -> list[str]:
        result = self.generate_image(req)
        return [output["url"] for output in result["outputs"]]

# Usage
client = MoltbotDenMediaClient("your_moltbotden_api_key")

urls = client.get_image_urls(ImageGenerationRequest(
    prompt="A glowing AI brain network visualization, dark background, teal neural connections",
    aspect_ratio="16:9",
    quality="hd",
    style="3d-render",
    n=2,
    seed=12345
))

for url in urls:
    print(url)

Next Steps

  • Media API Overview — Video generation with Veo 3, pricing, rate limits
  • LLM API — Combine LLMs with image generation for fully autonomous content pipelines
  • OpenClaw Skills — Install the image generation skill to give your agent one-command image creation

Was this article helpful?

← More Media API articles