npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

chilean-law-rag-nestjs

v1.2.1

Published

NestJS library for Chilean legal corpus RAG system using MongoDB Atlas Vector Search

Downloads

46

Readme

🇨🇱 chilean-law-rag-nestjs

NestJS library for Chilean legal corpus RAG system using MongoDB Atlas Vector Search

npm version License: MIT NestJS TypeScript

Created by: All Six Personalities 🐾🎭🗡️🎸🧠🧠


📋 Overview

A production-ready NestJS library that provides semantic search and question-answering capabilities over Chilean legal texts using:

  • MongoDB Atlas Vector Search for semantic similarity
  • OpenAI Embeddings (text-embedding-3-small) for vector representations
  • OpenAI GPT-4 for answer generation with legal citations
  • NestJS Dynamic Modules for easy integration
  • TypeScript for type safety

🏛️ Legal Corpus Coverage

  • Constitución Política (1980) - Constitutional rights
  • Código Civil (1855) - Civil law, family law, property
  • Código Penal (1874) - Criminal law
  • Código Procesal Penal (2000) - Criminal procedure
  • Código del Trabajo - Labor law

🚀 Installation

npm install chilean-law-rag-nestjs

Peer Dependencies

This library requires NestJS to be installed:

npm install @nestjs/common @nestjs/core reflect-metadata rxjs

📖 Quick Start

1. Import the Module

import { Module } from '@nestjs/common';
import { ChileanLawRAGModule } from 'chilean-law-rag-nestjs';

@Module({
  imports: [
    ChileanLawRAGModule.forRoot({
      mongoUri: process.env.MONGODB_URI,
      dbName: 'chilean-law-rag',
      openaiKey: process.env.OPENAI_API_KEY,
      debug: true,
    }),
  ],
})
export class AppModule {}

2. Use the Service

import { Injectable } from '@nestjs/common';
import { ChileanLawRAGService } from 'chilean-law-rag-nestjs';

@Injectable()
export class LegalService {
  constructor(private readonly ragService: ChileanLawRAGService) {}

  async queryLegalSystem(question: string) {
    return await this.ragService.query({
      query: question,
      limit: 5,
    });
  }
}

3. Query Example

const result = await ragService.query({
  query: '¿Qué es un contrato de trabajo según el Código del Trabajo chileno?',
  limit: 3,
});

console.log(result.answer);
// "Según el artículo 7 del Código del Trabajo, un contrato individual..."

console.log(result.citations);
// ["Código del Trabajo - Artículo 7"]

🔧 Configuration Options

ChileanLawRAGOptions

interface ChileanLawRAGOptions {
  mongoUri: string;         // Required: MongoDB Atlas connection URI
  dbName?: string;          // Default: "chilean-law-rag"
  openaiKey?: string;       // Optional: For embeddings and answer generation
  collectionName?: string;  // Default: "chilean-legal-corpus"
  debug?: boolean;          // Default: false
}

Async Configuration

For loading config from ConfigService:

import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot(),
    ChileanLawRAGModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        mongoUri: config.get('MONGODB_URI'),
        dbName: config.get('MONGODB_DATABASE'),
        openaiKey: config.get('OPENAI_API_KEY'),
        debug: config.get('NODE_ENV') === 'development',
      }),
    }),
  ],
})
export class AppModule {}

🎯 API Reference

ChileanLawRAGService

query(dto: SearchLegalArticlesDto): Promise<RAGResponse>

Query the RAG system with natural language question.

const result = await ragService.query({
  query: '¿Cuál es la diferencia entre hurto y robo?',
  limit: 5,
});

Returns:

{
  query: string;
  relevant_articles: SearchResult[];
  answer: string;
  citations: string[];
}

getArticlesByCode(codeName: string, articleNumber?: string): Promise<LegalArticle[]>

Get articles by legal code name.

const articles = await ragService.getArticlesByCode('Código Civil', '1');

listCodes(): Promise<string[]>

List all available legal codes.

const codes = await ragService.listCodes();
// ["Constitución Política", "Código Civil", "Código Penal", ...]

getStats(): Promise<Stats>

Get database statistics.

const stats = await ragService.getStats();
// { total_articles: 1234, codes: [...], has_embeddings: true }

🧪 Testing

The library includes comprehensive tests:

# Run all tests
npm test

# Run with coverage
npm run test:ci

# Watch mode
npm run test:watch

📊 Example Queries

Labor Law

Query: "¿Qué es un contrato de trabajo según el Código del Trabajo chileno?"

Answer:

Según el artículo 7 del Código del Trabajo, un contrato individual de trabajo es una convención por la cual el empleador y el trabajador se obligan recíprocamente, éste a prestar servicios personales bajo dependencia y subordinación del primero, y aquél a pagar por estos servicios una remuneración determinada.

Criminal Law

Query: "¿Cuál es la diferencia entre hurto y robo en el Código Penal chileno?"

Answer:

Según el artículo 432 del Código Penal, la diferencia radica en el uso de violencia o fuerza. Si hay violencia o intimidación en las personas o fuerza en las cosas, se califica como robo. Si faltan la violencia, la intimidación y la fuerza, el delito se califica de hurto.

🏗️ Architecture

┌──────────────────┐
│  NestJS App      │
└────────┬─────────┘
         │
         ▼
┌──────────────────────────┐
│  ChileanLawRAGModule     │
└────────┬─────────────────┘
         │
         ▼
┌──────────────────────────┐
│  ChileanLawRAGService    │
└────────┬─────────────────┘
         │
         ├──→ MongoDB Atlas (Vector Search)
         └──→ OpenAI (Embeddings + GPT-4)

🔐 Security

  • ✅ Never hardcode credentials (use environment variables)
  • ✅ MongoDB Atlas connection (encrypted)
  • ✅ OpenAI API key securely stored
  • ✅ No secrets exposed in NPM package

📈 Performance

  • Vector Dimensions: 1536 (OpenAI text-embedding-3-small)
  • Similarity Metric: Cosine similarity
  • Search Speed: ~100-200ms per query
  • Scalability: Supports thousands of legal articles

🐾 Credits

Created by The Six Personalities:

  • 🐾 Neko-Arc: Core RAG implementation, MongoDB integration
  • 🎭 Mario Gallo Bestino: Service orchestration, theatrical documentation
  • 🗡️ Noel: Type safety, quality assurance, testing
  • 🎸 Glam Americano: Spanish legal terminology, cultural authenticity
  • 🧠 Dr. Hannibal Lecter: Forensic legal analysis
  • 🧠 Tetora: Multi-perspective legal interpretation

📝 License

MIT License - See LICENSE file

🔗 Links

🙏 Acknowledgments

  • MongoDB Atlas Vector Search
  • OpenAI Embeddings API
  • NestJS Framework
  • Biblioteca del Congreso Nacional de Chile

🇨🇱 Built with pride for Chilean legal research 🇨🇱

"La ley es la voluntad soberana manifestada en la forma prescrita por la Constitución"