AI Agent App Generation Practices: RAG Q&A, Tool Simplification, and Self-Iteration

    This article explores the practical development of AI agent applications, focusing on building a robust RAG-based Q&A system. It covers the core pipeline from data ingestion and chunking to retrieval and answer generation with citations. Additionally, it details strategies for simplifying toolsets to improve accuracy and reduce costs, establishing an evaluation loop for self-iteration, organizing agent skills, and integrating multiple LLMs through a unified interface.

    I. From a Single Requirement to a Runnable Application

    In the past, building a document Q&A application required sequentially completing data collection, cleaning, chunking, vectorization, retrieval, generation, and frontend display, with each step requiring individual coding and debugging. In recent years, agent development tools have begun to support describing requirements in natural language, allowing the system to automatically generate project scaffolding, core code, and usage instructions. While this approach lowers the barrier to entry, it does not mean engineering judgment can be skipped. The generated results still require validation of retrieval quality, citation accuracy, and operational stability.

    To determine whether an automatically generated application is viable, focus on three things: first, whether the data sources are clear and traceable; second, whether the answers are based on retrieved content rather than hallucinated by the model; and third, whether the project structure is convenient for future modifications. Below, we use “building a Q&A expert based on a set of technical documents” as an example to break down the key steps.

    II. Core Pipeline of a Document Q&A Application

    A document Q&A system with citations typically includes five steps.

    1. Data Collection and Cleaning

    After obtaining raw files from a code repository or documentation site, you need to remove content unrelated to the main text, such as navigation bars and footers, and standardize the encoding and line breaks. The cleaned text should retain the original path, heading hierarchy, and page URL, as this metadata is the foundation for subsequent citations.

    2. Text Chunking

    Directly splitting text by a fixed character count can easily disrupt semantics. A more robust approach is to first divide chapters by heading hierarchy, then split overly long chapters by paragraph, and add a small amount of overlap to each chunk to preserve context.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Chunk:
    4. text: str
    5. source_url: str # Original page URL for citation linking
    6. heading_path: str # e.g., "Config > Permissions > Whitelist"
    7. chunk_id: str
    8. def split_by_heading(doc_text: str, source_url: str, max_chars: int = 800):
    9. chunks, buf, path = [], [], ""
    10. for line in doc_text.splitlines():
    11. if line.startswith("#"):
    12. if buf:
    13. chunks.append(Chunk("\n".join(buf), source_url, path, f"{source_url}#{len(chunks)}"))
    14. buf = []
    15. path = line.lstrip("#").strip()
    16. buf.append(line)
    17. if sum(len(x) for x in buf) > max_chars:
    18. chunks.append(Chunk("\n".join(buf), source_url, path, f"{source_url}#{len(chunks)}"))
    19. buf = []
    20. if buf:
    21. chunks.append(Chunk("\n".join(buf), source_url, path, f"{source_url}#{len(chunks)}"))
    22. return chunks

    3. Index Construction and Retrieval

    You can use vector retrieval, keyword retrieval, or a hybrid approach combining both. For technical documentation, which contains many proper nouns and command names, pure vector retrieval might miss exact matches, so hybrid retrieval is usually more stable. After retrieval, you can use a reranking model or simple rules to sort candidate chunks and keep only the top-scoring ones.

    4. Answer Generation with Citations

    The prompt should explicitly require the model to answer based only on the provided chunks and to annotate each conclusion with the chunk ID. On the program side, validation is needed: whether the IDs appearing in the answer actually exist in the current retrieval results. Citations that fail validation should be discarded or flagged, rather than displayed to the user as is.

    5. Frontend Display

    The citation IDs are mapped to the chunk’s source_url and heading_path, allowing users to click and jump to the corresponding position in the original text. Example questions can be automatically extracted from document titles or FAQs to help users quickly understand the system’s capabilities.

    III. Why Deliberately Simplify the Toolset

    Every time an agent makes a decision, it must place the names, descriptions, and parameter structures of available tools into the context. The more tools there are, the higher the input token count for a single call, and the higher the probability of the model choosing the wrong tool. Therefore, simplifying the toolset affects both cost and accuracy.

    Simplifying the toolset can follow these principles:

    • Keep only the tools essential for the core task. For example, document Q&A only needs tools for retrieval and reading the original text; there is no need to provide general web browsing or code execution capabilities.
    • Keep interface parameters simple. The meaning of each parameter should be immediately clear from its name, avoiding too many optional parameters that might lead to model input errors.
    • Unify the return structure. Success, failure, and empty results should use the same format, making it easier for the model to determine the next action.
    • Set timeouts and idempotency. Retrieval and reading tools should be safely retryable, while write operations require a clear confirmation mechanism.

    Note that the degree of improvement in cost and accuracy depends on the specific task and model, so you cannot directly apply someone else’s numbers. The most reliable approach is to use your own evaluation set to compare performance under different tool counts before deciding which tools to keep.

    IV. Enabling Agent Self-Evaluation and Iteration

    The most common problem in agent development is that after modifying prompts or skills, it is impossible to tell whether the overall effect has improved or degraded. The solution is to establish an evaluation loop.

    1. Design a Benchmark Set

    The benchmark set consists of a group of typical tasks and expected results. For document Q&A, it can include the following types of samples:

    • Factual questions with clear answers located in a single chunk;
    • Reasoning questions requiring synthesis across multiple chunks;
    • Questions where the answer does not exist in the document, which should be refused;
    • Questions where citation IDs must strictly correspond to the original text.

    2. Define Scoring Dimensions

    It is recommended to split the evaluation into at least three dimensions: correctness, citation accuracy, and refusal ability, scoring them separately to avoid masking problems with a single total score. Automated scoring can be done using rules or another model, but periodic manual sampling should be conducted to prevent the scoring model itself from introducing bias.

    3. Iteration Process

    The iteration process can be summarized as: run the evaluation, analyze failed samples, modify prompts or skills, save a snapshot, and re-evaluate. If the new version significantly regresses in a certain dimension, roll back to the previous snapshot.

    1. import json, shutil, time
    2. from pathlib import Path
    3. def snapshot(skill_dir: Path, store: Path) -> str:
    4. tag = time.strftime("%Y%m%d-%H%M%S")
    5. target = store / tag
    6. shutil.copytree(skill_dir, target)
    7. return tag
    8. def rollback(tag: str, skill_dir: Path, store: Path) -> None:
    9. shutil.rmtree(skill_dir)
    10. shutil.copytree(store / tag, skill_dir)
    11. def evaluate(run_benchmark, skill_dir: Path) -> dict:
    12. scores = run_benchmark(skill_dir) # Returns {"correctness": x, "citation": y, "refusal": z}
    13. return scores
    14. def improve_once(skill_dir, store, run_benchmark, apply_change, baseline):
    15. tag = snapshot(skill_dir, store)
    16. apply_change(skill_dir)
    17. new = evaluate(run_benchmark, skill_dir)
    18. if any(new[k] < baseline[k] - 0.02 for k in baseline):
    19. rollback(tag, skill_dir, store)
    20. return baseline, False
    21. return new, True

    The code above demonstrates the basic logic of snapshotting and rolling back. In actual projects, you also need to record the reason for each change and the evaluation results for post-hoc traceability.

    Be wary of overfitting. If you repeatedly adjust against the same benchmark set, scores will rise, but real-world performance may not improve. Regularly replacing some samples and adding real online questions is an effective way to control this risk.

    V. Organizing Skills

    A Skill can be understood as a set of domain-specific instructions, processes, and scripts that an agent loads on demand. Organizing skills logically helps control context length and facilitates team collaboration and maintenance.

    A common directory structure looks like this:

    1. skills/
    2. office/
    3. data-analysis/
    4. SKILL.md # Applicable scenarios, steps, and precautions
    5. scripts/
    6. web-collection/
    7. SKILL.md
    8. software/
    9. frontend-design/
    10. SKILL.md
    11. engineering-practice/
    12. SKILL.md
    13. ai-app/
    14. sdk-usage/
    15. SKILL.md
    16. model-serving/
    17. SKILL.md
    18. fine-tuning/
    19. SKILL.md

    It is recommended that SKILL.md contains four parts: when to use the skill, step-by-step operational procedures, common errors and troubleshooting methods, and example inputs and outputs. The script section should be independently executable, with dependencies and permission requirements documented.

    Agents can also write or optimize skills based on task experience, but new skills should undergo evaluation and manual review before being added to the official directory, preventing low-quality content from affecting subsequent tasks over the long term.

    VI. Unified Access to Multiple LLMs

    Different model providers have varying access methods, but most services now support standard chat completion API specifications. Therefore, the application layer can rely on a single unified client abstraction, placing the base URL, API key, and model name in the configuration.

    1. import os
    2. from dataclasses import dataclass
    3. @dataclass
    4. class ModelConfig:
    5. base_url: str
    6. api_key: str
    7. model: str
    8. def load_model_config(prefix: str = "LLM") -> ModelConfig:
    9. return ModelConfig(
    10. base_url=os.environ[f"{prefix}_BASE_URL"],
    11. api_key=os.environ[f"{prefix}_API_KEY"],
    12. model=os.environ[f"{prefix}_MODEL"],
    13. )

    API keys should only be read through environment variables or a key management service, never written into code or logs. When switching models, you only need to modify the environment variables without adjusting business code.

    After integrating multiple models, pay attention to the following differences:

    • Context length: In long-document scenarios, the chunking strategy and retrieval count must be adjusted according to the model’s context limit.
    • Tool calling capabilities: Different models vary in their stability regarding parameter formats and multi-step calls, requiring separate testing.
    • Structured output: The degree of adherence to requirements like citation IDs and JSON formats varies across models.
    • Latency and cost: Record the time to first token and token usage per call as a basis for model selection.

    When selecting a model, run the same benchmark set on candidate models and compare scores across dimensions before making a decision.

    VII. Deployment Checklist

    Before going live, inspect the system from the following aspects.

    Security

    • Retrieved document content may contain text attempting to alter the model’s behavior; treat it as data, not instructions, and explicitly constrain it in the prompt.
    • Tools involving code execution or file access should run in an isolated environment with restricted paths and network access.
    • Tool permissions follow the principle of least privilege, granting only the capabilities needed for the current task.

    Observability

    • Log the complete trajectory of each run, including retrieval results, tool call parameters, model outputs, and latency.
    • Track token usage and costs, setting up alerts for anomaly thresholds.

    Maintainability

    • Prompts, skills, and configurations should be under version control, with each change corresponding to a snapshot.
    • The evaluation set should be updated alongside the code to ensure that any changes can be quantitatively validated.

    VIII. Summary

    Using natural language to describe requirements can quickly yield a prototype for a document Q&A application, but what truly determines the effectiveness are retrieval quality, citation validation, tool design, and the evaluation loop. Keeping the toolset limited to the necessary scope, driving iteration with benchmark sets, and isolating model differences with a unified interface—these three combined allow agent applications to maintain a balance between cost, accuracy, and maintainability.