Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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 | 74x 13x 13x 78x 78x 78x 241x 78x 78x 13x 13x 13x 13x 78x 78x 78x 241x 78x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 45x 45x 13x 29x 13x 13x 45x 45x 45x 45x 42x 13x 13x 38x 108x 38x 38x 38x 6x 13x | /**
* Local BM25 + TF-IDF hybrid keyword search for tool discovery.
*
* Provides offline tool search as a fallback when the semantic search API
* is unavailable, or when explicitly requested via `search: "local"`.
*
* Algorithm:
* - BM25 scoring via Orama library
* - TF-IDF cosine similarity via custom TfidfIndex
* - Hybrid fusion: `alpha * bm25 + (1 - alpha) * tfidf`
* - Default alpha = 0.2 (20% BM25, 80% TF-IDF)
*/
import * as orama from '@orama/orama';
import { DEFAULT_HYBRID_ALPHA } from './consts';
import type { BaseTool } from './tool';
import { TfidfIndex } from './utils/tfidf-index';
/**
* Result from local tool search
*/
interface ToolSearchResult {
name: string;
description: string;
score: number;
}
type OramaDb = ReturnType<typeof orama.create>;
/**
* Clamp value to [0, 1]
*/
function clamp01(x: number): number {
return x < 0 ? 0 : x > 1 ? 1 : x;
}
/**
* Initialize TF-IDF index for tool search
*/
function initializeTfidfIndex(tools: BaseTool[]): TfidfIndex {
const index = new TfidfIndex();
const corpus = tools.map((tool) => {
const parts = tool.name.split('_');
const integration = parts[0];
const actionTypes = ['create', 'update', 'delete', 'get', 'list', 'search'];
const actions = parts.filter((p) => actionTypes.includes(p));
const text = [
`${tool.name} ${tool.name} ${tool.name}`, // boost name
`${integration} ${actions.join(' ')}`,
tool.description,
parts.join(' '),
].join(' ');
return { id: tool.name, text };
});
index.build(corpus);
return index;
}
/**
* Initialize Orama database with BM25 algorithm for tool search
* @see https://docs.orama.com/open-source/usage/create
* @see https://docs.orama.com/open-source/usage/search/bm25-algorithm/
*/
async function initializeOramaDb(tools: BaseTool[]): Promise<OramaDb> {
const oramaDb = orama.create({
schema: {
name: 'string' as const,
description: 'string' as const,
integration: 'string' as const,
tags: 'string[]' as const,
},
components: {
tokenizer: {
stemming: true,
},
},
});
for (const tool of tools) {
const parts = tool.name.split('_');
const integration = parts[0];
const actionTypes = ['create', 'update', 'delete', 'get', 'list', 'search'];
const actions = parts.filter((p) => actionTypes.includes(p));
await orama.insert(oramaDb, {
name: tool.name,
description: tool.description,
integration: integration,
tags: [...parts, ...actions],
});
}
return oramaDb;
}
/**
* Hybrid BM25 + TF-IDF tool search index.
*
* Provides local tool discovery without API calls.
* Used as a fallback when semantic search is unavailable.
*/
export class ToolIndex {
private tools: BaseTool[];
private hybridAlpha: number;
private oramaDbPromise: Promise<OramaDb>;
private tfidfIndex: TfidfIndex;
/**
* Initialize tool index with hybrid search
*
* @param tools - List of tools to index
* @param hybridAlpha - Weight for BM25 in hybrid search (0-1). Default 0.2.
*/
constructor(tools: BaseTool[], hybridAlpha?: number) {
this.tools = tools;
const alpha = hybridAlpha ?? DEFAULT_HYBRID_ALPHA;
this.hybridAlpha = Math.max(0, Math.min(1, alpha));
this.oramaDbPromise = initializeOramaDb(tools);
this.tfidfIndex = initializeTfidfIndex(tools);
}
/**
* Search for relevant tools using hybrid BM25 + TF-IDF
*
* @param query - Natural language query
* @param limit - Maximum number of results (default 5)
* @param minScore - Minimum relevance score 0-1 (default 0.0)
* @returns List of search results sorted by relevance
*/
async search(query: string, limit = 5, minScore = 0.0): Promise<ToolSearchResult[]> {
Iif (this.tools.length === 0) {
return [];
}
const fetchLimit = Math.max(50, limit);
const oramaDb = await this.oramaDbPromise;
const [bm25Results, tfidfResults] = await Promise.all([
orama.search(oramaDb, {
term: query,
limit: Math.max(50, limit),
} as Parameters<typeof orama.search>[1]),
Promise.resolve(this.tfidfIndex.search(query, fetchLimit)),
]);
// Build score map for fusion
const scoreMap = new Map<string, { bm25?: number; tfidf?: number }>();
for (const hit of bm25Results.hits) {
const doc = hit.document as { name: string };
scoreMap.set(doc.name, {
...scoreMap.get(doc.name),
bm25: clamp01(hit.score),
});
}
for (const r of tfidfResults) {
scoreMap.set(r.id, {
...scoreMap.get(r.id),
tfidf: clamp01(r.score),
});
}
// Fuse scores: hybrid_score = alpha * bm25 + (1 - alpha) * tfidf
const fused: Array<{ name: string; score: number }> = [];
for (const [name, scores] of scoreMap) {
const bm25 = scores.bm25 ?? 0;
const tfidf = scores.tfidf ?? 0;
const score = this.hybridAlpha * bm25 + (1 - this.hybridAlpha) * tfidf;
fused.push({ name, score });
}
fused.sort((a, b) => b.score - a.score);
const results: ToolSearchResult[] = [];
for (const r of fused) {
Iif (r.score < minScore) {
continue;
}
const tool = this.tools.find((t) => t.name === r.name);
Iif (!tool) {
continue;
}
results.push({
name: tool.name,
description: tool.description,
score: r.score,
});
if (results.length >= limit) {
break;
}
}
return results;
}
}
|