Skip to main content

09 - Building a Legal AI Assistant (Legal Copilot)

A legal assistant with RAG still gets things wrong: how to make it refuse, verify citations and measure it with test cases, with code that was run.

What do you think about this article?

At a Glance

A legal assistant with RAG still gets things wrong: how to make it refuse, verify citations and measure it with test cases, with code that was run.

Building a Legal AI Assistant: RAG, guardrails and verification tests

An assistant that answers legal questions can go wrong in a way that costs a lawyer dearly: citing with confidence a rule that does not say what it is made to say, or a judgment that does not exist. Adding to the model a search engine over the documents (so-called RAG, retrieval-augmented generation) reduces the problem but does not eliminate it. A Stanford study on commercial RAG-based legal research products shows it: the authors find that the LexisNexis and Thomson Reuters tools they evaluated hallucinate between 17% and 33% of the time, less than a generic chatbot but well beyond the vendors' promises (Magesh et al., 2024). The evaluation concerns US tools on questions of American law: it tells you what to expect from the method, not from your corpus.

The consequence for whoever builds is that trust does not come from the model, but from the checks around the model. This article is made of those checks: how to split a legal text without breaking the articles, how to decide not to answer, how to verify in code that a citation really exists and that a sentence has support in the sources, and how to measure everything with test cases written by a lawyer. The language model stays out of the listing: all the code can be run without calling one, and the sample answers are written by hand and declared as such. If you need the retrieval piece first, it is in the article on the case-law search engine.

The corpus sets the ceiling of quality

An assistant can cite only what it has in the corpus, and it can be correct only as far as the corpus is up to date. For an Italian use the corpus has four layers, with different problems:

  • Primary legislation in its current version: the official source is Normattiva, and the current version of an article changes over time.
  • European legislation: regulations and directives on EUR-Lex, in Italian, which have a numbering and a structure different from those of the national codes.
  • Case law: judgments that must be identified unambiguously, because the same ruling circulates with several numbers and several citation formats.
  • Acts of authorities and practice: guidelines and circulars, which do not have the value of a law and must be labelled as such.

The criterion that holds the four items together is the hierarchy of sources: the answer must be able to say not only what a source states but what kind of source it is, because a guideline does not weigh like a regulation. For this reason every chunk carries its type and its formal citation, and the citation is the string the model must repeat in the answer. The most underestimated item is the first: a corpus without a version date will answer with confidence even when the rule has changed.

Splitting a legal text without splitting the articles

RAG works on fragments: the text is divided into pieces, and each piece becomes a candidate for retrieval. Splitting at a fixed length is the easy choice and the worst for a statute, because it cuts an article in half and the fragment loses the number that identifies it. It is better to split by article, which is also the unit a lawyer cites.

Here lies a frequent mistake. A regular expression that looks for "article N" at any point, without distinguishing upper and lower case, also fires on the cross-references inside a sentence ("pursuant to Article 6(1)") and splits the articles at points that are not boundaries. The listing compares the two versions on a test text: three articles of the GDPR, abbreviated by me for the example and therefore not the official text. The anchored version looks for the heading only where it stands alone at the start of a line (^Article\s+(\d+)\s*$ with the re.MULTILINE flag, described in the documentation of the re module).

chunker.py - splitting by article: naive version and anchored version
import re

TESTO = """Article 7
Conditions for consent
3. The data subject shall have the right to withdraw his or her consent at any time. It shall be as easy to withdraw as to give consent.
Article 12
Transparent information, communication and modalities
3. The controller shall provide information on action taken on a request to the data subject without undue delay and in any event within one month of receipt of the request. That period may be extended by two further months where necessary, taking into account the complexity and number of the requests.
Article 17
Right to erasure
1. The data subject shall have the right to obtain the erasure of personal data. Pursuant to Article 6(1), the processing must have a legal basis.
"""

# Naive version: looks for "article N" anywhere, even in the middle of a sentence.
NAIVE = re.compile(r"article\s+\d+", re.IGNORECASE)
# Anchored version: an article heading stands alone at the start of a line.
ANCORATO = re.compile(r"^Article\s+(\d+)\s*$", re.MULTILINE)


def spezza_per_articolo(testo: str) -> list[dict]:
    teste = list(ANCORATO.finditer(testo))
    pezzi = []
    for i, m in enumerate(teste):
        fine = teste[i + 1].start() if i + 1 < len(teste) else len(testo)
        pezzi.append({"article": int(m.group(1)), "text": testo[m.end():fine].strip()})
    return pezzi


if __name__ == "__main__":
    print("naive    :", [m.group(0) for m in NAIVE.finditer(TESTO)])
    pezzi = spezza_per_articolo(TESTO)
    print("anchored :", [p["article"] for p in pezzi])
    print("art. 17  :", pezzi[2]["text"].splitlines()[0])

# Output:
# naive    : ['Article 7', 'Article 12', 'Article 17', 'Article 6']
# anchored : [7, 12, 17]
# art. 17  : Right to erasure

The output shows it: the naive search finds four "articles", and the last one is the cross-reference "Article 6" inside the text of article 17, which would have produced a meaningless fragment. The anchored version finds three and the text of article 17 starts from its heading. The limit of the approach is that it depends on the format in which you hold the text: if the source puts "Art. 17" on the same line as the content, the anchor does not fire and another rule is needed. For this reason a chunker for legal texts must be tried on the real format of each source, not assumed. Long articles are still subdivided, but inside the article and, where possible, by paragraph, repeating the article number at the head of every fragment.

Deciding not to answer, before calling a model

The first guardrail is also the cheapest: if retrieval found nothing relevant, the honest answer is "I have no sources to answer", and there is no need to consult the model. A model given a poor context tends to fill the gap with what it already "knows", and this is exactly the case to avoid. The function deve_rifiutare ("must refuse") relies on a relevance score produced by retrieval: with no sources it refuses, and it also refuses if the best one is below a threshold. The threshold of 0.4 in the listing is an example value: it depends on your retrieval and must be tuned on your corpus, looking at the cases where the system wrongly refuses or wrongly answers.

There is a second kind of refusal, one of scope: questions that ask for an opinion on a personal case ("can I win the case?") are not a search for sources. In a real system you recognise them with a classifier and handle them with a message that refers to a professional; the regular expressions you see in examples are fragile, because the same request is written in a thousand ways, and for this reason I have not put them in the listing.

Checking the answer: true citations and sentences with support

After generation two checks are needed, both in code and without a model. The first verifies that every [Source: ...] citation in the answer is one of those that retrieval returned: a citation that is not among the sources supplied is, by definition, invented. It is the check with the best ratio between cost and value, because a false citation is the defect a lawyer does not forgive. The second looks for sentences without support: for each sentence it counts how many significant words appear in the texts of the sources, and flags those below a minimum share.

The second check is deliberately crude, and it is worth saying so at once. It measures word overlap, not meaning: a sentence that uses the words of the source but reverses its sense gets through. The alternative that is often proposed, the similarity between sentence vectors with a threshold, is more sophisticated but has the same limit and, in addition, a threshold that seems scientific without being so. Better a simple check whose defect you know. The listing tests it on a grounded answer, one with a false citation, one with an invented sentence and one reversed; the texts are written by hand, and the test source is article 12, paragraph 3, of the GDPR, which I reported in a slightly abbreviated form from the text on EUR-Lex.

copilota.py - refusal, invented citations and sentences without support
import re
from dataclasses import dataclass

STOP = {"that", "with", "from", "shall", "where", "such", "which", "this", "have", "been", "their",
        "into", "taking", "than", "also", "when", "does", "each", "them", "those", "these"}


@dataclass(frozen=True)
class Fonte:
    citazione: str      # the label the model must repeat, in full
    testo: str
    rilevanza: float    # retrieval score, 0-1


def parole_significative(frase: str) -> set[str]:
    return {p for p in re.findall(r"[a-z]{4,}", frase.lower()) if p not in STOP}


def deve_rifiutare(fonti: list[Fonte], soglia: float = 0.4) -> str | None:
    """The refusal is decided BEFORE calling a model: it costs nothing and cannot invent."""
    if not fonti:
        return "No document in the corpus answers this question."
    migliore = max(f.rilevanza for f in fonti)
    if migliore < soglia:
        return f"The sources found are barely relevant (best: {migliore:.2f})."
    return None


def citazioni_inventate(risposta: str, fonti: list[Fonte]) -> list[str]:
    """Every [Source: ...] must be a citation that retrieval really returned."""
    ammesse = {f.citazione for f in fonti}
    citate = re.findall(r"\[Source:\s*([^\]]+)\]", risposta)
    return [c.strip() for c in citate if c.strip() not in ammesse]


def frasi_non_fondate(risposta: str, fonti: list[Fonte], minimo: float = 0.6) -> list[str]:
    """A sentence is supported if most of its significant words appear in the sources."""
    lessico = set().union(*(parole_significative(f.testo) for f in fonti)) if fonti else set()
    risultato = []
    for frase in re.split(r"(?<=[.!?])\s+", re.sub(r"\[Source:[^\]]*\]", "", risposta)):
        parole = parole_significative(frase)
        if len(parole) >= 4 and len(parole & lessico) / len(parole) < minimo:
            risultato.append(frase.strip())
    return risultato


def esamina(risposta: str, fonti: list[Fonte]) -> dict:
    return {"invented_citations": citazioni_inventate(risposta, fonti),
            "unsupported_sentences": frasi_non_fondate(risposta, fonti)}


FONTI = [
    Fonte("GDPR art. 12(3)",
          "The controller shall provide information on action taken on a request to the data "
          "subject without undue delay and in any event within one month of receipt of the "
          "request. That period may be extended by two further months where necessary, taking "
          "into account the complexity and number of the requests.", 0.91),
]

# Answers written BY HAND to test the checks: they do not come from a model.
RISPOSTA_FONDATA = ("The controller replies in any event within one month of receipt of the request. "
                    "The period may be extended by two further months, taking into account the "
                    "complexity and number of the requests [Source: GDPR art. 12(3)].")
RISPOSTA_CITAZIONE_FALSA = ("The controller replies within one month of receipt of the request "
                            "[Source: GDPR art. 99(1)].")
RISPOSTA_CON_INVENZIONE = ("The controller replies in any event within one month of receipt of the request "
                           "[Source: GDPR art. 12(3)]. Failure to comply always results in an "
                           "administrative fine of twenty thousand euros.")

# A false sentence made of the source's own words: the lexical check does NOT see it.
RISPOSTA_CAPOVOLTA = ("The controller does not provide the information within one month of receipt of the "
                      "request, because the period is two months [Source: GDPR art. 12(3)].")

if __name__ == "__main__":
    print("refusal, no sources    :", deve_rifiutare([]))
    print("refusal, weak source   :", deve_rifiutare([Fonte("X", "text", 0.2)]))
    print("refusal, good source   :", deve_rifiutare(FONTI))
    for nome, r in [("grounded", RISPOSTA_FONDATA), ("false citation", RISPOSTA_CITAZIONE_FALSA),
                    ("with invention", RISPOSTA_CON_INVENZIONE),
                    ("flipped", RISPOSTA_CAPOVOLTA)]:
        print(f"{nome:16}:", esamina(r, FONTI))

# Output:
# refusal, no sources    : No document in the corpus answers this question.
# refusal, weak source   : The sources found are barely relevant (best: 0.20).
# refusal, good source   : None
# grounded        : {'invented_citations': [], 'unsupported_sentences': []}
# false citation  : {'invented_citations': ['GDPR art. 99(1)'], 'unsupported_sentences': []}
# with invention  : {'invented_citations': [], 'unsupported_sentences': ['Failure to comply always results in an administrative fine of twenty thousand euros.']}
# flipped         : {'invented_citations': [], 'unsupported_sentences': []}

Read the output line by line. With no sources and with a weak source (relevance 0.20) the system refuses and says why; with the good source it returns None, meaning "go ahead". The grounded answer passes both checks. The citation to article 99 is intercepted by the first check, which does not look at the text but only at the label. The sentence about the fine of twenty thousand euros, which I wrote as an example of invention, is flagged by the second. The last line is the defect: the reversed answer passes both checks. For this reason the second check is not enough on its own, and the next step is not a more complicated check but a set of test cases with forbidden claims written by a lawyer.

Measuring: test cases with an expected answer

A legal assistant is not measured by user satisfaction, but by a set of questions for which a lawyer has fixed what must appear (which citations) and what must never appear (which false claims). The listing reuses the checks above and adds the two measures that depend on the lawyer: the recall of the expected citations and the count of forbidden claims. There are three cases, one for each type of defect, and they serve only to show the mechanism: a serious test needs many more, chosen by someone who knows the subject.

valutazione.py - test cases with expected citations and forbidden claims
import statistics
from dataclasses import dataclass

from copilota import (FONTI, RISPOSTA_CAPOVOLTA, RISPOSTA_CON_INVENZIONE,
                      RISPOSTA_FONDATA, esamina)


@dataclass(frozen=True)
class Caso:
    domanda: str
    risposta: str                  # in a real test: the system's own answer
    citazioni_attese: tuple[str, ...]
    affermazioni_vietate: tuple[str, ...]   # known falsehoods, decided by a lawyer


def valuta(caso: Caso) -> dict:
    testo = caso.risposta.lower()
    attese = sum(1 for c in caso.citazioni_attese if c.lower() in testo)
    vietate = sum(1 for a in caso.affermazioni_vietate if a.lower() in testo)
    esame = esamina(caso.risposta, FONTI)
    return {
        "citation_recall": attese / len(caso.citazioni_attese),
        "forbidden_claims": vietate,
        "invented_citations": len(esame["invented_citations"]),
        "unsupported_sentences": len(esame["unsupported_sentences"]),
    }


CASI = [
    Caso("By when must a request be answered?", RISPOSTA_FONDATA,
         ("GDPR art. 12(3)",), ("twenty thousand euros",)),
    Caso("By when must a request be answered?", RISPOSTA_CON_INVENZIONE,
         ("GDPR art. 12(3)",), ("twenty thousand euros",)),
    Caso("By when must a request be answered?", RISPOSTA_CAPOVOLTA,
         ("GDPR art. 12(3)",), ("does not provide",)),
]

if __name__ == "__main__":
    righe = [valuta(c) for c in CASI]
    for i, r in enumerate(righe, 1):
        print(i, r)
    print("average recall :", round(statistics.mean(r["citation_recall"] for r in righe), 2))
    print("cases with a forbidden claim:", sum(1 for r in righe if r["forbidden_claims"]))
    print("cases with unsupported sentences:", sum(1 for r in righe if r["unsupported_sentences"]))

# Output:
# 1 {'citation_recall': 1.0, 'forbidden_claims': 0, 'invented_citations': 0, 'unsupported_sentences': 0}
# 2 {'citation_recall': 1.0, 'forbidden_claims': 1, 'invented_citations': 0, 'unsupported_sentences': 1}
# 3 {'citation_recall': 1.0, 'forbidden_claims': 1, 'invented_citations': 0, 'unsupported_sentences': 0}
# average recall : 1.0
# cases with a forbidden claim: 2
# cases with unsupported sentences: 1

Case 1 is clean. In case 2 the lexical check and the list of forbidden claims find the same invention by two different routes. In case 3 the reversed answer has unsupported_sentences: 0, but forbidden_claims: 1: it is the lawyer's list, not the automatic check, that catches it. The recall of the citations is 1.0 in all three, and it is the most uncomfortable lesson: an answer can cite the right source and say something false, so recall alone does not measure correctness. The three measures must be read together, and none of the three replaces review by a person.

Streaming, logging and responsibility

Showing the answer as it arrives makes the interface more responsive, but here it has a price: the checks above can be done only on the complete answer, so the first tokens reach the user before they have been verified. There are two ways: show the text in streaming with an explicit "unverified draft" label and update it when the check ends, or give up streaming for legal answers. For a professional who cites what they read, I would choose the second until there is a clearly visible label.

Logging questions and answers serves to redo the checks and to respond to a dispute, but a lawyer's questions may contain client data: the log is itself a processing of personal data, with a purpose, a retention period and restricted access, as you can see in the GDPR compliance system of the series. And every answer carries a clear notice: the assistant searches and summarises sources, it does not provide legal advice. If you want to offer it to the public and not only to your collaborators, the question of who may offer which service is a question for a lawyer, not for this article.

What you can do now

You can split a legal text by article without confusing cross-references with headings, you can make the system refuse before spending a call on a model, and you can verify in code that the citations of an answer exist and that the sentences have support, knowing the defect of this second check. Above all you know what none of the three does: it does not decide whether an answer is legally right. The rest of the series, from the data integration patterns to the summarisation of legal documents, serves to bring the right documents up to this point.

Sources

The listings were run with Python 3.14 and do not call any language model: the answers are written by hand. The relevance threshold and the minimum share of words are example values to be tuned on your own corpus.

Frequently asked questions

Does RAG eliminate hallucinations in a legal assistant?

No. A Stanford study on commercial RAG-based legal research tools found hallucinations between 17% and 33% of the time: less than a generic chatbot, but not zero. Additional checks and human review are needed.

Why make the system refuse before calling the model?

Because a model with little context tends to fill the gap with what it already knows. If retrieval finds no relevant sources, refusing costs nothing and cannot invent anything.

How do you verify that a citation is not invented?

You compare every citation in the answer with the list of sources returned by retrieval: a citation that is not in that list is invented. The check is deterministic, but it does not verify that the source says what the answer attributes to it.

Can an assistant of this kind give legal advice?

Not here: it searches and summarises sources and says so in every answer. Whether and how to offer it to third parties as a service is a question to put to a lawyer.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects