-
Notifications
You must be signed in to change notification settings - Fork 227
feat(tools): add dependency-free BM25 ranker #1207
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
Open
edelauna
wants to merge
1
commit into
main
Choose a base branch
from
issue/575
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+182
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| import { Ranker, ToolDoc } from "./types" | ||
|
|
||
| type IndexedDocument = { | ||
| item: ToolDoc | ||
| termFrequencies: Map<string, number> | ||
| length: number | ||
| index: number | ||
| } | ||
|
|
||
| export class Bm25Ranker implements Ranker { | ||
| private readonly k1 = 1.5 | ||
| private readonly b = 0.75 | ||
| private indexedItems: ToolDoc[] | undefined | ||
| private documents: IndexedDocument[] = [] | ||
| private documentFrequency = new Map<string, number>() | ||
| private averageDocumentLength = 0 | ||
|
|
||
| rank(query: string, items: ToolDoc[], k: number): ToolDoc[] { | ||
| const queryTerms = tokenize(query) | ||
|
|
||
| if (queryTerms.length === 0 || items.length === 0 || k <= 0) { | ||
| return [] | ||
| } | ||
|
|
||
| this.ensureIndex(items) | ||
|
|
||
| const scores = this.documents | ||
| .map((document) => ({ | ||
| document, | ||
| score: this.score(document, new Set(queryTerms)), | ||
| })) | ||
| .filter(({ score }) => score > 0) | ||
|
|
||
| scores.sort((left, right) => right.score - left.score || left.document.index - right.document.index) | ||
|
|
||
| return scores.slice(0, k).map(({ document }) => document.item) | ||
| } | ||
|
|
||
| private ensureIndex(items: ToolDoc[]): void { | ||
| if (this.indexedItems === items) { | ||
| return | ||
| } | ||
|
|
||
| this.indexedItems = items | ||
| this.documentFrequency = new Map<string, number>() | ||
| this.documents = items.map((item, index) => { | ||
| const termFrequencies = countTerms(item) | ||
|
|
||
| for (const term of termFrequencies.keys()) { | ||
| this.documentFrequency.set(term, (this.documentFrequency.get(term) ?? 0) + 1) | ||
| } | ||
|
|
||
| return { | ||
| item, | ||
| termFrequencies, | ||
| length: Array.from(termFrequencies.values()).reduce((total, count) => total + count, 0), | ||
| index, | ||
| } | ||
| }) | ||
| this.averageDocumentLength = | ||
| this.documents.reduce((total, document) => total + document.length, 0) / this.documents.length | ||
| } | ||
|
|
||
| private score(document: IndexedDocument, queryTerms: Set<string>): number { | ||
| let score = 0 | ||
| const documentCount = this.documents.length | ||
|
|
||
| for (const term of queryTerms) { | ||
| const termFrequency = document.termFrequencies.get(term) | ||
|
|
||
| if (!termFrequency) { | ||
| continue | ||
| } | ||
|
|
||
| const documentFrequency = this.documentFrequency.get(term) ?? 0 | ||
| const inverseDocumentFrequency = Math.log( | ||
| 1 + (documentCount - documentFrequency + 0.5) / (documentFrequency + 0.5), | ||
| ) | ||
| const normalization = this.k1 * (1 - this.b + this.b * (document.length / this.averageDocumentLength)) | ||
|
|
||
| score += inverseDocumentFrequency * ((termFrequency * (this.k1 + 1)) / (termFrequency + normalization)) | ||
| } | ||
|
|
||
| return score | ||
| } | ||
| } | ||
|
|
||
| function tokenize(value: string): string[] { | ||
| return value.toLowerCase().split(/\W+/).filter(Boolean) | ||
| } | ||
|
|
||
| function countTerms(item: ToolDoc): Map<string, number> { | ||
| const frequencies = new Map<string, number>() | ||
| const text = `${item.serverName} ${item.toolName} ${item.description}` | ||
|
|
||
| for (const term of tokenize(text)) { | ||
| frequencies.set(term, (frequencies.get(term) ?? 0) + 1) | ||
| } | ||
|
|
||
| return frequencies | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| import { describe, expect, it } from "vitest" | ||
| import { Bm25Ranker } from "../Bm25Ranker" | ||
| import { ToolDoc } from "../types" | ||
|
|
||
| const tool = (serverName: string, toolName: string, description: string): ToolDoc => ({ | ||
| serverName, | ||
| toolName, | ||
| description, | ||
| }) | ||
|
|
||
| describe("Bm25Ranker", () => { | ||
| it("ranks matching MCP tools by BM25 relevance", () => { | ||
| const items = [ | ||
| tool("slack", "postMessage", "Send a Slack message"), | ||
| tool("jira", "createIssue", "Send messages and create Jira issues"), | ||
| tool("postgres", "query", "Send data and query a Postgres database"), | ||
| ] | ||
|
|
||
| expect(new Bm25Ranker().rank("send slack message", items, 3)).toEqual([items[0], items[1], items[2]]) | ||
| }) | ||
|
|
||
| it("returns an empty result for empty queries, empty items, and no matches", () => { | ||
| const ranker = new Bm25Ranker() | ||
| const items = [tool("slack", "postMessage", "Send a message")] | ||
|
|
||
| expect(ranker.rank(" ", items, 10)).toEqual([]) | ||
| expect(ranker.rank("message", [], 10)).toEqual([]) | ||
| expect(ranker.rank("unrelated", items, 10)).toEqual([]) | ||
| }) | ||
|
|
||
| it("truncates results to the requested top-k", () => { | ||
| const items = [ | ||
| tool("one", "search", "Search records"), | ||
| tool("two", "search", "Search records"), | ||
| tool("three", "search", "Search records"), | ||
| ] | ||
|
|
||
| expect(new Bm25Ranker().rank("search", items, 2)).toEqual(items.slice(0, 2)) | ||
| expect(new Bm25Ranker().rank("search", items, 0)).toEqual([]) | ||
| }) | ||
|
|
||
| it("preserves input order for equal scores", () => { | ||
| const items = [tool("first", "lookup", "Find a record"), tool("second", "lookup", "Find a record")] | ||
|
|
||
| expect(new Bm25Ranker().rank("record", items, 10)).toEqual(items) | ||
| }) | ||
|
|
||
| it("tokenizes case-insensitively around punctuation", () => { | ||
| const matching = tool("Slack-Server", "POST.Message", "Send a message") | ||
| const nonMatching = tool("calendar", "createEvent", "Create a calendar event") | ||
|
|
||
| expect(new Bm25Ranker().rank("SLACK post message", [nonMatching, matching], 10)).toEqual([matching]) | ||
| }) | ||
|
|
||
| it("handles tools with empty descriptions", () => { | ||
| const item = tool("GitHub", "listRepos", "") | ||
|
|
||
| expect(new Bm25Ranker().rank("github repos", [item], 10)).toEqual([item]) | ||
| }) | ||
|
|
||
| it("rebuilds only when the items array reference changes", () => { | ||
| const items = [tool("slack", "send", "Send a message")] | ||
| const ranker = new Bm25Ranker() | ||
|
|
||
| ranker.rank("send", items, 10) | ||
| items.push(tool("jira", "create", "Create an issue")) | ||
| expect(ranker.rank("issue", items, 10)).toEqual([]) | ||
|
|
||
| const newItems = items.slice() | ||
| expect(ranker.rank("issue", newItems, 10)).toEqual([newItems[1]]) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| export type ToolDoc = { | ||
| serverName: string | ||
| toolName: string | ||
| description: string | ||
| } | ||
|
|
||
| export interface Ranker { | ||
| rank(query: string, items: ToolDoc[], k: number): ToolDoc[] | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: Zoo-Code-Org/Zoo-Code
Length of output: 200
🏁 Script executed:
Repository: Zoo-Code-Org/Zoo-Code
Length of output: 6696
🏁 Script executed:
Repository: Zoo-Code-Org/Zoo-Code
Length of output: 2736
Split underscore-separated tool names into terms.
The ranked content uses the same
tokenize()helper, but\Wtreats_as part of a word. A tool namedcreate_issueindexes undercreate_issue, while the querycreate issueonly producescreateandissue, so it cannot match that name. Include_in the separator expression and add a regression test for an underscore-separated tool name.Proposed fix
function tokenize(value: string): string[] { - return value.toLowerCase().split(/\W+/).filter(Boolean) + return value.toLowerCase().split(/[\W_]+/).filter(Boolean) }📝 Committable suggestion
🤖 Prompt for AI Agents