AI Text Detection: Principles and Engineering Practices

    This article explains how AI-generated text detection works in practice, moving beyond simple yes-or-no answers toward confidence scores, layered technical pipelines, and appealable decisions. It covers the three core difficulties of the task—distribution drift, adversarial rewriting, and asymmetric costs—then compares perplexity and burstiness statistics, supervised classification, and watermarking. It also details feature design across lexical, syntactic, semantic, and probability layers, multilingual and cross-model generalization, evaluation metrics beyond accuracy, false-positive governance, system integration, and compliance boundaries. Developers will find guidance on building a detection pipeline that stays explainable, calibrated, appealable, and iterable as models keep evolving.

    1. Problem Definition: Why Source Attribution Is an Engineering Challenge

    Once generative models entered writing, translation, summarization, and code commenting at scale, the core demand from content platforms, educational institutions, and publishers shifted. The goal is no longer to “ban AI” but to make decisions that are determinable, explainable, and appealable. For this reason, AI-generated text detection is essentially a statistical discrimination task running in an open domain: the input is a piece of natural language text, and the output is a confidence score indicating source tendency, not a black-and-white verdict.

    Compared with traditional spam detection, this task has three notable difficulties. First is distribution drift: model versions keep updating, and the generation styles seen during training quickly become outdated. Second is adversarial rewriting: users can significantly weaken detection signals through synonym substitution, sentence restructuring, and paragraph reorganization. Third is asymmetric cost: the reputation damage from misclassifying human original work as machine-generated (a false positive) is usually far greater than the cost of a miss (a false negative). These three points determine that a detection system must be deployed as “probabilistic output + threshold strategy + human review” rather than exposing a simple boolean interface.

    2. Technical Approaches: From Statistical Features to Representation Learning

    Common detection approaches in the industry fall into three complementary routes, and real systems are usually hybrid architectures.

    The first route is perplexity and burstiness statistics. How “predictable” a text is to a language model can be characterized by perplexity; machine-generated text often shows a smoother local probability distribution. Meanwhile, human writing fluctuates more in sentence length and information density, which can be measured by a burstiness metric. This kind of method needs no trained classifier, starts up quickly, and is highly explainable, but its robustness is limited for rewritten text.

    The second route is supervised classification. Human text and machine-generated text from multiple models form the training set; a pretrained language encoder produces sentence-level or paragraph-level representations, and a discrimination head then outputs a confidence score. This route has a high accuracy ceiling but requires continuously adding samples from new models to counter distribution drift.

    The third route is watermarking and source signatures. A statistically testable bias is introduced into the sampling process at generation time, and the detection side runs a statistical test to determine whether a watermark signal is present. Its advantage is a controllable theoretical error rate, but it requires the generating party to cooperate proactively and cannot cover “historical content without watermarks.”

    A more robust engineering practice is layered fusion: first use statistical features for low-cost initial screening, then apply a representation-learning model to fine-grained discrimination of suspicious segments, and finally introduce human review and an appeal channel for high-risk conclusions.

    3. Designing the Feature and Signal System

    To make detection results explainable, black-box scores need to be decomposed into readable signals. Common feature families include:

    • Lexical layer: type-token ratio, proportion of low-frequency words, and vocabulary richness distribution;
    • Syntactic layer: average sentence length and sentence-length variance, clause nesting depth, and punctuation usage patterns;
    • Semantic layer: paragraph redundancy reflected by the sentence-vector similarity matrix, and topic drift curves;
    • Probability layer: perplexity sequences under a sliding window, and entropy of local probability distributions.

    A schematic feature-extraction skeleton is shown below (it expresses structure only and involves no specific platform interfaces):

    1. import re
    2. import math
    3. from statistics import mean, pstdev
    4. def lexical_features(text: str) -> dict:
    5. tokens = re.findall(r"\w+", text.lower())
    6. if not tokens:
    7. return {"tts": 0.0, "long_word_ratio": 0.0}
    8. types = set(tokens)
    9. long_words = [t for t in tokens if len(t) >= 7]
    10. return {
    11. "tts": len(types) / len(tokens), # vocabulary diversity
    12. "long_word_ratio": len(long_words) / len(tokens),
    13. }
    14. def rhythm_features(text: str) -> dict:
    15. sentences = [s for s in re.split(r"[。!?.!?]+", text) if s.strip()]
    16. lengths = [len(s) for s in sentences]
    17. if not lengths:
    18. return {"avg_len": 0.0, "burstiness": 0.0}
    19. return {
    20. "avg_len": mean(lengths),
    21. # burstiness: std dev of sentence length / mean; usually higher in human writing
    22. "burstiness": pstdev(lengths) / max(mean(lengths), 1e-6),
    23. }
    24. def fuse_score(feats: dict, model_score: float) -> float:
    25. # schematic: weighted fusion of statistical signals and model score; weights must be calibrated per scenario
    26. stat = 0.5 * (1.0 - feats["tts"]) + 0.5 * min(feats["burstiness"], 1.0)
    27. return 0.4 * stat + 0.6 * model_score

    It is worth emphasizing that no single feature is sufficient to support a conclusion. The value of explainability is that when a user appeals, the system can provide the basis for “which dimensions deviate from the human-writing baseline” instead of returning only a score.

    4. Multilingual and Cross-Model Generalization

    Supporting multiple languages is not simply a matter of expanding the corpus; it means handling three structural differences. First is tokenization granularity: space-free languages such as Chinese and Japanese need subword segmentation strategies, otherwise vocabulary-diversity metrics become distorted. Second is morphological richness: in languages such as Finnish and Russian, inflection inflates the type-token ratio, so lemmatization is needed before counting. Third is data scarcity for low-resource languages, which usually requires cross-lingual representation transfer plus small-scale threshold calibration on the target language.

    Cross-model generalization depends on the diversity of sample composition: the training set should cover generative models with different parameter sizes and different alignment strategies, and a portion of “unseen models” should be reserved as a generalization validation set. If evaluation is done only on samples from a single model, inflated metrics are the norm.

    5. Evaluation Metrics: Don’t Look at Accuracy Alone

    In open-domain detection, reporting a single accuracy figure is misleading, because the positive-to-negative sample ratio significantly affects perception. A more rigorous evaluation should include:

    • Stratified metrics split by scenario: academic long-form text, short news copy, and marketing copy counted separately;
    • The trade-off curve between false positive rate (FPR) and recall, i.e., ROC and PR curves;
    • Threshold sensitivity analysis: how large the overlap region of score distributions is;
    • Adversarial robustness testing: score decay after rewriting, back-translation, and segment concatenation;
    • Calibration: whether an output of 0.9 really corresponds to roughly a 90% empirical probability.

    A practical evaluation table structure is shown below:

    Scenario Sample size False positive rate Recall Calibration error
    Academic paper excerpt 5000 target < 1% adjustable by threshold lower is better
    Short news copy 5000 target < 2% adjustable by threshold lower is better

    6. False-Positive Governance and an Appeal Mechanism

    High accuracy metrics must translate into a “low-harm” design in engineering. Recommended practices include: setting a minimum text-length threshold so that conclusions are not output for overly short text; using a dual-threshold output with two tiers, “suspected” and “high confidence,” with the gray zone in between mandatorily routed to human review; retaining complete detection snapshots and version numbers for later auditing; and providing users with a convenient entry point for appeals and re-detection.

    The flow can be abstracted as:

    1. text input -> preprocessing and language identification -> statistical feature screening
    2. -> model discrimination scoring -> threshold routing (pass / gray zone / high confidence)
    3. -> gray zone enters human review -> results logged with an appeal channel

    7. System Integration and Engineering Deployment

    Detection capability is usually embedded into the content pipeline as an independent service, with submission, assignment submission, or publishing review upstream and the review console and risk-control policies downstream. There are four integration points. First, decouple via standard HTTP interfaces and message queues so that review peaks do not drag down the main pipeline. Second, run batch processing and real-time detection as parallel channels, with long documents returned asynchronously. Third, cover the full chain with logging and monitoring alerts for call volume, latency percentiles, and gray-zone ratio drift. Fourth, version-manage models and thresholds, support canary releases, and enable one-click rollback.

    When running in the cloud, capabilities can be combined under general categories: object storage holds training and audit data, a container platform hosts inference services with elastic scaling, logging and monitoring-alerting services provide observability, and message queues smooth out traffic peaks. Baidu AI Cloud also offers the above general-category capabilities for content risk-control scenarios like this, and they can be combined as needed.

    8. Governance Boundaries and Compliance Notes

    Detection conclusions should serve as “supporting evidence” rather than a final verdict, especially in high-stakes scenarios such as academics and hiring. Three compliance points need attention: notification and transparency, clearly stating that automated detection is used; data minimization, avoiding retention of personal information unrelated to the task; and a human backstop, ensuring any adverse decision has a human-review and explanation channel.

    9. Conclusion

    The engineering value of AI-generated text detection lies not in producing a nice-looking overall score but in building a decision pipeline that is explainable, calibratable, appealable, and iterable. Developers should focus on the readability of the feature system, the rigor of evaluation metrics, scenario-specific threshold strategies, and versioned operations, so that the system remains usable over the long term in an adversarial environment where models keep evolving.