Skip to content

Commit 66eb1bb

Browse files
author
福晋
committed
chore: remove chunk
1 parent 1864797 commit 66eb1bb

9 files changed

Lines changed: 42 additions & 912 deletions

File tree

‎README.md‎

Lines changed: 11 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@ A local context retrieval library that enables semantic search over your documen
1515
- 🔄 **Deduplication**: Automatically skip already-loaded documents; content-hash change detection for re-embedding updated files
1616
- ⚖️ **Weight Configuration**: Per-field FTS boost weights and RRF rank constant tuning
1717
- 🛡️ **Clear Error Messages**: Throws descriptive errors when Transformers model is unavailable, guiding users to fix the issue
18-
- 🧩 **Document Chunking**: Split documents into semantic chunks (heading-aware for Markdown, fixed-size for plain text) for finer-grained retrieval
18+
- 🔁 **Two-stage Reranking**: KeywordReranker boosts candidates with exact query term matches after coarse vector/hybrid search
1919
- 🔁 **Two-stage Reranking**: KeywordReranker boosts candidates with exact query term matches after coarse vector/hybrid search
2020
- 🌐 **Query Expansion**: SynonymExpander uses user-provided synonym maps to bridge CN↔EN terminology gaps
21-
- 📊 **Progress Callback**: `onProgress` hook for monitoring load phases (load → chunk → embed → insert)
21+
- 📊 **Progress Callback**: `onProgress` hook for monitoring load phases (load → embed → insert)
2222
- 🏗️ **fromDir() Quick-start**: One-call setup from a project directory with auto-derived defaults
2323

2424

@@ -43,7 +43,7 @@ await ctx.load('f2', './f2-docs/**/*.json');
4343

4444
// Query a single library (default: hybrid search = vector + FTS text)
4545
const results = await ctx.query('How to configure a line chart', { library: 'g2', topK: 5 });
46-
// => [{ content: '...', score: 0.92, scoreMode: 'hybrid', id: 'g2-docs/line.md', chunk: {...} }, ...]
46+
// => [{ content: '...', score: 0.92, scoreMode: 'hybrid', id: 'g2-docs/line.md' }, ...]
4747

4848
// Query with two-stage reranking (pulls extra candidates, then re-scores)
4949
const rerankedResults = await ctx.query('sankey diagram', { library: 'g2', topK: 5, rerank: { rerankFactor: 3 } });
@@ -58,10 +58,7 @@ const allResults = await ctx.query('visualization', { library: '*', topK: 10 });
5858
const vectorResults = await ctx.query('chart', { library: 'g2', topK: 5, mode: 'vector' });
5959

6060
// Filter results by field value
61-
const filteredResults = await ctx.query('tooltip', { library: 'g2', topK: 5, filter: "parentDocId = 'abc123__getting_started'" });
62-
63-
// Expand a chunk result — retrieve neighboring chunks for context
64-
const expanded = await ctx.expandChunk('g2', 'abc123__getting_started', { before: 1, after: 1 });
61+
const filteredResults = await ctx.query('tooltip', { library: 'g2', topK: 5, filter: "sourceFilePath = 'docs/line-chart.md'" });
6562

6663
// Close when done (releases resources)
6764
await ctx.close();
@@ -79,8 +76,7 @@ await ctx.close();
7976
| `model` | `string` | auto | Transformers model name for embedding. Skipped when custom `embedder` is provided. |
8077
| `loaders` | `Loader[]` | built-in | Custom loaders (default: MarkdownLoader, JsonLoader, TextLoader) |
8178
| `embedder` | `Embedder` | auto-resolved | Custom embedder. Skips auto-resolution when provided. |
82-
| `onProgress` | `(phase, detail) => void` | — | Progress callback for `load()` phases: `'load'` → `'chunk'` → `'embed'` → `'insert'`. |
83-
| `chunking` | `ChunkingOptions | false` | `{ strategy: 'auto', maxChunkSize: 1024, chunkOverlap: 128 }` | Document chunking config. `false` disables chunking. |
79+
| `onProgress` | `(phase, detail) => void` | — | Progress callback for `load()` phases: `'load'` → `'embed'` → `'insert'`. |
8480
| `queryExpansion` | `QueryExpansionOptions | false` | `false` (no-op) | Query expansion with user-provided synonym map. `false` disables. Without `synonyms`, expansion is a no-op. |
8581
| `ftsFields` | `string[]` | `['content']` | Fields to index for Full Text Search in hybrid mode |
8682
| `ftsFieldWeights` | `Record<string, number>` | `{ content: 1 }` | Per-field boost weights for FTS text path. Higher = more influence. |
@@ -99,22 +95,6 @@ const ctx = await Context.create({
9995
});
10096
```
10197

102-
#### Chunking Configuration Example
103-
104-
```typescript
105-
const ctx = await Context.create({
106-
vectorsDir: './vectors',
107-
// Heading-aware chunking for Markdown, fixed-size for plain text
108-
chunking: { strategy: 'auto', maxChunkSize: 1024, chunkOverlap: 128 },
109-
});
110-
111-
// Disable chunking — embed whole documents instead
112-
const ctxWhole = await Context.create({
113-
vectorsDir: './vectors',
114-
chunking: false,
115-
});
116-
```
117-
11898
#### Query Expansion Configuration Example
11999

120100
```typescript
@@ -139,7 +119,7 @@ const ctxNoExpand = await Context.create({
139119

140120
### `ctx.load(library, pattern)`
141121

142-
Load files into a specified library with automatic batch vectorization. Documents are split into semantic chunks (when chunking is enabled), embedded in batches, and inserted into the vector store. A content-hash change detection mechanism re-embeds files whose content has changed since the last load.
122+
Load files into a specified library with automatic batch vectorization. Documents are embedded in batches and inserted into the vector store. A content-hash change detection mechanism re-embeds files whose content has changed since the last load.
143123

144124
Document IDs are derived from file paths relative to `basePath` for cross-machine consistency.
145125

@@ -162,7 +142,7 @@ const ctx = await Context.create({
162142
console.log(`${phase}: ${detail.loaded}/${detail.total}`);
163143
},
164144
});
165-
// Phases: 'load' → 'chunk' → 'embed' → 'insert'
145+
// Phases: 'load' → 'embed' → 'insert'
166146
```
167147

168148
### `ctx.query(text, options)`
@@ -175,7 +155,7 @@ Two-stage retrieval: coarse search (vector / hybrid) → optional reranking →
175155
| `topK` | `number` | `5` | Number of results to return |
176156
| `mode` | `'hybrid' | 'vector'` | `'hybrid'` | Search mode. `'hybrid'` = vector + FTS text (better recall), `'vector'` = pure semantic search |
177157
| `rerank` | `RerankOptions | false` | `false` | Reranking configuration. Pass an object `{ rerankFactor, minCandidates }` to enable, or `false` to skip |
178-
| `filter` | `string` | — | Filter expression for zvec exact-match filtering, e.g. `"parentDocId = 'abc123'"` |
158+
| `filter` | `string` | — | Filter expression for zvec exact-match filtering, e.g. `"sourceFilePath = 'docs/line.md'"` |
179159

180160
```typescript
181161
// Hybrid search (default) — best recall for exact term matching
@@ -189,8 +169,8 @@ const results = await ctx.query('line chart config', {
189169
// Pure vector search — when FTS is not needed
190170
const results = await ctx.query('chart', { library: 'g2', topK: 5, mode: 'vector' });
191171

192-
// Filter by parent document — retrieve all chunks of a specific doc
193-
const chunks = await ctx.query('tooltip', { library: 'g2', filter: "parentDocId = 'abc123'" });
172+
// Filter by source file path
173+
const filtered = await ctx.query('tooltip', { library: 'g2', filter: "sourceFilePath = 'docs/line.md'" });
194174

195175
// Multiple libraries
196176
const results = await ctx.query('chart', { library: ['g2', 'f2'], topK: 5 });
@@ -205,12 +185,11 @@ Each result includes:
205185

206186
| Field | Type | Description |
207187
|------|------|-------------|
208-
| `id` | `string` | Document / chunk ID |
188+
| `id` | `string` | Document ID |
209189
| `content` | `string` | Document content |
210190
| `score` | `number` | Similarity score (0–1) |
211191
| `scoreMode` | `'vector' | 'hybrid' | 'reranked'` | How the score was computed |
212192
| `meta` | `Record<string, unknown>` | Front-matter metadata (if present) |
213-
| `chunk` | `ChunkMeta` | Chunk metadata (if chunking is enabled) |
214193
| `sourceFilePath` | `string` | Original file path relative to `basePath` |
215194
| `library` | `string` | Which library this result came from |
216195

@@ -242,21 +221,6 @@ await ctx.untrack('g2', 'abc123__getting_started');
242221
await ctx.rebuild('g2', './g2-docs/**/*.md');
243222
```
244223

245-
### `ctx.expandChunk(library, parentDocId, options?)`
246-
247-
Expand a chunk result — retrieve neighboring chunks from the same parent document for context. Useful when a query returns a chunked fragment and you need surrounding context.
248-
249-
| Parameter | Type | Default | Description |
250-
|-----------|------|---------|-------------|
251-
| `library` | `string` | — | Library the chunk belongs to |
252-
| `parentDocId` | `string` | — | Parent document ID (from `chunk.parentDocId`) |
253-
| `before` | `number` | `1` | Number of preceding chunks |
254-
| `after` | `number` | `1` | Number of following chunks |
255-
256-
```typescript
257-
const expanded = await ctx.expandChunk('g2', 'abc123__getting_started', { before: 2, after: 2 });
258-
```
259-
260224
### `Context.fromDir(dir, options?)`
261225

262226
Quick-start convenience method — creates a Context from a project directory with auto-derived defaults (`basePath` = dir, `vectorsDir` = dir/.context/vectors).

‎src/context.ts‎

Lines changed: 17 additions & 141 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as path from 'path';
22
import * as fs from 'fs';
33
import * as crypto from 'crypto';
44
import { glob } from 'glob';
5-
import { ContextOptions, QueryOptions, QueryResult, Document, ChunkMeta, LoadPhase, LoadProgress } from './types';
5+
import { ContextOptions, QueryOptions, QueryResult, Document, LoadPhase, LoadProgress } from './types';
66
import {
77
resolveEmbedder,
88
} from './embedder';
@@ -13,8 +13,6 @@ import { DocumentRegistry } from './registry';
1313
import { StoreManager } from './store-manager';
1414
import type { ZvecDoc } from './storage/zvec-store';
1515
import { pathToId } from './loaders/util';
16-
import { createChunker } from './loaders/chunker';
17-
import type { Chunker } from './loaders/chunker';
1816
import { createReranker } from './reranker';
1917
import type { Reranker, RerankCandidate } from './reranker';
2018
import { SynonymExpander, NoopExpander } from './query-expander';
@@ -32,7 +30,6 @@ export class Context {
3230
private readonly storeManager: StoreManager;
3331
private readonly registry: DocumentRegistry;
3432
private readonly loaders: Loader[];
35-
private readonly chunker: Chunker | null;
3633
private readonly reranker: Reranker | null;
3734
private readonly queryExpander: QueryExpander;
3835
private readonly _onProgress?: (phase: LoadPhase, detail: LoadProgress) => void;
@@ -49,13 +46,7 @@ export class Context {
4946
new JsonLoader(),
5047
new TextLoader(),
5148
];
52-
// Chunking defaults to enabled with auto strategy.
53-
// Set `chunking: false` to embed whole documents instead.
54-
this.chunker = options.chunking !== false
55-
? createChunker(options.chunking ?? undefined)
56-
: null;
5749
// Reranker is created eagerly — it has no model-load cost (KeywordReranker).
58-
// In the future this may be lazy if a cross-encoder is used.
5950
// Weights are configurable via ContextOptions.rerankWeights.
6051
this.reranker = createReranker(options.rerankWeights);
6152
// Query expansion — uses user-provided synonym map only, no built-in defaults.
@@ -113,13 +104,13 @@ export class Context {
113104
}
114105

115106
/**
116-
* Quick-start convenience method - creates a Context from a project directory.
107+
* Quick-start convenience method — creates a Context from a project directory.
117108
*
118109
* Auto-derives sensible defaults:
119110
* - basePath = dir (the project root)
120111
* - vectorsDir = dir/.context/vectors (hidden, won't pollute project)
121112
*
122-
* All other options (model, chunking, embedder, etc.) can still be
113+
* All other options (model, embedder, etc.) can still be
123114
* overridden via options.
124115
*/
125116
static async fromDir(dir: string, options?: Partial<ContextOptions>): Promise<Context> {
@@ -250,65 +241,36 @@ export class Context {
250241

251242
if (docsToEmbed.length === 0) return;
252243

253-
// Phase 2: Apply chunking (if enabled). Each chunk is independently
254-
// embedded so queries can match at the paragraph / section level.
255-
const items = this.chunker
256-
? docsToEmbed.flatMap((doc) => {
257-
const chunks = this.chunker!.chunk(doc);
258-
return chunks.map((chunk) => ({
259-
id: `${doc.id}__c${chunk.chunkIndex}`,
260-
content: chunk.content,
261-
meta: doc.meta,
262-
sourceFilePath: doc.sourceFilePath,
263-
chunk: {
264-
chunkIndex: chunk.chunkIndex,
265-
totalChunks: chunk.totalChunks,
266-
parentDocId: doc.id,
267-
headingPath: chunk.headingPath,
268-
} satisfies ChunkMeta,
269-
}));
270-
})
271-
: docsToEmbed;
272-
273-
// Progress: chunk phase complete
274-
if (this._onProgress) {
275-
this._onProgress('chunk', { loaded: items.length, total: docsToEmbed.length });
276-
}
277-
278-
// Phase 3: Batch embed all items for better performance
279-
const contents = items.map((item) => item.content);
244+
// Phase 2: Batch embed all items for better performance
245+
const contents = docsToEmbed.map((doc) => doc.content);
280246
const vectors = await this.embedder.embedBatch(contents);
281247

282248
// Progress: embed phase complete
283249
if (this._onProgress) {
284-
this._onProgress('embed', { loaded: vectors.length, total: items.length });
250+
this._onProgress('embed', { loaded: vectors.length, total: docsToEmbed.length });
285251
}
286252

287-
// Phase 4: Batch insert into store
288-
const zvecDocs: ZvecDoc[] = items.map((item, index) => ({
289-
id: item.id,
253+
// Phase 3: Batch insert into store
254+
const zvecDocs: ZvecDoc[] = docsToEmbed.map((doc, index) => ({
255+
id: doc.id,
290256
vector: vectors[index],
291257
fields: {
292-
content: item.content,
293-
meta: item.meta && Object.keys(item.meta).length > 0
294-
? JSON.stringify(item.meta)
258+
content: doc.content,
259+
meta: doc.meta && Object.keys(doc.meta).length > 0
260+
? JSON.stringify(doc.meta)
295261
: '',
296-
chunkIndex: item.chunk?.chunkIndex ?? -1,
297-
totalChunks: item.chunk?.totalChunks ?? 1,
298-
parentDocId: item.chunk?.parentDocId ?? item.id,
299-
headingPath: item.chunk?.headingPath?.join(' > ') ?? '',
300-
sourceFilePath: item.sourceFilePath ?? '',
262+
sourceFilePath: doc.sourceFilePath ?? '',
301263
},
302264
}));
303265

304266
await store.insert(zvecDocs);
305267

306268
// Progress: insert phase complete
307269
if (this._onProgress) {
308-
this._onProgress('insert', { loaded: zvecDocs.length, total: items.length });
270+
this._onProgress('insert', { loaded: zvecDocs.length, total: docsToEmbed.length });
309271
}
310272

311-
// Phase 5: Update registry (track by parent doc ID for deduplication + change detection)
273+
// Phase 4: Update registry (track by parent doc ID for deduplication + change detection)
312274
for (const doc of docsToEmbed) {
313275
this.registry.add(library, doc.id, doc.contentHash);
314276
}
@@ -375,34 +337,17 @@ export class Context {
375337
const content = String(result.fields?.content ?? '');
376338
const metaStr = result.fields?.meta as string | undefined;
377339
const meta = safeParseMeta(metaStr);
378-
const chunkIndex = result.fields?.chunkIndex as number | undefined;
379-
const parentDocId = result.fields?.parentDocId as string | undefined;
380-
const headingPathRaw = result.fields?.headingPath as string | undefined;
381340

382-
const queryResult: QueryResult = {
341+
return {
383342
id: result.id,
384343
content,
385344
score: result.score,
386-
scoreMode: mode === 'hybrid' ? 'hybrid' : 'vector',
345+
scoreMode: mode === 'hybrid' ? 'hybrid' as const : 'vector' as const,
387346
meta,
388347
sourceFilePath: result.fields?.sourceFilePath as string | undefined,
389348
library,
390349
embedderKind: this._embedderInfo.kind,
391350
};
392-
393-
// Attach chunk metadata when present (non-negative chunkIndex)
394-
if (chunkIndex !== undefined && chunkIndex >= 0 && parentDocId) {
395-
queryResult.chunk = {
396-
chunkIndex,
397-
totalChunks: result.fields?.totalChunks as number ?? 1,
398-
parentDocId,
399-
headingPath: headingPathRaw
400-
? headingPathRaw.split(' > ').filter(Boolean)
401-
: [],
402-
};
403-
}
404-
405-
return queryResult;
406351
});
407352
})
408353
);
@@ -418,7 +363,6 @@ export class Context {
418363
id: r.id,
419364
content: r.content,
420365
score: r.score,
421-
headingPath: r.chunk?.headingPath?.join(' > '),
422366
}));
423367

424368
const reranked = await this.reranker!.rerank(text, candidates);
@@ -439,74 +383,6 @@ export class Context {
439383
return allResults.slice(0, topK);
440384
}
441385

442-
/**
443-
* Expand a chunk result — retrieve neighboring chunks from the same
444-
* parent document for context.
445-
*
446-
* When a query returns a chunked document fragment, the user often
447-
* needs to see the surrounding context (before/after chunks) to
448-
* understand the full meaning. This method fetches those neighbors.
449-
*
450-
* @param library The library the chunk belongs to.
451-
* @param parentDocId The parent document ID (from `chunk.parentDocId`).
452-
* @param options Optional range control:
453-
* - `before`: number of preceding chunks (default 1)
454-
* - `after`: number of following chunks (default 1)
455-
*
456-
* @returns Array of chunk QueryResults sorted by chunkIndex, or empty
457-
* array if the library or parent document is not found.
458-
*/
459-
async expandChunk(
460-
library: string,
461-
parentDocId: string,
462-
options?: { before?: number; after?: number },
463-
): Promise<QueryResult[]> {
464-
const store = this.storeManager.tryOpen(library);
465-
if (!store) return [];
466-
467-
const before = options?.before ?? 1;
468-
const after = options?.after ?? 1;
469-
470-
// Use a zero-vector search with a filter on parentDocId to retrieve
471-
// all chunks of the parent document. The filter narrows results to
472-
// the correct parent, and we sort by chunkIndex to find neighbors.
473-
const zeroVector = new Array(this.embedder.dimensions).fill(0);
474-
const allChunks = await store.search({
475-
vector: zeroVector,
476-
topK: 100, // generous limit — a single doc rarely has >100 chunks
477-
filter: `parentDocId = '${parentDocId}'`,
478-
});
479-
480-
if (allChunks.length === 0) return [];
481-
482-
// Sort by chunkIndex and parse into QueryResults
483-
const parsed = allChunks
484-
.map((result) => {
485-
const chunkIndex = result.fields?.chunkIndex as number ?? -1;
486-
return {
487-
id: result.id,
488-
content: String(result.fields?.content ?? ''),
489-
score: result.score,
490-
meta: safeParseMeta(result.fields?.meta as string | undefined),
491-
sourceFilePath: result.fields?.sourceFilePath as string | undefined,
492-
library,
493-
chunk: {
494-
chunkIndex,
495-
totalChunks: result.fields?.totalChunks as number ?? 1,
496-
parentDocId: result.fields?.parentDocId as string ?? parentDocId,
497-
headingPath: (result.fields?.headingPath as string ?? '')
498-
.split(' > ').filter(Boolean),
499-
},
500-
chunkIndex,
501-
};
502-
})
503-
.sort((a, b) => a.chunkIndex - b.chunkIndex);
504-
505-
// Find the target chunk index and return the window around it
506-
// If we don't know which chunk the user came from, return all chunks
507-
return parsed.slice(0, parsed.length);
508-
}
509-
510386
/**
511387
* Remove a document from a library's dedup registry.
512388
*

0 commit comments

Comments
 (0)