Building a Knowledge System for LLM Application Development from Scratch
This article presents a practical, four-layer framework for learning large language model application development: model interaction and prompt engineering, knowledge supply with RAG, task orchestration with agents, and engineering governance. It explains how to design structured prompts with validation and fallback, build a retrieval pipeline with hybrid search and citations, control agent loops with clear termination conditions, and evaluate cost, latency, and safety. A four-week practice roadmap shows how to turn a demo into an application that can be tested, optimized, and scaled.
1. Why You Need an Executable Learning Path
The knowledge involved in LLM application development looks vast, but what usually determines whether a project succeeds is not the model itself. It is the engineering system built around the model. Many beginners chase new models and new frameworks right away, and end up with a prototype that can be demonstrated but not deployed. A more reliable approach is to break the capabilities into four layers: model interaction, knowledge supply, task orchestration, and engineering governance. Each layer has clear goals and acceptance criteria. Progressing layer by layer helps you avoid the awkward situation of being able to call an API but unable to build a product.
A practical test is that any feature should answer three questions: what is the input, what are the constraints, and how does it fall back when it fails. If you cannot answer them, the design is not finished.
2. Layer 1: Model Interaction and Prompt Engineering
A prompt is not a magic spell. It is a specification of the task. A well-structured prompt usually includes a role definition, the task goal, input data, constraints, the output format, and examples.
Role: You are a rigorous data analysis assistantTask: Extract fields from the given text and output JSONConstraints: Use only information in the text; fill missing fields with null; do not inferOutput: {"name": string, "amount": number|null, "date": string|null}Example: input -> output
In engineering, it is more worthwhile to invest in structured output plus validation. After the model returns JSON, use schema validation to check field types and required fields. If validation fails, retry once with the error message. If it still fails, fall back to rule-based parsing or human review. For extraction tasks, a lower temperature usually improves stability. For creative tasks, you can raise it, but stronger post-processing is then needed.
The context window is a limited resource and should be managed like memory. Keep system instructions permanently resident, retrieve long-term memory on demand, and keep only the most recent turns of short-term dialogue while summarizing and compressing earlier content.
3. Layer 2: Knowledge Supply and Retrieval-Augmented Generation (RAG)
The value of RAG is to replace parametric memory with external knowledge that can be updated and traced. The standard pipeline is: document parsing -> chunking -> vectorization -> indexing -> retrieval -> reranking -> generation -> citation.
Chunking strategy directly affects quality. Splitting by semantic paragraphs usually works better than cutting at a fixed character count. Keeping the heading path and a small overlap in each chunk can significantly reduce lost references. On the retrieval side, run vector recall and keyword recall in parallel, then use a reranking model to rank the candidates precisely and send only the top few into the context.
def build_context(query, k=5):candidates = vector_search(query, top_k=20) + keyword_search(query, top_k=20)reranked = rerank(query, dedup(candidates))[:k]return "\n\n".join(f"[{i+1}] {c.text}" for i, c in enumerate(reranked))
You must require the model to provide citation numbers for each item and to explicitly reply that the information is not mentioned in the materials when there is no answer. This is one of the most effective and lowest-cost ways to suppress hallucination.
4. Layer 3: Task Orchestration and Agents
Introduce an agent only when a task requires multi-step reasoning or calls to external capabilities. The three core elements are the toolset, loop control, and termination conditions.
- Design tools to be narrow and clear. One tool does one thing, parameters are described with strong types, and error messages are readable so the model can correct itself.
- Set limits on loop control (maximum steps, maximum elapsed time, maximum cost) to prevent infinite calls.
- Make termination conditions decidable: task completed, budget exhausted, or consecutive failures reaching a threshold. Exit on any one of them and output the current progress.
Multi-agent collaboration suits scenarios with clear responsibility boundaries, such as a retriever, a calculator, and a reviewer, completing a closed loop through message passing and result aggregation. But watch out for context expansion and diffused responsibility. If a single agent with tools can solve the problem, do not split it up blindly.
5. Layer 4: Engineering Governance (Evaluation, Cost, and Safety)
Optimization without evaluation is guesswork. Build three levels of evaluation: unit level (a single prompt and its parsing), scenario level (a batch of real questions), and regression level (comparison across version iterations). Metrics should cover correctness, citation accuracy, format compliance rate, average steps, and response latency.
Cost control measures include simplifying and deduplicating prompts, truncating retrieval results, using small models for front-end classification and routing, caching high-frequency questions, and batch and asynchronous processing. For observability, write the input summary, retrieval hits, tool call chain, and elapsed time of each call into a logging service, and use monitoring and alerting to locate long-tail issues.
For security, stick to least privilege: separate tool credentials from data access, mask sensitive fields before they enter the model, filter sensitive information and compliance issues on the output side, and keep a human confirmation step for all high-risk actions.
6. Putting It into Practice on the Cloud
The four layers above map directly to general cloud capabilities: object storage holds raw documents and artifacts, message queues handle asynchronous decoupling and peak shaving, container platforms host inference and orchestration services, logging services and monitoring handle observability, and key management handles credential custody. Baidu AI Cloud provides exactly this kind of general infrastructure, which makes it easier for teams to focus on business logic and data quality instead of reinventing the wheel.
7. A Four-Week Practice Roadmap
Week 1: Complete the structured extraction and validation loop, and get the prompt-parse-retry-fallback flow working.
Week 2: Connect your own documents, do chunking and hybrid retrieval, and enforce citations and refusal to answer.
Week 3: Add two or three tools and a step limit, and complete an end-to-end agent task.
Week 4: Fill in the evaluation set, logs, and alerts, and do a review of cost and latency optimization.
Stick to the order of make it testable first, then make it better, then scale it. That way you can evolve a one-off demo into an LLM application that can be iterated on continuously.
