Multimodal LLMs in Practice: UI Replication and Long Document Information Processing
As daily workflows increasingly rely on multimodal capabilities, engineering teams face challenges in managing diverse inputs like screenshots, long PDFs, and videos, as well as mitigating risks when switching models. This article explores practical, model-agnostic techniques for implementing multimodal large language models. It covers task decomposition and evaluation dimensions, followed by specific scenarios including UI replication to frontend code, image information extraction, long document and academic material analysis, long-form writing, and video understanding. Finally, it discusses strategies for cost control and model fallback to ensure workflow stability.
I. Background and Problem Definition
More daily workflows now depend on multimodal capabilities. A single workflow often includes interface screenshots, scanned documents, charts, long PDFs, and screen recordings. Different input formats require different model capabilities: UI replication requires accurate layout perception, long documents need stable context tracking, and videos require temporal understanding.
When API quotas tighten or free tiers decrease, workflows relying on a single model can be entirely disrupted. From an engineering perspective, two questions must be answered. First, which steps must rely on multimodal capabilities, and which can be replaced with rules or traditional tools? Second, when available models change, how can workflows switch smoothly without rewriting business code?
This article discusses only general technical approaches and does not judge the performance of any specific model. The practices described apply to any model service offering image, text, or video input capabilities.
II. Task Decomposition and Evaluation Dimensions
Breaking down multimodal requirements into verifiable subtasks is the first step in implementation. It is recommended to describe each task across four dimensions:
- Input format: Single image, continuous screenshots, long text, or video clips.
- Output constraints: Free text, structured JSON, or directly executable code.
- Correctness criteria: Whether it can be verified through rendering comparison, field comparison, or manual sampling.
- Fault tolerance cost: How expensive it is to fix an output error.
For UI replication, errors are often immediately exposed during browser rendering, resulting in a low fault tolerance cost. In ticket amount extraction, a single digit error can cause actual financial loss, requiring stricter validation and manual review. The clearer the decomposition, the easier it is to select appropriate models and validation methods for each subtask.
III. Scenario 1: UI Screenshots to Frontend Code
3.1 Layout Structure Recognition
Prompts should require the model to describe the hierarchical structure before outputting code. A common approach is to have the model list the structure in the order of “page regions, modules, elements,” such as top navigation, waterfall cards, and bottom action bars. Completing the structure description first usually reduces hierarchical errors in the generated code and facilitates manual verification.
3.2 Style Restoration
The focus of style restoration is colors, spacing, border-radius, font sizes, and shadows. It is recommended to require the model to centralize color and spacing definitions as CSS variables for easy subsequent adjustment. Example:
:root {--color-primary: #3b82f6;--color-text: #333333;--radius-card: 8px;--gap-grid: 12px;}.card {border-radius: var(--radius-card);margin-bottom: var(--gap-grid);}
3.3 Image Placeholder and Asset Filling
Images in screenshots usually cannot be directly reused due to copyright and clarity issues. Three common approaches exist: using placeholder elements with fixed dimensions; retrieving images from compliant stock libraries based on content themes; or retaining the position information of the original image areas for manual replacement.
When searching for assets by theme, two points require attention: the licensing scope of the assets and the generation method of search keywords. You can have the model generate search keywords for each card first, pass them to an asset service for querying, and finally backfill the results into the src and alt attributes of the image tags. When concatenating HTML, all external fields must be escaped to prevent cross-site scripting (XSS) issues.
const cards = [{ id: 1, topic: "autumn outfit", keyword: "autumn outfit" },{ id: 2, topic: "home organization", keyword: "home organization" },];function escapeHtml(value) {return String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);}function renderCard(card, imageUrl) {return `<article class="card" data-id="${escapeHtml(card.id)}"><img src="${escapeHtml(imageUrl)}"alt="${escapeHtml(card.keyword)}"loading="lazy" /><p class="title">${escapeHtml(card.topic)}</p></article>`;}
3.4 Interaction Replication
The interaction part includes clicking into details, toggling likes and favorites, displaying comment lists, dragging video progress bars, etc. During implementation, it is recommended to store interface states in a centralized object and drive rendering via state. This prevents multiple event handlers from modifying the DOM independently, thereby reducing state inconsistency issues.
const state = {liked: false,likeCount: 0,currentPostId: null,};function toggleLike() {state.liked = !state.liked;state.likeCount += state.liked ? 1 : -1;render();}function render() {// Update button text and count based on state}
3.5 Multi-round Iterative Modification
The key to multi-round modifications is controlling the scope of changes. Each request should include the code from the previous round, clearly specify the files and components to be modified, and require the model to return only the changed parts. After each round, render it in the browser and check against the requirements list item by item. This prevents the model from silently breaking another part while fixing one.
IV. Scenario 2: Image Information Extraction
Information extraction is suitable for structured outputs. Provide field definitions in the prompt and require the model to return in JSON format for direct programmatic parsing and validation. Example structure:
{"document_type": "string","fields": [{"name": "string","value": "string","confidence": "high | medium | low"}],"uncertain_regions": ["string"]}
Requiring the model to label confidence levels for uncertain fields and list unrecognizable regions is more reliable than directly asking for “all information.” For key fields like amounts, dates, and numbers, you can use rules for format validation or cross-check with dedicated OCR results. Low-confidence fields should enter a manual review queue rather than being directly committed to the database.
V. Scenario 3: Long Document and Academic Material Analysis
When a long document exceeds the capacity of a single input, segmented processing is required. When segmenting, retain a certain overlap area; otherwise, cross-paragraph arguments can easily be cut off. Below is a basic chunking function:
def chunk_text(text: str, max_chars: int = 4000, overlap: int = 400) -> list[str]:if overlap >= max_chars:raise ValueError("overlap must be less than max_chars")chunks = []start = 0while start < len(text):end = min(start + max_chars, len(text))chunks.append(text[start:end])if end == len(text):breakstart = end - overlapreturn chunks
After segmentation, a “local first, then summary” workflow is typically adopted. Extract key points from each segment first, recording the page number or chapter number, and finally merge and deduplicate in the summary step. Conclusions drawn this way can be traced back to their original locations.
For academic materials, analysis can be fixed into several fields: research question, method, data source, main conclusion, and limitations. Comparing multiple papers is best done using a unified table. Numerical values in the table must be verified against the original tables in the text, not just relying on the model’s paraphrasing.
VI. Scenario 4: Long-form Writing with Images
The quality of long-form writing depends on upfront structural design. The recommended workflow is to generate an outline first, write section by section, and finally unify the polishing. Prompts for each section should include a fact list and style constraints, such as reader level, glossary, and prohibited expressions.
The purpose of the fact list is to prevent fabrication. Before writing, compile all data, dates, and definitions that need to be referenced into a list; the model can only expand its arguments based on this list. For content involving numbers, verify the source one by one after the draft is completed.
VII. Scenario 5: Video Understanding
Video understanding usually involves frame extraction first, followed by combining speech-to-text and frame descriptions to generate a timeline. Frame extraction strategies can be divided into two categories. One is fixed-interval sampling, which is simple to implement and suitable for content with slow visual changes. The other is scene-change-based sampling, which adds sample points at abrupt visual transitions, suitable for heavily edited videos.
def sample_timestamps(duration_s: float, interval_s: float) -> list[float]:if interval_s <= 0:raise ValueError("interval_s must be greater than 0")timestamps = []t = 0.0while t < duration_s:timestamps.append(round(t, 2))t += interval_sreturn timestamps
Each sampled frame should carry a timestamp. Only after aligning the description results with speech-to-text by time can a searchable timeline be generated. For long videos, chapter-level summaries can be generated first, followed by frame-by-frame analysis for chapters requiring detailed review, to control input size.
VIII. Cost Control and Model Fallback
The cost of multimodal calls primarily comes from input volume. Common methods to reduce costs include:
- Tiering by task complexity: assigning simple classification and extraction to smaller models, and only invoking large models for complex reasoning.
- Calculating a hash of input content as a cache key: returning historical results directly for identical inputs.
- Compressing image resolution: removing areas irrelevant to the task.
- Merging multiple small tasks into a single request: reducing fixed overhead.
When the primary model is unavailable due to quotas or rate limiting, the workflow should automatically switch to alternative models.
