generated from SAP/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Reduce duplication of ResponseHandlers #244
Merged
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
40e56b3
Orchestration streaming first version
CharlesDuboisSAP bc899a1
Added unit tests
CharlesDuboisSAP 6abcd59
Formatting
bot-sdk-js 61198e1
Added documentation
CharlesDuboisSAP 837b23e
Added tests
CharlesDuboisSAP 21cace4
Merge branch 'refs/heads/main' into orchestration-streaming
CharlesDuboisSAP 33a92d5
Release notes
CharlesDuboisSAP 144c53b
Merge branch 'main' into orchestration-streaming
CharlesDuboisSAP c3c3938
Merge branch 'main' into orchestration-streaming
CharlesDuboisSAP 39642e5
Applied Alex's review comments
CharlesDuboisSAP 192db45
Merge branch 'main' into orchestration-streaming
CharlesDuboisSAP 8618dcd
Merge branch 'main' into orchestration-streaming
CharlesDuboisSAP 31fabfa
Reduce duplication of ResponseHandlers
CharlesDuboisSAP 8f28e41
OpenAiStreamingHandler
CharlesDuboisSAP d160e3e
fix spotbugs
CharlesDuboisSAP e00eb48
Apply suggestions from code review
newtork 5f42d9d
Formatting
bot-sdk-js fa0881b
Add Beta annotation to new public API
a-d d0fc4c2
Merge remote-tracking branch 'origin/main' into reduce-duplication
a-d 93266dc
Minor code reduction
a-d bdeaf00
Formatting
bot-sdk-js 2ec12c7
Minor change
a-d File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 changes: 21 additions & 0 deletions
21
core/src/main/java/com/sap/ai/sdk/core/commons/ClientError.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package com.sap.ai.sdk.core.commons; | ||
|
||
import com.google.common.annotations.Beta; | ||
import javax.annotation.Nullable; | ||
|
||
/** | ||
* Generic class that contains a JSON error response. | ||
* | ||
* @since 1.1.0 | ||
*/ | ||
@Beta | ||
@FunctionalInterface | ||
public interface ClientError { | ||
/** | ||
* Get the error message. | ||
* | ||
* @return The error message | ||
*/ | ||
@Nullable | ||
String getMessage(); | ||
} |
13 changes: 13 additions & 0 deletions
13
core/src/main/java/com/sap/ai/sdk/core/commons/ClientException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package com.sap.ai.sdk.core.commons; | ||
|
||
import com.google.common.annotations.Beta; | ||
import lombok.experimental.StandardException; | ||
|
||
/** | ||
* Generic exception for errors occurring when using AI SDK clients. | ||
* | ||
* @since 1.1.0 | ||
*/ | ||
@Beta | ||
@StandardException | ||
public class ClientException extends RuntimeException {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,15 @@ | ||
package com.sap.ai.sdk.orchestration; | ||
package com.sap.ai.sdk.core.commons; | ||
|
||
import static com.sap.ai.sdk.orchestration.OrchestrationClient.JACKSON; | ||
import static com.sap.ai.sdk.core.JacksonConfiguration.getDefaultObjectMapper; | ||
|
||
import com.fasterxml.jackson.core.JsonProcessingException; | ||
import com.sap.ai.sdk.orchestration.model.ErrorResponse; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import com.google.common.annotations.Beta; | ||
import io.vavr.control.Try; | ||
import java.io.IOException; | ||
import java.nio.charset.StandardCharsets; | ||
import java.util.Objects; | ||
import java.util.function.BiFunction; | ||
import javax.annotation.Nonnull; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
|
@@ -18,28 +21,80 @@ | |
import org.apache.hc.core5.http.io.HttpClientResponseHandler; | ||
import org.apache.hc.core5.http.io.entity.EntityUtils; | ||
|
||
/** | ||
* Parse incoming JSON responses and handles any errors. For internal use only. | ||
* | ||
* @param <T> The type of the response. | ||
* @param <E> The type of the exception to throw. | ||
* @since 1.1.0 | ||
*/ | ||
@Beta | ||
newtork marked this conversation as resolved.
Show resolved
Hide resolved
|
||
@Slf4j | ||
@RequiredArgsConstructor | ||
class OrchestrationResponseHandler<T> implements HttpClientResponseHandler<T> { | ||
public class ClientResponseHandler<T, E extends ClientException> | ||
implements HttpClientResponseHandler<T> { | ||
@Nonnull private final Class<T> responseType; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm marking this class as Beta, to discourage externals from using this class. Maybe we can find a way to make this class not 100% dependent on Apache HTTP Client 5 API(?) |
||
@Nonnull private final Class<? extends ClientError> errorType; | ||
@Nonnull private final BiFunction<String, Throwable, E> exceptionType; | ||
|
||
/** The parses for JSON responses, will be private once we can remove mixins */ | ||
@Nonnull public ObjectMapper JACKSON = getDefaultObjectMapper(); | ||
|
||
/** | ||
* Processes a {@link ClassicHttpResponse} and returns some value corresponding to that response. | ||
* | ||
* @param response The response to process | ||
* @return A model class instantiated from the response | ||
* @throws E in case of a problem or the connection was aborted | ||
*/ | ||
@Nonnull | ||
@Override | ||
public T handleResponse(@Nonnull final ClassicHttpResponse response) throws E { | ||
if (response.getCode() >= 300) { | ||
buildExceptionAndThrow(response); | ||
} | ||
return parseResponse(response); | ||
} | ||
|
||
// The InputStream of the HTTP entity is closed by EntityUtils.toString | ||
@SuppressWarnings("PMD.CloseResource") | ||
@Nonnull | ||
private static String getContent(@Nonnull final HttpEntity entity) { | ||
private T parseResponse(@Nonnull final ClassicHttpResponse response) throws E { | ||
final HttpEntity responseEntity = response.getEntity(); | ||
if (responseEntity == null) { | ||
throw exceptionType.apply("Response was empty.", null); | ||
} | ||
val content = getContent(responseEntity); | ||
log.debug("Parsing response from JSON response: {}", content); | ||
try { | ||
return JACKSON.readValue(content, responseType); | ||
} catch (final JsonProcessingException e) { | ||
log.error("Failed to parse the following response: {}", content); | ||
throw exceptionType.apply("Failed to parse response", e); | ||
} | ||
} | ||
|
||
@Nonnull | ||
private String getContent(@Nonnull final HttpEntity entity) { | ||
try { | ||
return EntityUtils.toString(entity, StandardCharsets.UTF_8); | ||
} catch (IOException | ParseException e) { | ||
throw new OrchestrationClientException("Failed to read response content.", e); | ||
throw exceptionType.apply("Failed to read response content.", e); | ||
} | ||
} | ||
|
||
// The InputStream of the HTTP entity is closed by EntityUtils.toString | ||
/** | ||
* Parse the error response and throw an exception. | ||
* | ||
* @param response The response to process | ||
*/ | ||
@SuppressWarnings("PMD.CloseResource") | ||
static void buildExceptionAndThrow(@Nonnull final ClassicHttpResponse response) | ||
throws OrchestrationClientException { | ||
public void buildExceptionAndThrow(@Nonnull final ClassicHttpResponse response) throws E { | ||
val exception = | ||
new OrchestrationClientException( | ||
"Request to orchestration service failed with status %s %s" | ||
.formatted(response.getCode(), response.getReasonPhrase())); | ||
exceptionType.apply( | ||
"Request failed with status %s %s" | ||
.formatted(response.getCode(), response.getReasonPhrase()), | ||
null); | ||
val entity = response.getEntity(); | ||
if (entity == null) { | ||
throw exception; | ||
|
@@ -54,9 +109,7 @@ static void buildExceptionAndThrow(@Nonnull final ClassicHttpResponse response) | |
throw exception; | ||
} | ||
|
||
log.error( | ||
"The orchestration service responded with an HTTP error and the following content: {}", | ||
content); | ||
log.error("The service responded with an HTTP error and the following content: {}", content); | ||
val contentType = ContentType.parse(entity.getContentType()); | ||
if (!ContentType.APPLICATION_JSON.isSameMimeType(contentType)) { | ||
throw exception; | ||
|
@@ -68,59 +121,19 @@ static void buildExceptionAndThrow(@Nonnull final ClassicHttpResponse response) | |
/** | ||
* Parse the error response and throw an exception. | ||
* | ||
* @param errorResponse the error response, most likely a JSON of {@link ErrorResponse}. | ||
* @param errorResponse the error response, most likely a unique JSON class. | ||
* @param baseException a base exception to add the error message to. | ||
*/ | ||
static void parseErrorAndThrow( | ||
@Nonnull final String errorResponse, | ||
@Nonnull final OrchestrationClientException baseException) | ||
throws OrchestrationClientException { | ||
val maybeError = Try.of(() -> JACKSON.readValue(errorResponse, ErrorResponse.class)); | ||
public void parseErrorAndThrow( | ||
@Nonnull final String errorResponse, @Nonnull final E baseException) throws E { | ||
val maybeError = Try.of(() -> JACKSON.readValue(errorResponse, errorType)); | ||
if (maybeError.isFailure()) { | ||
baseException.addSuppressed(maybeError.getCause()); | ||
throw baseException; | ||
} | ||
|
||
throw new OrchestrationClientException( | ||
"%s and error message: '%s'" | ||
.formatted(baseException.getMessage(), maybeError.get().getMessage())); | ||
} | ||
|
||
/** | ||
* Processes a {@link ClassicHttpResponse} and returns some value corresponding to that response. | ||
* | ||
* @param response The response to process | ||
* @return A model class instantiated from the response | ||
* @throws OrchestrationClientException in case of a problem or the connection was aborted | ||
*/ | ||
@Override | ||
public T handleResponse(@Nonnull final ClassicHttpResponse response) | ||
throws OrchestrationClientException { | ||
if (response.getCode() >= 300) { | ||
buildExceptionAndThrow(response); | ||
} | ||
val result = parseResponse(response); | ||
log.debug("Received the following response from orchestration service: {}", result); | ||
return result; | ||
} | ||
|
||
// The InputStream of the HTTP entity is closed by EntityUtils.toString | ||
@SuppressWarnings("PMD.CloseResource") | ||
@Nonnull | ||
private T parseResponse(@Nonnull final ClassicHttpResponse response) | ||
throws OrchestrationClientException { | ||
final HttpEntity responseEntity = response.getEntity(); | ||
if (responseEntity == null) { | ||
throw new OrchestrationClientException("Response from Orchestration service was empty."); | ||
} | ||
val content = getContent(responseEntity); | ||
log.debug("Parsing response from JSON response: {}", content); | ||
try { | ||
return JACKSON.readValue(content, responseType); | ||
} catch (final JsonProcessingException e) { | ||
log.error("Failed to parse the following response from orchestration service: {}", content); | ||
throw new OrchestrationClientException( | ||
"Failed to parse response from orchestration service", e); | ||
} | ||
val error = Objects.requireNonNullElse(maybeError.get().getMessage(), ""); | ||
val message = "%s and error message: '%s'".formatted(baseException.getMessage(), error); | ||
throw exceptionType.apply(message, baseException); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 2 additions & 1 deletion
3
...ls/openai/src/main/java/com/sap/ai/sdk/foundationmodels/openai/OpenAiClientException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,8 @@ | ||
package com.sap.ai.sdk.foundationmodels.openai; | ||
|
||
import com.sap.ai.sdk.core.commons.ClientException; | ||
import lombok.experimental.StandardException; | ||
|
||
/** Generic exception for errors occurring when using OpenAI foundation models. */ | ||
@StandardException | ||
public class OpenAiClientException extends RuntimeException {} | ||
public class OpenAiClientException extends ClientException {} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
orchestration tests don't count towards core coverage, therefore I separated the values into individual modules so these bad limits on the core module don't impact the other modules