Bedrock client refactoring and move to @aws-sdk/credential-providers (#1491)

* Refactor Bedrock LLM client

- Removed unused AWS auth logic
- Simplified message/content conversion

* Improve AWS credentials handling for Bedrock models
- Using @aws-sdk/credential-providers to support wider range of credential provider options
- Removing custom logic of parsing aws credentials file

---------

Co-authored-by: Ruben Kostandyan <kostard@amazon.com>
This commit is contained in:
Ruben Kostandyan 2024-06-16 19:35:02 +02:00 • committed by GitHub
parent 78d6ee815b
commit 38b1f54b0d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 1383 additions and 304 deletions

View file

@ -42,6 +42,7 @@
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",

View file

@ -2,33 +2,19 @@ import {
BedrockRuntimeClient,
InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import * as fs from "node:fs";
import os from "node:os";
import { join as joinPath } from "node:path";
import { promisify } from "util";
import { fromIni } from "@aws-sdk/credential-providers";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessageContent,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../countTokens.js";
import { BaseLLM } from "../index.js";
const aws4 = require("aws4");
const readFile = promisify(fs.readFile);
namespace BedrockCommon {
export enum Method {
Chat = "invoke-with-response-stream",
Completion = "invoke-with-response-stream",
}
export const Service: string = "bedrock";
export const AuthAlgo: string = "AWS4-HMAC-SHA256";
export const HashAlgo: string = "sha256";
}
class Bedrock extends BaseLLM {
private static PROFILE_NAME: string = "bedrock";
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
@ -41,128 +27,49 @@ class Bedrock extends BaseLLM {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
private _convertModelName(model: string): string {
return (
{
"claude-3-sonnet-20240229": "anthropic.claude-3-sonnet-20240229-v1:0",
"claude-3-haiku-20240307": "anthropic.claude-3-haiku-20240307-v1:0",
"claude-2": "anthropic.claude-v2:1",
}[model] ?? model
);
}
private _convertArgs(options: CompletionOptions) {
const finalOptions = {
top_k: options.topK,
top_p: options.topP,
temperature: options.temperature,
max_tokens: options.maxTokens ?? 4096,
stop_sequences: options.stop,
};
return finalOptions;
}
private _convertMessages(msgs: ChatMessage[]): any[] {
const messages = msgs
.filter((m) => m.role !== "system")
.map((message) => {
if (typeof message.content === "string") {
return message;
}
return {
...message,
content: message.content.map((part) => {
if (part.type === "text") {
return part;
}
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}),
};
});
return messages;
return msgs
.filter(m => m.role !== "system")
.map(message => this._convertMessage(message));
}
private _parseCredentialsFile(fileContents: string) {
const profiles: { [key: string]: any } = {};
const lines = fileContents.trim().split("\n");
private _convertMessage(message: ChatMessage): any {
return {
role: message.role,
content: this._convertMessageContent(message.content)
}
}
let currentProfile: string | null = null;
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith("[") && trimmedLine.endsWith("]")) {
currentProfile = trimmedLine.slice(1, -1);
profiles[currentProfile] = {};
} else if (currentProfile !== null && trimmedLine.includes("=")) {
const [key, value] = trimmedLine.split("=");
const trimmedKey = key.trim();
const trimmedValue = value.trim();
if (trimmedKey === "aws_access_key_id") {
profiles[currentProfile].accessKeyId = trimmedValue;
} else if (trimmedKey === "aws_secret_access_key") {
profiles[currentProfile].secretAccessKey = trimmedValue;
} else if (trimmedKey === "aws_session_token") {
profiles[currentProfile].sessionToken = trimmedValue;
}
private _convertMessageContent(messageContent: MessageContent): any {
if (typeof messageContent === "string") {
return messageContent;
}
return messageContent.map((part) => {
if (part.type === "text") {
return part;
}
}
return profiles;
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
});
}
private async _fetchWithAwsAuthSigV4(
apiMethod: BedrockCommon.Method,
body: string,
model: string,
): Promise<Response> {
const path = `/model/${model}/${apiMethod}`;
const opts = {
headers: {
accept: "application/vnd.amazon.eventstream",
"content-type": "application/json",
"x-amzn-bedrock-accept": "*/*",
},
path: path,
body: body,
service: "bedrock",
host: new URL(this.apiBase!).host,
region: this.region,
};
let accessKeyId: string;
let secretAccessKey: string;
let sessionToken: string;
private async _getCredentials() {
try {
const data = await readFile(
joinPath(process.env.HOME ?? os.homedir(), ".aws", "credentials"),
"utf8",
return await fromIni({
profile: Bedrock.PROFILE_NAME,
})();
} catch (e) {
console.warn(
`AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`,
);
const credentialsFile = this._parseCredentialsFile(data);
const credentials = credentialsFile.bedrock ?? credentialsFile.default;
accessKeyId = credentials.accessKeyId;
secretAccessKey = credentials.secretAccessKey;
sessionToken = credentials.sessionToken || "";
} catch (err) {
console.error("Error reading AWS credentials", err);
return new Response("403");
return await fromIni()();
}
return await this.fetch(new URL(`${this.apiBase}${path}`), {
method: "POST",
headers: aws4.sign(opts, { accessKeyId, secretAccessKey, sessionToken })
.headers,
body: body,
});
}
protected async *_streamComplete(
@ -179,12 +86,7 @@ class Bedrock extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const data = await readFile(
joinPath(process.env.HOME ?? os.homedir(), ".aws", "credentials"),
"utf8",
);
const credentialsFile = this._parseCredentialsFile(data);
const credentials = credentialsFile.bedrock ?? credentialsFile.default;
const credentials = await this._getCredentials();
const accessKeyId = credentials.accessKeyId;
const secretAccessKey = credentials.secretAccessKey;
const sessionToken = credentials.sessionToken || "";

1505
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -30,6 +30,7 @@
},
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.159",
"version": "0.9.160",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.159",
"version": "0.9.160",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -94,6 +94,7 @@
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.9.159",
"version": "0.9.160",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

1
gui/package-lock.json generated
View file

@ -87,6 +87,7 @@
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",