Building a Legal Vertical Large Language Model: Technical Architecture and Implementation Practices
General-purpose LLMs offer broad knowledge, but in legal practice they often cite the wrong statutes, produce unstable reasoning, and misuse terminology. Many teams therefore train legal vertical models on top of a general-purpose base model. This article walks through four key aspects of building such systems: technical architecture, core use cases, document integration, and evaluation practices.
General-purpose LLMs offer broad knowledge, but in legal practice they often cite the wrong statutes, produce unstable reasoning, and misuse terminology. Many teams therefore train legal vertical models on top of a general-purpose base model. This article covers the technical architecture, core use cases, document integration, and evaluation practices for building such systems.
1. Technical Architecture and Training Paradigms
Building a legal LLM typically involves three stages: base model selection, domain-adaptive mid-training, and reinforcement learning post-training. Each stage needs to be validated independently—never rely solely on the final demo output.
1.1 Choosing a Lightweight Base Model
Early projects often used very large general-purpose models. As applications matured, lightweight models in the tens-of-billions to low-hundred-billion parameter range became the mainstream choice. They offer lower inference latency, manageable compute costs, and are easier to deploy privately within enterprise networks.
Before deployment, confirm three things: whether the data storage location complies with regulatory requirements, whether the cloud service or data center holds the relevant security certifications, and whether the scaling strategy can handle peak loads during contract review cycles. Major cloud providers’ container platforms and self-hosted GPU clusters can both meet these requirements—compliance should be the first criterion.
Model quantization reduces GPU memory usage. INT8 quantization usually has minimal impact on inference quality, while INT4’s impact varies by model and quantization method; tasks like long-clause reasoning and statute citation are more prone to accuracy drops. Quantify the precision loss on your own legal test set rather than trusting published benchmarks.
1.2 Domain-Adaptive Mid-Training: Injecting Legal Knowledge
General-purpose base models have limited knowledge of specific statutes, judicial interpretations, and contract templates. Domain mid-training uses continued pre-training to feed statutes, judicial interpretations, standard contract libraries, and public case law into the model. The outcome depends heavily on corpus quality. Review each item before ingestion:
- Statute currency: Record the effective and expiration dates of every text so the model doesn’t learn repealed provisions.
- Conflicting case law: Courts in different regions or at different levels may disagree on the same issue; tag corpus entries with jurisdiction and court level.
- Personal information and trade secrets: PII and internal corporate data in training corpora must be anonymized.
- Copyright and licensing: Confirm that every corpus source permits training use.
The learning rate for continued pre-training is typically lower than the base model’s original training rate. To prevent catastrophic forgetting of general capabilities, mix in a proportion of general-purpose corpora. Run both general benchmarks and legal test sets before and after training to track changes in both capability types.
1.3 Reinforcement Learning Post-Training: Aligning with Legal Practice
Post-training aligns output format, reasoning steps, and revision suggestions with how lawyers actually work. Two common approaches:
| Dimension | RLHF | DPO |
|---|---|---|
| Training pipeline | Requires training a reward model first, then optimizing the policy with RL | Optimizes directly on preference comparison data; shorter pipeline |
| Annotation cost | Higher; needs reward model training data | Lower; needs paired preferred and rejected samples |
| Best suited for | Multi-step reasoning and complex tasks requiring process rewards | Preference alignment for output style, formatting, and single-turn suggestions |
| Tuning difficulty | Higher; debugging unstable training is costly | Lower, but sensitive to preference data quality |
For contract review, DPO works well for the wording and formatting preferences of revision suggestions. Multi-step evidence-chain reasoning that requires complex process rewards may call for RLHF, or combining verifiable rules as reward signals. The choice depends on annotation budget, task complexity, and your team’s training expertise.
2. Core Use Cases
2.1 Contract Review and Risk Identification
The basic pipeline: split the contract into clauses, retrieve similar cases, pass them to the model for analysis, and output structured results. Model output should use fixed fields for downstream processing. Recommended fields:
| Field | Type | Description |
|---|---|---|
| clause_id | string | Clause identifier |
| clause_span | object | Start and end positions of the clause in the source text |
| risk_level | enum | high, medium, or low |
| risk_type | string | e.g., clause conflict, rights/obligations imbalance, missing breach liability |
| evidence | array | Quoted source passages and retrieved case IDs |
| suggestion | string | Suggested revision |
| confidence | float | Value between 0 and 1 |
| needs_human_review | bool | Whether attorney review is required |
The confidence value is produced by the model itself and cannot be treated as a reliable probability without calibration. Measure the actual accuracy within different confidence intervals on labeled samples, then set thresholds accordingly.
Human review rules can be set like this:
- All high-level risks go to human review.
- Clauses involving amounts, breach liability, jurisdiction, and IP ownership always go to human review.
- Suggestions with empty evidence always go to human review.
- Confidence below the calibrated threshold triggers human review.
Model suggestions serve only as supporting material for attorneys and must never be issued directly as legal opinions.
2.2 Evidence Analysis and Timeline Reconstruction
In litigation or arbitration, evidence often comes from multiple sources with inconsistent formats and date annotations. The model can first extract dates, parties, and events from each document, arrange events chronologically, then compare documents for contradictions.
Input typically includes evidence text and metadata such as source, submitting party, and creation date. Example output:
{"timeline": [{"date": "2024-03-02", "event": "Party A sent a payment demand letter", "source_doc": "E-07", "party": "Party A", "confidence": 0.92}],"conflicts": [{"fact": "Goods delivery date", "doc_a": "E-03 delivery note", "doc_b": "E-11 witness statement", "description": "The two documents differ by 14 days"}]}
OCR on scanned documents can misread dates or numbers, so every conflict must be verified against the original documents—never draw conclusions from model output alone.
2.3 Dynamic Compliance Planning and Regulation Mapping
Corporate policy documents need to stay aligned with current regulations. A knowledge graph can record the mapping between statutory provisions and corporate policy clauses.
Three things to clarify in practice:
- Update frequency: Sync regularly via official regulation channels, e.g., weekly batch updates; handle major regulatory changes immediately.
- Version traceability: Record effective dates, revision history, and repeal status for every provision so historical compliance decisions can be reproduced.
- Human confirmation boundary: The model can flag potentially affected policies and draft remediation plans, but legal or compliance leads must confirm the final conclusions.
3. Integration with Office Document Tools
An LLM that only answers questions in a chat window is hard to fold into daily contract review workflows. A more practical approach: write analysis results directly back into Word documents as comments and tracked changes.
3.1 Human-in-the-Loop Document Revision
After the model identifies a risky clause, the system adds a comment at the corresponding location with a suggested revision. Once the attorney confirms, the change is written into the document as tracked changes, making it easy for counterparties and internal colleagues to see what changed.
This reduces lawyers’ repetitive clause-by-clause reading. The time saved depends on document quality and the review process; during the pilot phase, track revision acceptance rate and review time, and judge effectiveness with real data.
Contracts typically contain PII and trade secrets, so:
- Mask sensitive data before sending to the model. Replace phone numbers, ID numbers, and bank accounts with placeholders, and store the mapping locally for restoration.
- Prefer privately deployed model services.
- Log only clause IDs and error types—never contract text.
3.2 API Contracts and Engineering Implementation
The following code demonstrates the call sequence and error handling; it is not runnable as-is. DocumentProcessor is a placeholder class and should be replaced with a real document parsing library.
API contract:
- DocumentProcessor.load(path): loads a .docx file and returns a document object. Only files in designated directories may be read.
- extract_blocks_with_positions(): returns a list of paragraphs, each with index, text, page number, and start offset.
- call_model_api(endpoint, payload, token, timeout): returns a dict matching the field table in Section 2.1.
- Dependencies: python-docx for document read/write, requests for calling the model service.
- Word tracked changes require w:ins and w:del markup; track_replacement below is only a placeholder method.
# Illustrative code: demonstrates call sequence and error handling only. Not runnable as-is.import osimport loggingimport requestslogger = logging.getLogger("contract_review")REQUIRED_FIELDS = {"block_index", "risk_level", "analysis", "suggestion", "needs_human_review"}VALID_LEVELS = {"high", "medium", "low"}MAX_RETRIES = 3def mask_sensitive(text: str) -> str:# Placeholder: replace phone numbers, ID numbers, bank accounts, etc., and keep a mapping for restorationreturn textdef call_model_api(endpoint, payload, token, timeout=60):for attempt in range(1, MAX_RETRIES + 1):try:resp = requests.post(endpoint,json=payload,timeout=timeout,headers={"Authorization": f"Bearer {token}"},)resp.raise_for_status()return resp.json()except requests.RequestException as exc:# Log the exception type only; never log contract contentlogger.warning("model call failed, attempt=%d, error=%s", attempt, exc.__class__.__name__)raise RuntimeError("model service unavailable after retries")def is_valid_suggestion(s: dict, block_count: int) -> bool:if not REQUIRED_FIELDS.issubset(s):return Falseif s["risk_level"] not in VALID_LEVELS:return Falsereturn 0 <= s["block_index"] < block_countdef apply_contract_review(doc_path: str, model_api_endpoint: str):token = os.environ["LEGAL_M
