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

providers.bedrock.test.ts 16 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
  1. import dedent from 'dedent';
  2. import type {
  3. BedrockClaudeMessagesCompletionOptions,
  4. LlamaMessage,
  5. } from '../src/providers/bedrock';
  6. import {
  7. addConfigParam,
  8. AwsBedrockGenericProvider,
  9. BEDROCK_MODEL,
  10. formatPromptLlama2Chat,
  11. getLlamaModelHandler,
  12. LlamaVersion,
  13. parseValue,
  14. } from '../src/providers/bedrock';
  15. jest.mock('@aws-sdk/client-bedrock-runtime', () => {
  16. return {
  17. BedrockRuntime: jest.fn().mockImplementation(() => {
  18. return {
  19. invokeModel: jest.fn(),
  20. };
  21. }),
  22. };
  23. });
  24. jest.mock(
  25. '@smithy/node-http-handler',
  26. () => {
  27. return {
  28. NodeHttpHandler: jest.fn(),
  29. };
  30. },
  31. { virtual: true },
  32. );
  33. jest.mock('proxy-agent', () => jest.fn());
  34. jest.mock('../src/cache', () => ({
  35. getCache: jest.fn(),
  36. isCacheEnabled: jest.fn(),
  37. }));
  38. jest.mock('../src/logger', () => ({
  39. debug: jest.fn(),
  40. warn: jest.fn(),
  41. error: jest.fn(),
  42. }));
  43. describe('AwsBedrockGenericProvider', () => {
  44. let BedrockRuntime: any;
  45. beforeEach(() => {
  46. jest.resetModules();
  47. BedrockRuntime = require('@aws-sdk/client-bedrock-runtime').BedrockRuntime;
  48. jest.clearAllMocks();
  49. });
  50. afterEach(() => {
  51. delete process.env.HTTP_PROXY;
  52. delete process.env.HTTPS_PROXY;
  53. });
  54. it('should create Bedrock instance without proxy settings', async () => {
  55. const provider = new (class extends AwsBedrockGenericProvider {
  56. constructor() {
  57. super('test-model', { config: { region: 'us-east-1' } });
  58. }
  59. })();
  60. await provider.getBedrockInstance();
  61. expect(BedrockRuntime).toHaveBeenCalledWith({
  62. region: 'us-east-1',
  63. });
  64. });
  65. it('should throw an error if NodeHttpHandler dependency is missing for proxy', async () => {
  66. process.env.HTTP_PROXY = 'http://localhost:8080';
  67. process.env.HTTPS_PROXY = 'https://localhost:8080';
  68. jest.doMock('@smithy/node-http-handler', () => {
  69. throw new Error('Missing dependency');
  70. });
  71. const provider = new (class extends AwsBedrockGenericProvider {
  72. constructor() {
  73. super('test-model', { config: { region: 'us-east-1' } });
  74. }
  75. })();
  76. await expect(provider.getBedrockInstance()).rejects.toThrow(
  77. 'The @smithy/node-http-handler package is required as a peer dependency. Please install it in your project or globally.',
  78. );
  79. });
  80. describe('BEDROCK_MODEL CLAUDE_MESSAGES', () => {
  81. const modelHandler = BEDROCK_MODEL.CLAUDE_MESSAGES;
  82. it('should include tools and tool_choice in params when provided', () => {
  83. const config: BedrockClaudeMessagesCompletionOptions = {
  84. region: 'us-east-1',
  85. tools: [
  86. {
  87. name: 'get_current_weather',
  88. description: 'Get the current weather in a given location',
  89. input_schema: {
  90. type: 'object',
  91. properties: {
  92. location: { type: 'string' },
  93. unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
  94. },
  95. required: ['location'],
  96. },
  97. },
  98. ],
  99. tool_choice: {
  100. type: 'auto',
  101. },
  102. };
  103. const params = modelHandler.params(config, 'Test prompt');
  104. expect(params).toHaveProperty('tools');
  105. expect(params.tools).toHaveLength(1);
  106. expect(params.tools[0]).toHaveProperty('name', 'get_current_weather');
  107. expect(params).toHaveProperty('tool_choice');
  108. expect(params.tool_choice).toEqual({ type: 'auto' });
  109. });
  110. it('should not include tools and tool_choice in params when not provided', () => {
  111. const config: BedrockClaudeMessagesCompletionOptions = {
  112. region: 'us-east-1',
  113. };
  114. const params = modelHandler.params(config, 'Test prompt');
  115. expect(params).not.toHaveProperty('tools');
  116. expect(params).not.toHaveProperty('tool_choice');
  117. });
  118. it('should include specific tool_choice when provided', () => {
  119. const config: BedrockClaudeMessagesCompletionOptions = {
  120. region: 'us-east-1',
  121. tools: [
  122. {
  123. name: 'get_current_weather',
  124. description: 'Get the current weather in a given location',
  125. input_schema: {
  126. type: 'object',
  127. properties: {
  128. location: { type: 'string' },
  129. unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
  130. },
  131. required: ['location'],
  132. },
  133. },
  134. ],
  135. tool_choice: {
  136. type: 'tool',
  137. name: 'get_current_weather',
  138. },
  139. };
  140. const params = modelHandler.params(config, 'Test prompt');
  141. expect(params).toHaveProperty('tool_choice');
  142. expect(params.tool_choice).toEqual({ type: 'tool', name: 'get_current_weather' });
  143. });
  144. });
  145. });
  146. describe('addConfigParam', () => {
  147. it('should add config value if provided', () => {
  148. const params: any = {};
  149. addConfigParam(params, 'key', 'configValue');
  150. expect(params.key).toBe('configValue');
  151. });
  152. it('should add env value if config value is not provided', () => {
  153. const params: any = {};
  154. process.env.TEST_ENV_KEY = 'envValue';
  155. addConfigParam(params, 'key', undefined, process.env.TEST_ENV_KEY);
  156. expect(params.key).toBe('envValue');
  157. delete process.env.TEST_ENV_KEY;
  158. });
  159. it('should add default value if neither config nor env value is provided', () => {
  160. const params: any = {};
  161. addConfigParam(params, 'key', undefined, undefined, 'defaultValue');
  162. expect(params.key).toBe('defaultValue');
  163. });
  164. it('should prioritize config value over env and default values', () => {
  165. const params: any = {};
  166. process.env.TEST_ENV_KEY = 'envValue';
  167. addConfigParam(params, 'key', 'configValue', process.env.TEST_ENV_KEY, 'defaultValue');
  168. expect(params.key).toBe('configValue');
  169. delete process.env.TEST_ENV_KEY;
  170. });
  171. it('should prioritize env value over default value if config value is not provided', () => {
  172. const params: any = {};
  173. process.env.TEST_ENV_KEY = 'envValue';
  174. addConfigParam(params, 'key', undefined, process.env.TEST_ENV_KEY, 'defaultValue');
  175. expect(params.key).toBe('envValue');
  176. delete process.env.TEST_ENV_KEY;
  177. });
  178. it('should parse env value if default value is a number', () => {
  179. const params: any = {};
  180. process.env.TEST_ENV_KEY = '42';
  181. addConfigParam(params, 'key', undefined, process.env.TEST_ENV_KEY, 0);
  182. expect(params.key).toBe(42);
  183. delete process.env.TEST_ENV_KEY;
  184. });
  185. it('should handle undefined config, env, and default values gracefully', () => {
  186. const params: any = {};
  187. addConfigParam(params, 'key', undefined, undefined, undefined);
  188. expect(params.key).toBeUndefined();
  189. });
  190. it('should correctly parse non-number string values', () => {
  191. const params: any = {};
  192. process.env.TEST_ENV_KEY = 'nonNumberString';
  193. addConfigParam(params, 'key', undefined, process.env.TEST_ENV_KEY, 0);
  194. expect(params.key).toBe(0);
  195. delete process.env.TEST_ENV_KEY;
  196. });
  197. it('should correctly parse empty string values', () => {
  198. const params: any = {};
  199. process.env.TEST_ENV_KEY = '';
  200. addConfigParam(params, 'key', undefined, process.env.TEST_ENV_KEY, 'defaultValue');
  201. expect(params.key).toBe('');
  202. delete process.env.TEST_ENV_KEY;
  203. });
  204. it('should handle env value not set', () => {
  205. const params: any = {};
  206. addConfigParam(params, 'key', undefined, process.env.UNSET_ENV_KEY, 'defaultValue');
  207. expect(params.key).toBe('defaultValue');
  208. });
  209. it('should handle config values that are objects', () => {
  210. const params: any = {};
  211. const configValue = { nestedKey: 'nestedValue' };
  212. addConfigParam(params, 'key', configValue);
  213. expect(params.key).toEqual(configValue);
  214. });
  215. it('should handle config values that are arrays', () => {
  216. const params: any = {};
  217. const configValue = ['value1', 'value2'];
  218. addConfigParam(params, 'key', configValue);
  219. expect(params.key).toEqual(configValue);
  220. });
  221. it('should handle special characters in env values', () => {
  222. const params: any = {};
  223. process.env.TEST_ENV_KEY = '!@#$%^&*()_+';
  224. addConfigParam(params, 'key', undefined, process.env.TEST_ENV_KEY, 'defaultValue');
  225. expect(params.key).toBe('!@#$%^&*()_+');
  226. delete process.env.TEST_ENV_KEY;
  227. });
  228. });
  229. describe('parseValue', () => {
  230. it('should return the original value if defaultValue is not a number', () => {
  231. expect(parseValue('stringValue', 'defaultValue')).toBe('stringValue');
  232. });
  233. it('should return parsed float value if defaultValue is a number', () => {
  234. expect(parseValue('42.5', 0)).toBe(42.5);
  235. });
  236. it('should return NaN for non-numeric strings if defaultValue is a number', () => {
  237. expect(parseValue('notANumber', 0)).toBe(0);
  238. });
  239. it('should return 0 for an empty string if defaultValue is a number', () => {
  240. expect(parseValue('', 0)).toBe(0);
  241. });
  242. it('should return null for a null value if defaultValue is not a number', () => {
  243. expect(parseValue(null as never, 'defaultValue')).toBeNull();
  244. });
  245. it('should return undefined for an undefined value if defaultValue is not a number', () => {
  246. expect(parseValue(undefined as never, 'defaultValue')).toBeUndefined();
  247. });
  248. });
  249. describe('llama', () => {
  250. describe('getLlamaModelHandler', () => {
  251. describe('LLAMA2', () => {
  252. const handler = getLlamaModelHandler(LlamaVersion.V2);
  253. it('should generate correct prompt for a single user message', () => {
  254. const config = { temperature: 0.5, top_p: 0.9, max_gen_len: 512 };
  255. const prompt = 'Describe the purpose of a "hello world" program in one sentence.';
  256. expect(handler.params(config, prompt)).toEqual({
  257. prompt: `<s>[INST] Describe the purpose of a "hello world" program in one sentence. [/INST]`,
  258. temperature: 0.5,
  259. top_p: 0.9,
  260. max_gen_len: 512,
  261. });
  262. });
  263. it('should handle a system message followed by a user message', () => {
  264. const config = {};
  265. const prompt = JSON.stringify([
  266. { role: 'system', content: 'You are a helpful assistant.' },
  267. { role: 'user', content: 'What is the capital of France?' },
  268. ]);
  269. expect(handler.params(config, prompt)).toEqual({
  270. prompt: dedent`<s>[INST] <<SYS>>
  271. You are a helpful assistant.
  272. <</SYS>>
  273. What is the capital of France? [/INST]`,
  274. temperature: 0.01,
  275. top_p: 1,
  276. max_gen_len: 1024,
  277. });
  278. });
  279. it('should handle multiple turns of conversation', () => {
  280. const config = {};
  281. const prompt = JSON.stringify([
  282. { role: 'user', content: 'Hello' },
  283. { role: 'assistant', content: 'Hi there! How can I assist you today?' },
  284. { role: 'user', content: "What's the weather like?" },
  285. ]);
  286. expect(handler.params(config, prompt)).toEqual({
  287. prompt:
  288. "<s>[INST] Hello [/INST] Hi there! How can I assist you today? </s><s>[INST] What's the weather like? [/INST]",
  289. temperature: 0.01,
  290. top_p: 1,
  291. max_gen_len: 1024,
  292. });
  293. });
  294. });
  295. describe('LLAMA3', () => {
  296. const handler = getLlamaModelHandler(LlamaVersion.V3);
  297. it('should generate correct prompt for a single user message', () => {
  298. const config = { temperature: 0.5, top_p: 0.9, max_gen_len: 512 };
  299. const prompt = 'Describe the purpose of a "hello world" program in one sentence.';
  300. expect(handler.params(config, prompt)).toEqual({
  301. prompt: dedent`<|begin_of_text|><|start_header_id|>user<|end_header_id|>
  302. Describe the purpose of a "hello world" program in one sentence.<|eot_id|><|start_header_id|>assistant<|end_header_id|>`,
  303. temperature: 0.5,
  304. top_p: 0.9,
  305. max_gen_len: 512,
  306. });
  307. });
  308. it('should handle a system message followed by a user message', () => {
  309. const config = {};
  310. const prompt = JSON.stringify([
  311. { role: 'system', content: 'You are a helpful assistant.' },
  312. { role: 'user', content: 'What is the capital of France?' },
  313. ]);
  314. expect(handler.params(config, prompt)).toEqual({
  315. prompt: dedent`<|begin_of_text|><|start_header_id|>system<|end_header_id|>
  316. You are a helpful assistant.<|eot_id|><|start_header_id|>user<|end_header_id|>
  317. What is the capital of France?<|eot_id|><|start_header_id|>assistant<|end_header_id|>`,
  318. temperature: 0.01,
  319. top_p: 1,
  320. max_gen_len: 1024,
  321. });
  322. });
  323. it('should handle multiple turns of conversation', () => {
  324. const config = {};
  325. const prompt = JSON.stringify([
  326. { role: 'user', content: 'Hello' },
  327. { role: 'assistant', content: 'Hi there! How can I assist you today?' },
  328. { role: 'user', content: "What's the weather like?" },
  329. ]);
  330. expect(handler.params(config, prompt)).toEqual({
  331. prompt: dedent`<|begin_of_text|><|start_header_id|>user<|end_header_id|>
  332. Hello<|eot_id|><|start_header_id|>assistant<|end_header_id|>
  333. Hi there! How can I assist you today?<|eot_id|><|start_header_id|>user<|end_header_id|>
  334. What's the weather like?<|eot_id|><|start_header_id|>assistant<|end_header_id|>`,
  335. temperature: 0.01,
  336. top_p: 1,
  337. max_gen_len: 1024,
  338. });
  339. });
  340. });
  341. it('should throw an error for unsupported LLAMA version', () => {
  342. expect(() => getLlamaModelHandler(1 as LlamaVersion)).toThrow('Unsupported LLAMA version: 1');
  343. });
  344. it('should handle output correctly', () => {
  345. const handler = getLlamaModelHandler(LlamaVersion.V2);
  346. expect(handler.output({ generation: 'Test response' })).toBe('Test response');
  347. expect(handler.output({})).toBeUndefined();
  348. });
  349. });
  350. describe('formatPromptLlama2Chat', () => {
  351. it('should format a single user message correctly', () => {
  352. const messages: LlamaMessage[] = [
  353. {
  354. role: 'user',
  355. content: 'Describe the purpose of a "hello world" program in one sentence.',
  356. },
  357. ];
  358. const expectedPrompt =
  359. '<s>[INST] Describe the purpose of a "hello world" program in one sentence. [/INST]';
  360. expect(formatPromptLlama2Chat(messages)).toBe(expectedPrompt);
  361. });
  362. it('should handle a system message followed by a user message', () => {
  363. const messages: LlamaMessage[] = [
  364. { role: 'system', content: 'You are a helpful assistant.' },
  365. { role: 'user', content: 'What is the capital of France?' },
  366. ];
  367. const expectedPrompt = dedent`
  368. <s>[INST] <<SYS>>
  369. You are a helpful assistant.
  370. <</SYS>>
  371. What is the capital of France? [/INST]
  372. `;
  373. expect(formatPromptLlama2Chat(messages)).toBe(expectedPrompt);
  374. });
  375. it('should handle a system message, user message, and assistant response', () => {
  376. const messages: LlamaMessage[] = [
  377. { role: 'system', content: 'You are a helpful assistant.' },
  378. { role: 'user', content: 'What is the capital of France?' },
  379. { role: 'assistant', content: 'The capital of France is Paris.' },
  380. ];
  381. const expectedPrompt = dedent`
  382. <s>[INST] <<SYS>>
  383. You are a helpful assistant.
  384. <</SYS>>
  385. What is the capital of France? [/INST] The capital of France is Paris. </s>
  386. `;
  387. expect(formatPromptLlama2Chat(messages)).toBe(expectedPrompt);
  388. });
  389. it('should handle multiple turns of conversation', () => {
  390. // see https://huggingface.co/blog/llama2#how-to-prompt-llama-2
  391. const messages: LlamaMessage[] = [
  392. { role: 'system', content: 'You are a helpful assistant.' },
  393. { role: 'user', content: 'Hello' },
  394. { role: 'assistant', content: 'Hi there! How can I assist you today?' },
  395. { role: 'user', content: "What's the weather like?" },
  396. ];
  397. const expectedPrompt = dedent`
  398. <s>[INST] <<SYS>>
  399. You are a helpful assistant.
  400. <</SYS>>
  401. Hello [/INST] Hi there! How can I assist you today? </s><s>[INST] What's the weather like? [/INST]
  402. `;
  403. expect(formatPromptLlama2Chat(messages)).toBe(expectedPrompt);
  404. });
  405. it('should handle only a system message correctly', () => {
  406. const messages: LlamaMessage[] = [
  407. { role: 'system', content: 'You are a helpful assistant.' },
  408. ];
  409. const expectedPrompt = `${dedent`
  410. <s>[INST] <<SYS>>
  411. You are a helpful assistant.
  412. <</SYS>>
  413. `}\n\n`;
  414. expect(formatPromptLlama2Chat(messages)).toBe(expectedPrompt);
  415. });
  416. });
  417. });
Tip!

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

Comments

Loading...