LLM Application Development: Orchestration Frameworks and RAG Practices

    As Large Language Models (LLMs) mature, the focus of application development has shifted from basic API interactions to building maintainable, scalable, and observable systems. This article explores core abstractions, key processes, and engineering practices in LLM application development. It covers layered architecture, prompt management, structured output parsing, Retrieval-Augmented Generation (RAG), and multi-model routing, providing insights into transforming prototype capabilities into stable production systems.

    LLM Application Development: Orchestration Frameworks and RAG Practices

    As the capabilities of large language models (LLMs) mature, the focus of application development has shifted from “whether we can call the model” to “how to build a maintainable, scalable, and observable complete system.” A typical LLM application usually involves model access, prompt organization, context augmentation, output validation, business workflow orchestration, and service deployment. This article discusses core abstractions, key processes, and engineering practices in LLM application development based on general technical solutions, using pseudocode to illustrate how to translate prototype capabilities into stable systems.

    1. From Single Calls to Application Engineering

    Early LLM applications often relied on simple request-response calls: developers concatenated user questions into text, sent it to an inference service, and displayed the response directly to the user. While this approach is suitable for validating feasibility, it encounters numerous issues in real business scenarios, such as difficulties in prompt maintenance, unstable outputs, insufficient context, high costs of switching models, and hard-to-trace errors.

    Therefore, application engineering requires a layered design. The first layer is the model access layer, responsible for unifying message protocols, timeouts, retries, authentication, and streaming returns across different inference services. The second layer is the orchestration layer, handling prompt templates, example selection, output parsing, retrieval augmentation, and multi-model routing. The third layer is the business layer, managing workflows, permissions, auditing, and user interactions for specific scenarios. The fourth layer is the operations layer, responsible for logging, metrics, tracing, evaluation, and cost control. With this layered architecture, model calls are no longer scattered across business code; prompt and parsing logic can be reused, and replacing models or adjusting strategies does not require extensive modifications.

    For example, the model client can first be abstracted into a unified interface:

    1. class ChatClient:
    2. def __init__(self, endpoint: str, token: str):
    3. self.endpoint = endpoint
    4. self.token = token
    5. def chat(self, messages, stream=False):
    6. # Call inference services compatible with universal message protocols
    7. # Unify handling of auth, timeout, retry, and exceptions
    8. ...

    Business code depends only on the chat method, without caring about specific service details. This makes testing easier and facilitates canary releases and fallback strategies across different models.

    2. Core Abstractions: Prompt Templates, Chat Models, and Example Selection

    Prompt templates are the most fundamental reusable units in application development. They split system instructions, user questions, context, and output format requirements into configurable fields, preventing strings from being scattered throughout the code. A good prompt template should clearly define the role, task boundaries, input structure, and failure handling methods. For example:

    1. SYSTEM = "You are a rigorous technical assistant, answering only based on the given context."
    2. USER = "Question: {question}\nContext:\n{context}\nPlease provide the conclusion and the basis."
    3. def build_prompt(question, context):
    4. return [
    5. {"role": "system", "content": SYSTEM},
    6. {"role": "user", "content": USER.format(question=question, context=context)}
    7. ]

    Chat model interfaces typically accept a list of messages as input, including system, user, and assistant messages. Compared to plain text concatenation, the message structure makes it easier to distinguish instructions from content and manage multi-turn conversations. In practice, the length of historical messages should be limited, retaining recent turns and key summaries to prevent unlimited context growth.

    Example selectors are used to pick a small number of samples most relevant to the current question from an example library, placing them in the prompt to guide the model’s output. Examples should not be too many, as they will occupy context and increase costs; nor should they be entirely static, as they would fail to cover long-tail questions. A common practice is to first use an embedding model to calculate the similarity between the question and the examples, and then filter them based on business tags, difficulty, and output format. The example selector should also support version management to ensure synchronized evolution of prompts, examples, and evaluation sets.

    3. Output Parsing and Structured Contracts

    LLM outputs are probabilistic. If natural language results are handed directly to downstream systems, it easily leads to missing fields, format drift, and unexplainable issues. The value of an output parser lies in establishing a “structured contract”: requiring the model to return in an agreed format and performing retries, repairs, or fallbacks when parsing fails.

    For instance, you can require the model to output a JSON object containing the answer, citations, and confidence, and implement robust handling at the parsing layer:

    1. import json
    2. def parse_structured(text: str) -> dict:
    3. try:
    4. data = json.loads(text)
    5. except json.JSONDecodeError:
    6. start = text.find("{")
    7. end = text.rfind("}")
    8. if start == -1 or end == -1:
    9. raise ValueError("Output does not contain a parseable JSON object")
    10. data = json.loads(text[start:end + 1])
    11. required = {"answer", "citations", "confidence"}
    12. missing = required - data.keys()
    13. if missing:
    14. raise ValueError(f"Missing fields: {missing}")
    15. return data

    The parser does more than just “extract JSON”; it also assumes responsibilities for validation, normalization, and error classification. For critical business operations, you can add field type validation, enum checks, and citation validity checks; for parsing failures, you can trigger a “format repair prompt” or fall back to a more conservative rules engine. Structured output does not guarantee the model is correct, but it makes errors easier to detect and intercept.

    4. Retrieval-Augmented Generation: Grounding Answers in Data

    Retrieval-Augmented Generation (RAG) uses an external knowledge base to compensate for the limitations of the model’s parametric knowledge. A typical workflow includes document parsing, chunking, embedding, indexing, retrieval, re-ranking, context concatenation, and answer generation. From an engineering perspective, three areas require special attention: chunking strategy, retrieval quality, and citation traceability.

    Chunking too coarsely introduces irrelevant content, while chunking too finely loses semantic completeness. You can combine splitting based on heading hierarchy, paragraphs, and semantic boundaries, preserving metadata such as source, chapter, and time for each chunk. During retrieval, vector search can first be used to obtain a candidate set, followed by keyword matching or re-ranking models to improve relevance. When concatenating context, it is crucial to control the token budget, prioritize highly relevant chunks, and require the model to annotate citation numbers in the answer.

    1. def rag_answer(question: str, retriever, llm, parser):
    2. docs = retriever.search(question, top_k=5)
    3. context = "\n\n".join(
    4. f"[{i + 1}] {d.text}" for i, d in enumerate(docs)
    5. )
    6. messages = build_prompt(question, context)
    7. raw = llm.chat(messages)
    8. result = parser.parse(raw)
    9. result["citations"] = [d.id for d in docs]
    10. return result

    Evaluating RAG should not solely look at the final answer; it must separately assess retrieval hit rate, context relevance, answer faithfulness, and citation accuracy. If the correct documents cannot be retrieved, even the most powerful generative model cannot answer stably; if the context contains conflicting information, the model may produce mixed errors. Therefore, knowledge base governance, version updates, and expired document cleanup should be synchronized with application iteration.

    5. Model Composition, Routing, and Agent Workflows

    A single model is not suitable for all tasks. Common approaches to model composition include: using small models for classification and rewriting, and large models for complex reasoning; using specialized models for embedding and re-ranking, and general models for final generation; using rule engines for deterministic logic, and models for open semantics. Multi-model routing can select different models based on task type, input length, cost budget, and latency requirements, setting up fallback strategies for failures.

    Agent workflows transform model outputs into executable steps, such as querying retrievers, calling business functions, validating results, and generating final responses. In engineering, agents should not be allowed to loop autonomously without limits; instead, maximum steps, tool whitelists, parameter validation, and human confirmation points should be established. Tool call results must be backfilled into the context, and the call chain should be recorded for auditing and issue tracing.

    6. Project Implementation and Engineering Best Practices

    In scenarios such as natural language processing, information retrieval, and intelligent Q&A, project implementation usually follows the path of “evaluation sets first, rapid prototyping, gradual enhancement.” First, establish an evaluation set covering typical and edge-case questions. Then, build a minimal closed loop using a unified model client and prompt templates. Gradually incorporate example selection, structured output, RAG, and multi-model routing. Finally, complete the implementation with logging, metrics, tracing, and canary releases.

    When deploying on Baidu AI Cloud, you can use object storage for document archiving, logging services for call chain auditing, and monitoring alerts for quality and latency observation. These are general cloud product categories, and specific interfaces should be based on the relevant API documentation of your actual environment. The application side should record request IDs, model versions, prompt versions, retrieved chunks, parsing results, and execution time to form a traceable call chain. For high-risk scenarios, sensitive information filtering, permission validation, and manual review should also be included.

    7. Conclusion

    LLM application development is not merely about making API calls; it is about building a maintainable engineering ecosystem around model capabilities. Unified model access reduces coupling, prompt templates and example selection enhance controllability, output parsing establishes structured contracts, RAG grounds answers in data, and model composition with workflow orchestration expands capability boundaries, while observability and evaluation ensure the system’s continuous evolution. By mastering these general methods, developers can more robustly transform LLM capabilities into real business value.