forked from opensearch-project/skills
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreateAlertToolTests.java
398 lines (358 loc) · 16.2 KB
/
CreateAlertToolTests.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.agent.tools;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.opensearch.ml.common.utils.StringUtils.gson;
import static org.opensearch.ml.common.utils.StringUtils.isJson;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opensearch.action.admin.indices.get.GetIndexResponse;
import org.opensearch.action.admin.indices.mapping.get.GetMappingsResponse;
import org.opensearch.cluster.metadata.MappingMetadata;
import org.opensearch.common.action.ActionFuture;
import org.opensearch.core.action.ActionListener;
import org.opensearch.index.IndexNotFoundException;
import org.opensearch.ml.common.output.model.MLResultDataType;
import org.opensearch.ml.common.output.model.ModelTensor;
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.transport.prediction.MLPredictionTaskAction;
import org.opensearch.transport.client.AdminClient;
import org.opensearch.transport.client.Client;
import org.opensearch.transport.client.IndicesAdminClient;
import com.google.common.collect.ImmutableMap;
import lombok.extern.log4j.Log4j2;
@Log4j2
public class CreateAlertToolTests {
private final Client client = mock(Client.class);
@Mock
private AdminClient adminClient;
@Mock
private IndicesAdminClient indicesAdminClient;
@Mock
private GetMappingsResponse getMappingsResponse;
@Mock
private MappingMetadata mappingMetadata;
private Map<String, MappingMetadata> mockedMappings;
private Map<String, Object> indexMappings;
@Mock
private MLTaskResponse mlTaskResponse;
@Mock
private ModelTensorOutput modelTensorOutput;
@Mock
private ModelTensors modelTensors;
@Mock
private ActionFuture<GetIndexResponse> actionFuture;
@Mock
private GetIndexResponse getIndexResponse;
private final String jsonResponse = "{\"name\":\"mocked_response\"}";
private final String mockedIndexName = "mocked_index_name";
private final String mockedIndices = String.format("[%s]", mockedIndexName);
private CreateAlertTool tool;
@Before
public void setup() throws ExecutionException, InterruptedException {
MockitoAnnotations.openMocks(this);
createMappings();
when(client.admin()).thenReturn(adminClient);
when(adminClient.indices()).thenReturn(indicesAdminClient);
doAnswer(invocation -> {
ActionListener<GetIndexResponse> listener = (ActionListener<GetIndexResponse>) invocation.getArguments()[1];
listener.onResponse(getIndexResponse);
return null;
}).when(indicesAdminClient).getIndex(any(), any());
when(getIndexResponse.indices()).thenReturn(new String[] { mockedIndexName });
when(getIndexResponse.mappings()).thenReturn(mockedMappings);
when(mappingMetadata.getSourceAsMap()).thenReturn(indexMappings);
CreateAlertTool.Factory.getInstance().init(client);
tool = CreateAlertTool.Factory.getInstance().create(ImmutableMap.of("model_id", "modelId"));
assertEquals(CreateAlertTool.TYPE, tool.getName());
}
private void createMappings() {
indexMappings = new HashMap<>();
indexMappings
.put(
"properties",
ImmutableMap
.of(
"field1",
ImmutableMap.of("type", "integer"),
"field2",
ImmutableMap.of("type", "float"),
"field3",
ImmutableMap.of("type", "date")
)
);
mockedMappings = new HashMap<>();
mockedMappings.put(mockedIndexName, mappingMetadata);
}
private void initMLTensors(String response) {
Map<String, ?> modelReturns = Collections.singletonMap("response", response);
initMLTensors(modelReturns);
}
private void initMLTensorsWithoutResponse(String response) {
assert (isJson(response));
Map<String, ?> modelReturns = gson.fromJson(response, Map.class);
initMLTensors(modelReturns);
}
private void initMLTensors(Map<String, ?> modelReturns) {
ModelTensor modelTensor = new ModelTensor("tensor", new Number[0], new long[0], MLResultDataType.STRING, null, null, modelReturns);
when(modelTensors.getMlModelTensors()).thenReturn(Collections.singletonList(modelTensor));
when(modelTensorOutput.getMlModelOutputs()).thenReturn(Collections.singletonList(modelTensors));
when(mlTaskResponse.getOutput()).thenReturn(modelTensorOutput);
// call model
doAnswer(invocation -> {
ActionListener<MLTaskResponse> listener = (ActionListener<MLTaskResponse>) invocation.getArguments()[2];
listener.onResponse(mlTaskResponse);
return null;
}).when(client).execute(eq(MLPredictionTaskAction.INSTANCE), any(), any());
}
@Test
public void testTool_WithoutModelId() {
Exception exception = assertThrows(
IllegalArgumentException.class,
() -> CreateAlertTool.Factory.getInstance().create(Collections.emptyMap())
);
assertEquals("model_id cannot be null or blank.", exception.getMessage());
}
@Test
public void testTool_WithBlankModelId() {
Exception exception = assertThrows(
IllegalArgumentException.class,
() -> CreateAlertTool.Factory.getInstance().create(ImmutableMap.of("model_id", " "))
);
assertEquals("model_id cannot be null or blank.", exception.getMessage());
}
@Test
public void testTool_WithNonSupportedModelType() {
CreateAlertTool alertTool = CreateAlertTool.Factory
.getInstance()
.create(ImmutableMap.of("model_id", "modelId", "model_type", "non_supported_modelType"));
assertEquals("CLAUDE", alertTool.getModelType());
}
@Test
public void testTool_WithEmptyModelType() {
CreateAlertTool alertTool = CreateAlertTool.Factory.getInstance().create(ImmutableMap.of("model_id", "modelId", "model_type", ""));
assertEquals("CLAUDE", alertTool.getModelType());
}
@Test
public void testToolWithCustomPrompt() {
CreateAlertTool tool = CreateAlertTool.Factory
.getInstance()
.create(ImmutableMap.of("model_id", "modelId", "prompt", "custom prompt"));
assertEquals(CreateAlertTool.TYPE, tool.getName());
assertEquals("modelId", tool.getModelId());
assertEquals("custom prompt", tool.getToolPrompt());
tool
.run(
ImmutableMap.of("indices", mockedIndexName),
ActionListener.<String>wrap(response -> assertEquals(jsonResponse, response), log::info)
);
}
@Test
public void testTool() {
// test json response
initMLTensors(jsonResponse);
tool
.run(
ImmutableMap.of("indices", mockedIndices, "question", "test_question"),
ActionListener
.<String>wrap(response -> assertEquals(jsonResponse, response), e -> fail("Tool runs failed: " + e.getMessage()))
);
// test text response wrapping json
final String textResponseWithJson = String.format("RESPONSE_HEADER\n Tool output: ```json%s```, RESPONSE_FOOTER\n", jsonResponse);
initMLTensors(textResponseWithJson);
tool
.run(
ImmutableMap.of("indices", mockedIndices, "question", "test_question"),
ActionListener
.<String>wrap(response -> assertEquals(jsonResponse, response), e -> fail("Tool runs failed: " + e.getMessage()))
);
// test tensor result without a string response but a json object directly.
initMLTensorsWithoutResponse(jsonResponse);
tool
.run(
ImmutableMap.of("indices", mockedIndices, "question", "test_question"),
ActionListener
.<String>wrap(response -> assertEquals(jsonResponse, response), e -> fail("Tool runs failed: " + e.getMessage()))
);
}
@Test
public void testToolWithIndicesNotInJsonFormat() {
// test indices no in json format
initMLTensors(jsonResponse);
tool
.run(
ImmutableMap.of("indices", mockedIndexName, "question", "test_question"),
ActionListener
.<String>wrap(response -> assertEquals(jsonResponse, response), e -> fail("Tool runs failed: " + e.getMessage()))
);
tool
.run(
ImmutableMap.of("indices", mockedIndexName + "," + mockedIndexName, "question", "test_question"),
ActionListener
.<String>wrap(response -> assertEquals(jsonResponse, response), e -> fail("Tool runs failed: " + e.getMessage()))
);
}
@Test
public void testToolWithNoJsonResponse() {
String noJsonResponse = "No json response";
initMLTensors(noJsonResponse);
Exception exception = assertThrows(
IllegalArgumentException.class,
() -> tool
.run(
ImmutableMap.of("indices", mockedIndices, "question", "test_question"),
ActionListener.<String>wrap(response -> assertEquals(noJsonResponse, response), e -> {
throw new IllegalArgumentException(e.getMessage());
})
)
);
assertEquals(String.format("The response from LLM is not a json: [%s]", noJsonResponse), exception.getMessage());
final String textResponseWithJson = String.format("RESPONSE_HEADER\n Tool output: ```json%s```, RESPONSE_FOOTER\n", noJsonResponse);
initMLTensors(textResponseWithJson);
Exception exception2 = assertThrows(
IllegalArgumentException.class,
() -> tool
.run(
ImmutableMap.of("indices", mockedIndices, "question", "test_question"),
ActionListener.<String>wrap(response -> assertEquals(noJsonResponse, response), e -> {
throw new IllegalArgumentException(e.getMessage());
})
)
);
assertEquals(String.format("The response from LLM is not a json: [%s]", noJsonResponse), exception2.getMessage());
}
@Test
public void testToolWithPredictModelFailed() {
doAnswer(invocation -> {
ActionListener<MLTaskResponse> listener = (ActionListener<MLTaskResponse>) invocation.getArguments()[2];
listener.onFailure(new Exception("Failed to predict"));
return null;
}).when(client).execute(eq(MLPredictionTaskAction.INSTANCE), any(), any());
Exception exception = assertThrows(
RuntimeException.class,
() -> tool
.run(
ImmutableMap.of("indices", mockedIndices, "question", "test_question"),
ActionListener.<String>wrap(response -> assertEquals(jsonResponse, response), e -> {
throw new RuntimeException(e.getMessage());
})
)
);
assertEquals("Failed to predict", exception.getMessage());
}
@Test
public void testToolWithIllegalIndices() {
// no indices in input parameters
Exception exception = assertThrows(
RuntimeException.class,
() -> tool
.run(
ImmutableMap.of("question", "test_question"),
ActionListener.<String>wrap(response -> assertEquals(jsonResponse, response), e -> {
throw new RuntimeException(e.getMessage());
})
)
);
assertEquals(
"No indices in the input parameter. Ask user to provide index as your final answer directly without using any other tools",
exception.getMessage()
);
// empty string as indices
exception = assertThrows(
RuntimeException.class,
() -> tool
.run(
ImmutableMap.of("indices", "", "question", "test_question"),
ActionListener.<String>wrap(response -> assertEquals(jsonResponse, response), e -> {
throw new RuntimeException(e.getMessage());
})
)
);
assertEquals(
"No indices in the input parameter. Ask user to provide index as your final answer directly without using any other tools",
exception.getMessage()
);
// indices is an empty list
exception = assertThrows(
RuntimeException.class,
() -> tool
.run(
ImmutableMap.of("indices", "[]", "question", "test_question"),
ActionListener.<String>wrap(response -> assertEquals(jsonResponse, response), e -> {
throw new RuntimeException(e.getMessage());
})
)
);
assertEquals(
"The input indices is empty. Ask user to provide index as your final answer directly without using any other tools",
exception.getMessage()
);
// indices contain system index
exception = assertThrows(
RuntimeException.class,
() -> tool
.run(
ImmutableMap.of("indices", "[.kibana]", "question", "test_question"),
ActionListener.<String>wrap(response -> assertEquals(jsonResponse, response), e -> {
throw new RuntimeException(e.getMessage());
})
)
);
assertEquals(
"The provided indices [[.kibana]] contains system index, which is not allowed. Ask user to check the provided indices as your final answer without using any other.",
exception.getMessage()
);
// Cannot find provided indices in opensearch
when(getIndexResponse.indices()).thenReturn(new String[] {});
exception = assertThrows(
RuntimeException.class,
() -> tool
.run(
ImmutableMap.of("indices", "[non_existed_index]", "question", "test_question"),
ActionListener.<String>wrap(response -> assertEquals(jsonResponse, response), e -> {
throw new RuntimeException(e.getMessage());
})
)
);
assertEquals(
"Cannot find provided indices [non_existed_index]. Ask user to check the provided indices as your final answer without using any other tools",
exception.getMessage()
);
doAnswer(invocation -> {
ActionListener<GetIndexResponse> listener = (ActionListener<GetIndexResponse>) invocation.getArguments()[1];
listener.onFailure(new IndexNotFoundException("no such index"));
return null;
}).when(indicesAdminClient).getIndex(any(), any());
exception = assertThrows(
RuntimeException.class,
() -> tool
.run(
ImmutableMap.of("indices", "[non_existed_index]", "question", "test_question"),
ActionListener.<String>wrap(response -> assertEquals(jsonResponse, response), e -> {
throw new RuntimeException(e.getMessage());
})
)
);
assertEquals(
"Cannot find provided indices [non_existed_index]. Ask user to check the provided indices as your final answer without using any other tools",
exception.getMessage()
);
}
}