@molecule/api-ai-image-generation-molecule

Provider bond · ai-image-generation · API (Node) · v1.1.1 · Apache-2.0

molecule.dev hosted image generation provider — images billed to your molecule project, no vendor account

npm install @molecule/api-ai-image-generation-molecule

npm · Source on GitHub · Implements @molecule/api-ai-image-generation

How it works

@molecule/api-ai-image-generation-molecule is a provider bond on the API (Node) side: it implements the ai-image-generation core interface (@molecule/api-ai-image-generation) with a concrete vendor or library behind it.

Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.

Works with: @molecule/api-ai-image-generation, @molecule/api-secrets

Secrets: MOLECULE_API_KEY

Reference

molecule.dev hosted image generation provider — images billed to your molecule project, no vendor account

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Type

provider

Installation

npm install @molecule/api-ai-image-generation-molecule @molecule/api-ai-image-generation @molecule/api-secrets

API

Interfaces

MoleculeImageGenerationConfig

Options for createProvider. Every field falls back to an env var, so the zero-argument provider export works from .env alone.

interface MoleculeImageGenerationConfig {
  /**
   * The molecule project API key (`mk_…`), or the sandbox token molecule.dev
   * writes for in-IDE apps (`mbk_…`). Defaults to `MOLECULE_API_KEY`.
   */
  apiKey?: string
  /**
   * The hosted services base URL, without a trailing slash. Defaults to
   * `MOLECULE_SERVICES_URL`, then `https://api.molecule.dev/api/v1/services`.
   */
  servicesUrl?: string
  /**
   * Per-request timeout in milliseconds. Default 120000 — image generation is
   * slow (a 1536x1024 `high` image can take tens of seconds), so unlike the
   * other hosted bonds 15 seconds is not enough.
   */
  timeoutMs?: number
}

ProcessEnv

Environment variables this provider reads.

interface ProcessEnv {
  MOLECULE_API_KEY?: string
  MOLECULE_SERVICES_URL?: string
}

Classes

MoleculeServiceError

Error thrown for a refused or failed hosted-service call.

class MoleculeServiceError extends Error {
  /** HTTP status from molecule.dev. */
  readonly status: number
  /** Stable error key from molecule.dev, e.g. `broker.error.budgetExceeded`. */
  readonly errorKey: string | undefined

  /**
   * Create the error.
   *
   * @param message - Human-readable message.
   * @param status - HTTP status.
   * @param errorKey - Stable error key, when the service sent one.
   * @param cause - The underlying error, if any.
   */
  constructor(message: string, status: number, errorKey?: string, cause?: unknown) {
    super(message, cause === undefined ? undefined : { cause })
    this.name = 'MoleculeServiceError'
    this.status = status
    this.errorKey = errorKey
  }
}

MoleculeImageGenerationProvider

Image generation provider backed by molecule.dev's hosted service.

Only generate is implemented: the hosted service serves text-to-image. edit/imageToImage/upscale are optional methods on the core contract and are absent here — feature-detect (if (provider.edit)) as the core's own remarks prescribe.

class MoleculeImageGenerationProvider implements AIImageGenerationProvider {
  readonly name = 'molecule'

  private readonly apiKey: string
  private readonly servicesUrl: string
  private readonly timeoutMs: number

  /**
   * Create the provider.
   *
   * @param config - Options; each falls back to its env var.
   */
  constructor(config: MoleculeImageGenerationConfig = {}) {
    this.apiKey = config.apiKey ?? process.env.MOLECULE_API_KEY ?? ''
    this.servicesUrl = resolveServicesUrl(
      config.servicesUrl ?? process.env.MOLECULE_SERVICES_URL ?? DEFAULT_SERVICES_URL,
    )
    this.timeoutMs = config.timeoutMs ?? 120_000
  }

  /**
   * Generate images from a text prompt.
   *
   * Every generated image has passed molecule.dev's moderation classifier
   * before it is returned; a refused prompt or image throws
   * `MoleculeServiceError` with status 400 and errorKey
   * `hostedServices.error.contentFlagged`.
   *
   * @param params - Prompt plus the options the service prices: `model`,
   *   `size` and `quality`. `n` caps at 4. `responseFormat` is not forwarded —
   *   the service always returns base64 (it moderates the raw bytes).
   * @returns The generated images (base64 png) and the model that made them.
   */
  async generate(params: ImageGenerateParams): Promise<ImageGenerationResult> {
    if (typeof params.prompt !== 'string' || params.prompt.trim().length === 0) {
      throw new MoleculeServiceError('The prompt must be non-empty text.', 400)
    }
    if (params.prompt.length > IMAGE_GENERATION_SERVICE_LIMITS.maxPromptChars) {
      throw new MoleculeServiceError(
        `The prompt is ${params.prompt.length} characters. ${HINTS[413]}`,
        413,
        'hostedServices.error.inputTooLarge',
      )
    }
    if (
      params.n !== undefined &&
      (!Number.isInteger(params.n) ||
        params.n < 1 ||
        params.n > IMAGE_GENERATION_SERVICE_LIMITS.maxImages)
    ) {
      throw new MoleculeServiceError(
        `"n" must be an integer from 1 to ${IMAGE_GENERATION_SERVICE_LIMITS.maxImages}.`,
        400,
        'hostedServices.error.invalidInput',
      )
    }
    if (
      params.model !== undefined &&
      !(IMAGE_GENERATION_SERVICE_LIMITS.models as readonly string[]).includes(params.model)
    ) {
      throw new MoleculeServiceError(
        `"model" must be one of: ${IMAGE_GENERATION_SERVICE_LIMITS.models.join(', ')}.`,
        400,
        'hostedServices.error.invalidInput',
      )
    }
    if (
      params.size !== undefined &&
      !(IMAGE_GENERATION_SERVICE_LIMITS.sizes as readonly string[]).includes(params.size)
    ) {
      throw new MoleculeServiceError(
        `"size" must be one of: ${IMAGE_GENERATION_SERVICE_LIMITS.sizes.join(', ')}.`,
        400,
        'hostedServices.error.invalidInput',
      )
    }
    if (
      params.quality !== undefined &&
      !(IMAGE_GENERATION_SERVICE_LIMITS.qualities as readonly string[]).includes(params.quality)
    ) {
      throw new MoleculeServiceError(
        `"quality" must be one of: ${IMAGE_GENERATION_SERVICE_LIMITS.qualities.join(', ')} — "auto" is not served because it has no published per-image price.`,
        400,
        'hostedServices.error.invalidInput',
      )
    }
    return this.request({
      prompt: params.prompt,
      ...(params.n !== undefined ? { n: params.n } : {}),
      ...(params.model !== undefined ? { model: params.model } : {}),
      ...(params.size !== undefined ? { size: params.size } : {}),
      ...(params.quality !== undefined ? { quality: params.quality } : {}),
    })
  }

  // The core's optional operations are deliberately absent: the hosted service
  // is text-to-image only. (`edit`, `imageToImage`, `upscale`, `generateImage`)

  /** One POST to the hosted service. */
  private async request(body: Record<string, unknown>): Promise<ImageGenerationResult> {
    if (!this.apiKey) {
      throw new MoleculeServiceError(
        'MOLECULE_API_KEY is not set. Create a project API key on molecule.dev (or with `mlcl apikey create`) and put it in the API .env.',
        401,
        'hostedServices.error.tokenInvalid',
      )
    }
    const response = await fetch(`${this.servicesUrl}/image-generation/generate`, {
      method: 'POST',
      headers: { authorization: `Bearer ${this.apiKey}`, 'content-type': 'application/json' },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(this.timeoutMs),
    })
    const text = await response.text()
    let data: unknown
    try {
      data = text ? JSON.parse(text) : {}
    } catch (error) {
      // A proxy/gateway error page, not the service: report the status only.
      throw new MoleculeServiceError(
        `molecule.dev returned ${response.status} with a non-JSON body.`,
        response.status,
        undefined,
        error,
      )
    }
    if (!response.ok) {
      const err = data as { error?: string; errorKey?: string }
      const hint = HINTS[response.status]
      throw new MoleculeServiceError(
        `molecule.dev image-generation/generate failed (${response.status}): ${err.error ?? 'error'}${hint ? ` ${hint}` : ''}`,
        response.status,
        err.errorKey,
      )
    }
    const result = data as ImageGenerationResult
    if (!Array.isArray(result.images)) {
      throw new MoleculeServiceError(
        'molecule.dev returned a malformed image-generation response.',
        502,
        undefined,
      )
    }
    return {
      ...result,
      images: result.images.map((image) => ({
        // Provider URLs are molecule's and short-lived; only the portable
        // fields are handed on.
        base64: image.base64,
        revisedPrompt: image.revisedPrompt,
        ...(image.seed !== undefined ? { seed: image.seed } : {}),
      })),
    }
  }
}

Functions

createProvider(config)

Create a hosted image generation provider.

function createProvider(config?: MoleculeImageGenerationConfig): AIImageGenerationProvider
  • config — Options; each falls back to its env var.

Returns: An AIImageGenerationProvider backed by molecule.dev.

Constants

provider

The provider implementation (wire with setProvider).

const provider: AIImageGenerationProvider

DEFAULT_SERVICES_URL

Default hosted services base URL.

const DEFAULT_SERVICES_URL: 'https://api.molecule.dev/api/v1/services'

IMAGE_GENERATION_SERVICE_LIMITS

Per-request limits of the hosted service (mirrored locally, before any request).

const IMAGE_GENERATION_SERVICE_LIMITS: {
  readonly maxPromptChars: 2000
  readonly maxImages: 4
  readonly models: readonly ['gpt-image-1.5', 'gpt-image-1', 'gpt-image-1-mini']
  readonly sizes: readonly ['1024x1024', '1024x1536', '1536x1024']
  readonly qualities: readonly ['low', 'medium', 'high']
}

aiImageGenerationMoleculeSecretDefinitions

Secret definitions required by the molecule.dev hosted image generation bond.

const aiImageGenerationMoleculeSecretDefinitions: SecretDefinition[]

Core Interface

Implements @molecule/api-ai-image-generation interface.

Bond Wiring

Setup function to register this provider with the core interface:

import { setProvider } from '@molecule/api-ai-image-generation'
import { provider } from '@molecule/api-ai-image-generation-molecule'

export function setupAiImageGenerationMolecule(): void {
  setProvider(provider)
}

Injection Notes

Requirements

Peer dependencies:

  • @molecule/api-ai-image-generation >=1.0.2
  • @molecule/api-secrets ^1.0.1

Environment Variables

  • MOLECULE_API_KEY (required) — molecule.dev project API key
    • Setup: Create one for your project with mlcl apikey create --project <id> --name <name> (keys start with mk_).
    • Get it here: https://www.molecule.dev
    • Example: mk_...

Runtime Dependencies

  • @molecule/api-ai-image-generation
  • @molecule/api-secrets

E2E Tests

Integration checklist — drive the real UI (live preview, no mocks), adapt each item to this app's actual screens/flows, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip:

  • Entering a prompt in the UI and submitting produces a REAL rendered image in the live preview — not a broken img (image icon / alt text), a grey placeholder, or an error toast. Confirm the img element actually decoded (its naturalWidth/naturalHeight are non-zero) and the picture visibly reflects the prompt (a "red bicycle" prompt shows a red bicycle).
  • Two different prompts produce two visibly different images — a fixed stub, or a cached first result that never changes, is a broken integration.
  • The image is STORED AND SERVED FROM THE APP'S OWN ORIGIN: the rendered img src (and any saved record) points at the app's uploads/storage, not the provider's temporary URL. Provider url results expire — reload the page (or revisit the record later) and the image must still load. Download the provider result server-side and persist it (uploads bond); never hotlink the provider URL — it 404s later and can leak the API request context. (base64/data results must likewise be saved, not held only in the response.)
  • Any exposed generation options take effect: changing size/dimensions yields a differently-sized image; requesting a count (n) of N renders N images. If the UI exposes no such options, this box is n/a — say so.
  • A rejected or policy-violating prompt, or a provider/rate-limit error, surfaces a clear message in the UI — not a crash, a blank screen, or a silently-broken img. The user can recover and try another prompt.
  • Generation is server-side and authorized: the provider API key never reaches the browser (check the network tab / built client bundle — no key, no direct provider call from the page), the generate endpoint requires auth, and a caller cannot run unbounded costly generations through an open or unrate-limited route. Every image is billed.