diff --git a/core/config/load.ts b/core/config/load.ts index d4d0c0b5f..0df921486 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -29,6 +29,7 @@ import { slashCommandFromDescription, slashFromCustomCommand, } from "../commands/index.js"; +import { AllRerankers } from "../context/allRerankers"; import MCPConnectionSingleton from "../context/mcp"; import CodebaseContextProvider from "../context/providers/CodebaseContextProvider"; import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider"; @@ -36,13 +37,12 @@ import CustomContextProviderClass from "../context/providers/CustomContextProvid import FileContextProvider from "../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../context/providers/index"; import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider"; -import { AllRerankers } from "../context/rerankers/index"; -import { LLMReranker } from "../context/rerankers/llm"; import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders"; import { BaseLLM } from "../llm"; import { llmFromDescription } from "../llm/llms"; import CustomLLMClass from "../llm/llms/CustomLLM"; import FreeTrial from "../llm/llms/FreeTrial"; +import { LLMReranker } from "../llm/llms/llm"; import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider"; import { allTools } from "../tools"; import { copyOf } from "../util"; diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 1ea5d7d1a..e8d887303 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -5,7 +5,6 @@ import { IdeSettings, SerializedContinueConfig, } from "../../"; -import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker.js"; import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { controlPlaneEnv } from "../../control-plane/env.js"; @@ -114,7 +113,7 @@ async function injectControlPlaneProxyInfo( } if (config.reranker?.providerName === "continue-proxy") { - (config.reranker as ContinueProxyReranker).controlPlaneProxyInfo = info; + (config.reranker as ContinueProxy).controlPlaneProxyInfo = info; } return config; diff --git a/core/context/allRerankers.ts b/core/context/allRerankers.ts new file mode 100644 index 000000000..56aa13474 --- /dev/null +++ b/core/context/allRerankers.ts @@ -0,0 +1,17 @@ +import Bedrock from "../llm/llms/Bedrock"; +import Cohere from "../llm/llms/Cohere"; +import FreeTrial from "../llm/llms/FreeTrial"; +import HuggingFaceTEI from "../llm/llms/HuggingFaceTEI"; +import { LLMReranker } from "../llm/llms/llm"; +import ContinueProxy from "../llm/llms/stubs/ContinueProxy"; +import Voyage from "../llm/llms/Voyage"; + +export const AllRerankers: { [key: string]: any } = { + cohere: Cohere, + bedrock: Bedrock, + llm: LLMReranker, + voyage: Voyage, + "free-trial": FreeTrial, + "huggingface-tei": HuggingFaceTEI, + "continue-proxy": ContinueProxy, +}; diff --git a/core/context/rerankers/ContinueProxyReranker.ts b/core/context/rerankers/ContinueProxyReranker.ts deleted file mode 100644 index a504eb31a..000000000 --- a/core/context/rerankers/ContinueProxyReranker.ts +++ /dev/null @@ -1,38 +0,0 @@ -import fetch from "node-fetch"; - -import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; -import { Chunk } from "../../index.js"; -import { BaseLLM } from "../../llm/index.js"; - -export class ContinueProxyReranker extends BaseLLM { - static providerName = "continue-proxy"; - - private _controlPlaneProxyInfo?: ControlPlaneProxyInfo; - - set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { - this.apiKey = value.workOsAccessToken!; - this._controlPlaneProxyInfo = value; - } - - async rerank(query: string, chunks: Chunk[]): Promise { - const url = new URL( - "openai/v1/rerank", - this._controlPlaneProxyInfo?.controlPlaneProxyUrl, - ); - const resp = await fetch(url, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${this.apiKey}`, - }, - body: JSON.stringify({ - query, - documents: chunks.map((chunk) => chunk.content), - model: this.model, - }), - }); - const data: any = await resp.json(); - const results = data.data.sort((a: any, b: any) => a.index - b.index); - return results.map((result: any) => result.relevance_score); - } -} diff --git a/core/context/rerankers/bedrock.ts b/core/context/rerankers/bedrock.ts deleted file mode 100644 index 2186df146..000000000 --- a/core/context/rerankers/bedrock.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { - BedrockRuntimeClient, - InvokeModelCommand, -} from "@aws-sdk/client-bedrock-runtime"; -import { fromIni } from "@aws-sdk/credential-providers"; - -import { Chunk, LLMOptions } from "../../index.js"; -import { BaseLLM } from "../../llm/index.js"; - -export class BedrockReranker extends BaseLLM { - static providerName = "bedrock"; - - static defaultOptions: Partial | undefined = { - region: "us-east-1", - model: "amazon.rerank-v1:0", - profile: "bedrock", - }; - - private supportedModels = ["amazon.rerank-v1:0", "cohere.rerank-v3-5:0"]; - - constructor(options: LLMOptions) { - super(options); - if (options.model && !this.supportedModels.includes(options.model)) { - throw new Error( - `Unsupported model: ${options.model}. Supported models are: ${this.supportedModels.join(", ")}`, - ); - } - } - - async rerank(query: string, chunks: Chunk[]): Promise { - if (!query || !chunks.length) { - throw new Error("Query and chunks must not be empty"); - } - - try { - const credentials = await this._getCredentials(); - const client = new BedrockRuntimeClient({ - region: this.region, - credentials, - }); - - // Base payload for both models - const payload: any = { - query: query, - documents: chunks.map((chunk) => chunk.content), - top_n: chunks.length, - }; - - // Add api_version for Cohere model - if (this.model.startsWith("cohere.rerank")) { - payload.api_version = 2; - } - - const input = { - body: JSON.stringify(payload), - modelId: this.model, - accept: "*/*", - contentType: "application/json", - }; - - const command = new InvokeModelCommand(input); - const response = await client.send(command); - - if (!response.body) { - throw new Error("Empty response received from Bedrock"); - } - - const responseBody = JSON.parse(new TextDecoder().decode(response.body)); - - // Sort results by index to maintain original order - return responseBody.results - .sort((a: any, b: any) => a.index - b.index) - .map((result: any) => result.relevance_score); - } catch (error) { - console.error("Error in BedrockReranker.rerank:", error); - throw error; - } - } - - private async _getCredentials() { - try { - const credentials = await fromIni({ - profile: this.profile, - ignoreCache: true, - })(); - return credentials; - } catch (e) { - console.warn( - `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, - ); - return await fromIni()(); - } - } -} diff --git a/core/context/rerankers/cohere.ts b/core/context/rerankers/cohere.ts deleted file mode 100644 index 544166b8c..000000000 --- a/core/context/rerankers/cohere.ts +++ /dev/null @@ -1,41 +0,0 @@ -import fetch from "node-fetch"; - -import { Chunk } from "../../index.js"; -import { BaseLLM } from "../../llm/index.js"; - -export class CohereReranker extends BaseLLM { - static providerName = "cohere"; - - static defaultOptions = { - apiBase: "https://api.cohere.ai/v1/", - model: "rerank-english-v3.0", - }; - - async rerank(query: string, chunks: Chunk[]): Promise { - let apiBase = this.apiBase ?? CohereReranker.defaultOptions.apiBase; - if (!apiBase.endsWith("/")) { - apiBase += "/"; - } - - const resp = await fetch(new URL("rerank", apiBase), { - method: "POST", - headers: { - Authorization: `Bearer ${this.apiKey}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - model: this.model ?? CohereReranker.defaultOptions.model, - query, - documents: chunks.map((chunk) => chunk.content), - }), - }); - - if (!resp.ok) { - throw new Error(await resp.text()); - } - - const data = (await resp.json()) as any; - const results = data.results.sort((a: any, b: any) => a.index - b.index); - return results.map((result: any) => result.relevance_score); - } -} diff --git a/core/context/rerankers/freeTrial.ts b/core/context/rerankers/freeTrial.ts deleted file mode 100644 index 1cfc93b0b..000000000 --- a/core/context/rerankers/freeTrial.ts +++ /dev/null @@ -1,35 +0,0 @@ -import fetch from "node-fetch"; - -import { getHeaders } from "../../continueServer/stubs/headers.js"; -import { TRIAL_PROXY_URL } from "../../control-plane/client.js"; -import { Chunk } from "../../index.js"; -import { BaseLLM } from "../../llm/index.js"; - -export class FreeTrialReranker extends BaseLLM { - static providerName = "free-trial"; - - async rerank(query: string, chunks: Chunk[]): Promise { - if (chunks.length === 0) { - return []; - } - const resp = await fetch(new URL("rerank", TRIAL_PROXY_URL), { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(await getHeaders()), - }, - body: JSON.stringify({ - query, - documents: chunks.map((chunk) => chunk.content), - }), - }); - - if (!resp.ok) { - throw new Error(await resp.text()); - } - - const data = (await resp.json()) as any; - const results = data.sort((a: any, b: any) => a.index - b.index); - return results.map((result: any) => result.relevance_score); - } -} diff --git a/core/context/rerankers/index.ts b/core/context/rerankers/index.ts deleted file mode 100644 index f4a89d96d..000000000 --- a/core/context/rerankers/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { BedrockReranker } from "./bedrock.js"; -import { CohereReranker } from "./cohere.js"; -import { ContinueProxyReranker } from "./ContinueProxyReranker.js"; -import { FreeTrialReranker } from "./freeTrial.js"; -import { LLMReranker } from "./llm.js"; -import { HuggingFaceTEIReranker } from "./tei.js"; -import { VoyageReranker } from "./voyage.js"; - -export const AllRerankers: { [key: string]: any } = { - cohere: CohereReranker, - bedrock: BedrockReranker, - llm: LLMReranker, - voyage: VoyageReranker, - "free-trial": FreeTrialReranker, - "huggingface-tei": HuggingFaceTEIReranker, - "continue-proxy": ContinueProxyReranker, -}; diff --git a/core/context/rerankers/tei.ts b/core/context/rerankers/tei.ts deleted file mode 100644 index a0891271d..000000000 --- a/core/context/rerankers/tei.ts +++ /dev/null @@ -1,56 +0,0 @@ -import fetch from "node-fetch"; - -import { Chunk, LLMOptions } from "../../index.js"; -import { BaseLLM } from "../../llm/index.js"; - -export class HuggingFaceTEIReranker extends BaseLLM { - static providerName = "huggingface-tei"; - - static defaultOptions: Partial | undefined = { - apiBase: "http://localhost:8080", - // truncate: true, - // truncation_direction: "Right", - }; - - // constructor( - // private readonly params: { - // apiBase?: string; - // TODO support truncate and truncate_direction - // truncate?: boolean; - // truncation_direction?: string; - // apiKey?: string; - // }, - // ) {} - - async rerank(query: string, chunks: Chunk[]): Promise { - const headers: Record = { - "Content-Type": "application/json", - }; - - if (this.apiKey) { - headers["Authorization"] = `Bearer ${this.apiKey}`; - } - - const resp = await fetch(new URL("rerank", this.apiBase), { - method: "POST", - headers, - body: JSON.stringify({ - query: query, - return_text: false, - raw_scores: false, - texts: chunks.map((chunk) => chunk.content), - truncation_direction: "Right", - truncate: true, - }), - }); - - if (!resp.ok) { - throw new Error(await resp.text()); - } - - const data = (await resp.json()) as any; - // Resort into original order and extract scores - const results = data.sort((a: any, b: any) => a.index - b.index); - return results.map((result: any) => result.score); - } -} diff --git a/core/context/rerankers/voyage.ts b/core/context/rerankers/voyage.ts deleted file mode 100644 index 16be7b7dc..000000000 --- a/core/context/rerankers/voyage.ts +++ /dev/null @@ -1,43 +0,0 @@ -import fetch from "node-fetch"; - -import { Chunk, LLMOptions } from "../../index.js"; -import { BaseLLM } from "../../llm/index.js"; - -export class VoyageReranker extends BaseLLM { - static providerName: string = "voyage"; - - static defaultOptions: Partial | undefined = { - apiBase: "https://api.voyageai.com/v1/", - }; - - async rerank(query: string, chunks: Chunk[]): Promise { - if (!query || chunks.length === 0) { - return []; - } - const url = new URL("rerank", this.apiBase); - const resp = await fetch(url, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${this.apiKey}`, - }, - body: JSON.stringify({ - query, - documents: chunks.map((chunk) => chunk.content), - model: this.model ?? "rerank-2", - }), - }); - - if (resp.status !== 200) { - throw new Error( - `VoyageReranker API error ${resp.status}: ${await resp.text()}`, - ); - } - - const data = (await resp.json()) as { - data: Array<{ index: number; relevance_score: number }>; - }; - const results = data.data.sort((a, b) => a.index - b.index); - return results.map((result) => result.relevance_score); - } -} diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 48f5713e3..17d2911b8 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -7,6 +7,7 @@ import { fromIni } from "@aws-sdk/credential-providers"; import { ChatMessage, + Chunk, CompletionOptions, LLMOptions, MessageContent, @@ -255,6 +256,56 @@ class Bedrock extends BaseLLM { } return modelConfigs[modelPrefix]; } + + async rerank(query: string, chunks: Chunk[]): Promise { + if (!query || !chunks.length) { + throw new Error("Query and chunks must not be empty"); + } + + try { + const credentials = await this._getCredentials(); + const client = new BedrockRuntimeClient({ + region: this.region, + credentials, + }); + + // Base payload for both models + const payload: any = { + query: query, + documents: chunks.map((chunk) => chunk.content), + top_n: chunks.length, + }; + + // Add api_version for Cohere model + if (this.model.startsWith("cohere.rerank")) { + payload.api_version = 2; + } + + const input = { + body: JSON.stringify(payload), + modelId: this.model, + accept: "*/*", + contentType: "application/json", + }; + + const command = new InvokeModelCommand(input); + const response = await client.send(command); + + if (!response.body) { + throw new Error("Empty response received from Bedrock"); + } + + const responseBody = JSON.parse(new TextDecoder().decode(response.body)); + + // Sort results by index to maintain original order + return responseBody.results + .sort((a: any, b: any) => a.index - b.index) + .map((result: any) => result.relevance_score); + } catch (error) { + console.error("Error in BedrockReranker.rerank:", error); + throw error; + } + } } export default Bedrock; diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index f62c91ead..1c895c2fe 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -1,4 +1,9 @@ -import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { + ChatMessage, + Chunk, + CompletionOptions, + LLMOptions, +} from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamJSON } from "../stream.js"; @@ -110,6 +115,29 @@ class Cohere extends BaseLLM { const data = (await resp.json()) as any; return data.embeddings.float; } + + async rerank(query: string, chunks: Chunk[]): Promise { + const resp = await fetch(new URL("rerank", this.apiBase), { + method: "POST", + headers: { + Authorization: `Bearer ${this.apiKey}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + model: this.model, + query, + documents: chunks.map((chunk) => chunk.content), + }), + }); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + const results = data.results.sort((a: any, b: any) => a.index - b.index); + return results.map((result: any) => result.relevance_score); + } } export default Cohere; diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 77feb34b5..2465d1c7d 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -1,7 +1,12 @@ import { TRIAL_FIM_MODEL } from "../../config/onboarding.js"; import { getHeaders } from "../../continueServer/stubs/headers.js"; import { TRIAL_PROXY_URL } from "../../control-plane/client.js"; -import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { + ChatMessage, + Chunk, + CompletionOptions, + LLMOptions, +} from "../../index.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -226,6 +231,31 @@ class FreeTrial extends BaseLLM { const data = (await resp.json()) as any; return data.embeddings; } + + async rerank(query: string, chunks: Chunk[]): Promise { + if (chunks.length === 0) { + return []; + } + const resp = await this.fetch(new URL("rerank", TRIAL_PROXY_URL), { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(await getHeaders()), + }, + body: JSON.stringify({ + query, + documents: chunks.map((chunk) => chunk.content), + }), + }); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + const results = data.sort((a: any, b: any) => a.index - b.index); + return results.map((result: any) => result.relevance_score); + } } export default FreeTrial; diff --git a/core/llm/llms/HuggingFaceTEI.ts b/core/llm/llms/HuggingFaceTEI.ts index 34ced63a4..206bbd5e2 100644 --- a/core/llm/llms/HuggingFaceTEI.ts +++ b/core/llm/llms/HuggingFaceTEI.ts @@ -1,10 +1,9 @@ -import { LLMOptions } from "../../index.js"; +import { Chunk, LLMOptions } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; import { BaseLLM } from "../index.js"; class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { static providerName = "huggingface-tei"; - private _maxBatchSize?: number; static defaultOptions: Partial | undefined = { apiBase: "http://localhost:8080", @@ -70,6 +69,38 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM { } return (await resp.json()) as TEIInfoResponse; } + + async rerank(query: string, chunks: Chunk[]): Promise { + const headers: Record = { + "Content-Type": "application/json", + }; + + if (this.apiKey) { + headers["Authorization"] = `Bearer ${this.apiKey}`; + } + + const resp = await fetch(new URL("rerank", this.apiBase), { + method: "POST", + headers, + body: JSON.stringify({ + query: query, + return_text: false, + raw_scores: false, + texts: chunks.map((chunk) => chunk.content), + truncation_direction: "Right", + truncate: true, + }), + }); + + if (!resp.ok) { + throw new Error(await resp.text()); + } + + const data = (await resp.json()) as any; + // Resort into original order and extract scores + const results = data.sort((a: any, b: any) => a.index - b.index); + return results.map((result: any) => result.score); + } } class TEIEmbedError extends Error { diff --git a/core/llm/llms/Voyage.ts b/core/llm/llms/Voyage.ts index 6b31aca91..27db04e17 100644 --- a/core/llm/llms/Voyage.ts +++ b/core/llm/llms/Voyage.ts @@ -1,4 +1,4 @@ -import { LLMOptions } from "../../index.js"; +import { Chunk, LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; @@ -6,9 +6,39 @@ class Voyage extends OpenAI { static providerName = "voyage"; static defaultOptions: Partial | undefined = { apiBase: "https://api.voyageai.com/v1/", - model: "voyage-code-2", maxEmbeddingBatchSize: 128, }; + + async rerank(query: string, chunks: Chunk[]): Promise { + if (!query || chunks.length === 0) { + return []; + } + const url = new URL("rerank", this.apiBase); + const resp = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ + query, + documents: chunks.map((chunk) => chunk.content), + model: this.model ?? "rerank-2", + }), + }); + + if (resp.status !== 200) { + throw new Error( + `VoyageReranker API error ${resp.status}: ${await resp.text()}`, + ); + } + + const data = (await resp.json()) as { + data: Array<{ index: number; relevance_score: number }>; + }; + const results = data.data.sort((a, b) => a.index - b.index); + return results.map((result) => result.relevance_score); + } } export default Voyage; diff --git a/core/context/rerankers/llm.ts b/core/llm/llms/llm.ts similarity index 98% rename from core/context/rerankers/llm.ts rename to core/llm/llms/llm.ts index 469ae923c..4cd433232 100644 --- a/core/context/rerankers/llm.ts +++ b/core/llm/llms/llm.ts @@ -1,6 +1,6 @@ import { Chunk } from "../../index.js"; -import { BaseLLM } from "../../llm/index.js"; import { getBasename } from "../../util/index.js"; +import { BaseLLM } from "../index.js"; const RERANK_PROMPT = ( query: string, diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 138a3d679..c037ebd61 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -2,7 +2,7 @@ import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyti import { Telemetry } from "../../../util/posthog.js"; import OpenAI from "../OpenAI.js"; -import type { LLMOptions } from "../../../index.js"; +import type { Chunk, LLMOptions } from "../../../index.js"; class ContinueProxy extends OpenAI { set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { @@ -28,6 +28,25 @@ class ContinueProxy extends OpenAI { supportsFim(): boolean { return true; } + + async rerank(query: string, chunks: Chunk[]): Promise { + const url = new URL("rerank", this.apiBase); + const resp = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ + query, + documents: chunks.map((chunk) => chunk.content), + model: this.model, + }), + }); + const data: any = await resp.json(); + const results = data.data.sort((a: any, b: any) => a.index - b.index); + return results.map((result: any) => result.relevance_score); + } } export default ContinueProxy;