-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
sagemaker_endpoint.ts
289 lines (259 loc) Β· 8.56 KB
/
sagemaker_endpoint.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import {
InvokeEndpointCommand,
InvokeEndpointWithResponseStreamCommand,
SageMakerRuntimeClient,
SageMakerRuntimeClientConfig,
} from "@aws-sdk/client-sagemaker-runtime";
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
import { GenerationChunk } from "@langchain/core/outputs";
import {
type BaseLLMCallOptions,
type BaseLLMParams,
LLM,
} from "@langchain/core/language_models/llms";
/**
* A handler class to transform input from LLM to a format that SageMaker
* endpoint expects. Similarily, the class also handles transforming output from
* the SageMaker endpoint to a format that LLM class expects.
*
* Example:
* ```
* class ContentHandler implements ContentHandlerBase<string, string> {
* contentType = "application/json"
* accepts = "application/json"
*
* transformInput(prompt: string, modelKwargs: Record<string, unknown>) {
* const inputString = JSON.stringify({
* prompt,
* ...modelKwargs
* })
* return Buffer.from(inputString)
* }
*
* transformOutput(output: Uint8Array) {
* const responseJson = JSON.parse(Buffer.from(output).toString("utf-8"))
* return responseJson[0].generated_text
* }
*
* }
* ```
*/
export abstract class BaseSageMakerContentHandler<InputType, OutputType> {
contentType = "text/plain";
accepts = "text/plain";
/**
* Transforms the prompt and model arguments into a specific format for sending to SageMaker.
* @param {InputType} prompt The prompt to be transformed.
* @param {Record<string, unknown>} modelKwargs Additional arguments.
* @returns {Promise<Uint8Array>} A promise that resolves to the formatted data for sending.
*/
abstract transformInput(
prompt: InputType,
modelKwargs: Record<string, unknown>
): Promise<Uint8Array>;
/**
* Transforms SageMaker output into a desired format.
* @param {Uint8Array} output The raw output from SageMaker.
* @returns {Promise<OutputType>} A promise that resolves to the transformed data.
*/
abstract transformOutput(output: Uint8Array): Promise<OutputType>;
}
export type SageMakerLLMContentHandler = BaseSageMakerContentHandler<
string,
string
>;
/**
* The SageMakerEndpointInput interface defines the input parameters for
* the SageMakerEndpoint class, which includes the endpoint name, client
* options for the SageMaker client, the content handler, and optional
* keyword arguments for the model and the endpoint.
*/
export interface SageMakerEndpointInput extends BaseLLMParams {
/**
* The name of the endpoint from the deployed SageMaker model. Must be unique
* within an AWS Region.
*/
endpointName: string;
/**
* Options passed to the SageMaker client.
*/
clientOptions: SageMakerRuntimeClientConfig;
/**
* Key word arguments to pass to the model.
*/
modelKwargs?: Record<string, unknown>;
/**
* Optional attributes passed to the InvokeEndpointCommand
*/
endpointKwargs?: Record<string, unknown>;
/**
* The content handler class that provides an input and output transform
* functions to handle formats between LLM and the endpoint.
*/
contentHandler: SageMakerLLMContentHandler;
streaming?: boolean;
}
/**
* The SageMakerEndpoint class is used to interact with SageMaker
* Inference Endpoint models. It uses the AWS client for authentication,
* which automatically loads credentials.
* If a specific credential profile is to be used, the name of the profile
* from the ~/.aws/credentials file must be passed. The credentials or
* roles used should have the required policies to access the SageMaker
* endpoint.
*/
export class SageMakerEndpoint extends LLM<BaseLLMCallOptions> {
lc_serializable = true;
static lc_name() {
return "SageMakerEndpoint";
}
get lc_secrets(): { [key: string]: string } | undefined {
return {
"clientOptions.credentials.accessKeyId": "AWS_ACCESS_KEY_ID",
"clientOptions.credentials.secretAccessKey": "AWS_SECRET_ACCESS_KEY",
"clientOptions.credentials.sessionToken": "AWS_SESSION_TOKEN",
};
}
endpointName: string;
modelKwargs?: Record<string, unknown>;
endpointKwargs?: Record<string, unknown>;
client: SageMakerRuntimeClient;
contentHandler: SageMakerLLMContentHandler;
streaming: boolean;
constructor(fields: SageMakerEndpointInput) {
super(fields);
if (!fields.clientOptions.region) {
throw new Error(
`Please pass a "clientOptions" object with a "region" field to the constructor`
);
}
const endpointName = fields?.endpointName;
if (!endpointName) {
throw new Error(`Please pass an "endpointName" field to the constructor`);
}
const contentHandler = fields?.contentHandler;
if (!contentHandler) {
throw new Error(
`Please pass a "contentHandler" field to the constructor`
);
}
this.endpointName = fields.endpointName;
this.contentHandler = fields.contentHandler;
this.endpointKwargs = fields.endpointKwargs;
this.modelKwargs = fields.modelKwargs;
this.streaming = fields.streaming ?? false;
this.client = new SageMakerRuntimeClient(fields.clientOptions);
}
_llmType() {
return "sagemaker_endpoint";
}
/**
* Calls the SageMaker endpoint and retrieves the result.
* @param {string} prompt The input prompt.
* @param {this["ParsedCallOptions"]} options Parsed call options.
* @param {CallbackManagerForLLMRun} runManager Optional run manager.
* @returns {Promise<string>} A promise that resolves to the generated string.
*/
/** @ignore */
async _call(
prompt: string,
options: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun
): Promise<string> {
return this.streaming
? await this.streamingCall(prompt, options, runManager)
: await this.noStreamingCall(prompt, options);
}
private async streamingCall(
prompt: string,
options: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun
): Promise<string> {
const chunks = [];
for await (const chunk of this._streamResponseChunks(
prompt,
options,
runManager
)) {
chunks.push(chunk.text);
}
return chunks.join("");
}
private async noStreamingCall(
prompt: string,
options: this["ParsedCallOptions"]
): Promise<string> {
const body = await this.contentHandler.transformInput(
prompt,
this.modelKwargs ?? {}
);
const { contentType, accepts } = this.contentHandler;
const response = await this.caller.call(() =>
this.client.send(
new InvokeEndpointCommand({
EndpointName: this.endpointName,
Body: body,
ContentType: contentType,
Accept: accepts,
...this.endpointKwargs,
}),
{ abortSignal: options.signal }
)
);
if (response.Body === undefined) {
throw new Error("Inference result missing Body");
}
return this.contentHandler.transformOutput(response.Body);
}
/**
* Streams response chunks from the SageMaker endpoint.
* @param {string} prompt The input prompt.
* @param {this["ParsedCallOptions"]} options Parsed call options.
* @returns {AsyncGenerator<GenerationChunk>} An asynchronous generator yielding generation chunks.
*/
async *_streamResponseChunks(
prompt: string,
options: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun
): AsyncGenerator<GenerationChunk> {
const body = await this.contentHandler.transformInput(
prompt,
this.modelKwargs ?? {}
);
const { contentType, accepts } = this.contentHandler;
const stream = await this.caller.call(() =>
this.client.send(
new InvokeEndpointWithResponseStreamCommand({
EndpointName: this.endpointName,
Body: body,
ContentType: contentType,
Accept: accepts,
...this.endpointKwargs,
}),
{ abortSignal: options.signal }
)
);
if (!stream.Body) {
throw new Error("Inference result missing Body");
}
for await (const chunk of stream.Body) {
if (chunk.PayloadPart && chunk.PayloadPart.Bytes) {
const text = await this.contentHandler.transformOutput(
chunk.PayloadPart.Bytes
);
yield new GenerationChunk({
text,
generationInfo: {
...chunk,
response: undefined,
},
});
await runManager?.handleLLMNewToken(text);
} else if (chunk.InternalStreamFailure) {
throw new Error(chunk.InternalStreamFailure.message);
} else if (chunk.ModelStreamError) {
throw new Error(chunk.ModelStreamError.message);
}
}
}
}