A Practical Guide to Open-Source LLMs for Legal Use Cases

    This guide explains why general-purpose LLMs struggle with legal work and how to build a legal-domain model instead: a two-stage pipeline of domain-intermediate training and RL post-training, an evaluation system based on task pass rate rather than accuracy alone, embedding model capabilities into document workflows, and deployment and governance using general cloud capabilities. It also covers common pitfalls and practical engineering recommendations for teams building legal AI copilots on lightweight open-source base models.

    Legal text is highly context-dependent and intolerant of errors. A merger agreement can easily run to hundreds of pages, with definitions, cross-references, and exhibits forming a dense web of citations. A single wording difference, such as “shall not be deemed a breach,” can shift the entire allocation of liability. General-purpose LLMs perform well on open-domain question answering, but this kind of text exposes three weaknesses.

    The first is drift in terminology and style. Legal writing relies on fixed sentence patterns and conventional phrasing. When a model generates text from the probability distribution of everyday language, it tends to produce sentences that look professional but do not meet drafting conventions. The second is a lack of long-range consistency. Clauses within a contract must be internally coherent, yet models often lose earlier constraints as the context grows. The third is a blurred boundary between abstention and hallucination. Legal work requires the model to refuse clearly when evidence is insufficient, and to give actionable advice when it is supported. Balancing the two takes dedicated training.

    The right approach, then, is not to scale up a general model, but to align a suitable base model to the domain. A lightweight base model offers clear engineering benefits: low inference cost, support for private deployment, and suitability for high-frequency calls, while high-quality domain data closes the gap in professional capability.

    2. Two-Stage Training: Domain-Intermediate Training and RL Post-Training

    2.1 Domain-Intermediate Training

    The goal of intermediate training is to teach the model the feel and structure of legal language, not to memorize specific cases. Key practices include:

    • Corpus layering: tier legal statutes, judicial documents, contract templates, and compliance manuals by trustworthiness and recency so that low-quality text does not dilute the signal.
    • Deduplication and decontamination: strictly isolate evaluation sets to prevent evaluation data from leaking into training data and inflating metrics.
    • Long-context adaptation: introduce long-document concatenation and position-encoding extrapolation during training so the model can reliably handle very long contracts at inference time.

    A schematic data-processing flow:

    1. def build_domain_corpus(raw_docs, eval_blocklist):
    2. docs = [d for d in raw_docs if not hit_blocklist(d, eval_blocklist)]
    3. docs = dedup_by_minhash(docs, threshold=0.85)
    4. docs = sort_by_trust_and_recency(docs)
    5. return chunk_with_overlap(docs, max_len=32768, overlap=512)

    2.2 RL Post-Training

    Intermediate training addresses knowing; post-training addresses doing it right. Legal tasks are hard to score with a single scalar, so a composite reward is usually needed:

    • Rule-based reward: whether clause citations are accurate, whether revision suggestions land on specific locations, and whether the output format is parseable.
    • Model-based reward: a stronger review model scores the legality and actionability of suggestions.
    • Abstention reward: a positive reward for correctly abstaining when evidence is insufficient, and a negative reward for fabrication.

    A simplified reward aggregation:

    1. def reward(citation_ok, format_ok, review_score, should_abstain, abstained):
    2. r = 0.4 * citation_ok + 0.2 * format_ok + 0.4 * review_score
    3. if should_abstain:
    4. r += 0.5 if abstained else -0.5
    5. return r

    The value of this design is that it turns traceability into an objective the model must optimize, rather than an after-the-fact check.

    3. Evaluation: Why Task Pass Rate Matters More Than Accuracy Alone

    Legal workflows are sequential: reviewing a contract means first locating risky clauses, then proposing revisions, and finally producing a reviewable redline. If any step fails, the whole deliverable is unusable. That is why industry evaluations report two dimensions:

    • Task pass rate: a task counts as passed only when every sub-step is correct, which measures end-to-end usability.
    • Accuracy: the proportion of correct single-point judgments, which measures baseline capability.

    Optimizing accuracy alone encourages models that are strong at single points but unusable overall. The safer engineering practice is to decompose the evaluation set into multi-step tasks that mirror real workflows and attach an automatically checkable validator to each step. For example:

    1. def evaluate(task):
    2. steps = [locate_clause, assess_risk, propose_revision, format_track_changes]
    3. results = [step.run(task) for step in steps]
    4. return all(results), sum(results) / len(results)

    Evaluation should also cover multiple document types (procurement, labor, confidentiality, compliance) and multiple risk levels, and keep a human spot-check step so that automated metrics do not drift away from real user experience.

    4. Delivery: Embedding Model Capabilities into Document Workflows

    The last mile of model capability is the office application. A practical path is to package the model as a document intelligence service, invoked through a plugin or a desktop assistant, that generates revisions and comments in place within the document instead of making users copy and paste. Key design points:

    1. Structured parsing: parse the document into a tree of paragraphs, clauses, and tables, and assign a stable identifier to each node so revision locations can be pinpointed.
    2. Dual-channel diff presentation: present suggestions through both track changes and comments explaining the rationale. Track changes carry what to change; comments carry why.
    3. Rollback: keep all suggestions in draft state and write them into the body only after the user accepts or rejects them, preserving human final review.
    4. Audit trail: record the model version, prompt version, and sources relied on to meet compliance audit requirements.

    A schematic, vendor-neutral interface abstraction:

    1. class DocReviewService:
    2. def parse(self, file_bytes): ...
    3. def review(self, doc_tree, ruleset): ...
    4. def apply(self, doc_tree, suggestions, mode="track_changes"): ...

    5. Deployment and Governance: Closing the Loop with General Cloud Capabilities

    Private deployment is a common requirement among legal customers. A closed loop can be built from general cloud product categories: object storage holds desensitized corpora and model artifacts; a container platform hosts inference services and scales them elastically; a message queue smooths out bursts of traffic from batch contract review; logging, monitoring, and alerting track latency, failure rate, and abstention rate; and key management plus access control prevent unauthorized data access. Baidu AI Cloud offers corresponding capabilities in these general categories, so enterprises can bring model services into a unified operations system.

    For governance, three gates are recommended: desensitization of sensitive information on the input side, retrieval of supporting evidence and citation validation on the inference side, and human review with an audit trail on the output side. Missing any one of them lets suggestions that merely look correct enter the formal process.

    6. Common Pitfalls and Engineering Recommendations

    • Pitfall 1: treating parameter count as a capability metric. Legal scenarios care more about data quality and alignment strategy, and a lightweight base model paired with high-quality domain data is often the better investment.
    • Pitfall 2: pursuing full automation. A sensible positioning is a copilot: the human makes the final judgment while the model handles locating, drafting, and explaining.
    • Pitfall 3: ignoring recency. Regulations change frequently, so a regular cadence for corpus updates and model iteration is needed.
    • Pitfall 4: mixing evaluation and training sets. Strict isolation is mandatory, or the metrics cannot be trusted.

    Overall, the value of a legal vertical model is not to replace legal practitioners but to compress repetitive, retrieval-heavy, and formatting work down to minutes, so professional judgment concentrates where people are truly needed. Releasing in an open-source way and inviting professional users to help refine it is currently a mainstream and effective iteration path.