From 0341c60bdf6dc8d94320217f450046f51ef8895b Mon Sep 17 00:00:00 2001 From: Annoying Technology Date: Tue, 3 Dec 2024 14:06:40 +0100 Subject: [PATCH 1/7] Brings support for Bedrock's reranking models --- core/context/rerankers/bedrock.ts | 99 +++++++++++++++++++ core/context/rerankers/index.ts | 4 +- core/index.d.ts | 1 + .../model-providers/top-level/bedrock.md | 14 ++- extensions/vscode/config_schema.json | 27 +++++ 5 files changed, 142 insertions(+), 3 deletions(-) create mode 100644 core/context/rerankers/bedrock.ts diff --git a/core/context/rerankers/bedrock.ts b/core/context/rerankers/bedrock.ts new file mode 100644 index 000000000..071910bd9 --- /dev/null +++ b/core/context/rerankers/bedrock.ts @@ -0,0 +1,99 @@ +import { + BedrockRuntimeClient, + InvokeModelCommand, +} from "@aws-sdk/client-bedrock-runtime"; +import { fromIni } from "@aws-sdk/credential-providers"; +import { Chunk, Reranker, RerankerName } from "../../index.js"; + +export class BedrockReranker implements Reranker { + name: RerankerName = "bedrock"; + + static defaultOptions = { + region: "us-east-1", + model: "amazon.rerank-v1:0", + profile: "bedrock", + }; + + private supportedModels = ["amazon.rerank-v1:0", "cohere.rerank-v3-5:0"]; + + constructor( + private readonly params: { + region?: string; + model?: string; + profile?: string; + } = {}, + ) { + if (params.model && !this.supportedModels.includes(params.model)) { + throw new Error( + `Unsupported model: ${params.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.params.region ?? BedrockReranker.defaultOptions.region, + credentials, + }); + + const model = this.params.model ?? BedrockReranker.defaultOptions.model; + + // 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 (model.startsWith("cohere.rerank")) { + payload.api_version = 2; + } + + const input = { + body: JSON.stringify(payload), + modelId: 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.params.profile ?? BedrockReranker.defaultOptions.profile, + ignoreCache: true, + })(); + return credentials; + } catch (e) { + console.warn( + `AWS profile with name ${this.params.profile ?? BedrockReranker.defaultOptions.profile} not found in ~/.aws/credentials, using default profile`, + ); + return await fromIni()(); + } + } +} diff --git a/core/context/rerankers/index.ts b/core/context/rerankers/index.ts index 9b1db230d..ba6af849c 100644 --- a/core/context/rerankers/index.ts +++ b/core/context/rerankers/index.ts @@ -1,5 +1,6 @@ import { RerankerName } from "../../index.js"; +import { BedrockReranker } from "./bedrock.js"; import { CohereReranker } from "./cohere.js"; import { ContinueProxyReranker } from "./ContinueProxyReranker.js"; import { FreeTrialReranker } from "./freeTrial.js"; @@ -9,9 +10,10 @@ import { VoyageReranker } from "./voyage.js"; export const AllRerankers: { [key in RerankerName]: any } = { cohere: CohereReranker, + bedrock: BedrockReranker, llm: LLMReranker, voyage: VoyageReranker, "free-trial": FreeTrialReranker, "huggingface-tei": HuggingFaceTEIReranker, "continue-proxy": ContinueProxyReranker, -}; +}; \ No newline at end of file diff --git a/core/index.d.ts b/core/index.d.ts index 34212cfac..b66e00499 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1034,6 +1034,7 @@ export interface EmbeddingsProvider { export type RerankerName = | "cohere" + | "bedrock" | "voyage" | "llm" | "free-trial" diff --git a/docs/docs/customize/model-providers/top-level/bedrock.md b/docs/docs/customize/model-providers/top-level/bedrock.md index 8d46c5ad9..e76f88a77 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.md +++ b/docs/docs/customize/model-providers/top-level/bedrock.md @@ -46,9 +46,19 @@ We recommend configuring [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazo ## Reranking model -Bedrock currently does not offer any reranking models. +We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may also use `amazon.titan-embed-text-v2:0`. -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. +```json title="~/.continue/config.json" +{ + "reranker": { + "name": "bedrock", + "params": { + "model": "cohere.rerank-v3-5:0", + "region": "us-west-2" + } + } +} +``` ## Authentication diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 86a9d54a2..36fe771da 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2642,6 +2642,7 @@ "properties": { "name": { "enum": [ + "bedrock", "cohere", "voyage", "llm", @@ -2743,6 +2744,32 @@ } } }, + { + "if": { + "properties": { + "name": { + "enum": ["bedrock"] + } + }, + "required": ["name"] + }, + "then": { + "properties": { + "params": { + "type": "object", + "properties": { + "model": { + "enum": [ + "cohere.rerank-v3-5:0", + "amazon.rerank-v1:0" + ] + } + }, + "required": ["model"] + } + } + } + }, { "if": { "properties": { From 9c3cd49f08a8304435587f68a158c55a3258414f Mon Sep 17 00:00:00 2001 From: Annoying Technology Date: Tue, 3 Dec 2024 14:10:25 +0100 Subject: [PATCH 2/7] Wrong model specified in the documentation --- docs/docs/customize/model-providers/top-level/bedrock.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/customize/model-providers/top-level/bedrock.md b/docs/docs/customize/model-providers/top-level/bedrock.md index e76f88a77..fb88d5ae0 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.md +++ b/docs/docs/customize/model-providers/top-level/bedrock.md @@ -46,7 +46,7 @@ We recommend configuring [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazo ## Reranking model -We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may also use `amazon.titan-embed-text-v2:0`. +We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may also use `amazon.rerank-v1:0`. ```json title="~/.continue/config.json" { From d431a4645131212ef19f96136708e58ef3966614 Mon Sep 17 00:00:00 2001 From: Annoying Technology Date: Wed, 4 Dec 2024 09:40:13 +0100 Subject: [PATCH 3/7] Wrong sorting key used in the reranker --- core/context/rerankers/bedrock.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/core/context/rerankers/bedrock.ts b/core/context/rerankers/bedrock.ts index 071910bd9..262ef3482 100644 --- a/core/context/rerankers/bedrock.ts +++ b/core/context/rerankers/bedrock.ts @@ -72,10 +72,13 @@ export class BedrockReranker implements Reranker { 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); + // Sort results by relevance_score in descending order + const sortedResults = responseBody.results.sort( + (a: any, b: any) => b.relevance_score - a.relevance_score, + ); + + // Return the sorted relevance scores + return sortedResults.map((result: any) => result.relevance_score); } catch (error) { console.error("Error in BedrockReranker.rerank:", error); throw error; From abbf2fb74c6a0cd509cf4b19358d8dc5bbf9251e Mon Sep 17 00:00:00 2001 From: Annoying Technology Date: Wed, 4 Dec 2024 09:49:15 +0100 Subject: [PATCH 4/7] Cancels the last commit --- core/context/rerankers/bedrock.ts | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/core/context/rerankers/bedrock.ts b/core/context/rerankers/bedrock.ts index 262ef3482..071910bd9 100644 --- a/core/context/rerankers/bedrock.ts +++ b/core/context/rerankers/bedrock.ts @@ -72,13 +72,10 @@ export class BedrockReranker implements Reranker { const responseBody = JSON.parse(new TextDecoder().decode(response.body)); - // Sort results by relevance_score in descending order - const sortedResults = responseBody.results.sort( - (a: any, b: any) => b.relevance_score - a.relevance_score, - ); - - // Return the sorted relevance scores - return sortedResults.map((result: any) => result.relevance_score); + // 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; From 2f3121c4b9bcd26dd4ff8d43bce64008594d263a Mon Sep 17 00:00:00 2001 From: Annoying Technology Date: Thu, 5 Dec 2024 16:42:14 +0100 Subject: [PATCH 5/7] Fixes #400, a bug that sents chunks too large for the embedding model --- core/indexing/docs/article.ts | 88 +++++++++++++++++++++-------------- 1 file changed, 53 insertions(+), 35 deletions(-) diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index 1bc74c62e..99992b415 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -25,56 +25,74 @@ function breakdownArticleComponent( max_chunk_size: number, ): Chunk[] { const chunks: Chunk[] = []; - - const lines = article.body.split("\n"); + const words = article.body.split(/\s+/); + let currentChunk = ""; let startLine = 0; - let endLine = 0; - let content = ""; let index = 0; - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - if (content.length + line.length <= max_chunk_size) { - content += `${line}\n`; - endLine = i; - } else { - chunks.push({ - content: content.trim(), - startLine: startLine, - endLine: endLine, - otherMetadata: { - title: cleanHeader(article.title), - }, - index: index, - filepath: new URL( - `${subpath}#${cleanFragment(article.title)}`, - url, - ).toString(), - digest: subpath, - }); - content = `${line}\n`; - startLine = i; - endLine = i; - index += 1; - } - } - - // Push the last chunk - if (content) { + const createChunk = ( + content: string, + currentStartLine: number, + endLine: number, + ) => { chunks.push({ content: content.trim(), - startLine: startLine, + startLine: currentStartLine, endLine: endLine, otherMetadata: { title: cleanHeader(article.title), }, - index: index, + index: index++, filepath: new URL( `${subpath}#${cleanFragment(article.title)}`, url, ).toString(), digest: subpath, }); + }; + + for (let i = 0; i < words.length; i++) { + const word = words[i]; + + // If a single word is longer than max_chunk_size, split it + if (word.length > max_chunk_size) { + // First, push the current chunk if it has content + if (currentChunk.trim().length > 0) { + createChunk(currentChunk.trim(), startLine, i - 1); + currentChunk = ""; + } + + // Split the long word into smaller pieces + let remainingWord = word; + while (remainingWord.length > 0) { + const chunk = remainingWord.slice(0, max_chunk_size); + createChunk(chunk, i, i); + remainingWord = remainingWord.slice(max_chunk_size); + } + + startLine = i + 1; + continue; + } + + // Check if adding this word would exceed max_chunk_size + if (currentChunk.length + word.length + 1 > max_chunk_size) { + // Push current chunk if it has content + if (currentChunk.trim().length > 0) { + createChunk(currentChunk.trim(), startLine, i - 1); + } + + // Start new chunk with current word + currentChunk = word; + startLine = i; + } else { + // Add word to current chunk + currentChunk = currentChunk.length > 0 ? `${currentChunk} ${word}` : word; + } + } + + // Push the last chunk if it has content + if (currentChunk.trim().length > 0) { + createChunk(currentChunk.trim(), startLine, words.length - 1); } // Don't use small chunks. Probably they're a mistake. Definitely they'll confuse the embeddings model. From f1c7e5ad6b744a419b831afe6bd79ba1f591e9ab Mon Sep 17 00:00:00 2001 From: Annoying Technology Date: Thu, 5 Dec 2024 16:56:30 +0100 Subject: [PATCH 6/7] Preserves line breaks on doc chunking --- core/indexing/docs/article.ts | 76 +++++++++++++++++------------------ 1 file changed, 37 insertions(+), 39 deletions(-) diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index 99992b415..2ae0e7995 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -25,20 +25,21 @@ function breakdownArticleComponent( max_chunk_size: number, ): Chunk[] { const chunks: Chunk[] = []; - const words = article.body.split(/\s+/); - let currentChunk = ""; + const lines = article.body.split("\n"); let startLine = 0; + let endLine = 0; + let content = ""; let index = 0; const createChunk = ( - content: string, - currentStartLine: number, - endLine: number, + chunkContent: string, + chunkStartLine: number, + chunkEndLine: number, ) => { chunks.push({ - content: content.trim(), - startLine: currentStartLine, - endLine: endLine, + content: chunkContent.trim(), + startLine: chunkStartLine, + endLine: chunkEndLine, otherMetadata: { title: cleanHeader(article.title), }, @@ -51,51 +52,48 @@ function breakdownArticleComponent( }); }; - for (let i = 0; i < words.length; i++) { - const word = words[i]; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; - // If a single word is longer than max_chunk_size, split it - if (word.length > max_chunk_size) { - // First, push the current chunk if it has content - if (currentChunk.trim().length > 0) { - createChunk(currentChunk.trim(), startLine, i - 1); - currentChunk = ""; + // Handle oversized lines by splitting them + if (line.length > max_chunk_size) { + // First push any accumulated content + if (content.trim().length > 0) { + createChunk(content, startLine, endLine); + content = ""; } - // Split the long word into smaller pieces - let remainingWord = word; - while (remainingWord.length > 0) { - const chunk = remainingWord.slice(0, max_chunk_size); - createChunk(chunk, i, i); - remainingWord = remainingWord.slice(max_chunk_size); + // Split the long line into chunks + let remainingLine = line; + let subLineStart = i; + while (remainingLine.length > 0) { + const chunk = remainingLine.slice(0, max_chunk_size); + createChunk(chunk, subLineStart, i); + remainingLine = remainingLine.slice(max_chunk_size); } - startLine = i + 1; continue; } - // Check if adding this word would exceed max_chunk_size - if (currentChunk.length + word.length + 1 > max_chunk_size) { - // Push current chunk if it has content - if (currentChunk.trim().length > 0) { - createChunk(currentChunk.trim(), startLine, i - 1); - } - - // Start new chunk with current word - currentChunk = word; - startLine = i; + // Normal line handling + if (content.length + line.length + 1 <= max_chunk_size) { + content += `${line}\n`; + endLine = i; } else { - // Add word to current chunk - currentChunk = currentChunk.length > 0 ? `${currentChunk} ${word}` : word; + if (content.trim().length > 0) { + createChunk(content, startLine, endLine); + } + content = `${line}\n`; + startLine = i; + endLine = i; } } - // Push the last chunk if it has content - if (currentChunk.trim().length > 0) { - createChunk(currentChunk.trim(), startLine, words.length - 1); + // Push the last chunk + if (content.trim().length > 0) { + createChunk(content, startLine, endLine); } - // Don't use small chunks. Probably they're a mistake. Definitely they'll confuse the embeddings model. return chunks.filter((c) => c.content.trim().length > 20); } From 5e46f83f06d9611be541805c377b3231578afe45 Mon Sep 17 00:00:00 2001 From: Annoying Technology Date: Thu, 5 Dec 2024 16:58:10 +0100 Subject: [PATCH 7/7] Adds the support for bedrock reranking in the reference documentation --- docs/docs/reference.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 0a5c02aad..df3f08e75 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -206,10 +206,11 @@ Configuration for the reranker model used in response ranking. **Properties:** -- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei` +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei`, `bedrock` - `params`: - `model`: Model name - `apiKey`: Api key + - `region`: Region (for Bedrock only) Example