Personal project · 2026
RAG pipeline with cited answers
A learning project for the data side of LLM applications: how documents become chunks and vectors, how retrieval finds them, and how the answer stays tied to its sources.
- Role
- On my own
- When
- 2026
- Type
- Personal project
- Stack
- pgvector, OpenAI API, FastAPI, Docker
Text and Markdown documents are split by a paragraph-aware chunker (512 tokens, 64 overlap), embedded with text-embedding-3-large at 1536 dimensions and stored in pgvector with an HNSW cosine index. A question is embedded, the top matches are retrieved with an optional lexical rerank, packed into a token-budgeted context, and answered by an LLM at temperature 0 that returns the chunks it cited.
How it works
- A paragraph-aware chunker splits text and Markdown into 512-token chunks with 64 tokens of overlap.
- text-embedding-3-large embeddings at 1536 dimensions are stored in pgvector with an HNSW cosine index.
- A question retrieves the top matches (with an optional lexical rerank) into a token-budgeted context, and an LLM at temperature 0 answers with the chunks it cited.
What testing caught
- 3072-dimension embeddings can't be indexed by pgvector, so it now uses 1536 with HNSW.
- Re-ingesting a shorter document left stale chunks behind; it's now one atomic replace.
- Citations listed chunks the answer never used; now they list only what was cited.
Status
28 tests in CI, including integration tests against a real PostgreSQL and pgvector service. Retrieval quality and latency haven't been benchmarked yet, so no numbers are claimed.
From the code
Chunks are numbered for citation within a token budget, and the answer's citations are mapped back to the exact chunks it used.
def build_context(chunks: list[dict], max_tokens: int, enc=None) -> tuple[str, list[dict]]:
"""Number chunks for citation and stop before the token budget is exceeded."""
enc = enc or tiktoken.get_encoding("cl100k_base")
parts, used, total = [], [], 0
for c in chunks:
block = f"[Chunk {len(used) + 1}] (doc: {c['doc_id']})\n{c['text']}"
n = len(enc.encode(block))
if used and total + n > max_tokens:
break
parts.append(block)
used.append(c)
total += n
return "\n\n".join(parts), used
def cited_chunks(answer: str, chunks: list[dict]) -> list[dict]:
"""The chunks the answer actually cites, in citation order, without duplicates."""
seen, out = set(), []
for n in (int(m) for m in re.findall(r"\[Chunk (\d+)\]", answer)):
if 1 <= n <= len(chunks) and n not in seen:
seen.add(n)
out.append(chunks[n - 1])
return out