Stop Making AI Memorize Your Data—Teach It to Look It Up: A Local Retrieval Approach

    Stuffing entire spreadsheets or tens of thousands of rows into a conversation wastes context, slows responses, and often fails outright. This article explains why file-dumping is a bad retrieval strategy and walks through a four-step local alternative: build a lightweight catalog of your data, use it to recall candidate files, read only the relevant slices on demand, and keep extraction clean. A working Python example using only the standard library shows how to implement catalog building, keyword recall, and windowed reading—keeping things lightweight, fully local, and friendly to non-English text.

    Where the Problem Lies

    Sending a few megabytes of tables or tens of thousands of rows into a conversation in one go means betting most of your context capacity on a single file. Slightly larger datasets will overflow the window or crowd out everything else in the conversation. The typical outcomes: slower responses, mid-read failures, or simply a “content too long” error. This approach is expensive, and the results are unpredictable.

    The problem breaks down into three layers.

    1. Context is a scarce resource. Large language models can only process a limited amount of information at once—this limit is the context window. Reading an entire file is a one-shot, full-volume read that replaces actual retrieval, and it uses that resource very inefficiently.

    2. No sense of a table of contents. The model knows how to search, but it has no idea what’s actually in your data. Without a catalog, it can only scan files one by one—slow and prone to misses. When humans look up information, they check the table of contents first; models need the same kind of upfront reference.

    3. Parsing quality determines retrieval quality. If the extraction step turns a spreadsheet into blank rows and garbled text, no amount of downstream sophistication will help. Many retrieval failures happen at step one: the file was never read correctly in the first place.

    The Approach: Build a Catalog First, Fetch Data on Demand

    Instead of making the model read everything, split retrieval into four steps.

    Step 1: Generate a Catalog for Your Data

    For each file, extract lightweight metadata: file path, column names, row count, sheet names, and a one-line summary. This catalog is small enough to stay permanently in the conversation. When files change, update the catalog incrementally instead of rebuilding it from scratch every time.

    Step 2: Recall Candidates Using the Catalog

    When the user asks a question, match keywords or column names against the catalog first to identify a small set of candidate files. The recall phase only touches the catalog—never the raw files—so its cost is essentially independent of total data volume.

    Step 3: Read Only the Matched Segments

    Once candidates are identified, read only the relevant rows or sections on demand, fetching a fixed-size window each time. The smaller the read range, the more predictable your context usage.

    Step 4: Keep Extraction Clean

    Normalize encodings, strip empty rows and meaningless delimiters, and make sure headers map one-to-one with data rows. Encoding issues are especially common with non-ASCII text; a common practice is to try UTF-8 first and fall back to other common encodings if that fails.

    Example Code

    The following code demonstrates three stages: catalog building, recall, and windowed reading. It’s for illustration only—production use would need encoding detection and error handling.

    1. import csv
    2. import os
    3. from itertools import islice
    4. def build_catalog(root):
    5. """Generate lightweight metadata for CSV files under a directory."""
    6. catalog = []
    7. for dirpath, _, files in os.walk(root):
    8. for name in files:
    9. if not name.lower().endswith(".csv"):
    10. continue
    11. path = os.path.join(dirpath, name)
    12. with open(path, encoding="utf-8-sig", newline="") as f:
    13. reader = csv.reader(f)
    14. header = next(reader, [])
    15. row_count = sum(1 for _ in reader)
    16. catalog.append({"path": path, "columns": header, "rows": row_count})
    17. return catalog
    18. def recall(catalog, keyword, top_k=5):
    19. """Match column names in the catalog only, without reading raw files."""
    20. scored = []
    21. for item in catalog:
    22. score = sum(keyword in col for col in item["columns"])
    23. if score > 0:
    24. scored.append((score, item["path"]))
    25. scored.sort(reverse=True)
    26. return [path for _, path in scored[:top_k]]
    27. def read_window(path, start, size=50):
    28. """Read a fixed number of rows on demand to control context usage."""
    29. with open(path, encoding="utf-8-sig", newline="") as f:
    30. return list(islice(csv.reader(f), start, start + size))

    The example only shows column-name matching. A real catalog could also include an inverted index over values, so recall covers cell contents as well.

    Meeting Three Constraints at Once

    Lightweight, local, and multilingual-friendly are three common requirements for this kind of retrieval tool, and each can be addressed separately.

    • Lightweight: Rely only on the standard library—no resident services or extra runtimes. The catalog is just a regular file, easy to manage and version alongside your project.
    • Local: Files and indexes stay on your machine. No need to upload data to an external embedding service, so your data boundary stays clear.
    • Non-English text: Languages like Chinese have no natural word boundaries. Keyword matching can use character-level bigrams or dictionary-based segmentation, balancing recall rate against implementation complexity.

    In practice, few off-the-shelf solutions satisfy all three constraints simultaneously—which is one of the main reasons to build this kind of retrieval yourself.

    Practical Considerations

    • Validate the catalog regularly. When files are renamed or deleted, update the catalog in sync.
    • If recall is inaccurate, improve the column descriptions and keywords in the catalog first—don’t just increase the read volume.
    • Set an upper limit on each read. If content exceeds it, paginate instead of loading everything at once.
    • With sensitive data, keep only necessary fields in the catalog; never copy raw content into the index.

    Summary

    Build a catalog first, recall on demand, and read only the matched segments—this workflow decouples context overhead from total data volume. The model no longer needs to memorize your entire dataset; it just needs to know where to look and which slice to read once it gets there.