Search Tutorials
--Ads--Table-Aware RAG
Keep tables intact, summarise them for retrieval and answer numeric questions correctly.
Tables hold some of the most valuable facts in business documents: price lists, limits by grade, quarterly figures, specifications. They are also where naive RAG fails most often. Splitting a table across chunks separates values from their column headers; embedding a grid of numbers gives a vector that matches nothing; and asking the model to add up figures from text invites arithmetic mistakes. This lesson covers how to keep tables intact, make them findable and answer numeric questions correctly.
Rule 1: Extract tables as tables
Use a table-aware extractor (pdfplumber, Docling, Unstructured or a vision LLM, as covered in Parsing Complex Documents) and store each table as Markdown or HTML. Both keep rows and columns readable for an LLM.
Rule 2: Never separate values from headers
Small tables should be one chunk. Large tables must be split by rows, and every piece must repeat the header row and carry the table's title:
def split_markdown_table(title: str, table_md: str, rows_per_chunk: int = 20) -> list[str]:
lines = [l for l in table_md.strip().splitlines() if l.strip()]
header, separator, rows = lines[0], lines[1], lines[2:]
chunks = []
for start in range(0, len(rows), rows_per_chunk):
part = rows[start:start + rows_per_chunk]
chunks.append(f"Table: {title} (rows {start + 1}-{start + len(part)} of {len(rows)})\n"
+ "\n".join([header, separator, *part]))
return chunks
Rule 3: Make tables findable with a summary
A user asks "how much can I spend on a hotel in Mumbai?". The table chunk contains "| L1-L3 | 6,000 | 4,000 |", which shares almost no words with the question. Generate a natural-language summary of each table, index the summary, and return the table itself (the multi-vector pattern):
from rag_helpers import ask
def summarize_table(title: str, table_md: str, context: str = "") -> str:
return ask(f"Context: {context}\n\nTable title: {title}\n{table_md}\n\n"
"Describe in 2-4 sentences what this table contains: what the rows and columns "
"represent, the units, and the kinds of questions it can answer. Mention key "
"categories by name.", max_tokens=300)
table_md = """| Employee grade | Metro cities (INR/night) | Other cities (INR/night) |
|---|---|---|
| L1-L3 | 6,000 | 4,000 |
| L4-L5 | 9,000 | 6,000 |
| L6+ | 12,000 | 8,000 |"""
summary = summarize_table("Hotel limits by grade", table_md,
context="Travel policy. Metro cities: Mumbai, Delhi, Bengaluru, Chennai, Kolkata, Hyderabad.")
record = {"id": "travel-table-2", "text": summary, # what gets embedded
"metadata": {"type": "table", "table_markdown": table_md}} # what the LLM receives
Rule 4: Let code do the arithmetic
LLMs read tables well but can make mistakes when summing or averaging many numbers. For calculations over larger tables, load the table into a DataFrame or database and compute the answer with code:
- For tables that come from databases or spreadsheets, keep them there and use Text-to-SQL.
- For tables extracted from documents, load the Markdown into pandas and let the LLM write a pandas expression, run it in a restricted environment, and answer from the result. Alternatively, use the Claude API's server-side code execution tool, which runs the calculation in a sandbox.
import io
import pandas as pd
def markdown_to_dataframe(table_md: str) -> pd.DataFrame:
lines = [l for l in table_md.strip().splitlines() if not set(l.replace("|", "").strip()) <= set("-: ")]
df = pd.read_csv(io.StringIO("\n".join(l.strip().strip("|") for l in lines)), sep="|")
df.columns = [c.strip() for c in df.columns]
return df.apply(lambda col: col.str.strip() if col.dtype == "object" else col)
df = markdown_to_dataframe(table_md)
print(df)
Rule 5: Give the model the whole table at answer time
When a table chunk is retrieved, send the complete table (or the complete row group) plus its title and units, not a fragment. Ask the model to quote the row it used, which makes the answer easy to check: "Hotel limit for L2 in Mumbai: 6,000 rupees per night (row: L1-L3, column: Metro cities)."
Key takeaways
- Extract tables as Markdown or HTML and keep them whole where possible.
- When splitting large tables, repeat the header and title in every chunk.
- Index a natural-language summary of each table and return the table itself.
- Use SQL or pandas for calculations, and send complete tables to the LLM.