dense
dense
¶
In-memory dense retrieval backend.
Uses any :class:Embedder (default: :class:OllamaEmbedder with
nomic-embed-text) to embed stored text, then ranks queries by
cosine similarity via a single matrix multiply against an
L2-normalized matrix of document embeddings.
Design notes
- No persistence. The index lives in memory and is rebuilt at
startup via :mod:
scripts.index_docs. The docs corpus is small (~700 chunks) so this is fine and keeps the implementation simple. - Normalization happens at embed time, not at query time. Storing
unit vectors means retrieval is one
docs @ querydot product. - Store growth is amortized: we keep a list of per-call embedding
matrices and concatenate lazily in :meth:
retrieve. This avoids an O(n²)np.concatenatepattern while still giving callers one contiguous matrix when they actually need to search.
Classes¶
MdChunk
dataclass
¶
A markdown chunk annotated with its header breadcrumb.
DuplicateGroup
dataclass
¶
DuplicateGroup(kept_index: int, kept_source: str, dropped_indices: List[int] = list(), dropped_sources: List[str] = list(), distinct_files: int = 0, sample_text: str = '')
A cluster of chunks judged to be near-duplicates of each other.
DedupeReport
dataclass
¶
DedupeReport(input_count: int = 0, output_count: int = 0, groups: List[DuplicateGroup] = list())
Audit trail for a deduplication pass.
DenseMemory
¶
DenseMemory(embedder: Optional[Embedder] = None)
Bases: MemoryBackend
In-memory dense retrieval via cosine similarity.
The embedder is lazy: it is created on first :meth:store or
:meth:retrieve call, so instantiating :class:DenseMemory does
not require Ollama to be running.
| PARAMETER | DESCRIPTION |
|---|---|
embedder
|
An :class:
TYPE:
|
Source code in src/openjarvis/tools/storage/dense.py
Functions¶
store
¶
Embed and store one document. Returns its id.
Source code in src/openjarvis/tools/storage/dense.py
store_many
¶
store_many(contents: List[str], *, sources: Optional[List[str]] = None, metadatas: Optional[List[Dict[str, Any]]] = None) -> List[str]
Embed a batch of documents in one go. Much faster than per-doc.
Accepts parallel lists; missing sources/metadatas default to empty.
Source code in src/openjarvis/tools/storage/dense.py
retrieve
¶
retrieve(query: str, *, top_k: int = 5, **kwargs: Any) -> List[RetrievalResult]
Return top-k documents by cosine similarity.
Scores are in [-1, 1] for normalized vectors; for
nomic-embed-text in practice scores on reasonable queries
fall in [0.3, 0.8]. Empty index or query → empty list.
Source code in src/openjarvis/tools/storage/dense.py
delete
¶
Remove a document by id. Returns True if it existed.
Source code in src/openjarvis/tools/storage/dense.py
clear
¶
Drop all stored documents.
Functions¶
chunk_markdown
¶
chunk_markdown(text: str, *, source: str = '', max_section_tokens: int = 500, paragraph_overlap_tokens: int = 50, max_section_chars: int = 4000) -> List[MdChunk]
Split markdown into chunks using ##/### as primary boundaries.
Strategy:
1. Detect section boundaries at h2 (##) and h3 (###).
h1 (#) is treated as the document title (captured in the
breadcrumb but not used to split).
2. Skip headers that appear inside fenced code blocks — those are
usually shell comments (# Install X) not real headers.
3. If a section body exceeds max_section_tokens (whitespace
tokens) OR max_section_chars (raw chars), slide a window
over its paragraphs with paragraph_overlap_tokens overlap.
4. Prefix each chunk with a breadcrumb of its parent headers
so the embedding captures hierarchical context.
The char cap is the critical safety net: embedding models count BPE
tokens, and technical content (file paths, code, URLs) has ~8 BPE
tokens per whitespace token — so a whitespace-token-only limit
silently lets 2–3× overflows through and some embedders (e.g.
nomic-embed-text) reject them at runtime. 4000 chars is a
conservative ceiling for nomic-embed-text's 8192-token window.
Empty input → empty list.
Source code in src/openjarvis/tools/storage/dense.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | |
dedupe_chunks
¶
dedupe_chunks(chunks: List[MdChunk], *, ngram_n: int = 5, similarity_threshold: float = 0.7, min_files_for_dup: int = 3) -> Tuple[List[MdChunk], DedupeReport]
Drop near-duplicate chunks that recur across many source files.
A chunk cluster is considered a duplicate (and collapsed to one canonical entry) when:
- Pairwise word-level n-gram Jaccard >=
similarity_thresholdon the body text (breadcrumb stripped). N-grams are computed after lowercasing and stripping non-alphanumeric punctuation, so superficial differences (capitalization, typography) don't hide duplication. - The cluster spans >=
min_files_for_dupdistinct source files. Two-file repeats are kept on the assumption they may be legitimately doc-specific; >=3 is the bar for boilerplate.
For each qualifying cluster, the chunk from the most-specific source path wins (deepest dir, longest basename, lexicographic tiebreak); the rest are dropped.
Returns (surviving_chunks, report). The chunker, embedder and
retrieval logic are NOT modified — this function is a pure pre-
processing pass over the chunk list before embedding.
Source code in src/openjarvis/tools/storage/dense.py
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 | |
log_dedupe_report
¶
log_dedupe_report(report: DedupeReport, *, level: int = INFO) -> None
Emit a human-readable summary of a dedupe pass at level.