Spaces:
Running
Running
File size: 1,362 Bytes
e538a38 |
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 |
import { rerank } from "./rerankerService";
export async function rankSearchResults(
query: string,
searchResults: [title: string, content: string, url: string][],
preserveTopResults = false,
) {
const documents = searchResults.map(([title, snippet, url]) =>
`[${title}](${url} "${snippet.replaceAll('"', "'")}")`.toLocaleLowerCase(),
);
const results = await rerank(query.toLocaleLowerCase(), documents);
const scoredResults = results.map(({ index, relevance_score }) => ({
result: searchResults[index],
score: relevance_score,
}));
if (scoredResults.length === 0) {
return [];
}
const highestScore = Math.max(...scoredResults.map((r) => r.score));
const filteredResults = scoredResults.filter(
(r) => r.score >= highestScore / 10,
);
if (preserveTopResults) {
const [firstResult, ...nextResults] = filteredResults;
const nextTopResultsCount = 9;
const nextTopResults = nextResults
.slice(0, nextTopResultsCount)
.sort((a, b) => b.score - a.score);
const remainingResults = nextResults
.slice(nextTopResultsCount)
.sort((a, b) => b.score - a.score);
return [firstResult, ...nextTopResults, ...remainingResults].map(
({ result }) => result,
);
}
return filteredResults
.sort((a, b) => b.score - a.score)
.map(({ result }) => result);
}
|