मुख्य सामग्री पर जाएँ

Django में MongoDB ऑटो-एंबेडिंग्स के साथ Q&A असिस्टेंट बनाना

MongoDB ऑटो-एंबेडिंग्स के साथ Django में सेमांटिक सर्च बनाएं: बिना एंबेडिंग कोड, दस्तावेज़ बदलने पर स्वतः री-सिंक, और सादा-पाठ क्वेरियाँ।
· 7 मि॰ पढ़ें

AI के साथ खोजें

ऑटो-एंबेडिंग्स क्या सरल बनाती हैं

एक सामान्य Retrieval-Augmented Generation (RAG) सेटअप में, आप दस्तावेज़ डालते समय एंबेडिंग्स बनाते हैं, सामग्री बदलने पर उन्हें फिर से बनाते हैं, और हर क्वेरी को स्वयं एंबेड करते हैं। Automated Embedding सेमांटिक सर्च बनाने की प्रक्रिया को सरल बनाती है, क्योंकि MongoDB Atlas एंबेडिंग जनरेशन, अपडेट्स और क्वेरिंग को नेटिव रूप से संभालता है, और Vector Search आपके क्लस्टर पर जनरेट की गई वेक्टर एंबेडिंग्स को स्टोर करता है।

MongoDB ऑटोमैटिक एंबेडिंग कैसे करता है

जब autoEmbed प्रकार का एक वेक्टर सर्च इंडेक्स बनाया जाता है, तो MongoDB चुने गए फ़ील्ड के लिए एंबेडिंग्स जनरेट करता है, VoyageAI मॉडल का उपयोग करता है, दस्तावेज़ में बदलाव होने पर उन्हें सिंक में रखता है, और क्वेरी के समय उसी मॉडल से क्वेरी टेक्स्ट को एंबेड करता है। बनी हुई एंबेडिंग्स MongoDB क्लस्टर पर एक अलग आंतरिक डेटाबेस में असिंक्रोनस रूप से स्टोर होती हैं।

इस ट्यूटोरियल में, हम MongoDB ऑटोएंबेडिंग्स के साथ एक Q&A Docs असिस्टेंट बनाएंगे। मॉडल्स परिभाषित करने और दस्तावेज़ इनजेस्ट करने के लिए Django MongoDB बैकएंड का उपयोग होगा, और लुकअप्स, एंबेडिंग्स के स्वतः जनरेशन और सिंकिंग के लिए MongoDB का। LLM प्राप्त परिणामों के आधार पर दस्तावेज़ वापस करेगा।

ट्यूटोरियल के अंत तक, आप एक RAG पाइपलाइन का रिट्रीवल चरण बनाएंगे: Federal Register दस्तावेज़ों पर सेमांटिक सर्च, जहाँ ऑटो-एंबेडिंग्स आपके लिए एंबेडिंग का काम संभालती हैं। दस्तावेज़ डालते समय एंबेड होते हैं, बदलने पर फिर से एंबेड होते हैं, और आपकी क्वेरियाँ सर्च टाइम पर एंबेड होती हैं—वह भी बिना एंबेडिंग कोड लिखे।

इस ट्यूटोरियल को फॉलो करने के दो तरीके हैं।

  • विकल्प A: इस ट्यूटोरियल के तैयार कोड वाली GitHub रेपो को क्लोन करें, रेपो के README के अनुसार सेटअप करें, और स्वयं एक्सप्लोर करें। GitHub प्रोजेक्ट का लिंक: https://github.com/mongodb-developer/django-mongodb-regulations-qa
  • विकल्प B: नीचे दिए गए चरणों का पालन करके प्रोजेक्ट को शुरुआत से बनाएं।

सेटअप

शुरू करने से पहले, सुनिश्चित करें कि आपके पास ये हों:

इन पूर्वापेक्षाओं के पूरे हो जाने पर अगला कदम आपका प्रोजेक्ट फ़ोल्डर बनाना है।

प्रोजेक्ट और वर्चुअल एनवायरनमेंट बनाएं

अपने प्रोजेक्ट के लिए एक खाली फ़ोल्डर बनाएं और उसमें cd करें।

mkdir regulations_qa
cd regulations_qa

यह आपके प्रोजेक्ट की रूट डायरेक्टरी है। यहाँ अपना वर्चुअल एनवायरनमेंट बनाएं और सक्रिय करें, यदि पहले नहीं किया है:

python -m venv .venv

macOS या Linux पर वर्चुअल एनवायरनमेंट सक्रिय करने के लिए चलाएँ:

source .venv/bin/activate

Windows पर चलाएँ:

.venv\Scripts\activate

डिपेंडेंसीज़ इंस्टॉल करें

प्रोजेक्ट की रूट पर एक requirements.txt फ़ाइल बनाएँ और इसमें निम्न सामग्री रखें:

# requirements.txt
django-mongodb-backend
python-dotenv
requests #to fetch documents from the Federal Register API.

फिर सब कुछ इंस्टॉल करें:

pip install -r requirements.txt

Django प्रोजेक्ट और Django ऐप बनाएं

अपने प्रोजेक्ट की रूट डायरेक्टरी से, एक नया Django प्रोजेक्ट और ऐप बनाने के लिए निम्न कमांड चलाएँ। startproject कमांड में अंतिम . जोड़ें, जो Django को वर्तमान डायरेक्टरी में ही प्रोजेक्ट इंस्टॉल करने को कहता है, अलग नेस्टेड फ़ोल्डर बनाने के बजाय।

django-admin startproject regulations_qa --template https://github.com/mongodb-labs/django-mongodb-project/archive/refs/heads/6.0.x.zip .

documents ऐप बनाएँ

python manage.py startapp documents

regulations_qa/settings.py में ऐप को INSTALLED_APPS में जोड़कर रजिस्टर करें:

INSTALLED_APPS = [
    'regulations_qa.apps.MongoAdminConfig',
    'regulations_qa.apps.MongoAuthConfig',
    'regulations_qa.apps.MongoContentTypesConfig',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_mongodb_backend',
    'documents',
]

एनवायरनमेंट वेरिएबल्स कॉन्फ़िगर करें

प्रोजेक्ट की रूट पर अपनी मानों के साथ एक .env फ़ाइल बनाएँ, और उसे .gitignore में सूचीबद्ध करें ताकि पुश करते समय यह कमिट न हो।

# .env
SECRET_KEY=[REPLACE_WITH_YOUR_SECRET_KEY]
MONGODB_URI="mongodb+srv://<username>:<password>@<cluster>.mongodb.net/?retryWrites=true&w=majority"
DB_NAME=regulations_qa
VECTOR_INDEX_NAME=autoembed_index

settings.py से मूल हार्डकोडेड SECRET_KEY = '...' लाइन हटा दें, startproject चलाने पर settings.py में Django द्वारा जनरेटेड मान कॉपी करें और उसे अपनी .env फ़ाइल में रखें। यह डिफ़ॉल्ट रूप से वहाँ हार्डकोड रहता है, और हम इसे वर्शन कंट्रोल से बाहर रखने के लिए .env में ले जाते हैं, क्योंकि Django इसका उपयोग सेशन कुकीज़, CSRF टोकन और अन्य सुरक्षा-संवेदनशील डेटा पर साइन करने के लिए करता है।

regulations_qa/settings.py खोलें और सुनिश्चित करें कि इसमें निम्न सभी शामिल हैं। इम्पोर्ट लाइनें और load_dotenv() सबसे ऊपर रखें। मौजूदा SECRET_KEY और DATABASES परिभाषाएँ बदलें, और VECTOR_INDEX_NAME लाइन जोड़ें:

import os
from dotenv import load_dotenv

load_dotenv()

SECRET_KEY = os.getenv("SECRET_KEY")
VECTOR_INDEX_NAME = os.getenv("VECTOR_INDEX_NAME")

DATABASES = {
    'default': {
        'ENGINE': 'django_mongodb_backend',
        'HOST': os.getenv("MONGODB_URI"),
        'NAME': os.getenv("DB_NAME"),
    },
}

मैनेजमेंट कमांड्स के लिए फ़ोल्डर बनाएँ

अगले चरण में, हम मैनेजमेंट कमांड्स के लिए खाली __init__.py फ़ाइलों के साथ फ़ोल्डर बनाएँगे, क्योंकि Django केवल management/commands/ पैकेज में कस्टम कमांड्स को खोजता है।

mkdir -p documents/management/commands documents/services && touch documents/management/__init__.py documents/management/commands/__init__.py documents/services/__init__.py

डेटा का स्रोत: Federal Register दस्तावेज़

इस ट्यूटोरियल में, हम Federal Register से दस्तावेज़ों को इंडेक्स करेंगे; यह US सरकार के नियमों, प्रस्तावित नियमों और सूचनाओं का दैनिक प्रकाशन है। डेटा का स्रोत एक सार्वजनिक API है, जिसमें शीर्षक और एक संक्षिप्त गद्य सार (abstract) वाले दस्तावेज़ होते हैं—जो सेमांटिक सर्च के लिए उपयुक्त है।

API दस्तावेज़: https://www.federalregister.gov/developers/documentation/api/v1

रिकॉर्ड्स में title, type, abstract, document_number (एक यूनिक ID), publication_date, html_url, और agencies सूची जैसे फ़ील्ड होते हैं।

  • कुछ दस्तावेज़ों में null मान होते हैं, इसलिए हम उन्हें छोड़ देंगे।
  • एब्स्ट्रैक्ट्स में “PM2.5” में <INF>2.5</INF> जैसे मार्कअप होते हैं, इसलिए सेव करने से पहले हम टैग्स हटाएँगे।
  • परिणाम प्रति अनुरोध अधिकतम 100 पर पेज्ड होते हैं, और प्रत्येक पेज में फॉलो करने के लिए next_page_url (कर्सर-आधारित) शामिल होता है।

शेल के जरिए एंडपॉइंट टेस्ट करें

curl -g "https://www.federalregister.gov/api/v1/documents.json?conditions[agencies][]=environmental-protection-agency&per_page=2"

नोट: यह डेमो के लिए प्रयुक्त सार्वजनिक US सरकारी डेटा है। यह कोई कानूनी स्रोत नहीं है; कानूनी रिसर्च के लिए आधिकारिक संस्करण का उपयोग करें।

डेटा इनजेस्ट करें

हम models.py फ़ाइल में मॉडल बनाकर शुरुआत करेंगे।

# documents/models.py
from django.db import models


class Document(models.Model):
    document_number = models.CharField(max_length=32, unique=True)
    title = models.TextField()
    doc_type = models.CharField(max_length=32)
    agency = models.CharField(max_length=128)
    publication_date = models.DateField()
    abstract = models.TextField()
    source_url = models.URLField(max_length=500)

    def __str__(self):
        return f"{self.document_number}: {self.title[:60]}"

अब, हम माइग्रेशंस बनाएँगे और चलाएँगे।

python manage.py makemigrations documents
python manage.py migrate

अब, इनजेस्ट भाग पर चलते हैं।

# documents/management/commands/ingest_federal_register.py

import re
import time

import requests
from django.core.management.base import BaseCommand

from documents.models import Document

API_URL = "https://www.federalregister.gov/api/v1/documents.json"
TAG_PATTERN = re.compile(r"<[^>]+>")


class Command(BaseCommand):
    help = "Load Federal Register documents into MongoDB."

    def add_arguments(self, parser):
        parser.add_argument("--agency", default="environmental-protection-agency")
        parser.add_argument("--limit", type=int, default=300)

    def handle(self, *args, **options):
        params = [
            ("conditions[agencies][]", options["agency"]),
            ("conditions[type][]", "RULE"),
            ("conditions[type][]", "PRORULE"),
            ("per_page", "100"),
        ]
        headers = {"User-Agent": "regulations-qa-tutorial"}
        url, processed = API_URL, 0

        while url and processed < options["limit"]:
            response = requests.get(
                url,
                params=params if url == API_URL else None,
                headers=headers,
                timeout=30,
            )
            response.raise_for_status()
            page = response.json()

            for item in page["results"]:
                abstract = TAG_PATTERN.sub("", item.get("abstract") or "").strip()
                if not abstract:
                    continue
                agencies = item.get("agencies") or [{}]
                Document.objects.update_or_create(
                    document_number=item["document_number"],
                    defaults={
                        "title": TAG_PATTERN.sub("", item["title"]),
                        "doc_type": item["type"],
                        "agency": agencies[0].get("name", ""),
                        "publication_date": item["publication_date"],
                        "abstract": abstract,
                        "source_url": item["html_url"],
                    },
                )
                processed += 1
                if processed >= options["limit"]:
                    break
            url = page.get("next_page_url")
            time.sleep(1)

        self.stdout.write(f"Documents in database: {Document.objects.count()}")

कमांड चलाएँ:

python manage.py ingest_federal_register --limit 100

आप MongoDB Atlas UI में इम्पोर्ट की पुष्टि कर सकते हैं:

MongoDB Atlas Data Explorer, regulations_qa.documents_document कलेक्शन में 100 Federal Register दस्तावेज़ दिखा रहा है

ऑटो-एंबेड इंडेक्स परिभाषित करें

वेक्टर सर्च इंडेक्स MongoDB को बताता है कि किस फ़ील्ड पर एंबेडिंग्स करनी हैं और कौन सा मॉडल उपयोग होना चाहिए। इसके बाद, MongoDB स्वतः एंबेडिंग्स बनाता और स्टोर करता है।

  1. Atlas UI में अपना क्लस्टर खोलें, Search & Vector Search पर जाएँ, और Create Search Index पर क्लिक करें।

MongoDB Atlas में Search & Vector Search पेज, Create Search Index बटन के साथ

  1. Vector Search को सर्च प्रकार के रूप में चुनें और वेक्टर डेटा सेटअप के लिए Automated Embedding चुनें।

Atlas इंडेक्स कॉन्फ़िगरेशन, Vector Search और Automated Embedding चयनित

  1. JSON एडिटर चुनें, अपना डेटाबेस और documents_document कलेक्शन सेलेक्ट करें, और इंडेक्स का नाम autoembed_index रखें (यह नाम आपके .env में VECTOR_INDEX_NAME से मेल खाना चाहिए)। यह परिभाषा पेस्ट करें:
{
  "fields": [
    {
      "type": "autoEmbed",
      "modality": "text",
      "path": "abstract",
      "model": "voyage-4-lite"
    }
  ]
}

Atlas JSON एडिटर, abstract फ़ील्ड के लिए voyage-4-lite के साथ autoEmbed इंडेक्स परिभाषा दर्शाता हुआ

परिभाषा की समीक्षा करें, फिर इंडेक्स बनाएं।

regulations_qa.documents_document पर autoembed_index वेक्टर सर्च इंडेक्स के लिए समीक्षा चरण

  1. इंडेक्स की स्थिति क्वेरी के लिए तैयार दिखने तक प्रतीक्षा करें, क्योंकि एंबेडिंग्स बैकग्राउंड में जनरेट हो रही हैं।

Atlas Search & Vector Search सूची, autoembed_index को READY और क्वेरीएबल स्थिति में दिखाती हुई

सादे पाठ में क्वेरी करें

ऑटो-एंबेडिंग्स के लिए, हम $vectorSearch स्टेज को सादा-पाठ क्वेरी के साथ उपयोग करते हैं और प्रश्न को उसी मॉडल से एंबेड करते हैं जिसका उपयोग इंडेक्स करता है, इसलिए हमारे कोड में कोई एंबेडिंग कॉल नहीं होती।

इसे पाने के लिए, हम एक सर्विस मॉड्यूल बनाएँगे।

# documents/services/search_service.py
from functools import lru_cache

from django.conf import settings
from pymongo import MongoClient

from documents.models import Document

DEFAULT_LIMIT = 5


@lru_cache(maxsize=1)  # create the client once and reuse it
def _get_client():
    return MongoClient(settings.DATABASES["default"]["HOST"])


def _get_collection():
    db_name = settings.DATABASES["default"]["NAME"]
    return _get_client()[db_name][Document._meta.db_table]


def _get_index_name():
    index_name = settings.VECTOR_INDEX_NAME
    if not index_name:
        raise ValueError("VECTOR_INDEX_NAME is not set. Add it to your .env file.")
    return index_name


def semantic_search(question: str, limit: int = DEFAULT_LIMIT) -> list:
    """Search with a plain-text question.

    There is no query vector to pass in: MongoDB embeds the question
    with the index's model.
    """
    pipeline = [
        {
            "$vectorSearch": {
                "index": _get_index_name(),
                "path": "abstract",
                "query": question,
                "numCandidates": limit * 20,
                "limit": limit,
            }
        },
        {
            "$project": {
                "_id": 0,
                "document_number": 1,
                "title": 1,
                "abstract": 1,
                "source_url": 1,
                "score": {"$meta": "vectorSearchScore"},
            }
        },
    ]
    return list(_get_collection().aggregate(pipeline))
  • _get_client() MongoDB से कनेक्शन एक बार बनाता है और उसे पुन: उपयोग करता है। lru_cache पहली कॉल के परिणाम को याद रखता है, ताकि हर सर्च एक ही क्लाइंट साझा करे और हर बार नया कनेक्शन न खुले।
  • _get_collection() Django की सेटिंग्स का उपयोग करके regulations_qa डेटाबेस और documents_document कलेक्शन चुनता है।
  • _get_index_name() सेटिंग्स से इंडेक्स नाम पढ़ता है और यदि यह गायब हो, तो स्पष्ट त्रुटि देता है।
  • semantic_search() प्रश्न को query फ़ील्ड में टेक्स्ट के रूप में भेजता है। दूसरा स्टेज आउटपुट को ज़रूरी फ़ील्ड्स तक सीमित करता है और समानता स्कोर जोड़ता है।

फिर हम डॉक्युमेंट्स सर्च करने के लिए एक हेल्पर जोड़ते हैं:

# documents/management/commands/search_docs.py
from django.core.management.base import BaseCommand

from documents.services.search_service import semantic_search


class Command(BaseCommand):
    help = "Run a plain-text search."

    def add_arguments(self, parser):
        parser.add_argument("question")

    def handle(self, *args, **options):
        for hit in semantic_search(options["question"]):
            self.stdout.write(
                f"{hit['score']:.3f}  {hit['document_number']}  {hit['title'][:80]}"
            )

अब, टेस्ट करने के लिए चलाएँ:

python manage.py search_docs "limits on pollution from factories"

उदाहरण में, हम ऐसे प्रश्न चुनते हैं जो एब्स्ट्रैक्ट्स के साथ कीवर्ड साझा नहीं करते। “limits on pollution from factories” पर प्रश्न को इमीशन स्टैंडर्ड्स से संबंधित दस्तावेज़ लौटाने चाहिए।

नोट: बिना पेमेंट मेथड वाले मुफ्त (M0) क्लस्टर पर, क्वेरी एंबेडिंग अनुरोधों पर रेट लिमिटिंग हो सकती है।

डेमो: किसी दस्तावेज़ को संपादित करें और री-सिंक देखें

डेमो के लिए, हम या तो MongoDB Atlas में Search Tester का उपयोग कर सकते हैं, जो पहले बनाए गए regulations_qa.documents_document कलेक्शन पर autoembed_index से जुड़ा है, या Python शेल का।

regulations_qa.documents_document पर autoembed_index के लिए Atlas Search Tester

चरण 1: MongoDB Atlas और शेल के जरिए सर्च

MongoDB Atlas UI में इसे टेस्ट करने के लिए, यह क्वेरी दर्ज करें:

which states need to clean up their air

क्वेरी which states need to clean up their air के लिए Search Tester परिणाम, समानता स्कोर के साथ

शेल के जरिए टेस्ट करने के लिए:

python manage.py shell से शेल खोलें, फिर चलाएँ:

from documents.models import Document
from documents.services.search_service import semantic_search
Q = "which states need to clean up their air"
hits = semantic_search(Q, limit=10)
print("\n".join(f"{i}  {h['score']:.3f}  {h['document_number']}  {h['title'][:70]}" for i, h in enumerate(hits, 1)))

Django शेल आउटपुट, शीर्ष 10 सेमांटिक सर्च परिणाम और उनके स्कोर सूचीबद्ध

आउटपुट वही होना चाहिए जो हमने GUI के जरिए देखा था।

चरण 2: दस्तावेज़ संपादित करें

target = hits[-1]
doc = Document.objects.get(document_number=target["document_number"])
original = doc.abstract
doc.abstract = original + " This action also identifies which states and areas must clean up their air to meet health-based standards."
doc.save()
print(target["document_number"], "edited")

Django शेल, दस्तावेज़ 2026-16515 के एब्स्ट्रैक्ट में एक वाक्य जोड़कर सेव करता हुआ

चरण 3: फिर से सर्च करें

ऑटो-एंबेडिंग्स असिंक्रोनस रूप से जनरेट होती हैं, इसलिए 30–60 सेकंड प्रतीक्षा करें, फिर क्वेरी दोबारा चलाएँ:

hits = semantic_search(Q, limit=10)
print("\n".join(f"{i}  {h['score']:.3f}  {h['document_number']}  {h['title'][:70]}" for i, h in enumerate(hits, 1)))

एडिट के बाद सर्च परिणाम, दस्तावेज़ 2026-16515 10वें से 5वें स्थान पर आया

अब हमें संपादित दस्तावेज़ को पहले से अधिक ऊँचे रैंक पर देखना चाहिए।

GUI के जरिए परिणाम देखने के लिए वही क्वेरी Search Tester में चलाएँ।

यह हुआ कि MongoDB ने देखा कि इंडेक्स्ड फ़ील्ड बदला है और उस दस्तावेज़ की एंबेडिंग फिर से जनरेट की, इसलिए दस्तावेज़ 2026-16515, जो नमूने में 10वें स्थान पर था, एडिट और सिंक के बाद ऊँचे रैंक पर आकर 5वें स्थान पर आ गया।

समापन

यहाँ तक पहुँचने के लिए बधाई! अब हमारे पास ऐसा डॉक्यूमेंट Q&A असिस्टेंट है, जहाँ MongoDB एंबेडिंग वर्कफ़्लो को संभालता है। यह निम्न चरणों में हासिल हुआ:

  • Insert: दस्तावेज़ Django ORM के जरिए लोड किए गए
  • Index: एक इंडेक्स परिभाषा, Atlas UI में बनाई गई, जिसमें फ़ील्ड और मॉडल का नाम दिया गया।
  • Query: एक छोटे से सर्विस के जरिए सादा-पाठ प्रश्न, बिना अलग एंबेडिंग कॉल जोड़े।
  • Edit: इंडेक्स्ड फ़ील्ड में बदलाव बिना री-एंबेडिंग स्क्रिप्ट के फिर से सिंक हो जाते हैं।

नोट: इस ट्यूटोरियल में डेटा Federal Register से आता है, जो US सरकारी दस्तावेज़ प्रकाशित करता है। यह ट्यूटोरियल स्वतंत्र है और Federal Register से संबद्ध या उसके द्वारा समर्थित नहीं है।

संदर्भ

Afi Gbadago

लेखक

Afi Gbadago

Afi, MongoDB में डेवलपर्स की पैरवी करती हैं, जहाँ वह Django और Python पर केंद्रित रहते हुए ट्यूटोरियल्स, वार्ताओं और सामुदायिक सहभागिता के माध्यम से इंजीनियरों को आधुनिक डेटा तकनीकों के साथ निर्माण करने में मदद करती हैं। Python और वेब के लिए Microsoft MVP के रूप में मान्यता प्राप्त, वह Django Software Foundation के बोर्ड में सेवा देती हैं और DjangoCon US 2025 की प्रोग्राम चेयर हैं। Afi, Black Python Devs की रीजनल एग्जीक्यूटर भी हैं, साथ ही सक्रिय ओपन-सोर्स योगदानकर्ता और अंतरराष्ट्रीय वक्ता हैं।

विषय