LLM-Assisted Programming: From Architecture Design to Runnable Code

    This article walks through building a complete image-community mini-program with an LLM to demonstrate a repeatable collaboration method, rather than reviewing any single model or tool. The core idea is to have the LLM act first as an architect—producing an architecture document, data model, and API contracts—and then as a full-stack engineer implementing one module at a time. You will find a reusable prompt template for eliciting architecture-first output, a checklist for evaluating that output, and practical guidance on pagination strategy, direct-to-storage uploads with least-privilege credentials, and server-side orchestration of AI image generation. It also covers the engineering work models rarely handle on their own—authentication, content moderation, compliance, cost control, observability, and quality assurance—plus common failure modes and how to counter them. If you want to move an LLM from generating code snippets to delivering a shippable product, this shows where your attention is best spent.

    From Writing Code to Building the Scaffold: A Shift in How We Collaborate with LLMs

    With AI coding assistants, it is now routine to ask an LLM to generate code from a one-line requirement. But in most cases it behaves more like a “code snippet generator.” You describe a specific feature, it returns a chunk of code that looks complete and works locally, and the remaining work—aligning interfaces, integrating data, and handling edge cases—still falls to the developer, item by item.

    The problem is not whether the model writes correct code. The problem is that the collaboration stays at the implementation layer. As requirement complexity rises, what actually decides whether a project succeeds is architecture, not any single function. The tech stack, data model, API contracts, state machine, and failure handling: overlook any one of them, and the problems all surface at once during integration. Take “build an image-community mini-program” as an example. If you do not first agree on the object-storage access policy, how upload credentials are issued, and the database indexes, the waterfall feed will suffer performance degradation on deep pagination, uploads will hit timeouts under high concurrency, and the fields the frontend receives will not match what the backend defines.

    This article uses the complete build of an image-community mini-program as its example. The app includes a wallpaper waterfall, upload management, and AI image generation. The focus is not the experience of any single model or tool, but a transferable working method: first have the LLM act as an architect and produce an architecture document, data model, and API contracts; then have it act as a full-stack engineer and implement module by module. The requirements are as follows:

    Module Main features Key constraints
    Wallpaper library Homepage waterfall, album details, image preview and download First-screen speed, deep-pagination performance, image delivery
    Upload management Upload, content moderation, categorization and archiving, backend search and takedown File size and type limits, content compliance, unauthorized access
    AI image generation Image upload and analysis, prompt editing, one-click outfit change, image generation Inference latency and cost, style consistency, generated-content labeling
    User center My works, favorites, settings User isolation, privacy protection

    Non-functional requirements matter just as much: cost control, failure recovery, content moderation, and usage monitoring. Writing them all out up front is the basis for every technical decision that follows.

    Step 1: Structure the Requirements and Put Architecture First

    Prompt Design: From “Write Me a Page” to “Give Me a Plan First”

    The same model produces very different output depending on the input. A method that works well in practice is to have it produce an architecture document first, and generate code only after that document passes review. Here is a reusable prompt template:

    1. Role: You are a senior full-stack architect.
    2. Goal: Produce a technical solution for an "image-community mini-program."
    3. This round outputs only the solution—no code.
    4. Requirements:
    5. 1. Wallpaper library: homepage waterfall (category filtering, pagination),
    6. album details, preview and download.
    7. 2. Upload management: user uploads, content moderation,
    8. backend search and takedown.
    9. 3. AI image generation: upload image -> vision understanding ->
    10. structured prompt -> manual editing -> image generation.
    11. 4. User center: my works, favorites, settings.
    12. Constraints:
    13. - The client is a mini-program; prefer a serverless, pay-as-you-go backend.
    14. - Image generation is billed per call; single-call cost and concurrency must
    15. be controlled.
    16. - Both uploaded and generated content must pass content-safety moderation.
    17. Output requirements:
    18. 1. Frontend pages and component breakdown, routing structure.
    19. 2. Backend architecture: selection of storage, compute, and database
    20. capabilities, with rationale.
    21. 3. Data model: collections, fields, indexes, soft-delete strategy.
    22. 4. API list: method, input, output, error codes.
    23. 5. Cloud function breakdown and call sequence.
    24. 6. Key technical challenges and how to address them.
    25. Finally, list the questions you need me to confirm.

    This template has four key elements:

    • Role and boundaries: “senior architect” and “this round outputs only the solution” steer the model toward design reasoning first, instead of rushing to pile up code.
    • Verifiable constraints: constraints like “billed per call” and “requires moderation” can each be checked during acceptance, which is far more effective than “code quality should be high.”
    • Structured output requirements: an architecture document maps naturally onto the later breakdown of development tasks.
    • Clarifying questions: a good architecture proposal actively asks about business rules. When the model asks questions on its own, it usually means it has understood the constraints behind the requirements.

    What a Complete Architecture Output Contains

    Following the template above, the model produced a fairly complete technical proposal, which can be summarized in six parts.

    (1) Frontend selection

    • Use native mini-program development, with three bottom tabs: Home (wallpaper library), AI Image Generation, and Me.
    • Build shared components at the component layer: waterfall list, image previewer, upload progress bar, prompt-editing card.
    • Split non-first-screen and low-frequency pages into subpackages to keep the main package small.

    (2) Backend selection

    • Use a serverless architecture: cloud functions handle business logic, a managed cloud database holds structured data, object storage holds images, and static hosting serves the admin console.
    • Rationale: no servers to operate yourself; billing by call volume and storage fits a small project with an uncertain user base; cloud functions reach a same-region database and object storage over the internal network, reducing latency and traffic costs.

    (3) AI capability selection: match the model to the task

    AI image generation involves three kinds of tasks that should be handled by three separate capabilities, not by one model doing everything:

    Task Capability type Input and output Design notes
    Image analysis Multimodal vision-understanding model Image -> structured description of subject, style, background, etc. Constrain output dimensions to prevent the description from drifting
    Prompt optimization Long-context text-generation model Structured description -> editable prompt Long context; structured output for easy frontend prefill
    Image-to-image / outfit change Image-generation model Reference image + prompt -> new image The reference image constrains consistency of style, subject, and pose

    It is worth noting that under the constraints set here (a single cloud ecosystem, no operations overhead, pay-as-you-go billing, and support for vision-understanding, text-generation, and image-generation models), a general serverless backend meeting these conditions is available from cloud providers such as Baidu AI Cloud. When choosing, verify each item against your own tech stack and cost model rather than copying any single solution.

    (4) Feature planning

    • Wallpaper library: homepage, album details, image preview, download.
    • AI image generation: upload, analysis, prompt editing, one-click outfit change, generation.
    • Admin side: content moderation, upload-record management, statistics.

    (5) Data model and indexes

    Taking wallpapers as an example, the main collections and fields are as follows:

    1. // Collection wallpaper: wallpaper metadata (image binaries live in object storage;
    2. // the database stores only references)
    3. {
    4. _id, title, categoryId, albumId,
    5. storageKey, thumbKey, width, height,
    6. tags: [], likeCount: 0, downloadCount: 0,
    7. status: "pending" | "approved" | "rejected",
    8. auditReason, creatorId,
    9. createTime, updateTime, deletedAt
    10. }
    11. // Recommended indexes
    12. // 1. categoryId + status + createTime (descending): homepage category list + cursor pagination
    13. // 2. creatorId + createTime (descending): profile works list
    14. // 3. albumId: album-detail aggregation queries

    There are two design points here:

    • Soft delete instead of hard delete: the admin “takedown” only changes status, so removed content remains traceable and recoverable.
    • Decouple counters from metadata: high-write fields such as like counts can be split into a separate collection and incremented asynchronously, so list queries and counter updates do not hold each other back.

    (6) Cloud function breakdown

    The proposal splits the cloud functions by responsibility:

    • feed.list: list queries
    • upload.credential: upload-credential issuance
    • audit.submit: moderation-task submission
    • generate.submit: generation-task submission
    • generate.query: generation-task query
    • admin.*: admin-side interfaces

    Each function has a single responsibility, validates input with a schema, and returns unified error codes. This way each function can be tested independently, and switching to another cloud provider later requires replacing only the adapter layer.

    The proposal also ends with questions for you to confirm: how should content that fails moderation be handled? Should a failed generation be refunded automatically? Can unauthenticated users download? The answers directly affect the interface and data-model design, so it is best to settle them before writing code.

    How to Evaluate an Architecture Proposal: A Review Checklist

    A model’s proposal should not be adopted as-is. Use a checklist like this to review it:

    • Contract completeness: does every interface have clearly defined inputs, outputs, and error codes?
    • Data and indexes: is every high-frequency query backed by an index? Are there denormalized designs that will bloat as data grows?
    • Failure paths: how does the system behave when a model call times out, an object-storage upload is interrupted, or a generation task is throttled?
    • Security boundaries: who can read, who can write? How long is a credential valid? Is the permission scope minimized?
    • Cost model: which calls are billed per use? Are there concurrency and rate limits?
    • Evolvability: if traffic grows later, which designs will become bottlenecks?

    Time invested in the architecture stage is usually paid back many times over during integration. This is the highest-return step in the whole workflow.

    Step 2: Generate Code Module by Module

    Once the architecture is fixed, implement it module by module. Practice has yielded three principles:

    1. Define the contract before writing the implementation: treat the API schemas, data model, and error codes as fixed inputs, and supply them with every prompt, so earlier and later modules do not each assume their own field names.
    2. Core paths before edge features: once the main path “list -> upload -> generate” works end to end, build peripheral features such as the user center and admin console.
    3. Always verify after generating: static checks, unit tests, and real-environment integration are all essential; code generated by a model needs code review just like any other code.

    Waterfall List: Pagination Strategy Sets the Performance Ceiling

    A waterfall feed looks like a layout problem, but what actually sets its performance ceiling is the pagination strategy. Common skip + limit pagination forces the database to scan and discard all preceding records when the page number is deep. Users of community apps often browse dozens of screens, so the latency from deep pagination becomes very noticeable.

    A better approach is cursor pagination: based on a “category + status + creation time” composite index, use the creation time of the last record on the previous page as the starting point for the next page.

    1. // cloudfunctions/feed.list/index.js (illustrative)
    2. const MAX_LIMIT = 30;
    3. const allowedSort = { hot: 'likeCount', latest: 'createTime' };
    4. exports.main = async (event) => {
    5. const { categoryId = 'all', sort = 'latest', cursor, limit = 20 } = event;
    6. const field = allowedSort[sort];
    7. if (!field) return { code: 400, message: 'invalid sort field' };
    8. const where = { status: 'approved', deletedAt: null };
    9. if (categoryId !== 'all') where.categoryId = categoryId;
    10. // cursor is the value of that field on the last record of the previous page.
    11. // Never concatenate query conditions directly, to prevent injection.
    12. if (cursor) where[field] = { $lt: Number(cursor) };
    13. const res = await db.collection('wallpaper')
    14. .where(where)
    15. .orderBy(field, 'desc')
    16. .orderBy('_id', 'desc') // second sort key keeps the cursor unique; avoids skipping records with equal values
    17. .limit(Math.min(Number(limit), MAX_LIMIT))
    18. .get();
    19. const last = res.data[res.data.length - 1];
    20. return {
    21. code: 0,
    22. list: res.data,
    23. nextCursor: res.data.length === MAX_LIMIT && last ? String(last[field]) : null,
    24. };
    25. };

    The frontend just sends nextCursor to request the next page when it scrolls to the bottom. Combined with “load the image’s real dimensions first, then render a placeholder,” this avoids a great deal of layout jank.

    On the component side, you can wrap a stateful list base:

    1. // Reusable list logic for the waterfall, album details, and similar pages (illustrative)
    2. function createPagedList(fetchPage) {
    3. return {
    4. list: [], loading: false, finished: false, error: null,
    5. async loadMore() {
    6. if (this.loading || this.finished) return;
    7. this.loading = true;
    8. try {
    9. const res = await fetchPage(this.cursor);
    10. this.list = this.list.concat(res.list);
    11. this.cursor = res.nextCursor;
    12. this.finished = !res.nextCursor;
    13. } catch (e) {
    14. this.error = e;
    15. } finally {
    16. this.loading = false;
    17. }
    18. },
    19. };
    20. }

    Upload Pipeline: Compression, Direct Upload, and Server-Side Validation

    A common mistake in image upload is having a cloud function receive the file’s binary data: the request body is large, timeouts are likely, and cloud-function costs rise. The correct pipeline is:

    1. The frontend calls a cloud function to obtain a limited, short-lived upload credential.
    2. After compressing the image, the frontend uses that credential to write the file directly to object storage.
    3. The metadata is written to the database.
    4. Moderation is triggered asynchronously.
    1. // Client: compress, then upload directly to object storage (illustrative)
    2. async function uploadImage(filePath) {
    3. // Compress: keep higher resolution for generation entries; list thumbnails can be compressed further
    4. const compressed = await compressImage(filePath, { maxWidth: 1920, quality: 0.85 });
    5. const { credential, objectKey } = await callFunction('upload.credential', { size: compressed.size });
    6. await uploadFile({ url: credential.url, file: compressed.path, headers: credential.headers });
    7. // Register metadata only after the file lands, to avoid dirty data with "a record but no file"
    8. await callFunction('upload.commit', {
    9. objectKey,
    10. width: compressed.width,
    11. height: compressed.height,
    12. });
    13. return objectKey;
    14. }

    The server must validate before issuing a credential; it cannot issue one unconditionally:

    1. // cloudfunctions/upload.credential/index.js (illustrative)
    2. const crypto = require('crypto');
    3. const RULES = {
    4. // Different entry points map to different type, size, and directory limits
    5. wallpaper: { maxSize: 10 * 1024 * 1024, mime: ['image/jpeg', 'image/png', 'image/webp'] },
    6. generate: { maxSize: 8 * 1024 * 1024, mime: ['image/jpeg', 'image/png', 'image/webp'] },
    7. };
    8. exports.main = async (event) => {
    9. const { scene, size } = event;
    10. const rule = RULES[scene];
    11. if (!rule) return { code: 400, message: 'invalid scene' };
    12. if (!rule.mime.includes(event.mime)) return { code: 415, message: 'unsupported media type' };
    13. if (size > rule.maxSize) return { code: 413, message: 'file too large' };
    14. const uid = getUidFromContext(); // take user identity from the call context; do not trust client-supplied params
    15. // The object key is generated server-side so clients cannot overwrite another user's directory
    16. const objectKey = `${scene}/${uid}/${Date.now()}-${crypto.randomUUID()}`;
    17. const credential = await createUploadCredential({
    18. objectKey,
    19. expiresIn: 900, // short-lived, to limit the blast radius if the credential leaks
    20. maxSize: rule.maxSize,
    21. contentType: rule.mime,
    22. });
    23. return { code: 0, objectKey, credential };
    24. };

    The design logic behind this code is “least-privilege credentials.” The credential authorizes writing only files of a specified type into a specific directory, and is valid for minutes. Even if it leaks, the impact is limited.

    AI Image Generation Pipeline: Server-Side Orchestration and Async Execution

    Frontend flow:

    1. Upload a reference image.
    2. Call the vision-understanding model, which returns a structured description across three dimensions: “subject style / visual detail / background mood.”
    3. Assemble it into an editable prompt, with key elements highlighted in the frontend.
    4. After the user edits, choose “generate / outfit change.”
    5. Submit the generation task and poll for the result.
    6. Once generated, the user can save, regenerate, or continue editing.

    Server responsibilities:

    • Call the vision-understanding model.
    • Call the text model to rewrite the prompt.
    • Submit the image-generation task.
    • Maintain task status.
    1. // Generation orchestration (illustrative): all model calls are proxied through the server;
    2. // keys are never sent to the client.
    3. // Vision understanding -> structured description -> prompt rewriting -> result write-back
    4. async function runGeneration(taskId, input) {
    5. // 1. Idempotency check: re-delivered tasks reuse the previous result directly
    6. const existing = await db.collection('generation_task').doc(taskId).get().catch(() => null);
    7. if (existing && existing.data && existing.data.status === 'succeeded') {
    8. return existing.data;
    9. }
    10. // 2. Vision understanding: constrain output dimensions to reduce description drift
    11. const analysis = await visionModel.analyze(input.objectKey, {
    12. dimensions: ['subject style', 'visual detail', 'background mood'],
    13. });
    14. // 3. Prompt rewriting: both input and output are constrained by a JSON Schema to keep fields stable
    15. const prompt = await textModel.complete({
    16. system: PROMPT_SYSTEM, // defines output fields: subject/style/detail/mood/negative
    17. user: JSON.stringify(analysis),
    18. responseFormat: { type: 'json_schema', schema: PROMPT_SCHEMA },
    19. });
    20. // 4. Submit the image-generation task and save the task id for the client to poll
    21. const result = await imageModel.submit({
    22. prompt,
    23. referenceKey: input.objectKey,
    24. size: input.size || '1024x1024',
    25. // Generation calls are typically billed per call, so user-level rate limiting is mandatory
    26. requestId: taskId,
    27. });
    28. await db.collection('generation_task').doc(taskId).set({
    29. status: 'succeeded', prompt, result, updateTime: Date.now(),
    30. });
    31. return { taskId, status: 'succeeded', result };
    32. }

    PROMPT_SCHEMA can be defined with JSON Schema; a key fragment looks like this:

    1. {
    2. "type": "object",
    3. "required": ["subject", "style", "detail", "mood", "promptText"],
    4. "properties": {
    5. "subject": { "type": "string", "description": "main subject of the image" },
    6. "style": { "type": "string", "description": "style, e.g. realistic/illustration/oil painting" },
    7. "detail": { "type": "array", "items": { "type": "string" }, "description": "key detail elements" },
    8. "mood": { "type": "string", "description": "background and mood" },
    9. "negative": { "type": "array", "items": { "type": "string" }, "description": "elements to avoid" },
    10. "promptText":{ "type": "string", "description": "final prompt for the frontend to edit" }
    11. }
    12. }

    The generation feature also needs three design points:

    • Async task model: image generation usually takes several seconds to tens of seconds, far beyond an acceptable wait for a synchronous request. The server should create a task record and return the taskId immediately; the frontend polls or uses a long-lived connection for the result, with a timeout and a fallback for failures.
    • Reuse of generated results: use “reference-image digest + prompt + parameters” as the idempotency key. When the same inputs are requested again, return the existing result directly. This saves cost and makes “regenerate” traceable.
    • Special handling for outfit change: outfit change places higher demands on consistency of pose, garment outline, and lighting. Prefer image-generation capabilities that support reference-image constraints, and state explicitly in the prompt to “preserve the person’s pose and background, and replace only the clothing.”

    Beyond the Model: Engineering Capabilities You Must Add

    Between a prototype that runs and a product that can ship sit several classes of engineering problems the model will not raise for you. The developer must write these explicitly into the requirements.

    Security and Privacy

    • Authentication: cloud functions must verify the caller’s identity. Reading another user’s works without authorization is the most common security hole in community apps.
    • Upload allowlist: validate the real type by the file-header magic number, not just the extension. Allowing formats such as SVG that can carry scripts creates a stored cross-site scripting risk.
    • Sensitive data: personal information such as phone numbers and locations should be encrypted or masked at rest, and access to the admin console should keep audit logs.
    • Content moderation: both uploaded and generated images should be moderated before publishing; records that fail moderation go into a pending queue rather than being discarded outright.

    Compliance Requirements

    • Generated-content labeling: in line with applicable regulations on labeling AI-synthesized content, AI-generated images should carry an explicit or implicit label, and the display page should state “generated by AI.”
    • Distribution of unreviewed content: content that has not passed moderation should be visible only to its uploader.

    Cost and Observability

    • Budget guardrails: set a daily generation limit per user and an alert threshold for the total budget.
    • Parameter tiers: tier generation resolution and model levels—low resolution for previews, high-definition output only when the user confirms and saves.
    • Monitoring: connect logging and monitoring/alerting services, and set alerts for cloud-function error rates, P95 latency, and object-storage request volume. Only then can cost be managed quantitatively instead of by looking at the bill at month end.

    Quality Assurance

    • Unit tests: require the model to generate corresponding unit tests alongside its code, and include them in continuous integration.
    • Type checking and static analysis: run automatically after each generation to catch obvious type errors and unhandled exceptions.
    • End-to-end tests: cover the two main paths, “upload -> moderation -> display” and “generation -> polling -> save.”
    • Contract tests: front-end/back-end mismatches caused by changing interface fields often surface only during integration; contract tests catch them earlier.

    Common Problems and How to Address Them

    In practice, this workflow runs into some typical problems.

    Problem 1: In a long conversation, the model forgets earlier constraints.

    The fix is to turn “immutable context” into spec files stored in the repository, such as ARCHITECTURE.md and API_CONTRACT.md, and supply them with every prompt. Constraints then depend on files, not on the model’s memory.

    Problem 2: Cross-module changes cause regressions.

    Have the model work on one module at a time and run the relevant unit tests after each change. For changes with a large blast radius, require the model to first list the affected files and get human confirmation before making edits.

    Problem 3: The model’s code “runs” but lacks failure handling.

    Write failure handling into the acceptance criteria during the architecture stage: every external call must have a timeout, a retry, and a fallback path. At acceptance, check each item against the list rather than only checking whether the main flow works.

    Problem 4: Treating a prototype as a product.

    A prototype phase may allow “getting it working first,” but you must explicitly record technical debt in the task list—for example, missing authentication, hard-coded configuration, and indexes that have not been added—and set a time to pay it down.

    Conclusion: Redrawing the Line Between Human and Machine

    Looking back over the whole build, one plain conclusion stands out: what LLMs truly change is how developers allocate their attention.

    In the past, developers spent much of their time on boilerplate code and interface integration, while design decisions were squeezed into the most rushed stage. Once a model can take on most of the execution work of “architect + implementer,” the developer’s value concentrates where the model is weak and cannot substitute:

    • Defining the problem: which requirements are real needs, and which metrics are the success criteria.
    • Setting boundaries: where the red lines for cost, compliance, security, and performance lie.
    • Making trade-offs: when there is no absolute winner among options, choosing based on the team’s current situation and long-term evolution.
    • Verifying results: beyond code correctness, whether the system remains reliable under real traffic and malicious input.

    Do these parts well, and the code the model generates can genuinely become a deliverable product. This may also be the most reliable response to rapidly evolving model capabilities: instead of chasing every new version, build a stable method for defining problems and verifying results.