Baseline44
AI for Business

Building Sheria Bot: Engineering a Grounded RAG System for Kenyan Law

How I built Sheria Bot, a grounded RAG system for Kenyan law — hybrid retrieval, citation verification, evaluation, and fail-safe design in TypeScript.

By Alex NjorogePublished 7 min read

I've been building Sheria Bot, a Retrieval-Augmented Generation (RAG) application designed to help Kenyans understand their legal rights through plain-language questions, with answers grounded in actual Kenyan legislation.

Think questions like:

  • Can a police officer search my vehicle without a warrant?
  • What are my rights when arrested?
  • Can I be detained without being informed of the reason?

The interesting part wasn't getting an LLM to answer these questions. It was engineering a system that knows when it has sufficient evidence to answer, how to retrieve that evidence, and when it should refuse to generate an answer.

Here's how I approached the architecture.

1. Architecture: why I didn't use LangChain

I deliberately chose not to use LangChain. Instead, I implemented the orchestration pipeline myself in TypeScript.

Not because frameworks are inherently bad, but because I wanted direct control over:

  • Retrieval strategies and ranking.
  • Embedding generation.
  • Context construction.
  • Model selection and provider fallbacks.
  • Structured generation and validation.
  • Citation verification.
  • Failure handling, observability and evaluation.

The result is a modular architecture where each stage has a clearly defined responsibility.

Core stack:

  • Next.js 16 App Router
  • TypeScript
  • PostgreSQL + pgvector
  • Gemini Embedding API
  • Groq for LLM inference and classification
  • OpenRouter as an additional generation fallback
  • Zod for runtime validation
  • Reciprocal Rank Fusion (RRF)
  • Jina / Cohere-compatible reranking
  • No separate vector database or orchestration framework.

2. The indexing pipeline

Before a question can be answered, the legal corpus needs to be prepared.

I implemented an offline ingestion pipeline:

  1. Source Kenyan legislation from official legal documents.
  2. Extract PDF content into reviewable Markdown.
  3. Clean extraction artefacts, headers, footers and OCR inconsistencies.
  4. Identify legal boundaries such as Articles, Sections, Parts and Subsections.
  5. Chunk documents according to their legal structure.
  6. Infer topic tags for individual chunks.
  7. Generate embeddings.
  8. Persist the chunks, metadata and vectors in PostgreSQL.

One important design decision was semantic chunking around legal provisions rather than arbitrary token windows.

A legal provision is a bounded unit of meaning. Splitting it indiscriminately can remove qualifications or conditions that fundamentally change its interpretation.

I also implemented content hashing, duplicate detection and transactional document replacement to make ingestion safe and repeatable.

Embedding strategy

I chose Google's gemini-embedding-001, using 768-dimensional embeddings.

An important detail is the distinction between embedding task types:

  • RETRIEVAL_DOCUMENT for indexed legal provisions.
  • RETRIEVAL_QUERY for incoming user questions.

Both use the same embedding model, preserving compatibility between indexed documents and live queries.

Pure vector similarity is not sufficient for legal information retrieval.

A question mentioning Article 49 or Section 36 should be able to retrieve that exact provision, even when its wording differs from the user's question.

I implemented three retrieval mechanisms:

A. Dense vector retrieval

pgvector cosine similarity identifies semantically related legal provisions.

B. Sparse retrieval

PostgreSQL full-text search using tsvector, weighted section references and document content, with GIN indexing. This helps retrieve exact terminology, statutory references and legal phrases.

C. Explicit citation retrieval

A dedicated shortcut recognizes references such as Article 49, Section 36 and Cap 403.

The three ranked lists are combined using Reciprocal Rank Fusion (RRF), with k=60.

The system then:

  1. Retrieves up to 15 vector candidates.
  2. Retrieves up to 15 full-text candidates.
  3. Fuses the results into 12 candidates.
  4. Optionally reranks them using a cross-encoder.
  5. Applies a grounding threshold.
  6. Enforces provision diversity.
  7. Selects the final four passages.

The reranker is provider-agnostic, supporting Jina, Cohere, an LLM-based option or no reranker. If a reranker is unavailable, the system falls back to RRF.

4. Generation pipeline: grounding before generation

Retrieval alone doesn't guarantee reliable answers.

The generation pipeline receives only the provisions that survive retrieval and grounding checks.

The system constructs a constrained prompt containing:

  • The user's question.
  • Retrieved legal provisions.
  • Source references.
  • Relevant conversational context.
  • Explicit instructions against answering beyond the supplied evidence.
  • A predefined JSON response schema.

Generation uses a provider fallback chain:

Groq (gpt-oss-120b) → Groq (gpt-oss-20b) → Gemini Flash Lite → OpenRouter.

The generated response must satisfy a Zod schema before it can reach the client. If validation fails, the system attempts one repair.

5. Hallucination mitigation and citation verification

This was one of the most important engineering challenges.

I approached it through multiple independent safeguards rather than relying on prompt engineering alone.

Retrieval confidence gate

If retrieved passages fail the configured grounding threshold, the system refuses to generate an answer.

Ambiguity handling

If classification or retrieval indicates uncertainty, Sheria Bot asks a clarifying question instead of guessing. This path makes zero generation calls.

Structured output validation

Zod validates the generated response against the expected schema.

Citation verification

I implemented a separate verification stage that checks whether cited legal provisions actually exist in the retrieved context.

Unsupported claims and citations are removed. If nothing reliable survives, the answer is withheld. A repair generation can also be attempted.

An important distinction: citation matching is currently provision-level, not full semantic entailment verification. A valid citation does not automatically prove every statement attached to it is legally correct. That's an area I'm continuing to improve.

6. Evaluation and testing

I didn't want to rely on a few successful manual prompts to conclude that the system worked.

I built an evaluation harness with a 30-question golden dataset:

  • 24 in-scope questions.
  • 6 out-of-scope questions.
  • English, Swahili and Sheng variations.

The harness supports retrieval-only and full-pipeline evaluation. Metrics include:

  • Retrieval Hit@K.
  • Overall pass rate.
  • Out-of-scope refusal correctness.
  • Citation validity.
  • Average latency.
  • Token consumption per request.

Recorded evaluation results:

  • 96.7% overall pass rate (29/30).
  • 95.8% in-scope pass rate.
  • 95.8% retrieval Hit@4.
  • 100% out-of-scope refusal.
  • 100% mechanical citation validity.
  • 930.5 average tokens per request.
  • 2.9 seconds average latency.

The evaluation used Gemini Flash Lite because the configured Groq API key had expired. The Groq generation path still needs a fresh-key evaluation.

I also implemented 78 automated unit tests covering chunking, citation matching, retrieval fusion, ranking, provider fallbacks, retry logic, ambiguity handling, citation verification, caching and rate limiting.

Type checking and linting also pass.

These results are from a 24-chunk seed corpus, not the complete legislation corpus. They are an engineering baseline, not proof of production-grade legal accuracy.

7. Beyond RAG: production considerations

I also implemented several supporting systems:

  • PostgreSQL-backed rate limiting across users, IPs and shared provider budgets.
  • Answer caching with SHA-256 keys, corpus versioning and a 24-hour TTL.
  • Cross-provider fallback and retry handling.
  • Generation observability tracking model, provider, latency and token usage.
  • Account-based authentication and saved conversations.
  • Admin document ingestion and usage dashboards.
  • Live pipeline progress using NDJSON events.

An interesting implementation decision: the model generates and validates the complete structured answer before the application streams its sections to the client.

This preserves citation verification before displaying the answer, rather than streaming unverified model tokens.

8. What I'm learning from this project

Building Sheria Bot has reinforced something important:

RAG engineering is not simply connecting an embedding model to a vector database and passing retrieved text into an LLM.

The difficult engineering work is in the boundaries between components:

  • How do you preserve meaning during chunking?
  • How do you combine semantic and lexical retrieval?
  • How do you distinguish weak relevance from sufficient grounding?
  • How do you prevent unsupported citations?
  • How do you handle provider failures?
  • How do you measure retrieval quality independently of generation quality?
  • How do you make a system fail safely?

These are architectural decisions, not prompt-engineering tricks.

The next steps: expanding and reviewing the legal corpus, enabling and evaluating the cross-encoder reranker, improving semantic claim verification, and conducting broader end-to-end testing.

Sheria Bot is an ongoing engineering project, but it's been an excellent opportunity to explore the intersection of RAG, LLM infrastructure, information retrieval, distributed application design and AI safety.

Building a grounded AI system? Explore Baseline44 AI solutions, our AI automation work, or contact the team.

Need this for your business?

Book a free consultation and we'll map it to your situation.

Book a consultation
AN
AI and Software Engineer

I'm Alex Njoroge, an AI and software engineer at Baseline44. I build grounded AI systems, retrieval pipelines and production software for organisations in Kenya, and I write about the engineering decisions behind projects like Sheria Bot.

Frequently asked questions

What is Sheria Bot?
Sheria Bot is a Retrieval-Augmented Generation (RAG) application that answers plain-language questions about Kenyan law using retrieved provisions from Kenyan legislation. It is an ongoing engineering project, not a substitute for advice from a qualified lawyer.
Why did you not use LangChain?
I wanted direct control over retrieval strategies, context construction, provider fallbacks, structured validation and citation verification, so the orchestration pipeline is implemented in TypeScript.
Why use hybrid retrieval instead of vector search alone?
Legal questions often contain explicit references such as Article 49 or Section 36. Dense vector search finds semantically related provisions, while PostgreSQL full-text search and an explicit citation shortcut retrieve exact statutory references. The ranked lists are combined with Reciprocal Rank Fusion.
How does Sheria Bot reduce hallucinations?
It applies a retrieval confidence threshold, asks a clarifying question when evidence is ambiguous, validates structured output with Zod, and verifies that cited provisions exist in the retrieved context. Unsupported claims and citations are removed; if nothing reliable survives, the answer is withheld.
What evaluation results were recorded?
On a 30-question golden dataset and a 24-chunk seed corpus, the recorded results were a 96.7% overall pass rate, 95.8% in-scope pass rate, 95.8% retrieval Hit@4, 100% out-of-scope refusal, 100% mechanical citation validity, 930.5 average tokens per request, and 2.9 seconds average latency. These are an engineering baseline, not proof of production-grade legal accuracy.