Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 8.3 KiBRawPermalink
1import {
2 InvokeEndpointCommand,
3 InvokeEndpointWithResponseStreamCommand,
4 SageMakerRuntimeClient,
5} from "@aws-sdk/client-sagemaker-runtime";
6import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
7
8// @ts-ignore
9import jinja from "jinja-js";
10
11import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
12import { BaseLLM } from "../index.js";
13
14class 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 responseBody = JSON.parse(new TextDecoder().decode(response.Body));
161 // If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body
162 if (responseBody.embedding) {
163 return responseBody.embedding;
164 } else if (responseBody.embeddings) {
165 return responseBody.embeddings;
166 } else {
167 return responseBody;
168 }
169 }
170 }
171 private _generateInvokeModelCommandInput(prompts: string | string[]): any {
172 const payload = {
173 inputs: prompts,
174 normalize: true,
175 // ...(options.requestOptions?.extraBodyProperties || {}),
176 };
177
178 if (this.requestOptions?.extraBodyProperties) {
179 Object.assign(payload, this.requestOptions.extraBodyProperties);
180 }
181
182 return {
183 EndpointName: this.model,
184 Body: JSON.stringify(payload),
185 ContentType: "application/json",
186 CustomAttributes: "accept_eula=false",
187 };
188 }
189}
190
191interface SageMakerModelToolkit {
192 generateCommand(
193 messages: ChatMessage[],
194 prompt: string,
195 options: CompletionOptions,
196 ): InvokeEndpointWithResponseStreamCommand;
197}
198
199class MessageAPIToolkit implements SageMakerModelToolkit {
200 constructor(private sagemaker: SageMaker) {}
201 generateCommand(
202 messages: ChatMessage[],
203 prompt: string,
204 options: CompletionOptions,
205 ): InvokeEndpointWithResponseStreamCommand {
206 if ("chat_template" in this.sagemaker.completionOptions) {
207 // for some model you can apply chat_template to the model
208 let prompt = jinja
209 .compile(this.sagemaker.completionOptions.chat_template)
210 .render(
211 { messages: messages, add_generation_prompt: true },
212 { autoEscape: false },
213 );
214 const payload = {
215 inputs: prompt,
216 parameters: this.sagemaker.completionOptions,
217 stream: true,
218 };
219
220 return new InvokeEndpointWithResponseStreamCommand({
221 EndpointName: options.model,
222 Body: new TextEncoder().encode(JSON.stringify(payload)),
223 ContentType: "application/json",
224 CustomAttributes: "accept_eula=false",
225 });
226 } else {
227 const payload = {
228 messages: messages,
229 max_tokens: options.maxTokens,
230 temperature: options.temperature,
231 top_p: options.topP,
232 top_k: options.topK,
233 stop: options.stop,
234 frequencyPenalty: options.frequencyPenalty,
235 presencePenalty: options.presencePenalty,
236 stream: true,
237 };
238
239 return new InvokeEndpointWithResponseStreamCommand({
240 EndpointName: options.model,
241 Body: new TextEncoder().encode(JSON.stringify(payload)),
242 ContentType: "application/json",
243 CustomAttributes: "accept_eula=false",
244 });
245 }
246 }
247}
248class CompletionAPIToolkit implements SageMakerModelToolkit {
249 constructor(private sagemaker: SageMaker) {}
250 generateCommand(
251 messages: ChatMessage[],
252 prompt: string,
253 options: CompletionOptions,
254 ): InvokeEndpointWithResponseStreamCommand {
255 const payload = {
256 inputs: prompt,
257 prompt: prompt,
258 parameters: this.sagemaker.completionOptions,
259 stream: true,
260 };
261
262 return new InvokeEndpointWithResponseStreamCommand({
263 EndpointName: options.model,
264 Body: new TextEncoder().encode(JSON.stringify(payload)),
265 ContentType: "application/json",
266 CustomAttributes: "accept_eula=false",
267 });
268 }
269}
270
271export default SageMaker;