Engineering a Legal Vertical Large Language Model: From Domain Adaptation to Workflow Integration

    This article walks through the practical engineering of a legal vertical large language model, covering why general-purpose models underperform on legal tasks, a two-stage post-training route built on a lightweight base model, a four-layer evaluation framework, agent integration into existing workflows, and the data security and effectiveness validation questions enterprises must answer before deployment. It is intended for AI and software engineers working on domain-specific LLM applications in regulated industries.

    The capability distribution of a general-purpose base model is “broad but shallow.” It has seen massive amounts of text, but rarely encounters fully structured contract attachments, case file indexes, or the citation relationships between regulatory provisions. The core difficulty of legal practice is not generating fluent sentences, but three things: the mutual constraints between clauses, the completeness of the chain of factual evidence, and the requirement that every conclusion be traceable to a specific provision.

    When a general model is dropped directly into a legal workflow, the common symptoms are: missing cross-referenced clauses, confusing “shall” with “may,” insensitivity to exceptions, and an inability to point to the basis for a conclusion. Prompt engineering can only relieve these surface symptoms. The fundamental fix is domain adaptation at the model level.

    2. Technical Route: Lightweight Base + Two-Stage Post-Training

    A widely adopted path in the industry is “lightweight base model + domain-adaptive intermediate training + reinforcement learning post-training.” The engineering logic is as follows.

    2.1 Base Model Selection: Prioritize Inference Cost and On-Premises Feasibility

    Legal scenarios typically involve long documents, high concurrency, and strict compliance requirements, so a larger parameter count is not necessarily better. The advantages of a lightweight base model are: controllable cost for single long-context inference, deployability inside a private environment, and response latency that meets the needs of interactive review. Selection should focus on long-context stability, the ability to follow structured output requirements, and corpus coverage of Chinese legal documents.

    2.2 Stage One: Domain-Adaptive Pretraining

    The goal is to close the gap in “language distribution,” not to teach the model to answer questions. A typical corpus mix looks like this:

    1. Domain corpus mix (illustrative)
    2. ├── Laws, regulations, and judicial interpretations ~30%
    3. ├── Contracts and transaction documents ~25%
    4. ├── Court judgments and arbitration awards ~20%
    5. ├── Compliance policies and audit working papers ~15%
    6. └── General corpus (anti-forgetting) ~10%

    Keeping general corpus is a detail that is easy to overlook: if the proportion is too low, the model’s capability on non-legal instructions degrades — so-called “catastrophic forgetting.”

    2.3 Stage Two: Reinforcement Learning Post-Training (RLHF / Preference Optimization)

    Intermediate training solves “knowing”; post-training solves “getting it right.” Reward signals for legal tasks should be built around verifiable objectives, for example: whether risk points are recalled, whether revision suggestions are actionable, whether cited provisions actually exist, and whether the output format can be parsed by downstream systems. For the parts that cannot be judged automatically, legal professionals are brought in to produce pairwise preference annotations; a reward model is trained first, and policy optimization follows.

    3. Evaluation: A Single Accuracy Number Is Not Enough

    The “task pass-all rate” and “accuracy” mentioned above point to the key issue in evaluation design: a legal workflow is a composite task, and partial correctness means unusable. A practical evaluation framework has at least four layers:

    Layer What is evaluated How it is judged
    Fact Whether provision citations are real and currently in force Knowledge base comparison
    Reasoning Whether risk identification is complete and the logic is self-consistent Expert annotation + rule checks
    Generation Whether revision suggestions are specific and actionable Pairwise preference comparison
    Engineering Structured output parsing success rate, long-document truncation rate Automated pipeline

    The “task pass-all rate” requires every sub-item in a task to be correct, which is far stricter than average accuracy and much closer to real delivery standards. Teams are advised to keep both metrics in internal evaluation so that long-tail defects are not hidden by an average.

    4. From Model to Workflow: Agent Integration Is the Critical Step

    Model capability only creates business value once it is embedded in the existing toolchain. Take contract review as an example: the mature form is a desktop agent that presents results inside document processing software as “track changes + comments.” Revisions carry text replacements that can be accepted directly; comments carry risk explanations and the supporting basis. This design turns “model output” into a “change set a human can review,” with clear boundaries of responsibility.

    A simplified processing pipeline:

    1. def review_contract(doc_path, policy_db, model):
    2. clauses = parse_to_clauses(doc_path) # Parse into clause structure
    3. retrieved = policy_db.search(clauses) # Retrieve applicable rules and internal controls
    4. result = model.review(clauses, retrieved) # Generate risks and revision suggestions
    5. return to_track_changes(result) # Output revisions and comments

    Three things need extra engineering attention: segmenting long documents and aligning clauses, traceable citations for retrieval results, and proactively falling back to “flag for human review” when confidence is low.

    5. Two Questions Enterprise Deployment Must Answer

    Data security. Legal texts contain trade secrets and sensitive personal information. Prefer options that support on-premises or private network deployment, combined with encryption in transit and at rest, fine-grained permissions, and complete audit logs. If cloud resources are used, a closed loop can be built on general capabilities such as object storage, key management, log services, and monitoring and alerting.

    Effectiveness validation. Do not use a demo as the acceptance criterion. Sample from historical cases to build an internal test set, set “zero critical misses” as a red-line metric, run a canary release in a narrow scenario first, then expand the scope step by step, and keep human final review in place.

    6. Conclusion

    The value of a legal vertical model does not come from parameter scale, but from the product of four factors: domain data quality, post-training objective design, evaluation strictness, and depth of workflow integration. In its engineering practice of large models for industry scenarios, Baidu AI Cloud likewise emphasizes driving model iteration with scenario metrics and meeting compliance requirements through controllable deployment — an approach with direct relevance to building legal intelligence.