# How to Evaluate and Select LLMs for Frontend and 3D Code Generation

    A reproducible approach to benchmarking large language models on frontend implementation and 3D graphics tasks: layered task sets, pinned environments, automated build/render/visual scoring, per-task cost accounting instead of token price, sandboxing for untrusted generated code, and a layered routing strategy that spends budget where it actually matters. Includes failure-mode analysis, prompt-constraint tactics, an evaluation harness sketch, and a selection checklist.

    1. Why “it generated a page” is no longer enough

    Code-generation benchmarks have long stayed at toy level: “can it write a to-do list app?” In real engineering, the two hardest deliverables are pixel-accurate frontend implementations of a design spec and 3D interactive scenes that actually run. Both share the same traits: vague requirements, heavy reliance on implicit conventions, and errors that never surface at compile time — you only see them in the rendered output.

    A demo that “looks good” is not a shippable deliverable. The bar should be: does the generated code pass the build on the first try, does it pass visual acceptance, and does modifying it later stay cheap? This article is about an evaluation and model-selection method built around exactly those criteria.

    2. Building a reproducible evaluation set

    The most common reason evaluations fail is that the questions change every round. Before conclusions can be trusted, freeze the evaluation into an asset.

    Task tiers

    Tier Task type What it probes
    L1 Single-file static page or component snippet Semantic markup, style organization, basic accessibility
    L2 Multi-file project (state management, routing, API layer) Module boundaries, type completeness, reasonable dependency versions
    L3 Design-spec reproduction (given visual spec and target size) Layout precision, spacing system, typography and responsive breakpoints
    L4 3D / graphics scene (camera, lighting, geometry, picking) Correct coordinate system, understanding of the render pipeline, performance budget
    L5 Incremental changes and refactors on an existing codebase Context comprehension, minimal diffs, respect for existing conventions

    L5 is closest to daily work and the least evaluated. Include at least 3–5 tasks drawn from your own repositories, and keep the original unit tests as an objective criterion.

    Pin the environment

    One evaluation run must lock down: the dependency manifest and versions, build-tool configuration, render environment (browser or rendering engine version, viewport size), sampling temperature, max output tokens, and the full verbatim prompt. Any change to these should be annotated in the report, otherwise data across rounds is not comparable.

    Scoring dimensions

    Don’t score on a single “good/bad” axis. Break it into metrics you can obtain automatically or semi-automatically:

    • First-pass rate — share of first attempts that pass build and static checks
    • Runnable rate — share that builds but fails at render time or has broken functionality
    • Visual fidelity — structural similarity and pixel-diff rate against a target screenshot
    • Interaction completeness — share of the interaction points enumerated in the spec that were implemented (empty state, loading state, error state, keyboard operation)
    • Maintainability — duplicated-code ratio, naming consistency, presence of type or contract constraints
    • Fix cost — editing time or lines changed for a human to reach “shippable”

    The first three can be automated; the last three require manual or semi-automated collection. In practice, fix cost often predicts real-world experience better than first-pass rate: some models score mid-tier on the first round, but their mistakes are easy to localize and the diffs stay small, so the total cost is lower.

    Automated checks

    Compress “a human looks at the output” into a pipeline: build → static check → unit tests → render → screenshot → compare against the target.

    1. # Sketch: core flow of the evaluation harness
    2. def evaluate(task, model_client, env):
    3. prompt = render_prompt(task.spec, task.constraints) # fixed prompt template
    4. artifact = model_client.generate(prompt) # sample multiple times, log each output
    5. build = env.build(artifact) # failure is recorded as build_fail
    6. if build.failed:
    7. return Result(task.id, stage="build_fail", log=build.log)
    8. tests = env.run_tests(artifact) # objective criterion, re-runnable
    9. shot = env.screenshot(artifact, viewport=task.viewport)
    10. return Result(
    11. task.id,
    12. build_ok=True,
    13. test_pass=tests.pass_ratio,
    14. visual_score=compare(shot, task.golden), # structural similarity + pixel diff rate
    15. manual_fix_minutes=None, # filled in by a human
    16. )

    For the comparison step, keep two signals side by side. Pixel-diff rate is sensitive to color and spacing; structural similarity is sensitive to layout breakage. Together they distinguish “small offsets” from “wrong overall structure” — and the latter usually comes from picking the wrong layout model or missing responsive breakpoints.

    3. Frontend and visual tasks: failure modes and prompt countermeasures

    Common failure modes

    1. Right structure, wrong visuals — element positions are sensible, but spacing, type scale, corner radii and shadows don’t match the spec.
    2. No responsive behavior — a single breakpoint is implemented, and the layout overflows or crushes on narrow screens.
    3. Missing states — only the happy path; no empty, loading, error, or disabled states.
    4. No accessibility — interactive elements are carried by non-semantic tags, with no visible focus style and no label association.
    5. Dependency bloat — a large dependency is pulled in for one gradient, and bundle size and startup time become uncontrollable.
    6. Unrunnable resource references — paths point at static assets that don’t exist, leaving blank regions on the page.

    Prompt-level constraint tactics

    • State the delivery shape explicitly: single file or multi-file, must it run standalone, are external resources allowed.
    • Give quantified visual specs instead of adjectives. Replace “comfortable whitespace” with “24px section spacing, 12px card radius, 1.6 body line-height” and executability improves noticeably.
    • Require an explicit layout strategy — for example, “flex layout for the outer container, CSS grid for the card grid with a declared minimum column width and auto-fill”.
    • Require self-证明 of runnability: have the model append the build command and a list of expected interaction points to its output, so automated checks can align.
    • Declare constraint boundaries: dependency allowlist, no inline event attributes, keyboard reachability must be preserved.
    1. /* Prompt constraint example: adaptive grid + explicit breakpoint + visible focus */
    2. .card-grid {
    3. display: grid;
    4. grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    5. gap: 24px;
    6. }
    7. @media (max-width: 640px) {
    8. .card-grid { gap: 16px; }
    9. }
    10. :focus-visible {
    11. outline: 2px solid #1a73e8;
    12. outline-offset: 2px;
    13. }

    4. 3D and graphics tasks: harder, and more revealing

    3D tasks separate models because they demand both a correct mental model and a strict performance budget. Anything left ambiguous shows up directly as a rendering error.

    Core difficulties

    • Coordinate system and handedness conventions — if a model mixes up left- and right-handed systems or rotation order, objects point in ways that are hard to attribute.
    • Units and scale — models tend to default to fixed units, while a real scene needs camera and light parameters aligned in meters.
    • Render state management — the order of toggles for depth testing, blending modes, and double-sided rendering affects occlusion.
    • Lighting and material coupling — when the material type doesn’t match the lighting model, the image goes flat gray or blows out.
    • Assets and performance — polygon count, draw calls, texture sizes, and whether geometry and materials are reused determine whether the frame rate holds on mobile.
    • Closed interaction loops — picking, dragging, camera orbit control, collision and boundary handling are often only half implemented.

    Sketch: a scoreable scene skeleton

    The following is pseudo-code illustrating the checkpoints; it does not refer to any specific API.

    1. scene = createScene(background = color(0.05, 0.05, 0.06))
    2. camera = createPerspectiveCamera(fov = 45, aspect = viewport.width / viewport.height,
    3. near = 0.1, far = 100)
    4. camera.position = (3.2, 2.4, 4.0)
    5. camera.lookAt(origin)
    6. // Lighting: ambient + directional + contact shadow; probes the model's choices across lighting layers
    7. scene.add(createAmbientLight(intensity = 0.4))
    8. scene.add(createDirectionalLight(intensity = 1.2, position = (5, 8, 3), castShadow = true))
    9. // Geometry and materials: reuse first; probes understanding of shared vs. cloned resources
    10. sharedMaterial = createStandardMaterial(baseColor = gray(0.7), roughness = 0.5)
    11. for i in 0..N:
    12. mesh = createMesh(createBoxGeometry(1, 1, 1), sharedMaterial)
    13. mesh.position.x = i * 1.2
    14. scene.add(mesh)
    15. // Render loop: probes pausing, resource disposal, and frame-rate control
    16. onAnimationFrame((dt) => {
    17. group.rotation.y += dt * 0.5
    18. renderer.render(scene, camera)
    19. })
    20. // Interaction: picking and orbit control; probes pointer-event and teardown handling
    21. enableOrbitControl(camera, domElement)
    22. enablePicking(canvas, { onSelect: (obj) => highlight(obj) })

    Checklist derived from the sketch: Are units and scale conventions declared? Are geometry and materials reused? Are shadow and depth-related states configured? Are geometry, materials and textures disposed and event listeners removed when the view unmounts? Is there a degradation path for low-end devices (lower pixel ratio, smaller shadow maps, capped polygon count)? Is the picking and camera-control loop actually closed?

    Write the performance budget into the requirements. For example: “target 60fps, no more than 100 draw calls, initial asset payload under 2MB”. A 3D generation without a budget will almost inevitably degrade on a real device.

    5. Cost evaluation: cost per task, not price per token

    Unit price is only one term in the formula. The real bill is decided by retry count, context length, and manual fixes. A workable accounting model:

    1. Cost per task = (input tokens × input price + output tokens × output price) × average attempts
    2. + manual fix hours × hourly human cost
    3. + rework cost from unusable output (build failures, render failures)

    This model produces a few counterintuitive but important conclusions:

    1. The cheapest per-token option isn’t necessarily the cheapest overall. If first-pass rate drops, average attempts rise and total spend can end up higher; the hidden cost of fix hours usually exceeds token fees.
    2. Context length is a cost amplifier. Stuffing an entire repository into the context is expensive and introduces noise. It works better to retrieve relevant snippets and supply type definitions and call contracts instead of feeding everything in.
    3. Route by tier. Split tasks by complexity: format conversion, style tweaks and boilerplate go to lighter models; cross-file refactors, 3D architecture design and hard bug localization go to stronger models. In testing, this split keeps delivery quality roughly intact while lowering overall spend.
    4. Build an observability loop. At minimum, collect input and output tokens, task type, first-pass rate, average attempts and fix hours for every request, bucketed by task type and by model — that’s the only way to locate which stage is burning money. Cost optimization without observability is guesswork.

    At the infrastructure level, these needs map onto a few generic product categories: a model service for unified access and routing, a container platform to host evaluation sandboxes and concurrent jobs, object storage to hold build artifacts and screenshot baselines, and logging plus monitoring and alerting to track usage and failure rates. Baidu AI Cloud has corresponding capabilities in each of these generic categories and can serve as a candidate foundation for such a pipeline, though the actual choice should still be driven by your own evaluation data.

    6. Safety boundary: sandboxing untrusted code

    Running an evaluation means executing model-generated code on your own machines. Treat every round as untrusted input:

    • Execute in an isolated container; block host network access or allow only necessary domains
    • Set limits on CPU, memory, process count and execution time to prevent infinite loops and resource exhaustion
    • Run as a non-privileged user, mount the filesystem read-only, restrict writes to a temporary directory
    • Install dependencies from fixed versions with a local cache, so no arbitrary script runs in install hooks
    • Archive all inputs, outputs and execution logs for reproducibility and audit

    7. Rollout: four steps to make evaluation routine

    1. Build the set — assemble 20–40 tasks from real projects covering L1–L5, with golden outputs and acceptance criteria defined.
    2. Build the pipeline — chain build, static checks, unit tests, render screenshots and visual comparison into a single re-runnable command, storing results in a structured store.
    3. Build the dashboard — show first-pass rate, visual score, average attempts and cost per task by model × task tier, and run regression checks on a schedule so version upgrades don’t cause silent degradation.
    4. Build the routing policy — use dashboard data to set split rules and budget alerts: downgrade simple tasks, escalate complex ones, and keep calibrating thresholds with new samples.

    8. Selection checklist

    • Do the two hard categories (visual reproduction, 3D scenes) meet a shippable bar, not just a demo bar?
    • What are the first-pass rate and average attempts, and what does that translate to as cost per task?
    • On incremental changes to your own codebase, does it respect existing conventions and keep diffs local?
    • Do outputs pass build, static checks and tests consistently, rather than needing a human to patch conditions afterward?
    • Are performance and resource constraints considered proactively (responsive breakpoints, polygon and draw-call budgets, resource disposal)?
    • Is there observability data to support routing decisions, rather than impressions from a single run?
    • Is there vendor lock-in risk — can prompts and the evaluation set be migrated at low cost?

    Conclusion: The point of evaluating these models isn’t to find a single “strongest” answer. It’s to turn evaluation into a reproducible asset: fixed tasks and criteria, automated checks, decisions based on total cost rather than unit price, and layered routing that spends the budget where it’s genuinely needed. Once that machinery runs, selection stops being a coin flip and becomes a series of data-backed regressions.