Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public class StringUtils {
}
public static final String TO_STRING_FUNCTION_NAME = ".toString()";

private static final ObjectMapper MAPPER = new ObjectMapper();
public static final ObjectMapper MAPPER = new ObjectMapper();

public static boolean isValidJsonString(String json) {
if (json == null || json.isBlank()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,41 @@ public void createPayload() {
Assert.assertEquals("{\"input\": \"test input value\"}", predictPayload);
}

@Test
public void createPayload_ExtraParams() {

String requestBody =
"{\"input\": \"${parameters.input}\", \"parameters\": {\"sparseEmbeddingFormat\": \"${parameters.sparseEmbeddingFormat}\", \"content_type\": \"${parameters.content_type}\" }}";
String expected =
"{\"input\": \"test value\", \"parameters\": {\"sparseEmbeddingFormat\": \"WORD\", \"content_type\": \"query\" }}";

HttpConnector connector = createHttpConnectorWithRequestBody(requestBody);
Map<String, String> parameters = new HashMap<>();
parameters.put("input", "test value");
parameters.put("sparseEmbeddingFormat", "WORD");
parameters.put("content_type", "query");
String predictPayload = connector.createPayload(PREDICT.name(), parameters);
connector.validatePayload(predictPayload);
Assert.assertEquals(expected, predictPayload);
}

@Test
public void createPayload_MissingParamsInvalidJson() {
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule
.expectMessage(
"Invalid payload: {\"input\": \"test value\", \"parameters\": {\"sparseEmbeddingFormat\": \"WORD\", \"content_type\": ${parameters.content_type} }}"
);
String requestBody =
"{\"input\": \"${parameters.input}\", \"parameters\": {\"sparseEmbeddingFormat\": \"${parameters.sparseEmbeddingFormat}\", \"content_type\": ${parameters.content_type} }}";
HttpConnector connector = createHttpConnectorWithRequestBody(requestBody);
Map<String, String> parameters = new HashMap<>();
parameters.put("input", "test value");
parameters.put("sparseEmbeddingFormat", "WORD");
String predictPayload = connector.createPayload(PREDICT.name(), parameters);
connector.validatePayload(predictPayload);
}

@Test
public void parseResponse_modelTensorJson() throws IOException {
HttpConnector connector = createHttpConnector();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@

package org.opensearch.ml.engine.algorithms.remote;

import static org.opensearch.ml.common.utils.StringUtils.getParameterMap;
import static org.opensearch.ml.engine.algorithms.remote.ConnectorUtils.SKIP_VALIDATE_MISSING_PARAMETERS;
import static org.opensearch.ml.engine.algorithms.remote.ConnectorUtils.escapeRemoteInferenceInputData;
import static org.opensearch.ml.engine.algorithms.remote.ConnectorUtils.processInput;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
Expand All @@ -28,11 +30,14 @@
import org.opensearch.common.collect.Tuple;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.common.util.TokenBucket;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.commons.ConfigConstants;
import org.opensearch.commons.authuser.User;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.ml.common.FunctionName;
import org.opensearch.ml.common.connector.Connector;
import org.opensearch.ml.common.connector.ConnectorAction;
Expand All @@ -42,10 +47,12 @@
import org.opensearch.ml.common.dataset.TextDocsInputDataSet;
import org.opensearch.ml.common.dataset.remote.RemoteInferenceInputDataSet;
import org.opensearch.ml.common.input.MLInput;
import org.opensearch.ml.common.input.parameter.MLAlgoParams;
import org.opensearch.ml.common.model.MLGuard;
import org.opensearch.ml.common.output.model.ModelTensorOutput;
import org.opensearch.ml.common.output.model.ModelTensors;
import org.opensearch.ml.common.transport.MLTaskResponse;
import org.opensearch.ml.common.utils.StringUtils;
import org.opensearch.script.ScriptService;
import org.opensearch.threadpool.ThreadPool;
import org.opensearch.transport.client.Client;
Expand Down Expand Up @@ -83,6 +90,7 @@ default void executeAction(String action, MLInput mlInput, ActionListener<MLTask
MLInput
.builder()
.algorithm(FunctionName.TEXT_EMBEDDING)
.parameters(mlInput.getParameters())
.inputDataset(TextDocsInputDataSet.builder().docs(textDocs).build())
.build(),
new ExecutionContext(sequence++),
Expand Down Expand Up @@ -187,6 +195,18 @@ default void preparePayloadAndInvoke(
inputParameters.putAll(((RemoteInferenceInputDataSet) inputDataset).getParameters());
}
parameters.putAll(inputParameters);

MLAlgoParams algoParams = mlInput.getParameters();
if (algoParams != null) {
try {
Map<String, String> parametersMap = getParams(mlInput);
parameters.putAll(parametersMap);
} catch (IOException e) {
actionListener.onFailure(e);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add return here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

return;
}
}

RemoteInferenceInputDataSet inputData = processInput(action, mlInput, connector, parameters, getScriptService());
if (inputData.getParameters() != null) {
parameters.putAll(inputData.getParameters());
Expand Down Expand Up @@ -227,6 +247,15 @@ && getUserRateLimiterMap().get(user.getName()) != null
}
}

static Map<String, String> getParams(MLInput mlInput) throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder();
mlInput.getParameters().toXContent(builder, ToXContent.EMPTY_PARAMS);
builder.flush();
String json = builder.toString();
Map<String, Object> tempMap = StringUtils.MAPPER.readValue(json, Map.class);
return getParameterMap(tempMap);
}

default BackoffPolicy getRetryBackoffPolicy(ConnectorClientConfig connectorClientConfig) {
switch (connectorClientConfig.getRetryBackoffPolicy()) {
case EXPONENTIAL_EQUAL_JITTER:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.opensearch.ml.common.connector.AbstractConnector.ACCESS_KEY_FIELD;
import static org.opensearch.ml.common.connector.AbstractConnector.SECRET_KEY_FIELD;
Expand All @@ -17,7 +19,9 @@
import static org.opensearch.ml.common.connector.HttpConnector.SERVICE_NAME_FIELD;
import static org.opensearch.ml.engine.algorithms.remote.ConnectorUtils.SKIP_VALIDATE_MISSING_PARAMETERS;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
Expand All @@ -30,6 +34,7 @@
import org.opensearch.common.settings.Settings;
import org.opensearch.common.util.concurrent.ThreadContext;
import org.opensearch.core.action.ActionListener;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.ingest.TestTemplateService;
import org.opensearch.ml.common.FunctionName;
import org.opensearch.ml.common.connector.AwsConnector;
Expand All @@ -39,6 +44,10 @@
import org.opensearch.ml.common.connector.RetryBackoffPolicy;
import org.opensearch.ml.common.dataset.remote.RemoteInferenceInputDataSet;
import org.opensearch.ml.common.input.MLInput;
import org.opensearch.ml.common.input.parameter.MLAlgoParams;
import org.opensearch.ml.common.input.parameter.clustering.KMeansParams;
import org.opensearch.ml.common.input.parameter.textembedding.AsymmetricTextEmbeddingParameters;
import org.opensearch.ml.common.input.parameter.textembedding.SparseEmbeddingFormat;
import org.opensearch.ml.common.output.model.ModelTensors;
import org.opensearch.ml.engine.encryptor.Encryptor;
import org.opensearch.ml.engine.encryptor.EncryptorImpl;
Expand All @@ -64,6 +73,9 @@ public class RemoteConnectorExecutorTest {
@Mock
ActionListener<Tuple<Integer, ModelTensors>> actionListener;

@Mock
private MLAlgoParams mlInputParams;

@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
Expand Down Expand Up @@ -169,4 +181,165 @@ public void executePreparePayloadAndInvoke_SkipValidateMissingParameterDefault()
);
assert exception.getMessage().contains("Some parameter placeholder not filled in payload: role");
}

@Test
public void executePreparePayloadAndInvoke_PassingParameter() {
Map<String, String> parameters = ImmutableMap.of(SERVICE_NAME_FIELD, "sagemaker", REGION_FIELD, "us-west-2");
Connector connector = getConnector(parameters);
AwsConnectorExecutor executor = getExecutor(connector);

RemoteInferenceInputDataSet inputDataSet = RemoteInferenceInputDataSet
.builder()
.parameters(Map.of("input", "You are a ${parameters.role}"))
.actionType(PREDICT)
.build();
String actionType = inputDataSet.getActionType().toString();
AsymmetricTextEmbeddingParameters inputParams = AsymmetricTextEmbeddingParameters
.builder()
.sparseEmbeddingFormat(SparseEmbeddingFormat.WORD)
.embeddingContentType(null)
.build();
MLInput mlInput = MLInput
.builder()
.algorithm(FunctionName.TEXT_EMBEDDING)
.parameters(inputParams)
.inputDataset(inputDataSet)
.build();

Exception exception = Assert
.assertThrows(
IllegalArgumentException.class,
() -> executor.preparePayloadAndInvoke(actionType, mlInput, null, actionListener)
);
assert exception.getMessage().contains("Some parameter placeholder not filled in payload: role");
}

@Test
public void executePreparePayloadAndInvoke_GetParamsIOException() throws Exception {
Map<String, String> parameters = ImmutableMap.of(SERVICE_NAME_FIELD, "sagemaker", REGION_FIELD, "us-west-2");
Connector connector = getConnector(parameters);
AwsConnectorExecutor executor = getExecutor(connector);

RemoteInferenceInputDataSet inputDataSet = RemoteInferenceInputDataSet
.builder()
.parameters(Map.of("input", "test input"))
.actionType(PREDICT)
.build();
String actionType = inputDataSet.getActionType().toString();
doThrow(new IOException("UT test IOException")).when(mlInputParams).toXContent(any(XContentBuilder.class), any());
MLInput mlInput = MLInput
.builder()
.algorithm(FunctionName.TEXT_EMBEDDING)
.parameters(mlInputParams)
.inputDataset(inputDataSet)
.build();

executor.preparePayloadAndInvoke(actionType, mlInput, null, actionListener);
verify(actionListener).onFailure(argThat(e -> e instanceof IOException && e.getMessage().contains("UT test IOException")));
}

@Test
public void executeGetParams_MissingParameter() {
Map<String, String> parameters = ImmutableMap.of(SERVICE_NAME_FIELD, "sagemaker", REGION_FIELD, "us-west-2");
Connector connector = getConnector(parameters);
AwsConnectorExecutor executor = getExecutor(connector);

RemoteInferenceInputDataSet inputDataSet = RemoteInferenceInputDataSet
.builder()
.parameters(Map.of("input", "${parameters.input}"))
.actionType(PREDICT)
.build();
String actionType = inputDataSet.getActionType().toString();
AsymmetricTextEmbeddingParameters inputParams = AsymmetricTextEmbeddingParameters
.builder()
.sparseEmbeddingFormat(SparseEmbeddingFormat.WORD)
.embeddingContentType(null)
.build();
MLInput mlInput = MLInput
.builder()
.algorithm(FunctionName.TEXT_EMBEDDING)
.parameters(inputParams)
.inputDataset(inputDataSet)
.build();

try {
Map<String, String> paramsMap = RemoteConnectorExecutor.getParams(mlInput);
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("sparse_embedding_format", "WORD");
Assert.assertEquals(expectedMap, paramsMap);
} catch (IOException e) {
e.printStackTrace();
}
}

@Test
public void executeGetParams_PassingParameter() {
Map<String, String> parameters = ImmutableMap.of(SERVICE_NAME_FIELD, "sagemaker", REGION_FIELD, "us-west-2");
Connector connector = getConnector(parameters);
AwsConnectorExecutor executor = getExecutor(connector);

RemoteInferenceInputDataSet inputDataSet = RemoteInferenceInputDataSet
.builder()
.parameters(Map.of("input", "${parameters.input}"))
.actionType(PREDICT)
.build();
String actionType = inputDataSet.getActionType().toString();
AsymmetricTextEmbeddingParameters inputParams = AsymmetricTextEmbeddingParameters
.builder()
.sparseEmbeddingFormat(SparseEmbeddingFormat.WORD)
.embeddingContentType(AsymmetricTextEmbeddingParameters.EmbeddingContentType.PASSAGE)
.build();
MLInput mlInput = MLInput
.builder()
.algorithm(FunctionName.TEXT_EMBEDDING)
.parameters(inputParams)
.inputDataset(inputDataSet)
.build();

try {
Map<String, String> paramsMap = RemoteConnectorExecutor.getParams(mlInput);
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("sparse_embedding_format", "WORD");
expectedMap.put("content_type", "PASSAGE");
Assert.assertEquals(expectedMap, paramsMap);
} catch (IOException e) {
e.printStackTrace();
}
}

@Test
public void executeGetParams_ConvertToString() {
Map<String, String> parameters = ImmutableMap.of(SERVICE_NAME_FIELD, "sagemaker", REGION_FIELD, "us-west-2");
Connector connector = getConnector(parameters);
AwsConnectorExecutor executor = getExecutor(connector);

RemoteInferenceInputDataSet inputDataSet = RemoteInferenceInputDataSet
.builder()
.parameters(Map.of("input", "${parameters.input}"))
.actionType(PREDICT)
.build();
KMeansParams inputParams = KMeansParams
.builder()
.centroids(5)
.iterations(100)
.distanceType(KMeansParams.DistanceType.EUCLIDEAN)
.build();
MLInput mlInput = MLInput
.builder()
.algorithm(FunctionName.TEXT_EMBEDDING)
.parameters(inputParams)
.inputDataset(inputDataSet)
.build();

try {
Map<String, String> paramsMap = RemoteConnectorExecutor.getParams(mlInput);
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("centroids", "5");
expectedMap.put("iterations", "100");
expectedMap.put("distance_type", "EUCLIDEAN");
Assert.assertEquals(expectedMap, paramsMap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Loading