Building a Legal Domain LLM: Technical Architecture and Engineering Practices

    This article explains why legal tasks require a specialized domain model rather than a general-purpose LLM, and walks through the engineering layers involved: base model selection, domain continued pre-training, post-training and alignment, evaluation, workflow implementation, desktop agent integration, and governance. It covers practical trade-offs such as prioritizing effective long-context usage over nominal window size, enforcing citations as a required output field, and measuring task-level pass rates instead of average accuracy. The goal is to turn domain knowledge, retrieval evidence, and tool calls into an auditable, deliverable workflow for contract review, evidence analysis, and compliance planning.

    General-purpose LLMs often look capable on legal tasks, but they struggle to deliver reliably. The problem is not fluency. It comes from three structural constraints.

    First, legal text is long, heavily structured, and full of cross-references. Clauses carry definition dependencies and priority relationships. Second, the tolerance for error in legal judgment is minimal: a single missed item can change the risk exposure of an entire contract. Third, legal work is not question answering. It is a process with input and output contracts, and it must produce tracked changes, annotation rationale, and citation locations.

    So the core goal of a legal domain model is not better conversation. It is to orchestrate domain knowledge, retrieval evidence, and tool calls into an auditable workflow. In engineering terms, this is usually split into four layers: the base model layer, the domain continued pre-training layer, the alignment and post-training layer, and the application orchestration layer.

    2. Base Model Selection: Engineering Trade-offs of a Lightweight Base

    A common misconception is that more parameters always mean better results. In real deployments, a lightweight base paired with high-quality domain data often wins on cost, latency, and controllability. Selection can focus on these dimensions:

    • Effective utilization of long context, not just the nominal window size;
    • Structured output stability, and whether output can be constrained to a fixed schema;
    • Instruction following and refusal boundaries; legal scenarios need the model to say it is uncertain when it is uncertain;
    • Inference cost and concurrency, which determine whether the model fits document-level batch processing.

    A schematic output constraint can be expressed like this:

    1. {
    2. "risk_items": [
    3. {"clause": "Section 8.2", "type": "Limitation of Liability", "level": "High", "suggestion": "Add exception cases"}
    4. ],
    5. "citations": ["Contract page 3, paragraph 2", "Internal Compliance Handbook 4.1"]
    6. }

    The goal of mid-training is to let the model learn the distributional characteristics of legal corpora, including the regulatory system, terminology system, document formats, and argumentation structures. Three practices matter. First, layer the data: separate statutory text, judicial documents, contract templates, and internal policies so their styles do not contaminate each other. Second, deduplicate and denoise: templated text is highly repetitive, so near-duplicate removal and template stripping are necessary. Third, put evaluation first: build a small gold-standard set up front and monitor it continuously during training to prevent the model from learning formats without learning judgment.

    4. Post-Training and Alignment: From Answering to Deliverables

    Post-training focuses on three things: task decomposition, citation of sources, and risk grading. Supervised fine-tuning can establish output specifications, and preference optimization can then balance the model between conservatively flagging risks and over-alerting. Legal scenarios especially need to suppress two tendencies: fabricating clause numbers, and giving absolute conclusions without a basis. A practical approach is to make citations a strongly constrained field, treating any sample that lacks citations as unqualified.

    5. Evaluation: Why Full Pass Rate Matters More Than Average Score

    A single accuracy metric gets inflated by a large number of easy samples. A metric closer to real work is the task full pass rate, where all sub-items of a task must be correct to count as a pass. This matches the reality of contract review, where missing one item means failure. It is advisable to build a three-tier evaluation: clause-level extraction and classification, cross-clause consistency reasoning, and end-to-end document delivery quality, tracking strict pass rate and error type distribution for each.

    6. Workflow Implementation: Contract Review, Evidence Analysis, and Compliance Planning

    Contract review should output risk points, revision suggestions, and citation locations, and support accepting or rejecting changes item by item. Evidence analysis emphasizes timelines and element alignment, and outputs must be traceable back to the location in the original material. Compliance planning leans toward multi-constraint solving, mapping changes in external regulations into an update list for internal policies. All three share the same capability foundation: long-document parsing, structured extraction, retrieval augmentation, and tool calls.

    7. Desktop Agent Integration: Sending Results Back to the Document

    Model capabilities ultimately need to return to the interface users are familiar with. Once the capabilities are connected to a desktop agent platform, revisions can be presented as tracked changes and annotations in document processing software, so users do not have to move content between multiple windows. The recommended engineering approach is a “suggestions are not written to disk directly” strategy: generate candidate revisions first, then let the user confirm before writing, and keep a complete operation log for auditing.

    8. Common Risks and Governance Recommendations

    Key concerns include data compliance and permission isolation, prompt injection and malicious instructions embedded in documents, and regression validation of model updates. Object storage can hold original materials, a message queue can smooth out peak loads for long-document batch tasks, a container platform can host inference services, and logging and monitoring with alerting can track quality drift. Baidu AI Cloud has mature practices in these general capability categories and can serve as a reference foundation for building such systems.

    In summary, the value of a legal domain model comes from the closed loop of domain training, strict evaluation, and workflow orchestration, not from a single point of model capability. With this method, teams can steadily build auditable, deliverable legal intelligence capabilities within their own data and compliance boundaries.