{"id":315,"date":"2026-11-29T14:40:09","date_gmt":"2026-11-29T14:40:09","guid":{"rendered":"https:\/\/devdojo.co.in\/?p=315"},"modified":"2026-11-29T14:40:10","modified_gmt":"2026-11-29T14:40:10","slug":"genai-series-part-12-document-loading-chunking","status":"publish","type":"post","link":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/","title":{"rendered":"Generative AI Part 12: Document Loading and Chunking Strategies for RAG"},"content":{"rendered":"\n<div class=\"dd-post\">\n<style>\n.single article:has(.dd-hero) .entry-media{display:none}\n.dd-post{--navy:#0b1020;--blue:#3178c6;--violet:#7c5cff;--ink:#1f2433;--muted:#5b6275;--line:#e3e6ef;font-size:17px;line-height:1.75;color:var(--ink)}\n.dd-post h2{margin:2.2em 0 .6em;font-size:1.6em;line-height:1.3;scroll-margin-top:90px}\n.dd-post h3{margin:1.6em 0 .5em;font-size:1.22em;scroll-margin-top:90px}\n.dd-post a{color:var(--blue);text-decoration:underline;text-underline-offset:3px}\n.dd-post pre{background:#0f1430;color:#e6e9f5;padding:18px 20px;border-radius:12px;overflow-x:auto;line-height:1.6;border:1px solid #232a52;margin:1.2em 0;font-size:14.5px !important}\n.dd-post pre code{font-size:1em !important;background:none;color:inherit;padding:0;font-family:\"JetBrains Mono\",\"Fira Code\",Consolas,Menlo,monospace;white-space:pre}\n.dd-post :not(pre)>code{background:#eef1fb;color:#2b3a8f;padding:2px 6px;border-radius:5px;font-size:.9em}\n.dd-post .dd-file{display:inline-block;background:#151b3b;color:#c9d1ff;font:600 13px\/1 \"JetBrains Mono\",Consolas,monospace;padding:7px 12px;border-radius:8px 8px 0 0;margin:1em 0 -1.2em;position:relative}\n.dd-post .dd-hero{margin:0 0 1.6em;border-radius:16px;overflow:hidden;box-shadow:0 10px 30px rgba(11,16,32,.25)}\n.dd-post .dd-hero svg{display:block;width:100%;height:auto}\n.dd-post .dd-hero .node{transition:transform .25s,filter .25s;transform-box:fill-box;transform-origin:center;cursor:pointer}\n.dd-post .dd-hero .node:hover{transform:scale(1.08);filter:drop-shadow(0 0 10px #7c5cff)}\n.dd-post .dd-series{display:inline-flex;align-items:center;gap:8px;background:#151b3b;color:#dfe3ff;border-radius:999px;padding:6px 14px;font-size:.88em;font-weight:600;margin:0 0 .8em}\n.dd-post .dd-series span{background:var(--violet);color:#fff;border-radius:999px;padding:2px 10px}\n.dd-post .dd-prereq{font-size:.96em;color:var(--muted);border-left:3px solid var(--line);padding-left:12px;margin:.6em 0 1.2em}\n.dd-post .dd-summary{background:linear-gradient(135deg,#eef3ff,#f4efff);border:1px solid #d6dcf5;border-left:5px solid var(--violet);border-radius:12px;padding:18px 22px;margin:1.4em 0}\n.dd-post .dd-summary strong.lbl{display:block;font-size:1.05em;margin-bottom:6px;color:#3a2fa0}\n.dd-post .dd-summary ul{margin:.3em 0 0 1.1em}\n.dd-post .dd-toc{background:#f8f9fc;border:1px solid var(--line);border-radius:12px;padding:16px 22px;margin:1.4em 0}\n.dd-post .dd-toc ol{margin:.4em 0 0 1.2em;columns:2;column-gap:28px}\n.dd-post .dd-toc li{break-inside:avoid;margin:.15em 0}\n@media(max-width:640px){.dd-post .dd-toc ol{columns:1}}\n.dd-post .dd-tip,.dd-post .dd-note,.dd-post .dd-warn{border-radius:10px;padding:14px 18px;margin:1.3em 0}\n.dd-post .dd-tip{background:#ecfbf3;border-left:4px solid #1f9d61}\n.dd-post .dd-note{background:#eef4ff;border-left:4px solid var(--blue)}\n.dd-post .dd-warn{background:#fff6e8;border-left:4px solid #e08a00}\n.dd-post .dd-cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:14px;margin:1.3em 0}\n.dd-post .dd-card{border:1px solid var(--line);border-radius:12px;padding:14px 16px;background:#fff;box-shadow:0 2px 8px rgba(20,30,70,.05)}\n.dd-post .dd-card b{display:block;color:#3a2fa0;margin-bottom:4px}\n.dd-post table{width:100%;border-collapse:collapse;margin:1.3em 0;font-size:.95em}\n.dd-post th,.dd-post td{border:1px solid var(--line);padding:10px 12px;text-align:left;vertical-align:top}\n.dd-post th{background:#151b3b;color:#fff}\n.dd-post tr:nth-child(even) td{background:#f8f9fc}\n.dd-post .dd-tablewrap{overflow-x:auto}\n.dd-post figure{margin:1.6em 0;text-align:center}\n.dd-post figure svg{width:100%;height:auto;border-radius:12px}\n.dd-post figcaption{font-size:.9em;color:var(--muted);margin-top:8px}\n.dd-post details{border:1px solid var(--line);border-radius:10px;padding:12px 16px;margin:.7em 0;background:#fff}\n.dd-post details summary{cursor:pointer;font-weight:600}\n.dd-post details[open] summary{margin-bottom:8px;color:#3a2fa0}\n.dd-post .dd-roadmap{border:2px solid #d6dcf5;background:#fbfbff}\n.dd-post .dd-roadmap h4{margin:1em 0 .3em;color:#151b3b;font-size:1em;text-transform:uppercase;letter-spacing:.04em}\n.dd-post .dd-roadmap ol{margin:.2em 0 .6em 1.4em;padding:0}\n.dd-post .dd-roadmap li{margin:.2em 0}\n.dd-post .dd-roadmap .here{background:var(--violet);color:#fff;border-radius:999px;padding:1px 9px;font-size:.8em;font-weight:700;margin-left:6px}\n.dd-post .dd-roadmap .soon{color:#8a90a6;font-size:.82em;margin-left:6px}\n.dd-post .dd-tabs{border:1px solid var(--line);border-radius:12px;padding:6px 16px 16px;margin:1.4em 0;background:#fbfbfe}\n.dd-post .dd-tabs>input{position:absolute;opacity:0;pointer-events:none}\n.dd-post .dd-tabs .labels label{display:inline-block;padding:8px 16px;margin:10px 6px 0 0;border-radius:999px;border:1px solid #cfd5ea;cursor:pointer;font-weight:600;font-size:.95em;background:#fff;transition:background .2s}\n.dd-post .dd-tabs .labels label:hover{border-color:var(--violet)}\n.dd-post .dd-tabs .panel{display:none;margin-top:12px}\n.dd-post .dd-tabs #ti1:checked~.labels label[for=ti1],.dd-post .dd-tabs #ti2:checked~.labels label[for=ti2],.dd-post .dd-tabs #ti3:checked~.labels label[for=ti3],.dd-post .dd-tabs #ti4:checked~.labels label[for=ti4]{background:var(--violet);color:#fff;border-color:var(--violet)}\n.dd-post .dd-tabs #ti1:checked~.p1,.dd-post .dd-tabs #ti2:checked~.p2,.dd-post .dd-tabs #ti3:checked~.p3,.dd-post .dd-tabs #ti4:checked~.p4{display:block}\n.dd-post .dd-tabs #ti1:focus-visible~.labels label[for=ti1],.dd-post .dd-tabs #ti2:focus-visible~.labels label[for=ti2],.dd-post .dd-tabs #ti3:focus-visible~.labels label[for=ti3],.dd-post .dd-tabs #ti4:focus-visible~.labels label[for=ti4]{outline:2px solid var(--blue);outline-offset:2px}\n.dd-post .dd-cta{background:linear-gradient(135deg,#0b1020,#151b3b);color:#e8ebff;border-radius:16px;padding:24px 26px;margin:2em 0;text-align:center}\n.dd-post .dd-cta h3{color:#fff;margin-top:0}\n.dd-post .dd-cta a{color:#a99bff}\n.dd-post .dd-vsc{position:relative;margin:1.5em 0;border-radius:12px;overflow:hidden;background:#1e1e1e;border:1px solid #2b2b2b;box-shadow:0 14px 34px rgba(0,0,0,.28);font-family:\"Segoe UI\",system-ui,sans-serif}\n.dd-post .dd-vsc>input{position:absolute;opacity:0;pointer-events:none}\n.dd-post .dd-vsc-bar{display:flex;align-items:center;gap:12px;background:#323233;color:#cccccc;font-size:12.5px;padding:8px 12px}\n.dd-post .dd-dots{display:inline-flex;gap:7px}.dd-post .dd-dots i{width:12px;height:12px;border-radius:50%;background:#ff5f57;display:block}.dd-post .dd-dots i:nth-child(2){background:#febc2e}.dd-post .dd-dots i:nth-child(3){background:#28c840}\n.dd-post .dd-vsc-title{flex:1;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding-right:50px;opacity:.85}\n.dd-post .dd-vsc-tabs{display:flex;align-items:stretch;background:#252526;border-bottom:1px solid #1e1e1e;overflow-x:auto}\n.dd-post .dd-vsc-tabs label{display:flex;align-items:center;gap:7px;padding:9px 16px;color:#969696;font-size:13px;cursor:pointer;background:#2d2d2d;border-right:1px solid #252526;border-top:1px solid transparent;white-space:nowrap;margin:0;transition:color .15s}\n.dd-post .dd-vsc-tabs label:hover{color:#e0e0e0}\n.dd-post .dd-vsc-tabs .ic{font:700 9.5px\/1 Consolas,monospace;padding:3px 4px;border-radius:3px;color:#1e1e1e}\n.dd-post .ic.py{background:#ffd43b}.dd-post .ic.js{background:#f1e05a}.dd-post .ic.sh{background:#89e051}\n.dd-post .dd-vsc-tabs label.run{margin-left:auto;background:transparent;border:0;color:#89d185;font-weight:600;display:none}\n.dd-post .dd-vsc-tabs label.run:hover{color:#b5f0b0;background:#2a2d2e}\n.dd-post .dd-vsc-pane{display:none}\n.dd-post .dd-vsc>.f1:checked~.dd-vsc-tabs .t1,.dd-post .dd-vsc>.f2:checked~.dd-vsc-tabs .t2,.dd-post .dd-vsc>.f3:checked~.dd-vsc-tabs .t3{background:#1e1e1e;color:#ffffff;border-top-color:#3178c6}\n.dd-post .dd-vsc>.f1:checked~.p1,.dd-post .dd-vsc>.f2:checked~.p2,.dd-post .dd-vsc>.f3:checked~.p3{display:block}\n.dd-post .dd-vsc>.f1:checked~.dd-vsc-tabs .run1,.dd-post .dd-vsc>.f2:checked~.dd-vsc-tabs .run2,.dd-post .dd-vsc>.f3:checked~.dd-vsc-tabs .run3{display:flex}\n.dd-post .dd-vsc>.f1:focus-visible~.dd-vsc-tabs .t1,.dd-post .dd-vsc>.f2:focus-visible~.dd-vsc-tabs .t2,.dd-post .dd-vsc>.f3:focus-visible~.dd-vsc-tabs .t3,.dd-post .dd-vsc>input[type=checkbox]:focus-visible~.dd-vsc-tabs .run{outline:2px solid #3178c6;outline-offset:-2px}\n.dd-post .dd-vsc-crumbs{background:#1e1e1e;color:#a9a9a9;font-size:12px;padding:5px 16px 2px}\n.dd-post .dd-vsc pre.dd-vsc-code{background:#1e1e1e;color:#d4d4d4;border:0;border-radius:0;margin:0;padding:8px 0 14px;counter-reset:ln;line-height:1.62;overflow-x:auto}\n.dd-post .dd-vsc pre code{font-family:Consolas,\"JetBrains Mono\",\"Fira Code\",Menlo,monospace;color:inherit;background:none;white-space:pre}\n.dd-post .dd-vsc .l{display:inline-block;min-width:100%;padding-right:18px;box-sizing:border-box}\n.dd-post .dd-vsc .l::before{counter-increment:ln;content:counter(ln);display:inline-block;width:3.2em;padding-right:1.4em;text-align:right;color:#6e7681;user-select:none;-webkit-user-select:none}\n.dd-post .dd-vsc .l:hover{background:#2a2d2e}.dd-post .dd-vsc .l:hover::before{color:#c6c6c6}\n.dd-post .dd-vsc .k,.dd-post .dd-vsc .kn{color:#c586c0}.dd-post .dd-vsc .kc{color:#569cd6}.dd-post .dd-vsc .s{color:#ce9178}.dd-post .dd-vsc .c{color:#6a9955}.dd-post .dd-vsc .m{color:#b5cea8}.dd-post .dd-vsc .nf{color:#dcdcaa}.dd-post .dd-vsc .nc{color:#4ec9b0}.dd-post .dd-vsc .nb{color:#4ec9b0}.dd-post .dd-vsc .nd{color:#dcdcaa}.dd-post .dd-vsc .n{color:#9cdcfe}.dd-post .dd-vsc .o{color:#d4d4d4}.dd-post .dd-vsc .gp{color:#89d185;user-select:none;-webkit-user-select:none}\n.dd-post .dd-vsc-term{display:none;border-top:1px solid #3c3c3c;background:#181818}\n.dd-post .dd-vsc>.r1:checked~.p1 .dd-vsc-term,.dd-post .dd-vsc>.r2:checked~.p2 .dd-vsc-term,.dd-post .dd-vsc>.r3:checked~.p3 .dd-vsc-term{display:block;animation:ddterm .35s ease-out}\n@keyframes ddterm{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}\n.dd-post .dd-term-head{display:flex;gap:18px;align-items:center;font-size:11px;letter-spacing:.06em;color:#8b8b8b;padding:7px 16px 0}\n.dd-post .dd-term-head span:first-child{color:#e7e7e7;border-bottom:1px solid #e7e7e7;padding-bottom:4px}\n.dd-post .dd-term-head .dd-term-note{margin-left:auto;letter-spacing:0;text-transform:none;color:#d7ba7d;border:0;font-size:11.5px}\n.dd-post .dd-vsc-term pre{background:#181818;color:#cccccc;border:0;margin:0;padding:10px 16px 14px;border-radius:0}\n.dd-post .dd-vsc-status{display:flex;flex-wrap:wrap;gap:4px 14px;background:#007acc;color:#fff;font-size:11.5px;padding:4px 12px}\n.dd-post .dd-vsc-status .sp{flex:1}\n.dd-post .dd-vsc-termonly pre.dd-vsc-code{background:#181818;padding:12px 16px}\n@media(max-width:640px){.dd-post .dd-vsc-title{padding-right:0;text-align:left}.dd-post .dd-vsc-status span:nth-child(n+4){display:none}.dd-post .dd-vsc .l::before{width:2.2em;padding-right:1em}}\n.dd-post .dd-vsc-hint{font-size:.93em;color:var(--muted);margin-top:-.6em}\n.dd-post .dd-next{border:1px dashed var(--violet);border-radius:12px;padding:16px 20px;margin:1.6em 0;background:#f7f4ff}\n<\/style>\n<div class=\"dd-hero\">\n<svg viewBox=\"0 0 1200 520\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" role=\"img\" aria-label=\"Generative AI series Part 12 banner: PDF, Markdown and HTML files go into a loader that extracts clean text with metadata, a splitter cuts it into chunks, and each chunk gets a stable ID ready for the vector database\">\n<defs>\n<linearGradient id=\"ddbg\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"><stop offset=\"0\" stop-color=\"#0b1020\"\/><stop offset=\"1\" stop-color=\"#151b3b\"\/><\/linearGradient>\n<linearGradient id=\"ddac\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\"><stop offset=\"0\" stop-color=\"#3178c6\"\/><stop offset=\"1\" stop-color=\"#7c5cff\"\/><\/linearGradient>\n<radialGradient id=\"ddglow\" cx=\".5\" cy=\".5\" r=\".5\"><stop offset=\"0\" stop-color=\"#7c5cff\" stop-opacity=\".45\"\/><stop offset=\"1\" stop-color=\"#7c5cff\" stop-opacity=\"0\"\/><\/radialGradient>\n<\/defs>\n<rect x=\"0\" y=\"-60\" width=\"1200\" height=\"640\" fill=\"url(#ddbg)\"\/>\n<circle cx=\"1000\" cy=\"110\" r=\"250\" fill=\"url(#ddglow)\"\/>\n<g opacity=\".12\" stroke=\"#9fb2ff\"><path d=\"M0 100H1200M0 200H1200M0 300H1200M0 400H1200M200 0V520M400 0V520M600 0V520M800 0V520M1000 0V520\"\/><\/g>\n<rect x=\"60\" y=\"46\" width=\"140\" height=\"38\" rx=\"19\" fill=\"url(#ddac)\"\/>\n<text x=\"130\" y=\"71\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"18\" font-weight=\"700\" fill=\"#fff\">PART 12<\/text>\n<text x=\"216\" y=\"71\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"18\" fill=\"#aab4e8\">Generative AI Series \u00b7 DevDojo<\/text>\n<text x=\"60\" y=\"148\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"58\" font-weight=\"800\" fill=\"#ffffff\">Document Loading<\/text>\n<text x=\"60\" y=\"204\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"44\" font-weight=\"800\" fill=\"url(#ddac)\">&amp; Chunking Strategies<\/text>\n<text x=\"60\" y=\"246\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"23\" fill=\"#c9d1ff\">Turn PDFs, web pages and Markdown into clean RAG chunks<\/text>\n<g font-family=\"Segoe UI,Arial,sans-serif\">\n<g class=\"node\"><rect x=\"50\" y=\"300\" width=\"200\" height=\"150\" rx=\"16\" fill=\"#1b2250\" stroke=\"#3178c6\" stroke-width=\"2\"\/><text x=\"150\" y=\"330\" text-anchor=\"middle\" font-size=\"15\" fill=\"#aac8f0\">Your files<\/text>\n<rect x=\"75\" y=\"345\" width=\"70\" height=\"28\" rx=\"7\" fill=\"#e5534b\"\/><text x=\"110\" y=\"365\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#fff\">PDF<\/text>\n<rect x=\"155\" y=\"345\" width=\"70\" height=\"28\" rx=\"7\" fill=\"#3178c6\"\/><text x=\"190\" y=\"365\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#fff\">MD<\/text>\n<rect x=\"75\" y=\"383\" width=\"70\" height=\"28\" rx=\"7\" fill=\"#e08a00\"\/><text x=\"110\" y=\"403\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#fff\">HTML<\/text>\n<rect x=\"155\" y=\"383\" width=\"70\" height=\"28\" rx=\"7\" fill=\"#5b6275\"\/><text x=\"190\" y=\"403\" text-anchor=\"middle\" font-size=\"14\" font-weight=\"700\" fill=\"#fff\">TXT<\/text>\n<text x=\"150\" y=\"436\" text-anchor=\"middle\" font-size=\"13\" fill=\"#8f9ad0\">messy, mixed formats<\/text><\/g>\n<g class=\"node\"><rect x=\"330\" y=\"310\" width=\"230\" height=\"130\" rx=\"16\" fill=\"#0b1020\" stroke=\"#61dafb\" stroke-width=\"2\"\/><text x=\"445\" y=\"342\" text-anchor=\"middle\" font-size=\"16\" font-weight=\"700\" fill=\"#a8ecfb\">1 \u00b7 Load + Clean<\/text>\n<text x=\"445\" y=\"374\" text-anchor=\"middle\" font-size=\"15\" fill=\"#e8ebff\">plain text<\/text><text x=\"445\" y=\"398\" text-anchor=\"middle\" font-size=\"15\" fill=\"#e8ebff\">+ metadata<\/text><text x=\"445\" y=\"422\" text-anchor=\"middle\" font-size=\"13\" fill=\"#8f9ad0\">source \u00b7 page \u00b7 section<\/text><\/g>\n<g class=\"node\"><rect x=\"640\" y=\"320\" width=\"220\" height=\"110\" rx=\"20\" fill=\"url(#ddac)\"\/><text x=\"750\" y=\"362\" text-anchor=\"middle\" font-size=\"16\" fill=\"#dfe3ff\">2 \u00b7 Chunk<\/text><text x=\"750\" y=\"398\" text-anchor=\"middle\" font-size=\"27\" font-weight=\"800\" fill=\"#fff\">Splitter<\/text><\/g>\n<g class=\"node\"><rect x=\"940\" y=\"300\" width=\"220\" height=\"150\" rx=\"16\" fill=\"#1b2250\" stroke=\"#89e051\" stroke-width=\"2\"\/><text x=\"1050\" y=\"330\" text-anchor=\"middle\" font-size=\"15\" fill=\"#b8f0a0\">3 \u00b7 Chunks with IDs<\/text>\n<rect x=\"962\" y=\"344\" width=\"176\" height=\"26\" rx=\"7\" fill=\"#2a2160\" stroke=\"#7c5cff\"\/><text x=\"974\" y=\"362\" font-size=\"13\" fill=\"#fff\">refund.md:1 \u00b7 280 chars<\/text>\n<rect x=\"962\" y=\"376\" width=\"176\" height=\"26\" rx=\"7\" fill=\"#1e2a5a\"\/><text x=\"974\" y=\"394\" font-size=\"13\" fill=\"#c9d1ff\">refund.md:2 \u00b7 260 chars<\/text>\n<rect x=\"962\" y=\"408\" width=\"176\" height=\"26\" rx=\"7\" fill=\"#1e2a5a\"\/><text x=\"974\" y=\"426\" font-size=\"13\" fill=\"#c9d1ff\">handbook.pdf:p2:1<\/text><\/g>\n<\/g>\n<path id=\"ddf1\" d=\"M250 375 L330 375\" fill=\"none\" stroke=\"url(#ddac)\" stroke-width=\"3\" stroke-dasharray=\"8 8\" opacity=\".8\"\/>\n<path id=\"ddf2\" d=\"M560 375 L640 375\" fill=\"none\" stroke=\"url(#ddac)\" stroke-width=\"3\" stroke-dasharray=\"8 8\" opacity=\".8\"\/>\n<path id=\"ddf3\" d=\"M860 375 L940 375\" fill=\"none\" stroke=\"url(#ddac)\" stroke-width=\"3\" stroke-dasharray=\"8 8\" opacity=\".8\"\/>\n<circle r=\"6\" fill=\"#61dafb\"><animateMotion dur=\"1.2s\" repeatCount=\"indefinite\"><mpath href=\"#ddf1\"\/><\/animateMotion><\/circle>\n<circle r=\"6\" fill=\"#7c5cff\"><animateMotion dur=\"1.2s\" begin=\".4s\" repeatCount=\"indefinite\"><mpath href=\"#ddf2\"\/><\/animateMotion><\/circle>\n<circle r=\"6\" fill=\"#89e051\"><animateMotion dur=\"1.2s\" begin=\".8s\" repeatCount=\"indefinite\"><mpath href=\"#ddf3\"\/><\/animateMotion><\/circle>\n<circle r=\"4\" fill=\"#ffffff\"><animateMotion dur=\"1.2s\" begin=\".6s\" repeatCount=\"indefinite\"><mpath href=\"#ddf2\"\/><\/animateMotion><\/circle>\n<text x=\"60\" y=\"505\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"16\" fill=\"#7f89b5\">devdojo.co.in \u00b7 Beginner friendly \u00b7 Python + Node.js examples<\/text>\n<\/svg>\n<\/div>\n\n<div class=\"dd-series\">Series: Generative AI <span>Part 12 of 30<\/span><\/div>\n<p class=\"dd-prereq\"><strong>What you should know first:<\/strong> read <a href=\"https:\/\/devdojo.co.in\/?p=313\">Part 11: RAG Fundamentals<\/a> and <a href=\"https:\/\/devdojo.co.in\/?p=306\">Part 9: Embeddings Explained<\/a>. You need Python 3.10+ or Node.js 20+. No API key is needed for any example in this post.<\/p>\n\n<p>In Part 11 we built a RAG app, but we cheated a little: our &#8220;documents&#8221; were four neat sentences typed straight into the code. Real knowledge lives in PDFs, web pages, Markdown docs and messy notes. Before an LLM can answer from them, you must <strong>load<\/strong> each file into clean text and then cut that text into small, meaningful pieces called <strong>chunks<\/strong>. In this post you will learn <strong>document loading and chunking strategies<\/strong> for RAG: how to read PDF, HTML, Markdown and text files in Python and Node.js, how fixed-size, overlapping, recursive and heading-based chunking differ, and how to test which chunking strategy gives the best answers on your own data.<\/p>\n\n<div class=\"dd-summary\">\n<strong class=\"lbl\">Quick Summary<\/strong>\n<ul>\n<li><strong>Document loading<\/strong> = turning each file (PDF, HTML, Markdown, text) into plain text plus <strong>metadata<\/strong> like file name, page and section.<\/li>\n<li><strong>Chunking<\/strong> = cutting that text into pieces small enough to embed and retrieve, but big enough to hold a complete idea.<\/li>\n<li>Four main <strong>chunking strategies<\/strong>: fixed size, fixed size with <strong>overlap<\/strong>, <strong>recursive<\/strong> (paragraph \u2192 sentence \u2192 word) and <strong>by structure<\/strong> (headings, pages).<\/li>\n<li>A good default: split by headings when you have them, then use a recursive splitter of about 300&#8211;1,000 characters with 10&#8211;20% overlap.<\/li>\n<li>Don&#8217;t guess. Write 10&#8211;20 test questions and measure which strategy retrieves the right chunk.<\/li>\n<\/ul>\n<\/div>\n\n<nav class=\"dd-toc\" aria-label=\"Table of contents\">\n<strong>In this post<\/strong>\n<ol>\n<li><a href=\"#what-is-chunking\">What are document loading and chunking?<\/a><\/li>\n<li><a href=\"#why-chunking\">Why chunk size matters<\/a><\/li>\n<li><a href=\"#loading\">Loading PDF, HTML, Markdown and text<\/a><\/li>\n<li><a href=\"#strategies\">Chunking strategies for RAG<\/a><\/li>\n<li><a href=\"#from-scratch\">Chunkers from scratch<\/a><\/li>\n<li><a href=\"#langchain\">LangChain text splitters<\/a><\/li>\n<li><a href=\"#measure\">Testing which strategy works best<\/a><\/li>\n<li><a href=\"#pipeline\">A complete ingest pipeline<\/a><\/li>\n<li><a href=\"#sizes\">Choosing chunk size and overlap<\/a><\/li>\n<li><a href=\"#errors\">Common errors and fixes<\/a><\/li>\n<li><a href=\"#practice\">Practice task<\/a><\/li>\n<li><a href=\"#faq\">FAQ<\/a><\/li>\n<\/ol>\n<\/nav>\n\n<details class=\"dd-roadmap\">\n<summary>Full Generative AI roadmap (30 parts)<\/summary>\n<h4>Beginner<\/h4>\n<ol start=\"1\">\n<li><a href=\"https:\/\/devdojo.co.in\/?p=215\">What Is Generative AI and How Do LLMs Work?<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=219\">Tokens, Context Windows and Model Parameters<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=223\">Your First LLM API Calls in Python and Node.js (OpenAI, Anthropic, Gemini)<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=240\">Prompt Engineering Basics: Roles, Instructions and Examples<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=244\">Temperature, Top-p and Controlling Model Output<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=281\">Run LLMs Locally with Ollama<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=284\">Streaming Responses and Building a Simple Chat UI<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=303\">Structured Outputs: Getting Reliable JSON from LLMs<\/a><\/li>\n<\/ol>\n<h4>Intermediate<\/h4>\n<ol start=\"9\">\n<li><a href=\"https:\/\/devdojo.co.in\/?p=306\">Embeddings Explained: Turning Text into Vectors<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=310\">Vector Databases: pgvector, Chroma and Pinecone<\/a><\/li>\n<li><a href=\"https:\/\/devdojo.co.in\/?p=313\">RAG Fundamentals: Retrieval-Augmented Generation<\/a><\/li>\n<li><strong>Document Loading and Chunking Strategies<\/strong><span class=\"here\">You are here<\/span><\/li>\n<li>Better RAG: Hybrid Search, Re-ranking and Query Rewriting<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Function Calling and Tool Use<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Conversation Memory and Long Context Management<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Multimodal AI: Vision, Images and Audio Inputs<span class=\"soon\">Coming soon<\/span><\/li>\n<li>How Image Generation Works: Diffusion Models Basics<span class=\"soon\">Coming soon<\/span><\/li>\n<li>LangChain vs LlamaIndex: When to Use a Framework<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Testing LLM Apps: Evals, Metrics and Test Sets<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Cutting Cost and Latency: Caching, Batching and Model Choice<span class=\"soon\">Coming soon<\/span><\/li>\n<\/ol>\n<h4>Advanced<\/h4>\n<ol start=\"21\">\n<li>Fine-Tuning vs Prompting vs RAG: Choosing the Right Tool<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Fine-Tuning an Open Model with LoRA<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Transformers Deep Dive: Attention Explained Simply<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Reasoning Models and Thinking Time<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Guardrails, Safety and Prompt Injection Defence<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Monitoring and Tracing LLM Apps in Production<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Serving Open Models: vLLM, Quantization and GPUs<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Building a Production GenAI App End to End<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Responsible AI: Privacy, Licensing and Bias<span class=\"soon\">Coming soon<\/span><\/li>\n<li>Final Project: Build Your Own AI Knowledge Assistant<span class=\"soon\">Coming soon<\/span><\/li>\n<\/ol>\n<\/details>\n\n<h2 id=\"what-is-chunking\">What are document loading and chunking?<\/h2>\n<p>Every RAG app has an <strong>indexing<\/strong> phase that runs before anyone asks a question (you saw it in Part 11). Today we zoom into its first three steps:<\/p>\n<ol>\n<li><strong>Load:<\/strong> open each file and pull out its text. A PDF needs a PDF reader, a web page needs its HTML tags removed, a Markdown file can be read as it is.<\/li>\n<li><strong>Clean:<\/strong> throw away text that is not real content: menus, cookie banners, footers, page numbers, repeated headers.<\/li>\n<li><strong>Chunk:<\/strong> cut the clean text into pieces and attach metadata to each piece, so you can cite it later (&#8220;refund-policy.md, section: How to ask for a refund&#8221;).<\/li>\n<\/ol>\n<p>Only after this do you create embeddings and store them in a vector database.<\/p>\n<figure>\n<svg viewBox=\"0 0 1000 300\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" role=\"img\" aria-label=\"The RAG indexing pipeline: files are loaded, cleaned and chunked (the focus of this post), then each chunk is embedded and stored in a vector database\">\n<rect width=\"1000\" height=\"300\" rx=\"14\" fill=\"#0f1430\"\/>\n<rect x=\"20\" y=\"40\" width=\"490\" height=\"190\" rx=\"14\" fill=\"none\" stroke=\"#7c5cff\" stroke-width=\"2\" stroke-dasharray=\"7 6\"\/>\n<text x=\"265\" y=\"28\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"15\" font-weight=\"700\" fill=\"#b9a8ff\">This post: Load \u2192 Clean \u2192 Chunk<\/text>\n<g font-family=\"Segoe UI,Arial,sans-serif\" text-anchor=\"middle\">\n<rect x=\"40\" y=\"90\" width=\"130\" height=\"90\" rx=\"12\" fill=\"#1b2250\" stroke=\"#3178c6\" stroke-width=\"2\"\/><text x=\"105\" y=\"128\" font-size=\"18\" font-weight=\"700\" fill=\"#fff\">Load<\/text><text x=\"105\" y=\"153\" font-size=\"13\" fill=\"#aab4e8\">PDF, MD, HTML<\/text>\n<rect x=\"200\" y=\"90\" width=\"130\" height=\"90\" rx=\"12\" fill=\"#1b2250\" stroke=\"#61dafb\" stroke-width=\"2\"\/><text x=\"265\" y=\"128\" font-size=\"18\" font-weight=\"700\" fill=\"#fff\">Clean<\/text><text x=\"265\" y=\"153\" font-size=\"13\" fill=\"#aab4e8\">drop menus, ads<\/text>\n<rect x=\"360\" y=\"90\" width=\"130\" height=\"90\" rx=\"12\" fill=\"#2a2160\" stroke=\"#7c5cff\" stroke-width=\"2\"\/><text x=\"425\" y=\"128\" font-size=\"18\" font-weight=\"700\" fill=\"#fff\">Chunk<\/text><text x=\"425\" y=\"153\" font-size=\"13\" fill=\"#c9bfff\">split + metadata<\/text>\n<rect x=\"560\" y=\"90\" width=\"150\" height=\"90\" rx=\"12\" fill=\"#151b3b\" stroke=\"#5b6275\" stroke-width=\"2\"\/><text x=\"635\" y=\"128\" font-size=\"18\" font-weight=\"700\" fill=\"#dfe3ff\">Embed<\/text><text x=\"635\" y=\"153\" font-size=\"13\" fill=\"#8f9ad0\">Part 9<\/text>\n<rect x=\"760\" y=\"90\" width=\"200\" height=\"90\" rx=\"12\" fill=\"#151b3b\" stroke=\"#5b6275\" stroke-width=\"2\"\/><text x=\"860\" y=\"128\" font-size=\"18\" font-weight=\"700\" fill=\"#dfe3ff\">Store<\/text><text x=\"860\" y=\"153\" font-size=\"13\" fill=\"#8f9ad0\">vector DB \u00b7 Part 10<\/text>\n<\/g>\n<g stroke=\"#7c5cff\" stroke-width=\"3\" fill=\"#7c5cff\"><path d=\"M170 135h22\"\/><path d=\"M330 135h22\"\/><path d=\"M490 135h62\"\/><path d=\"M710 135h42\"\/><\/g>\n<g fill=\"#7c5cff\"><path d=\"M192 129l8 6-8 6z\"\/><path d=\"M352 129l8 6-8 6z\"\/><path d=\"M552 129l8 6-8 6z\"\/><path d=\"M752 129l8 6-8 6z\"\/><\/g>\n<text x=\"500\" y=\"270\" text-anchor=\"middle\" font-family=\"Segoe UI,Arial,sans-serif\" font-size=\"15\" fill=\"#c9d1ff\">Bad chunks here = bad answers later. Retrieval can only find what chunking kept together.<\/text>\n<\/svg>\n<figcaption>Figure 1: The RAG indexing pipeline. Loading, cleaning and chunking happen before embeddings and the vector database you met in Parts 9 and 10.<\/figcaption>\n<\/figure>\n\n<p>Think of it like preparing notes for an open-book exam. If you tear the book into random strips, you will never find the right answer quickly. If you keep each topic on its own labelled card, you will.<\/p>\n\n<h2 id=\"why-chunking\">Why chunk size matters<\/h2>\n<p>Why not just embed a whole file? Because an embedding is <em>one<\/em> vector that summarises the whole text. Embed a 40-page handbook as one vector and its meaning becomes a blurry average of everything, so it matches no question well. Also, embedding models and LLMs have input limits (remember context windows from <a href=\"https:\/\/devdojo.co.in\/?p=219\">Part 2<\/a>).<\/p>\n<div class=\"dd-cards\">\n<div class=\"dd-card\"><b>Chunks too big<\/b>Vectors get blurry, retrieval gets less precise, and each chunk fills the prompt with unrelated text (more tokens, more cost, more confusion).<\/div>\n<div class=\"dd-card\"><b>Chunks too small<\/b>A single sentence like &#8220;It takes 5 to 7 days.&#8221; loses its context. What takes 5 to 7 days? The model can&#8217;t tell.<\/div>\n<div class=\"dd-card\"><b>Just right<\/b>One complete idea per chunk: a paragraph or a short section, with its title. Small enough to be precise, big enough to make sense alone.<\/div>\n<\/div>\n\n<h2 id=\"loading\">Step 1: Loading PDF, HTML, Markdown and text files<\/h2>\n<p>Let&#8217;s create a tiny knowledge base for an imaginary &#8220;DevDojo Pro&#8221; plan with four file types: <code>refund-policy.md<\/code>, a two-page <code>handbook.pdf<\/code>, an <code>faq.html<\/code> page (with a menu, footer and a script we must ignore) and <code>notes.txt<\/code>. Install the packages first:<\/p>\n<div class=\"dd-vsc dd-vsc-termonly\" role=\"group\" aria-label=\"Terminal: Terminal \u2014 setup\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">Terminal \u2014 setup<\/span><\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"c\"># Project folder with the sample files from this post<\/span>\n<span class=\"gp\">$<\/span> mkdir devdojo-chunking &amp;&amp; cd devdojo-chunking &amp;&amp; mkdir docs\n<span class=\"c\"># Python packages (Python 3.10+)<\/span>\n<span class=\"gp\">$<\/span> pip install pypdf langchain-text-splitters\n<span class=\"c\"># Node.js packages (Node.js 20+)<\/span>\n<span class=\"gp\">$<\/span> npm install unpdf @langchain\/textsplitters @langchain\/core<\/code><\/pre>\n<\/div>\n<p>We use <a href=\"https:\/\/pypdf.readthedocs.io\/en\/stable\/\" rel=\"noopener\" target=\"_blank\">pypdf<\/a> to read PDFs in Python and <code>unpdf<\/code> in Node.js. For HTML we keep things dependency-free: Python&#8217;s built-in <code>html.parser<\/code>, and a couple of regular expressions in Node.js. Every loader returns the same shape: <code>{text, metadata}<\/code>. PDFs return <strong>one document per page<\/strong>, so the page number becomes metadata you can cite.<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: load_docs.py, load_docs.mjs\">\n<input type=\"radio\" name=\"v1\" id=\"v1f1\" class=\"f1\" checked>\n<input type=\"radio\" name=\"v1\" id=\"v1f2\" class=\"f2\">\n<input type=\"checkbox\" id=\"v1r1\" class=\"r1\">\n<input type=\"checkbox\" id=\"v1r2\" class=\"r2\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">load_docs.py \u2014 devdojo-chunking \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v1f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>load_docs.py<\/label>\n<label for=\"v1f2\" class=\"t2\"><b class=\"ic js\">JS<\/b>load_docs.mjs<\/label>\n<label for=\"v1r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<label for=\"v1r2\" class=\"run run2\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">devdojo-chunking \u203a load_docs.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">pathlib<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Path<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">html.parser<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">HTMLParser<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">pypdf<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">PdfReader<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">class<\/span> <span class=\"nc\">TextOnly<\/span>(<span class=\"n\">HTMLParser<\/span>):<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"Keeps visible text, skips &lt;script&gt;, &lt;style&gt;, &lt;nav&gt; and &lt;footer&gt;.\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"n\">SKIP<\/span> = {<span class=\"s\">\"script\"<\/span>, <span class=\"s\">\"style\"<\/span>, <span class=\"s\">\"nav\"<\/span>, <span class=\"s\">\"footer\"<\/span>}<\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">__init__<\/span>(<span class=\"kc\">self<\/span>):<\/span>\n<span class=\"l\">        <span class=\"nb\">super<\/span>().<span class=\"nf\">__init__<\/span>()<\/span>\n<span class=\"l\">        <span class=\"kc\">self<\/span>.<span class=\"n\">parts<\/span>, <span class=\"kc\">self<\/span>.<span class=\"n\">skipping<\/span> = [], <span class=\"m\">0<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">handle_starttag<\/span>(<span class=\"kc\">self<\/span>, <span class=\"n\">tag<\/span>, <span class=\"n\">attrs<\/span>):<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> <span class=\"n\">tag<\/span> in <span class=\"kc\">self<\/span>.<span class=\"n\">SKIP<\/span>:<\/span>\n<span class=\"l\">            <span class=\"kc\">self<\/span>.<span class=\"n\">skipping<\/span> += <span class=\"m\">1<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">handle_endtag<\/span>(<span class=\"kc\">self<\/span>, <span class=\"n\">tag<\/span>):<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> <span class=\"n\">tag<\/span> in <span class=\"kc\">self<\/span>.<span class=\"n\">SKIP<\/span>:<\/span>\n<span class=\"l\">            <span class=\"kc\">self<\/span>.<span class=\"n\">skipping<\/span> -= <span class=\"m\">1<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">def<\/span> <span class=\"nf\">handle_data<\/span>(<span class=\"kc\">self<\/span>, <span class=\"n\">data<\/span>):<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> not <span class=\"kc\">self<\/span>.<span class=\"n\">skipping<\/span> and <span class=\"n\">data<\/span>.<span class=\"n\">strip<\/span>():<\/span>\n<span class=\"l\">            <span class=\"kc\">self<\/span>.<span class=\"n\">parts<\/span>.<span class=\"n\">append<\/span>(<span class=\"n\">data<\/span>.<span class=\"n\">strip<\/span>())<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">load<\/span>(<span class=\"n\">path<\/span>: <span class=\"n\">Path<\/span>):<\/span>\n<span class=\"l\">    <span class=\"s\">\"\"\"Return a list of {text, metadata} documents for one file.\"\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">if<\/span> <span class=\"n\">path<\/span>.<span class=\"n\">suffix<\/span> == <span class=\"s\">\".pdf\"<\/span>:<\/span>\n<span class=\"l\">        <span class=\"n\">reader<\/span> = <span class=\"n\">PdfReader<\/span>(<span class=\"n\">path<\/span>)<\/span>\n<span class=\"l\">        <span class=\"k\">return<\/span> [{<span class=\"s\">\"text\"<\/span>: <span class=\"n\">page<\/span>.<span class=\"n\">extract_text<\/span>(), <span class=\"s\">\"metadata\"<\/span>: {<span class=\"s\">\"source\"<\/span>: <span class=\"n\">path<\/span>.<span class=\"n\">name<\/span>, <span class=\"s\">\"page\"<\/span>: <span class=\"n\">i<\/span>}}<\/span>\n<span class=\"l\">                <span class=\"k\">for<\/span> <span class=\"n\">i<\/span>, <span class=\"n\">page<\/span> in <span class=\"nb\">enumerate<\/span>(<span class=\"n\">reader<\/span>.<span class=\"n\">pages<\/span>, <span class=\"m\">1<\/span>)]<\/span>\n<span class=\"l\">    <span class=\"n\">raw<\/span> = <span class=\"n\">path<\/span>.<span class=\"n\">read_text<\/span>(<span class=\"n\">encoding<\/span>=<span class=\"s\">\"utf-8\"<\/span>)<\/span>\n<span class=\"l\">    <span class=\"k\">if<\/span> <span class=\"n\">path<\/span>.<span class=\"n\">suffix<\/span> == <span class=\"s\">\".html\"<\/span>:<\/span>\n<span class=\"l\">        <span class=\"n\">parser<\/span> = <span class=\"n\">TextOnly<\/span>()<\/span>\n<span class=\"l\">        <span class=\"n\">parser<\/span>.<span class=\"n\">feed<\/span>(<span class=\"n\">raw<\/span>)<\/span>\n<span class=\"l\">        <span class=\"n\">raw<\/span> = <span class=\"s\">\"\\n\"<\/span>.<span class=\"n\">join<\/span>(<span class=\"n\">parser<\/span>.<span class=\"n\">parts<\/span>)<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> [{<span class=\"s\">\"text\"<\/span>: <span class=\"n\">raw<\/span>, <span class=\"s\">\"metadata\"<\/span>: {<span class=\"s\">\"source\"<\/span>: <span class=\"n\">path<\/span>.<span class=\"n\">name<\/span>}}]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">if<\/span> <span class=\"n\">__name__<\/span> == <span class=\"s\">\"__main__\"<\/span>:<\/span>\n<span class=\"l\">    <span class=\"n\">docs<\/span> = [<span class=\"n\">d<\/span> <span class=\"k\">for<\/span> <span class=\"n\">p<\/span> in <span class=\"nb\">sorted<\/span>(<span class=\"n\">Path<\/span>(<span class=\"s\">\"docs\"<\/span>).<span class=\"n\">iterdir<\/span>()) <span class=\"k\">for<\/span> <span class=\"n\">d<\/span> in <span class=\"n\">load<\/span>(<span class=\"n\">p<\/span>)]<\/span>\n<span class=\"l\">    <span class=\"k\">for<\/span> <span class=\"n\">d<\/span> in <span class=\"n\">docs<\/span>:<\/span>\n<span class=\"l\">        <span class=\"n\">preview<\/span> = <span class=\"n\">d<\/span>[<span class=\"s\">\"text\"<\/span>].<span class=\"n\">replace<\/span>(<span class=\"s\">\"\\n\"<\/span>, <span class=\"s\">\" \"<\/span>)[:<span class=\"m\">55<\/span>]<\/span>\n<span class=\"l\">        <span class=\"nb\">print<\/span>(<span class=\"s\">f\"{<\/span><span class=\"nb\">str<\/span>(<span class=\"n\">d<\/span>[<span class=\"s\">'metadata'<\/span>])<span class=\"s\">:38} {<\/span><span class=\"nb\">len<\/span>(<span class=\"n\">d<\/span>[<span class=\"s\">'text'<\/span>])<span class=\"s\">:4} chars | {<\/span><span class=\"n\">preview<\/span><span class=\"s\">}...\"<\/span>)<\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">f\"Loaded {<\/span><span class=\"nb\">len<\/span>(<span class=\"n\">docs<\/span>)<span class=\"s\">} documents\"<\/span>)<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> python load_docs.py\n{'source': 'faq.html'}                  281 chars | DevDojo FAQ Frequently asked questions Do I get a certi...\n{'source': 'handbook.pdf', 'page': 1}   173 chars | DevDojo Student Handbook Page 1: Getting started Create...\n{'source': 'handbook.pdf', 'page': 2}   201 chars | Page 2: Mentors and projects Every DevDojo Pro student ...\n{'source': 'notes.txt'}                 246 chars | Team meeting notes - support desk  Support is available...\n{'source': 'refund-policy.md'}          538 chars | # DevDojo Pro Refund Policy  DevDojo Pro is our paid pl...\nLoaded 5 documents<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 39, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<div class=\"dd-vsc-pane p2\">\n<div class=\"dd-vsc-crumbs\">devdojo-chunking \u203a load_docs.mjs<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"k\">import<\/span> { <span class=\"n\">readdir<\/span>, <span class=\"n\">readFile<\/span> } <span class=\"k\">from<\/span> <span class=\"s\">\"node:fs\/promises\"<\/span>;<\/span>\n<span class=\"l\"><span class=\"k\">import<\/span> { <span class=\"n\">extname<\/span>, <span class=\"n\">join<\/span> } <span class=\"k\">from<\/span> <span class=\"s\">\"node:path\"<\/span>;<\/span>\n<span class=\"l\"><span class=\"k\">import<\/span> { <span class=\"n\">extractText<\/span>, <span class=\"n\">getDocumentProxy<\/span> } <span class=\"k\">from<\/span> <span class=\"s\">\"unpdf\"<\/span>;<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\">\/\/ Keep visible text: drop &lt;script&gt;, &lt;style&gt;, &lt;nav&gt;, &lt;footer&gt;, then all tags<\/span><\/span>\n<span class=\"l\"><span class=\"kc\">function<\/span> <span class=\"n\">htmlToText<\/span>(<span class=\"n\">html<\/span>) {<\/span>\n<span class=\"l\">  <span class=\"k\">return<\/span> <span class=\"n\">html<\/span><\/span>\n<span class=\"l\">    .<span class=\"n\">replace<\/span>(<span class=\"s\">\/&lt;(script|style|nav|footer)[\\s\\S]*?&lt;\\\/\\1&gt;\/gi<\/span>, <span class=\"s\">\" \"<\/span>)<\/span>\n<span class=\"l\">    .<span class=\"n\">replace<\/span>(<span class=\"s\">\/&lt;[^&gt;]+&gt;\/g<\/span>, <span class=\"s\">\"\\n\"<\/span>)<\/span>\n<span class=\"l\">    .<span class=\"n\">split<\/span>(<span class=\"s\">\"\\n\"<\/span>).<span class=\"n\">map<\/span>((<span class=\"n\">s<\/span>) =&gt; <span class=\"n\">s<\/span>.<span class=\"n\">trim<\/span>()).<span class=\"n\">filter<\/span>(<span class=\"nb\">Boolean<\/span>).<span class=\"n\">join<\/span>(<span class=\"s\">\"\\n\"<\/span>);<\/span>\n<span class=\"l\">}<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">async<\/span> <span class=\"kc\">function<\/span> <span class=\"n\">load<\/span>(<span class=\"n\">file<\/span>) {<\/span>\n<span class=\"l\">  <span class=\"kc\">const<\/span> <span class=\"n\">path<\/span> = <span class=\"n\">join<\/span>(<span class=\"s\">\"docs\"<\/span>, <span class=\"n\">file<\/span>);<\/span>\n<span class=\"l\">  <span class=\"k\">if<\/span> (<span class=\"n\">extname<\/span>(<span class=\"n\">file<\/span>) === <span class=\"s\">\".pdf\"<\/span>) {<\/span>\n<span class=\"l\">    <span class=\"kc\">const<\/span> <span class=\"n\">pdf<\/span> = <span class=\"k\">await<\/span> <span class=\"n\">getDocumentProxy<\/span>(new <span class=\"nb\">Uint8Array<\/span>(<span class=\"k\">await<\/span> <span class=\"n\">readFile<\/span>(<span class=\"n\">path<\/span>)));<\/span>\n<span class=\"l\">    <span class=\"kc\">const<\/span> { <span class=\"n\">text<\/span> } = <span class=\"k\">await<\/span> <span class=\"n\">extractText<\/span>(<span class=\"n\">pdf<\/span>, { <span class=\"n\">mergePages<\/span>: <span class=\"kc\">false<\/span> });<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"n\">text<\/span>.<span class=\"n\">map<\/span>((<span class=\"n\">t<\/span>, <span class=\"n\">i<\/span>) =&gt; ({ <span class=\"n\">text<\/span>: <span class=\"n\">t<\/span>, <span class=\"n\">metadata<\/span>: { <span class=\"n\">source<\/span>: <span class=\"n\">file<\/span>, <span class=\"n\">page<\/span>: <span class=\"n\">i<\/span> + <span class=\"m\">1<\/span> } }));<\/span>\n<span class=\"l\">  }<\/span>\n<span class=\"l\">  <span class=\"kc\">let<\/span> <span class=\"n\">raw<\/span> = <span class=\"k\">await<\/span> <span class=\"n\">readFile<\/span>(<span class=\"n\">path<\/span>, <span class=\"s\">\"utf8\"<\/span>);<\/span>\n<span class=\"l\">  <span class=\"k\">if<\/span> (<span class=\"n\">extname<\/span>(<span class=\"n\">file<\/span>) === <span class=\"s\">\".html\"<\/span>) <span class=\"n\">raw<\/span> = <span class=\"n\">htmlToText<\/span>(<span class=\"n\">raw<\/span>);<\/span>\n<span class=\"l\">  <span class=\"k\">return<\/span> [{ <span class=\"n\">text<\/span>: <span class=\"n\">raw<\/span>, <span class=\"n\">metadata<\/span>: { <span class=\"n\">source<\/span>: <span class=\"n\">file<\/span> } }];<\/span>\n<span class=\"l\">}<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"kc\">const<\/span> <span class=\"n\">files<\/span> = (<span class=\"k\">await<\/span> <span class=\"n\">readdir<\/span>(<span class=\"s\">\"docs\"<\/span>)).<span class=\"n\">sort<\/span>();<\/span>\n<span class=\"l\"><span class=\"kc\">const<\/span> <span class=\"n\">docs<\/span> = (<span class=\"k\">await<\/span> <span class=\"nb\">Promise<\/span>.<span class=\"n\">all<\/span>(<span class=\"n\">files<\/span>.<span class=\"n\">map<\/span>(<span class=\"n\">load<\/span>))).<span class=\"n\">flat<\/span>();<\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> (<span class=\"kc\">const<\/span> <span class=\"n\">d<\/span> <span class=\"k\">of<\/span> <span class=\"n\">docs<\/span>) {<\/span>\n<span class=\"l\">  <span class=\"kc\">const<\/span> <span class=\"n\">preview<\/span> = <span class=\"n\">d<\/span>.<span class=\"n\">text<\/span>.<span class=\"n\">replace<\/span>(<span class=\"s\">\/\\n\/g<\/span>, <span class=\"s\">\" \"<\/span>).<span class=\"n\">slice<\/span>(<span class=\"m\">0<\/span>, <span class=\"m\">55<\/span>);<\/span>\n<span class=\"l\">  <span class=\"n\">console<\/span>.<span class=\"n\">log<\/span>(<span class=\"s\">`${<\/span><span class=\"nb\">JSON<\/span>.<span class=\"n\">stringify<\/span>(<span class=\"n\">d<\/span>.<span class=\"n\">metadata<\/span>).<span class=\"n\">padEnd<\/span>(<span class=\"m\">38<\/span>)<span class=\"s\">} ${<\/span><span class=\"nb\">String<\/span>(<span class=\"n\">d<\/span>.<span class=\"n\">text<\/span>.<span class=\"n\">length<\/span>).<span class=\"n\">padStart<\/span>(<span class=\"m\">4<\/span>)<span class=\"s\">} chars | ${<\/span><span class=\"n\">preview<\/span><span class=\"s\">}...`<\/span>);<\/span>\n<span class=\"l\">}<\/span>\n<span class=\"l\"><span class=\"n\">console<\/span>.<span class=\"n\">log<\/span>(<span class=\"s\">`Loaded ${<\/span><span class=\"n\">docs<\/span>.<span class=\"n\">length<\/span><span class=\"s\">} documents`<\/span>);<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> node load_docs.mjs\n{\"source\":\"faq.html\"}                   281 chars | DevDojo FAQ Frequently asked questions Do I get a certi...\n{\"source\":\"handbook.pdf\",\"page\":1}      173 chars | DevDojo Student Handbook Page 1: Getting started Create...\n{\"source\":\"handbook.pdf\",\"page\":2}      201 chars | Page 2: Mentors and projects Every DevDojo Pro student ...\n{\"source\":\"notes.txt\"}                  246 chars | Team meeting notes - support desk  Support is available...\n{\"source\":\"refund-policy.md\"}           538 chars | # DevDojo Pro Refund Policy  DevDojo Pro is our paid pl...\nLoaded 5 documents<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 31, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 2<\/span><span>UTF-8<\/span><span>LF<\/span><span>JavaScript<\/span><\/div>\n<\/div>\n<\/div>\n<p class=\"dd-vsc-hint\">Click the <strong>load_docs.py<\/strong> \/ <strong>load_docs.mjs<\/strong> tabs to switch language, then press <strong>\u25b6 Run<\/strong> to see the real output.<\/p>\n<div class=\"dd-note\"><strong>Why one document per PDF page?<\/strong> When the bot answers &#8220;Mentors review 3 projects (handbook.pdf, page 2)&#8221;, users can open the exact page and check. Keep metadata from the very first step; it is very hard to add later.<\/div>\n<div class=\"dd-warn\"><strong>Scanned PDFs have no text.<\/strong> If <code>extract_text()<\/code> returns an empty string, the PDF is just images of pages. You need OCR (for example Tesseract) or a document-parsing service before you can chunk it.<\/div>\n\n<h2 id=\"strategies\">Chunking strategies for RAG<\/h2>\n<p>There are many chunking strategies, but four cover almost every project. Click through the explorer below to compare them.<\/p>\n<div class=\"dd-tabs\" role=\"group\" aria-label=\"Chunking strategy explorer\">\n<input type=\"radio\" name=\"ddst\" id=\"ti1\" checked>\n<input type=\"radio\" name=\"ddst\" id=\"ti2\">\n<input type=\"radio\" name=\"ddst\" id=\"ti3\">\n<input type=\"radio\" name=\"ddst\" id=\"ti4\">\n<div class=\"labels\"><label for=\"ti1\">1 \u00b7 Fixed size<\/label><label for=\"ti2\">2 \u00b7 Fixed + overlap<\/label><label for=\"ti3\">3 \u00b7 Recursive<\/label><label for=\"ti4\">4 \u00b7 By structure<\/label><\/div>\n<div class=\"panel p1\"><p><strong>How it works:<\/strong> cut the text every N characters (or N tokens), no matter what is there.<\/p><p><strong>Good:<\/strong> very simple, fast, predictable chunk sizes. <strong>Bad:<\/strong> breaks words and sentences, so one fact can end up split across two chunks and neither chunk answers the question.<\/p><p><strong>Use it when:<\/strong> you need a quick baseline, or the text has no structure at all (logs, transcripts).<\/p><\/div>\n<div class=\"panel p2\"><p><strong>How it works:<\/strong> fixed-size chunks, but each new chunk starts a little before the previous one ended (for example 300 characters with 50 of overlap).<\/p><p><strong>Good:<\/strong> a sentence cut at a border usually survives whole in the next chunk. <strong>Bad:<\/strong> more chunks to embed and store, and repeated text can show up twice in the prompt.<\/p><p><strong>Use it when:<\/strong> you use fixed or recursive splitting. 10&#8211;20% overlap is a common starting point.<\/p><\/div>\n<div class=\"panel p3\"><p><strong>How it works:<\/strong> try to split on the biggest natural break first (blank line between paragraphs), and only if a piece is still too long, split it on a smaller break (line, sentence, word). This is LangChain&#8217;s <code>RecursiveCharacterTextSplitter<\/code>.<\/p><p><strong>Good:<\/strong> respects paragraphs and sentences while keeping a size limit. <strong>Bad:<\/strong> does not know what a heading means, so a heading can land alone in its own tiny chunk.<\/p><p><strong>Use it when:<\/strong> almost always. It is the best general-purpose default.<\/p><\/div>\n<div class=\"panel p4\"><p><strong>How it works:<\/strong> split on the document&#8217;s own structure: Markdown or HTML headings, PDF pages, code functions. Each chunk keeps its section title as metadata. Long sections are then cut again with a recursive splitter.<\/p><p><strong>Good:<\/strong> each chunk is one complete topic, and you can cite &#8220;Refund Policy \u203a How to ask for a refund&#8221;. <strong>Bad:<\/strong> needs clean structure; sections can be very uneven in size.<\/p><p><strong>Use it when:<\/strong> docs, help centres, wikis, READMEs, legal and policy pages.<\/p><\/div>\n<\/div>\n<figure>\n<svg viewBox=\"0 0 1000 404\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" role=\"img\" aria-label=\"The same refund policy split three ways: fixed size cuts sentences in the middle, overlap repeats a little text between chunks, and splitting by headings keeps each section whole\">\n<rect width=\"1000\" height=\"404\" rx=\"14\" fill=\"#0f1430\"\/>\n<g font-family=\"Segoe UI,Arial,sans-serif\">\n<text x=\"30\" y=\"48\" font-size=\"16\" font-weight=\"700\" fill=\"#ffffff\">Fixed size<\/text><text x=\"30\" y=\"68\" font-size=\"12.5\" fill=\"#8f9ad0\">cuts anywhere<\/text>\n<rect x=\"230\" y=\"34\" width=\"180\" height=\"34\" rx=\"7\" fill=\"#3a4170\" stroke=\"none\" stroke-width=\"2\"\/><text x=\"320.0\" y=\"56\" text-anchor=\"middle\" font-size=\"13\" fill=\"#fff\">\u2026refund within 7 da<\/text><rect x=\"416\" y=\"34\" width=\"180\" height=\"34\" rx=\"7\" fill=\"#3a4170\" stroke=\"none\" stroke-width=\"2\"\/><text x=\"506.0\" y=\"56\" text-anchor=\"middle\" font-size=\"13\" fill=\"#fff\">ys of your first pay<\/text><rect x=\"602\" y=\"34\" width=\"180\" height=\"34\" rx=\"7\" fill=\"#3a4170\" stroke=\"none\" stroke-width=\"2\"\/><text x=\"692.0\" y=\"56\" text-anchor=\"middle\" font-size=\"13\" fill=\"#fff\">ment. Refunds are no<\/text><rect x=\"788\" y=\"34\" width=\"180\" height=\"34\" rx=\"7\" fill=\"#3a4170\" stroke=\"none\" stroke-width=\"2\"\/><text x=\"878.0\" y=\"56\" text-anchor=\"middle\" font-size=\"13\" fill=\"#fff\">t available for\u2026<\/text>\n<g stroke=\"#e5534b\" stroke-width=\"3\"><path d=\"M413 28v46M599 28v46M785 28v46\"\/><\/g>\n<text x=\"230\" y=\"96\" font-size=\"12.5\" fill=\"#ff9a94\">Cuts &#8220;7 days&#8221; and &#8220;payment&#8221; in half<\/text>\n<text x=\"30\" y=\"170\" font-size=\"16\" font-weight=\"700\" fill=\"#ffffff\">With overlap<\/text><text x=\"30\" y=\"190\" font-size=\"12.5\" fill=\"#8f9ad0\">repeats a little text<\/text>\n<rect x=\"230\" y=\"140\" width=\"330\" height=\"34\" rx=\"7\" fill=\"#2c5a9a\" stroke=\"none\" stroke-width=\"2\"\/><text x=\"395.0\" y=\"162\" text-anchor=\"middle\" font-size=\"13\" fill=\"#fff\">\u2026refund within 7 days of your first<\/text>\n<rect x=\"450\" y=\"182\" width=\"330\" height=\"34\" rx=\"7\" fill=\"#2c5a9a\" stroke=\"none\" stroke-width=\"2\"\/><text x=\"615.0\" y=\"204\" text-anchor=\"middle\" font-size=\"13\" fill=\"#fff\">days of your first payment. Refunds are\u2026<\/text>\n<rect x=\"450\" y=\"136\" width=\"110\" height=\"84\" rx=\"9\" fill=\"#7c5cff\" fill-opacity=\".22\" stroke=\"#7c5cff\" stroke-width=\"2\" stroke-dasharray=\"5 4\"\/>\n<text x=\"572\" y=\"164\" font-size=\"12.5\" fill=\"#c9bfff\">shared part<\/text>\n<text x=\"230\" y=\"244\" font-size=\"12.5\" fill=\"#c9bfff\">The shared part keeps the sentence whole in at least one chunk<\/text>\n<text x=\"30\" y=\"296\" font-size=\"16\" font-weight=\"700\" fill=\"#ffffff\">By headings<\/text><text x=\"30\" y=\"316\" font-size=\"12.5\" fill=\"#8f9ad0\">follows structure<\/text>\n<rect x=\"230\" y=\"282\" width=\"230\" height=\"34\" rx=\"7\" fill=\"#1f7a4d\" stroke=\"#89e051\" stroke-width=\"2\"\/><text x=\"345.0\" y=\"304\" text-anchor=\"middle\" font-size=\"13\" fill=\"#fff\">## Who can get a refund<\/text><rect x=\"470\" y=\"282\" width=\"240\" height=\"34\" rx=\"7\" fill=\"#1f7a4d\" stroke=\"#89e051\" stroke-width=\"2\"\/><text x=\"590.0\" y=\"304\" text-anchor=\"middle\" font-size=\"13\" fill=\"#fff\">## How to ask for a refund<\/text><rect x=\"720\" y=\"282\" width=\"250\" height=\"34\" rx=\"7\" fill=\"#1f7a4d\" stroke=\"#89e051\" stroke-width=\"2\"\/><text x=\"845.0\" y=\"304\" text-anchor=\"middle\" font-size=\"13\" fill=\"#fff\">## When the money comes back<\/text>\n<text x=\"230\" y=\"344\" font-size=\"12.5\" fill=\"#b8f0a0\">Each chunk = one complete topic with its title. Best for docs with headings.<\/text>\n<text x=\"500\" y=\"384\" text-anchor=\"middle\" font-size=\"14\" fill=\"#c9d1ff\">Same text, three strategies, very different chunks.<\/text>\n<\/g>\n<\/svg>\n<figcaption>Figure 2: Fixed-size, overlapping and heading-based chunking of the same refund policy. Red lines show where a fixed-size split breaks words.<\/figcaption>\n<\/figure>\n<p>You may also hear about <strong>semantic chunking<\/strong> (start a new chunk where the meaning changes, measured with embeddings) and <strong>agentic or LLM-based chunking<\/strong> (ask a model to split the text). They can help on long, unstructured text, but they are slower and cost more. Start with recursive or structure-based splitting and only move on if your tests show a real gain.<\/p>\n\n<h2 id=\"from-scratch\">Chunkers from scratch in Python and Node.js<\/h2>\n<p>Libraries are great, but writing the three basic chunkers yourself takes 30 lines and makes everything else easy to understand. We run each one on <code>refund-policy.md<\/code> and print the start of the second chunk:<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: chunkers.py, chunkers.mjs\">\n<input type=\"radio\" name=\"v2\" id=\"v2f1\" class=\"f1\" checked>\n<input type=\"radio\" name=\"v2\" id=\"v2f2\" class=\"f2\">\n<input type=\"checkbox\" id=\"v2r1\" class=\"r1\">\n<input type=\"checkbox\" id=\"v2r2\" class=\"r2\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">chunkers.py \u2014 devdojo-chunking \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v2f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>chunkers.py<\/label>\n<label for=\"v2f2\" class=\"t2\"><b class=\"ic js\">JS<\/b>chunkers.mjs<\/label>\n<label for=\"v2r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<label for=\"v2r2\" class=\"run run2\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">devdojo-chunking \u203a chunkers.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">re<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">text<\/span> = <span class=\"nb\">open<\/span>(<span class=\"s\">\"docs\/refund-policy.md\"<\/span>, <span class=\"n\">encoding<\/span>=<span class=\"s\">\"utf-8\"<\/span>).<span class=\"n\">read<\/span>()<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\"># Strategy 1: fixed size (simple, but cuts words and sentences)<\/span><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">fixed_size<\/span>(<span class=\"n\">text<\/span>, <span class=\"n\">size<\/span>=<span class=\"m\">120<\/span>, <span class=\"n\">overlap<\/span>=<span class=\"m\">0<\/span>):<\/span>\n<span class=\"l\">    <span class=\"n\">step<\/span> = <span class=\"n\">size<\/span> - <span class=\"n\">overlap<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> [<span class=\"n\">text<\/span>[<span class=\"n\">i<\/span>:<span class=\"n\">i<\/span> + <span class=\"n\">size<\/span>] <span class=\"k\">for<\/span> <span class=\"n\">i<\/span> in <span class=\"nb\">range<\/span>(<span class=\"m\">0<\/span>, <span class=\"nb\">len<\/span>(<span class=\"n\">text<\/span>), <span class=\"n\">step<\/span>)]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\"># Strategy 2: sentence-based (pack whole sentences up to a size limit)<\/span><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">by_sentences<\/span>(<span class=\"n\">text<\/span>, <span class=\"n\">max_chars<\/span>=<span class=\"m\">200<\/span>):<\/span>\n<span class=\"l\">    <span class=\"n\">sentences<\/span> = <span class=\"n\">re<\/span>.<span class=\"n\">split<\/span>(<span class=\"s\">r\"(?&lt;=[.!?])\\s+\"<\/span>, <span class=\"n\">text<\/span>.<span class=\"n\">replace<\/span>(<span class=\"s\">\"\\n\"<\/span>, <span class=\"s\">\" \"<\/span>))<\/span>\n<span class=\"l\">    <span class=\"n\">chunks<\/span>, <span class=\"n\">current<\/span> = [], <span class=\"s\">\"\"<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">for<\/span> <span class=\"n\">s<\/span> in <span class=\"n\">sentences<\/span>:<\/span>\n<span class=\"l\">        <span class=\"k\">if<\/span> <span class=\"n\">current<\/span> and <span class=\"nb\">len<\/span>(<span class=\"n\">current<\/span>) + <span class=\"nb\">len<\/span>(<span class=\"n\">s<\/span>) + <span class=\"m\">1<\/span> &gt; <span class=\"n\">max_chars<\/span>:<\/span>\n<span class=\"l\">            <span class=\"n\">chunks<\/span>.<span class=\"n\">append<\/span>(<span class=\"n\">current<\/span>)<\/span>\n<span class=\"l\">            <span class=\"n\">current<\/span> = <span class=\"n\">s<\/span><\/span>\n<span class=\"l\">        <span class=\"k\">else<\/span>:<\/span>\n<span class=\"l\">            <span class=\"n\">current<\/span> = <span class=\"s\">f\"{<\/span><span class=\"n\">current<\/span><span class=\"s\">} {<\/span><span class=\"n\">s<\/span><span class=\"s\">}\"<\/span>.<span class=\"n\">strip<\/span>()<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"n\">chunks<\/span> + [<span class=\"n\">current<\/span>] <span class=\"k\">if<\/span> <span class=\"n\">current<\/span> <span class=\"k\">else<\/span> <span class=\"n\">chunks<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\"># Strategy 3: by Markdown headings (each section keeps its title)<\/span><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">by_headings<\/span>(<span class=\"n\">md<\/span>):<\/span>\n<span class=\"l\">    <span class=\"n\">sections<\/span> = <span class=\"n\">re<\/span>.<span class=\"n\">split<\/span>(<span class=\"s\">r\"\\n(?=#{1,3} )\"<\/span>, <span class=\"n\">md<\/span>.<span class=\"n\">strip<\/span>())<\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> [<span class=\"n\">s<\/span>.<span class=\"n\">strip<\/span>() <span class=\"k\">for<\/span> <span class=\"n\">s<\/span> in <span class=\"n\">sections<\/span> <span class=\"k\">if<\/span> <span class=\"n\">s<\/span>.<span class=\"n\">strip<\/span>()]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">if<\/span> <span class=\"n\">__name__<\/span> == <span class=\"s\">\"__main__\"<\/span>:<\/span>\n<span class=\"l\">    <span class=\"k\">for<\/span> <span class=\"n\">name<\/span>, <span class=\"n\">chunks<\/span> in [(<span class=\"s\">\"fixed_size(120)\"<\/span>, <span class=\"n\">fixed_size<\/span>(<span class=\"n\">text<\/span>)),<\/span>\n<span class=\"l\">                         (<span class=\"s\">\"fixed_size(120, overlap=30)\"<\/span>, <span class=\"n\">fixed_size<\/span>(<span class=\"n\">text<\/span>, <span class=\"m\">120<\/span>, <span class=\"m\">30<\/span>)),<\/span>\n<span class=\"l\">                         (<span class=\"s\">\"by_sentences(200)\"<\/span>, <span class=\"n\">by_sentences<\/span>(<span class=\"n\">text<\/span>)),<\/span>\n<span class=\"l\">                         (<span class=\"s\">\"by_headings\"<\/span>, <span class=\"n\">by_headings<\/span>(<span class=\"n\">text<\/span>))]:<\/span>\n<span class=\"l\">        <span class=\"nb\">print<\/span>(<span class=\"s\">f\"{<\/span><span class=\"n\">name<\/span><span class=\"s\">}: {<\/span><span class=\"nb\">len<\/span>(<span class=\"n\">chunks<\/span>)<span class=\"s\">} chunks\"<\/span>)<\/span>\n<span class=\"l\">        <span class=\"nb\">print<\/span>(<span class=\"s\">f\"  chunk 2 -&gt; {<\/span><span class=\"n\">chunks<\/span>[<span class=\"m\">1<\/span>][:<span class=\"m\">70<\/span>]<span class=\"s\">!r}\"<\/span>)<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> python chunkers.py\nfixed_size(120): 5 chunks\n  chunk 2 -&gt; 't a refund\\n\\nYou can ask for a full refund within 7 days of your first '\nfixed_size(120, overlap=30): 6 chunks\n  chunk 2 -&gt; 'doubt sessions.\\n\\n## Who can get a refund\\n\\nYou can ask for a full refun'\nby_sentences(200): 3 chunks\n  chunk 2 -&gt; 'Refunds are not available for renewals after the first month. ## How t'\nby_headings: 4 chunks\n  chunk 2 -&gt; '## Who can get a refund\\n\\nYou can ask for a full refund within 7 days o'<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 33, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<div class=\"dd-vsc-pane p2\">\n<div class=\"dd-vsc-crumbs\">devdojo-chunking \u203a chunkers.mjs<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"k\">import<\/span> { <span class=\"n\">readFileSync<\/span> } <span class=\"k\">from<\/span> <span class=\"s\">\"node:fs\"<\/span>;<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"kc\">const<\/span> <span class=\"n\">text<\/span> = <span class=\"n\">readFileSync<\/span>(<span class=\"s\">\"docs\/refund-policy.md\"<\/span>, <span class=\"s\">\"utf8\"<\/span>);<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\">\/\/ Strategy 1: fixed size (simple, but cuts words and sentences)<\/span><\/span>\n<span class=\"l\"><span class=\"kc\">function<\/span> <span class=\"n\">fixedSize<\/span>(<span class=\"n\">text<\/span>, <span class=\"n\">size<\/span> = <span class=\"m\">120<\/span>, <span class=\"n\">overlap<\/span> = <span class=\"m\">0<\/span>) {<\/span>\n<span class=\"l\">  <span class=\"kc\">const<\/span> <span class=\"n\">chunks<\/span> = [];<\/span>\n<span class=\"l\">  <span class=\"k\">for<\/span> (<span class=\"kc\">let<\/span> <span class=\"n\">i<\/span> = <span class=\"m\">0<\/span>; <span class=\"n\">i<\/span> &lt; <span class=\"n\">text<\/span>.<span class=\"n\">length<\/span>; <span class=\"n\">i<\/span> += <span class=\"n\">size<\/span> - <span class=\"n\">overlap<\/span>) <span class=\"n\">chunks<\/span>.<span class=\"n\">push<\/span>(<span class=\"n\">text<\/span>.<span class=\"n\">slice<\/span>(<span class=\"n\">i<\/span>, <span class=\"n\">i<\/span> + <span class=\"n\">size<\/span>));<\/span>\n<span class=\"l\">  <span class=\"k\">return<\/span> <span class=\"n\">chunks<\/span>;<\/span>\n<span class=\"l\">}<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\">\/\/ Strategy 2: sentence-based (pack whole sentences up to a size limit)<\/span><\/span>\n<span class=\"l\"><span class=\"kc\">function<\/span> <span class=\"n\">bySentences<\/span>(<span class=\"n\">text<\/span>, <span class=\"n\">maxChars<\/span> = <span class=\"m\">200<\/span>) {<\/span>\n<span class=\"l\">  <span class=\"kc\">const<\/span> <span class=\"n\">sentences<\/span> = <span class=\"n\">text<\/span>.<span class=\"n\">replace<\/span>(<span class=\"s\">\/\\n\/g<\/span>, <span class=\"s\">\" \"<\/span>).<span class=\"n\">split<\/span>(<span class=\"s\">\/(?&lt;=[.!?])\\s+\/<\/span>);<\/span>\n<span class=\"l\">  <span class=\"kc\">const<\/span> <span class=\"n\">chunks<\/span> = [];<\/span>\n<span class=\"l\">  <span class=\"kc\">let<\/span> <span class=\"n\">current<\/span> = <span class=\"s\">\"\"<\/span>;<\/span>\n<span class=\"l\">  <span class=\"k\">for<\/span> (<span class=\"kc\">const<\/span> <span class=\"n\">s<\/span> <span class=\"k\">of<\/span> <span class=\"n\">sentences<\/span>) {<\/span>\n<span class=\"l\">    <span class=\"k\">if<\/span> (<span class=\"n\">current<\/span> &amp;&amp; <span class=\"n\">current<\/span>.<span class=\"n\">length<\/span> + <span class=\"n\">s<\/span>.<span class=\"n\">length<\/span> + <span class=\"m\">1<\/span> &gt; <span class=\"n\">maxChars<\/span>) {<\/span>\n<span class=\"l\">      <span class=\"n\">chunks<\/span>.<span class=\"n\">push<\/span>(<span class=\"n\">current<\/span>);<\/span>\n<span class=\"l\">      <span class=\"n\">current<\/span> = <span class=\"n\">s<\/span>;<\/span>\n<span class=\"l\">    } <span class=\"k\">else<\/span> <span class=\"n\">current<\/span> = <span class=\"s\">`${<\/span><span class=\"n\">current<\/span><span class=\"s\">} ${<\/span><span class=\"n\">s<\/span><span class=\"s\">}`<\/span>.<span class=\"n\">trim<\/span>();<\/span>\n<span class=\"l\">  }<\/span>\n<span class=\"l\">  <span class=\"k\">return<\/span> <span class=\"n\">current<\/span> ? [...<span class=\"n\">chunks<\/span>, <span class=\"n\">current<\/span>] : <span class=\"n\">chunks<\/span>;<\/span>\n<span class=\"l\">}<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\">\/\/ Strategy 3: by Markdown headings (each section keeps its title)<\/span><\/span>\n<span class=\"l\"><span class=\"kc\">const<\/span> <span class=\"n\">byHeadings<\/span> = (<span class=\"n\">md<\/span>) =&gt;<\/span>\n<span class=\"l\">  <span class=\"n\">md<\/span>.<span class=\"n\">trim<\/span>().<span class=\"n\">split<\/span>(<span class=\"s\">\/\\n(?=#{1,3} )\/<\/span>).<span class=\"n\">map<\/span>((<span class=\"n\">s<\/span>) =&gt; <span class=\"n\">s<\/span>.<span class=\"n\">trim<\/span>()).<span class=\"n\">filter<\/span>(<span class=\"nb\">Boolean<\/span>);<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> (<span class=\"kc\">const<\/span> [<span class=\"n\">name<\/span>, <span class=\"n\">chunks<\/span>] <span class=\"k\">of<\/span> [<\/span>\n<span class=\"l\">  [<span class=\"s\">\"fixedSize(120)\"<\/span>, <span class=\"n\">fixedSize<\/span>(<span class=\"n\">text<\/span>)],<\/span>\n<span class=\"l\">  [<span class=\"s\">\"fixedSize(120, overlap=30)\"<\/span>, <span class=\"n\">fixedSize<\/span>(<span class=\"n\">text<\/span>, <span class=\"m\">120<\/span>, <span class=\"m\">30<\/span>)],<\/span>\n<span class=\"l\">  [<span class=\"s\">\"bySentences(200)\"<\/span>, <span class=\"n\">bySentences<\/span>(<span class=\"n\">text<\/span>)],<\/span>\n<span class=\"l\">  [<span class=\"s\">\"byHeadings\"<\/span>, <span class=\"n\">byHeadings<\/span>(<span class=\"n\">text<\/span>)],<\/span>\n<span class=\"l\">]) {<\/span>\n<span class=\"l\">  <span class=\"n\">console<\/span>.<span class=\"n\">log<\/span>(<span class=\"s\">`${<\/span><span class=\"n\">name<\/span><span class=\"s\">}: ${<\/span><span class=\"n\">chunks<\/span>.<span class=\"n\">length<\/span><span class=\"s\">} chunks`<\/span>);<\/span>\n<span class=\"l\">  <span class=\"n\">console<\/span>.<span class=\"n\">log<\/span>(<span class=\"s\">`  chunk 2 -&gt; ${<\/span><span class=\"nb\">JSON<\/span>.<span class=\"n\">stringify<\/span>(<span class=\"n\">chunks<\/span>[<span class=\"m\">1<\/span>].<span class=\"n\">slice<\/span>(<span class=\"m\">0<\/span>, <span class=\"m\">70<\/span>))<span class=\"s\">}`<\/span>);<\/span>\n<span class=\"l\">}<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> node chunkers.mjs\nfixedSize(120): 5 chunks\n  chunk 2 -&gt; \"t a refund\\n\\nYou can ask for a full refund within 7 days of your first \"\nfixedSize(120, overlap=30): 6 chunks\n  chunk 2 -&gt; \"doubt sessions.\\n\\n## Who can get a refund\\n\\nYou can ask for a full refun\"\nbySentences(200): 3 chunks\n  chunk 2 -&gt; \"Refunds are not available for renewals after the first month. ## How t\"\nbyHeadings: 4 chunks\n  chunk 2 -&gt; \"## Who can get a refund\\n\\nYou can ask for a full refund within 7 days o\"<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 38, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 2<\/span><span>UTF-8<\/span><span>LF<\/span><span>JavaScript<\/span><\/div>\n<\/div>\n<\/div>\n<p class=\"dd-vsc-hint\">Press <strong>\u25b6 Run<\/strong> and look at &#8220;chunk 2&#8221; for each strategy: only the heading-based chunk starts at a clean boundary.<\/p>\n<p>Look closely at the output. The plain fixed-size chunk starts with <code>\"t a refund\"<\/code>: a broken word. With overlap, chunk 2 starts a bit earlier and keeps the full heading. The sentence chunker keeps whole sentences, but it removed the line breaks, so a heading (<code>## How t&#8230;<\/code>) got glued onto the previous section. Only the heading-based chunker starts exactly at a topic boundary.<\/p>\n\n<h2 id=\"langchain\">LangChain text splitters (Python and Node.js)<\/h2>\n<p>In real projects you will usually use a ready-made splitter. The most popular are in LangChain&#8217;s small, standalone text splitter packages. You don&#8217;t need the rest of LangChain to use them. The <a href=\"https:\/\/docs.langchain.com\/oss\/python\/integrations\/splitters\/recursive_text_splitter\" rel=\"noopener\" target=\"_blank\">RecursiveCharacterTextSplitter<\/a> tries a list of separators in order (<code>\"\\n\\n\"<\/code>, <code>\"\\n\"<\/code>, sentence end, space) and only falls back to a smaller one when a piece is still longer than <code>chunk_size<\/code>.<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: splitters.py, splitters.mjs\">\n<input type=\"radio\" name=\"v3\" id=\"v3f1\" class=\"f1\" checked>\n<input type=\"radio\" name=\"v3\" id=\"v3f2\" class=\"f2\">\n<input type=\"checkbox\" id=\"v3r1\" class=\"r1\">\n<input type=\"checkbox\" id=\"v3r2\" class=\"r2\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">splitters.py \u2014 devdojo-chunking \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v3f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>splitters.py<\/label>\n<label for=\"v3f2\" class=\"t2\"><b class=\"ic js\">JS<\/b>splitters.mjs<\/label>\n<label for=\"v3r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<label for=\"v3r2\" class=\"run run2\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">devdojo-chunking \u203a splitters.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">langchain_text_splitters<\/span> <span class=\"kn\">import<\/span> (<\/span>\n<span class=\"l\">    <span class=\"n\">MarkdownHeaderTextSplitter<\/span>,<\/span>\n<span class=\"l\">    <span class=\"n\">RecursiveCharacterTextSplitter<\/span>,<\/span>\n<span class=\"l\">)<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">md<\/span> = <span class=\"nb\">open<\/span>(<span class=\"s\">\"docs\/refund-policy.md\"<\/span>, <span class=\"n\">encoding<\/span>=<span class=\"s\">\"utf-8\"<\/span>).<span class=\"n\">read<\/span>()<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\"># 1. Split by headings first; each chunk remembers its section titles<\/span><\/span>\n<span class=\"l\"><span class=\"n\">header_splitter<\/span> = <span class=\"n\">MarkdownHeaderTextSplitter<\/span>(<\/span>\n<span class=\"l\">    <span class=\"n\">headers_to_split_on<\/span>=[(<span class=\"s\">\"#\"<\/span>, <span class=\"s\">\"title\"<\/span>), (<span class=\"s\">\"##\"<\/span>, <span class=\"s\">\"section\"<\/span>)]<\/span>\n<span class=\"l\">)<\/span>\n<span class=\"l\"><span class=\"n\">sections<\/span> = <span class=\"n\">header_splitter<\/span>.<span class=\"n\">split_text<\/span>(<span class=\"n\">md<\/span>)<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\"># 2. Then cut long sections into ~150-character pieces with overlap<\/span><\/span>\n<span class=\"l\"><span class=\"n\">splitter<\/span> = <span class=\"n\">RecursiveCharacterTextSplitter<\/span>(<\/span>\n<span class=\"l\">    <span class=\"n\">chunk_size<\/span>=<span class=\"m\">150<\/span>,<\/span>\n<span class=\"l\">    <span class=\"n\">chunk_overlap<\/span>=<span class=\"m\">30<\/span>,<\/span>\n<span class=\"l\">    <span class=\"n\">separators<\/span>=[<span class=\"s\">\"\\n\\n\"<\/span>, <span class=\"s\">\"\\n\"<\/span>, <span class=\"s\">\". \"<\/span>, <span class=\"s\">\" \"<\/span>, <span class=\"s\">\"\"<\/span>],  <span class=\"c\"># try big breaks first<\/span><\/span>\n<span class=\"l\">)<\/span>\n<span class=\"l\"><span class=\"n\">chunks<\/span> = <span class=\"n\">splitter<\/span>.<span class=\"n\">split_documents<\/span>(<span class=\"n\">sections<\/span>)<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> <span class=\"n\">i<\/span>, <span class=\"n\">c<\/span> in <span class=\"nb\">enumerate<\/span>(<span class=\"n\">chunks<\/span>, <span class=\"m\">1<\/span>):<\/span>\n<span class=\"l\">    <span class=\"n\">section<\/span> = <span class=\"n\">c<\/span>.<span class=\"n\">metadata<\/span>.<span class=\"n\">get<\/span>(<span class=\"s\">\"section\"<\/span>, <span class=\"s\">\"(intro)\"<\/span>)<\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">f\"[{<\/span><span class=\"n\">i<\/span><span class=\"s\">}] {<\/span><span class=\"n\">section<\/span><span class=\"s\">:26} | {<\/span><span class=\"n\">c<\/span>.<span class=\"n\">page_content<\/span>[:<span class=\"m\">58<\/span>]<span class=\"s\">}\"<\/span>)<\/span>\n<span class=\"l\"><span class=\"nb\">print<\/span>(<span class=\"s\">f\"{<\/span><span class=\"nb\">len<\/span>(<span class=\"n\">sections<\/span>)<span class=\"s\">} sections -&gt; {<\/span><span class=\"nb\">len<\/span>(<span class=\"n\">chunks<\/span>)<span class=\"s\">} chunks\"<\/span>)<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> python splitters.py\n[1] (intro)                    | DevDojo Pro is our paid plan with all video courses and li\n[2] Who can get a refund       | You can ask for a full refund within 7 days of your first \n[3] How to ask for a refund    | Email support@devdojo.example with your order ID. Our team\n[4] When the money comes back  | Refunds go back to the original payment method. UPI and ca\n4 sections -&gt; 4 chunks<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 25, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<div class=\"dd-vsc-pane p2\">\n<div class=\"dd-vsc-crumbs\">devdojo-chunking \u203a splitters.mjs<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"k\">import<\/span> { <span class=\"n\">readFileSync<\/span> } <span class=\"k\">from<\/span> <span class=\"s\">\"node:fs\"<\/span>;<\/span>\n<span class=\"l\"><span class=\"k\">import<\/span> { <span class=\"n\">RecursiveCharacterTextSplitter<\/span> } <span class=\"k\">from<\/span> <span class=\"s\">\"@langchain\/textsplitters\"<\/span>;<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"kc\">const<\/span> <span class=\"n\">md<\/span> = <span class=\"n\">readFileSync<\/span>(<span class=\"s\">\"docs\/refund-policy.md\"<\/span>, <span class=\"s\">\"utf8\"<\/span>);<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\">\/\/ Markdown-aware recursive splitter: tries headings, then paragraphs,<\/span><\/span>\n<span class=\"l\"><span class=\"c\">\/\/ then sentences, then words, so chunks break at natural places<\/span><\/span>\n<span class=\"l\"><span class=\"kc\">const<\/span> <span class=\"n\">splitter<\/span> = <span class=\"n\">RecursiveCharacterTextSplitter<\/span>.<span class=\"n\">fromLanguage<\/span>(<span class=\"s\">\"markdown\"<\/span>, {<\/span>\n<span class=\"l\">  <span class=\"n\">chunkSize<\/span>: <span class=\"m\">150<\/span>,<\/span>\n<span class=\"l\">  <span class=\"n\">chunkOverlap<\/span>: <span class=\"m\">30<\/span>,<\/span>\n<span class=\"l\">});<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"kc\">const<\/span> <span class=\"n\">chunks<\/span> = <span class=\"k\">await<\/span> <span class=\"n\">splitter<\/span>.<span class=\"n\">createDocuments<\/span>(<\/span>\n<span class=\"l\">  [<span class=\"n\">md<\/span>],<\/span>\n<span class=\"l\">  [{ <span class=\"n\">source<\/span>: <span class=\"s\">\"refund-policy.md\"<\/span> }],<\/span>\n<span class=\"l\">);<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">chunks<\/span>.<span class=\"n\">forEach<\/span>((<span class=\"n\">c<\/span>, <span class=\"n\">i<\/span>) =&gt; {<\/span>\n<span class=\"l\">  <span class=\"kc\">const<\/span> <span class=\"n\">preview<\/span> = <span class=\"n\">c<\/span>.<span class=\"n\">pageContent<\/span>.<span class=\"n\">replace<\/span>(<span class=\"s\">\/\\n\/g<\/span>, <span class=\"s\">\" \"<\/span>).<span class=\"n\">slice<\/span>(<span class=\"m\">0<\/span>, <span class=\"m\">58<\/span>);<\/span>\n<span class=\"l\">  <span class=\"n\">console<\/span>.<span class=\"n\">log<\/span>(<span class=\"s\">`[${<\/span><span class=\"n\">i<\/span> + <span class=\"m\">1<\/span><span class=\"s\">}] lines ${<\/span><span class=\"n\">c<\/span>.<span class=\"n\">metadata<\/span>.<span class=\"n\">loc<\/span>.<span class=\"n\">lines<\/span>.<span class=\"k\">from<\/span><span class=\"s\">}-${<\/span><span class=\"n\">c<\/span>.<span class=\"n\">metadata<\/span>.<span class=\"n\">loc<\/span>.<span class=\"n\">lines<\/span>.<span class=\"n\">to<\/span><span class=\"s\">} | ${<\/span><span class=\"n\">preview<\/span><span class=\"s\">}`<\/span>);<\/span>\n<span class=\"l\">});<\/span>\n<span class=\"l\"><span class=\"n\">console<\/span>.<span class=\"n\">log<\/span>(<span class=\"s\">`${<\/span><span class=\"n\">chunks<\/span>.<span class=\"n\">length<\/span><span class=\"s\">} chunks`<\/span>);<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> node splitters.mjs\n[1] lines 1-3 | # DevDojo Pro Refund Policy  DevDojo Pro is our paid plan \n[2] lines 5-5 | ## Who can get a refund\n[3] lines 7-7 | You can ask for a full refund within 7 days of your first \n[4] lines 9-11 | ## How to ask for a refund  Email support@devdojo.example \n[5] lines 13-13 | ## When the money comes back\n[6] lines 15-15 | Refunds go back to the original payment method. UPI and ca\n6 chunks<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 22, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 2<\/span><span>UTF-8<\/span><span>LF<\/span><span>JavaScript<\/span><\/div>\n<\/div>\n<\/div>\n<p class=\"dd-vsc-hint\">Compare the two outputs: the Python version splits by headings first, the Node.js version leaves headings in their own small chunks.<\/p>\n<p>The Python version is the pattern to copy for Markdown: <strong>first<\/strong> split by headings with <code>MarkdownHeaderTextSplitter<\/code> (each chunk gets <code>title<\/code> and <code>section<\/code> in its metadata), <strong>then<\/strong> run the recursive splitter so very long sections still fit the size limit. In the Node.js output you can see the weakness of a size-only splitter: chunks 2 and 5 are just headings with no content, which are useless for retrieval. Merge them or prefix each chunk with its heading (we do this in the pipeline below).<\/p>\n<div class=\"dd-tip\"><strong>Characters or tokens?<\/strong> Both splitters measure size in characters by default. A rough rule for English: 1 token &#8776; 4 characters, so 1,000 characters &#8776; 250 tokens. Hindi and other non-Latin scripts use more tokens per character, so check with a tokenizer if you work with them.<\/div>\n\n<h2 id=\"measure\">Testing which chunking strategy works best<\/h2>\n<p>The honest answer to &#8220;what is the best chunk size?&#8221; is: <em>it depends on your documents, so measure it<\/em>. Write a handful of real questions, note a phrase the correct chunk must contain, and count how often the top retrieved chunk contains it. To keep this example free and fast, we use simple word matching instead of embeddings. The idea is exactly the same with a vector database.<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: compare_chunking.py\">\n<input type=\"radio\" name=\"v4\" id=\"v4f1\" class=\"f1\" checked>\n<input type=\"checkbox\" id=\"v4r1\" class=\"r1\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">compare_chunking.py \u2014 devdojo-chunking \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v4f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>compare_chunking.py<\/label>\n<label for=\"v4r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">devdojo-chunking \u203a compare_chunking.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">re<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">chunkers<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">fixed_size<\/span>, <span class=\"n\">by_sentences<\/span>, <span class=\"n\">by_headings<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">md<\/span> = <span class=\"nb\">open<\/span>(<span class=\"s\">\"docs\/refund-policy.md\"<\/span>, <span class=\"n\">encoding<\/span>=<span class=\"s\">\"utf-8\"<\/span>).<span class=\"n\">read<\/span>()<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"c\"># Small test set: question -&gt; words the right chunk MUST contain<\/span><\/span>\n<span class=\"l\"><span class=\"n\">tests<\/span> = [<\/span>\n<span class=\"l\">    (<span class=\"s\">\"How many days do I have to ask for a refund?\"<\/span>, <span class=\"s\">\"7 days of your first payment\"<\/span>),<\/span>\n<span class=\"l\">    (<span class=\"s\">\"Can I get a refund on a renewal?\"<\/span>, <span class=\"s\">\"not available for renewals\"<\/span>),<\/span>\n<span class=\"l\">    (<span class=\"s\">\"How do I ask for a refund?\"<\/span>, <span class=\"s\">\"with your order ID\"<\/span>),<\/span>\n<span class=\"l\">    (<span class=\"s\">\"How long does a UPI refund take?\"<\/span>, <span class=\"s\">\"5 to 7 working days\"<\/span>),<\/span>\n<span class=\"l\">]<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">STOP<\/span> = {<span class=\"s\">\"a\"<\/span>, <span class=\"s\">\"an\"<\/span>, <span class=\"s\">\"the\"<\/span>, <span class=\"s\">\"i\"<\/span>, <span class=\"s\">\"do\"<\/span>, <span class=\"s\">\"does\"<\/span>, <span class=\"s\">\"how\"<\/span>, <span class=\"s\">\"to\"<\/span>, <span class=\"s\">\"on\"<\/span>, <span class=\"s\">\"for\"<\/span>, <span class=\"s\">\"of\"<\/span>, <span class=\"s\">\"my\"<\/span>, <span class=\"s\">\"can\"<\/span>, <span class=\"s\">\"is\"<\/span>}<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">words<\/span>(<span class=\"n\">t<\/span>):<\/span>\n<span class=\"l\">    <span class=\"c\"># lowercase words, no common filler words, \"refunds\" -&gt; \"refund\"<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> {<span class=\"n\">w<\/span>.<span class=\"n\">rstrip<\/span>(<span class=\"s\">\"s\"<\/span>) <span class=\"k\">for<\/span> <span class=\"n\">w<\/span> in <span class=\"n\">re<\/span>.<span class=\"n\">findall<\/span>(<span class=\"s\">r\"[a-z0-9]+\"<\/span>, <span class=\"n\">t<\/span>.<span class=\"n\">lower<\/span>()) <span class=\"k\">if<\/span> <span class=\"n\">w<\/span> not in <span class=\"n\">STOP<\/span>}<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">top_chunk<\/span>(<span class=\"n\">question<\/span>, <span class=\"n\">chunks<\/span>):<\/span>\n<span class=\"l\">    <span class=\"c\"># stand-in for embedding search: most shared words wins<\/span><\/span>\n<span class=\"l\">    <span class=\"k\">return<\/span> <span class=\"nb\">max<\/span>(<span class=\"n\">chunks<\/span>, <span class=\"n\">key<\/span>=<span class=\"k\">lambda<\/span> <span class=\"n\">c<\/span>: <span class=\"nb\">len<\/span>(<span class=\"n\">words<\/span>(<span class=\"n\">question<\/span>) &amp; <span class=\"n\">words<\/span>(<span class=\"n\">c<\/span>)))<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">strategies<\/span> = {<\/span>\n<span class=\"l\">    <span class=\"s\">\"fixed 80, no overlap\"<\/span>: <span class=\"n\">fixed_size<\/span>(<span class=\"n\">md<\/span>, <span class=\"m\">80<\/span>),<\/span>\n<span class=\"l\">    <span class=\"s\">\"fixed 80, overlap 20\"<\/span>: <span class=\"n\">fixed_size<\/span>(<span class=\"n\">md<\/span>, <span class=\"m\">80<\/span>, <span class=\"m\">20<\/span>),<\/span>\n<span class=\"l\">    <span class=\"s\">\"sentences (200)\"<\/span>: <span class=\"n\">by_sentences<\/span>(<span class=\"n\">md<\/span>, <span class=\"m\">200<\/span>),<\/span>\n<span class=\"l\">    <span class=\"s\">\"headings\"<\/span>: <span class=\"n\">by_headings<\/span>(<span class=\"n\">md<\/span>),<\/span>\n<span class=\"l\">}<\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> <span class=\"n\">name<\/span>, <span class=\"n\">chunks<\/span> in <span class=\"n\">strategies<\/span>.<span class=\"n\">items<\/span>():<\/span>\n<span class=\"l\">    <span class=\"n\">hits<\/span> = <span class=\"nb\">sum<\/span>(<span class=\"n\">answer<\/span> in <span class=\"n\">top_chunk<\/span>(<span class=\"n\">q<\/span>, <span class=\"n\">chunks<\/span>) <span class=\"k\">for<\/span> <span class=\"n\">q<\/span>, <span class=\"n\">answer<\/span> in <span class=\"n\">tests<\/span>)<\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">f\"{<\/span><span class=\"n\">name<\/span><span class=\"s\">:22} {<\/span><span class=\"nb\">len<\/span>(<span class=\"n\">chunks<\/span>)<span class=\"s\">:2} chunks  -&gt; {<\/span><span class=\"n\">hits<\/span><span class=\"s\">}\/{<\/span><span class=\"nb\">len<\/span>(<span class=\"n\">tests<\/span>)<span class=\"s\">} answers found\"<\/span>)<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> python compare_chunking.py\nfixed 80, no overlap    7 chunks  -&gt; 0\/4 answers found\nfixed 80, overlap 20    9 chunks  -&gt; 1\/4 answers found\nsentences (200)         3 chunks  -&gt; 2\/4 answers found\nheadings                4 chunks  -&gt; 3\/4 answers found<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 32, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<\/div>\n<p class=\"dd-vsc-hint\">Press <strong>\u25b6 Run<\/strong> to see how many test questions each strategy answers. This file imports the functions from <code>chunkers.py<\/code> above.<\/p>\n<p>On this small file, fixed-size chunks with no overlap answer <strong>0 of 4<\/strong> questions: every answer phrase was cut across a border. Overlap rescues one. Sentence packing gets 2, and heading-based chunks get <strong>3 of 4<\/strong>. With real embeddings the scores will be higher, but the ranking is usually similar on well-structured docs. The miss also teaches something: for &#8220;How do I ask for a refund?&#8221; the useful words are only &#8220;ask&#8221; and &#8220;refund&#8221;, and the &#8220;Who can get a refund&#8221; section contains both too, so simple word matching picked the wrong section. Fixing that is the job of better retrieval (hybrid search and re-ranking), which is exactly what Part 13 covers.<\/p>\n\n<h2 id=\"pipeline\">A complete ingest pipeline with metadata and stable IDs<\/h2>\n<p>Now let&#8217;s put it together into a script you can actually reuse: load every file, split Markdown by headings, cut everything with a recursive splitter (300 characters, 50 overlap), add the section title to the chunk text, and give every chunk a <strong>stable ID<\/strong>.<\/p>\n<div class=\"dd-vsc\" role=\"group\" aria-label=\"Code editor: ingest.py\">\n<input type=\"radio\" name=\"v5\" id=\"v5f1\" class=\"f1\" checked>\n<input type=\"checkbox\" id=\"v5r1\" class=\"r1\">\n<div class=\"dd-vsc-bar\"><span class=\"dd-dots\"><i><\/i><i><\/i><i><\/i><\/span><span class=\"dd-vsc-title\">ingest.py \u2014 devdojo-chunking \u2014 Visual Studio Code<\/span><\/div>\n<div class=\"dd-vsc-tabs\">\n<label for=\"v5f1\" class=\"t1\"><b class=\"ic py\">PY<\/b>ingest.py<\/label>\n<label for=\"v5r1\" class=\"run run1\" title=\"Show the output in the terminal\">\u25b6 Run<\/label>\n<\/div>\n<div class=\"dd-vsc-pane p1\">\n<div class=\"dd-vsc-crumbs\">devdojo-chunking \u203a ingest.py<\/div>\n<pre class=\"dd-vsc-code\"><code><span class=\"l\"><span class=\"kn\">import<\/span> <span class=\"n\">json<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">pathlib<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Path<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">langchain_text_splitters<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">MarkdownHeaderTextSplitter<\/span>, <span class=\"n\">RecursiveCharacterTextSplitter<\/span><\/span>\n<span class=\"l\"><span class=\"kn\">from<\/span> <span class=\"n\">load_docs<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">load<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">headers<\/span> = <span class=\"n\">MarkdownHeaderTextSplitter<\/span>([(<span class=\"s\">\"#\"<\/span>, <span class=\"s\">\"title\"<\/span>), (<span class=\"s\">\"##\"<\/span>, <span class=\"s\">\"section\"<\/span>)])<\/span>\n<span class=\"l\"><span class=\"n\">splitter<\/span> = <span class=\"n\">RecursiveCharacterTextSplitter<\/span>(<span class=\"n\">chunk_size<\/span>=<span class=\"m\">300<\/span>, <span class=\"n\">chunk_overlap<\/span>=<span class=\"m\">50<\/span>)<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"k\">def<\/span> <span class=\"nf\">chunk_document<\/span>(<span class=\"n\">doc<\/span>):<\/span>\n<span class=\"l\">    <span class=\"n\">meta<\/span> = <span class=\"n\">doc<\/span>[<span class=\"s\">\"metadata\"<\/span>]<\/span>\n<span class=\"l\">    <span class=\"k\">if<\/span> <span class=\"n\">meta<\/span>[<span class=\"s\">\"source\"<\/span>].<span class=\"n\">endswith<\/span>(<span class=\"s\">\".md\"<\/span>):  <span class=\"c\"># structure-aware for Markdown<\/span><\/span>\n<span class=\"l\">        <span class=\"n\">parts<\/span> = [(<span class=\"n\">p<\/span>.<span class=\"n\">page_content<\/span>, {**<span class=\"n\">meta<\/span>, **<span class=\"n\">p<\/span>.<span class=\"n\">metadata<\/span>}) <span class=\"k\">for<\/span> <span class=\"n\">p<\/span> in <span class=\"n\">headers<\/span>.<span class=\"n\">split_text<\/span>(<span class=\"n\">doc<\/span>[<span class=\"s\">\"text\"<\/span>])]<\/span>\n<span class=\"l\">    <span class=\"k\">else<\/span>:<\/span>\n<span class=\"l\">        <span class=\"n\">parts<\/span> = [(<span class=\"n\">doc<\/span>[<span class=\"s\">\"text\"<\/span>], <span class=\"n\">meta<\/span>)]<\/span>\n<span class=\"l\">    <span class=\"k\">for<\/span> <span class=\"n\">text<\/span>, <span class=\"n\">m<\/span> in <span class=\"n\">parts<\/span>:<\/span>\n<span class=\"l\">        <span class=\"k\">for<\/span> <span class=\"n\">piece<\/span> in <span class=\"n\">splitter<\/span>.<span class=\"n\">split_text<\/span>(<span class=\"n\">text<\/span>):<\/span>\n<span class=\"l\">            <span class=\"k\">yield<\/span> <span class=\"n\">piece<\/span>, <span class=\"n\">m<\/span><\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">records<\/span> = []<\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> <span class=\"n\">path<\/span> in <span class=\"nb\">sorted<\/span>(<span class=\"n\">Path<\/span>(<span class=\"s\">\"docs\"<\/span>).<span class=\"n\">iterdir<\/span>()):<\/span>\n<span class=\"l\">    <span class=\"k\">for<\/span> <span class=\"n\">doc<\/span> in <span class=\"n\">load<\/span>(<span class=\"n\">path<\/span>):<\/span>\n<span class=\"l\">        <span class=\"k\">for<\/span> <span class=\"n\">n<\/span>, (<span class=\"n\">text<\/span>, <span class=\"n\">meta<\/span>) in <span class=\"nb\">enumerate<\/span>(<span class=\"n\">chunk_document<\/span>(<span class=\"n\">doc<\/span>), <span class=\"m\">1<\/span>):<\/span>\n<span class=\"l\">            <span class=\"n\">heading<\/span> = <span class=\"n\">meta<\/span>.<span class=\"n\">get<\/span>(<span class=\"s\">\"section\"<\/span>) or <span class=\"n\">meta<\/span>.<span class=\"n\">get<\/span>(<span class=\"s\">\"title\"<\/span>)<\/span>\n<span class=\"l\">            <span class=\"c\"># Stable ID: same file + page + position -&gt; same ID on re-index<\/span><\/span>\n<span class=\"l\">            <span class=\"n\">records<\/span>.<span class=\"n\">append<\/span>({<\/span>\n<span class=\"l\">                <span class=\"s\">\"id\"<\/span>: <span class=\"s\">f\"{<\/span><span class=\"n\">meta<\/span>[<span class=\"s\">'source'<\/span>]<span class=\"s\">}:p{<\/span><span class=\"n\">meta<\/span>.<span class=\"n\">get<\/span>(<span class=\"s\">'page'<\/span>, <span class=\"m\">1<\/span>)<span class=\"s\">}:{<\/span><span class=\"n\">n<\/span><span class=\"s\">}\"<\/span>,<\/span>\n<span class=\"l\">                <span class=\"s\">\"text\"<\/span>: <span class=\"s\">f\"{<\/span><span class=\"n\">heading<\/span><span class=\"s\">}: {<\/span><span class=\"n\">text<\/span><span class=\"s\">}\"<\/span> <span class=\"k\">if<\/span> <span class=\"n\">heading<\/span> <span class=\"k\">else<\/span> <span class=\"n\">text<\/span>,  <span class=\"c\"># add context<\/span><\/span>\n<span class=\"l\">                <span class=\"s\">\"metadata\"<\/span>: <span class=\"n\">meta<\/span>,<\/span>\n<span class=\"l\">            })<\/span>\n<span class=\"l\"><\/span>\n<span class=\"l\"><span class=\"n\">Path<\/span>(<span class=\"s\">\"chunks.jsonl\"<\/span>).<span class=\"n\">write_text<\/span>(<span class=\"s\">\"\\n\"<\/span>.<span class=\"n\">join<\/span>(<span class=\"n\">json<\/span>.<span class=\"n\">dumps<\/span>(<span class=\"n\">r<\/span>) <span class=\"k\">for<\/span> <span class=\"n\">r<\/span> in <span class=\"n\">records<\/span>), <span class=\"n\">encoding<\/span>=<span class=\"s\">\"utf-8\"<\/span>)<\/span>\n<span class=\"l\"><span class=\"k\">for<\/span> <span class=\"n\">r<\/span> in <span class=\"n\">records<\/span>[:<span class=\"m\">3<\/span>] + <span class=\"n\">records<\/span>[-<span class=\"m\">2<\/span>:]:<\/span>\n<span class=\"l\">    <span class=\"n\">preview<\/span> = <span class=\"n\">r<\/span>[<span class=\"s\">\"text\"<\/span>][:<span class=\"m\">48<\/span>].<span class=\"n\">replace<\/span>(<span class=\"s\">\"\\n\"<\/span>, <span class=\"s\">\" \"<\/span>)<\/span>\n<span class=\"l\">    <span class=\"nb\">print<\/span>(<span class=\"s\">f\"{<\/span><span class=\"n\">r<\/span>[<span class=\"s\">'id'<\/span>]<span class=\"s\">:24} {<\/span><span class=\"nb\">len<\/span>(<span class=\"n\">r<\/span>[<span class=\"s\">'text'<\/span>])<span class=\"s\">:3} chars | {<\/span><span class=\"n\">preview<\/span><span class=\"s\">}\"<\/span>)<\/span>\n<span class=\"l\"><span class=\"nb\">print<\/span>(<span class=\"s\">f\"Saved {<\/span><span class=\"nb\">len<\/span>(<span class=\"n\">records<\/span>)<span class=\"s\">} chunks to chunks.jsonl\"<\/span>)<\/span><\/code><\/pre>\n<div class=\"dd-vsc-term\"><div class=\"dd-term-head\"><span>TERMINAL<\/span><span>OUTPUT<\/span><span>PROBLEMS<\/span><\/div><pre><code><span class=\"gp\">$<\/span> python ingest.py\nfaq.html:p1:1            281 chars | DevDojo FAQ Frequently asked questions Do I get \nhandbook.pdf:p1:1        173 chars | DevDojo Student Handbook Page 1: Getting started\nhandbook.pdf:p2:1        201 chars | Page 2: Mentors and projects Every DevDojo Pro s\nrefund-policy.md:p1:3    114 chars | How to ask for a refund: Email support@devdojo.e\nrefund-policy.md:p1:4    153 chars | When the money comes back: Refunds go back to th\nSaved 8 chunks to chunks.jsonl<\/code><\/pre><\/div>\n<div class=\"dd-vsc-status\"><span>\u2387 main<\/span><span>Ln 35, Col 1<\/span><span class=\"sp\"><\/span><span>Spaces: 4<\/span><span>UTF-8<\/span><span>LF<\/span><span>Python<\/span><\/div>\n<\/div>\n<\/div>\n<p class=\"dd-vsc-hint\">This is the version you would use in a real project: it reuses <code>load()<\/code> from <code>load_docs.py<\/code> and writes <code>chunks.jsonl<\/code>, ready for embedding.<\/p>\n<p>Two small details make a big difference in production:<\/p>\n<ul>\n<li><strong>Stable IDs<\/strong> such as <code>handbook.pdf:p2:1<\/code> mean that when you re-index after a document changes, you can <code>upsert<\/code> (update or insert) instead of creating duplicate chunks.<\/li>\n<li><strong>Heading prefix<\/strong> (&#8220;How to ask for a refund: Email support&#8230;&#8221;) gives every chunk context, which improves both the embedding and the LLM&#8217;s understanding. This simple trick is often called a <em>contextual chunk header<\/em>.<\/li>\n<\/ul>\n<p>The <code>chunks.jsonl<\/code> file is the input for the embedding and vector-database code from Parts 9&#8211;11: read each line, embed <code>text<\/code>, and store it with its <code>id<\/code> and <code>metadata<\/code>.<\/p>\n\n<h2 id=\"sizes\">Choosing chunk size and overlap<\/h2>\n<p>These are starting points, not rules. Always confirm with your own test questions.<\/p>\n<div class=\"dd-tablewrap\"><table>\n<thead><tr><th>Content type<\/th><th>Strategy<\/th><th>Starting size<\/th><th>Overlap<\/th><\/tr><\/thead>\n<tbody>\n<tr><td>Docs, help centre, wiki (Markdown\/HTML)<\/td><td>By headings, then recursive<\/td><td>500&#8211;1,000 chars<\/td><td>10&#8211;15%<\/td><\/tr>\n<tr><td>FAQ pages<\/td><td>One question + answer per chunk<\/td><td>Whole Q&amp;A<\/td><td>None<\/td><\/tr>\n<tr><td>PDF reports and manuals<\/td><td>Per page, then recursive<\/td><td>800&#8211;1,500 chars<\/td><td>15&#8211;20%<\/td><\/tr>\n<tr><td>Chat logs, transcripts<\/td><td>Recursive or by time window<\/td><td>500&#8211;1,000 chars<\/td><td>20%<\/td><\/tr>\n<tr><td>Source code<\/td><td>By function or class (language-aware splitter)<\/td><td>One function<\/td><td>None<\/td><\/tr>\n<tr><td>Legal and policy text<\/td><td>By clause or section number<\/td><td>One clause<\/td><td>Small<\/td><\/tr>\n<\/tbody><\/table><\/div>\n\n<h2 id=\"errors\">Common errors and fixes<\/h2>\n<div class=\"dd-tablewrap\"><table>\n<thead><tr><th>Problem<\/th><th>Why it happens<\/th><th>Fix<\/th><\/tr><\/thead>\n<tbody>\n<tr><td><code>extract_text()<\/code> returns <code>\"\"<\/code> for a PDF<\/td><td>Scanned PDF: the pages are images<\/td><td>Run OCR first, or use a document-parsing tool that supports scanned pages<\/td><\/tr>\n<tr><td>Words glued together or split with hyphens (&#8220;pay-<br>ment&#8221;)<\/td><td>PDF layout extraction is not perfect<\/td><td>Clean with a small regex (join hyphenated line breaks, collapse spaces) before chunking<\/td><\/tr>\n<tr><td>Every chunk contains &#8220;Home | Courses | Login&#8221;<\/td><td>Menus and footers were loaded as content<\/td><td>Skip <code>nav<\/code>, <code>footer<\/code>, <code>script<\/code>, <code>style<\/code> tags, or extract only <code>main<\/code>\/<code>article<\/code><\/td><\/tr>\n<tr><td>The answer is half in one chunk, half in the next<\/td><td>Fixed-size split with no overlap<\/td><td>Add 10&#8211;20% overlap or split on structure<\/td><\/tr>\n<tr><td>Chunks that contain only a heading<\/td><td>Size-based splitter cut before the content<\/td><td>Split by headings first, or prefix each chunk with its heading<\/td><\/tr>\n<tr><td>Duplicate chunks after re-indexing<\/td><td>Random IDs on every run<\/td><td>Use stable IDs (file + page + position) and <code>upsert<\/code><\/td><\/tr>\n<tr><td>Embedding API error: input too long<\/td><td>Chunk is bigger than the embedding model&#8217;s input limit<\/td><td>Lower <code>chunk_size<\/code>, or measure length in tokens<\/td><\/tr>\n<tr><td><code>ModuleNotFoundError: langchain_text_splitters<\/code><\/td><td>Package name uses dashes on pip<\/td><td><code>pip install langchain-text-splitters<\/code><\/td><\/tr>\n<tr><td><code>SyntaxError<\/code> on <code>await<\/code> or <code>import<\/code> in Node.js<\/td><td>File is treated as CommonJS<\/td><td>Use the <code>.mjs<\/code> extension or add <code>\"type\": \"module\"<\/code> to <code>package.json<\/code><\/td><\/tr>\n<\/tbody><\/table><\/div>\n\n<h2 id=\"best-practices\">Best practices for document loading and chunking<\/h2>\n<ul>\n<li><strong>Look at your chunks.<\/strong> Print 20 random chunks and read them. If a human can&#8217;t understand a chunk alone, the model can&#8217;t either.<\/li>\n<li><strong>Keep metadata from the start:<\/strong> source, page, section, URL, last updated date. You will need it for citations and filters.<\/li>\n<li><strong>Use structure when you have it<\/strong> (headings, pages, FAQ items). Fall back to recursive splitting when you don&#8217;t.<\/li>\n<li><strong>Clean before you chunk.<\/strong> Remove menus, cookie text and repeated headers; they waste tokens and pollute search results.<\/li>\n<li><strong>Measure with a test set.<\/strong> Change one thing at a time (size, overlap, strategy) and re-run the same questions.<\/li>\n<li><strong>Treat document text as data.<\/strong> A loaded file can contain text like &#8220;ignore your instructions&#8221;. Never let document content act as instructions to your bot (more in Part 25).<\/li>\n<\/ul>\n\n<h2 id=\"practice\">Practice task<\/h2>\n<div class=\"dd-tip\">\n<p><strong>Chunk your own notes:<\/strong><\/p>\n<ol>\n<li>Put 3 of your own files in <code>docs\/<\/code>: one PDF (any notes or a resume), one Markdown file (a project README works well) and one saved web page.<\/li>\n<li>Run <code>load_docs.py<\/code> or <code>load_docs.mjs<\/code> and check that the text looks clean. Fix anything messy.<\/li>\n<li>Write 5 questions with an answer phrase each and add them to <code>compare_chunking.py<\/code>. Point it at your Markdown file.<\/li>\n<li>Try chunk sizes 100, 300 and 600 with overlap 0 and 20%. Which combination wins?<\/li>\n<li>Bonus: feed <code>chunks.jsonl<\/code> into the Ollama RAG app from <a href=\"https:\/\/devdojo.co.in\/?p=313\">Part 11<\/a> and ask your questions for real.<\/li>\n<\/ol>\n<\/div>\n\n<h2 id=\"conclusion\">Conclusion<\/h2>\n<p>A RAG app is only as good as its chunks. Load each file into clean text with metadata, use the document&#8217;s structure when it has one, fall back to a recursive splitter with a little overlap, give every chunk a stable ID and a heading, and test your choices with real questions. With this, you can turn real PDFs, web pages and docs into a knowledge base your LLM can actually use.<\/p>\n\n<div class=\"dd-next\"><strong>Next part &#8594; Part 13: Better RAG: Hybrid Search, Re-ranking and Query Rewriting.<\/strong> Our test showed simple matching can pick the wrong chunk. Next we combine keyword and vector search, re-rank the results and rewrite vague questions, so the right chunk comes first.<\/div>\n\n<div class=\"dd-cta\">\n<h3>New posts every day on DevDojo<\/h3>\n<p>Follow the full <strong>Generative AI series<\/strong> from basics to production. Bookmark <a href=\"https:\/\/devdojo.co.in\/\">devdojo.co.in<\/a> and open the roadmap above to see what is coming next.<\/p>\n<\/div>\n\n<h2 id=\"faq\">FAQ<\/h2>\n<details><summary>What is chunking in RAG?<\/summary><p>Chunking is cutting documents into smaller pieces before you create embeddings. Each chunk gets its own vector, so the retriever can find the exact paragraph that answers a question instead of a whole document.<\/p><\/details>\n<details><summary>What is the best chunk size for RAG?<\/summary><p>There is no single best size. A common starting point is 500&#8211;1,000 characters (roughly 100&#8211;250 tokens) with 10&#8211;20% overlap, adjusted after testing with real questions on your own documents.<\/p><\/details>\n<details><summary>Why use chunk overlap?<\/summary><p>Overlap repeats a little text at the start of each chunk, so a sentence that falls on a border still appears whole in at least one chunk. It costs a few more chunks, but prevents answers from being split in half.<\/p><\/details>\n<details><summary>Do I need LangChain for chunking?<\/summary><p>No. You can write simple chunkers in a few lines, as shown above. The <code>langchain-text-splitters<\/code> and <code>@langchain\/textsplitters<\/code> packages are small and handy, but they are optional.<\/p><\/details>\n<details><summary>How do I load PDFs for RAG?<\/summary><p>Use a PDF library such as pypdf (Python) or unpdf (Node.js) to extract text page by page and keep the page number as metadata. Scanned PDFs need OCR first because they contain images, not text.<\/p><\/details>\n<details><summary>What is semantic chunking?<\/summary><p>Semantic chunking uses embeddings to find places where the topic changes and starts a new chunk there. It can help with long unstructured text, but it is slower and costs more, so try recursive or heading-based chunking first.<\/p><\/details>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Learn document loading and chunking strategies for RAG: load PDF, HTML and Markdown in Python and Node.js, compare chunk size and overlap, and test the results.<\/p>\n","protected":false},"author":1,"featured_media":314,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[38],"tags":[173,174,43,175,52,86,112],"class_list":["post-315","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ai","tag-chunking","tag-langchain","tag-node-js","tag-pdf-parsing","tag-python","tag-rag","tag-series-generative-ai"],"aioseo_notices":[],"aioseo_head":"\n\t\t<!-- All in One SEO 5.0.4 - aioseo.com -->\n\t<meta name=\"description\" content=\"Learn document loading and chunking strategies for RAG: load PDF, HTML and Markdown in Python and Node.js, compare chunk size and overlap, and test the results.\" \/>\n\t<meta name=\"robots\" content=\"max-image-preview:large\" \/>\n\t<meta name=\"author\" content=\"Lokendra\"\/>\n\t<link rel=\"canonical\" href=\"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/\" \/>\n\t\t<meta name=\"generator\" content=\"All in One SEO (AIOSEO) 5.0.4\" \/>\n\t\t<meta property=\"og:locale\" content=\"en_US\" \/>\n\t\t<meta property=\"og:site_name\" content=\"DevDojo - Empowering Developers\" \/>\n\t\t<meta property=\"og:type\" content=\"article\" \/>\n\t\t<meta property=\"og:title\" content=\"Document Loading and Chunking Strategies for RAG\" \/>\n\t\t<meta property=\"og:description\" content=\"Learn document loading and chunking strategies for RAG: load PDF, HTML and Markdown in Python and Node.js, compare chunk size and overlap, and test the results.\" \/>\n\t\t<meta property=\"og:url\" content=\"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/\" \/>\n\t\t<meta property=\"article:published_time\" content=\"2026-11-29T14:40:09+00:00\" \/>\n\t\t<meta property=\"article:modified_time\" content=\"2026-11-29T14:40:10+00:00\" \/>\n\t\t<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n\t\t<meta name=\"twitter:title\" content=\"Document Loading and Chunking Strategies for RAG\" \/>\n\t\t<meta name=\"twitter:description\" content=\"Learn document loading and chunking strategies for RAG: load PDF, HTML and Markdown in Python and Node.js, compare chunk size and overlap, and test the results.\" \/>\n\t\t<script type=\"application\/ld+json\" class=\"aioseo-schema\">\n\t\t\t{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"BlogPosting\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/#blogposting\",\"name\":\"Document Loading and Chunking Strategies for RAG\",\"headline\":\"Generative AI Part 12: Document Loading and Chunking Strategies for RAG\",\"author\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\"},\"publisher\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#organization\"},\"image\":{\"@type\":\"ImageObject\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/genai-series-part-12-document-loading-chunking.jpg\",\"width\":1200,\"height\":630,\"caption\":\"Generative AI Part 12 banner: PDF, Markdown and HTML files loaded, cleaned and split into chunks with IDs for RAG\"},\"datePublished\":\"2026-11-29T14:40:09+00:00\",\"dateModified\":\"2026-11-29T14:40:10+00:00\",\"inLanguage\":\"en-US\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/#webpage\"},\"isPartOf\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/#webpage\"},\"articleSection\":\"AI, Chunking, LangChain, Node.js, PDF Parsing, Python, RAG, Series: Generative AI\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/#breadcrumblist\",\"itemListElement\":[{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#listItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/devdojo.co.in\\\/\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/#listItem\",\"name\":\"AI\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/#listItem\",\"position\":2,\"name\":\"AI\",\"item\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/\",\"nextItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/#listItem\",\"name\":\"Generative AI Part 12: Document Loading and Chunking Strategies for RAG\"},\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#listItem\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/#listItem\",\"position\":3,\"name\":\"Generative AI Part 12: Document Loading and Chunking Strategies for RAG\",\"previousItem\":{\"@type\":\"ListItem\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/category\\\/ai\\\/#listItem\",\"name\":\"AI\"}}]},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#organization\",\"name\":\"DevDojo\",\"description\":\"Empowering Developers\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/\",\"name\":\"Lokendra\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/#authorImage\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/99f102f0cc9080237ce54b91304fd1b3b6fa29925cbaeba93cd796872e58b45c?s=96&d=mm&r=g\",\"width\":96,\"height\":96,\"caption\":\"Lokendra\"}},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/#webpage\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/\",\"name\":\"Document Loading and Chunking Strategies for RAG\",\"description\":\"Learn document loading and chunking strategies for RAG: load PDF, HTML and Markdown in Python and Node.js, compare chunk size and overlap, and test the results.\",\"inLanguage\":\"en-US\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#website\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/#breadcrumblist\"},\"author\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\"},\"creator\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/author\\\/lokendra\\\/#author\"},\"image\":{\"@type\":\"ImageObject\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/genai-series-part-12-document-loading-chunking.jpg\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/#mainImage\",\"width\":1200,\"height\":630,\"caption\":\"Generative AI Part 12 banner: PDF, Markdown and HTML files loaded, cleaned and split into chunks with IDs for RAG\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/index.php\\\/2026\\\/11\\\/29\\\/genai-series-part-12-document-loading-chunking\\\/#mainImage\"},\"datePublished\":\"2026-11-29T14:40:09+00:00\",\"dateModified\":\"2026-11-29T14:40:10+00:00\"},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#website\",\"url\":\"https:\\\/\\\/devdojo.co.in\\\/\",\"name\":\"DevDojo\",\"description\":\"Empowering Developers\",\"inLanguage\":\"en-US\",\"publisher\":{\"@id\":\"https:\\\/\\\/devdojo.co.in\\\/#organization\"}}]}\n\t\t<\/script>\n\t\t<!-- All in One SEO -->\n\n","aioseo_head_json":{"title":"Document Loading and Chunking Strategies for RAG","description":"Learn document loading and chunking strategies for RAG: load PDF, HTML and Markdown in Python and Node.js, compare chunk size and overlap, and test the results.","canonical_url":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/","robots":"max-image-preview:large","keywords":"","webmasterTools":{"miscellaneous":""},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"BlogPosting","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/#blogposting","name":"Document Loading and Chunking Strategies for RAG","headline":"Generative AI Part 12: Document Loading and Chunking Strategies for RAG","author":{"@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author"},"publisher":{"@id":"https:\/\/devdojo.co.in\/#organization"},"image":{"@type":"ImageObject","url":"https:\/\/devdojo.co.in\/wp-content\/uploads\/2026\/11\/genai-series-part-12-document-loading-chunking.jpg","width":1200,"height":630,"caption":"Generative AI Part 12 banner: PDF, Markdown and HTML files loaded, cleaned and split into chunks with IDs for RAG"},"datePublished":"2026-11-29T14:40:09+00:00","dateModified":"2026-11-29T14:40:10+00:00","inLanguage":"en-US","mainEntityOfPage":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/#webpage"},"isPartOf":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/#webpage"},"articleSection":"AI, Chunking, LangChain, Node.js, PDF Parsing, Python, RAG, Series: Generative AI"},{"@type":"BreadcrumbList","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/#breadcrumblist","itemListElement":[{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/#listItem","position":1,"name":"Home","item":"https:\/\/devdojo.co.in\/","nextItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/#listItem","name":"AI"}},{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/#listItem","position":2,"name":"AI","item":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/","nextItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/#listItem","name":"Generative AI Part 12: Document Loading and Chunking Strategies for RAG"},"previousItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/#listItem","name":"Home"}},{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/#listItem","position":3,"name":"Generative AI Part 12: Document Loading and Chunking Strategies for RAG","previousItem":{"@type":"ListItem","@id":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/#listItem","name":"AI"}}]},{"@type":"Organization","@id":"https:\/\/devdojo.co.in\/#organization","name":"DevDojo","description":"Empowering Developers","url":"https:\/\/devdojo.co.in\/"},{"@type":"Person","@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author","url":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/","name":"Lokendra","image":{"@type":"ImageObject","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/#authorImage","url":"https:\/\/secure.gravatar.com\/avatar\/99f102f0cc9080237ce54b91304fd1b3b6fa29925cbaeba93cd796872e58b45c?s=96&d=mm&r=g","width":96,"height":96,"caption":"Lokendra"}},{"@type":"WebPage","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/#webpage","url":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/","name":"Document Loading and Chunking Strategies for RAG","description":"Learn document loading and chunking strategies for RAG: load PDF, HTML and Markdown in Python and Node.js, compare chunk size and overlap, and test the results.","inLanguage":"en-US","isPartOf":{"@id":"https:\/\/devdojo.co.in\/#website"},"breadcrumb":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/#breadcrumblist"},"author":{"@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author"},"creator":{"@id":"https:\/\/devdojo.co.in\/index.php\/author\/lokendra\/#author"},"image":{"@type":"ImageObject","url":"https:\/\/devdojo.co.in\/wp-content\/uploads\/2026\/11\/genai-series-part-12-document-loading-chunking.jpg","@id":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/#mainImage","width":1200,"height":630,"caption":"Generative AI Part 12 banner: PDF, Markdown and HTML files loaded, cleaned and split into chunks with IDs for RAG"},"primaryImageOfPage":{"@id":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/#mainImage"},"datePublished":"2026-11-29T14:40:09+00:00","dateModified":"2026-11-29T14:40:10+00:00"},{"@type":"WebSite","@id":"https:\/\/devdojo.co.in\/#website","url":"https:\/\/devdojo.co.in\/","name":"DevDojo","description":"Empowering Developers","inLanguage":"en-US","publisher":{"@id":"https:\/\/devdojo.co.in\/#organization"}}]},"og:locale":"en_US","og:site_name":"DevDojo - Empowering Developers","og:type":"article","og:title":"Document Loading and Chunking Strategies for RAG","og:description":"Learn document loading and chunking strategies for RAG: load PDF, HTML and Markdown in Python and Node.js, compare chunk size and overlap, and test the results.","og:url":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/","article:published_time":"2026-11-29T14:40:09+00:00","article:modified_time":"2026-11-29T14:40:10+00:00","twitter:card":"summary_large_image","twitter:title":"Document Loading and Chunking Strategies for RAG","twitter:description":"Learn document loading and chunking strategies for RAG: load PDF, HTML and Markdown in Python and Node.js, compare chunk size and overlap, and test the results."},"aioseo_meta_data":{"post_id":"315","title":"Document Loading and Chunking Strategies for RAG","description":"Learn document loading and chunking strategies for RAG: load PDF, HTML and Markdown in Python and Node.js, compare chunk size and overlap, and test the results.","keywords":null,"keyphrases":{"focus":{"keyphrase":"chunking strategies","score":63},"additional":[]},"primary_term":null,"canonical_url":null,"og_title":"Document Loading and Chunking Strategies for RAG","og_description":"Learn document loading and chunking strategies for RAG: load PDF, HTML and Markdown in Python and Node.js, compare chunk size and overlap, and test the results.","og_object_type":"default","og_image_type":"default","og_image_url":null,"og_image_width":null,"og_image_height":null,"og_image_custom_url":null,"og_image_custom_fields":null,"og_video":"","og_custom_url":null,"og_article_section":null,"og_article_tags":null,"twitter_use_og":false,"twitter_card":"default","twitter_image_type":"default","twitter_image_url":null,"twitter_image_custom_url":null,"twitter_image_custom_fields":null,"twitter_title":null,"twitter_description":null,"schema":{"blockGraphs":[],"customGraphs":[],"default":{"data":{"Article":[],"Course":[],"Dataset":[],"FAQPage":[],"Movie":[],"Person":[],"Product":[],"ProductReview":[],"Car":[],"Recipe":[],"Service":[],"SoftwareApplication":[],"WebPage":[]},"graphName":"BlogPosting","isEnabled":true},"graphs":[]},"schema_type":"default","schema_type_options":null,"pillar_content":false,"robots_default":true,"robots_noindex":false,"robots_noarchive":false,"robots_nosnippet":false,"robots_nofollow":false,"robots_noimageindex":false,"robots_noodp":false,"robots_notranslate":false,"robots_max_snippet":"-1","robots_max_videopreview":"-1","robots_max_imagepreview":"large","priority":0,"frequency":"default","local_seo":null,"breadcrumb_settings":null,"limit_modified_date":false,"ai":{"faqs":[],"keyPoints":[],"schemas":[],"titles":[],"descriptions":[],"socialPosts":{"email":{"subject":"","preview":"","content":""},"linkedin":[],"twitter":[],"facebook":[],"instagram":[]}},"created":"2026-11-29 14:28:30","updated":"2026-11-29 14:40:10","focus_keyword":"chunking strategies","additional_keywords":null,"truseo_locale":null,"seo_analyzer_scan_date":null},"aioseo_breadcrumb":"<div class=\"aioseo-breadcrumbs\"><span class=\"aioseo-breadcrumb\">\n\t\t\t<a href=\"https:\/\/devdojo.co.in\/\" title=\"Home\">Home<\/a>\n\t\t<\/span><span class=\"aioseo-breadcrumb-separator\">\u00bb<\/span><span class=\"aioseo-breadcrumb\">\n\t\t\t<a href=\"https:\/\/devdojo.co.in\/index.php\/category\/ai\/\" title=\"AI\">AI<\/a>\n\t\t<\/span><span class=\"aioseo-breadcrumb-separator\">\u00bb<\/span><span class=\"aioseo-breadcrumb\">\n\t\t\tGenerative AI Part 12: Document Loading and Chunking Strategies for RAG\n\t\t<\/span><\/div>","aioseo_breadcrumb_json":[{"label":"Home","link":"https:\/\/devdojo.co.in\/"},{"label":"AI","link":"https:\/\/devdojo.co.in\/index.php\/category\/ai\/"},{"label":"Generative AI Part 12: Document Loading and Chunking Strategies for RAG","link":"https:\/\/devdojo.co.in\/index.php\/2026\/11\/29\/genai-series-part-12-document-loading-chunking\/"}],"_links":{"self":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts\/315","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/comments?post=315"}],"version-history":[{"count":1,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts\/315\/revisions"}],"predecessor-version":[{"id":317,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/posts\/315\/revisions\/317"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/media\/314"}],"wp:attachment":[{"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/media?parent=315"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/categories?post=315"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devdojo.co.in\/index.php\/wp-json\/wp\/v2\/tags?post=315"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}