Module 1 · LlamaIndex architecture

LlamaHub and data connectors

5 min read

A company's data lives everywhere: files on a shared drive, Notion or Confluence pages, tickets, SQL databases, internal APIs. LlamaIndex converts all of it into the same format — Documents — through its readers. Hundreds are available via LlamaHub; and when none fits, writing one takes twenty lines. This lesson shows both, and the rules for good loading.

SimpleDirectoryReader: the Swiss army knife for files

from llama_index.core import SimpleDirectoryReader

reader = SimpleDirectoryReader(
    input_dir="data",
    recursive=True,                  # walks subfolders
    required_exts=[".md", ".pdf"],   # ignores the rest
    filename_as_id=True,             # identifier derived from the file name
)
documents = reader.load_data()

It picks a reader by extension (PDF, Word, PowerPoint, Markdown, HTML, images…, most provided by the llama-index-readers-file package) and adds file metadata: name, path, type, size, dates. For a PDF, it produces one document per page, with page_label as metadata — handy to cite the exact page.

Three parameters change everything in production:

  • file_extractor replaces the reader for an extension with yours.
  • file_metadata is a function called for each file, returning the metadata to attach.
  • filename_as_id gives each document a stable identifier, essential for incremental ingestion.

A custom reader: Markdown with a header

Nimbus product sheets start with a metadata header:

---
sku: LAMP-3
name: Lampe de bureau Halo
category: eclairage
---
# Lampe de bureau Halo (LAMP-3)
…

The default Markdown reader would treat this header as text: it would be indexed, and the metadata would not be usable for filtering. Lumen provides its own reader:

from llama_index.core.readers.base import BaseReader


class FrontMatterMarkdownReader(BaseReader):
    """Lit un fichier Markdown et transforme son en-tête YAML simple (clé: valeur) en métadonnées."""

    def load_data(self, file: Path, extra_info: dict | None = None) -> list[Document]:
        text = Path(file).read_text(encoding="utf-8")
        metadata: dict = dict(extra_info or {})
        if text.startswith("---"):
            header, _, text = text[3:].partition("\n---")
            for line in header.strip().splitlines():
                key, _, value = line.partition(":")
                metadata[key.strip()] = value.strip()
        return [Document(text=text.strip(), metadata=metadata)]

It is plugged into the desired extension: file_extractor={".md": FrontMatterMarkdownReader()}. The extra_info parameter contains the metadata that SimpleDirectoryReader has already computed for the file: we complete it rather than lose it.

Truly stable identifiers

filename_as_id=True produces identifiers from the file's full path, for example L:\projects\lumen\data\policies\returns.md_part_0. The day the folder is moved — another machine, a container, a server — all identifiers change, and incremental ingestion treats the whole corpus as new. Lumen makes them relative to the data folder:

for doc in documents:
    # « policies/returns.md_part_0 »
    doc.id_ = doc.metadata["source"] + doc.id_[doc.id_.rfind("_part_"):]

It seems like a detail; in production, it's the difference between reindexing three modified files and reindexing (and paying again for) the whole corpus.

Choosing what the model and the embeddings see

Not all metadata is useful everywhere. The file path or its size help filtering and auditing, but they pollute the embedding (the vector also encodes this noise) and consume tokens in the prompt. Each document lets you exclude keys separately:

doc.excluded_embed_metadata_keys += ["file_path", "file_size", "creation_date", "last_modified_date"]
doc.excluded_llm_metadata_keys += ["file_path", "file_size", "creation_date", "last_modified_date"]

Conversely, metadata like the section title or the product name improves the embedding: it gives context to a passage that, alone, would be ambiguous ("Warranty: 3 years" — of what?).

One source, many documents: the FAQ case

For a CSV, the generic reader often concatenates rows. For a FAQ, that's the wrong granularity: each entry is standalone and must be retrieved alone. Lumen creates one document per row, with the question and the answer in the text, so it can be found through either wording:

Document(
    text=f"Question : {row['question']}\nRéponse : {row['answer']}",
    metadata={"source": "faq.csv", "collection": "faq", "category": row["category"]},
    id_=f"faq.csv#{i}",
)

Choosing the right document granularity at loading time avoids contortions at chunking time.

LlamaHub: hundreds of connectors

For sources other than files, LlamaHub lists readers published as llama-index-readers-* packages: web pages, Notion, Confluence, Google Drive, Slack, GitHub, SQL databases, S3, and many more. They are all used the same way: install the package, instantiate the reader, call load_data(), and get Documents.

Before adopting one in production, check three points:

  1. The metadata produced. Does it include a stable identifier (the Notion page ID, not its title which can change) and the modification date?
  2. Incremental loading. Can the connector fetch only what changed since a given date? Otherwise, every refresh rereads the whole source.
  3. Access rights. A connector reads with the rights of the account that configures it. Indexing an entire document space makes its content queryable by every user of the assistant: documents reserved for management have no place in the support base.

Key takeaways

  • Readers convert each source into Documents; SimpleDirectoryReader covers most files.
  • file_extractor plugs in a custom reader; file_metadata attaches metadata to each file.
  • Relative, stable identifiers are essential for incremental ingestion.
  • Exclude technical metadata from embeddings and prompts; keep the metadata that gives context.
  • Choose document granularity at loading time; check identifiers, incremental loading and access rights of connectors.

Practice

  1. Load data/ without the custom reader: what happens to the product sheet headers? And to the metadata?
  2. Add a language metadata field ("fr" by default) in load_files and check that it appears on the nodes.
  3. Write a reader for a JSON file of support tickets (one document per ticket, identifier = ticket number).

Resources