You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Date: 2025-09-23
Scope: Current rag/ package (loaders, splitter, embeddings, vectorstore, retriever, chain, wrapper) + how API & UI consume it.
1. Conceptual Model
The Retrieval-Augmented Generation (RAG) layer transforms raw log text into structured, queryable semantic & lexical indices and feeds a language model with the most relevant context for each issue (query). The pipeline stages:
Acquisition (line Documents)
Issue Extraction (filtering for severity)
Context Chunking (windowed text segments)
Embedding (dense vector representations)
Index Construction (FAISS + BM25)
Hybrid Retrieval (ensemble weighted merge)
Prompt Assembly (structured diagnostic template)
Answer Generation (LLM)
Enrichment (citations / timestamps)
2. Data Primitives
LangChain Document
Each Document = { page_content: str, metadata: { source, line_no, severity? } }.
Two logical corpora:
Issue Documents: individual ERROR/WARN lines.
Context Documents: larger chunks built from many adjacent lines (for semantic coverage).
In-Memory Stores
ERROR_STORE (api layer) maps issue id → issue record + optional _answer (answer cache + sources).
VectorStores instance retains: raw docs, FAISS index, BM25 retriever reference.
3. Module Overview & Responsibilities
Module
Responsibility
Key Exports
loaders.py
Convert raw files to line Documents + severity filtering
load_log_files, extract_issue_docs
splitter.py
Chunk raw lines into retrieval windows
split_context
embeddings.py
Provide embedding function/backends
get_embeddings (implied)
vectorstore.py
Build/augment FAISS + BM25 & persistence
VectorStores
retriever.py
Compose hybrid ensemble & raw source fetch
build_ensemble, fetch_sources
chain.py
Build & run RetrievalQA LLM chain
build_chain, run_qa
wrapper.py
All-in-one programmatic interface
RAGWrapper
4. loaders.py – Acquisition & Issue Filtering
Flow
Iterate files line-by-line, constructing a Document per non-empty line.
extract_issue_docs(docs) returns only documents with severity set.
Design Notes
Using line-level Documents preserves source + line number for fine-grained citations.
Severity detection intentionally simple for speed; can extend to parse timestamps / log levels via regex groups.
Non-blocking: If a file is huge, still O(lines) streaming; memory footprint bounded by keeping lines (optimizable with streaming chunker).
Extension Points
Need
Strategy
Additional severities (INFO, DEBUG)
Expand predicate & badge mapping
Structured fields (thread id, module)
Regex extract & add to metadata
Multiline stack traces
Accumulate until blank line → single Document
5. splitter.py – Context Chunking
Purpose
Dense retrieval benefits from semantic windows richer than a single log line. Chunking aggregates adjacent lines up to CHUNK_SIZE chars with overlap to preserve cross-boundary context.
Algorithm (Typical)
Pseudo:
current = [] ; length = 0
for doc in line_docs:
current.append(doc.page_content)
length += len(doc.page_content) + 1
if length >= CHUNK_SIZE:
emit Document('\n'.join(current), metadata={source: first.source, line_no: first.line_no})
rewind buffer by overlap characters (approx via slicing concatenated string)
Trade-offs
Parameter
Impact
CHUNK_SIZE large
Fewer embeddings, broader context per vector; risk of noise
CHUNK_SIZE small
More precise retrieval; higher embedding cost
Overlap high
Better continuity; more tokens + cost
Enhancements
Dynamic splitting on semantic boundaries (timestamps, severity transitions).
Skip embedding lines classified as low value (DEBUG noise) to reduce token volume.
6. embeddings.py – Embedding Backend Abstraction
Goals
Uniform interface for vectorization.
Simple backend switch via env (EMBED_BACKEND = hf or openai).
Returns answer; attach original docs as sources with trimmed metadata.
Error Handling
If retriever empty: still produce answer (LLM may disclaim) — can enforce fallback text.
Add token length guard (truncate docs when exceeding model context limit).
Enhancements
Feature
Method
Streaming
Replace standard invoke with async streaming & SSE to client
Citation markup
Insert inline markers [1][2] referencing doc rank
Confidence score
Add self-eval secondary prompt (answer critique)
10. wrapper.py – High-Level Orchestration
Purpose
Allow external Python code to leverage the same ingestion & question answering logic without HTTP. Encapsulates state lifecycle and provides a clean API.
Pattern
rag = RAGWrapper(embedding_backend="hf")
rag.ingest_logs(["/path/app.log"]) # internally loads, extracts issues, chunks
rag.build() # if not auto-triggered
ans = rag.query("ERROR connecting to DB")
print(ans.answer, ans.sources)
Internal State
Maintains its own VectorStores instance.
Tracks whether build is done (status).
Provides retrieval-only path for debugging and evaluation.
Extension
Multi-corpus mode: maintain dict of corpora keyed by label.
Caching: store (query_hash -> answer) to bypass recompute.
Sanitize / filter suspicious tokens before prompt assembly
PII Leakage
Raw logs may contain IDs
Add redaction pre-embedding (regex patterns)
Model Misuse
Off-policy answers
Constrain system prompt to scope (diagnostics only)
16. Testing Suggestions (RAG Focused)
Test
Purpose
Retrieval sanity
Query known log snippet returns its source top-1
Hybrid parity
Vector-only vs hybrid quality delta measured
Chunk boundary
Issue near chunk edges still retrieved
Export correctness
Ensure resolved flag + timestamps present
Add incremental
Second upload doesn't degrade prior recall
17. Common Customizations
Need
Change
Adjust recall depth
Set TOP_K env; consider differing values per retriever internally
Penalize stale docs
Add decay factor to combined score using ingestion timestamp
Multi-tenant
Instantiate a VectorStores + QA_CHAIN per tenant id
Severity weighting
Re-rank results boosting docs near ERROR lines
18. Minimal Re-Implementation Sketch
(For quick port to another stack)
lines = read_lines(files)
issues = [l for l in lines if is_issue(l)]
chunks = make_chunks(lines)
vecs = embed(chunks)
faiss = build_faiss(vecs)
while query:
docs_v = search_faiss(query, faiss)
docs_b = bm25(query, chunks)
merged = fuse(docs_v, docs_b)
prompt = make_prompt(query, merged)
answer = llm(prompt)
return answer, citations(merged)
19. Quick Reference Table
Stage
File
Primary Function
Load Lines
loaders.py
load_log_files
Filter Issues
loaders.py
extract_issue_docs
Build Context
splitter.py
split_context
Embed
embeddings.py
get_embeddings (implied)
Index
vectorstore.py
build / add
Retrieve
retriever.py
fetch_sources / ensemble internal
QA Chain
chain.py
run_qa
Programmatic Wrapper
wrapper.py
RAGWrapper.query
20. Summary
The rag/ package implements a clear, extensible RAG core: minimal, modular pieces aligned to ingestion, indexing, retrieval fusion, and guided answer generation. Each module has a single responsibility, allowing targeted optimization (performance or quality) without broad refactors. This document serves as a comprehensive guide to understand, extend, and safely optimize the system.