Everything-as-a-Plugin Architecture in Practice: From AI-Assisted TCM Consultation to Safety Workflows

    This article explains how to apply a plugin-based architecture to high-risk AI applications, using AI-assisted Traditional Chinese Medicine (TCM) consultation as a case study. It covers why plugin architecture outperforms monolithic prompt-and-logic design, how to define plugins as governable units with explicit contracts rather than plain functions, how to model a consultation as a state machine, and how to structure user input more reliably than open-ended questionnaires. It also details the "two-gate" design separating pattern-matching from evidence verification, the requirements for a literature-verification plugin, why a safety plugin needs veto power, how an explanation-and-correction plugin should handle user pushback, the engineering governance practices plugin systems require, and the metrics for evaluating whether such a system actually works.

    In intelligent application development, “everything as a plugin” does not mean breaking every feature down into a handful of functions. It means packaging model capabilities, business logic, data access, user interaction, and security policy into modules that are discoverable, callable, and auditable. The value of this approach is that when requirements change, developers don’t need to rewrite the entire agent — they can simply swap or add a plugin to extend the application’s capabilities.

    Take AI-assisted learning and consultation support for Traditional Chinese Medicine (TCM) as an example of a high-risk scenario. A system like this cannot rely on free-form model generation alone. It needs to first gather information, then perform pattern differentiation (辨证), then verify the evidence against classical texts, and only then decide whether to allow a formula recommendation to be generated. If information is insufficient or evidence is inadequate at any stage, the system should halt rather than force an answer just to complete the conversation.

    1. Why Adopt a Plugin-Based Architecture

    Traditional AI applications typically bundle prompts, business logic, and tool calls into one large pipeline. This is fast to build at first, but as features accumulate, several problems emerge.

    First, the pipeline becomes hard to maintain. Consultation questions, differentiation rules, literature retrieval, and output formatting are all tightly coupled, so modifying one step can affect the others.

    Second, capability boundaries blur. The model ends up responsible for asking questions, making judgments, and generating prescriptions all at once. When something goes wrong, it’s hard to tell whether the cause was insufficient information gathering, a flawed rule, or uncontrolled generation.

    Third, fine-grained governance becomes impossible. If every decision is left to the model, the system can’t enforce hard constraints like “don’t output without evidence” or “keep asking when key information is missing.”

    The core idea of a plugin-based architecture is to define each capability as an execution unit with explicit input, output, and permission boundaries. For example:

    • Information collection plugin: gathers basic patient information and chief complaints
    • Symptom structuring plugin: organizes symptoms, signs, and timeline
    • Differential analysis plugin: raises key points that need further confirmation
    • Candidate recommendation plugin: proposes possible syndrome patterns or formula directions
    • Literature verification plugin: searches classical texts and modern research
    • Safety review plugin: identifies contraindications, special populations, and high-risk substances
    • Explanation and rebuttal plugin: presents supporting evidence, states uncertainty, and corrects errors

    Each plugin should be a relatively independent module, not a set of rules hidden inside a prompt.

    2. A Plugin Is Not a Function — It’s a Governable Capability Unit

    A proper plugin should include at least the following information:

    1. Capability description: what problem it solves, and what it does not solve
    2. Input contract: required fields, field types, and which are mandatory
    3. Output contract: the returned structure, and which fields may be empty
    4. State requirements: at which stage of the workflow it can be called
    5. Permission scope: whether it can access health data, literature data, or private user information
    6. Failure policy: how it responds when information is insufficient, and whether retries are allowed
    7. Audit information: call timestamp, input summary, output version, and the basis for the decision

    A plugin can be described using an abstract structure like the following:

    1. Plugin {
    2. name: "evidence_check",
    3. purpose: "Verify whether a candidate formula has reliable supporting evidence",
    4. input: {
    5. syndrome: required,
    6. candidate: required,
    7. patient_context: optional
    8. },
    9. output: {
    10. supported: boolean,
    11. evidence_items: array,
    12. uncertainty: string,
    13. alternatives: array
    14. },
    15. failure_policy: "deny_by_default"
    16. }

    The point here is not the specific field names but the idea of a contract. The caller should not have to guess how a plugin works — it only needs to pass data according to the protocol and handle the structured result.

    3. Modeling the Consultation Process as a State Machine

    Complex medical dialogue is not well suited to free-form natural language progression. It’s better handled with a state machine. A reasonably robust flow can be divided as follows:

    1. Basic information collection
    2. ↓
    3. Chief complaint and history organization
    4. ↓
    5. Symptoms, tongue/pulse signs, and objective indicators
    6. ↓
    7. Differential question confirmation
    8. ↓
    9. Candidate syndrome/formula analysis
    10. ↓
    11. Classical and modern literature verification
    12. ↓
    13. Safety review
    14. ↓
    15. Educational explanation or handoff to a human expert

    The value of a state machine is that every step has clear entry and exit conditions.

    For instance, before entering “candidate analysis,” the system should have confirmed the chief complaint, disease history, key accompanying symptoms, and necessary signs. Before entering “literature verification,” a clear candidate must already have been formed. Before entering “formula output,” contraindication and special-population checks must be complete.

    If any condition is not met, the system should return “continue gathering information” rather than filling in unknown facts on its own.

    4. Structured Interaction Is More Reliable Than Open-Ended Questionnaires

    On mobile apps or in ordinary chat interfaces, asking users to type a long medical history in one go often results in omissions, ambiguity, and disordered information. A better approach is to use grouped cards and option lists.

    For example, chief-complaint collection can be broken down into:

    • Pain: location, nature, duration, triggers
    • Digestive: appetite, nausea, bloating, bowel movements
    • Sleep: difficulty falling asleep, waking easily, excessive dreaming
    • Respiratory: cough, phlegm, chest tightness
    • Women’s health: menstruation, pregnancy, postpartum and breastfeeding status
    • Other special conditions: allergy history, underlying conditions, recent medication

    Structured options don’t mean excluding free text entirely. A reasonable approach is “structured options as the primary input, free text as a supplement.” Users select from standard options first, then add anything the system didn’t cover, and the backend converts both into structured data.

    For indicators like temperature, blood pressure, and pulse rate, the system should support both range selection and exact numeric entry. Ranges work well for quick interaction, while exact values are better suited for downstream judgment. For tongue and pulse signs, users should be reminded that these observations are inherently subjective and should not be treated as established fact.

    5. Separating “Pattern Differentiation” and “Formula Output” Into Two Gates

    This is one of the most critical design decisions in a high-risk AI application.

    The first gate is the matching gate, which answers: “Is the current information sufficient to support a given syndrome pattern or candidate recommendation?” It can combine primary-symptom coverage, key symptom matches, the results of differential questions, and how clearly distinguishable the candidates are from each other.

    The second gate is the evidence gate, which answers: “Does this candidate have sufficient supporting evidence, and is it appropriate for this user’s specific background?” This step requires checking classical texts, reliable research, contraindications, and risks for special populations.

    Only when both gates are passed can the system generate an educational explanatory result — and even then, it should never replace clinical diagnosis and treatment.

    The decision logic can be expressed abstractly as:

    1. if required_information_missing:
    2. return ask_more_questions
    3. if syndrome_confidence < threshold:
    4. return request_differentiation
    5. if evidence_status != supported:
    6. return reject_and_show_alternatives
    7. if safety_review != passed:
    8. return recommend_professional_review
    9. return generate_educational_explanation

    Thresholds should not be treated as fixed truths. They need ongoing calibration through expert review, historical case analysis, and safety testing. In particular, thresholds must never be lowered simply to raise a “completion rate.”

    6. The Literature-Verification Plugin Should Return Evidence, Not Just “Literature Exists”

    The goal of literature verification is not to produce a simple true/false label, but to let users and reviewers understand the reasoning behind the verdict. A reasonably complete result should include at least:

    • The type of source the evidence comes from
    • The original text or excerpt corresponding to the candidate
    • Applicable conditions
    • Inapplicable conditions
    • Strength and limitations of the evidence
    • Whether conflicting sources exist
    • Whether professional review is required

    For classical theory, the system should distinguish between what is explicitly stated in the original text and what is inferred from later clinical experience. For modern research, it should distinguish between observational studies, experimental studies, and clinical studies — different tiers of evidence should not be blended together.

    If no reliable evidence can be found, the system should explicitly return “insufficient supporting evidence found” rather than masking the gap with polished language.

    7. The Safety Plugin Must Have Veto Power

    In an ordinary recommendation system, plugins typically just supply information. In a medical support system, the safety plugin must also be able to block downstream actions.

    Safety checks should cover at least:

    • Pregnancy, postpartum, and breastfeeding status
    • Children, elderly users, and patients with underlying conditions
    • Allergy history and prior adverse reactions
    • Medications currently in use
    • Possible signs of acute or critical illness
    • Formulas containing substances with potential toxicity or strong pharmacological effects
    • Whether the user might mistake the system’s output for a formal prescription

    If any high-risk signal is detected, the system should interrupt the automated workflow and recommend seeking medical care or route the case to human review, rather than continuing to generate detailed dosage information.

    8. “Defending a Position” Should Serve Error Correction, Not Argument

    An AI system will inevitably face user pushback, and it may also make mistakes of its own. This calls for a dedicated explanation-and-correction plugin.

    When a user raises an objection, the system can process it in this order:

    1. Restate the facts and assumptions currently in use
    2. Present the evidence supporting the current judgment
    3. Identify which parts are inference rather than confirmed conclusions
    4. Check whether the user has provided new information
    5. If the new information changes the judgment, rerun the analysis
    6. If the matter cannot be resolved, explicitly acknowledge the uncertainty and hand off to a human expert

    Persistence is not the same as stubbornness. The system should maintain its original conclusion only when the evidence is sufficient and the input hasn’t changed. If a factual error, insufficient evidence, or a rule conflict is found, correction should take priority.

    9. Plugin-Based Systems Also Need Engineering Governance

    Beyond functional design, several engineering concerns need attention.

    Version management. Plugin rules, prompt templates, knowledge bases, and safety policies all need version numbers. Every output must be traceable back to the exact versions in use at the time.

    Observability. Log state transitions, plugin calls, failure reasons, and points of human intervention — while anonymizing sensitive information such as names and contact details.

    Permission isolation. The literature plugin should not have default access to all user private data, and the safety plugin should not be able to arbitrarily modify original medical record data.

    Testing. Beyond ordinary functional testing, systems need boundary testing, adversarial testing, privilege-escalation testing, and regression testing against high-risk cases.

    Human review. For any functionality involving diagnosis, prescriptions, dosage, or emergency judgment, a human review channel must be preserved. A high degree of automation should never be equated with reliability.

    10. How to Evaluate the Real-World Effectiveness of “Everything as a Plugin”

    Evaluating a system like this requires looking beyond response speed or user satisfaction. Relevant metrics include:

    • Completion rate for gathering key information
    • Rate of blocking unnecessary or premature output
    • Accuracy of evidence citations
    • Detection rate for high-risk scenarios
    • Speed of correcting erroneous conclusions
    • Recovery capability after plugin failures
    • Expert approval of the workflow and its explanations
    • Whether users correctly understand the system’s boundaries

    In the end, what “everything as a plugin” actually solves isn’t “giving the model more tools” — it’s giving complex AI applications a composable, constrainable, explainable, and auditable engineering foundation. In medical learning and consultation support scenarios, the most important capability isn’t producing an answer faster. It’s continuing to ask questions when information is insufficient, refusing to cross a gate when evidence is lacking, and promptly handing off to a professional when risk appears. Only when these principles are built into plugin contracts and workflow control does a plugin-based architecture become more than a way to organize code — it becomes a foundational method for building reliable AI systems.