-
Notifications
You must be signed in to change notification settings - Fork 25.6k
[ML] Adding response parsers for custom service #127179
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
Merged
jonathan-buttner
merged 7 commits into
elastic:main
from
jonathan-buttner:ml-custom-model-response-parsers
Apr 28, 2025
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
53af9be
Adding response parsers for custom service
jonathan-buttner 5b8c573
[CI] Auto commit changes from spotless
27d2a70
Update x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/…
jonathan-buttner fa1dd88
Refactoring to include field names in exceptions
jonathan-buttner 90d2320
Adding list entry index to error message and field names
jonathan-buttner 8685ddd
Addressing feedback for validation exception
jonathan-buttner 69c00ab
Merge branch 'main' of github.com:elastic/elasticsearch into ml-custo…
jonathan-buttner 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 hidden or 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 hidden or 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
19 changes: 19 additions & 0 deletions
19
...rc/main/java/org/elasticsearch/xpack/inference/services/custom/CustomServiceSettings.java
This file contains hidden or 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,19 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0; you may not use this file except in compliance with the Elastic License | ||
| * 2.0. | ||
| */ | ||
|
|
||
| package org.elasticsearch.xpack.inference.services.custom; | ||
|
|
||
| public class CustomServiceSettings { | ||
|
Contributor
Author
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. Not all of these values are referenced but they will be once I pull in the rest of the custom service changes in future PRs. |
||
| public static final String NAME = "custom_service_settings"; | ||
| public static final String URL = "url"; | ||
| public static final String HEADERS = "headers"; | ||
| public static final String REQUEST = "request"; | ||
| public static final String REQUEST_CONTENT = "content"; | ||
| public static final String RESPONSE = "response"; | ||
| public static final String JSON_PARSER = "json_parser"; | ||
| public static final String ERROR_PARSER = "error_parser"; | ||
| } | ||
149 changes: 149 additions & 0 deletions
149
.../org/elasticsearch/xpack/inference/services/custom/response/BaseCustomResponseParser.java
This file contains hidden or 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,149 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0; you may not use this file except in compliance with the Elastic License | ||
| * 2.0. | ||
| */ | ||
|
|
||
| package org.elasticsearch.xpack.inference.services.custom.response; | ||
|
|
||
| import org.elasticsearch.common.Strings; | ||
| import org.elasticsearch.inference.InferenceServiceResults; | ||
| import org.elasticsearch.xcontent.XContentFactory; | ||
| import org.elasticsearch.xcontent.XContentParser; | ||
| import org.elasticsearch.xcontent.XContentParserConfiguration; | ||
| import org.elasticsearch.xcontent.XContentType; | ||
| import org.elasticsearch.xpack.inference.external.http.HttpResult; | ||
|
|
||
| import java.io.IOException; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Objects; | ||
| import java.util.function.BiFunction; | ||
|
|
||
| public abstract class BaseCustomResponseParser<T extends InferenceServiceResults> implements CustomResponseParser { | ||
|
|
||
| @Override | ||
| public InferenceServiceResults parse(HttpResult response) throws IOException { | ||
| try ( | ||
| XContentParser jsonParser = XContentFactory.xContent(XContentType.JSON) | ||
| .createParser(XContentParserConfiguration.EMPTY, response.body()) | ||
| ) { | ||
| var map = jsonParser.map(); | ||
|
|
||
| return transform(map); | ||
| } | ||
| } | ||
|
|
||
| protected abstract T transform(Map<String, Object> extractedField); | ||
|
|
||
| static List<?> validateList(Object obj, String fieldName) { | ||
| validateNonNull(obj, fieldName); | ||
|
|
||
| if (obj instanceof List<?> == false) { | ||
| throw new IllegalArgumentException( | ||
| Strings.format( | ||
| "Extracted field [%s] is an invalid type, expected a list but received [%s]", | ||
| fieldName, | ||
| obj.getClass().getSimpleName() | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| return (List<?>) obj; | ||
| } | ||
|
|
||
| static void validateNonNull(Object obj, String fieldName) { | ||
| Objects.requireNonNull(obj, Strings.format("Failed to parse field [%s], extracted field was null", fieldName)); | ||
| } | ||
|
|
||
| static Map<String, Object> validateMap(Object obj, String fieldName) { | ||
| validateNonNull(obj, fieldName); | ||
|
|
||
| if (obj instanceof Map<?, ?> == false) { | ||
| throw new IllegalArgumentException( | ||
| Strings.format( | ||
| "Extracted field [%s] is an invalid type, expected a map but received [%s]", | ||
| fieldName, | ||
| obj.getClass().getSimpleName() | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| var keys = ((Map<?, ?>) obj).keySet(); | ||
| for (var key : keys) { | ||
| if (key instanceof String == false) { | ||
| throw new IllegalStateException( | ||
| Strings.format( | ||
| "Extracted field [%s] map has an invalid key type. Expected a string but received [%s]", | ||
| fieldName, | ||
| key.getClass().getSimpleName() | ||
| ) | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| @SuppressWarnings("unchecked") | ||
| var result = (Map<String, Object>) obj; | ||
| return result; | ||
| } | ||
|
|
||
| static List<Float> convertToListOfFloats(Object obj, String fieldName) { | ||
| return castList(validateList(obj, fieldName), BaseCustomResponseParser::toFloat, fieldName); | ||
| } | ||
|
|
||
| static Float toFloat(Object obj, String fieldName) { | ||
| return toNumber(obj, fieldName).floatValue(); | ||
| } | ||
|
|
||
| private static Number toNumber(Object obj, String fieldName) { | ||
| if (obj instanceof Number == false) { | ||
| throw new IllegalArgumentException( | ||
| Strings.format("Unable to convert field [%s] of type [%s] to Number", fieldName, obj.getClass().getSimpleName()) | ||
| ); | ||
| } | ||
|
|
||
| return ((Number) obj); | ||
| } | ||
|
|
||
| static List<Integer> convertToListOfIntegers(Object obj, String fieldName) { | ||
| return castList(validateList(obj, fieldName), BaseCustomResponseParser::toInteger, fieldName); | ||
| } | ||
|
|
||
| private static Integer toInteger(Object obj, String fieldName) { | ||
| return toNumber(obj, fieldName).intValue(); | ||
| } | ||
|
|
||
| static <T> List<T> castList(List<?> items, BiFunction<Object, String, T> converter, String fieldName) { | ||
| validateNonNull(items, fieldName); | ||
|
|
||
| List<T> resultList = new ArrayList<>(); | ||
| for (int i = 0; i < items.size(); i++) { | ||
| try { | ||
| resultList.add(converter.apply(items.get(i), fieldName)); | ||
| } catch (Exception e) { | ||
| throw new IllegalStateException(Strings.format("Failed to parse list entry [%d], error: %s", i, e.getMessage()), e); | ||
| } | ||
| } | ||
|
|
||
| return resultList; | ||
| } | ||
|
|
||
| static <T> T toType(Object obj, Class<T> type, String fieldName) { | ||
| validateNonNull(obj, fieldName); | ||
|
|
||
| if (type.isInstance(obj) == false) { | ||
| throw new IllegalArgumentException( | ||
| Strings.format( | ||
| "Unable to convert field [%s] of type [%s] to [%s]", | ||
| fieldName, | ||
| obj.getClass().getSimpleName(), | ||
| type.getSimpleName() | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| return type.cast(obj); | ||
| } | ||
| } |
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.
Needed these so the
assertThatcalls in the error parser tests can succeed.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.
Alternatively could
ErrorResponsebe a record rather than an classThere 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.
Yeah that would make it cleaner. At the moment
ErrorResponseis a base class and extended in a few places so we'd have to switch that to composition (I don't think we can extend a record 🤔 ).