Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

index.test.ts 45 KB

You have to be logged in to leave a comment. Sign In
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
  1. import chalk from 'chalk';
  2. import child_process from 'child_process';
  3. import dedent from 'dedent';
  4. import * as fs from 'fs';
  5. import * as path from 'path';
  6. import Stream from 'stream';
  7. import { clearCache, disableCache, enableCache } from '../../src/cache';
  8. import { importModule } from '../../src/esm';
  9. import logger from '../../src/logger';
  10. import { loadApiProvider, loadApiProviders } from '../../src/providers';
  11. import { AnthropicCompletionProvider } from '../../src/providers/anthropic';
  12. import { AzureChatCompletionProvider, AzureCompletionProvider } from '../../src/providers/azure';
  13. import { AwsBedrockCompletionProvider } from '../../src/providers/bedrock';
  14. import {
  15. CloudflareAiChatCompletionProvider,
  16. CloudflareAiCompletionProvider,
  17. CloudflareAiEmbeddingProvider,
  18. type ICloudflareProviderBaseConfig,
  19. type ICloudflareTextGenerationResponse,
  20. type ICloudflareEmbeddingResponse,
  21. type ICloudflareProviderConfig,
  22. } from '../../src/providers/cloudflare-ai';
  23. import {
  24. HuggingfaceTextGenerationProvider,
  25. HuggingfaceFeatureExtractionProvider,
  26. HuggingfaceTextClassificationProvider,
  27. } from '../../src/providers/huggingface';
  28. import { LlamaProvider } from '../../src/providers/llama';
  29. import {
  30. OllamaChatProvider,
  31. OllamaCompletionProvider,
  32. OllamaEmbeddingProvider,
  33. } from '../../src/providers/ollama';
  34. import { OpenAiAssistantProvider } from '../../src/providers/openai/assistant';
  35. import { OpenAiChatCompletionProvider } from '../../src/providers/openai/chat';
  36. import { OpenAiCompletionProvider } from '../../src/providers/openai/completion';
  37. import { OpenAiEmbeddingProvider } from '../../src/providers/openai/embedding';
  38. import { PythonProvider } from '../../src/providers/pythonCompletion';
  39. import {
  40. ReplicateImageProvider,
  41. ReplicateModerationProvider,
  42. ReplicateProvider,
  43. } from '../../src/providers/replicate';
  44. import { ScriptCompletionProvider } from '../../src/providers/scriptCompletion';
  45. import { VertexChatProvider, VertexEmbeddingProvider } from '../../src/providers/vertex';
  46. import { VoyageEmbeddingProvider } from '../../src/providers/voyage';
  47. import { WebhookProvider } from '../../src/providers/webhook';
  48. import RedteamGoatProvider from '../../src/redteam/providers/goat';
  49. import RedteamIterativeProvider from '../../src/redteam/providers/iterative';
  50. import RedteamImageIterativeProvider from '../../src/redteam/providers/iterativeImage';
  51. import RedteamIterativeTreeProvider from '../../src/redteam/providers/iterativeTree';
  52. import type { ProviderOptionsMap, ProviderFunction } from '../../src/types';
  53. jest.mock('fs', () => ({
  54. readFileSync: jest.fn(),
  55. writeFileSync: jest.fn(),
  56. statSync: jest.fn(),
  57. readdirSync: jest.fn(),
  58. existsSync: jest.fn(),
  59. mkdirSync: jest.fn(),
  60. promises: {
  61. readFile: jest.fn(),
  62. },
  63. }));
  64. jest.mock('glob', () => ({
  65. globSync: jest.fn(),
  66. }));
  67. jest.mock('proxy-agent', () => ({
  68. ProxyAgent: jest.fn().mockImplementation(() => ({})),
  69. }));
  70. jest.mock('../../src/esm', () => ({
  71. ...jest.requireActual('../../src/esm'),
  72. importModule: jest.fn(),
  73. }));
  74. jest.mock('fs', () => ({
  75. readFileSync: jest.fn(),
  76. existsSync: jest.fn(),
  77. mkdirSync: jest.fn(),
  78. }));
  79. jest.mock('glob', () => ({
  80. globSync: jest.fn(),
  81. }));
  82. jest.mock('../../src/database', () => ({
  83. getDb: jest.fn(),
  84. }));
  85. jest.mock('../../src/redteam/remoteGeneration', () => ({
  86. shouldGenerateRemote: jest.fn().mockReturnValue(false),
  87. neverGenerateRemote: jest.fn().mockReturnValue(false),
  88. getRemoteGenerationUrl: jest.fn().mockReturnValue('http://test-url'),
  89. }));
  90. jest.mock('../../src/providers/websocket');
  91. const mockFetch = jest.mocked(jest.fn());
  92. global.fetch = mockFetch;
  93. const defaultMockResponse = {
  94. status: 200,
  95. statusText: 'OK',
  96. headers: {
  97. get: jest.fn().mockReturnValue(null),
  98. entries: jest.fn().mockReturnValue([]),
  99. },
  100. };
  101. // Dynamic import
  102. jest.mock('../../src/providers/adaline.gateway', () => ({
  103. AdalineGatewayChatProvider: jest.fn().mockImplementation((providerName, modelName) => ({
  104. id: () => `adaline:${providerName}:chat:${modelName}`,
  105. constructor: { name: 'AdalineGatewayChatProvider' },
  106. })),
  107. AdalineGatewayEmbeddingProvider: jest.fn().mockImplementation((providerName, modelName) => ({
  108. id: () => `adaline:${providerName}:embedding:${modelName}`,
  109. constructor: { name: 'AdalineGatewayEmbeddingProvider' },
  110. })),
  111. }));
  112. describe('call provider apis', () => {
  113. afterEach(async () => {
  114. jest.clearAllMocks();
  115. await clearCache();
  116. });
  117. it('AzureOpenAiCompletionProvider callApi', async () => {
  118. const mockResponse = {
  119. ...defaultMockResponse,
  120. text: jest.fn().mockResolvedValue(
  121. JSON.stringify({
  122. choices: [{ text: 'Test output' }],
  123. usage: { total_tokens: 10, prompt_tokens: 5, completion_tokens: 5 },
  124. }),
  125. ),
  126. };
  127. mockFetch.mockResolvedValue(mockResponse);
  128. const provider = new AzureCompletionProvider('text-davinci-003');
  129. const result = await provider.callApi('Test prompt');
  130. expect(mockFetch).toHaveBeenCalledTimes(1);
  131. expect(result.output).toBe('Test output');
  132. expect(result.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5 });
  133. });
  134. it('AzureOpenAiChatCompletionProvider callApi', async () => {
  135. const mockResponse = {
  136. ...defaultMockResponse,
  137. text: jest.fn().mockResolvedValue(
  138. JSON.stringify({
  139. choices: [{ message: { content: 'Test output' } }],
  140. usage: { total_tokens: 10, prompt_tokens: 5, completion_tokens: 5 },
  141. }),
  142. ),
  143. };
  144. mockFetch.mockResolvedValue(mockResponse);
  145. const provider = new AzureChatCompletionProvider('gpt-4o-mini');
  146. const result = await provider.callApi(
  147. JSON.stringify([{ role: 'user', content: 'Test prompt' }]),
  148. );
  149. expect(mockFetch).toHaveBeenCalledTimes(1);
  150. expect(result.output).toBe('Test output');
  151. expect(result.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5 });
  152. });
  153. it('AzureOpenAiChatCompletionProvider callApi with dataSources', async () => {
  154. const dataSources = [
  155. {
  156. type: 'AzureCognitiveSearch',
  157. endpoint: 'https://search.windows.net',
  158. indexName: 'search-test',
  159. semanticConfiguration: 'default',
  160. queryType: 'vectorSimpleHybrid',
  161. },
  162. ];
  163. const mockResponse = {
  164. ...defaultMockResponse,
  165. text: jest.fn().mockResolvedValue(
  166. JSON.stringify({
  167. choices: [
  168. { message: { role: 'system', content: 'System prompt' } },
  169. { message: { role: 'user', content: 'Test prompt' } },
  170. { message: { role: 'assistant', content: 'Test response' } },
  171. ],
  172. usage: { total_tokens: 10, prompt_tokens: 5, completion_tokens: 5 },
  173. }),
  174. ),
  175. };
  176. mockFetch.mockResolvedValue(mockResponse);
  177. const provider = new AzureChatCompletionProvider('gpt-4o-mini', {
  178. config: { dataSources },
  179. });
  180. const result = await provider.callApi(
  181. JSON.stringify([
  182. { role: 'system', content: 'System prompt' },
  183. { role: 'user', content: 'Test prompt' },
  184. ]),
  185. );
  186. expect(mockFetch).toHaveBeenCalledTimes(1);
  187. expect(result.output).toBe('Test response');
  188. expect(result.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5 });
  189. });
  190. it('AzureOpenAiChatCompletionProvider callApi with cache disabled', async () => {
  191. disableCache();
  192. const mockResponse = {
  193. ...defaultMockResponse,
  194. text: jest.fn().mockResolvedValue(
  195. JSON.stringify({
  196. choices: [{ message: { content: 'Test output' } }],
  197. usage: { total_tokens: 10, prompt_tokens: 5, completion_tokens: 5 },
  198. }),
  199. ),
  200. };
  201. mockFetch.mockResolvedValue(mockResponse);
  202. const provider = new AzureChatCompletionProvider('gpt-4o-mini');
  203. const result = await provider.callApi(
  204. JSON.stringify([{ role: 'user', content: 'Test prompt' }]),
  205. );
  206. expect(mockFetch).toHaveBeenCalledTimes(1);
  207. expect(result.output).toBe('Test output');
  208. expect(result.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5 });
  209. enableCache();
  210. });
  211. it('LlamaProvider callApi', async () => {
  212. const mockResponse = {
  213. ...defaultMockResponse,
  214. text: jest.fn().mockResolvedValue(
  215. JSON.stringify({
  216. content: 'Test output',
  217. }),
  218. ),
  219. };
  220. mockFetch.mockResolvedValue(mockResponse);
  221. const provider = new LlamaProvider('llama.cpp');
  222. const result = await provider.callApi('Test prompt');
  223. expect(mockFetch).toHaveBeenCalledTimes(1);
  224. expect(result.output).toBe('Test output');
  225. });
  226. it('OllamaCompletionProvider callApi', async () => {
  227. const mockResponse = {
  228. ...defaultMockResponse,
  229. text: jest.fn()
  230. .mockResolvedValue(`{"model":"llama2:13b","created_at":"2023-08-08T21:50:34.898068Z","response":"Gre","done":false}
  231. {"model":"llama2:13b","created_at":"2023-08-08T21:50:34.929199Z","response":"at","done":false}
  232. {"model":"llama2:13b","created_at":"2023-08-08T21:50:34.959989Z","response":" question","done":false}
  233. {"model":"llama2:13b","created_at":"2023-08-08T21:50:34.992117Z","response":"!","done":false}
  234. {"model":"llama2:13b","created_at":"2023-08-08T21:50:35.023658Z","response":" The","done":false}
  235. {"model":"llama2:13b","created_at":"2023-08-08T21:50:35.0551Z","response":" sky","done":false}
  236. {"model":"llama2:13b","created_at":"2023-08-08T21:50:35.086103Z","response":" appears","done":false}
  237. {"model":"llama2:13b","created_at":"2023-08-08T21:50:35.117166Z","response":" blue","done":false}
  238. {"model":"llama2:13b","created_at":"2023-08-08T21:50:41.695299Z","done":true,"context":[1,29871,1,13,9314],"total_duration":10411943458,"load_duration":458333,"sample_count":217,"sample_duration":154566000,"prompt_eval_count":11,"prompt_eval_duration":3334582000,"eval_count":216,"eval_duration":6905134000}`),
  239. };
  240. mockFetch.mockResolvedValue(mockResponse);
  241. const provider = new OllamaCompletionProvider('llama');
  242. const result = await provider.callApi('Test prompt');
  243. expect(mockFetch).toHaveBeenCalledTimes(1);
  244. expect(result.output).toBe('Great question! The sky appears blue');
  245. });
  246. it('OllamaChatProvider callApi', async () => {
  247. const mockResponse = {
  248. ...defaultMockResponse,
  249. text: jest.fn()
  250. .mockResolvedValue(`{"model":"orca-mini","created_at":"2023-12-16T01:46:19.263682972Z","message":{"role":"assistant","content":" Because","images":null},"done":false}
  251. {"model":"orca-mini","created_at":"2023-12-16T01:46:19.275143974Z","message":{"role":"assistant","content":" of","images":null},"done":false}
  252. {"model":"orca-mini","created_at":"2023-12-16T01:46:19.288137727Z","message":{"role":"assistant","content":" Ray","images":null},"done":false}
  253. {"model":"orca-mini","created_at":"2023-12-16T01:46:19.301139709Z","message":{"role":"assistant","content":"leigh","images":null},"done":false}
  254. {"model":"orca-mini","created_at":"2023-12-16T01:46:19.311364699Z","message":{"role":"assistant","content":" scattering","images":null},"done":false}
  255. {"model":"orca-mini","created_at":"2023-12-16T01:46:19.324309782Z","message":{"role":"assistant","content":".","images":null},"done":false}
  256. {"model":"orca-mini","created_at":"2023-12-16T01:46:19.337165395Z","done":true,"total_duration":1486443841,"load_duration":1280794143,"prompt_eval_count":35,"prompt_eval_duration":142384000,"eval_count":6,"eval_duration":61912000}`),
  257. };
  258. mockFetch.mockResolvedValue(mockResponse);
  259. const provider = new OllamaChatProvider('llama');
  260. const result = await provider.callApi('Test prompt');
  261. expect(mockFetch).toHaveBeenCalledTimes(1);
  262. expect(result.output).toBe(' Because of Rayleigh scattering.');
  263. });
  264. it('WebhookProvider callApi', async () => {
  265. const mockResponse = {
  266. ...defaultMockResponse,
  267. text: jest.fn().mockResolvedValue(
  268. JSON.stringify({
  269. output: 'Test output',
  270. }),
  271. ),
  272. };
  273. mockFetch.mockResolvedValue(mockResponse);
  274. const provider = new WebhookProvider('http://example.com/webhook');
  275. const result = await provider.callApi('Test prompt');
  276. expect(mockFetch).toHaveBeenCalledTimes(1);
  277. expect(result.output).toBe('Test output');
  278. });
  279. describe.each([
  280. ['Array format', [{ generated_text: 'Test output' }]], // Array format
  281. ['Object format', { generated_text: 'Test output' }], // Object format
  282. ])('HuggingfaceTextGenerationProvider callApi with %s', (format, mockedData) => {
  283. it('returns expected output', async () => {
  284. const mockResponse = {
  285. ...defaultMockResponse,
  286. text: jest.fn().mockResolvedValue(JSON.stringify(mockedData)),
  287. };
  288. mockFetch.mockResolvedValue(mockResponse);
  289. const provider = new HuggingfaceTextGenerationProvider('gpt2');
  290. const result = await provider.callApi('Test prompt');
  291. expect(mockFetch).toHaveBeenCalledTimes(1);
  292. expect(result.output).toBe('Test output');
  293. });
  294. });
  295. it('HuggingfaceFeatureExtractionProvider callEmbeddingApi', async () => {
  296. const mockResponse = {
  297. ...defaultMockResponse,
  298. text: jest.fn().mockResolvedValue(JSON.stringify([0.1, 0.2, 0.3, 0.4, 0.5])),
  299. };
  300. mockFetch.mockResolvedValue(mockResponse);
  301. const provider = new HuggingfaceFeatureExtractionProvider('distilbert-base-uncased');
  302. const result = await provider.callEmbeddingApi('Test text');
  303. expect(mockFetch).toHaveBeenCalledTimes(1);
  304. expect(result.embedding).toEqual([0.1, 0.2, 0.3, 0.4, 0.5]);
  305. });
  306. it('HuggingfaceTextClassificationProvider callClassificationApi', async () => {
  307. const mockClassification = [
  308. [
  309. {
  310. label: 'nothate',
  311. score: 0.9,
  312. },
  313. {
  314. label: 'hate',
  315. score: 0.1,
  316. },
  317. ],
  318. ];
  319. const mockResponse = {
  320. ...defaultMockResponse,
  321. text: jest.fn().mockResolvedValue(JSON.stringify(mockClassification)),
  322. };
  323. mockFetch.mockResolvedValue(mockResponse);
  324. const provider = new HuggingfaceTextClassificationProvider('foo');
  325. const result = await provider.callClassificationApi('Test text');
  326. expect(mockFetch).toHaveBeenCalledTimes(1);
  327. expect(result.classification).toEqual({
  328. nothate: 0.9,
  329. hate: 0.1,
  330. });
  331. });
  332. describe('CloudflareAi', () => {
  333. beforeAll(() => {
  334. enableCache();
  335. });
  336. const cloudflareMinimumConfig: Required<
  337. Pick<ICloudflareProviderBaseConfig, 'accountId' | 'apiKey'>
  338. > = {
  339. accountId: 'testAccountId',
  340. apiKey: 'testApiKey',
  341. };
  342. const testModelName = '@cf/meta/llama-2-7b-chat-fp16';
  343. // Token usage is not implemented for cloudflare so this is the default that
  344. // is returned
  345. const tokenUsageDefaultResponse = {
  346. total: undefined,
  347. prompt: undefined,
  348. completion: undefined,
  349. };
  350. describe('CloudflareAiCompletionProvider', () => {
  351. it('callApi with caching enabled', async () => {
  352. const PROMPT = 'Test prompt for caching';
  353. const provider = new CloudflareAiCompletionProvider(testModelName, {
  354. config: cloudflareMinimumConfig,
  355. });
  356. const responsePayload: ICloudflareTextGenerationResponse = {
  357. success: true,
  358. errors: [],
  359. messages: [],
  360. result: {
  361. response: 'Test text output',
  362. },
  363. };
  364. const mockResponse = {
  365. ...defaultMockResponse,
  366. text: jest.fn().mockResolvedValue(JSON.stringify(responsePayload)),
  367. ok: true,
  368. };
  369. mockFetch.mockResolvedValue(mockResponse);
  370. const result = await provider.callApi(PROMPT);
  371. expect(mockFetch).toHaveBeenCalledTimes(1);
  372. expect(result.output).toBe(responsePayload.result.response);
  373. expect(result.tokenUsage).toEqual(tokenUsageDefaultResponse);
  374. const resultFromCache = await provider.callApi(PROMPT);
  375. expect(mockFetch).toHaveBeenCalledTimes(1);
  376. expect(resultFromCache.output).toBe(responsePayload.result.response);
  377. expect(resultFromCache.tokenUsage).toEqual(tokenUsageDefaultResponse);
  378. });
  379. it('callApi with caching disabled', async () => {
  380. const PROMPT = 'test prompt without caching';
  381. try {
  382. disableCache();
  383. const provider = new CloudflareAiCompletionProvider(testModelName, {
  384. config: cloudflareMinimumConfig,
  385. });
  386. const responsePayload: ICloudflareTextGenerationResponse = {
  387. success: true,
  388. errors: [],
  389. messages: [],
  390. result: {
  391. response: 'Test text output',
  392. },
  393. };
  394. const mockResponse = {
  395. ...defaultMockResponse,
  396. text: jest.fn().mockResolvedValue(JSON.stringify(responsePayload)),
  397. ok: true,
  398. };
  399. mockFetch.mockResolvedValue(mockResponse);
  400. const result = await provider.callApi(PROMPT);
  401. expect(mockFetch).toHaveBeenCalledTimes(1);
  402. expect(result.output).toBe(responsePayload.result.response);
  403. expect(result.tokenUsage).toEqual(tokenUsageDefaultResponse);
  404. const resultFromCache = await provider.callApi(PROMPT);
  405. expect(mockFetch).toHaveBeenCalledTimes(2);
  406. expect(resultFromCache.output).toBe(responsePayload.result.response);
  407. expect(resultFromCache.tokenUsage).toEqual(tokenUsageDefaultResponse);
  408. } finally {
  409. enableCache();
  410. }
  411. });
  412. it('callApi handles cloudflare error properly', async () => {
  413. const PROMPT = 'Test prompt for caching';
  414. const provider = new CloudflareAiCompletionProvider(testModelName, {
  415. config: cloudflareMinimumConfig,
  416. });
  417. const responsePayload: ICloudflareTextGenerationResponse = {
  418. success: false,
  419. errors: ['Some error occurred'],
  420. messages: [],
  421. };
  422. const mockResponse = {
  423. ...defaultMockResponse,
  424. text: jest.fn().mockResolvedValue(JSON.stringify(responsePayload)),
  425. ok: true,
  426. };
  427. mockFetch.mockResolvedValue(mockResponse);
  428. const result = await provider.callApi(PROMPT);
  429. expect(result.error).toContain(JSON.stringify(responsePayload.errors));
  430. });
  431. it('Can be invoked with custom configuration', async () => {
  432. const cloudflareChatConfig: ICloudflareProviderConfig = {
  433. accountId: 'MADE_UP_ACCOUNT_ID',
  434. apiKey: 'MADE_UP_API_KEY',
  435. frequency_penalty: 10,
  436. };
  437. const rawProviderConfigs: ProviderOptionsMap[] = [
  438. {
  439. [`cloudflare-ai:completion:${testModelName}`]: {
  440. config: cloudflareChatConfig,
  441. },
  442. },
  443. ];
  444. const providers = await loadApiProviders(rawProviderConfigs);
  445. expect(providers).toHaveLength(1);
  446. expect(providers[0]).toBeInstanceOf(CloudflareAiCompletionProvider);
  447. const cfProvider = providers[0] as CloudflareAiCompletionProvider;
  448. expect(cfProvider.config).toEqual(cloudflareChatConfig);
  449. const PROMPT = 'Test prompt for custom configuration';
  450. const responsePayload: ICloudflareTextGenerationResponse = {
  451. success: true,
  452. errors: [],
  453. messages: [],
  454. result: {
  455. response: 'Test text output',
  456. },
  457. };
  458. const mockResponse = {
  459. ...defaultMockResponse,
  460. text: jest.fn().mockResolvedValue(JSON.stringify(responsePayload)),
  461. ok: true,
  462. };
  463. mockFetch.mockResolvedValue(mockResponse);
  464. await cfProvider.callApi(PROMPT);
  465. expect(mockFetch).toHaveBeenCalledTimes(1);
  466. expect(mockFetch).toHaveBeenCalledWith(
  467. expect.any(String),
  468. expect.objectContaining({
  469. body: expect.stringMatching(`"prompt":"${PROMPT}"`),
  470. }),
  471. );
  472. const {
  473. accountId: _accountId,
  474. apiKey: _apiKey,
  475. ...passThroughConfig
  476. } = cloudflareChatConfig;
  477. const { prompt: _prompt, ...bodyWithoutPrompt } = JSON.parse(
  478. jest.mocked(mockFetch).mock.calls[0][1].body as string,
  479. );
  480. expect(bodyWithoutPrompt).toEqual(passThroughConfig);
  481. });
  482. });
  483. describe('CloudflareAiChatCompletionProvider', () => {
  484. it('Should handle chat provider', async () => {
  485. const provider = new CloudflareAiChatCompletionProvider(testModelName, {
  486. config: cloudflareMinimumConfig,
  487. });
  488. const responsePayload: ICloudflareTextGenerationResponse = {
  489. success: true,
  490. errors: [],
  491. messages: [],
  492. result: {
  493. response: 'Test text output',
  494. },
  495. };
  496. const mockResponse = {
  497. ...defaultMockResponse,
  498. text: jest.fn().mockResolvedValue(JSON.stringify(responsePayload)),
  499. ok: true,
  500. };
  501. mockFetch.mockResolvedValue(mockResponse);
  502. const result = await provider.callApi('Test chat prompt');
  503. expect(mockFetch).toHaveBeenCalledTimes(1);
  504. expect(result.output).toBe(responsePayload.result.response);
  505. expect(result.tokenUsage).toEqual(tokenUsageDefaultResponse);
  506. });
  507. });
  508. describe('CloudflareAiEmbeddingProvider', () => {
  509. it('Should return embeddings in the proper format', async () => {
  510. const provider = new CloudflareAiEmbeddingProvider(testModelName, {
  511. config: cloudflareMinimumConfig,
  512. });
  513. const responsePayload: ICloudflareEmbeddingResponse = {
  514. success: true,
  515. errors: [],
  516. messages: [],
  517. result: {
  518. shape: [1, 3],
  519. data: [[0.02055364102125168, -0.013749595731496811, 0.0024201320484280586]],
  520. },
  521. };
  522. const mockResponse = {
  523. ...defaultMockResponse,
  524. text: jest.fn().mockResolvedValue(JSON.stringify(responsePayload)),
  525. ok: true,
  526. };
  527. mockFetch.mockResolvedValue(mockResponse);
  528. const result = await provider.callEmbeddingApi('Create embeddings from this');
  529. expect(mockFetch).toHaveBeenCalledTimes(1);
  530. expect(result.embedding).toEqual(responsePayload.result.data[0]);
  531. expect(result.tokenUsage).toEqual(tokenUsageDefaultResponse);
  532. });
  533. });
  534. });
  535. describe.each([
  536. ['python rag.py', 'python', ['rag.py']],
  537. ['echo "hello world"', 'echo', ['hello world']],
  538. ['./path/to/file.py run', './path/to/file.py', ['run']],
  539. ['"/Path/To/My File.py"', '/Path/To/My File.py', []],
  540. ])('ScriptCompletionProvider callApi with script %s', (script, inputFile, inputArgs) => {
  541. it('returns expected output', async () => {
  542. const mockResponse = 'Test script output';
  543. const mockChildProcess = {
  544. stdout: new Stream.Readable(),
  545. stderr: new Stream.Readable(),
  546. } as child_process.ChildProcess;
  547. const execFileSpy = jest
  548. .spyOn(child_process, 'execFile')
  549. .mockImplementation(
  550. (
  551. file: string,
  552. args: readonly string[] | null | undefined,
  553. options: child_process.ExecFileOptions | null | undefined,
  554. callback?:
  555. | null
  556. | ((
  557. error: child_process.ExecFileException | null,
  558. stdout: string | Buffer,
  559. stderr: string | Buffer,
  560. ) => void),
  561. ) => {
  562. process.nextTick(
  563. () => callback && callback(null, Buffer.from(mockResponse), Buffer.from('')),
  564. );
  565. return mockChildProcess;
  566. },
  567. );
  568. const provider = new ScriptCompletionProvider(script, {
  569. config: {
  570. some_config_val: 42,
  571. },
  572. });
  573. const result = await provider.callApi('Test prompt', {
  574. prompt: {
  575. label: 'Test prompt',
  576. raw: 'Test prompt',
  577. },
  578. vars: {
  579. var1: 'value 1',
  580. var2: 'value 2 "with some double "quotes""',
  581. },
  582. });
  583. expect(result.output).toBe(mockResponse);
  584. expect(execFileSpy).toHaveBeenCalledTimes(1);
  585. expect(execFileSpy).toHaveBeenCalledWith(
  586. expect.stringContaining(inputFile),
  587. expect.arrayContaining(
  588. inputArgs.concat([
  589. 'Test prompt',
  590. '{"config":{"some_config_val":42}}',
  591. '{"prompt":{"label":"Test prompt","raw":"Test prompt"},"vars":{"var1":"value 1","var2":"value 2 \\"with some double \\"quotes\\"\\""}}',
  592. ]),
  593. ),
  594. expect.any(Object),
  595. expect.any(Function),
  596. );
  597. jest.restoreAllMocks();
  598. });
  599. });
  600. });
  601. describe('loadApiProvider', () => {
  602. beforeEach(() => {
  603. jest.clearAllMocks();
  604. });
  605. it('loadApiProvider with yaml filepath', async () => {
  606. const mockYamlContent = dedent`
  607. id: 'openai:gpt-4'
  608. config:
  609. key: 'value'`;
  610. const mockReadFileSync = jest.mocked(fs.readFileSync);
  611. mockReadFileSync.mockReturnValue(mockYamlContent);
  612. const provider = await loadApiProvider('file://path/to/mock-provider-file.yaml');
  613. expect(provider.id()).toBe('openai:gpt-4');
  614. expect(mockReadFileSync).toHaveBeenCalledWith(
  615. expect.stringMatching(/path[\\\/]to[\\\/]mock-provider-file\.yaml/),
  616. 'utf8',
  617. );
  618. });
  619. it('loadApiProvider with json filepath', async () => {
  620. const mockJsonContent = `{
  621. "id": "openai:gpt-4",
  622. "config": {
  623. "key": "value"
  624. }
  625. }`;
  626. jest.mocked(fs.readFileSync).mockReturnValueOnce(mockJsonContent);
  627. const provider = await loadApiProvider('file://path/to/mock-provider-file.json');
  628. expect(provider.id()).toBe('openai:gpt-4');
  629. expect(fs.readFileSync).toHaveBeenCalledWith(
  630. expect.stringMatching(/path[\\\/]to[\\\/]mock-provider-file\.json/),
  631. 'utf8',
  632. );
  633. });
  634. it('loadApiProvider with openai:chat', async () => {
  635. const provider = await loadApiProvider('openai:chat');
  636. expect(provider).toBeInstanceOf(OpenAiChatCompletionProvider);
  637. });
  638. it('loadApiProvider with openai:completion', async () => {
  639. const provider = await loadApiProvider('openai:completion');
  640. expect(provider).toBeInstanceOf(OpenAiCompletionProvider);
  641. });
  642. it('loadApiProvider with openai:assistant', async () => {
  643. const provider = await loadApiProvider('openai:assistant:foobar');
  644. expect(provider).toBeInstanceOf(OpenAiAssistantProvider);
  645. });
  646. it('loadApiProvider with openai:chat:modelName', async () => {
  647. const provider = await loadApiProvider('openai:chat:gpt-3.5-turbo');
  648. expect(provider).toBeInstanceOf(OpenAiChatCompletionProvider);
  649. });
  650. it('loadApiProvider with openai:completion:modelName', async () => {
  651. const provider = await loadApiProvider('openai:completion:text-davinci-003');
  652. expect(provider).toBeInstanceOf(OpenAiCompletionProvider);
  653. });
  654. it('loadApiProvider with OpenAI finetuned model', async () => {
  655. const provider = await loadApiProvider('openai:chat:ft:gpt-4o-mini:company-name::ID:');
  656. expect(provider).toBeInstanceOf(OpenAiChatCompletionProvider);
  657. expect(provider.id()).toBe('openai:ft:gpt-4o-mini:company-name::ID:');
  658. });
  659. it('loadApiProvider with azureopenai:completion:modelName', async () => {
  660. const provider = await loadApiProvider('azureopenai:completion:text-davinci-003');
  661. expect(provider).toBeInstanceOf(AzureCompletionProvider);
  662. });
  663. it('loadApiProvider with azureopenai:chat:modelName', async () => {
  664. const provider = await loadApiProvider('azureopenai:chat:gpt-3.5-turbo');
  665. expect(provider).toBeInstanceOf(AzureChatCompletionProvider);
  666. });
  667. it('loadApiProvider with anthropic:completion', async () => {
  668. const provider = await loadApiProvider('anthropic:completion');
  669. expect(provider).toBeInstanceOf(AnthropicCompletionProvider);
  670. });
  671. it('loadApiProvider with anthropic:completion:modelName', async () => {
  672. const provider = await loadApiProvider('anthropic:completion:claude-1');
  673. expect(provider).toBeInstanceOf(AnthropicCompletionProvider);
  674. });
  675. it('loadApiProvider with ollama:modelName', async () => {
  676. const provider = await loadApiProvider('ollama:llama2:13b');
  677. expect(provider).toBeInstanceOf(OllamaCompletionProvider);
  678. expect(provider.id()).toBe('ollama:completion:llama2:13b');
  679. });
  680. it('loadApiProvider with ollama:completion:modelName', async () => {
  681. const provider = await loadApiProvider('ollama:completion:llama2:13b');
  682. expect(provider).toBeInstanceOf(OllamaCompletionProvider);
  683. expect(provider.id()).toBe('ollama:completion:llama2:13b');
  684. });
  685. it('loadApiProvider with ollama:embedding:modelName', async () => {
  686. const provider = await loadApiProvider('ollama:embedding:llama2:13b');
  687. expect(provider).toBeInstanceOf(OllamaEmbeddingProvider);
  688. });
  689. it('loadApiProvider with ollama:embeddings:modelName', async () => {
  690. const provider = await loadApiProvider('ollama:embeddings:llama2:13b');
  691. expect(provider).toBeInstanceOf(OllamaEmbeddingProvider);
  692. });
  693. it('loadApiProvider with ollama:chat:modelName', async () => {
  694. const provider = await loadApiProvider('ollama:chat:llama2:13b');
  695. expect(provider).toBeInstanceOf(OllamaChatProvider);
  696. expect(provider.id()).toBe('ollama:chat:llama2:13b');
  697. });
  698. it('loadApiProvider with llama:modelName', async () => {
  699. const provider = await loadApiProvider('llama');
  700. expect(provider).toBeInstanceOf(LlamaProvider);
  701. });
  702. it('loadApiProvider with webhook', async () => {
  703. const provider = await loadApiProvider('webhook:http://example.com/webhook');
  704. expect(provider).toBeInstanceOf(WebhookProvider);
  705. });
  706. it('loadApiProvider with huggingface:text-generation', async () => {
  707. const provider = await loadApiProvider('huggingface:text-generation:foobar/baz');
  708. expect(provider).toBeInstanceOf(HuggingfaceTextGenerationProvider);
  709. });
  710. it('loadApiProvider with huggingface:feature-extraction', async () => {
  711. const provider = await loadApiProvider('huggingface:feature-extraction:foobar/baz');
  712. expect(provider).toBeInstanceOf(HuggingfaceFeatureExtractionProvider);
  713. });
  714. it('loadApiProvider with huggingface:text-classification', async () => {
  715. const provider = await loadApiProvider('huggingface:text-classification:foobar/baz');
  716. expect(provider).toBeInstanceOf(HuggingfaceTextClassificationProvider);
  717. });
  718. it('loadApiProvider with hf:text-classification', async () => {
  719. const provider = await loadApiProvider('hf:text-classification:foobar/baz');
  720. expect(provider).toBeInstanceOf(HuggingfaceTextClassificationProvider);
  721. });
  722. it('loadApiProvider with bedrock:completion', async () => {
  723. const provider = await loadApiProvider('bedrock:completion:anthropic.claude-v2:1');
  724. expect(provider).toBeInstanceOf(AwsBedrockCompletionProvider);
  725. });
  726. it('loadApiProvider with openrouter', async () => {
  727. const provider = await loadApiProvider('openrouter:mistralai/mistral-medium');
  728. expect(provider).toBeInstanceOf(OpenAiChatCompletionProvider);
  729. // Intentionally openai, because it's just a wrapper around openai
  730. expect(provider.id()).toBe('mistralai/mistral-medium');
  731. });
  732. it('loadApiProvider with github', async () => {
  733. const provider = await loadApiProvider('github:gpt-4o-mini');
  734. expect(provider).toBeInstanceOf(OpenAiChatCompletionProvider);
  735. // Intentionally openai, because it's just a wrapper around openai
  736. expect(provider.id()).toBe('gpt-4o-mini');
  737. });
  738. it('loadApiProvider with perplexity', async () => {
  739. const provider = await loadApiProvider('perplexity:llama-3-sonar-large-32k-online');
  740. expect(provider).toBeInstanceOf(OpenAiChatCompletionProvider);
  741. expect(provider.id()).toBe('llama-3-sonar-large-32k-online');
  742. expect(provider.config.apiBaseUrl).toBe('https://api.perplexity.ai');
  743. expect(provider.config.apiKeyEnvar).toBe('PERPLEXITY_API_KEY');
  744. });
  745. it('loadApiProvider with togetherai', async () => {
  746. const provider = await loadApiProvider(
  747. 'togetherai:chat:meta/meta-llama/Meta-Llama-3-8B-Instruct',
  748. );
  749. expect(provider).toBeInstanceOf(OpenAiChatCompletionProvider);
  750. expect(provider.id()).toBe('meta/meta-llama/Meta-Llama-3-8B-Instruct');
  751. });
  752. it('loadApiProvider with voyage', async () => {
  753. const provider = await loadApiProvider('voyage:voyage-2');
  754. expect(provider).toBeInstanceOf(VoyageEmbeddingProvider);
  755. expect(provider.id()).toBe('voyage:voyage-2');
  756. });
  757. it('loadApiProvider with vertex:chat', async () => {
  758. const provider = await loadApiProvider('vertex:chat:vertex-chat-model');
  759. expect(provider).toBeInstanceOf(VertexChatProvider);
  760. expect(provider.id()).toBe('vertex:vertex-chat-model');
  761. });
  762. it('loadApiProvider with vertex:embedding', async () => {
  763. const provider = await loadApiProvider('vertex:embedding:vertex-embedding-model');
  764. expect(provider).toBeInstanceOf(VertexEmbeddingProvider);
  765. expect(provider.id()).toBe('vertex:vertex-embedding-model');
  766. });
  767. it('loadApiProvider with vertex:embeddings', async () => {
  768. const provider = await loadApiProvider('vertex:embeddings:vertex-embedding-model');
  769. expect(provider).toBeInstanceOf(VertexEmbeddingProvider);
  770. expect(provider.id()).toBe('vertex:vertex-embedding-model');
  771. });
  772. it('loadApiProvider with vertex:modelname', async () => {
  773. const provider = await loadApiProvider('vertex:vertex-chat-model');
  774. expect(provider).toBeInstanceOf(VertexChatProvider);
  775. expect(provider.id()).toBe('vertex:vertex-chat-model');
  776. });
  777. it('loadApiProvider with replicate:modelname', async () => {
  778. const provider = await loadApiProvider('replicate:meta/llama3');
  779. expect(provider).toBeInstanceOf(ReplicateProvider);
  780. expect(provider.id()).toBe('replicate:meta/llama3');
  781. });
  782. it('loadApiProvider with replicate:modelname:version', async () => {
  783. const provider = await loadApiProvider('replicate:meta/llama3:abc123');
  784. expect(provider).toBeInstanceOf(ReplicateProvider);
  785. expect(provider.id()).toBe('replicate:meta/llama3:abc123');
  786. });
  787. it('loadApiProvider with replicate:image', async () => {
  788. const provider = await loadApiProvider('replicate:image:stability-ai/sdxl');
  789. expect(provider).toBeInstanceOf(ReplicateImageProvider);
  790. expect(provider.id()).toBe('replicate:stability-ai/sdxl');
  791. });
  792. it('loadApiProvider with replicate:image:version', async () => {
  793. const provider = await loadApiProvider('replicate:image:stability-ai/sdxl:abc123');
  794. expect(provider).toBeInstanceOf(ReplicateImageProvider);
  795. expect(provider.id()).toBe('replicate:stability-ai/sdxl:abc123');
  796. });
  797. it('loadApiProvider with replicate:moderation', async () => {
  798. const provider = await loadApiProvider('replicate:moderation:foo/bar');
  799. expect(provider).toBeInstanceOf(ReplicateModerationProvider);
  800. expect(provider.id()).toBe('replicate:foo/bar');
  801. });
  802. it('loadApiProvider with replicate:moderation:version', async () => {
  803. const provider = await loadApiProvider('replicate:moderation:foo/bar:abc123');
  804. expect(provider).toBeInstanceOf(ReplicateModerationProvider);
  805. expect(provider.id()).toBe('replicate:foo/bar:abc123');
  806. });
  807. it('loadApiProvider with file://*.py', async () => {
  808. const provider = await loadApiProvider('file://script.py:function_name');
  809. expect(provider).toBeInstanceOf(PythonProvider);
  810. expect(provider.id()).toBe('python:script.py:function_name');
  811. });
  812. it('loadApiProvider with python:*.py', async () => {
  813. const provider = await loadApiProvider('python:script.py');
  814. expect(provider).toBeInstanceOf(PythonProvider);
  815. expect(provider.id()).toBe('python:script.py:default');
  816. });
  817. it('loadApiProvider with cloudflare-ai', async () => {
  818. const supportedModelTypes = [
  819. { modelType: 'chat', providerKlass: CloudflareAiChatCompletionProvider },
  820. { modelType: 'embedding', providerKlass: CloudflareAiEmbeddingProvider },
  821. { modelType: 'embeddings', providerKlass: CloudflareAiEmbeddingProvider },
  822. { modelType: 'completion', providerKlass: CloudflareAiCompletionProvider },
  823. ] as const;
  824. const unsupportedModelTypes = ['assistant'] as const;
  825. const modelName = 'mistralai/mistral-medium';
  826. // Without any model type should throw an error
  827. await expect(loadApiProvider(`cloudflare-ai:${modelName}`)).rejects.toThrow(
  828. /Unknown Cloudflare AI model type/,
  829. );
  830. for (const unsupportedModelType of unsupportedModelTypes) {
  831. await expect(
  832. loadApiProvider(`cloudflare-ai:${unsupportedModelType}:${modelName}`),
  833. ).rejects.toThrow(/Unknown Cloudflare AI model type/);
  834. }
  835. for (const { modelType, providerKlass } of supportedModelTypes) {
  836. const cfProvider = await loadApiProvider(`cloudflare-ai:${modelType}:${modelName}`);
  837. const modelTypeForId: (typeof supportedModelTypes)[number]['modelType'] =
  838. modelType === 'embeddings' ? 'embedding' : modelType;
  839. expect(cfProvider.id()).toMatch(`cloudflare-ai:${modelTypeForId}:${modelName}`);
  840. expect(cfProvider).toBeInstanceOf(providerKlass);
  841. }
  842. });
  843. it('loadApiProvider with promptfoo:redteam:iterative', async () => {
  844. const provider = await loadApiProvider('promptfoo:redteam:iterative', {
  845. options: { config: { injectVar: 'foo' } },
  846. });
  847. expect(provider).toBeInstanceOf(RedteamIterativeProvider);
  848. expect(provider.id()).toBe('promptfoo:redteam:iterative');
  849. });
  850. it('loadApiProvider with promptfoo:redteam:iterative:tree', async () => {
  851. const provider = await loadApiProvider('promptfoo:redteam:iterative:tree', {
  852. options: { config: { injectVar: 'foo' } },
  853. });
  854. expect(provider).toBeInstanceOf(RedteamIterativeTreeProvider);
  855. expect(provider.id()).toBe('promptfoo:redteam:iterative:tree');
  856. });
  857. it('loadApiProvider with promptfoo:redteam:iterative:image', async () => {
  858. const provider = await loadApiProvider('promptfoo:redteam:iterative:image', {
  859. options: {
  860. config: {
  861. injectVar: 'imageUrl',
  862. },
  863. },
  864. });
  865. expect(provider).toBeInstanceOf(RedteamImageIterativeProvider);
  866. expect(provider.id()).toBe('promptfoo:redteam:iterative:image');
  867. });
  868. it('loadApiProvider with promptfoo:redteam:goat', async () => {
  869. const provider = await loadApiProvider('promptfoo:redteam:goat', {
  870. options: { config: { injectVar: 'goal' } },
  871. });
  872. expect(provider).toBeInstanceOf(RedteamGoatProvider);
  873. expect(provider.id()).toBe('promptfoo:redteam:goat');
  874. });
  875. it('loadApiProvider with RawProviderConfig', async () => {
  876. const rawProviderConfig = {
  877. 'openai:chat': {
  878. id: 'test',
  879. config: { foo: 'bar' },
  880. },
  881. };
  882. const provider = await loadApiProvider('openai:chat', {
  883. options: rawProviderConfig['openai:chat'],
  884. });
  885. expect(provider).toBeInstanceOf(OpenAiChatCompletionProvider);
  886. });
  887. it('loadApiProviders with ProviderFunction', async () => {
  888. const providerFunction: ProviderFunction = async (prompt) => {
  889. return {
  890. output: `Output for ${prompt}`,
  891. tokenUsage: { total: 10, prompt: 5, completion: 5 },
  892. };
  893. };
  894. const providers = await loadApiProviders(providerFunction);
  895. expect(providers).toHaveLength(1);
  896. expect(providers[0].id()).toBe('custom-function');
  897. const response = await providers[0].callApi('Test prompt');
  898. expect(response.output).toBe('Output for Test prompt');
  899. expect(response.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5 });
  900. });
  901. it('loadApiProviders with CustomApiProvider', async () => {
  902. const providerPath = 'file://path/to/file.js';
  903. class CustomApiProvider {
  904. id() {
  905. return 'custom-api-provider';
  906. }
  907. async callApi(input: string) {
  908. return { output: `Processed ${input}` };
  909. }
  910. }
  911. jest.mocked(importModule).mockResolvedValue(CustomApiProvider);
  912. const providers = await loadApiProviders(providerPath);
  913. expect(importModule).toHaveBeenCalledWith(path.resolve('path/to/file.js'));
  914. expect(providers).toHaveLength(1);
  915. expect(providers[0].id()).toBe('custom-api-provider');
  916. const response = await providers[0].callApi('Test input');
  917. expect(response.output).toBe('Processed Test input');
  918. });
  919. it('loadApiProviders with CustomApiProvider, absolute path', async () => {
  920. const providerPath = 'file:///absolute/path/to/file.js';
  921. class CustomApiProvider {
  922. id() {
  923. return 'custom-api-provider';
  924. }
  925. async callApi(input: string) {
  926. return { output: `Processed ${input}` };
  927. }
  928. }
  929. jest.mocked(importModule).mockResolvedValue(CustomApiProvider);
  930. const providers = await loadApiProviders(providerPath);
  931. expect(importModule).toHaveBeenCalledWith('/absolute/path/to/file.js');
  932. expect(providers).toHaveLength(1);
  933. expect(providers[0].id()).toBe('custom-api-provider');
  934. const response = await providers[0].callApi('Test input');
  935. expect(response.output).toBe('Processed Test input');
  936. });
  937. it('loadApiProviders with RawProviderConfig[]', async () => {
  938. const rawProviderConfigs: ProviderOptionsMap[] = [
  939. {
  940. 'openai:chat:abc123': {
  941. config: { foo: 'bar' },
  942. },
  943. },
  944. {
  945. 'openai:completion:def456': {
  946. config: { foo: 'bar' },
  947. },
  948. },
  949. {
  950. 'anthropic:completion:ghi789': {
  951. config: { foo: 'bar' },
  952. },
  953. },
  954. ];
  955. const providers = await loadApiProviders(rawProviderConfigs);
  956. expect(providers).toHaveLength(3);
  957. expect(providers[0]).toBeInstanceOf(OpenAiChatCompletionProvider);
  958. expect(providers[1]).toBeInstanceOf(OpenAiCompletionProvider);
  959. expect(providers[2]).toBeInstanceOf(AnthropicCompletionProvider);
  960. });
  961. it('loadApiProvider sets provider.delay', async () => {
  962. const providerOptions = {
  963. id: 'test-delay',
  964. config: {},
  965. delay: 500,
  966. };
  967. const provider = await loadApiProvider('echo', { options: providerOptions });
  968. expect(provider.delay).toBe(500);
  969. });
  970. it('supports templating in provider URL', async () => {
  971. process.env.MY_HOST = 'api.example.com';
  972. process.env.MY_PORT = '8080';
  973. const provider = await loadApiProvider('https://{{ env.MY_HOST }}:{{ env.MY_PORT }}/query', {
  974. options: {
  975. config: {
  976. body: {},
  977. },
  978. },
  979. });
  980. expect(provider.id()).toBe('https://api.example.com:8080/query');
  981. delete process.env.MY_HOST;
  982. delete process.env.MY_PORT;
  983. });
  984. it('throws an error for unidentified providers', async () => {
  985. const mockExit = jest.spyOn(process, 'exit').mockImplementation(() => {
  986. throw new Error('process.exit called');
  987. });
  988. const unknownProviderPath = 'unknown:provider';
  989. await expect(loadApiProvider(unknownProviderPath)).rejects.toThrow('process.exit called');
  990. expect(logger.error).toHaveBeenCalledWith(
  991. dedent`
  992. Could not identify provider: ${chalk.bold(unknownProviderPath)}.
  993. ${chalk.white(dedent`
  994. Please check your configuration and ensure the provider is correctly specified.
  995. For more information on supported providers, visit: `)} ${chalk.cyan('https://promptfoo.dev/docs/providers/')}
  996. `,
  997. );
  998. expect(mockExit).toHaveBeenCalledWith(1);
  999. mockExit.mockRestore();
  1000. });
  1001. it('renders label using Nunjucks', async () => {
  1002. process.env.someVariable = 'foo';
  1003. const providerOptions = {
  1004. id: 'openai:chat:gpt-4o',
  1005. config: {},
  1006. label: '{{ env.someVariable }}',
  1007. };
  1008. const provider = await loadApiProvider('openai:chat:gpt-4o', { options: providerOptions });
  1009. expect(provider.label).toBe('foo');
  1010. });
  1011. it('loadApiProvider with xai', async () => {
  1012. const provider = await loadApiProvider('xai:grok-2');
  1013. expect(provider).toBeInstanceOf(OpenAiChatCompletionProvider);
  1014. expect(provider.id()).toBe('grok-2');
  1015. expect(provider.config.apiBaseUrl).toBe('https://api.x.ai/v1');
  1016. expect(provider.config.apiKeyEnvar).toBe('XAI_API_KEY');
  1017. });
  1018. it('loadApiProvider with adaline:openai:chat', async () => {
  1019. const provider = await loadApiProvider('adaline:openai:chat:gpt-4');
  1020. expect(provider.id()).toBe('adaline:openai:chat:gpt-4');
  1021. });
  1022. it('loadApiProvider with adaline:openai:embedding', async () => {
  1023. const provider = await loadApiProvider('adaline:openai:embedding:text-embedding-3-large');
  1024. expect(provider.id()).toBe('adaline:openai:embedding:text-embedding-3-large');
  1025. });
  1026. it('should throw error for invalid adaline provider path', async () => {
  1027. await expect(loadApiProvider('adaline:invalid')).rejects.toThrow(
  1028. "Invalid adaline provider path: adaline:invalid. path format should be 'adaline:<provider_name>:<model_type>:<model_name>' eg. 'adaline:openai:chat:gpt-4o'",
  1029. );
  1030. });
  1031. it.each([
  1032. ['dashscope:chat:qwen-max', 'qwen-max'],
  1033. ['dashscope:vl:qwen-vl-max', 'qwen-vl-max'],
  1034. ['alibaba:qwen-plus', 'qwen-plus'],
  1035. ['alibaba:chat:qwen-max', 'qwen-max'],
  1036. ['alibaba:vl:qwen-vl-max', 'qwen-vl-max'],
  1037. ['alicloud:qwen-plus', 'qwen-plus'],
  1038. ['aliyun:qwen-plus', 'qwen-plus'],
  1039. ])('loadApiProvider with %s', async (providerId, expectedModelId) => {
  1040. const provider = await loadApiProvider(providerId);
  1041. expect(provider).toBeInstanceOf(OpenAiChatCompletionProvider);
  1042. expect(provider.id()).toBe(expectedModelId);
  1043. expect(provider.config.apiBaseUrl).toBe(
  1044. 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',
  1045. );
  1046. expect(provider.config.apiKeyEnvar).toBe('DASHSCOPE_API_KEY');
  1047. });
  1048. it('loadApiProvider with alibaba embedding', async () => {
  1049. const provider = await loadApiProvider('alibaba:embedding:text-embedding-v3');
  1050. expect(provider).toBeInstanceOf(OpenAiEmbeddingProvider);
  1051. expect(provider.id()).toBe('text-embedding-v3');
  1052. expect(provider.config.apiBaseUrl).toBe(
  1053. 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',
  1054. );
  1055. expect(provider.config.apiKeyEnvar).toBe('DASHSCOPE_API_KEY');
  1056. });
  1057. it('loadApiProvider with alibaba unknown model', async () => {
  1058. await expect(loadApiProvider('alibaba:unknown-model')).rejects.toThrow(
  1059. 'Invalid Alibaba Cloud model: unknown-model',
  1060. );
  1061. });
  1062. });
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...