Skip to article

Applied AIExample

Building a RAG assistant on a regulatory corpus

Chunking, hybrid search and citations: the steps for an assistant to answer from official texts.

An assistant that answers from a regulatory corpus has two jobs: find the right passages, then answer without making anything up. Retrieval-augmented generation, or RAG, organises this work into steps that can be tested separately.

Why RAG

A language model on its own does not know the latest texts and cannot cite its sources. By giving it the relevant extracts of the corpus with each question, you get answers that can be checked: every statement points to a specific article.

Chunking the corpus

Follow the structure of the text

A tax code or a law is already split into articles, paragraphs and tables. Chunking along that structure keeps each passage coherent and lets you cite "article 12, paragraph 3" instead of a page number.

Choose the chunk size

Chunks that are too short lose context; too long, they dilute the search. A few hundred words, with a small overlap, is a good starting point.

SizeBenefitRisk
ShortPrecise searchLost context
MediumGood balanceNeeds tuning per corpus
LongFull contextIrrelevant passages retrieved

Combining two searches

Vector search finds passages that are close in meaning; keyword search finds exact terms, such as an article number or a tax name. Merging both rankings keeps the best of each.

ts
type Passage = { id: string; score: number };

/** Merge two rankings (Reciprocal Rank Fusion). */
export function fuse(vectors: Passage[], keywords: Passage[], k = 60): Passage[] {
  const scores = new Map<string, number>();
  for (const list of [vectors, keywords]) {
    list.forEach((p, rank) => scores.set(p.id, (scores.get(p.id) ?? 0) + 1 / (k + rank + 1)));
  }
  return [...scores].map(([id, score]) => ({ id, score })).sort((a, b) => b.score - a.score);
}

Citing sources

The instructions given to the model require it to answer only from the extracts provided and to cite the source article for each statement. If no extract answers the question, the assistant must say so rather than guess.

Evaluating the assistant

You prepare a list of questions whose answer and source article you know, then measure two things separately: did the search find the right article, and is the answer faithful to it?

  • Search recall: share of questions where the right passage is among the top results.
  • Faithfulness: share of answers fully supported by the quoted passages.

Share the article