feat(core): add support for Llama models on Bedrock (#1499)

This commit adds support for streaming completions from Llama models alongside with Anthropic's Claude on Bedrock. Key changes:

- Introduce a `BedrockModelToolkit` interface to encapsulate model-specific logic for generating commands and unwrapping response chunks
- Implement `AnthropicClaude3Toolkit` for Claude model
- Implement `Llama3Toolkit` for Llama models
- Refactor `_streamChat` method to use the appropriate toolkit based on the selected model
- Clean up code formatting and remove unused imports

Co-authored-by: Ruben Kostandyan <kostard@amazon.com>
This commit is contained in:
Ruben Kostandyan 2024-06-17 00:09:59 +02:00 • committed by GitHub
parent 38b1f54b0d
commit 53aab1e6fd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 147 additions and 68 deletions

View file

@ -27,17 +27,108 @@ class Bedrock extends BaseLLM {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
yield stripImages(update.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const toolkit = this._getToolkit(options.model);
const command = toolkit.generateCommand(messages, options);
const response = await client.send(command);
if (response.body) {
for await (const value of response.body) {
const text = toolkit.unwrapResponseChunk(value);
if (text) {
yield { role: "assistant", content: text };
}
}
}
}
private async _getCredentials() {
try {
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`,
);
return await fromIni()();
}
}
private _getToolkit(model: string): BedrockModelToolkit {
if (model.includes("claude-3")) {
return new AnthropicClaude3Toolkit(this);
} else if (model.includes("llama")) {
return new Llama3Toolkit(this);
} else {
throw new Error(`Model ${model} is currently not supported in Continue for Bedrock`);
}
}
}
interface BedrockModelToolkit {
generateCommand(
messages: ChatMessage[],
options: CompletionOptions,
): InvokeModelWithResponseStreamCommand;
unwrapResponseChunk(rawValue: any): string;
}
class AnthropicClaude3Toolkit implements BedrockModelToolkit {
constructor(private bedrock: Bedrock) {}
generateCommand(
messages: ChatMessage[],
options: CompletionOptions,
): InvokeModelWithResponseStreamCommand {
const payload = {
anthropic_version: "bedrock-2023-05-31",
max_tokens: options.maxTokens,
system: this.bedrock.systemMessage,
messages: this._convertMessages(messages),
temperature: options.temperature,
top_p: options.topP,
top_k: options.topK,
stop_sequences: options.stop,
};
return new InvokeModelWithResponseStreamCommand({
body: new TextEncoder().encode(JSON.stringify(payload)),
contentType: "application/json",
modelId: options.model,
});
}
private _convertMessages(msgs: ChatMessage[]): any[] {
return msgs
.filter(m => m.role !== "system")
.map(message => this._convertMessage(message));
.filter((m) => m.role !== "system")
.map((message) => this._convertMessage(message));
}
private _convertMessage(message: ChatMessage): any {
return {
role: message.role,
content: this._convertMessageContent(message.content)
}
role: message.role,
content: this._convertMessageContent(message.content),
};
}
private _convertMessageContent(messageContent: MessageContent): any {
@ -58,73 +149,61 @@ class Bedrock extends BaseLLM {
};
});
}
private async _getCredentials() {
try {
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`,
);
return await fromIni()();
}
unwrapResponseChunk(rawValue: any): string {
const binaryChunk = rawValue.chunk?.bytes;
const textChunk = new TextDecoder().decode(binaryChunk);
const chunk = JSON.parse(textChunk).delta?.text;
return chunk;
}
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
yield stripImages(update.content);
}
}
protected async *_streamChat(
class Llama3Toolkit implements BedrockModelToolkit {
constructor(private bedrock: Bedrock) {}
generateCommand(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
const accessKeyId = credentials.accessKeyId;
const secretAccessKey = credentials.secretAccessKey;
const sessionToken = credentials.sessionToken || "";
const client = new BedrockRuntimeClient({
region: this.region,
credentials: {
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
sessionToken: sessionToken,
},
});
const command = new InvokeModelWithResponseStreamCommand({
body: new TextEncoder().encode(
JSON.stringify({
anthropic_version: "bedrock-2023-05-31",
max_tokens: options.maxTokens,
system: this.systemMessage,
messages: this._convertMessages(messages),
temperature: options.temperature,
top_p: options.topP,
top_k: options.topK,
stop_sequences: options.stop,
}),
),
): InvokeModelWithResponseStreamCommand {
let prompt = "<|begin_of_text|>";
if (this.bedrock.systemMessage) {
prompt += `<|start_header_id|>system<|end_header_id|>${this.bedrock.systemMessage}<|eot_id|>`;
}
for (const message of messages) {
let content = "";
if (typeof message.content === "string") {
content = message.content;
} else {
for (const part of message.content) {
if (part.type === "text") {
content += part.text || "";
} else {
console.warn("Skipping non-text message part", part);
}
}
}
if (content) {
prompt += `<|start_header_id|>${message.role}<|end_header_id|>${content}<|eot_id|>`;
}
}
prompt += "<|start_header_id|>assistant<|end_header_id|>";
const payload = {
prompt,
max_gen_len: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
};
return new InvokeModelWithResponseStreamCommand({
body: new TextEncoder().encode(JSON.stringify(payload)),
contentType: "application/json",
modelId: options.model,
});
const response = await client.send(command);
if (response.body) {
for await (const value of response.body) {
const binaryChunk = value.chunk?.bytes;
const textChunk = new TextDecoder().decode(binaryChunk);
const chunk = JSON.parse(textChunk).delta?.text;
if (chunk) {
yield { role: "assistant", content: chunk };
}
}
}
}
unwrapResponseChunk(rawValue: any): string {
const binaryChunk = rawValue.chunk?.bytes;
const textChunk = new TextDecoder().decode(binaryChunk);
const chunk = JSON.parse(textChunk).generation;
return chunk;
}
}

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.160",
"version": "0.9.162",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.160",
"version": "0.9.162",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",

View file

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