| 1 | import { |
| 2 | InvokeEndpointCommand, |
| 3 | InvokeEndpointWithResponseStreamCommand, |
| 4 | SageMakerRuntimeClient, |
| 5 | } from "@aws-sdk/client-sagemaker-runtime"; |
| 6 | import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; |
| 7 | |
| 8 | // @ts-ignore |
| 9 | import jinja from "jinja-js"; |
| 10 | |
| 11 | import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; |
| 12 | import { BaseLLM } from "../index.js"; |
| 13 | |
| 14 | class SageMaker extends BaseLLM { |
| 15 | private static DEFAULT_PROFILE_NAME: string = "sagemaker"; |
| 16 | |
| 17 | static providerName = "sagemaker"; |
| 18 | |
| 19 | static defaultOptions: Partial<LLMOptions> = { |
| 20 | region: "us-west-2", |
| 21 | contextLength: 200_000, |
| 22 | maxEmbeddingBatchSize: 1, |
| 23 | }; |
| 24 | |
| 25 | constructor(options: LLMOptions) { |
| 26 | super(options); |
| 27 | if (!options.apiBase) { |
| 28 | this.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`; |
| 29 | } |
| 30 | |
| 31 | this.profile ??= SageMaker.DEFAULT_PROFILE_NAME; |
| 32 | } |
| 33 | |
| 34 | protected async *_streamComplete( |
| 35 | prompt: string, |
| 36 | signal: AbortSignal, |
| 37 | options: CompletionOptions, |
| 38 | ): AsyncGenerator<string> { |
| 39 | const credentials = await this._getCredentials(); |
| 40 | const client = new SageMakerRuntimeClient({ |
| 41 | region: this.region, |
| 42 | credentials: { |
| 43 | accessKeyId: credentials.accessKeyId, |
| 44 | secretAccessKey: credentials.secretAccessKey, |
| 45 | sessionToken: credentials.sessionToken || "", |
| 46 | }, |
| 47 | }); |
| 48 | const toolkit = new CompletionAPIToolkit(this); |
| 49 | const command = toolkit.generateCommand([], prompt, options); |
| 50 | const response = await client.send(command, { abortSignal: signal }); |
| 51 | if (response.Body) { |
| 52 | let buffer = ""; |
| 53 | for await (const rawValue of response.Body) { |
| 54 | const binaryChunk = rawValue.PayloadPart?.Bytes; |
| 55 | let value = new TextDecoder().decode(binaryChunk); |
| 56 | buffer += value; |
| 57 | let position; |
| 58 | while ((position = buffer.indexOf("\n")) >= 0) { |
| 59 | const line = buffer.slice(0, position); |
| 60 | try { |
| 61 | const data = JSON.parse(line.replace(/^data:/, "")); |
| 62 | let text = undefined; |
| 63 | if ("choices" in data) { |
| 64 | if ("delta" in data.choices[0]) { |
| 65 | text = data.choices[0].delta.content; |
| 66 | } else { |
| 67 | text = data.choices[0].text; |
| 68 | } |
| 69 | } else if ("token" in data) { |
| 70 | text = data.token.text; |
| 71 | } |
| 72 | if (text !== undefined) { |
| 73 | yield text; |
| 74 | } |
| 75 | } catch (e) {} |
| 76 | buffer = buffer.slice(position + 1); |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | protected async *_streamChat( |
| 83 | messages: ChatMessage[], |
| 84 | signal: AbortSignal, |
| 85 | options: CompletionOptions, |
| 86 | ): AsyncGenerator<ChatMessage> { |
| 87 | const credentials = await this._getCredentials(); |
| 88 | const client = new SageMakerRuntimeClient({ |
| 89 | region: this.region, |
| 90 | credentials: { |
| 91 | accessKeyId: credentials.accessKeyId, |
| 92 | secretAccessKey: credentials.secretAccessKey, |
| 93 | sessionToken: credentials.sessionToken || "", |
| 94 | }, |
| 95 | }); |
| 96 | const toolkit = new MessageAPIToolkit(this); |
| 97 | |
| 98 | const command = toolkit.generateCommand(messages, "", options); |
| 99 | const response = await client.send(command, { abortSignal: signal }); |
| 100 | if (response.Body) { |
| 101 | let buffer = ""; |
| 102 | for await (const rawValue of response.Body) { |
| 103 | const binaryChunk = rawValue.PayloadPart?.Bytes; |
| 104 | let value = new TextDecoder().decode(binaryChunk); |
| 105 | buffer += value; |
| 106 | let position; |
| 107 | while ((position = buffer.indexOf("\n")) >= 0) { |
| 108 | const line = buffer.slice(0, position); |
| 109 | try { |
| 110 | const data = JSON.parse(line.replace(/^data:/, "")); |
| 111 | let text = undefined; |
| 112 | if ("choices" in data) { |
| 113 | if ("delta" in data.choices[0]) { |
| 114 | text = data.choices[0].delta.content; |
| 115 | } else { |
| 116 | text = data.choices[0].text; |
| 117 | } |
| 118 | } else if ("token" in data) { |
| 119 | text = data.token.text; |
| 120 | } |
| 121 | if (text !== undefined) { |
| 122 | yield { role: "assistant", content: text }; |
| 123 | } |
| 124 | } catch (e) {} |
| 125 | buffer = buffer.slice(position + 1); |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | private async _getCredentials() { |
| 132 | try { |
| 133 | return await fromNodeProviderChain({ |
| 134 | profile: this.profile, |
| 135 | })(); |
| 136 | } catch (e) { |
| 137 | console.warn( |
| 138 | `AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`, |
| 139 | ); |
| 140 | return await fromNodeProviderChain()(); |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | async _embed(chunks: string[]) { |
| 145 | const credentials = await this._getCredentials(); |
| 146 | const client = new SageMakerRuntimeClient({ |
| 147 | region: this.region, |
| 148 | credentials: { |
| 149 | accessKeyId: credentials.accessKeyId, |
| 150 | secretAccessKey: credentials.secretAccessKey, |
| 151 | sessionToken: credentials.sessionToken || "", |
| 152 | }, |
| 153 | }); |
| 154 | |
| 155 | const input = this._generateInvokeModelCommandInput(chunks); |
| 156 | const command = new InvokeEndpointCommand(input); |
| 157 | const response = await client.send(command); |
| 158 | |
| 159 | if (response.Body) { |
| 160 | const decoder = new TextDecoder(); |
| 161 | const decoded = decoder.decode(response.Body); |
| 162 | try { |
| 163 | const responseBody = JSON.parse(decoded); |
| 164 | // If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body |
| 165 | if (responseBody.embedding) { |
| 166 | return responseBody.embedding; |
| 167 | } else if (responseBody.embeddings) { |
| 168 | return responseBody.embeddings; |
| 169 | } else { |
| 170 | return responseBody; |
| 171 | } |
| 172 | } catch (e) { |
| 173 | let message = e instanceof Error ? e.message : String(e); |
| 174 | throw new Error( |
| 175 | `Failed to parse response from SageMaker:\n${decoded}\nError: ${message}`, |
| 176 | ); |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | private _generateInvokeModelCommandInput(prompts: string | string[]): any { |
| 181 | const payload = { |
| 182 | inputs: prompts, |
| 183 | normalize: true, |
| 184 | // ...(options.requestOptions?.extraBodyProperties || {}), |
| 185 | }; |
| 186 | |
| 187 | if (this.requestOptions?.extraBodyProperties) { |
| 188 | Object.assign(payload, this.requestOptions.extraBodyProperties); |
| 189 | } |
| 190 | |
| 191 | return { |
| 192 | EndpointName: this.model, |
| 193 | Body: JSON.stringify(payload), |
| 194 | ContentType: "application/json", |
| 195 | CustomAttributes: "accept_eula=false", |
| 196 | }; |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | interface SageMakerModelToolkit { |
| 201 | generateCommand( |
| 202 | messages: ChatMessage[], |
| 203 | prompt: string, |
| 204 | options: CompletionOptions, |
| 205 | ): InvokeEndpointWithResponseStreamCommand; |
| 206 | } |
| 207 | |
| 208 | class MessageAPIToolkit implements SageMakerModelToolkit { |
| 209 | constructor(private sagemaker: SageMaker) {} |
| 210 | generateCommand( |
| 211 | messages: ChatMessage[], |
| 212 | prompt: string, |
| 213 | options: CompletionOptions, |
| 214 | ): InvokeEndpointWithResponseStreamCommand { |
| 215 | if ("chat_template" in this.sagemaker.completionOptions) { |
| 216 | // for some model you can apply chat_template to the model |
| 217 | let prompt = jinja |
| 218 | .compile(this.sagemaker.completionOptions.chat_template) |
| 219 | .render( |
| 220 | { messages: messages, add_generation_prompt: true }, |
| 221 | { autoEscape: false }, |
| 222 | ); |
| 223 | const payload = { |
| 224 | inputs: prompt, |
| 225 | parameters: this.sagemaker.completionOptions, |
| 226 | stream: true, |
| 227 | }; |
| 228 | |
| 229 | return new InvokeEndpointWithResponseStreamCommand({ |
| 230 | EndpointName: options.model, |
| 231 | Body: new TextEncoder().encode(JSON.stringify(payload)), |
| 232 | ContentType: "application/json", |
| 233 | CustomAttributes: "accept_eula=false", |
| 234 | }); |
| 235 | } else { |
| 236 | const payload = { |
| 237 | messages: messages, |
| 238 | max_tokens: options.maxTokens, |
| 239 | temperature: options.temperature, |
| 240 | top_p: options.topP, |
| 241 | top_k: options.topK, |
| 242 | stop: options.stop, |
| 243 | frequencyPenalty: options.frequencyPenalty, |
| 244 | presencePenalty: options.presencePenalty, |
| 245 | stream: true, |
| 246 | }; |
| 247 | |
| 248 | return new InvokeEndpointWithResponseStreamCommand({ |
| 249 | EndpointName: options.model, |
| 250 | Body: new TextEncoder().encode(JSON.stringify(payload)), |
| 251 | ContentType: "application/json", |
| 252 | CustomAttributes: "accept_eula=false", |
| 253 | }); |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | class CompletionAPIToolkit implements SageMakerModelToolkit { |
| 258 | constructor(private sagemaker: SageMaker) {} |
| 259 | generateCommand( |
| 260 | messages: ChatMessage[], |
| 261 | prompt: string, |
| 262 | options: CompletionOptions, |
| 263 | ): InvokeEndpointWithResponseStreamCommand { |
| 264 | const payload = { |
| 265 | inputs: prompt, |
| 266 | prompt: prompt, |
| 267 | parameters: this.sagemaker.completionOptions, |
| 268 | stream: true, |
| 269 | }; |
| 270 | |
| 271 | return new InvokeEndpointWithResponseStreamCommand({ |
| 272 | EndpointName: options.model, |
| 273 | Body: new TextEncoder().encode(JSON.stringify(payload)), |
| 274 | ContentType: "application/json", |
| 275 | CustomAttributes: "accept_eula=false", |
| 276 | }); |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | export default SageMaker; |