-
Notifications
You must be signed in to change notification settings - Fork 295
/
CohereRerank.ts
83 lines (68 loc) · 1.82 KB
/
CohereRerank.ts
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
import { CohereClient } from "cohere-ai";
import type { NodeWithScore } from "../../Node.js";
import { MetadataMode } from "../../Node.js";
import type { BaseNodePostprocessor } from "../types.js";
type CohereRerankOptions = {
topN?: number;
model?: string;
apiKey: string | null;
};
export class CohereRerank implements BaseNodePostprocessor {
topN: number = 2;
model: string = "rerank-english-v2.0";
apiKey: string | null = null;
private client: CohereClient | null = null;
/**
* Constructor for CohereRerank.
* @param topN Number of nodes to return.
*/
constructor({
topN = 2,
model = "rerank-english-v2.0",
apiKey = null,
}: CohereRerankOptions) {
if (apiKey === null) {
throw new Error("CohereRerank requires an API key");
}
this.topN = topN;
this.model = model;
this.apiKey = apiKey;
this.client = new CohereClient({
token: this.apiKey,
});
}
/**
* Reranks the nodes using the Cohere API.
* @param nodes Array of nodes with scores.
* @param query Query string.
*/
async postprocessNodes(
nodes: NodeWithScore[],
query?: string,
): Promise<NodeWithScore[]> {
if (this.client === null) {
throw new Error("CohereRerank client is null");
}
if (nodes.length === 0) {
return [];
}
if (query === undefined) {
throw new Error("CohereRerank requires a query");
}
const results = await this.client.rerank({
query,
model: this.model,
topN: this.topN,
documents: nodes.map((n) => n.node.getContent(MetadataMode.ALL)),
});
const newNodes: NodeWithScore[] = [];
for (const result of results.results) {
const node = nodes[result.index];
newNodes.push({
node: node.node,
score: result.relevanceScore,
});
}
return newNodes;
}
}