Elffuss BraidHub

kikocis/continue public

main · 1.6 KiBRawPermalink
1import { z } from "zod";
2
3import { Chunk, LLMOptions } from "../../index.js";
4import OpenAI from "./OpenAI.js";
5
6/**used to check a valid response from voyage is received
7 * reference: https://docs.voyageai.com/reference/reranker-api
8 */
9const VoyageRerankSuccessResponseSchema = z.object({
10 data: z.array(
11 z.object({
12 index: z.number(),
13 relevance_score: z.number(),
14 document: z.string(),
15 }),
16 ),
17});
18
19class Voyage extends OpenAI {
20 static providerName = "voyage";
21 static defaultOptions: Partial<LLMOptions> | undefined = {
22 apiBase: "https://api.voyageai.com/v1/",
23 maxEmbeddingBatchSize: 128,
24 };
25
26 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
27 if (!query || chunks.length === 0) {
28 return [];
29 }
30 const url = new URL("rerank", this.apiBase);
31 const resp = await this.fetch(url, {
32 method: "POST",
33 headers: {
34 "Content-Type": "application/json",
35 Authorization: `Bearer ${this.apiKey}`,
36 },
37 body: JSON.stringify({
38 query,
39 documents: chunks.map((chunk) => chunk.content),
40 model: this.model ?? "rerank-2",
41 }),
42 });
43
44 if (resp.status !== 200) {
45 throw new Error(
46 `VoyageReranker API error ${resp.status}: ${await resp.text()}`,
47 );
48 }
49
50 const data = (await resp.json()) as {
51 data: Array<{ index: number; relevance_score: number }>;
52 };
53
54 const parsedData = VoyageRerankSuccessResponseSchema.parse(data);
55
56 const results = parsedData.data.sort((a, b) => a.index - b.index);
57 return results.map((result) => result.relevance_score);
58 }
59}
60
61export default Voyage;