Skip to Content
Slloy Docs
Prompt Library, Compliance & Translation

Prompt Library Architecture & Recommendation Engine

Prompt data model, 8 deliverable families (A-H), 10 target platforms, 60-second isolate cache with generation invalidation, ring-queue recommendations, and slot replacement state machine.

The Prompt Library (/prompts and /<locale>/prompts/<slug>) is rendered at the edge via TanStack Start SSR inside the Cloudflare Worker (server/src/promptLibrary.ts). Both the SSR renderer and public JSON endpoints (/api/prompts) share the exact same PromptReader implementation.

1. Prompt Data Model (prompts Table & PromptInput)

Each prompt preset is stored in PostgreSQL (prompts table) and validated by parsePromptInput() (server/src/promptLibrary.ts):

FieldType & ConstraintsPurpose
slugstring (<= 120 chars, /^[a-z0-9]+(?:-[a-z0-9]+)*$/)Immutable URL identifier once published (SLUG_LOCKED).
output"image" | "video" (default "image")Determines whether "Generate Same Style" routes to the image or video workbench and which model registry validates model.
modelstringValidated against imageModels.getModel() when output === "image", or videoModels.getModel() when output === "video".
usePROMPT_USES ("poster", "commerce", "portrait", "character", "illustration")Primary use-case filter tag.
familyPROMPT_FAMILIES | nullDeliverable family (A–H, see Section 2). Also provides fallback cover /assets/family-<id>.webp.
stylePROMPT_STYLES | null ("cyberpunk", "ink", "product", "cute", "anime", "cinematic", "portrait", "flat", "watercolor")Workbench style preset.
ratioPROMPT_RATIOS | null ("1:1", "4:5", "2:3", "3:2", "3:4", "9:16", "16:9", "3:1")For output === "video", restricted to PROMPT_VIDEO_RATIOS ("16:9", "9:16", "1:1").
imageCountint (1..8) or nullMust be null for video presets.
durationint (1..30) or nullMandatory for output === "video" (and <= model.maxDuration); must be null for image presets. Video preset credits scale by ceil((model.credits5s * duration) / 5).
needsReferencebooleanWhether the user must upload a reference photo before generating.
platformsPROMPT_PLATFORMS[] | null (max 8)Target publishing platforms (see Section 2).
seasonPROMPT_SEASONS | null ("spring", "summer", "autumn", "winter", "holiday", "evergreen")Fourth filter dimension on /prompts. Invalid/missing values coerce to null.
slotsArray<{ key: string }> (max 6, /^[a-z][a-z0-9_]*$/)Variable placeholders (e.g., `{product}`, `{headline}`) exposed as interactive inputs on the detail page.
promptEnstring | null (<= 4000 chars)Canonical English prompt text sent to the AI model (promptIsEnglish = record.promptEn != null).
translationsRecord<Locale, Translation>Localized title (<= 120 chars, mandatory in at least en and zh-CN to publish), subtitle (<= 200), uploadHint (<= 200), caveat (<= 300), and disclosure (<= 300).
imageUrlstring | null (isOwnImageUrl)Only accepts self-hosted /uploads/YYYY/MM/prompt_<12hex>.(webp|png|jpg) or static /assets/(demo|family|preset)-<slug>.webp. External URLs are rejected.

2. The 8 Deliverable Families (A–H) & 10 Platforms

8 Deliverable Families (PROMPT_FAMILIES)

Every overseas preset belongs to one of 8 deliverable families (server/src/promptLibrary.ts and frontend/site/content/prompt-families.ts):

Family Codefamily SlugDeliverable ScopeFallback Cover Asset
Family AlistingE-commerce product listing shots (studio backgrounds, lifestyle scenes, detail callouts)/assets/family-listing.webp
Family BsocialSocial media feed & story posts (Instagram 4:5, Pinterest 2:3, TikTok 9:16)/assets/family-social.webp
Family CcoverVideo thumbnails, podcast covers, newsletter headers (3:1), and blog hero banners/assets/family-cover.webp
Family DpersonProfessional headshots, creator portraits, and lookbooks (enforces reference upload & disclosure redlines)/assets/family-person.webp
Family EbrandBrand collateral, flyers (3:4 with A5 trim caveat), packaging mockups, and menu cards/assets/family-brand.webp
Family FeditReference-locked image editing (e.g., F-02 product-photo-pure-white auto-framed to 85% fill, F-04 virtual staging)/assets/family-edit.webp
Family GmotionE-commerce product motion clips and social video loops (output = "video", requires duration)/assets/family-motion.webp
Family HprintPrint-on-demand (POD) graphics, digital downloads, stickers, and seamless patterns/assets/family-print.webp

10 Supported Platforms (PROMPT_PLATFORMS)

Stored as lowercase slugs (brand names are never translated): amazon, etsy, shopify, instagram, tiktok, pinterest, youtube, linkedin, facebook, printful.

URL Filter Validation (hasUnknownPromptFilter)

On /prompts, known filter keys (use, family, platform, season) are strictly validated against their enum sets (ALLOWED_PROMPT_FILTERS). Any request with a known filter key but an unknown or empty value (e.g., ?family=nonexistent) returns HTTP 404 (not a 307 redirect) to prevent search engines from indexing infinite junk parameter URLs, while unknown tracking query parameters (such as utm_*) pass through.


3. 60-Second Isolate Cache & Generation Counter (createCachedPromptReader)

Prior to 2026-11-16, rendering a single uncached /prompts/<slug> page required two cross-region Neon PostgreSQL queries (findPublishedPromptBySlug + listPublishedPrompts for related presets), adding ~1.3s of DB latency (~0.6s per round-trip).

createCachedPromptReader(repo, { ttlMs: 60_000 }) eliminates both redundant queries:

  1. Single Full-Set Snapshot:
    • Caches the complete listPublishedPrompts() array in Worker isolate memory for 60 seconds (ttlMs = 60,000, aligned with the HTML edge cache window).
    • Both list(locale) and detail(locale, slug) derive their output from this single cached array (detail finds the target slug in memory and computes pickRelated() from the same array—zero second DB query).
  2. In-Flight Promise Deduplication:
    • Concurrent requests across 14 locales hitting a cold isolate share a single inflight Promise so the database is queried only once.
    • Failed DB queries clear inflight in .finally() and are never cached.
  3. Generation Counter Invalidation (generation vs. inflightGeneration):
    • Whenever an operator creates, edits, reorders, batch-updates, or changes the status of a prompt in /admin, the admin route calls onPromptsChanged() -> promptReader.invalidate().
    • invalidate() increments generation += 1, clears cached = null, and resets inflight = null.
    • If an older DB query was already in flight when invalidate() fired (startedAt !== generation), its .then() handler refuses to write the stale snapshot into cached, guaranteeing that admin edits are visible immediately on the next preview request.

Earlier versions selected related presets using [...sameUse, ...rest].slice(0, 3), which caused extreme link-equity skew: across 41 live pages (123 recommendation links), 6 head pages captured 82 inbound links while 23 pages received 0 inbound links (orphaned from internal recommendations).

pickRelated(rows, slug, limit = 3) (server/src/promptLibrary.ts) solves this with a deterministic Ring-Queue Algorithm:

  1. Canonical Topological Sort:
    • Sorts all published prompts by:
      1. rankOf(PROMPT_FAMILIES, row.family) (listing -> social -> ... -> print -> null)
      2. rankOf(PROMPT_USES, row.use) (poster -> commerce -> ... -> illustration)
      3. Lexicographical row.slug (a.slug < b.slug)
  2. Ring-Queue Traversal:
    • Finds the current prompt's index at in the sorted ring order.
    • Selects the next limit = 3 items immediately following at modulo order.length:
      const row = order[(at + step) % order.length]!;
  3. Mathematical & SEO Properties:
    • Provably Uniform In-Degree: In a library of N published prompts, every prompt recommends 3 neighbors and is recommended by the 3 predecessors behind it—guaranteeing exact in-degree = 3 and out-degree = 3 for every single prompt page with zero orphan pages.
    • High Topical Relevance: Because items are sorted by (family, use, slug), adjacent items in the ring share the same deliverable family or use case (81 / 123 live edges share family or use case).

5. Variable Slot Replacement vs. Translation State Machine

On the prompt detail page, presets with slots (such as `{product}`, `{brand_color}`) allow users to type custom values in their native language while keeping the final prompt delivered to the image/video model in accurate English:

  1. Canonical English Base (promptEn):
    • The prompt template is authored in English with curly-brace placeholders (e.g., `Studio product photo of {product} on a marble podium...`).
  2. Two-Way Edge Translation Coordination:
    • Reading the Prompt ("Translate" Toggle): When a user on a non-English locale clicks "Translate", the frontend (frontend/site/prompt-translate.ts) calls POST /api/translate with to = currentLocale. protectSlots() replaces `{product}` with [[1]] before calling Workers AI and restoreSlots() restores `{product}` afterward, caching the translated template in a session Map keyed by `${to}\n${text}`.
    • Filling Slot Inputs: When a user enters a non-ASCII value (e.g., "磨砂玻璃香水瓶 30ml") into a slot input (<= 200 chars, TRANSLATE_MAX_VALUE) and triggers generation or copy, the slot value is translated to English (to = "en") via /api/translate and substituted into the canonical English promptEn template so the upstream model receives a pure, high-precision English prompt.
    • Graceful Degradation on HTTP 503: If /api/translate returns 503 UNAVAILABLE (e.g., local dev without Workers AI binding), translateText throws PromptTranslateError("UNAVAILABLE") and the UI hides the translation button rather than showing a broken control.

On this page