Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(community): Incorporate BM25 score in the results #7236

Merged
merged 3 commits into from
Nov 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion libs/langchain-community/src/retrievers/bm25.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { BM25 } from "../utils/@furkantoprak/bm25/BM25.js";
export type BM25RetrieverOptions = {
docs: Document[];
k: number;
includeScore?: boolean;
} & BaseRetrieverInput;

/**
Expand All @@ -14,6 +15,8 @@ export type BM25RetrieverOptions = {
* The k parameter determines the number of documents to return for each query.
*/
export class BM25Retriever extends BaseRetriever {
includeScore = false;

static lc_name() {
return "BM25Retriever";
}
Expand All @@ -35,6 +38,7 @@ export class BM25Retriever extends BaseRetriever {
super(options);
this.docs = options.docs;
this.k = options.k;
this.includeScore = options.includeScore ?? this.includeScore;
}

private preprocessFunc(text: string): string[] {
Expand All @@ -53,6 +57,19 @@ export class BM25Retriever extends BaseRetriever {

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

return scoredDocs.slice(0, this.k).map((item) => item.document);
return scoredDocs.slice(0, this.k).map((item) => {
if (this.includeScore) {
return new Document({
...(item.document.id && { id: item.document.id }),
pageContent: item.document.pageContent,
metadata: {
bm25Score: item.score,
...item.document.metadata,
},
});
} else {
return item.document;
}
});
}
}
Loading