LLM Application Development in Practice: Framework and Model Collaboration

    This article explains how to build production LLM applications by separating the application orchestration framework from the foundation model. It covers the core design principles, how to move from a single model call to composable chains, data augmentation with prompt templates and structured output parsers, retrieval-augmented generation with a focus on chunking and recall quality, multi-model integration, and a practical rollout path from scenario selection to evaluation and launch.

    1. Why You Need a Two-Layer Structure: Framework Plus Model

    The core challenge in LLM application development is the gap between the uncertainty of model capabilities and the business demand for deterministic output. Calling a model API alone usually only gets you a single question-and-answer exchange. Real applications need context management, external knowledge access, tool calling, result validation, and service exposure. In engineering practice, the system is typically split into two layers: an upper application orchestration framework that handles chain organization, state management, and observability; and a lower foundation model that handles semantic understanding and generation. Once the two layers are decoupled, the model can be swapped or upgraded while the business chain stays stable.

    Three principles are recommended when making technology choices. First, prioritize interface abstraction and avoid scattering model-specific parameters across business code. Second, make the chain observable, so the input and output of every step can be traced. Third, make failures recoverable, with timeouts, retries, and fallback strategies for any external dependency.

    2. Core Building Blocks: From a Single Call to a Chain

    A minimal working program usually has only three steps: construct a client, organize messages, and parse the response. After engineering hardening, these three steps need to be abstracted into reusable components.

    1. # Illustrative code: structure only, not tied to any specific product
    2. from app_framework import ChatModel, PromptTemplate, StrOutputParser
    3. model = ChatModel(model_name="your-model", temperature=0.2)
    4. prompt = PromptTemplate.from_template("You are a rigorous technical assistant. Answer: {question}")
    5. chain = prompt | model | StrOutputParser()
    6. print(chain.invoke({"question": "How can we reduce hallucination in retrieval-augmented generation?"}))

    The value of a chain lies in composability. Common patterns include a single-turn generation chain, a retrieval chain (fetch knowledge first, then generate), a conversational retrieval chain (rewrite the question using history, then retrieve), and an agent-style chain (the model decides which tool to call). When designing, start with the simplest chain to get an end-to-end flow working, then gradually add retrieval and tools. Avoid introducing too many abstractions at the very beginning.

    3. Data Augmentation: Making the Model Speak in the Right Format

    The data augmentation layer solves two problems: how to organize the input and how to constrain the output.

    • Prompt templates: parameterize the variable parts and fix the role setting and constraint clauses, reducing drift caused by repeated string concatenation.
    • Chat templates and message lists: separate system instructions, conversation history, and the current input to make multi-turn context management easier.
    • Dynamic insertion: inject context such as time, permissions, and tenant based on the scenario, avoiding hardcoding sensitive information into templates.
    • Example selection: retrieve a small number of examples most similar to the current question from the knowledge base to form in-context examples, which are more stable than fixed examples.

    On the output side, it is recommended to introduce a parser that converts free text into structured objects and performs repair-style retries on failure:

    1. from app_framework import JsonOutputParser, PydanticModel
    2. class Answer(PydanticModel):
    3. conclusion: str
    4. evidence: list[str]
    5. confidence: float
    6. parser = JsonOutputParser(pydantic_object=Answer)
    7. # On parse failure, feed the error back to the model and require valid JSON only

    The benefit of structured output is more than cosmetic: it lets downstream systems directly validate, store, and alert on results, and it makes evaluation metrics computable.

    4. Retrieval-Augmented Generation: Putting Knowledge in a Controllable Place

    The key to retrieval-augmented generation is not “vectors” but “chunking and recall quality.” Practical points include: split documents along semantic boundaries while preserving heading hierarchy; attach metadata (source, time, permissions) to each chunk; rerank and remove redundancy after recall; write citation numbers into the prompt and require the model to annotate its basis item by item. For evaluation, look at both recall hit rate and answer faithfulness, rather than only answer fluency.

    5. Model Composition and Integration

    Complex tasks often require division of labor across multiple models: small models for classification and extraction, large models for综合 reasoning; or embedding models for retrieval and generation models for summarization. The integration layer should unify timeouts, rate limiting, retries, and cost accounting, and set quality baselines for different capabilities. When exposing services externally, wrap the chain as an API service, and pair it with logging and monitoring alerts to form a closed loop for continuous iteration.

    6. Recommendations for Project Delivery

    The recommended path is “scenario, data, evaluation, launch”: first pick a high-frequency, verifiable scenario; then prepare a small-scale, high-quality corpus; build an evaluation set covering accuracy, faithfulness, and latency; and finally roll out gradually while continuously feeding back bad cases. For team configuration, the engineering side owns the chain and stability, the product side owns the scenario and acceptance criteria, and both jointly maintain the prompt and evaluation assets.