नमस्ते दोस्तों!
स्वागत है The Easy Master पर!
Part 7 का bot काम करता है, लेकिन असली app के लिए उसमें चार कमियाँ हैं:
- हर बार चलने पर सारी embeddings दोबारा बनती हैं
- Chunks सिर्फ़ paragraph से कटते हैं – लंबे documents पर नहीं चलेगा
- User को पता नहीं चलता कि जवाब कहाँ से आया
- बेकार सवाल ("France ki capital?") भी AI तक पहुँच जाता है
आज चारों ठीक करेंगे, और सीखेंगे कि ग़लत जवाब को debug कैसे करें।
Is RAG chunking in Hindi post mein aap seekhenge:
✅ Chunking with overlap – बात बीच से न कटे
✅ Saved index – embeddings एक बार, file में
✅ Minimum score – बेकार सवाल AI तक न पहुँचे
✅ Source numbers – जवाब के साथ [1], [2]
✅ Debugging – search ग़लत है या model?
1. Do Files – Index Banao, Phir Poochho
असली RAG apps दो हिस्सों में बँटी होती हैं:
| File | Kab chalti hai | Kaam |
|---|---|---|
build-index.js | Document बदलने पर, एक बार | Chunks + embeddings बनाकर index.json में save |
ask.js | हर सवाल पर | index.json पढ़ो, ढूँढो, जवाब दो |
2. Chunking With Overlap
// build-index.js — notes ko ek baar padho, chunks + vectors file mein save karo
import fs from 'node:fs';
async function embed(texts) {
const res = await fetch('http://localhost:11434/api/embed', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: 'nomic-embed-text', input: texts }),
});
return (await res.json()).embeddings;
}
// Text ko chhote chunks mein todo (~size characters). Har naya chunk pichhle
// chunk ke aakhri sentence se shuru hota hai (overlap), taaki koi baat beech se na kate.
function chunk(text, size = 300) {
const sentences = text.replace(/s+/g, ' ').split(/(?<=[.?!।])s+/);
const chunks = [];
let current = [];
for (const s of sentences) {
if (current.length && [...current, s].join(' ').length > size) {
chunks.push(current.join(' '));
current = [current[current.length - 1]]; // aakhri sentence agle chunk mein bhi
}
current.push(s);
}
if (current.length) chunks.push(current.join(' '));
return chunks;
}
const files = process.argv.slice(2);
const index = [];
for (const file of files) {
const pieces = chunk(fs.readFileSync(file, 'utf8'));
const vectors = await embed(pieces);
pieces.forEach((text, i) => index.push({ file, text, vector: vectors[i] }));
console.log(`${file}: ${pieces.length} chunks`);
}
fs.writeFileSync('index.json', JSON.stringify(index));
console.log(`index.json mein ${index.length} chunks save ho gaye`);Chalaiye: node build-index.js notes.txt (कई files भी दे सकते हैं: node build-index.js a.txt b.txt)
notes.txt: 5 chunks
index.json mein 5 chunks save ho gayeOverlap kyun?
मान लीजिए एक ज़रूरी बात दो chunks की सीमा पर कट गई – आधी chunk 3 में, आधी chunk 4 में। Search दोनों में से किसी को अच्छा नहीं मानेगा। Overlap का मतलब: हर नया chunk पिछले chunk के आख़िरी sentence से शुरू होता है, ताकि सीमा पर की बात दोनों में पूरी रहे।
Hamari ek galti – aur uska sabak
पहले हमने overlap characters में रखा था (आख़िरी 60 characters)। नतीजा? Chunk ऐसे शुरू हुआ: "i fees wapas milti hai…" – शब्द बीच से कट गया। इसलिए अब overlap पूरे sentence का है। Chunks काटते समय हमेशा देखिए कि वो कैसे दिख रहे हैं:
node -e "require('./index.json').forEach((c, n) => console.log(n + 1, c.text.slice(0, 70)))"3. Ask – Score, Sources Aur Debug
// ask.js — saved index se jawab, source number ke saath
import fs from 'node:fs';
const MODEL = 'qwen2.5:7b';
const MIN_SCORE = 0.5; // isse kam mel = kaam ka chunk nahi
const index = JSON.parse(fs.readFileSync('index.json', 'utf8'));
async function embed(texts) {
const res = await fetch('http://localhost:11434/api/embed', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: 'nomic-embed-text', input: texts }),
});
return (await res.json()).embeddings;
}
function similarity(a, b) {
let dot = 0, na = 0, nb = 0;
for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; }
return dot / (Math.sqrt(na) * Math.sqrt(nb));
}
async function ask(question) {
const [q] = await embed([question]);
const found = index
.map((c) => ({ ...c, score: similarity(q, c.vector) }))
.filter((c) => c.score >= MIN_SCORE)
.sort((a, b) => b.score - a.score)
.slice(0, 3);
// DEBUG=1 node ask.js "..." — dekho search ne kya dhoondha
if (process.env.DEBUG) found.forEach((c) => console.log(` ${c.score.toFixed(2)} ${c.text.slice(0, 70)}...`));
if (found.length === 0) return 'Is sawal se milti koi jaankari notes mein nahi mili.';
// har chunk ko number do, taaki jawab bata sake ki kahan se aaya
const context = found.map((c, i) => `[${i + 1}] (${c.file}) ${c.text}`).join('nn');
const res = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: MODEL,
stream: false,
options: { temperature: 0 },
messages: [
{ role: 'system', content: 'Sirf diye gaye NOTES se jawab do. Har baat ke baad uska source number likho, jaise [1]. Jawab notes mein na ho toh kaho "Notes mein yeh nahi hai." Hinglish mein jawab do.' },
{ role: 'user', content: `NOTES:n${context}nnSAWAL: ${question}` },
],
}),
});
return (await res.json()).message.content;
}
const question = process.argv.slice(2).join(' ');
console.log(await ask(question));node ask.js "Fees kitni hai aur kaise de sakte hain?"
Fees 45,000 rupaye hai aur fees do installments mein di ja sakti hai: pehli joining par, doosri 45 din baad. [1]
node ask.js "What is the capital of France?"
Is sawal se milti koi jaankari notes mein nahi mili.MIN_SCORE – darwaze par chowkidaar
France वाला सवाल AI तक पहुँचा ही नहीं – किसी chunk का score 0.5 से ऊपर नहीं था, तो code ने ख़ुद मना कर दिया। फ़ायदे: AI call का पैसा बचा, और hallucination का मौका ही नहीं मिला।
0.5 कोई जादुई number नहीं है – यह आपके data और embedding model पर निर्भर है। 10-20 असली सवालों के scores देखकर तय कीजिए।
Source numbers – bharose ki buniyaad
Chunks को [1], [2] नंबर देकर भेजा, और system prompt में कहा "har baat ke baad source number likho"। अब user (या आप) जाँच सकते हैं कि जवाब सच में document में है या नहीं।
4. Debugging – Search Galat Hai Ya Model?
यह सवाल चलाया: "Refund kab milta hai?" जवाब आया:
Refund 7 din ke baad nahi milta [1]. CodeKul Institute mein bhi iska same prakar hai [2].आधा सही, आधा बेकार। अब debug mode में चलाइए:
DEBUG=1 node ask.js "Refund kab milta hai?"
0.73 7 din ke baad koi refund nahi milta. Classes: Classes Monday se Friday...
0.68 CodeKul Institute – Student Handbook Fees: Full Stack course ki fees 4...
0.61 Final project ka demo course ke aakhri hafte mein hota hai. Placement:...(Windows PowerShell में: $env:DEBUG=1; node ask.js "...")
Ab saaf dikh raha hai: असली नियम – "Joining ke 7 din ke andar poori fees wapas milti hai" – chunk 1 के आख़िर में था, refund वाले हिस्से से अलग कट गया। Search ने सबसे ऊपर वो chunk दिया जिसमें सिर्फ़ "7 din ke baad koi refund nahi" था। Model ग़लत नहीं था – उसे आधी बात मिली थी।
Fix: document ki apni banawat se kaatiye
हमारी handbook में हर topic का अपना paragraph है ("Fees: …", "Refund: …")। ऐसे documents को paragraph या heading से काटना बेहतर है – Part 7 वाला तरीका यहाँ सही जवाब देता था। Size वाली chunking लंबे, बिना banawat वाले text (books, transcripts) के लिए है।
Debugging ka niyam: ग़लत जवाब पर हमेशा पहले retrieved chunks देखिए। सही जानकारी chunks में नहीं → chunking/search ठीक कीजिए। Chunks में है फिर भी जवाब ग़लत → prompt या model ठीक कीजिए।
5. Bade Documents Ke Liye – Vector Database
index.json कुछ हज़ार chunks तक ठीक है। उससे ज़्यादा हो, या कई users एक साथ search करें, तो vector database चाहिए:
- pgvector – PostgreSQL में ही vectors (पहले से Postgres है तो सबसे आसान – Postgres से जुड़ना FastAPI PostgreSQL SQLModel में सीखिए)
- MongoDB Atlas Vector Search – MongoDB use करते हैं तो Atlas में ही (MongoDB Atlas setup)
- Chroma – छोटे projects के लिए आसान
- Qdrant, Weaviate – बड़े scale के लिए
सबका idea वही है जो आपने बनाया – vectors save करो, सवाल के vector से सबसे पास वाले ढूँढो। बस वो यह काम लाखों vectors पर milliseconds में करते हैं।
6. PDF Se Kaise?
PDF से text निकालिए (Node में pdf-parse, Python में pypdf जैसी libraries), उसे .txt में save कीजिए, और build-index.js को दे दीजिए। बाकी सब वही रहता है। Users ख़ुद PDF upload करें, ऐसा feature चाहिए तो Express File Upload – Multer देखिए।
7. Common Mistakes
- Chunks kabhi dekhna hi nahi – आधी RAG problems chunking में होती हैं। Chunks print करके पढ़िए।
- MIN_SCORE bina test ke – बहुत ऊँचा = सही सवाल भी मना; बहुत नीचा = बेकार chunks AI तक।
- Document badla, index purana –
build-index.jsदोबारा चलाना भूल गए तो पुराने जवाब आएंगे। - Sources ko bina check kiye dikhana – AI कभी ग़लत number भी लिख सकता है। ज़रूरी apps में source का text भी साथ दिखाइए।
📌 Cheat sheets: इस post की theory – RAG Cheat Sheet और Embeddings & Vector DB Cheat Sheet। Series का सारा code एक जगह – AI Engineering Code Cheat Sheet।
Conclusion
आपकी RAG app अब असली दुनिया के लिए तैयार है: index एक बार बनता है, बेकार सवाल दरवाज़े पर रुकते हैं, जवाब के साथ source आता है, और आप जानते हैं कि ग़लत जवाब पर पहले कहाँ देखना है।
अब तक AI सिर्फ़ पढ़ रहा था। अगले post में वो काम करेगा – आपके functions चलाकर, जैसे order status देखना। Part 9 पढ़िए → (24 Nov को आएगा) 🚀