remove all rerankers

This commit is contained in:
Nate 2024-12-08 16:28:23 -08:00
parent b14b8c4652
commit 8790be177b
17 changed files with 217 additions and 336 deletions

View file

@ -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";

View file

@ -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;

View file

@ -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,
};

View file

@ -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<number[]> {
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);
}
}

View file

@ -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<LLMOptions> | 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<number[]> {
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()();
}
}
}

View file

@ -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<number[]> {
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);
}
}

View file

@ -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<number[]> {
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);
}
}

View file

@ -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,
};

View file

@ -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<LLMOptions> | 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<number[]> {
const headers: Record<string, string> = {
"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);
}
}

View file

@ -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<LLMOptions> | undefined = {
apiBase: "https://api.voyageai.com/v1/",
};
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
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);
}
}

View file

@ -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<number[]> {
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;

View file

@ -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<number[]> {
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;

View file

@ -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<number[]> {
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;

View file

@ -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<LLMOptions> | 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<number[]> {
const headers: Record<string, string> = {
"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 {

View file

@ -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<LLMOptions> | undefined = {
apiBase: "https://api.voyageai.com/v1/",
model: "voyage-code-2",
maxEmbeddingBatchSize: 128,
};
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
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;

View file

@ -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,

View file

@ -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<number[]> {
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;