Engineering LLM Applications: Workflows, Agents, and Knowledge Retrieval
LLM applications move quickly from prototype to production challenges. This article outlines a layered architecture for building production-grade LLM applications, covering workflow and conversational flow design, agent runtime boundaries, retrieval-augmented generation (RAG) data pipelines, versioning, observability, and evaluation loops, with practical guidance on how to scale from a minimal closed loop to higher levels of autonomy.
From Model Calls to Full Application Engineering
Calling an LLM API is a fast way to validate ideas, but moving from a demo to a production system requires solving a series of engineering problems: how to keep external knowledge up to date, how to decompose complex tasks, how to authorize tool calls, how to maintain state across multi-turn conversations, and how to pinpoint the responsible component when something goes wrong.
The focus of building LLM applications should therefore shift from “wiring up a model” to “building a governable runtime system.” The model handles language understanding, content generation, and part of the reasoning; the application system handles data access, process constraints, execution permissions, and result validation. These responsibilities must not be conflated: the fact that a model generates a suggested operation does not mean the system has verified that the operation is safe, nor that it has actually been executed.
A common architectural approach combines backend-as-a-service with LLM application operations. The former packages common backend capabilities—data storage, authentication, API calls—as services; the latter covers lifecycle management of prompts, model configurations, knowledge indexes, execution chains, evaluation, and deployment. The value is not eliminating backend development, but reducing duplicated work so developers can focus on business rules and quality control.
Layered Architecture: Avoiding Blurred Capability Boundaries
For enterprise applications, responsibilities can be divided into five layers.
1. Access Layer: Unified Input and Identity Context
The access layer receives user messages, files, or requests from business systems, performing authentication, rate limiting, and input format validation, while carrying necessary tenant, user, role, and session information.
It is critical to distinguish between “what the user submitted” and “what permissions the system grants.” A user must not be able to read data or invoke sensitive tools simply by claiming a permission in natural language. Authorization should come from a trusted identity and permission system.
2. Orchestration Layer: Defining How Tasks Progress
The orchestration layer organizes input processing, knowledge retrieval, model inference, conditional branching, and tool calls, while maintaining execution state. For tasks with clear rules, prefer explicit workflows; for tasks with uncertain paths, introduce agent-driven decisions locally.
The orchestration layer must also define timeouts, retries, cancellations, and exception exits. A flowchart showing only the happy path does not represent a complete production flow.
3. Capability Layer: Encapsulating Model, Tool, and Knowledge Access
Model calls, business queries, document retrieval, and external operations should be exposed to the orchestration layer through stable capability interfaces. Interfaces must define input structures, output structures, error types, and permission requirements, rather than exposing arbitrary low-level operations.
Tool extension mechanisms especially need execution isolation, credential management, and auditing. The richer the extension capabilities, the more important it is not to conflate “can be called” with “allowed to be called in the current scenario.”
4. Data Layer: Managing State and Knowledge Assets
The data layer typically holds conversation state, task records, knowledge documents, indexes, and business data. Different data types have different retention periods and access scopes, and should be governed separately.
For example, conversation content may contain personal information, knowledge indexes may carry internal policies, and tool execution records may involve business vouchers. Storing everything together does not mean a single access policy applies to all of it.
5. Governance Layer: Spanning the Entire Lifecycle
The governance layer handles version management, runtime observability, quality evaluation, cost tracking, and security auditing. It should not be bolted on after launch—it should be established at the architecture design stage.
Workflows and Conversation Flows: Process Determinism vs. Session Continuity
A workflow describes the execution structure of a task; a conversation flow adds multi-turn interaction and session state management on top. Both can reuse the underlying capabilities, but they should not be treated as the same process with different UIs.
1. Understanding Workflows Through Six Node Responsibilities
Node classifications vary across implementations. For design purposes, common responsibilities can be grouped into six categories rather than treated as a fixed product standard:
- Input nodes: receive user text, files, structured parameters, or upstream events, and validate required fields and formats.
- Processing nodes: perform text cleaning, data transformation, variable concatenation, or deterministic computation, reducing unnecessary model calls.
- Retrieval nodes: fetch evidence from authorized knowledge scopes, returning content along with source information.
- Model nodes: handle understanding, generation, classification, or information extraction, with structural and business validation of outputs.
- Control nodes: organize conditional branching, loops, parallelism, and exception handling, constraining how the flow progresses.
- Tool and output nodes: invoke business capabilities, or return final results to users and downstream systems.
The core value of this classification is clear accountability at each step. For example, the model generates the query intent, deterministic logic checks whether the query conditions are valid, and the tool actually executes the query.
2. Conversation Flows Must Handle State Invalidation
The common problem in multi-turn interaction is not “forgetting”—it is “remembering the wrong information.” If a user changes a date, target, or task goal and the old state is not invalidated, the system may continue executing an outdated task.
It is advisable to split state into:
- Conversation history: for understanding the current dialogue context;
- Task state: records confirmed parameters, current steps, and pending information;
- Long-term memory: stores authorized information with lasting value.
For sensitive pending operations, do not rely on vague consent buried in conversation history. The system should display the exact operation target and key parameters before execution and obtain explicit confirmation at that moment.
Agent Runtimes: Autonomy Requires Boundaries
Agents can choose their next action based on the task and execution feedback, but this flexibility introduces risks such as path uncertainty, repeated calls, and privilege escalation.
1. Separate Planning from Execution
The model can propose an action plan, but the runtime should independently verify tool names, parameter structures, call permissions, and resource budgets. After a tool returns its result, the model decides whether to continue—rather than the model having unconstrained access to the execution environment.
For operations with external side effects, such as writes, deletions, or sending notifications, add human confirmation, approval workflows, or compensation mechanisms based on risk level.
2. Control Iterations and Context Budgets
Agent runs should enforce maximum step counts, total execution time, tool call limits, and context budgets. These limits prevent infinite loops and runaway resource consumption; they do not guarantee reasoning quality.
Token counting can help manage input length and call costs, but actual counts depend on the model’s tokenization. In practice, prefer usage information returned by the model itself; local estimation is suitable as a pre-check, not as a basis for precise billing.
3. Memory Needs Sources and Validity Periods
Long-term memory should not automatically absorb all conversation content. For information that needs to be saved, record its source, confirmation status, update time, and scope of applicability, and provide mechanisms for modification and deletion.
In particular, authorization details, identity attributes, and business conclusions should never become trusted facts simply because the model summarized them.
Retrieval-Augmented Generation: Govern the Knowledge First, Then Optimize the Answers
Retrieval-augmented generation (RAG) retrieves relevant evidence from external knowledge and has the model organize its answer based on that evidence. It improves knowledge freshness and traceability, but does not automatically eliminate errors.
A complete data pipeline should cover extraction, cleaning, chunking, indexing, retrieval testing, and continuous updating.
1. Extraction and Cleaning: Preserve Document Semantic Structure
Files, websites, online documents, and cloud-drive materials have different structures and update patterns. During extraction, preserve heading hierarchies, table relationships, section numbering, and source identifiers wherever possible.
Cleaning can remove duplicate headers, meaningless navigation, and formatting noise, but must not accidentally delete key fields such as version numbers, effective dates, or applicable scopes. For documents with poor recognition quality, set up sampling checks or manual review rather than indexing them directly.
2. Chunking: Balance Retrieval Granularity and Contextual Completeness
Fixed-length chunking is easy to implement but may cut off relationships between definitions, conditions, and exceptions. A more robust approach organizes content around paragraphs, headings, and semantic boundaries, then controls chunk length and necessary overlap.
Parent-child chunking uses smaller child chunks for precise localization, then returns the corresponding larger parent chunk for added context. The trade-off is a longer context, so return ranges must be controlled to avoid feeding large amounts of irrelevant content into the model.
There is no universally optimal chunk size. Evaluate different strategies against real questions rather than setting parameters based on experience alone.
3. Hybrid Retrieval and Reranking: Combining Exact Matching with Semantic Relevance
Term-based retrieval excels at locating terminology, identifiers, and exact expressions; vector retrieval handles semantically similar but differently worded questions better. Hybrid retrieval can combine both, but the fusion method needs evaluation—simply adding uncalibrated scores will not work.
Reranking further assesses how relevant candidate passages are to the question. It improves candidate ordering but cannot recover documents entirely missed by initial retrieval, so pay attention to both the recall and ranking stages.
4. Permission Filtering Must Cover the Entire Retrieval Chain
Knowledge permissions should remain consistent across candidate recall, context assembly, and citation output. Relying only on instructing the model “not to leak sensitive information” at the final answer stage is not reliable isolation.
Document updates and deletions must also be synchronized to the index. For important knowledge, keep versions and effective dates to prevent the system from citing outdated policies.
Reusable Data Pipelines Reduce Maintenance Costs
Knowledge ingestion should not be a one-time bulk upload, but a repeatable processing flow:
Data source ingestion → content extraction → quality checks → chunking → index building → retrieval testing → publishing.
Each stage should record input versions, processing rules, and failure reasons. For incremental updates, identify changes using source identifiers, update timestamps, or content fingerprints to avoid reprocessing unchanged content.
When processing steps change—such as modifying chunking rules or adjusting the indexing approach—determine whether the index needs rebuilding. Before switching from old to new indexes, verify data completeness, permission consistency, and performance on representative questions, avoiding a situation where “the task ran successfully” but “the knowledge is unusable.”
Versioning and Observability: Making Problems Reproducible
A single application release usually involves workflow definitions, prompts, model configurations, tool contracts, and knowledge versions. Managing only the workflow diagram is not enough to reproduce historical behavior.
Build these dependencies into traceable release snapshots, and associate each request with the corresponding versions. When rolling back, check compatibility as well: an old workflow may not handle new tool outputs, and old prompts may not suit new knowledge structures.
Runtime observability should cover:
- Execution time and status of each node;
- Retrieval queries, candidate sources, and filtering results;
- Model call usage and output validation results;
- Tool call parameter summaries, authorization results, and error types;
- Evidence cited in final answers and release versions.
Logs must be sanitized with controlled access. Fully retaining all prompts, documents, and credentials for troubleshooting purposes introduces new security risks.
Build an Evaluation Loop, Not Just a Fluency Check
Quality evaluation should analyze retrieval, generation, and tool execution separately.
Retrieval evaluation checks whether key evidence enters the candidate set; generation evaluation checks whether answers are faithful to the evidence and correctly express uncertainty; tool evaluation checks whether parameters are correct, operations stay within authorized scope, and failures are handled properly.
Test sets should include common questions, ambiguous questions, unanswerable questions, conflicting documents, outdated knowledge, permission-restricted requests, and malicious instructions. When knowledge is insufficient, the system should allow clarification, refusal to answer, or handoff to a human—rather than forcing a seemingly complete conclusion.
After launch, continuously collect failure cases and determine whether the cause is missing data, retrieval drift, prompt issues, or incomplete business rules. Only by pinpointing the specific component can optimization be verifiable.
Practical Advice: Expand from a Minimal Closed Loop
Start with a well-bounded knowledge Q&A scenario. First establish a complete closed loop of authorized access, knowledge processing, retrieval, evidence-based answering, and log tracing, then add multi-turn clarification and read-only tools.
Once read-only capabilities are stable, evaluate whether to introduce write operations and more autonomous agents. Each new capability should come with corresponding additions to the permission model, exception handling, evaluation cases, and rollback plans.
The key to engineering LLM applications is not making the model handle all decisions, but assigning deterministic parts to rules and systems while leaving language understanding and reasoning to the model. Clear separation of responsibilities, reliable knowledge pipelines, and continuous quality governance are the foundation of a long-term maintainable application.
