@molecule/api-ai-summarization-molecule

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

molecule.dev hosted AI summarization — summaries with hard word caps enforced in code, billed to your molecule project

npm install @molecule/api-ai-summarization-molecule

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

How it works

@molecule/api-ai-summarization-molecule is a provider bond on the API (Node) side: it implements the ai-summarization core interface (@molecule/api-ai-summarization) 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-summarization, @molecule/api-secrets

Secrets: MOLECULE_API_KEY

Reference

molecule.dev hosted AI summarization — summaries with hard word caps enforced in code, billed to your molecule project

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-summarization-molecule @molecule/api-ai-summarization @molecule/api-secrets

API

Interfaces

MoleculeSummarizationConfig

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

interface MoleculeSummarizationConfig {
  /**
   * 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 60000 — a capped summary can
   * take several model round trips (it re-asks when an attempt runs long).
   */
  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. */
  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
  }
}

MoleculeSummarizationProvider

AI summarization provider backed by molecule.dev's hosted service.

The model is the SERVICE's choice — SummarizeInput.model and SummarizeInput.provider (a self-hosted bond's ai-provider selectors) are not forwarded, so a call that sets them keeps running on the hosted default instead of failing.

class MoleculeSummarizationProvider implements AISummarizationProvider {
  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: MoleculeSummarizationConfig = {}) {
    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 ?? 60_000
  }

  /**
   * Summarize the text.
   *
   * @param input - The source text plus optional shape/length/focus controls.
   * @returns The summary and metering metadata.
   */
  async summarize(input: SummarizeInput): Promise<SummarizeResult> {
    const limits = SUMMARIZATION_SERVICE_LIMITS
    if (typeof input.text !== 'string' || input.text.length === 0) {
      throw new MoleculeServiceError(
        '"text" must be non-empty text.',
        400,
        'hostedServices.error.invalidInput',
      )
    }
    if (input.text.length > limits.maxTextChars) {
      throw new MoleculeServiceError(
        `The text is ${input.text.length} characters; the limit is ${limits.maxTextChars}. ${HINTS[413]}`,
        413,
        'hostedServices.error.inputTooLarge',
      )
    }
    for (const [field, max] of [
      ['maxWords', limits.maxWords],
      ['maxLength', limits.maxLength],
      ['sentences', limits.maxSentences],
      ['attempts', limits.maxAttempts],
    ] as const) {
      const value = input[field]
      if (value !== undefined && (typeof value !== 'number' || !Number.isInteger(value))) {
        throw new MoleculeServiceError(
          `"${field}" must be an integer.`,
          400,
          'hostedServices.error.invalidInput',
        )
      }
      if (value !== undefined && (value < 1 || value > max)) {
        throw new MoleculeServiceError(
          `"${field}" must be between 1 and ${max}.`,
          400,
          'hostedServices.error.invalidInput',
        )
      }
    }
    if (
      input.focus !== undefined &&
      (typeof input.focus !== 'string' || input.focus.length > limits.maxFocusChars)
    ) {
      throw new MoleculeServiceError(
        `"focus" must be text of up to ${limits.maxFocusChars} characters.`,
        400,
        'hostedServices.error.invalidInput',
      )
    }
    if (input.format !== undefined && !(FORMATS as readonly string[]).includes(input.format)) {
      throw new MoleculeServiceError(
        `"format" must be one of: ${FORMATS.join(', ')}.`,
        400,
        'hostedServices.error.invalidInput',
      )
    }
    const body: Record<string, unknown> = {
      text: input.text,
      ...(input.maxLength !== undefined ? { maxLength: input.maxLength } : {}),
      ...(input.maxWords !== undefined ? { maxWords: input.maxWords } : {}),
      ...(input.sentences !== undefined ? { sentences: input.sentences } : {}),
      ...(input.attempts !== undefined ? { attempts: input.attempts } : {}),
      ...(input.format !== undefined ? { format: input.format } : {}),
      ...(input.focus !== undefined ? { focus: input.focus } : {}),
    }
    const signal = input.signal
      ? AbortSignal.any([input.signal, AbortSignal.timeout(this.timeoutMs)])
      : AbortSignal.timeout(this.timeoutMs)
    return this.request(body, signal)
  }

  /** One POST to the hosted service. */
  private async request(
    body: Record<string, unknown>,
    signal: AbortSignal,
  ): Promise<SummarizeResult> {
    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}/summarization/summarize`, {
      method: 'POST',
      headers: { authorization: `Bearer ${this.apiKey}`, 'content-type': 'application/json' },
      body: JSON.stringify(body),
      signal,
    })
    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 = (typeof data === 'object' && data !== null ? data : {}) as {
        error?: unknown
        errorKey?: unknown
      }
      const hint = HINTS[response.status]
      const message = typeof err.error === 'string' ? err.error : 'error'
      throw new MoleculeServiceError(
        `molecule.dev summarization/summarize failed (${response.status}): ${message}${hint ? ` ${hint}` : ''}`,
        response.status,
        typeof err.errorKey === 'string' ? err.errorKey : undefined,
      )
    }
    if (
      typeof data !== 'object' ||
      data === null ||
      typeof (data as { summary?: unknown }).summary !== 'string'
    ) {
      throw new MoleculeServiceError(
        'molecule.dev returned a summarization response without a summary string.',
        response.status,
        'hostedServices.error.invalidResponse',
      )
    }
    return data as SummarizeResult
  }
}

Functions

createProvider(config)

Create a hosted AI summarization provider.

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

Returns: An AISummarizationProvider backed by molecule.dev.

Constants

provider

The provider implementation (wire with setProvider).

const provider: AISummarizationProvider

DEFAULT_SERVICES_URL

Default hosted services base URL.

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

SUMMARIZATION_SERVICE_LIMITS

Per-request limits of the hosted service (mirrored for local refusal).

const SUMMARIZATION_SERVICE_LIMITS: {
  readonly maxTextChars: 100000
  readonly maxWords: 500
  readonly maxLength: 1000
  readonly maxSentences: 10
  readonly maxAttempts: 5
  readonly maxFocusChars: 2000
}

aiSummarizationMoleculeSecretDefinitions

Secret definitions required by the molecule.dev hosted AI summarization bond.

const aiSummarizationMoleculeSecretDefinitions: SecretDefinition[]

Core Interface

Implements @molecule/api-ai-summarization interface.

Bond Wiring

Setup function to register this provider with the core interface:

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

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

Injection Notes

Requirements

Peer dependencies:

  • @molecule/api-ai-summarization >=1.1.0
  • @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-summarization
  • @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:

  • Summarizing a real long document through the app's UI returns a summary that is clearly SHORTER than the input and captures its key points — not a truncation of the first N characters, not an echo of the input, not empty. The sandbox has a live AI provider, so this runs for real; the output is non-deterministic, so assert on behavior (it is shorter, the main ideas are present), never on an exact string.
  • A second, different document yields a genuinely different summary — not the same cached/boilerplate text — confirming each summary reflects the actual input rather than a canned response.
  • The shape/length controls actually change the output: a smaller maxLength (approx target words) produces a shorter summary than a larger one, and switching format between 'paragraph', 'bullets', and 'tldr' visibly changes the structure (bullets render as a list, tldr is terser). If the app exposes only some of these, verify the ones it exposes.
  • Edge inputs are handled, not silently mangled: empty or whitespace-only input does not crash and gives a clear "nothing to summarize" response; very long input (beyond the model's limit) either summarizes or fails with a visible, clear message — never a silent truncation that drops half the meaning.
  • A provider failure (the AI request errors, is rate-limited, or times out) surfaces gracefully in the UI — a readable error, no blank screen, no crash, no uncaught 500.
  • The summarize call runs server-side only: no AI key or provider secret is ever exposed to the browser. Confirm the request goes to this app's own API and the key never appears in network traffic or the client bundle.