Building LLM-Powered Applications with Workflows: From Content Processing to Invoice Verification
Large language models can generate text, understand images, and extract information—but turning those capabilities into a reliable business application requires far more than a good prompt. This article walks through a practical five-layer architecture for LLM applications, using three real-world scenarios as examples: a news collection and summarization workflow, multimodal invoice recognition and field extraction, and invoice comparison with business verification. It also covers when to use prompt engineering, RAG, or fine-tuning, and the engineering practices—timeouts, retries, idempotency, prompt injection defenses, testing, and versioning—needed to move from prototype to production. Readers will learn how to structure complex AI tasks into verifiable, traceable workflow steps rather than one-shot demonstrations.
From “A Model Can Answer” to “An Application Can Deliver”
LLMs can generate text, understand images, and extract information, but these capabilities do not automatically translate into a usable business system. Real-world applications must also handle data sources, access control, task scheduling, result validation, human review, and operational monitoring.
Take news content production as an example. A model must not only generate a summary—it also needs to know where articles come from, whether they are duplicates, whether publication timing meets requirements, and whether conclusions can be traced back to the source. Or consider invoice processing: the fact that a model can read the text on an invoice does not mean it can take on financial verification responsibilities. Recognition errors, missing fields, and inconsistent amounts all require clearly defined handling paths.
The core of LLM application development, therefore, is not cramming every requirement into a single prompt, but breaking complex tasks into manageable, verifiable steps:
Input reception → Data preparation → Model processing → Rule validation → Result output → Exception handling.
The workflow fixes the business path; the model handles the steps that require semantic understanding or content generation. Only by combining the two can an application move from a one-off demo to continuous operation.
A Clear Architecture for LLM Applications
A general-purpose LLM application can be divided into five layers.
1. Interaction and Input Layer
This layer receives user questions, files, images, or tasks submitted by business systems, while performing necessary input checks.
During development, first define the allowed input types, file sizes, task volumes, and user permissions. For example, an invoice recognition app should restrict acceptable image or document formats and verify that files can be parsed correctly; a content generation app should ask users to specify audience, purpose, tone, and output length.
The clearer the input constraints, the more stable the downstream workflow. For invalid requests, return understandable error messages early rather than letting the model guess user intent.
2. Orchestration Layer
The orchestration layer manages step ordering, branching conditions, loops, and state transitions. Common node types include data extraction, model invocation, conditional judgment, list iteration, external API requests, and result aggregation.
Nodes should exchange structured data rather than natural language alone. For example, a news item can carry its title, publication time, source identifier, and body text; an invoice record can carry its type, amount, date, and field status.
For businesses with fixed paths, prefer deterministic workflows. Introduce agent-style decision-making only when a task requires dynamic tool selection or multi-step exploration—and even then, constrain its tool permissions, execution counts, and accessible resources.
3. Model Capability Layer
This layer provides text understanding, information extraction, image comprehension, and content generation. Different tasks do not necessarily need the same model.
Simple classification and field normalization can use a cheaper option that meets the requirements; complex semantic analysis, cross-document comparison, or image understanding demands stronger capability. Selection should be based on test results on representative samples, not model names or parameter counts.
4. Data and Tool Layer
This layer connects to document repositories, business APIs, object storage, and other data sources. The model should never receive unrestricted data access; instead, it should read necessary information through controlled interfaces.
External APIs should specify authentication, timeouts, response structure, and error types. For sensitive fields, configure masking, access auditing, and retention policies.
5. Governance and Operations Layer
After launch, the application must continuously record execution status, latency, failed nodes, model call volumes, and human review outcomes.
Logs should be sufficient to support troubleshooting but should not unconditionally retain complete invoices, personal information, or internal documents. The goal of governance is a system that is observable, traceable, and recoverable—not simply accumulating more logs.
Practice 1: A News Collection and Summarization Workflow
News summarization is a good scenario for understanding external data ingestion, list iteration, and result aggregation.
1. Define Collection Boundaries First
Data should come from interfaces or subscription sources you are authorized to access, or materials provided by users. “The page can be opened” does not mean “unlimited scraping and redistribution are allowed.”
Before collection, define the time window, article count, topic scope, and intended use. Internal research summaries have different requirements from publicly published content—the latter also involves citation, copyright, and fact-checking.
2. Separate List Discovery from Content Fetching
The first step fetches a candidate article list; the second fetches each article’s body. This lets you handle list errors, missing content, and individual article failures independently.
When processing the body, strip navigation, ads, and repeated paragraphs—but do not accidentally remove titles, publication times, or key quotations. For especially long articles, segment them semantically first, then extract per segment and aggregate overall.
Never rely on a short excerpt from the beginning as a proxy for the full article; otherwise, you risk missing qualifying conditions, dissenting views, or conclusions in the latter half.
3. Use an Iteration Node for Independent Items
Each article flows through the same sub-workflow:
Content check → Information extraction → Summary generation → Source linking → Status recording.
When items are independent, limited concurrency is fine, but it should be bounded by API rate limits, model call capacity, and system resources. If a single article fails, log the reason and continue with the rest, then report successes and failures together at the end.
Retries should also distinguish error types. Temporary network failures can be retried per policy; permission errors and malformed data should not trigger repeated identical requests.
4. Separate Facts from Analysis in Summaries
For each article, output the following:
- Topic and core event;
- Key facts explicitly supported by the source;
- Relevant dates and parties;
- A concise summary;
- A traceable source identifier;
- Notes on missing or uncertain information.
If trend analysis is also required, keep it separate from the factual summary. Model speculation must not be packaged as a source’s conclusion, and similar opinions across multiple articles do not automatically establish that a trend exists.
5. Deduplicate Before Aggregation
Deduplication can combine source identifiers, title similarity, and body content. Different reports on the same event can be grouped into an event cluster while preserving each individual source.
The final output should show not only summaries but also the collection scope and failure cases, so readers understand the coverage boundaries instead of assuming the summary includes everything relevant.
Practice 2: Multimodal Invoice Recognition and Field Extraction
The difficulty of invoice recognition is not just reading text clearly—it includes understanding field positions, distinguishing invoice types, and correctly handling blurry or missing information.
1. Check Image Quality First
Images may be skewed, reflective, partially occluded, low-resolution, or contain multiple invoices in one shot. Before entering the recognition pipeline, determine whether the material meets basic processing conditions.
Preprocessing such as orientation correction and region cropping can help when needed, but always retain the original file for review. Image enhancement cannot recover information that was already lost, and improved visual quality is not a guarantee of recognition accuracy.
2. Classify First, Then Extract by Type
Different invoice types have different field layouts and required fields. A safer flow is to identify the invoice type first, then apply the corresponding field template.
For materials whose type cannot be determined, route them to generic extraction or human review rather than forcing them into a template. Multi-page documents also require identifying relationships between pages so that fields from different invoices are not mixed together.
3. Enforce Structured Output Constraints
Field results should distinguish the “raw recognized value” from the “normalized value.” For example, dates can be unified in format and amounts can have display symbols removed, but the raw recognized text should be retained for traceability.
For important fields, capture:
- Raw text;
- Normalized result;
- Page number or region where the field was found;
- Status: missing, blurry, or conflicting;
- Whether human review is needed.
Unrecognizable fields should be explicitly left empty or marked unknown. Never ask the model to fill in invoice numbers, transaction amounts, or other critical facts based on context.
4. Do Not Treat Model-Reported Confidence as Reliable Probability
When a model claims to be “very confident,” it does not mean error risk has been objectively measured. Recognition quality should be evaluated against labeled test sets, with particular attention to critical fields like amounts, dates, and entity information.
If the underlying recognition engine provides confidence scores, validate their effectiveness on real business samples. Never use an unvalidated score directly as the basis for automatic approval.
Practice 3: Invoice Comparison and Business Verification
Recognition and verification should be two separate stages. The former answers “what does the document say”; the latter answers “does this information comply with the rules.”
1. Prefer Deterministic Rules
Checks such as amount calculations, date ranges, required fields, and duplicate records should be handled by rules wherever possible.
For example, some invoice types include amount, tax, and total fields—assuming the invoice type supports this rule, you can verify:
amount + tax equals the total.
Amount arithmetic should use representations suitable for exact decimal computation, and rounding should follow business rules, avoiding unnecessary discrepancies from ordinary floating-point arithmetic.
2. Models Handle Semantic Differences; Rules Define the Final Boundary
Name abbreviations and differing project descriptions may require semantic assistance. But “semantically similar” does not mean “the same legal entity”—let alone grounds for automatic reimbursement.
The system can output explanations of differences and suggested verification points, but final approval should be decided by explicit business rules or authorized personnel.
3. Design Actionable Result States
Instead of simply outputting “pass” or “fail,” more useful states include:
- Information complete and rule checks passed;
- Information missing, waiting for supplementary materials;
- Field conflicts detected, human review required;
- Material unreadable, resubmission required;
- Duplicate or other risk rules triggered, further processing paused.
Every state should have a corresponding follow-up action, so that exceptions do not become dead records nobody handles.
It is worth emphasizing: recognizing invoice content and checking field consistency is not the same as verifying invoice authenticity. When authenticity matters, rely on legally available authoritative verification channels or clearly defined business verification processes.
How to Decompose Content Generation and Digital Human Scenarios
For creator-focused applications, decompose topic selection, research, script generation, image generation, voice, and video synthesis into independent stages rather than relying on a single model call for everything.
At the script stage, establish factual grounding and audience first, then refine the expression. At the image generation stage, watch for visual requirements, text errors, and rights boundaries. At the voice and video stage, check pronunciation, subtitles, duration, and audio-video sync.
Digital human lip-sync typically requires dedicated audio/video processing capabilities—it is not something a language model produces automatically after generating text. Sync quality also depends on material quality, facial angles, occlusion, and speech rhythm. Do not claim perfectly flawless synchronization without testing.
When content involves a person’s likeness, voice, or portrait, confirm authorization and, where applicable, disclose that the content is synthetically generated to prevent identity confusion.
Choosing Between Prompts, RAG, and Fine-Tuning
These three approaches solve different problems and should not be conflated.
1. Prompt and Workflow Optimization
When the main issues are unclear task descriptions, disorganized steps, or unstable output formats, optimize prompts and the workflow first.
Clarifying inputs, outputs, fields that must never be filled in, and exception handling is usually easier to validate and maintain than training a model directly.
2. Retrieval-Augmented Generation (RAG)
When the model needs to answer based on continuously updated documents, retrieve relevant material first, then have the model generate answers grounded in that material.
Key work includes document chunking, permission filtering, retrieval quality evaluation, and source retention. Retrieving material does not guarantee a correct answer—you still need to check whether the response is faithful to the material and whether important constraints were omitted.
3. Fine-Tuning
Fine-tuning continues training an existing model on task-specific data to adjust its behavior or output style.
It suits scenarios with stable task definitions and high-quality training samples, but it cannot guarantee the model accurately memorizes all facts, nor can it replace real-time data queries or business rules. When data is scarce, labeling is messy, or tasks change frequently, rushing into fine-tuning may increase costs without improving results.
For evaluation, use test sets held out from the training data, and cover different invoice types, image qualities, and edge cases—do not judge performance on a handful of familiar samples.
From Prototype to Production: Engineering Capabilities You Must Add
1. Timeouts, Retries, and Idempotency
Every external call needs explicit timeout and failure policies. Retryable and non-retryable errors must be handled differently.
Steps that submit, write, or notify should implement idempotency mechanisms, so a single network retry does not create duplicate records or send duplicate messages.
2. Defend Against Instruction Injection in External Content
Text in web pages, files, and invoices is data to be processed—it should never automatically gain control over the workflow.
If external content contains text demanding information disclosure, rule changes, or tool calls, the system should treat it as material content, not executable instructions. Tool permissions, access scope, and output validation must be controlled at the application layer—prompt constraints alone are not enough.
3. Control Data and Deployment Boundaries
Local deployment offers more environmental control, but it does not guarantee data never leaves your environment. If the workflow still calls external models or APIs, relevant data may still cross the local boundary.
Cloud deployment requires careful management of access permissions, keys, network isolation, and storage policies. Either way, map your actual data flows: which data goes to which components, how long it is retained, and who can access it.
4. Establish Testing and Version Management
Test sets should cover normal inputs, missing fields, blurry images, overly long text, API failures, and malicious instructions.
Version-control workflow configurations, prompts, model choices, and rule changes. Run regression tests before release, monitor error distributions after release, and keep rollback capability.
Judge Value with Business Metrics
Evaluating an LLM application should never stop at “does the answer sound fluent.” More valuable metrics include task completion rate, critical field accuracy, human review ratio, average processing time, and cost per successful task.
Content production scenarios should also track factual errors, editor revision volume, and pre-publish review costs; invoice scenarios should focus on critical field errors, missed exceptions, and the burden of manual handling.
Any claimed efficiency gains should cover the entire process—collection, recognition, validation, correction, and maintenance. Do not quote specific multiples or percentages without measurement in real business conditions.
Conclusion
The reliability of LLM applications comes from the combined effect of model capability and engineering constraints. Models handle understanding and generation; workflows organize the steps; rules make deterministic judgments; human review handles high-risk and uncertain cases.
For teams deploying for the first time, start with a small scenario that has clear boundaries, controllable inputs, and verifiable outputs. Build complete exception handling and evaluation mechanisms, then gradually expand the task scope. A truly valuable application is not one that can demo many capabilities—it is one that, under well-defined business conditions, continuously produces traceable, reviewable, and maintainable results.
