Merge pull request #2478 from Anantha-Kandrapu/bedrock-cohere-embeddings

Added Bedrock Cohere Embeddings Provider
This commit is contained in:
Patrick Erichsen 2024-10-24 12:16:25 -07:00 • committed by GitHub
commit 78f950cd9b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -6,11 +6,14 @@ import { fromIni } from "@aws-sdk/credential-providers";
import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
interface ModelConfig {
formatPayload: (text: string) => any;
extractEmbeddings: (responseBody: any) => number[][];
}
class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "bedrock";
static defaultOptions: Partial<EmbedOptions> | undefined = {
static defaultOptions: Partial<EmbedOptions> = {
model: "amazon.titan-embed-text-v2:0",
region: "us-east-1"
};
@ -18,6 +21,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
constructor(options: EmbedOptions, fetch: FetchFunction) {
super(options, fetch);
this.options.model = this.options.model || BedrockEmbeddingsProvider.defaultOptions.model!;
if (!options.apiBase) {
options.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
@ -29,7 +33,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
}
}
async embed(chunks: string[]) {
async embed(chunks: string[]): Promise<number[][]> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.options.region,
@ -43,41 +47,64 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
return (
await Promise.all(
chunks.map(async (chunk) => {
const input = this._generateInvokeModelCommandInput(chunk, this.options);
const input = this._generateInvokeModelCommandInput(chunk);
const command = new InvokeModelCommand(input);
const response = await client.send(command);
if (response.body) {
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
return [responseBody.embedding];
return this._extractEmbeddings(responseBody);
}
return [];
}),
)
).flat();
}
private _generateInvokeModelCommandInput(
prompt: string,
options: EmbedOptions,
): any {
const payload = {
"inputText": prompt,
"dimensions": 512,
"normalize": true
};
private _generateInvokeModelCommandInput(text: string): any {
const modelConfig = this._getModelConfig();
const payload = modelConfig.formatPayload(text);
return {
body: JSON.stringify(payload),
modelId: this.options.model,
accept: "application/json",
contentType: "application/json"
accept: "*/*",
contentType: "application/json",
};
}
private _extractEmbeddings(responseBody: any): number[][] {
const modelConfig = this._getModelConfig();
return modelConfig.extractEmbeddings(responseBody);
}
private _getModelConfig() {
const modelConfigs: { [key: string]: ModelConfig } = {
'cohere': {
formatPayload: (text: string) => ({
texts: [text],
input_type: "search_document",
truncate: "END",
}),
extractEmbeddings: (responseBody: any) => responseBody.embeddings || [],
},
'amazon.titan-embed': {
formatPayload: (text: string) => ({
inputText: text,
}),
extractEmbeddings: (responseBody: any) => responseBody.embedding ? [responseBody.embedding] : [],
},
};
const modelPrefix = Object.keys(modelConfigs).find(prefix => this.options.model!.startsWith(prefix));
if (!modelPrefix) {
throw new Error(`Unsupported model: ${this.options.model}`);
}
return modelConfigs[modelPrefix];
}
private async _getCredentials() {
try {
return await
fromIni({
return await fromIni({
profile: this.profile,
ignoreCache: true
})();
@ -88,7 +115,6 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
return await fromIni()();
}
}
}
export default BedrockEmbeddingsProvider;