Skip to content

Commit fb6dd73

Browse files
committed
refactor: update reranker
1 parent 629f436 commit fb6dd73

7 files changed

Lines changed: 266 additions & 47 deletions

File tree

‎README.md‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -208,14 +208,6 @@ await ctx.close();
208208
+------------------------------------------------------------------------+
209209
```
210210

211-
### Module Structure
212-
213-
- **Public API**: `Context`, `QueryOptions`, `QueryResult`, `Document`, `Loader`, `MarkdownLoader`, `JsonLoader`, `TextLoader`, `pathToId`
214-
- **Reranking**: `KeywordReranker`, `createReranker`, `Reranker`, `RerankCandidate`, `RerankResult`, `RerankOptions`
215-
- **Query Expansion**: `SynonymExpander`, `NoopExpander`, `QueryExpander`, `QueryExpansionOptions`
216-
- **Advanced API**: `Embedder`, `TransformersEmbedder`, `EmbedderManager`, `IZvecStore`, `ActualZvecStore`, `Store`
217-
218-
219211
## License
220212

221213
MIT

‎src/context.ts‎

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,7 @@ import {
55
ContextOptions,
66
QueryOptions,
77
QueryResult,
8-
Document,
98
LoadedDoc,
10-
LoadPhase,
11-
LoadProgress,
129
} from './types';
1310
import { Embedder } from './embedder';
1411

@@ -18,13 +15,12 @@ import { pathToId } from './utils/doc';
1815
import { Store } from './storage/store';
1916
import type { ZvecDoc } from './storage/zvec-store';
2017
import {
21-
createReranker,
2218
safeJsonParse,
2319
computeContentHash,
2420
loadSampleText,
2521
} from './utils';
2622
import { expand } from './expander';
27-
import type { Reranker, RerankCandidate } from './utils';
23+
import { createReranker, applyRerank } from './reranker';
2824

2925
// ---------------------------------------------------------------------------
3026
// Context class
@@ -35,7 +31,6 @@ export class Context {
3531
private readonly embedder: Embedder;
3632
readonly embedderInfo: EmbedderInfo;
3733
private readonly store: Store;
38-
private readonly reranker: Reranker | null;
3934

4035
private constructor(options: ContextOptions, embedder: Embedder, embedderInfo: EmbedderInfo) {
4136
this.options = {
@@ -46,7 +41,6 @@ export class Context {
4641
this.embedder = embedder;
4742
this.embedderInfo = embedderInfo;
4843
this.store = new Store(this.options.vectorsDir!, embedder, this.options);
49-
this.reranker = createReranker(this.options.rerankWeights);
5044
}
5145

5246
static async create(options: ContextOptions): Promise<Context> {
@@ -163,23 +157,9 @@ export class Context {
163157
};
164158
});
165159

166-
if (rerankEnabled && queryResults.length > topK) {
167-
const docs: RerankCandidate[] = queryResults.map((r) => ({
168-
id: r.id,
169-
content: r.content,
170-
score: r.score,
171-
}));
172-
173-
const reranked = await this.reranker!.rerank(text, docs);
174-
175-
const scoreMap = new Map(reranked.map((r) => [r.id, r.score]));
176-
for (const result of queryResults) {
177-
const newScore = scoreMap.get(result.id);
178-
if (newScore !== undefined) {
179-
result.score = newScore;
180-
result.scoreMode = 'reranked';
181-
}
182-
}
160+
if (rerankEnabled) {
161+
const reranker = createReranker(this.options.rerankWeights);
162+
await applyRerank(reranker, text, queryResults, topK);
183163
}
184164

185165
queryResults.sort((a, b) => b.score - a.score);

‎src/index.ts‎

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,2 @@
1-
// ---------------------------------------------------------------------------
2-
// Public API
3-
// ---------------------------------------------------------------------------
4-
51
export { Context } from './context';
6-
export * from './types';
7-
8-
// Reranker
9-
export { KeywordReranker, createReranker } from './utils/reranker';
10-
export type { RerankCandidate, RerankResult } from './utils/reranker';
11-
12-
// Query expansion
13-
export { expand } from './expander';
14-
15-
// Embedder
16-
export { Embedder } from './embedder';
2+
export * from './types';

‎src/reranker/index.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import type { Reranker, RerankCandidate, RerankResult, RerankOptions } from './types';
2+
import { KeywordReranker } from './keyword-reranker';
3+
import { applyRerank } from './rerank';
4+
5+
export type { Reranker, RerankCandidate, RerankResult, RerankOptions };
6+
export { applyRerank };
7+
8+
/**
9+
* Create a reranker with optional weight configuration.
10+
*/
11+
export function createReranker(options?: RerankOptions): Reranker {
12+
return new KeywordReranker(options);
13+
}

‎src/reranker/keyword-reranker.ts‎

Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
import type { Reranker, RerankCandidate, RerankResult, RerankOptions } from './types';
2+
3+
// ---------------------------------------------------------------------------
4+
// Defaults
5+
// ---------------------------------------------------------------------------
6+
7+
const DEFAULT_WEIGHTS = {
8+
phraseWeight: 3.0,
9+
phraseRepeatBonus: 0.5,
10+
termWeight: 1.0,
11+
termRepeatBonus: 0.2,
12+
substringWeight: 0.3,
13+
headingTermBonus: 2.0,
14+
headingPhraseBonus: 2.5,
15+
originalScoreCarry: 0.1,
16+
} as const;
17+
18+
// ---------------------------------------------------------------------------
19+
// KeywordReranker — lexical overlap scoring
20+
// ---------------------------------------------------------------------------
21+
22+
/**
23+
* Reranker that scores candidates by keyword / phrase overlap with the query.
24+
*
25+
* All scoring weights are configurable via constructor options.
26+
* Scores are normalised to [0, 1] via min-max scaling.
27+
*/
28+
export class KeywordReranker implements Reranker {
29+
private readonly weights: Record<string, number>;
30+
31+
constructor(options?: RerankOptions) {
32+
this.weights = {
33+
phraseWeight: options?.phraseWeight ?? DEFAULT_WEIGHTS.phraseWeight,
34+
phraseRepeatBonus: options?.phraseRepeatBonus ?? DEFAULT_WEIGHTS.phraseRepeatBonus,
35+
termWeight: options?.termWeight ?? DEFAULT_WEIGHTS.termWeight,
36+
termRepeatBonus: options?.termRepeatBonus ?? DEFAULT_WEIGHTS.termRepeatBonus,
37+
substringWeight: options?.substringWeight ?? DEFAULT_WEIGHTS.substringWeight,
38+
headingTermBonus: options?.headingTermBonus ?? DEFAULT_WEIGHTS.headingTermBonus,
39+
headingPhraseBonus: options?.headingPhraseBonus ?? DEFAULT_WEIGHTS.headingPhraseBonus,
40+
originalScoreCarry: options?.originalScoreCarry ?? DEFAULT_WEIGHTS.originalScoreCarry,
41+
};
42+
}
43+
44+
async rerank(query: string, candidates: RerankCandidate[]): Promise<RerankResult[]> {
45+
if (candidates.length === 0) return [];
46+
47+
const queryLower = query.toLowerCase();
48+
const queryTerms = tokenizeQuery(queryLower);
49+
const queryPhrase = queryLower.trim();
50+
const w = this.weights;
51+
52+
const scored = candidates.map((c) => {
53+
const contentLower = c.content.toLowerCase();
54+
let score = 0;
55+
56+
// 1. Exact phrase match — strongest signal
57+
if (contentLower.includes(queryPhrase)) {
58+
score += w.phraseWeight;
59+
const phraseCount = countOccurrences(contentLower, queryPhrase);
60+
score += (phraseCount - 1) * w.phraseRepeatBonus;
61+
}
62+
63+
// 2. Per-term matching
64+
for (const term of queryTerms) {
65+
if (contentLower.includes(term)) {
66+
if (isWordBoundary(contentLower, term)) {
67+
score += w.termWeight;
68+
const termCount = countTermMatches(contentLower, term);
69+
score += (termCount - 1) * w.termRepeatBonus;
70+
} else {
71+
score += w.substringWeight;
72+
}
73+
}
74+
}
75+
76+
// 3. Heading path bonus
77+
if (c.headingPath) {
78+
const headingLower = c.headingPath.toLowerCase();
79+
for (const term of queryTerms) {
80+
if (headingLower.includes(term)) {
81+
score += w.headingTermBonus;
82+
}
83+
}
84+
if (queryPhrase.length > 2 && headingLower.includes(queryPhrase)) {
85+
score += w.headingPhraseBonus;
86+
}
87+
}
88+
89+
// 4. Carry over a fraction of the original vector score
90+
score += c.score * w.originalScoreCarry;
91+
92+
return { id: c.id, score };
93+
});
94+
95+
// Min-max normalise to [0, 1]
96+
const scores = scored.map((s) => s.score);
97+
const min = Math.min(...scores);
98+
const max = Math.max(...scores);
99+
const range = max - min || 1;
100+
101+
return scored.map((s) => ({
102+
id: s.id,
103+
score: (s.score - min) / range,
104+
}));
105+
}
106+
}
107+
108+
// ---------------------------------------------------------------------------
109+
// Helpers
110+
// ---------------------------------------------------------------------------
111+
112+
/** Split a query into meaningful tokens. */
113+
function tokenizeQuery(query: string): string[] {
114+
const raw = query
115+
.split(/[\s,,。.!!??、::;;]+/)
116+
.filter(Boolean);
117+
118+
const tokens: string[] = [];
119+
for (const r of raw) {
120+
tokens.push(r);
121+
if (/[一-鿿]{3,}/.test(r)) {
122+
for (let i = 0; i + 2 <= r.length; i++) {
123+
tokens.push(r.slice(i, i + 2));
124+
}
125+
}
126+
}
127+
return [...new Set(tokens)];
128+
}
129+
130+
/** Count non-overlapping occurrences of a substring. */
131+
function countOccurrences(text: string, sub: string): number {
132+
let count = 0;
133+
let pos = 0;
134+
while ((pos = text.indexOf(sub, pos)) !== -1) {
135+
count++;
136+
pos += sub.length;
137+
}
138+
return count;
139+
}
140+
141+
/** Count whole-word matches of a term. */
142+
function countTermMatches(text: string, term: string): number {
143+
let count = 0;
144+
let pos = 0;
145+
while ((pos = text.indexOf(term, pos)) !== -1) {
146+
if (isWordBoundary(text, term, pos)) {
147+
count++;
148+
}
149+
pos += term.length;
150+
}
151+
return count;
152+
}
153+
154+
/** Check if a substring occurrence is at a word boundary. */
155+
function isWordBoundary(
156+
text: string,
157+
term: string,
158+
pos?: number,
159+
): boolean {
160+
const idx = pos ?? text.indexOf(term);
161+
if (idx === -1) return false;
162+
const before = idx === 0 || /[\s\n.,;:!?,。!?、:;"'((【《\-_]/.test(text[idx - 1]);
163+
const afterIdx = idx + term.length;
164+
const after = afterIdx >= text.length || /[\s\n.,;:!?,。!?、:;"'))】》\-_]/.test(text[afterIdx]);
165+
return before && after;
166+
}

‎src/reranker/rerank.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import type { Reranker, RerankCandidate } from './types';
2+
import type { QueryResult } from '../types';
3+
4+
/**
5+
* Apply reranking to query results.
6+
*
7+
* @param reranker - The reranker instance
8+
* @param query - The original query text
9+
* @param results - Query results to rerank
10+
* @param topK - Original topK (only rerank if results > topK)
11+
* @returns The results with scores updated if reranking was applied
12+
*/
13+
export async function applyRerank(
14+
reranker: Reranker,
15+
query: string,
16+
results: QueryResult[],
17+
topK: number,
18+
): Promise<QueryResult[]> {
19+
if (results.length <= topK) return results;
20+
21+
const candidates: RerankCandidate[] = results.map((r) => ({
22+
id: r.id,
23+
content: r.content,
24+
score: r.score,
25+
}));
26+
27+
const reranked = await reranker.rerank(query, candidates);
28+
29+
const scoreMap = new Map(reranked.map((r) => [r.id, r.score]));
30+
for (const result of results) {
31+
const newScore = scoreMap.get(result.id);
32+
if (newScore !== undefined) {
33+
result.score = newScore;
34+
result.scoreMode = 'reranked';
35+
}
36+
}
37+
38+
return results;
39+
}

‎src/reranker/types.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Reranker — second-stage precision scoring for search results.
3+
*/
4+
5+
// ---------------------------------------------------------------------------
6+
// Types
7+
// ---------------------------------------------------------------------------
8+
9+
/** A candidate document for reranking. */
10+
export interface RerankCandidate {
11+
id: string;
12+
content: string;
13+
/** Original score from the coarse search stage. */
14+
score: number;
15+
/** Heading path as a string (e.g. "Line Chart > Tooltip"). */
16+
headingPath?: string;
17+
}
18+
19+
/** A reranked result. */
20+
export interface RerankResult {
21+
id: string;
22+
/** Final score after reranking (higher is better). */
23+
score: number;
24+
}
25+
26+
/** Reranker type */
27+
export type Reranker = {
28+
rerank(query: string, candidates: RerankCandidate[]): Promise<RerankResult[]>;
29+
};
30+
31+
/** Configuration for reranking. */
32+
export interface RerankOptions {
33+
rerankFactor?: number;
34+
minCandidates?: number;
35+
phraseWeight?: number;
36+
phraseRepeatBonus?: number;
37+
termWeight?: number;
38+
termRepeatBonus?: number;
39+
substringWeight?: number;
40+
headingTermBonus?: number;
41+
headingPhraseBonus?: number;
42+
originalScoreCarry?: number;
43+
}

0 commit comments

Comments
 (0)