-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathRestMLRemoteInferenceIT.java
1283 lines (1216 loc) · 58.8 KB
/
RestMLRemoteInferenceIT.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.ml.rest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.message.BasicHeader;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.opensearch.client.Response;
import org.opensearch.client.ResponseException;
import org.opensearch.ml.common.MLTaskState;
import org.opensearch.ml.utils.TestHelper;
import com.google.common.collect.ImmutableList;
public class RestMLRemoteInferenceIT extends MLCommonsRestTestCase {
final String OPENAI_KEY = System.getenv("OPENAI_KEY");
final String COHERE_KEY = System.getenv("COHERE_KEY");
final String completionModelConnectorEntity = "{\n"
+ "\"name\": \"OpenAI Connector\",\n"
+ "\"description\": \"The connector to public OpenAI model service for GPT 3.5\",\n"
+ "\"version\": 1,\n"
+ "\"client_config\": {\n"
+ " \"max_connection\": 20,\n"
+ " \"connection_timeout\": 50000,\n"
+ " \"read_timeout\": 50000\n"
+ " },\n"
+ "\"protocol\": \"http\",\n"
+ "\"parameters\": {\n"
+ " \"endpoint\": \"api.openai.com\",\n"
+ " \"auth\": \"API_Key\",\n"
+ " \"content_type\": \"application/json\",\n"
+ " \"max_tokens\": 7,\n"
+ " \"temperature\": 0,\n"
+ " \"model\": \"gpt-3.5-turbo-instruct\"\n"
+ " },\n"
+ " \"credential\": {\n"
+ " \"openAI_key\": \""
+ OPENAI_KEY
+ "\"\n"
+ " },\n"
+ " \"actions\": [\n"
+ " {"
+ " \"action_type\": \"predict\",\n"
+ " \"method\": \"POST\",\n"
+ " \"url\": \"https://${parameters.endpoint}/v1/completions\",\n"
+ " \"headers\": {\n"
+ " \"Authorization\": \"Bearer ${credential.openAI_key}\"\n"
+ " },\n"
+ " \"request_body\": \"{ \\\"model\\\": \\\"${parameters.model}\\\", \\\"prompt\\\": \\\"${parameters.prompt}\\\", \\\"max_tokens\\\": ${parameters.max_tokens}, \\\"temperature\\\": ${parameters.temperature} }\"\n"
+ " }\n"
+ " ]\n"
+ "}";
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Before
public void setup() throws IOException, InterruptedException {
disableClusterConnectorAccessControl();
// TODO Do we really need to wait this long? This adds 20s to every test case run.
// Can we instead check the cluster state and move on?
Thread.sleep(20000);
}
public void testCreate_Get_DeleteConnector() throws IOException {
Response response = createConnector(completionModelConnectorEntity);
Map responseMap = parseResponseToMap(response);
String connectorId = (String) responseMap.get("connector_id");
assertNotNull(connectorId); // Testing create connector
// Testing Get connector
response = TestHelper.makeRequest(client(), "GET", "/_plugins/_ml/connectors/" + connectorId, null, "", null);
responseMap = parseResponseToMap(response);
assertEquals("OpenAI Connector", responseMap.get("name"));
assertEquals("1", responseMap.get("version"));
assertEquals("The connector to public OpenAI model service for GPT 3.5", responseMap.get("description"));
assertEquals("http", responseMap.get("protocol"));
// Testing delete connector
response = TestHelper.makeRequest(client(), "DELETE", "/_plugins/_ml/connectors/" + connectorId, null, "", null);
responseMap = parseResponseToMap(response);
assertEquals("deleted", responseMap.get("result"));
}
private static String maskSensitiveInfo(String input) {
// Regex to remove the whole credential object and replace it with "***"
String regex = "\"credential\":\\{.*?}";
return input.replaceAll(regex, "\"credential\": \"***\"");
}
@Test
public void testMaskSensitiveInfo_withCredential() {
String input = "{\"credential\":{\"username\":\"admin\",\"password\":\"secret\"}}";
String expectedOutput = "{\"credential\": \"***\"}";
String actualOutput = maskSensitiveInfo(input);
assertEquals(expectedOutput, actualOutput);
}
@Test
public void testMaskSensitiveInfo_noCredential() {
String input = "{\"otherInfo\":\"someValue\"}";
String expectedOutput = "{\"otherInfo\":\"someValue\"}";
String actualOutput = maskSensitiveInfo(input);
assertEquals(expectedOutput, actualOutput);
}
@Test
public void testMaskSensitiveInfo_emptyInput() {
String input = "";
String expectedOutput = "";
String actualOutput = maskSensitiveInfo(input);
assertEquals(expectedOutput, actualOutput);
}
public void testSearchConnectors_beforeCreation() throws IOException {
String searchEntity = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"size\": 1000\n" + "}";
Response response = TestHelper
.makeRequest(client(), "GET", "/_plugins/_ml/connectors/_search", null, TestHelper.toHttpEntity(searchEntity), null);
Map responseMap = parseResponseToMap(response);
assertEquals(0.0, ((Map) ((Map) responseMap.get("hits")).get("total")).get("value"));
}
public void testSearchConnectors_afterCreation() throws IOException {
createConnector(completionModelConnectorEntity);
String searchEntity = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"size\": 1000\n" + "}";
Response response = TestHelper
.makeRequest(client(), "GET", "/_plugins/_ml/connectors/_search", null, TestHelper.toHttpEntity(searchEntity), null);
Map responseMap = parseResponseToMap(response);
assertEquals((Double) 1.0, (Double) ((Map) ((Map) responseMap.get("hits")).get("total")).get("value"));
}
public void testSearchRemoteModels_beforeCreation() throws IOException {
String searchEntity = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"size\": 1000\n" + "}";
Response response = TestHelper
.makeRequest(client(), "GET", "/_plugins/_ml/models/_search", null, TestHelper.toHttpEntity(searchEntity), null);
Map responseMap = parseResponseToMap(response);
assertEquals(0.0, ((Map) ((Map) responseMap.get("hits")).get("total")).get("value"));
}
public void testSearchRemoteModels_afterCreation() throws IOException {
registerRemoteModel();
String searchEntity = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"size\": 1000\n" + "}";
Response response = TestHelper
.makeRequest(client(), "GET", "/_plugins/_ml/models/_search", null, TestHelper.toHttpEntity(searchEntity), null);
Map responseMap = parseResponseToMap(response);
assertEquals(1.0, ((Map) ((Map) responseMap.get("hits")).get("total")).get("value"));
}
public void testSearchModelGroups_beforeCreation() throws IOException {
String searchEntity = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"size\": 1000\n" + "}";
Response response = TestHelper
.makeRequest(client(), "GET", "/_plugins/_ml/model_groups/_search", null, TestHelper.toHttpEntity(searchEntity), null);
Map responseMap = parseResponseToMap(response);
assertEquals(0.0, ((Map) ((Map) responseMap.get("hits")).get("total")).get("value"));
}
public void testSearchModelGroups_afterCreation() throws IOException {
registerRemoteModel();
String searchEntity = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"size\": 1000\n" + "}";
Response response = TestHelper
.makeRequest(client(), "GET", "/_plugins/_ml/model_groups/_search", null, TestHelper.toHttpEntity(searchEntity), null);
Map responseMap = parseResponseToMap(response);
assertEquals(1.0, ((Map) ((Map) responseMap.get("hits")).get("total")).get("value"));
}
public void testSearchMLTasks_beforeCreation() throws IOException {
String searchEntity = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"size\": 1000\n" + "}";
Response response = TestHelper
.makeRequest(client(), "GET", "/_plugins/_ml/tasks/_search", null, TestHelper.toHttpEntity(searchEntity), null);
Map responseMap = parseResponseToMap(response);
assertEquals(0.0, ((Map) ((Map) responseMap.get("hits")).get("total")).get("value"));
}
public void testSearchMLTasks_afterCreation() throws IOException {
registerRemoteModel();
String searchEntity = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"size\": 1000\n" + "}";
Response response = TestHelper
.makeRequest(client(), "GET", "/_plugins/_ml/tasks/_search", null, TestHelper.toHttpEntity(searchEntity), null);
Map responseMap = parseResponseToMap(response);
assertEquals(1.0, ((Map) ((Map) responseMap.get("hits")).get("total")).get("value"));
}
public void testDeployRemoteModel() throws IOException, InterruptedException {
Response response = createConnector(completionModelConnectorEntity);
Map responseMap = parseResponseToMap(response);
String connectorId = (String) responseMap.get("connector_id");
response = registerRemoteModel("openAI-GPT-3.5 completions", connectorId);
responseMap = parseResponseToMap(response);
String taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
response = getTask(taskId);
responseMap = parseResponseToMap(response);
String modelId = (String) responseMap.get("model_id");
response = deployRemoteModel(modelId);
responseMap = parseResponseToMap(response);
assertEquals("COMPLETED", responseMap.get("status"));
taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
}
public void testPredictWithAutoDeployAndTTL_RemoteModel() throws IOException, InterruptedException {
// Skip test if key is null
if (OPENAI_KEY == null) {
System.out.println("OPENAI_KEY is null");
return;
}
Response response = createConnector(completionModelConnectorEntity);
Map responseMap = parseResponseToMap(response);
String connectorId = (String) responseMap.get("connector_id");
response = registerRemoteModelWithTTLAndSkipHeapMemCheck("openAI-GPT-3.5 completions", connectorId, 1);
responseMap = parseResponseToMap(response);
String modelId = (String) responseMap.get("model_id");
String predictInput = "{\n" + " \"parameters\": {\n" + " \"prompt\": \"Say this is a test\"\n" + " }\n" + "}";
response = predictRemoteModel(modelId, predictInput);
responseMap = parseResponseToMap(response);
List responseList = (List) responseMap.get("inference_results");
responseMap = (Map) responseList.get(0);
responseList = (List) responseMap.get("output");
responseMap = (Map) responseList.get(0);
responseMap = (Map) responseMap.get("dataAsMap");
responseList = (List) responseMap.get("choices");
if (responseList == null) {
assertTrue(checkThrottlingOpenAI(responseMap));
return;
}
responseMap = (Map) responseList.get(0);
assertFalse(((String) responseMap.get("text")).isEmpty());
getModelProfile(modelId, verifyRemoteModelDeployed());
TimeUnit.SECONDS.sleep(71);
assertTrue(getModelProfile(modelId, verifyRemoteModelDeployed()).isEmpty());
}
public void testPredictRemoteModelWithInterface(String testCase, Consumer<Map> verifyResponse, Consumer<Exception> verifyException)
throws IOException,
InterruptedException {
// Skip test if key is null
if (OPENAI_KEY == null) {
return;
}
Response response = createConnector(completionModelConnectorEntity);
Map responseMap = parseResponseToMap(response);
String connectorId = (String) responseMap.get("connector_id");
response = registerRemoteModelWithInterface("openAI-GPT-3.5 completions", connectorId, testCase);
responseMap = parseResponseToMap(response);
String taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
response = getTask(taskId);
responseMap = parseResponseToMap(response);
String modelId = (String) responseMap.get("model_id");
response = deployRemoteModel(modelId);
responseMap = parseResponseToMap(response);
taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
String predictInput = "{\n" + " \"parameters\": {\n" + " \"prompt\": \"Say this is a test\"\n" + " }\n" + "}";
try {
response = predictRemoteModel(modelId, predictInput);
responseMap = parseResponseToMap(response);
verifyResponse.accept(responseMap);
} catch (Exception e) {
verifyException.accept(e);
}
}
public void testPredictRemoteModelWithCorrectInterface() throws IOException, InterruptedException {
testPredictRemoteModelWithInterface("correctInterface", (responseMap) -> {
List responseList = (List) responseMap.get("inference_results");
responseMap = (Map) responseList.get(0);
responseList = (List) responseMap.get("output");
responseMap = (Map) responseList.get(0);
responseMap = (Map) responseMap.get("dataAsMap");
responseList = (List) responseMap.get("choices");
if (responseList == null) {
assertTrue(checkThrottlingOpenAI(responseMap));
return;
}
responseMap = (Map) responseList.get(0);
assertFalse(((String) responseMap.get("text")).isEmpty());
}, null);
}
public void testPredictRemoteModelWithWrongInputInterface() throws IOException, InterruptedException {
testPredictRemoteModelWithInterface("wrongInputInterface", null, (exception) -> {
assertTrue(exception instanceof org.opensearch.client.ResponseException);
String stackTrace = ExceptionUtils.getStackTrace(exception);
assertTrue(stackTrace.contains("Error validating input schema"));
});
}
public void testPredictRemoteModelWithWrongOutputInterface() throws IOException, InterruptedException {
testPredictRemoteModelWithInterface("wrongOutputInterface", null, (exception) -> {
assertTrue(exception instanceof org.opensearch.client.ResponseException);
String stackTrace = ExceptionUtils.getStackTrace(exception);
assertTrue(stackTrace.contains("Error validating output schema"));
});
}
public void testPredictRemoteModelWithSkipValidatingMissingParameter(
String testCase,
Consumer<Map> verifyResponse,
Consumer<Exception> verifyException
) throws IOException,
InterruptedException {
// Skip test if key is null
if (OPENAI_KEY == null) {
return;
}
Response response = createConnector(this.getConnectorBodyBySkipValidatingMissingParameter(testCase));
Map responseMap = parseResponseToMap(response);
String connectorId = (String) responseMap.get("connector_id");
response = registerRemoteModelWithInterface("openAI-GPT-3.5 completions", connectorId, "correctInterface");
responseMap = parseResponseToMap(response);
String taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
response = getTask(taskId);
responseMap = parseResponseToMap(response);
String modelId = (String) responseMap.get("model_id");
response = deployRemoteModel(modelId);
responseMap = parseResponseToMap(response);
taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
String predictInput = "{\n" + " \"parameters\": {\n" + " \"prompt\": \"Say this is a ${parameters.test}\"\n" + " }\n" + "}";
try {
response = predictRemoteModel(modelId, predictInput);
responseMap = parseResponseToMap(response);
verifyResponse.accept(responseMap);
} catch (Exception e) {
verifyException.accept(e);
}
}
public void testPredictRemoteModelWithSkipValidatingMissingParameterMissing() throws IOException, InterruptedException {
testPredictRemoteModelWithSkipValidatingMissingParameter("missing", null, (exception) -> {
assertTrue(exception.getMessage().contains("Some parameter placeholder not filled in payload: test"));
});
}
public void testPredictRemoteModelWithSkipValidatingMissingParameterEnabled() throws IOException, InterruptedException {
testPredictRemoteModelWithSkipValidatingMissingParameter("enabled", (responseMap) -> {
List responseList = (List) responseMap.get("inference_results");
responseMap = (Map) responseList.get(0);
responseList = (List) responseMap.get("output");
responseMap = (Map) responseList.get(0);
responseMap = (Map) responseMap.get("dataAsMap");
responseList = (List) responseMap.get("choices");
if (responseList == null) {
assertTrue(checkThrottlingOpenAI(responseMap));
return;
}
responseMap = (Map) responseList.get(0);
assertFalse(((String) responseMap.get("text")).isEmpty());
}, null);
}
public void testPredictRemoteModelWithSkipValidatingMissingParameterDisabled() throws IOException, InterruptedException {
testPredictRemoteModelWithSkipValidatingMissingParameter("disabled", null, (exception) -> {
assertTrue(exception.getMessage().contains("Some parameter placeholder not filled in payload: test"));
});
}
public void testOpenAIChatCompletionModel() throws IOException, InterruptedException {
// Skip test if key is null
if (OPENAI_KEY == null) {
return;
}
String entity = "{\n"
+ " \"name\": \"OpenAI chat model Connector\",\n"
+ " \"description\": \"The connector to public OpenAI model service for GPT 3.5\",\n"
+ " \"version\": 1,\n"
+ "\"client_config\": {\n"
+ " \"max_connection\": 20,\n"
+ " \"connection_timeout\": 50000,\n"
+ " \"read_timeout\": 50000\n"
+ " },\n"
+ " \"protocol\": \"http\",\n"
+ " \"parameters\": {\n"
+ " \"endpoint\": \"api.openai.com\",\n"
+ " \"auth\": \"API_Key\",\n"
+ " \"content_type\": \"application/json\",\n"
+ " \"max_tokens\": 7,\n"
+ " \"temperature\": 0,\n"
+ " \"model\": \"gpt-3.5-turbo\"\n"
+ " },\n"
+ " \"credential\": {\n"
+ " \"openAI_key\": \""
+ OPENAI_KEY
+ "\"\n"
+ " },\n"
+ " \"actions\": [\n"
+ " {\n"
+ " \"action_type\": \"predict\",\n"
+ " \"method\": \"POST\",\n"
+ " \"url\": \"https://api.openai.com/v1/chat/completions\",\n"
+ " \"headers\": { \n"
+ " \"Authorization\": \"Bearer ${credential.openAI_key}\"\n"
+ " },\n"
+ " \"request_body\": \"{ \\\"model\\\": \\\"${parameters.model}\\\", \\\"messages\\\": ${parameters.messages} }\"\n"
+ " }\n"
+ " ]\n"
+ "}";
Response response = createConnector(entity);
Map responseMap = parseResponseToMap(response);
String connectorId = (String) responseMap.get("connector_id");
response = registerRemoteModel("openAI-GPT-3.5 chat model", connectorId);
responseMap = parseResponseToMap(response);
String taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
response = getTask(taskId);
responseMap = parseResponseToMap(response);
String modelId = (String) responseMap.get("model_id");
response = deployRemoteModel(modelId);
responseMap = parseResponseToMap(response);
taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
String predictInput = "{\n"
+ " \"parameters\": {\n"
+ " \"messages\": [{\"role\": \"user\", \"content\": \"Hello!\"}]\n"
+ " }\n"
+ "}";
response = predictRemoteModel(modelId, predictInput);
responseMap = parseResponseToMap(response);
// TODO handle throttling error
assertNotNull(responseMap);
response = undeployRemoteModel(modelId);
responseMap = parseResponseToMap(response);
assertTrue(responseMap.toString().contains("undeployed"));
}
@Ignore
public void testOpenAIEditsModel() throws IOException, InterruptedException {
// Skip test if key is null
if (OPENAI_KEY == null) {
return;
}
String entity = "{\n"
+ " \"name\": \"OpenAI Edit model Connector\",\n"
+ " \"description\": \"The connector to public OpenAI edit model service\",\n"
+ " \"version\": 1,\n"
+ " \"protocol\": \"http\",\n"
+ "\"client_config\": {\n"
+ " \"max_connection\": 20,\n"
+ " \"connection_timeout\": 50000,\n"
+ " \"read_timeout\": 50000\n"
+ " },\n"
+ " \"parameters\": {\n"
+ " \"endpoint\": \"api.openai.com\",\n"
+ " \"auth\": \"API_Key\",\n"
+ " \"content_type\": \"application/json\",\n"
+ " \"model\": \"gpt-4\"\n"
+ " },\n"
+ " \"credential\": {\n"
+ " \"openAI_key\": \""
+ OPENAI_KEY
+ "\"\n"
+ " },\n"
+ " \"actions\": [\n"
+ " {\n"
+ " \"action_type\": \"predict\",\n"
+ " \"method\": \"POST\",\n"
+ " \"url\": \"https://api.openai.com/v1/chat/completions\",\n"
+ " \"headers\": { \n"
+ " \"Authorization\": \"Bearer ${credential.openAI_key}\"\n"
+ " },\n"
+ " \"request_body\": \"{ \\\"model\\\": \\\"${parameters.model}\\\", \\\"messages\\\": [{\\\"role\\\": \\\"user\\\", \\\"content\\\": \\\"${parameters.input}\\\"}]}\"\n"
+ " }\n"
+ " ]\n"
+ "}";
Response response = createConnector(entity);
Map responseMap = parseResponseToMap(response);
String connectorId = (String) responseMap.get("connector_id");
response = registerRemoteModel("openAI-GPT-4 edit model", connectorId);
responseMap = parseResponseToMap(response);
String taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
response = getTask(taskId);
responseMap = parseResponseToMap(response);
String modelId = (String) responseMap.get("model_id");
response = deployRemoteModel(modelId);
responseMap = parseResponseToMap(response);
taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
String predictInput = "{\"parameters\":{\"input\":\"What day of the wek is it?\"}}";
response = predictRemoteModel(modelId, predictInput);
responseMap = parseResponseToMap(response);
List responseList = (List) responseMap.get("inference_results");
responseMap = (Map) responseList.get(0);
responseList = (List) responseMap.get("output");
responseMap = (Map) responseList.get(0);
responseMap = (Map) responseMap.get("dataAsMap");
responseList = (List) responseMap.get("choices");
if (responseList == null) {
assertTrue(checkThrottlingOpenAI(responseMap));
return;
}
responseMap = (Map) responseList.get(0);
responseMap = (Map) responseMap.get("message");
assertFalse(((String) responseMap.get("content")).isEmpty());
}
@Ignore
public void testOpenAIModerationsModel() throws IOException, InterruptedException {
// Skip test if key is null
if (OPENAI_KEY == null) {
return;
}
String entity = "{\n"
+ " \"name\": \"OpenAI moderations model Connector\",\n"
+ " \"description\": \"The connector to public OpenAI moderations model service\",\n"
+ " \"version\": 1,\n"
+ "\"client_config\": {\n"
+ " \"max_connection\": 20,\n"
+ " \"connection_timeout\": 50000,\n"
+ " \"read_timeout\": 50000\n"
+ " },\n"
+ " \"protocol\": \"http\",\n"
+ " \"parameters\": {\n"
+ " \"endpoint\": \"api.openai.com\",\n"
+ " \"auth\": \"API_Key\",\n"
+ " \"content_type\": \"application/json\",\n"
+ " \"model\": \"moderations\"\n"
+ " },\n"
+ " \"credential\": {\n"
+ " \"openAI_key\": \""
+ OPENAI_KEY
+ "\"\n"
+ " },\n"
+ " \"actions\": [\n"
+ " {\n"
+ " \"action_type\": \"predict\",\n"
+ " \"method\": \"POST\",\n"
+ " \"url\": \"https://api.openai.com/v1/moderations\",\n"
+ " \"headers\": { \n"
+ " \"Authorization\": \"Bearer ${credential.openAI_key}\"\n"
+ " },\n"
+ " \"request_body\": \"{ \\\"input\\\": \\\"${parameters.input}\\\" }\"\n"
+ " }\n"
+ " ]\n"
+ "}";
Response response = createConnector(entity);
Map responseMap = parseResponseToMap(response);
String connectorId = (String) responseMap.get("connector_id");
response = registerRemoteModel("openAI-GPT-3.5 moderations model", connectorId);
responseMap = parseResponseToMap(response);
String taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
response = getTask(taskId);
responseMap = parseResponseToMap(response);
String modelId = (String) responseMap.get("model_id");
response = deployRemoteModel(modelId);
responseMap = parseResponseToMap(response);
taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
String predictInput = "{\n" + " \"parameters\": {\n" + " \"input\": \"I want to kill them.\"\n" + " }\n" + "}";
response = predictRemoteModel(modelId, predictInput);
responseMap = parseResponseToMap(response);
List responseList = (List) responseMap.get("inference_results");
responseMap = (Map) responseList.get(0);
responseList = (List) responseMap.get("output");
responseMap = (Map) responseList.get(0);
responseMap = (Map) responseMap.get("dataAsMap");
responseList = (List) responseMap.get("results");
if (responseList == null) {
assertTrue(checkThrottlingOpenAI(responseMap));
return;
}
responseMap = (Map) responseList.get(0);
assertTrue((Boolean) responseMap.get("flagged"));
responseMap = (Map) responseMap.get("categories");
assertTrue((Boolean) responseMap.get("violence"));
}
public void testOpenAITextEmbeddingModel_UTF8() throws IOException, InterruptedException {
testOpenAITextEmbeddingModel("UTF-8", (responseMap) -> {
List responseList = (List) responseMap.get("inference_results");
responseMap = (Map) responseList.get(0);
responseList = (List) responseMap.get("output");
responseMap = (Map) responseList.get(0);
responseList = (List) responseMap.get("data");
assertFalse(responseList.isEmpty());
}, null);
}
private void testOpenAITextEmbeddingModel(String charset, Consumer<Map> verifyResponse, Consumer<Exception> verifyException)
throws IOException,
InterruptedException {
// Skip test if key is null
if (OPENAI_KEY == null) {
return;
}
String entity = "{\n"
+ " \"name\": \"OpenAI text embedding model Connector\",\n"
+ " \"description\": \"The connector to public OpenAI text embedding model service\",\n"
+ " \"version\": 1,\n"
+ "\"client_config\": {\n"
+ " \"max_connection\": 20,\n"
+ " \"connection_timeout\": 50000,\n"
+ " \"read_timeout\": 50000\n"
+ " },\n"
+ " \"protocol\": \"http\",\n"
+ " \"parameters\": {\n"
+ " \"model\": \"text-embedding-ada-002\"\n"
+ " },\n"
+ " \"credential\": {\n"
+ " \"openAI_key\": \""
+ OPENAI_KEY
+ "\"\n"
+ " },\n"
+ " \"actions\": [\n"
+ " {\n"
+ " \"action_type\": \"predict\",\n"
+ " \"method\": \"POST\",\n"
+ " \"url\": \"https://api.openai.com/v1/embeddings\",\n"
+ " \"headers\": { \n"
+ " \"Authorization\": \"Bearer ${credential.openAI_key}\"\n"
+ " },\n"
+ " \"request_body\": \"{ \\\"input\\\": ${parameters.input}, \\\"model\\\": \\\"${parameters.model}\\\" }\",\n"
+ " \"pre_process_function\": \"connector.pre_process.openai.embedding\",\n"
+ " \"post_process_function\": \"connector.post_process.openai.embedding\"\n"
+ " }\n"
+ " ]\n"
+ "}";
Response response = createConnector(entity);
Map responseMap = parseResponseToMap(response);
String connectorId = (String) responseMap.get("connector_id");
response = registerRemoteModel("openAI text embedding model", connectorId);
responseMap = parseResponseToMap(response);
String taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
response = getTask(taskId);
responseMap = parseResponseToMap(response);
String modelId = (String) responseMap.get("model_id");
response = deployRemoteModel(modelId);
responseMap = parseResponseToMap(response);
taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
String predictInput = "{\n"
+ " \"parameters\": {\n"
+ " \"input\": [\"This is a string containing Moët Hennessy\"],\n"
+ " \"charset\": \""
+ charset
+ "\"\n"
+ " }\n"
+ "}";
try {
response = predictRemoteModel(modelId, predictInput);
responseMap = parseResponseToMap(response);
verifyResponse.accept(responseMap);
} catch (Exception e) {
verifyException.accept(e);
}
}
public void testCohereGenerateTextModel() throws IOException, InterruptedException {
// Skip test if key is null
if (COHERE_KEY == null) {
return;
}
String entity = "{\n"
+ " \"name\": \"Cohere generate text model Connector\",\n"
+ " \"description\": \"The connector to public Cohere generate text model service\",\n"
+ " \"version\": 1,\n"
+ "\"client_config\": {\n"
+ " \"max_connection\": 20,\n"
+ " \"connection_timeout\": 50000,\n"
+ " \"read_timeout\": 50000\n"
+ " },\n"
+ " \"protocol\": \"http\",\n"
+ " \"parameters\": {\n"
+ " \"endpoint\": \"api.cohere.ai\",\n"
+ " \"auth\": \"API_Key\",\n"
+ " \"content_type\": \"application/json\",\n"
+ " \"max_tokens\": \"20\"\n"
+ " },\n"
+ " \"credential\": {\n"
+ " \"cohere_key\": \""
+ COHERE_KEY
+ "\"\n"
+ " },\n"
+ " \"actions\": [\n"
+ " {\n"
+ " \"action_type\": \"predict\",\n"
+ " \"method\": \"POST\",\n"
+ " \"url\": \"https://${parameters.endpoint}/v1/generate\",\n"
+ " \"headers\": { \n"
+ " \"Authorization\": \"Bearer ${credential.cohere_key}\"\n"
+ " },\n"
+ " \"request_body\": \"{ \\\"max_tokens\\\": ${parameters.max_tokens}, \\\"return_likelihoods\\\": \\\"NONE\\\", \\\"truncate\\\": \\\"END\\\", \\\"prompt\\\": \\\"${parameters.prompt}\\\" }\"\n"
+ " }\n"
+ " ]\n"
+ "}";
Response response = createConnector(entity);
Map responseMap = parseResponseToMap(response);
String connectorId = (String) responseMap.get("connector_id");
response = registerRemoteModel("cohere generate text model", connectorId);
responseMap = parseResponseToMap(response);
String taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
response = getTask(taskId);
responseMap = parseResponseToMap(response);
String modelId = (String) responseMap.get("model_id");
response = deployRemoteModel(modelId);
responseMap = parseResponseToMap(response);
taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
String predictInput = "{\n"
+ " \"parameters\": {\n"
+ " \"prompt\": \"Once upon a time in a magical land called\",\n"
+ " \"max_tokens\": 40\n"
+ " }\n"
+ "}";
response = predictRemoteModel(modelId, predictInput);
responseMap = parseResponseToMap(response);
List responseList = (List) responseMap.get("inference_results");
responseMap = (Map) responseList.get(0);
responseList = (List) responseMap.get("output");
responseMap = (Map) responseList.get(0);
responseMap = (Map) responseMap.get("dataAsMap");
responseList = (List) responseMap.get("generations");
responseMap = (Map) responseList.get(0);
assertFalse(((String) responseMap.get("text")).isEmpty());
}
public void testCohereClassifyModel() throws IOException, InterruptedException {
// Skip test if key is null
if (COHERE_KEY == null) {
return;
}
String entity = "{\n"
+ " \"name\": \"Cohere classify model Connector\",\n"
+ " \"description\": \"The connector to public Cohere classify model service\",\n"
+ " \"version\": 1,\n"
+ " \"client_config\": {\n"
+ " \"max_connection\": 20,\n"
+ " \"connection_timeout\": 50000,\n"
+ " \"read_timeout\": 50000\n"
+ " },\n"
+ " \"protocol\": \"http\",\n"
+ " \"parameters\": {\n"
+ " \"endpoint\": \"api.cohere.ai\",\n"
+ " \"auth\": \"API_Key\",\n"
+ " \"content_type\": \"application/json\",\n"
+ " \"max_tokens\": \"20\"\n"
+ " },\n"
+ " \"credential\": {\n"
+ " \"cohere_key\": \""
+ COHERE_KEY
+ "\"\n"
+ " },\n"
+ " \"actions\": [\n"
+ " {\n"
+ " \"action_type\": \"predict\",\n"
+ " \"method\": \"POST\",\n"
+ " \"url\": \"https://${parameters.endpoint}/v1/classify\",\n"
+ " \"headers\": { \n"
+ " \"Authorization\": \"Bearer ${credential.cohere_key}\"\n"
+ " },\n"
+ " \"request_body\": \"{ \\\"inputs\\\": ${parameters.inputs}, \\\"examples\\\": ${parameters.examples}, \\\"truncate\\\": \\\"END\\\" }\"\n"
+ " }\n"
+ " ]\n"
+ "}";
Response response = createConnector(entity);
Map responseMap = parseResponseToMap(response);
String connectorId = (String) responseMap.get("connector_id");
response = registerRemoteModel("cohere classify model", connectorId);
responseMap = parseResponseToMap(response);
String taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
response = getTask(taskId);
responseMap = parseResponseToMap(response);
String modelId = (String) responseMap.get("model_id");
response = deployRemoteModel(modelId);
responseMap = parseResponseToMap(response);
taskId = (String) responseMap.get("task_id");
waitForTask(taskId, MLTaskState.COMPLETED);
String predictInput = "{\n"
+ " \"parameters\": {\n"
+ " \"inputs\": [\n"
+ " \"Confirm your email address\",\n"
+ " \"hey i need u to send some $\"\n"
+ " ],\n"
+ " \"examples\": [\n"
+ " {\n"
+ " \"text\": \"Dermatologists don't like her!\",\n"
+ " \"label\": \"Spam\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"Hello, open to this?\",\n"
+ " \"label\": \"Spam\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"I need help please wire me $1000 right now\",\n"
+ " \"label\": \"Spam\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"Nice to know you ;)\",\n"
+ " \"label\": \"Spam\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"Please help me?\",\n"
+ " \"label\": \"Spam\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"Your parcel will be delivered today\",\n"
+ " \"label\": \"Not spam\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"Review changes to our Terms and Conditions\",\n"
+ " \"label\": \"Not spam\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"Weekly sync notes\",\n"
+ " \"label\": \"Not spam\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"Re: Follow up from todays meeting\",\n"
+ " \"label\": \"Not spam\"\n"
+ " },\n"
+ " {\n"
+ " \"text\": \"Pre-read for tomorrow\",\n"
+ " \"label\": \"Not spam\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ "}";
response = predictRemoteModel(modelId, predictInput);
responseMap = parseResponseToMap(response);
List responseList = (List) responseMap.get("inference_results");
responseMap = (Map) responseList.get(0);
responseList = (List) responseMap.get("output");
responseMap = (Map) responseList.get(0);
responseMap = (Map) responseMap.get("dataAsMap");
responseList = (List) responseMap.get("classifications");
assertFalse(responseList.isEmpty());
}
public static Response createConnector(String input) throws IOException {
try {
return TestHelper.makeRequest(client(), "POST", "/_plugins/_ml/connectors/_create", null, TestHelper.toHttpEntity(input), null);
} catch (ResponseException e) {
String sanitizedMessage = maskSensitiveInfo(e.getMessage());// Log sanitized message
throw new RuntimeException("Request failed: " + sanitizedMessage); // Re-throw sanitized exception
}
}
public static Response registerRemoteModel(String name, String connectorId) throws IOException {
return registerRemoteModel("remote_model_group", name, connectorId);
}
public static Response registerRemoteModel(String modelGroupName, String name, String connectorId) throws IOException {
String registerModelGroupEntity = "{\n"
+ " \"name\": \""
+ modelGroupName
+ "\",\n"
+ " \"description\": \"This is an example description\"\n"
+ "}";
Response response = TestHelper
.makeRequest(
client(),
"POST",
"/_plugins/_ml/model_groups/_register",
null,
TestHelper.toHttpEntity(registerModelGroupEntity),
null
);
Map responseMap = parseResponseToMap(response);
assertEquals((String) responseMap.get("status"), "CREATED");
String modelGroupId = (String) responseMap.get("model_group_id");
String registerModelEntity = "{\n"
+ " \"name\": \""
+ name
+ "\",\n"
+ " \"function_name\": \"remote\",\n"
+ " \"model_group_id\": \""
+ modelGroupId
+ "\",\n"
+ " \"version\": \"1.0.0\",\n"
+ " \"description\": \"test model\",\n"
+ " \"connector_id\": \""
+ connectorId
+ "\",\n"
+ " \"interface\": {\n"
+ " \"input\": {},\n"
+ " \"output\": {}\n"
+ " }\n"
+ "}";
return TestHelper
.makeRequest(client(), "POST", "/_plugins/_ml/models/_register", null, TestHelper.toHttpEntity(registerModelEntity), null);
}
public static Response registerRemoteModelWithTTLAndSkipHeapMemCheck(String name, String connectorId, int ttl) throws IOException {
String registerModelGroupEntity = "{\n"
+ " \"name\": \"remote_model_group\",\n"
+ " \"description\": \"This is an example description\"\n"
+ "}";
String updateJVMHeapThreshold = "{\"persistent\":{\"plugins.ml_commons.jvm_heap_memory_threshold\":0}}";
TestHelper.makeRequest(client(), "PUT", "/_cluster/settings", null, TestHelper.toHttpEntity(updateJVMHeapThreshold), null);
Response response = TestHelper
.makeRequest(
client(),
"POST",
"/_plugins/_ml/model_groups/_register",
null,
TestHelper.toHttpEntity(registerModelGroupEntity),
null
);
Map responseMap = parseResponseToMap(response);
assertEquals((String) responseMap.get("status"), "CREATED");
String modelGroupId = (String) responseMap.get("model_group_id");
String registerModelEntity = "{\n"
+ " \"name\": \""
+ name
+ "\",\n"
+ " \"function_name\": \"remote\",\n"
+ " \"model_group_id\": \""
+ modelGroupId
+ "\",\n"
+ " \"version\": \"1.0.0\",\n"
+ " \"description\": \"test model\",\n"
+ " \"connector_id\": \""
+ connectorId
+ "\",\n"
+ " \"deploy_setting\": "
+ " { \"model_ttl_minutes\": "
+ ttl
+ "},\n"
+ " \"interface\": {\n"
+ " \"input\": {},\n"
+ " \"output\": {}\n"
+ " }\n"
+ "}";
return TestHelper
.makeRequest(client(), "POST", "/_plugins/_ml/models/_register", null, TestHelper.toHttpEntity(registerModelEntity), null);
}
private String getConnectorBodyBySkipValidatingMissingParameter(String testCase) {
switch (testCase) {
case "missing":
return completionModelConnectorEntity;
case "enabled":
return "{\n"
+ "\"name\": \"OpenAI Connector\",\n"
+ "\"description\": \"The connector to public OpenAI model service for GPT 3.5\",\n"
+ "\"version\": 1,\n"
+ "\"client_config\": {\n"
+ " \"max_connection\": 20,\n"
+ " \"connection_timeout\": 50000,\n"
+ " \"read_timeout\": 50000\n"
+ " },\n"
+ "\"protocol\": \"http\",\n"
+ "\"parameters\": {\n"
+ " \"endpoint\": \"api.openai.com\",\n"
+ " \"auth\": \"API_Key\",\n"
+ " \"content_type\": \"application/json\",\n"
+ " \"max_tokens\": 7,\n"
+ " \"temperature\": 0,\n"
+ " \"model\": \"gpt-3.5-turbo-instruct\",\n"
+ " \"skip_validating_missing_parameters\": \"true\"\n"
+ " },\n"
+ " \"credential\": {\n"
+ " \"openAI_key\": \""
+ this.OPENAI_KEY
+ "\"\n"
+ " },\n"
+ " \"actions\": [\n"
+ " {"
+ " \"action_type\": \"predict\",\n"
+ " \"method\": \"POST\",\n"
+ " \"url\": \"https://${parameters.endpoint}/v1/completions\",\n"
+ " \"headers\": {\n"
+ " \"Authorization\": \"Bearer ${credential.openAI_key}\"\n"
+ " },\n"
+ " \"request_body\": \"{ \\\"model\\\": \\\"${parameters.model}\\\", \\\"prompt\\\": \\\"${parameters.prompt}\\\", \\\"max_tokens\\\": ${parameters.max_tokens}, \\\"temperature\\\": ${parameters.temperature} }\"\n"
+ " }\n"
+ " ]\n"
+ "}";
case "disabled":
return "{\n"