Building an AI Wallpaper Mini Program with LLMs: Architecture, Engineering Details, and Lessons Learned

    This article walks through a real project: a mini program that combines an image library browser with AI image creation. It explains how LLM-assisted development shifts from generating code snippets to drafting full architecture proposals, how to write a requirements brief that produces executable output, the three-tier layered architecture (native mini program frontend, Serverless backend, three-model AI pipeline), the data model, and the engineering details that actually matter — waterfall pagination, direct client-to-object-storage uploads, structured prompt pipelines, single-entry cloud functions with observability — plus cost controls, compliance obligations, a generation review checklist, and which developer skills stay relevant as models keep iterating.

    1. From Writing Snippets to Designing Architecture

    When we used AI coding assistants in the past, the interaction mostly stayed at the level of “write me a carousel component”: the model returned a sample snippet, while integrating it into the project, aligning data structures, and handling edge cases were still the developer’s job — assembling line by line, debugging, and filling in the gaps. The model’s role was closer to a snippet generator.

    In a recent full project — a mini program with both an image library browser and AI image creation — that collaboration model changed noticeably when paired with a newer generation of LLMs. The requirement was given as a single short paragraph, yet the model first returned a complete implementation plan: technology choices, module boundaries, data structures, and dependencies. That made me reconsider where the line between human and machine actually sits: LLMs are moving from local implementation toward overall planning.

    One point deserves emphasis: what the model outputs is a solution skeleton and a runnable code starting point, not a production-ready product. What ultimately determines project quality is still the clarity of the requirements, the rigor of the architecture review, and the engineering work required to fill the gaps.

    2. Requirements Input: The First Gate on Solution Quality

    The ceiling on model output quality is set by the precision of the requirements description. Vague input produces plans that look reasonable but cannot be built; structured input significantly improves executability.

    An effective requirements brief should cover at least six categories of information:

    • Target users and use scenarios: who opens the product, in what context, and whether their primary need is browsing, saving, or creating.
    • Functional boundaries: which capabilities are mandatory, and which are explicitly out of scope for this release (for example, “no community comments, no payment system”).
    • Technical constraints: target platform, whether a backend is required, whether a managed development backend is allowed, and the per-user cost ceiling.
    • Data volume estimates: order of magnitude of content items, total image count, and peak concurrency — these directly shape pagination strategy and storage design.
    • Performance and experience requirements: acceptable first-screen load time, image sizing strategy, and degradation behavior on poor networks.
    • Deliverable format: which files are expected, plus directory structure, naming, and commenting conventions.

    Here is the requirements brief used for this project (anonymized and rewritten):

    1. I want to build a mini program with an image library and AI image creation.
    2. 1. Platform: a major mini program container, three TabBar pages: Home, Create, Profile.
    3. 2. Home: waterfall browsing + album/category filtering + image preview and save.
    4. 3. Create: upload image -> analyze the scene -> generate/edit the prompt -> generate a new image -> save or keep editing.
    5. 4. Profile: my favorites, my works, management of my uploads.
    6. 5. Backend: prefer an all-in-one Serverless development solution (managed database + cloud functions + object storage); I do not want to operate servers myself.
    7. 6. AI capabilities: a vision model for scene analysis, a text model for prompt rewriting, and an image generation model for generation and image-to-image.
    8. 7. Data volume: about 5,000 content items initially; each image kept under 300KB after compression.
    9. 8. Please output the technical architecture and data model first; once confirmed, write the code module by module.

    The last line — “output the architecture first, write code only after confirmation” — is especially important. It splits generation into two reviewable stages and avoids the situation where a large amount of code arrives at once and problems are hard to localize.

    3. Layered Architecture: A Route That Can Actually Ship

    The architecture the model returned aligns closely with established industry practice. It can be summarized as “three tiers, decoupled capabilities.”

    3.1 Frontend: Native Development on the Mini Program Container

    Three reasons drove the choice of native container capabilities over a cross-platform framework: image-browsing applications are sensitive to rendering performance and gesture interaction, and native component chains are shorter; metrics such as waterfall layouts and long-list virtual scrolling are demanding; and with only three simple pages, the benefit of introducing a cross-platform compilation layer is lower than its debugging cost.

    Page division and responsibility boundaries:

    Page Core responsibility Key components
    Home Category filtering, waterfall browsing, preview and save Waterfall container, lazy-load sentinel, image preview layer
    Create Upload, analysis, prompt editing, generation Upload component, structured prompt editor, result comparison area
    Profile Favorites, works, upload management Segmented control, reusable lists, delete confirmation dialog

    The three-page TabBar split may look arbitrary, but it actually determines state management complexity. Favorite state and in-progress creation state must persist across pages, so I recommend maintaining a lightweight global state layer alongside page data (for example, the ID of the session currently being edited) instead of reinitializing the flow on every page switch.

    3.2 Backend: Serverless First

    For a content-driven application like this, self-hosting servers is poor value: traffic has pronounced peaks and troughs, and image processing plus AI calls are classic burst workloads. A managed development backend provides a database, cloud functions, and object storage as a package, which naturally fits a “no operations + pay per use” scenario. Comparable capabilities exist in the product portfolios of major cloud providers (for example, Baidu AI Cloud); evaluate them against selection criteria such as cold-start behavior, concurrency quotas, cross-region access latency, and completeness of the surrounding tooling.

    3.3 Layering the AI Capabilities: Three Models in One Pipeline

    AI creation should not be the responsibility of a single model doing everything. The sound approach is to chain models by capability:

    1. Vision model: takes the user’s uploaded image and outputs a structured description of subject, style, details, and atmosphere.
    2. Text model: rewrites the structured description into a prompt suited to the generation model’s preferences, with room for the user to edit it afterwards.
    3. Image generation model: supports both text-to-image and image-to-image, accepting parameters such as size and aspect ratio.

    This layering brings three direct benefits: each stage can be replaced and canary-released independently; user editing happens at the prompt level, which is far more controllable than editing the image itself; and a single failed call only requires rerunning that stage rather than the whole chain.

    3.4 Data Model

    A minimal viable schema usually contains five tables: the content table (image library entries), the album table, the user favorites table, the works table (generation records), and the uploads management table. The content table should include at least the following fields:

    1. // Content item (illustrative)
    2. {
    3. _id, title, albumId,
    4. fileID, // points to the original image in object storage
    5. width, height, // original dimensions, used for waterfall ratio calculation
    6. tags: [], // tags used for filtering
    7. status, // review status: pending / approved / rejected
    8. createTime
    9. }

    The critical dependency for a waterfall layout is the width and height fields. If dimensions are not recorded at upload time, the frontend can only wait for each image to finish loading before reflowing the layout, which causes visible jank.

    4. Key Engineering Details

    The code below is illustrative pseudocode intended to convey the approach, not implementations to copy directly.

    4.1 Waterfall Layout and Pagination

    A waterfall layout needs to distribute items evenly across columns by height while avoiding the memory pressure of long lists.

    1. // Mini program: pagination + two-column height balancing
    2. Page({
    3. data: { page: 0, size: 20, left: [], right: [], lh: 0, rh: 0, hasMore: true },
    4. async loadMore() {
    5. if (this.data.loading || !this.data.hasMore) return;
    6. this.setData({ loading: true });
    7. const { list, next } = await api.listWallpapers({
    8. page: this.data.page, size: this.data.size,
    9. albumId: this.data.albumId,
    10. });
    11. const left = [...this.data.left], right = [...this.data.right];
    12. let { lh, rh } = this.data;
    13. for (const item of list) {
    14. // Derive card height from the original dimensions instead of waiting for image load
    15. const h = this.columnWidth * (item.height / item.width) + GAP;
    16. if (lh <= rh) { left.push({ ...item, h }); lh += h; }
    17. else { right.push({ ...item, h }); rh += h; }
    18. }
    19. this.setData({ left, right, lh, rh, page: next, hasMore: next > 0 });
    20. },
    21. });

    On the cloud function side, I recommend “cursor pagination + total count separated”: the list endpoint returns only data and the next cursor, while the total count comes from a separate lightweight endpoint. This avoids running a full count on every pagination request.

    4.2 The Image Upload Path

    Do not have the client stream image bytes through a cloud function to object storage — that consumes both the function’s memory and its execution duration quota. The correct approach is to obtain a temporary upload ticket and let the client upload directly:

    1. // Client: compress -> exchange for temporary ticket -> upload directly to object storage
    2. const picked = await platform.chooseImage({ count: 1 });
    3. const compressed = await platform.compressImage({ src: picked.path, quality: 80 });
    4. const { uploadPath, credentials } = await api.getUploadTicket({
    5. scene: 'wallpaper', // the scene determines the directory and validation policy
    6. size: compressed.size,
    7. });
    8. const { fileID } = await platform.uploadFile({ uploadPath, credentials, filePath: compressed });

    The server must validate when issuing the ticket: whether the scene and file size match, whether the call rate exceeds limits, and whether the ticket’s lifetime is short enough. Otherwise the bucket quickly turns into a dumping ground for junk files.

    4.3 A Structured Prompt Pipeline

    A natural-language description returned directly by the vision model is awkward to use and hard for users to edit. A better approach is to constrain the model to return structured fields, which the frontend renders as editable tags and text inputs.

    1. async function analyzeImage(fileID) {
    2. const raw = await visionModel.analyze({ fileID });
    3. // Mark key elements as highlight so the frontend can emphasize them
    4. return {
    5. subject: { text: raw.subject, highlight: true },
    6. detail: { text: raw.detail, highlight: false },
    7. atmosphere: { text: raw.atmosphere, highlight: true },
    8. };
    9. }
    10. async function optimizePrompt(structured) {
    11. return textModel.rewrite({
    12. input: structured,
    13. rules: ['keep the subject characteristics', 'add composition and lighting description', 'output no more than 120 characters'],
    14. });
    15. }
    16. async function generateImage({ prompt, mode, refImageId, size }) {
    17. // mode: 'text2img' | 'img2img'
    18. return imageModel.generate({ prompt, mode, refImageId, size, seed });
    19. }

    Fixing the seed is an easy-to-miss detail. It makes “tweak the prompt and regenerate” comparable — the user can see what the change actually did, rather than getting a random new image every time.

    4.4 Cloud Functions: Single Entry, Multiple Actions, Observable

    Splitting AI capabilities into a pile of small, fine-grained cloud functions amplifies the cold-start problem. A more practical pattern is a single entry that routes by action:

    1. const actions = { analyzeImage, optimizePrompt, generateImage };
    2. exports.main = async (event) => {
    3. const t0 = Date.now();
    4. const { action, payload, requestId } = event;
    5. if (!actions[action]) return { code: 400, msg: 'unsupported action' };
    6. try {
    7. const data = await actions[action](payload);
    8. await logger.info({ requestId, action, costMs: Date.now() - t0 });
    9. return { code: 0, data };
    10. } catch (e) {
    11. await logger.error({ requestId, action, err: e.message, costMs: Date.now() - t0 });
    12. // Distinguish retryable from non-retryable errors so the client does not blindly retry and inflate cost
    13. const retryable = isRetryable(e);
    14. return { code: retryable ? 503 : 500, msg: e.message, retryable };
    15. }
    16. };

    The requestId must be threaded through the logs; otherwise, once a single AI call has crossed three segments — the frontend, the cloud function, and the external model — the problem becomes impossible to trace. Pairing this with a logging service, alerting, and a dashboard covering call volume, failure rate, and per-call latency is what determines whether this architecture can run in the long term.

    5. Why Dozens of One-Shot Generated Files Actually Run

    Generating more than thirty files in one pass with no blocking defects is not magic. It comes down to four controllable factors:

    • Conventions first: endpoint paths, request/response structures, and database fields were defined before coding, so modules could not be structurally mismatched.
    • A converged technology stack: once native development and a managed backend were specified, the model did not have to waver between engineering paradigms, which avoided dependency-version and directory-structure chaos.
    • Module-by-module generation: producing one module at a time instead of everything at once keeps the context focused and the semantic consistency of each module higher.
    • Explicit exclusions: stating “not in this release” in the requirements prevents the model from generating half-finished payment or comment code.

    The limitations, however, must also be acknowledged. Three classes of problems still require human involvement:

    1. Implicit business knowledge: rules such as review policy, copyright handling, and promotional slot configuration are often absent from requirements documents, and the model has no way to know them.
    2. Platform differences and version behavior: container permission configuration, differences between real devices and simulators, and the availability scope of specific APIs all require verification on real devices.
    3. Security defaults: whether keys end up bundled into the client package, whether upload paths are predictable, whether endpoints have rate limits — none of these are handled automatically.

    So I recommend a fixed review checklist for every generation pass:

    • No long-lived keys or access credentials exist anywhere in client code
    • All public-facing endpoints have identity verification and rate limiting
    • Database writes account for duplicate submissions and idempotency
    • User-uploaded content enters a pending-review state and becomes publicly visible only after approval
    • Error paths show degradation messages and never expose stack traces to users
    • Critical flows (upload, generation, save) have end-to-end tests

    6. Cost and Compliance: The Most Commonly Underestimated Parts

    AI image generation is metered per call, so cost grows roughly linearly with active users and is easy to abuse. At minimum, I recommend four controls: a per-user daily generation quota, request queuing and rate limiting under concurrency, a retry cap for failed calls, and cache reuse for generated results (identical prompt and seed hits the cache instead of calling the model again).

    Three compliance points cannot be ignored. First, copyright risk in uploaded content: users may upload someone else’s work as a reference image, which can constitute infringement, so this must be disclosed and confirmed before upload. Second, review of generated content: for image content, integrate a content safety capability for automated moderation and keep a channel for manual review of suspicious results. Third, data minimization for personal information: fields such as avatar and nickname should follow the principle of minimum necessity, with an explicit data retention period.

    7. What Developers Should Focus On When Models Keep Iterating

    Model capabilities evolve far faster than engineering practice. Chasing every new release is neither realistic nor necessary. A more effective approach is to invest in three capabilities that will not go out of date:

    • Problem definition: translating business needs into clear, verifiable specifications. Models cannot replace this, and it sets the ceiling on output quality.
    • Architectural judgment: recognizing where a solution applies, knowing when to use Serverless, when self-hosting is mandatory, and where caching or queues are needed.
    • Verification and governance awareness: writing tests, reading logs, conducting security reviews. The more code a model generates, the more valuable human verification becomes.

    To summarize the real takeaway from this project in one line: LLMs have compressed the time from zero to runnable more than ever before, and engineering competitiveness is shifting toward “can you state clearly what you want, and can you judge whether it is right.” The tools will keep getting stronger, while clear thinking and a commitment to quality remain the parts that cannot be generated.