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

watsonx.test.ts 18 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
  1. import { WatsonXAI } from '@ibm-cloud/watsonx-ai';
  2. import { IamAuthenticator, BearerTokenAuthenticator } from 'ibm-cloud-sdk-core';
  3. import { getCache, isCacheEnabled, fetchWithCache } from '../../src/cache';
  4. import * as envarsModule from '../../src/envars';
  5. import logger from '../../src/logger';
  6. import {
  7. WatsonXProvider,
  8. generateConfigHash,
  9. clearModelSpecsCache,
  10. } from '../../src/providers/watsonx';
  11. jest.mock('@ibm-cloud/watsonx-ai', () => ({
  12. WatsonXAI: {
  13. newInstance: jest.fn(),
  14. },
  15. }));
  16. jest.mock('ibm-cloud-sdk-core', () => ({
  17. IamAuthenticator: jest.fn(),
  18. BearerTokenAuthenticator: jest.fn(),
  19. }));
  20. jest.mock('../../src/cache', () => ({
  21. getCache: jest.fn(),
  22. isCacheEnabled: jest.fn(),
  23. fetchWithCache: jest.fn().mockImplementation(async () => ({
  24. data: {
  25. resources: [
  26. {
  27. model_id: 'meta-llama/llama-3-2-1b-instruct',
  28. input_tier: 'class_c1',
  29. output_tier: 'class_c1',
  30. label: 'llama-3-2-1b-instruct',
  31. provider: 'Meta',
  32. source: 'Hugging Face',
  33. model_limits: {
  34. max_sequence_length: 131072,
  35. max_output_tokens: 8192,
  36. },
  37. },
  38. ],
  39. },
  40. cached: false,
  41. })),
  42. }));
  43. jest.mock('../../src/envars', () => ({
  44. getEnvString: jest.fn(),
  45. getEnvInt: jest.fn(),
  46. }));
  47. describe('WatsonXProvider', () => {
  48. const modelName = 'test-model';
  49. const config = {
  50. apiKey: 'test-api-key',
  51. projectId: 'test-project-id',
  52. modelId: 'test-model-id',
  53. maxNewTokens: 50,
  54. };
  55. const prompt = 'Test prompt';
  56. beforeEach(() => {
  57. jest.clearAllMocks();
  58. });
  59. describe('constructor', () => {
  60. it('should initialize with modelName and config', async () => {
  61. const mockedWatsonXAIClient: Partial<any> = {
  62. generateText: jest.fn(),
  63. };
  64. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  65. const provider = new WatsonXProvider(modelName, { config });
  66. expect(provider.modelName).toBe(modelName);
  67. expect(provider.options.config).toEqual(config);
  68. // Get client to trigger authentication
  69. await provider.getClient();
  70. expect(logger.info).toHaveBeenCalledWith('Using IAM Authentication.');
  71. });
  72. it('should initialize with default id based on modelName', () => {
  73. const mockedWatsonXAIClient: Partial<any> = {
  74. generateText: jest.fn(),
  75. };
  76. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  77. const provider = new WatsonXProvider(modelName, { config });
  78. expect(provider.id()).toBe(`watsonx:${modelName}`);
  79. });
  80. });
  81. describe('id', () => {
  82. it('should return the correct id string', () => {
  83. const mockedWatsonXAIClient: Partial<any> = {
  84. generateText: jest.fn(),
  85. };
  86. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  87. const provider = new WatsonXProvider(modelName, { config });
  88. expect(provider.id()).toBe(`watsonx:${modelName}`);
  89. });
  90. });
  91. describe('toString', () => {
  92. it('should return the correct string representation', () => {
  93. const mockedWatsonXAIClient: Partial<any> = {
  94. generateText: jest.fn(),
  95. };
  96. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  97. const provider = new WatsonXProvider(modelName, { config });
  98. expect(provider.toString()).toBe(`[Watsonx Provider ${modelName}]`);
  99. });
  100. });
  101. describe('getClient', () => {
  102. it('should initialize WatsonXAI client with correct parameters', async () => {
  103. const mockedWatsonXAIClient: Partial<any> = {
  104. generateText: jest.fn(),
  105. };
  106. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  107. const provider = new WatsonXProvider(modelName, { config });
  108. const client = await provider.getClient();
  109. expect(WatsonXAI.newInstance).toHaveBeenCalledWith({
  110. version: '2023-05-29',
  111. serviceUrl: 'https://us-south.ml.cloud.ibm.com',
  112. authenticator: expect.any(IamAuthenticator),
  113. });
  114. expect(IamAuthenticator).toHaveBeenCalledWith({ apikey: 'test-api-key' });
  115. expect(client).toBe(mockedWatsonXAIClient);
  116. });
  117. it('should throw an error if neither API key nor Bearer Token is set', async () => {
  118. jest.spyOn(envarsModule, 'getEnvString').mockReturnValue(undefined as any);
  119. const provider = new WatsonXProvider(modelName, {
  120. config: { ...config, apiKey: undefined, apiBearerToken: undefined },
  121. });
  122. await expect(provider.getClient()).rejects.toThrow(
  123. /Authentication credentials not provided\. Please set either `WATSONX_AI_APIKEY` for IAM Authentication or `WATSONX_AI_BEARER_TOKEN` for Bearer Token Authentication\./,
  124. );
  125. });
  126. });
  127. describe('constructor with Bearer Token', () => {
  128. it('should use Bearer Token Authentication when apiKey is not provided', async () => {
  129. const bearerTokenConfig = {
  130. ...config,
  131. apiKey: undefined,
  132. apiBearerToken: 'test-bearer-token',
  133. };
  134. const mockedWatsonXAIClient: Partial<any> = {
  135. generateText: jest.fn(),
  136. };
  137. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  138. const provider = new WatsonXProvider(modelName, { config: bearerTokenConfig });
  139. await provider.getClient();
  140. expect(logger.info).toHaveBeenCalledWith('Using Bearer Token Authentication.');
  141. expect(WatsonXAI.newInstance).toHaveBeenCalledWith({
  142. version: '2023-05-29',
  143. serviceUrl: 'https://us-south.ml.cloud.ibm.com',
  144. authenticator: expect.any(BearerTokenAuthenticator),
  145. });
  146. });
  147. it('should prefer API Key Authentication over Bearer Token Authentication when both are provided', async () => {
  148. const dualAuthConfig = { ...config, apiBearerToken: 'test-bearer-token' };
  149. const mockedWatsonXAIClient: Partial<any> = {
  150. generateText: jest.fn(),
  151. };
  152. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  153. const provider = new WatsonXProvider(modelName, { config: dualAuthConfig });
  154. await provider.getClient();
  155. expect(logger.info).toHaveBeenCalledWith('Using IAM Authentication.');
  156. expect(WatsonXAI.newInstance).toHaveBeenCalledWith({
  157. version: '2023-05-29',
  158. serviceUrl: 'https://us-south.ml.cloud.ibm.com',
  159. authenticator: expect.any(IamAuthenticator),
  160. });
  161. });
  162. it('should use IAM Authentication when WATSONX_AI_AUTH_TYPE is set to iam', async () => {
  163. const dualAuthConfig = { ...config, apiBearerToken: 'test-bearer-token' };
  164. const mockedWatsonXAIClient: Partial<any> = {
  165. generateText: jest.fn(),
  166. };
  167. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  168. const provider = new WatsonXProvider(modelName, {
  169. config: dualAuthConfig,
  170. env: { WATSONX_AI_AUTH_TYPE: 'iam' },
  171. });
  172. await provider.getClient();
  173. expect(logger.info).toHaveBeenCalledWith(
  174. 'Using IAM Authentication based on WATSONX_AI_AUTH_TYPE.',
  175. );
  176. expect(WatsonXAI.newInstance).toHaveBeenCalledWith({
  177. version: '2023-05-29',
  178. serviceUrl: 'https://us-south.ml.cloud.ibm.com',
  179. authenticator: expect.any(IamAuthenticator),
  180. });
  181. });
  182. it('should use Bearer Token Authentication when WATSONX_AI_AUTH_TYPE is set to bearertoken', async () => {
  183. const dualAuthConfig = {
  184. ...config,
  185. apiKey: 'test-api-key',
  186. apiBearerToken: 'test-bearer-token',
  187. };
  188. const mockedWatsonXAIClient: Partial<any> = {
  189. generateText: jest.fn(),
  190. };
  191. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  192. const provider = new WatsonXProvider(modelName, {
  193. config: dualAuthConfig,
  194. env: { WATSONX_AI_AUTH_TYPE: 'bearertoken' },
  195. });
  196. await provider.getClient();
  197. expect(logger.info).toHaveBeenCalledWith(
  198. 'Using Bearer Token Authentication based on WATSONX_AI_AUTH_TYPE.',
  199. );
  200. expect(WatsonXAI.newInstance).toHaveBeenCalledWith({
  201. version: '2023-05-29',
  202. serviceUrl: 'https://us-south.ml.cloud.ibm.com',
  203. authenticator: expect.any(BearerTokenAuthenticator),
  204. });
  205. });
  206. it('should fallback to default behavior when WATSONX_AI_AUTH_TYPE is invalid', async () => {
  207. const dualAuthConfig = { ...config, apiBearerToken: 'test-bearer-token' };
  208. const mockedWatsonXAIClient: Partial<any> = {
  209. generateText: jest.fn(),
  210. };
  211. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  212. const provider = new WatsonXProvider(modelName, {
  213. config: dualAuthConfig,
  214. env: { WATSONX_AI_AUTH_TYPE: 'invalid' },
  215. });
  216. await provider.getClient();
  217. expect(logger.info).toHaveBeenCalledWith('Using IAM Authentication.');
  218. expect(WatsonXAI.newInstance).toHaveBeenCalledWith({
  219. version: '2023-05-29',
  220. serviceUrl: 'https://us-south.ml.cloud.ibm.com',
  221. authenticator: expect.any(IamAuthenticator),
  222. });
  223. });
  224. });
  225. describe('callApi', () => {
  226. it('should call generateText with correct parameters and return the correct response', async () => {
  227. const mockedWatsonXAIClient: Partial<any> = {
  228. generateText: jest.fn().mockResolvedValue({
  229. result: {
  230. model_id: 'ibm/test-model',
  231. model_version: '1.0.0',
  232. created_at: '2023-10-10T00:00:00Z',
  233. results: [
  234. {
  235. generated_text: 'Test response from WatsonX',
  236. generated_token_count: 10,
  237. input_token_count: 5,
  238. stop_reason: 'max_tokens',
  239. },
  240. ],
  241. },
  242. }),
  243. };
  244. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  245. const cache: Partial<any> = {
  246. get: jest.fn().mockResolvedValue(null),
  247. set: jest.fn(),
  248. wrap: jest.fn(),
  249. del: jest.fn(),
  250. reset: jest.fn(),
  251. store: {} as any,
  252. };
  253. jest.mocked(getCache).mockReturnValue(cache as any);
  254. jest.mocked(isCacheEnabled).mockReturnValue(true);
  255. const provider = new WatsonXProvider(modelName, { config });
  256. const response = await provider.callApi(prompt);
  257. expect(mockedWatsonXAIClient.generateText).toHaveBeenCalledWith({
  258. input: prompt,
  259. modelId: config.modelId,
  260. projectId: config.projectId,
  261. parameters: {
  262. max_new_tokens: config.maxNewTokens,
  263. },
  264. });
  265. expect(response).toEqual({
  266. error: undefined,
  267. output: 'Test response from WatsonX',
  268. tokenUsage: {
  269. total: 10,
  270. prompt: 5,
  271. completion: 5,
  272. },
  273. cost: undefined,
  274. cached: undefined,
  275. logProbs: undefined,
  276. });
  277. expect(cache.set).toHaveBeenCalledWith(
  278. `watsonx:${modelName}:${generateConfigHash(config)}:${prompt}`,
  279. JSON.stringify(response),
  280. );
  281. });
  282. it('should return cached response if available', async () => {
  283. const cachedResponse = {
  284. error: undefined,
  285. output: 'Cached response',
  286. tokenUsage: {
  287. total: 8,
  288. prompt: 3,
  289. completion: 5,
  290. },
  291. cost: undefined,
  292. cached: undefined,
  293. logProbs: undefined,
  294. };
  295. const cacheKey = `watsonx:${modelName}:${generateConfigHash(config)}:${prompt}`;
  296. const cache: Partial<any> = {
  297. get: jest.fn().mockResolvedValue(JSON.stringify(cachedResponse)),
  298. set: jest.fn(),
  299. wrap: jest.fn(),
  300. del: jest.fn(),
  301. reset: jest.fn(),
  302. store: {} as any,
  303. };
  304. jest.mocked(getCache).mockReturnValue(cache as any);
  305. jest.mocked(isCacheEnabled).mockReturnValue(true);
  306. const provider = new WatsonXProvider(modelName, { config });
  307. const generateTextSpy = jest.spyOn(await provider.getClient(), 'generateText');
  308. const response = await provider.callApi(prompt);
  309. expect(cache.get).toHaveBeenCalledWith(cacheKey);
  310. expect(response).toEqual(cachedResponse);
  311. expect(generateTextSpy).not.toHaveBeenCalled();
  312. });
  313. it('should handle API errors gracefully', async () => {
  314. const mockedWatsonXAIClient: Partial<any> = {
  315. generateText: jest.fn().mockRejectedValue(new Error('API error')),
  316. };
  317. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  318. const cache: Partial<any> = {
  319. get: jest.fn().mockResolvedValue(null),
  320. set: jest.fn(),
  321. wrap: jest.fn(),
  322. del: jest.fn(),
  323. reset: jest.fn(),
  324. store: {} as any,
  325. };
  326. jest.mocked(getCache).mockReturnValue(cache as any);
  327. jest.mocked(isCacheEnabled).mockReturnValue(true);
  328. const provider = new WatsonXProvider(modelName, { config });
  329. const response = await provider.callApi(prompt);
  330. expect(response).toEqual({
  331. error: 'API call error: Error: API error',
  332. output: '',
  333. tokenUsage: {},
  334. });
  335. expect(logger.error).toHaveBeenCalledWith('Watsonx: API call error: Error: API error');
  336. });
  337. });
  338. describe('calculateWatsonXCost', () => {
  339. const MODEL_ID = 'meta-llama/llama-3-2-1b-instruct';
  340. const configWithModelId = {
  341. ...config,
  342. modelId: MODEL_ID,
  343. };
  344. beforeEach(() => {
  345. jest.clearAllMocks();
  346. clearModelSpecsCache();
  347. jest.mocked(fetchWithCache).mockImplementation(async () => ({
  348. data: {
  349. resources: [
  350. {
  351. model_id: MODEL_ID,
  352. input_tier: 'class_c1',
  353. output_tier: 'class_c1',
  354. label: 'llama-3-2-1b-instruct',
  355. provider: 'Meta',
  356. source: 'Hugging Face',
  357. model_limits: {
  358. max_sequence_length: 131072,
  359. max_output_tokens: 8192,
  360. },
  361. },
  362. ],
  363. },
  364. cached: false,
  365. status: 200,
  366. statusText: 'OK',
  367. headers: {},
  368. }));
  369. });
  370. it('should calculate cost correctly when token counts are provided', async () => {
  371. const mockedWatsonXAIClient: Partial<any> = {
  372. generateText: jest.fn().mockResolvedValue({
  373. result: {
  374. model_id: MODEL_ID,
  375. model_version: '3.2.0',
  376. created_at: '2024-03-25T00:00:00Z',
  377. results: [
  378. {
  379. generated_text: 'Test response',
  380. generated_token_count: 100,
  381. input_token_count: 50,
  382. stop_reason: 'max_tokens',
  383. },
  384. ],
  385. },
  386. }),
  387. };
  388. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  389. const cache: Partial<any> = {
  390. get: jest.fn().mockResolvedValue(null),
  391. set: jest.fn(),
  392. };
  393. jest.mocked(getCache).mockReturnValue(cache as any);
  394. jest.mocked(isCacheEnabled).mockReturnValue(true);
  395. const provider = new WatsonXProvider(MODEL_ID, { config: configWithModelId });
  396. const response = await provider.callApi(prompt);
  397. expect(response.cost).toBeDefined();
  398. expect(typeof response.cost).toBe('number');
  399. // For class_c1 tier ($0.0001 per 1M tokens)
  400. // Input: 50 tokens * $0.0001/1M = 0.000005
  401. // Output: 50 tokens * $0.0001/1M = 0.000005
  402. // Total expected: 0.00001
  403. expect(response.cost).toBeCloseTo(0.00001, 6);
  404. });
  405. it('should calculate cost correctly for class_9 tier', async () => {
  406. const modelId = 'meta-llama/llama-3-2-11b-vision-instruct';
  407. const configWithClass9ModelId = { ...config, modelId };
  408. clearModelSpecsCache();
  409. jest.mocked(fetchWithCache).mockImplementation(async () => ({
  410. data: {
  411. resources: [
  412. {
  413. model_id: modelId,
  414. label: 'llama-3-2-11b-vision-instruct',
  415. provider: 'Meta',
  416. source: 'Hugging Face',
  417. functions: [{ id: 'image_chat' }, { id: 'text_chat' }, { id: 'text_generation' }],
  418. input_tier: 'class_9',
  419. output_tier: 'class_9',
  420. number_params: '11b',
  421. model_limits: {
  422. max_sequence_length: 131072,
  423. max_output_tokens: 8192,
  424. },
  425. },
  426. ],
  427. },
  428. cached: false,
  429. status: 200,
  430. statusText: 'OK',
  431. headers: {},
  432. }));
  433. const mockedWatsonXAIClient: Partial<any> = {
  434. generateText: jest.fn().mockResolvedValue({
  435. result: {
  436. model_id: modelId,
  437. model_version: '3.2.0',
  438. created_at: '2024-03-25T00:00:00Z',
  439. results: [
  440. {
  441. generated_text: 'Test response',
  442. generated_token_count: 100,
  443. input_token_count: 50,
  444. stop_reason: 'max_tokens',
  445. },
  446. ],
  447. },
  448. }),
  449. };
  450. jest.mocked(WatsonXAI.newInstance).mockReturnValue(mockedWatsonXAIClient as any);
  451. const cache: Partial<any> = {
  452. get: jest.fn().mockResolvedValue(null),
  453. set: jest.fn(),
  454. };
  455. jest.mocked(getCache).mockReturnValue(cache as any);
  456. jest.mocked(isCacheEnabled).mockReturnValue(true);
  457. const provider = new WatsonXProvider(modelId, { config: configWithClass9ModelId });
  458. const response = await provider.callApi(prompt);
  459. expect(response.cost).toBeDefined();
  460. expect(typeof response.cost).toBe('number');
  461. // For class_9 tier ($0.00035 per 1M tokens)
  462. // Input: 50 tokens * $0.00035/1M = 0.0000175
  463. // Output: 50 tokens * $0.00035/1M = 0.0000175
  464. // Total expected: 0.000035
  465. expect(response.cost).toBeCloseTo(0.000035, 6);
  466. });
  467. });
  468. });
Tip!

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

Comments

Loading...