From 53aab1e6fd2a0f21fbca1c29b82d1f96d2f5e074 Mon Sep 17 00:00:00 2001 From: Ruben Kostandyan <30292877+KoStard@users.noreply.github.com> Date: Mon, 17 Jun 2024 00:09:59 +0200 Subject: [PATCH] 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 --- core/llm/llms/Bedrock.ts | 209 +++++++++++++++++++--------- extensions/vscode/package-lock.json | 4 +- extensions/vscode/package.json | 2 +- 3 files changed, 147 insertions(+), 68 deletions(-) diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 0c4a6304f..2f7af46a4 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -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 { + 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 { + 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 { - 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 { - 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; } } diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 09036dbf9..b45fb2b33 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -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", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 9e8675a15..441f6ec7c 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -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"