-
Notifications
You must be signed in to change notification settings - Fork 603
/
AbstractBedrockApi.java
323 lines (288 loc) · 12 KB
/
AbstractBedrockApi.java
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/*
* Copyright 2023 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// @formatter:off
package org.springframework.ai.bedrock.api;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;
import reactor.core.publisher.Sinks.EmitFailureHandler;
import reactor.core.publisher.Sinks.EmitResult;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelRequest;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelResponse;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler;
import software.amazon.awssdk.services.bedrockruntime.model.ResponseStream;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.util.Assert;
/**
* Abstract class for the Bedrock API. It provides the basic functionality to invoke the chat completion model and
* receive the response for streaming and non-streaming requests.
* <p>
* https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids-arns.html
* <p>
* https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess
*
* @param <I> The input request type.
* @param <O> The output response type.
* @param <SO> The streaming response type. For some models this type can be the same as the output response type.
*
* @see <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html">Model Parameters</a>
* @author Christian Tzolov
* @since 0.8.0
*/
public abstract class AbstractBedrockApi<I, O, SO> {
private static final Logger logger = LoggerFactory.getLogger(AbstractBedrockApi.class);
private final String modelId;
private final ObjectMapper objectMapper;
private final String region;
private final BedrockRuntimeClient client;
private final BedrockRuntimeAsyncClient clientStreaming;
/**
* Create a new AbstractBedrockApi instance using default credentials provider and object mapper.
*
* @param modelId The model id to use.
* @param region The AWS region to use.
*/
public AbstractBedrockApi(String modelId, String region) {
this(modelId, ProfileCredentialsProvider.builder().build(), region, ModelOptionsUtils.OBJECT_MAPPER, Duration.ofMinutes(5));
}
/**
* Create a new AbstractBedrockApi instance using default credentials provider and object mapper.
*
* @param modelId The model id to use.
* @param region The AWS region to use.
* @param timeout The timeout to use.
*/
public AbstractBedrockApi(String modelId, String region, Duration timeout) {
this(modelId, ProfileCredentialsProvider.builder().build(), region, ModelOptionsUtils.OBJECT_MAPPER, timeout);
}
/**
* Create a new AbstractBedrockApi instance using the provided credentials provider, region and object mapper.
*
* @param modelId The model id to use.
* @param credentialsProvider The credentials provider to connect to AWS.
* @param region The AWS region to use.
* @param objectMapper The object mapper to use for JSON serialization and deserialization.
*/
public AbstractBedrockApi(String modelId, AwsCredentialsProvider credentialsProvider, String region,
ObjectMapper objectMapper) {
this(modelId, credentialsProvider, region, objectMapper, Duration.ofMinutes(5));
}
/**
* Create a new AbstractBedrockApi instance using the provided credentials provider, region and object mapper.
*
* @param modelId The model id to use.
* @param credentialsProvider The credentials provider to connect to AWS.
* @param region The AWS region to use.
* @param objectMapper The object mapper to use for JSON serialization and deserialization.
* @param timeout Configure the amount of time to allow the client to complete the execution of an API call.
* This timeout covers the entire client execution except for marshalling. This includes request handler execution,
* all HTTP requests including retries, unmarshalling, etc. This value should always be positive, if present.
*/
public AbstractBedrockApi(String modelId, AwsCredentialsProvider credentialsProvider, String region,
ObjectMapper objectMapper, Duration timeout) {
Assert.hasText(modelId, "Model id must not be empty");
Assert.notNull(credentialsProvider, "Credentials provider must not be null");
Assert.hasText(region, "Region must not be empty");
Assert.notNull(objectMapper, "Object mapper must not be null");
Assert.notNull(timeout, "Timeout must not be null");
this.modelId = modelId;
this.objectMapper = objectMapper;
this.region = region;
this.client = BedrockRuntimeClient.builder()
.region(Region.of(this.region))
.credentialsProvider(credentialsProvider)
.overrideConfiguration(c -> c.apiCallTimeout(timeout))
.build();
this.clientStreaming = BedrockRuntimeAsyncClient.builder()
.region(Region.of(this.region))
.credentialsProvider(credentialsProvider)
.overrideConfiguration(c -> c.apiCallTimeout(timeout))
.build();
}
/**
* @return The model id.
*/
public String getModelId() {
return this.modelId;
}
/**
* @return The AWS region.
*/
public String getRegion() {
return this.region;
}
/**
* Encapsulates the metrics about the model invocation.
* https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-claude.html
*
* @param inputTokenCount The number of tokens in the input prompt.
* @param firstByteLatency The time in milliseconds between the request being sent and the first byte of the
* response being received.
* @param outputTokenCount The number of tokens in the generated text.
* @param invocationLatency The time in milliseconds between the request being sent and the response being received.
*/
@JsonInclude(Include.NON_NULL)
public record AmazonBedrockInvocationMetrics(
@JsonProperty("inputTokenCount") Long inputTokenCount,
@JsonProperty("firstByteLatency") Long firstByteLatency,
@JsonProperty("outputTokenCount") Long outputTokenCount,
@JsonProperty("invocationLatency") Long invocationLatency) {
}
/**
* Compute the embedding for the given text.
*
* @param request The embedding request.
* @return Returns the embedding response.
*/
protected O embedding(I request) {
throw new UnsupportedOperationException("Embedding is not supported for this model: " + this.modelId);
}
/**
* Chat completion invocation.
*
* @param request The chat completion request.
* @return The chat completion response.
*/
protected O chatCompletion(I request) {
throw new UnsupportedOperationException("Chat completion is not supported for this model: " + this.modelId);
}
/**
* Chat completion invocation with streaming response.
*
* @param request The chat completion request.
* @return The chat completion response stream.
*/
protected Flux<SO> chatCompletionStream(I request) {
throw new UnsupportedOperationException(
"Streaming chat completion is not supported for this model: " + this.modelId);
}
/**
* Internal method to invoke the model and return the response.
* https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html
* https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html
* https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/bedrockruntime/BedrockRuntimeClient.html#invokeModel
*
* @param request Model invocation request.
* @param clazz The response class type
* @return The model invocation response.
*
*/
protected O internalInvocation(I request, Class<O> clazz) {
SdkBytes body;
try {
body = SdkBytes.fromUtf8String(new ObjectMapper().writeValueAsString(request));
}
catch (JsonProcessingException e) {
throw new IllegalArgumentException("Invalid JSON format for the input request: " + request, e);
}
InvokeModelRequest invokeRequest = InvokeModelRequest.builder()
.modelId(this.modelId)
.body(body)
.build();
InvokeModelResponse response = this.client.invokeModel(invokeRequest);
String responseBody = response.body().asString(StandardCharsets.UTF_8);
try {
return this.objectMapper.readValue(responseBody, clazz);
}
catch (JsonProcessingException | UncheckedIOException e) {
throw new IllegalArgumentException("Invalid JSON format for the response: " + responseBody, e);
}
}
/**
* Internal method to invoke the model and return the response stream.
*
* @param request Model invocation request.
* @param clazz Response class type.
* @return The model invocation response stream.
*/
protected Flux<SO> internalInvocationStream(I request, Class<SO> clazz) {
// final Sinks.Many<SO> eventSink = Sinks.many().unicast().onBackpressureError();
final Sinks.Many<SO> eventSink = Sinks.many().multicast().onBackpressureBuffer();
SdkBytes body;
try {
body = SdkBytes.fromUtf8String(this.objectMapper.writeValueAsString(request));
}
catch (JsonProcessingException e) {
eventSink.tryEmitError(e);
return eventSink.asFlux();
}
InvokeModelWithResponseStreamRequest invokeRequest = InvokeModelWithResponseStreamRequest.builder()
.modelId(this.modelId)
.body(body)
.build();
InvokeModelWithResponseStreamResponseHandler.Visitor visitor = InvokeModelWithResponseStreamResponseHandler.Visitor
.builder()
.onChunk((chunk) -> {
try {
logger.debug("Received chunk: " + chunk.bytes().asString(StandardCharsets.UTF_8));
SO response = this.objectMapper.readValue(chunk.bytes().asByteArray(), clazz);
eventSink.tryEmitNext(response);
}
catch (Exception e) {
logger.error("Failed to unmarshall", e);
eventSink.tryEmitError(e);
}
})
.onDefault((event) -> {
logger.error("Unknown or unhandled event: " + event.toString());
eventSink.tryEmitError(new Throwable("Unknown or unhandled event: " + event.toString()));
})
.build();
InvokeModelWithResponseStreamResponseHandler responseHandler = InvokeModelWithResponseStreamResponseHandler
.builder()
.onComplete(
() -> {
EmitResult emitResult = eventSink.tryEmitComplete();
while(!emitResult.isSuccess()){
System.out.println("Emitting complete:" + emitResult);
emitResult = eventSink.tryEmitComplete();
};
eventSink.emitComplete(EmitFailureHandler.busyLooping(Duration.ofSeconds(3)));
// EmitResult emitResult = eventSink.tryEmitComplete();
logger.debug("\nCompleted streaming response.");
})
.onError((error) -> {
logger.error("\n\nError streaming response: " + error.getMessage());
eventSink.tryEmitError(error);
})
.onEventStream((stream) -> {
stream.subscribe(
(ResponseStream e) -> {
e.accept(visitor);
});
})
.build();
this.clientStreaming.invokeModelWithResponseStream(invokeRequest, responseHandler);
return eventSink.asFlux();
}
}
// @formatter:on