Online · Novi Sad · Serbia

Python Coding Classes for Children in Novi Sad

Python coding classes for children in Novi Sad provide an essential foundation in software engineering logic—variables, games, calculators and interactive tools—suited to a city known for its tech community.

Python Novi Sad

Chapter 180 — How to Load Documents and Prepare Data for a RAG AI Chatbot

1. Introduction to Document Loaders in RAG

When building a Retrieval-Augmented Generation (RAG) pipeline, Large Language Models (LLMs) need access to external knowledge bases to answer questions accurately. Document Loaders serve as the foundational component in LangChain that ingests external data—from local files, web pages, or databases—and brings it into the RAG workflow.

  ┌─────────────────────────────────────────────────────────────┐
  │              Document Loader Role in RAG Pipeline           │
  ├─────────────────────────────────────────────────────────────┤
  │  External Knowledge Sources  ──►  Document Loaders          │
  │  (PDFs, CSVs, Web URLs, YT)      (Ingestion & Extraction)   │
  │                                           │                 │
  │                                           ▼                 │
  │  RAG Search & Vector Index ◄── Text Chunks + Metadata       │
  └─────────────────────────────────────────────────────────────┘
    

Core Definition:

  • Document Loaders: Framework utilities in LangChain that read external files or streams, extract raw content, attach metadata, and format the data into standardized Document objects for processing.

2. Categories of Document Loaders (Structured vs. Unstructured Data)

LangChain provides specialized loaders categorized by data type and file format:

  ┌─────────────────────────────────────────────────────────────┐
  │                Document Loader Classifications              │
  ├───────────────────────────────┬─────────────────────────────┤
  │ Structured / Semi-Structured  │ Unstructured Data           │
  ├───────────────────────────────┼─────────────────────────────┤
  │ • PDF Loaders                 │ • Web Page Loaders          │
  │   (PyPDFLoader,               │   (UnstructuredURLLoader)   │
  │    PDFPlumberLoader)          │ • YouTube Loaders           │
  │ • CSV Loaders                 │   (Extracts transcripts)    │
  │   (CSVLoader for tables)      │                             │
  └───────────────────────────────┴─────────────────────────────┘
    

A. PDF Loaders (PyPDFLoader, PDFPlumberLoader):

  • Formatting Preservation: Unlike Word or Notepad documents where formatting can shift across platforms, PDF documents preserve exact formatting and layout across different operating systems.
  • Static Content: PDFs often store uneditable text, making dedicated PDF loaders necessary to extract clean text streams into the RAG pipeline.

B. CSV Loaders (CSVLoader):

  • Tabular Data: Client data provided in data science workflows frequently comes in tabular format as Comma-Separated Values (CSV). CSV loaders parse structured rows and columns into usable document objects.

C. Web Page Loaders (UnstructuredURLLoader):

  • Up-to-Date Web Content: Much of the world's current knowledge resides on the internet. Web page loaders scrape live web URLs to pull updated, unstructured text into the RAG system.

D. YouTube Loaders (YoutubeLoader):

  • Transcript Extraction: Video loaders extract text transcripts directly from YouTube video URLs to incorporate video knowledge into the pipeline.

3. How Document Loaders Work

When a document loader ingests a source file, it performs a multi-step pre-processing sequence:

  ┌─────────────────────────────────────────────────────────────┐
  │                 Document Loader Execution Flow              │
  ├─────────────────────────────────────────────────────────────┤
  │  1. Read Source      ──► Ingests raw data from disk or URL  │
  │  2. Text Chunking    ──► Divides long text into chunks      │
  │  3. Attach Metadata  ──► Adds title, timestamp, URL, source │
  │  4. Vector Embedding ──► Converts chunks to vector embeddings│
  └─────────────────────────────────────────────────────────────┘
    
  1. Read Source Data: Reads content from local hard drives or remote URLs.
  2. Text Chunking: Divides long text into smaller segments (chunks) to increase retrieval speed and processing performance.
  3. Attach Metadata: Attaches extra contextual attributes to each chunk—such as document title, creation timestamp, source URL, or page number.
  4. Vector Embedding Generation: Converts each text chunk into a high-dimensional vector embedding for vector database indexing.

4. Industry Best Practices for Data Preparation

To ensure high accuracy and fast retrieval, developers should follow three key best practices:

  ┌─────────────────────────────────────────────────────────────┐
  │             Best Practices for Document Pre-Processing      │
  ├─────────────────────────────────────────────────────────────┤
  │  1. Clean & Preprocess Data                                 │
  │     • Remove boilerplate text, headers, & HTML tags.        │
  │                                                             │
  │  2. Target the 500–1,000 Token "Sweet Spot"                 │
  │     • Balances context quality with retrieval speed.        │
  │                                                             │
  │  3. Attach & Preserve Metadata                              │
  │     • Enables source tracking across massive datasets.      │
  └─────────────────────────────────────────────────────────────┘
    

A. Clean & Preprocess Data:

  • Remove unwanted boilerplate text, redundant elements, and raw HTML tags before feeding data into the pipeline to eliminate noise.

B. The 500–1,000 Token "Sweet Spot" for Chunk Size:

Selecting chunk size requires balancing context quality and retrieval speed:

  • Large Chunks: Increase answer quality/context accuracy but decrease retrieval speed.
  • Small Chunks: Increase retrieval speed but reduce answer quality due to truncated context.
  • The Sweet Spot: Setting chunk size between 500 and 1,000 tokens delivers optimal performance, maintaining both high output quality and fast retrieval speed.

C. Attach & Preserve Metadata:

  • When training or retrieving from large, multi-source datasets over time, tracking content origin becomes difficult. Attaching metadata ensures every chunk retains clear provenance tracking back to its original file source.

5. Hands-On Python Implementation in VS Code

Below is a complete Python script demonstrating how to write sample text to a file, load it using TextLoader, split it into chunks using RecursiveCharacterTextSplitter, and inspect the resulting chunks.

# =====================================================================
# Document Loading and Text Splitting with LangChain (Topic 180)
# =====================================================================

import os
# 1. Import TextLoader and RecursiveCharacterTextSplitter
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter

# 2. Define Sample Text Content
sample_content = (
    "LangChain simplifies building applications powered by language models. "
    "Retrieval-Augmented Generation (RAG) lets AI answer questions from documents. "
    "Document loaders ingest external knowledge into the RAG pipeline. "
    "Text splitters divide long documents into manageable text chunks. "
    "Attaching metadata allows developers to track the exact source of content."
)

# 3. Save Sample Text to Local Storage File with UTF-8 Encoding
file_name = "langchain_intro.txt"
with open(file_name, "w", encoding="utf-8") as f:
    f.write(sample_content)

print("Sample file created successfully on disk.")

# 4. Initialize TextLoader with UTF-8 Encoding
loader = TextLoader(file_name, encoding="utf-8")

# 5. Load Document Objects into Memory
documents = loader.load()
print(f"Loaded {len(documents)} document object(s) from storage.")

# 6. Configure RecursiveCharacterTextSplitter
# Setting chunk_size=100 characters and chunk_overlap=20 characters
text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=100,
    chunk_overlap=20,
    length_function=len,
    separators=["\\n", " "]
)

# 7. Split Documents into Text Chunks
chunks = text_splitter.split_documents(documents)

# 8. Output Splitting Results and Chunk Contents
print(f"\\nTotal Text Chunks Created: {len(chunks)}\\n")
for idx, chunk in enumerate(chunks):
    print(f"--- Chunk {idx} ---")
    print(f"Content : {chunk.page_content}")
    print(f"Metadata: {chunk.metadata}\\n")

# Clean up local sample file
if os.path.exists(file_name):
    os.remove(file_name)
    

Execution Results:

  • File Creation & Loading: The script saves raw text to langchain_intro.txt using utf-8 encoding and loads it as a Document object.
  • Chunk Generation: RecursiveCharacterTextSplitter splits the text into 5 distinct chunks (Chunks 0 through 4) with a chunk_overlap of 20 characters to preserve context across boundaries.

6. Summary Comparison Table

Component / Concept Setting / Parameter Practical Role in RAG Pipeline
Document Loader TextLoader, PyPDFLoader, CSVLoader Ingests external source data into standardized documents.
Data Types Structured (PDF/CSV) vs. Unstructured (Web/YT) Handles diverse client formats.
Text Splitter RecursiveCharacterTextSplitter Divides long text into smaller chunks.
Optimal Chunk Size 500 to 1,000 tokens Sweet spot balancing retrieval speed and quality.
Chunk Overlap chunk_overlap=20 Preserves context across chunk boundaries.
Metadata Title, timestamp, URL, source Tracks content provenance across multi-source data.

Lesson Q&A

Purpose & Essential Role: Document loaders are specialized components in LangChain designed to bring external knowledge into a Retrieval-Augmented Generation (RAG) pipeline. To perform RAG, relevant documents must first be ingested and retrieved from external sources, and document loaders automate this process.

Primary Types of Document Loaders:

  1. PDF Loaders (PyPDFLoader & PDFPlumberLoader): Used to load PDF files into the RAG pipeline. Unlike Word or Notepad documents where formatting may shift across platforms, PDFs preserve strict formatting across systems.
  2. CSV Loader: Ingests tabular datasets (comma-separated values) commonly provided by clients for data analysis.
  3. Unstructured URL Loader: Fetches up-to-date web page data from the internet to supply current information to the pipeline.
  4. YouTube Loader: Extracts video transcripts directly from YouTube URLs into the pipeline.

Structured vs. Unstructured Classification: PDF and CSV loaders process structured data, whereas web page loaders handle unstructured data.

Data Processing & Metadata: Loaders read raw data from sources, split content into chunks to accelerate pipeline processing speed, and attach metadata attributes (such as document titles, timestamps, and URLs) to each chunk.

Data Cleaning & Preprocessing: Raw text should be cleaned prior to pipeline ingestion by stripping away boilerplate elements and irrelevant HTML tags that add noise without contributing semantic value.

Optimal Chunk Size & Trade-Offs:

  • Large Chunks: Improve retrieval quality and context accuracy, but reduce processing and retrieval speed.
  • Small Chunks: Speed up retrieval processing, but degrade context quality and accuracy.
  • Recommended Sweet Spot: Setting a chunk size of 500 to 1,000 tokens provides the optimal balance between high context quality and fast retrieval speed.

Metadata Tagging: Attaching metadata (such as document source, title, and timestamp) to every chunk is essential for source traceability. As models scale to train on massive, multi-source datasets over time, metadata tags allow developers to track exact document origins and prevent data loss.

Step 1: Module Imports: Import TextLoader from langchain_community.document_loaders and RecursiveCharacterTextSplitter from langchain_text_splitters.

Step 2: File Creation & Document Loading:

  • Create or specify a text document (e.g., langchain_intro.txt) saved with UTF-8 encoding.
  • Instantiate TextLoader with the target file path and UTF-8 encoding parameter.
  • Call the .load() method on the loader instance to read the file and store the extracted data in a document object.

Step 3: Text Splitting Configuration & Execution:

  • Instantiate RecursiveCharacterTextSplitter with specific parameters: a chunk_size of 100, a chunk_overlap of 20 characters to preserve context across chunk boundaries, length_function=len, and newline or space characters as separators.
  • Call .split_documents(documents) to segment the loaded text into structured chunks (e.g., yielding 5 individual text chunks) ready for vector embedding.

What children can learn

WhatsApp +92 322 421 7059

AI and Robotics Club | The 100 Mission AI & Robotics Hero Journey

Recommended self-paced course for parents & educators

Python for Kids – 12 Pillars on Udemy.

Disclosure: This page contains affiliate links. We may earn from qualifying purchases at no extra cost to you. Links are intended for parents and educators, not as marketing directed at young children.

Software Capital Skills: Beginner Python Syntax Courses in Novi Sad

Novi Sad’s software culture makes Python a natural first language. Classes emphasise readable structure and small working projects. Video materials are listed in the course directory. Enquire +92 322 4217059. Foundations first—no career guarantees.

Frequently asked questions

Why learn Python in a tech hub like Novi Sad?

Python provides an essential foundation in software engineering logic, ideal for tech-forward students.

What projects do kids build in Python?

Projects include text games, automated calculators, and interactive logic tools.

Where can we find self-paced video learning materials?

Links to our Python video courses are available in our website's course directory.

Explore related learning

BelgradeRobotics · Belgrade SplitPython · Split MariborPython · Maribor