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

google.test.ts 19 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
  1. import * as cache from '../../src/cache';
  2. import { GoogleChatProvider } from '../../src/providers/google';
  3. import * as vertexUtil from '../../src/providers/vertexUtil';
  4. jest.mock('../../src/cache', () => ({
  5. fetchWithCache: jest.fn(),
  6. }));
  7. jest.mock('../../src/providers/vertexUtil', () => ({
  8. maybeCoerceToGeminiFormat: jest.fn(),
  9. }));
  10. describe('GoogleChatProvider', () => {
  11. let provider: GoogleChatProvider;
  12. beforeEach(() => {
  13. provider = new GoogleChatProvider('gemini-pro', {
  14. config: {
  15. temperature: 0.7,
  16. maxOutputTokens: 100,
  17. topP: 0.9,
  18. topK: 40,
  19. },
  20. });
  21. });
  22. afterEach(() => {
  23. jest.clearAllMocks();
  24. });
  25. describe('constructor and configuration', () => {
  26. it('should handle API key from different sources', () => {
  27. // From config
  28. const providerWithConfigKey = new GoogleChatProvider('gemini-pro', {
  29. config: { apiKey: 'config-key' },
  30. });
  31. expect(providerWithConfigKey.getApiKey()).toBe('config-key');
  32. // From env override
  33. const providerWithEnvOverride = new GoogleChatProvider('gemini-pro', {
  34. env: { GOOGLE_API_KEY: 'env-key' },
  35. });
  36. expect(providerWithEnvOverride.getApiKey()).toBe('env-key');
  37. });
  38. it('should handle API host from different sources', () => {
  39. // From config
  40. const providerWithConfigHost = new GoogleChatProvider('gemini-pro', {
  41. config: { apiHost: 'custom.host.com' },
  42. });
  43. expect(providerWithConfigHost.getApiHost()).toBe('custom.host.com');
  44. // From env override
  45. const providerWithEnvOverride = new GoogleChatProvider('gemini-pro', {
  46. env: { GOOGLE_API_HOST: 'env.host.com' },
  47. });
  48. expect(providerWithEnvOverride.getApiHost()).toBe('env.host.com');
  49. });
  50. it('should handle custom provider ID', () => {
  51. const customId = 'custom-google-provider';
  52. const providerWithCustomId = new GoogleChatProvider('gemini-pro', {
  53. id: customId,
  54. });
  55. expect(providerWithCustomId.id()).toBe(customId);
  56. });
  57. it('should handle default configuration', () => {
  58. const defaultProvider = new GoogleChatProvider('gemini-pro');
  59. expect(defaultProvider.getApiHost()).toBe('generativelanguage.googleapis.com');
  60. expect(defaultProvider.id()).toBe('google:gemini-pro');
  61. });
  62. it('should handle configuration with safety settings', () => {
  63. const providerWithSafety = new GoogleChatProvider('gemini-pro', {
  64. config: {
  65. safetySettings: [
  66. { category: 'HARM_CATEGORY_HARASSMENT', probability: 'BLOCK_MEDIUM_AND_ABOVE' },
  67. ],
  68. },
  69. });
  70. expect(providerWithSafety).toBeDefined();
  71. });
  72. });
  73. describe('error handling', () => {
  74. it('should throw error when API key is not set', async () => {
  75. provider = new GoogleChatProvider('gemini-pro', {});
  76. await expect(provider.callApi('test')).rejects.toThrow('Google API key is not set');
  77. });
  78. it('should handle empty candidate responses', async () => {
  79. const provider = new GoogleChatProvider('gemini-pro', {
  80. config: {
  81. apiKey: 'test-key',
  82. },
  83. });
  84. // Mock maybeCoerceToGeminiFormat
  85. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValueOnce({
  86. contents: [{ role: 'user', parts: [{ text: 'test prompt' }] }],
  87. coerced: false,
  88. systemInstruction: undefined,
  89. });
  90. // Mock fetchWithCache to return empty candidates
  91. jest.mocked(cache.fetchWithCache).mockResolvedValueOnce({
  92. data: {
  93. candidates: [],
  94. },
  95. cached: false,
  96. status: 200,
  97. statusText: 'OK',
  98. headers: {},
  99. });
  100. const response = await provider.callGemini('test prompt');
  101. expect(response.error).toContain('API did not return any candidate responses');
  102. });
  103. it('should handle malformed API responses', async () => {
  104. const provider = new GoogleChatProvider('gemini-pro', {
  105. config: {
  106. apiKey: 'test-key',
  107. },
  108. });
  109. // Mock maybeCoerceToGeminiFormat
  110. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValueOnce({
  111. contents: [{ role: 'user', parts: [{ text: 'test prompt' }] }],
  112. coerced: false,
  113. systemInstruction: undefined,
  114. });
  115. // Mock fetchWithCache to return malformed response
  116. jest.mocked(cache.fetchWithCache).mockResolvedValueOnce({
  117. data: {
  118. candidates: [
  119. {
  120. content: {
  121. parts: null, // This will cause the map function to throw
  122. },
  123. },
  124. ],
  125. },
  126. cached: false,
  127. status: 200,
  128. statusText: 'OK',
  129. headers: {},
  130. });
  131. await expect(provider.callGemini('test prompt')).rejects.toThrow(
  132. "Cannot read properties of null (reading 'map')",
  133. );
  134. });
  135. });
  136. describe('non-Gemini models', () => {
  137. beforeEach(() => {
  138. provider = new GoogleChatProvider('palm2', {
  139. config: {
  140. temperature: 0.7,
  141. maxOutputTokens: 100,
  142. },
  143. });
  144. });
  145. it('should handle errors for non-Gemini models', async () => {
  146. const provider = new GoogleChatProvider('palm2', {
  147. config: {
  148. apiKey: 'test-key',
  149. },
  150. });
  151. // Mock fetchWithCache to return error response
  152. jest.mocked(cache.fetchWithCache).mockResolvedValueOnce({
  153. data: {
  154. error: {
  155. message: 'Model not found',
  156. },
  157. },
  158. cached: false,
  159. status: 404,
  160. statusText: 'Not Found',
  161. headers: {},
  162. });
  163. const response = await provider.callApi('test prompt');
  164. expect(response.error).toContain('Model not found');
  165. });
  166. it('should call the correct API endpoint for non-Gemini models', async () => {
  167. const provider = new GoogleChatProvider('palm2', {
  168. config: {
  169. apiKey: 'test-key',
  170. },
  171. });
  172. await provider.callApi('test prompt');
  173. expect(cache.fetchWithCache).toHaveBeenCalledWith(
  174. expect.stringContaining('v1beta3/models/palm2:generateMessage'),
  175. expect.objectContaining({
  176. method: 'POST',
  177. headers: expect.any(Object),
  178. body: expect.any(String),
  179. }),
  180. expect.any(Number),
  181. 'json',
  182. false,
  183. );
  184. });
  185. });
  186. describe('callGemini', () => {
  187. it('should call the Gemini API and return the response with token usage', async () => {
  188. const mockResponse = {
  189. data: {
  190. candidates: [{ content: { parts: [{ text: 'response text' }] } }],
  191. usageMetadata: {
  192. promptTokenCount: 10,
  193. candidatesTokenCount: 5,
  194. totalTokenCount: 15,
  195. },
  196. },
  197. cached: false,
  198. };
  199. jest.mocked(cache.fetchWithCache).mockResolvedValue(mockResponse as any);
  200. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValue({
  201. contents: [{ role: 'user', parts: [{ text: 'test prompt' }] }],
  202. coerced: false,
  203. systemInstruction: undefined,
  204. });
  205. const response = await provider.callGemini('test prompt');
  206. expect(response).toEqual({
  207. output: 'response text',
  208. tokenUsage: {
  209. prompt: 10,
  210. completion: 5,
  211. total: 15,
  212. numRequests: 1,
  213. },
  214. raw: mockResponse.data,
  215. cached: false,
  216. });
  217. expect(cache.fetchWithCache).toHaveBeenCalledWith(
  218. expect.stringContaining('v1beta/models/gemini-pro:generateContent'),
  219. expect.objectContaining({
  220. method: 'POST',
  221. body: expect.stringContaining(
  222. '"contents":[{"role":"user","parts":[{"text":"test prompt"}]}]',
  223. ),
  224. }),
  225. expect.any(Number),
  226. 'json',
  227. false,
  228. );
  229. });
  230. it('should handle cached responses correctly', async () => {
  231. const mockResponse = {
  232. data: {
  233. candidates: [{ content: { parts: [{ text: 'cached response' }] } }],
  234. usageMetadata: {
  235. totalTokenCount: 15,
  236. },
  237. },
  238. cached: true,
  239. };
  240. jest.mocked(cache.fetchWithCache).mockResolvedValue(mockResponse as any);
  241. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValue({
  242. contents: [{ role: 'user', parts: [{ text: 'test prompt' }] }],
  243. coerced: false,
  244. systemInstruction: undefined,
  245. });
  246. const response = await provider.callGemini('test prompt');
  247. expect(response).toEqual({
  248. output: 'cached response',
  249. tokenUsage: {
  250. cached: 15,
  251. total: 15,
  252. numRequests: 0,
  253. },
  254. raw: mockResponse.data,
  255. cached: true,
  256. });
  257. });
  258. it('should use v1alpha API for thinking model', async () => {
  259. provider = new GoogleChatProvider('gemini-2.0-flash-thinking-exp');
  260. const mockResponse = {
  261. data: {
  262. candidates: [{ content: { parts: [{ text: 'thinking response' }] } }],
  263. },
  264. cached: false,
  265. };
  266. jest.mocked(cache.fetchWithCache).mockResolvedValue(mockResponse as any);
  267. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValue({
  268. contents: [{ role: 'user', parts: [{ text: 'test prompt' }] }],
  269. coerced: false,
  270. systemInstruction: undefined,
  271. });
  272. await provider.callGemini('test prompt');
  273. expect(cache.fetchWithCache).toHaveBeenCalledWith(
  274. expect.stringContaining('v1alpha/models/gemini-2.0-flash-thinking-exp:generateContent'),
  275. expect.any(Object),
  276. expect.any(Number),
  277. 'json',
  278. false,
  279. );
  280. });
  281. it('should handle system messages correctly', async () => {
  282. const mockResponse = {
  283. data: {
  284. candidates: [{ content: { parts: [{ text: 'response text' }] } }],
  285. usageMetadata: {
  286. promptTokenCount: 10,
  287. candidatesTokenCount: 5,
  288. totalTokenCount: 15,
  289. },
  290. },
  291. cached: false,
  292. };
  293. jest.mocked(cache.fetchWithCache).mockResolvedValue(mockResponse as any);
  294. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValue({
  295. contents: [
  296. { role: 'system' as any, parts: [{ text: 'system instruction' }] },
  297. { role: 'user', parts: [{ text: 'user message' }] },
  298. ],
  299. coerced: false,
  300. systemInstruction: undefined,
  301. } as any);
  302. const response = await provider.callGemini('test prompt');
  303. expect(response).toEqual({
  304. output: 'response text',
  305. tokenUsage: {
  306. prompt: 10,
  307. completion: 5,
  308. total: 15,
  309. numRequests: 1,
  310. },
  311. raw: mockResponse.data,
  312. cached: false,
  313. });
  314. expect(cache.fetchWithCache).toHaveBeenCalledWith(
  315. expect.stringContaining('v1beta/models/gemini-pro:generateContent'),
  316. expect.objectContaining({
  317. method: 'POST',
  318. headers: expect.objectContaining({
  319. 'Content-Type': 'application/json',
  320. }),
  321. body: expect.stringContaining(
  322. '"contents":[{"role":"system","parts":[{"text":"system instruction"}]},{"role":"user","parts":[{"text":"user message"}]}]',
  323. ),
  324. }),
  325. expect.any(Number),
  326. 'json',
  327. false,
  328. );
  329. });
  330. it('should handle API call errors', async () => {
  331. const provider = new GoogleChatProvider('gemini-pro', {
  332. config: {
  333. apiKey: 'test-key',
  334. },
  335. });
  336. // Mock maybeCoerceToGeminiFormat
  337. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValueOnce({
  338. contents: [{ role: 'user', parts: [{ text: 'test prompt' }] }],
  339. coerced: false,
  340. systemInstruction: undefined,
  341. });
  342. // Mock fetchWithCache to return error
  343. jest.mocked(cache.fetchWithCache).mockRejectedValueOnce(new Error('API call failed'));
  344. const response = await provider.callGemini('test prompt');
  345. expect(response.error).toContain('API call failed');
  346. });
  347. it('should handle response schema', async () => {
  348. provider = new GoogleChatProvider('gemini-pro', {
  349. config: {
  350. responseSchema: '{"type":"object","properties":{"name":{"type":"string"}}}',
  351. },
  352. });
  353. const mockResponse = {
  354. data: {
  355. candidates: [{ content: { parts: [{ text: '{"name":"John"}' }] } }],
  356. usageMetadata: {
  357. promptTokenCount: 10,
  358. candidatesTokenCount: 5,
  359. totalTokenCount: 15,
  360. },
  361. },
  362. cached: false,
  363. };
  364. jest.mocked(cache.fetchWithCache).mockResolvedValue(mockResponse as any);
  365. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValue({
  366. contents: [{ role: 'user', parts: [{ text: 'test prompt' }] }],
  367. coerced: false,
  368. systemInstruction: undefined,
  369. });
  370. const response = await provider.callGemini('test prompt');
  371. expect(response.tokenUsage).toEqual({
  372. prompt: 10,
  373. completion: 5,
  374. total: 15,
  375. numRequests: 1,
  376. });
  377. expect(cache.fetchWithCache).toHaveBeenCalledWith(
  378. expect.any(String),
  379. expect.objectContaining({
  380. body: expect.stringMatching(/response_schema.*response_mime_type/),
  381. }),
  382. expect.any(Number),
  383. 'json',
  384. false,
  385. );
  386. });
  387. it('should handle safety ratings', async () => {
  388. const mockResponse = {
  389. data: {
  390. candidates: [
  391. {
  392. content: { parts: [{ text: 'response text' }] },
  393. safetyRatings: [{ category: 'HARM_CATEGORY', probability: 'HIGH' }],
  394. },
  395. ],
  396. promptFeedback: {
  397. safetyRatings: [{ category: 'HARM_CATEGORY', probability: 'NEGLIGIBLE' }],
  398. },
  399. },
  400. cached: false,
  401. };
  402. jest.mocked(cache.fetchWithCache).mockResolvedValue(mockResponse as any);
  403. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValue({
  404. contents: [{ role: 'user', parts: [{ text: 'test prompt' }] }],
  405. coerced: false,
  406. systemInstruction: undefined,
  407. });
  408. const response = await provider.callGemini('test prompt');
  409. expect(response.guardrails).toEqual({
  410. flaggedInput: false,
  411. flaggedOutput: true,
  412. flagged: true,
  413. });
  414. });
  415. it('should handle structured output with response schema', async () => {
  416. provider = new GoogleChatProvider('gemini-pro', {
  417. config: {
  418. generationConfig: {
  419. response_mime_type: 'application/json',
  420. response_schema: '{"type":"object","properties":{"name":{"type":"string"}}}',
  421. },
  422. },
  423. });
  424. const mockResponse = {
  425. data: {
  426. candidates: [
  427. {
  428. content: {
  429. parts: [{ text: '{"name":"John"}' }],
  430. role: 'model',
  431. },
  432. finishReason: 'STOP',
  433. },
  434. ],
  435. usageMetadata: {
  436. promptTokenCount: 10,
  437. candidatesTokenCount: 5,
  438. totalTokenCount: 15,
  439. },
  440. },
  441. cached: false,
  442. };
  443. jest.mocked(cache.fetchWithCache).mockResolvedValue(mockResponse as any);
  444. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValue({
  445. contents: [{ role: 'user', parts: [{ text: 'test prompt' }] }],
  446. coerced: false,
  447. systemInstruction: undefined,
  448. });
  449. const response = await provider.callGemini('test prompt');
  450. expect(response.tokenUsage).toEqual({
  451. prompt: 10,
  452. completion: 5,
  453. total: 15,
  454. numRequests: 1,
  455. });
  456. expect(cache.fetchWithCache).toHaveBeenCalledWith(
  457. expect.any(String),
  458. expect.objectContaining({
  459. body: expect.stringContaining('"response_mime_type":"application/json"'),
  460. }),
  461. expect.any(Number),
  462. 'json',
  463. false,
  464. );
  465. });
  466. it('should handle multipart messages', async () => {
  467. const mockResponse = {
  468. data: {
  469. candidates: [{ content: { parts: [{ text: 'multipart response' }] } }],
  470. },
  471. cached: false,
  472. };
  473. jest.mocked(cache.fetchWithCache).mockResolvedValue(mockResponse as any);
  474. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValue({
  475. contents: [
  476. {
  477. role: 'user',
  478. parts: [{ text: 'First part' }, { text: 'Second part' }],
  479. },
  480. ],
  481. coerced: false,
  482. systemInstruction: undefined,
  483. });
  484. const response = await provider.callGemini('First part\nSecond part');
  485. expect(response.output).toBe('multipart response');
  486. expect(cache.fetchWithCache).toHaveBeenCalledWith(
  487. expect.any(String),
  488. expect.objectContaining({
  489. body: expect.stringMatching(/parts.*First part.*Second part/),
  490. }),
  491. expect.any(Number),
  492. 'json',
  493. false,
  494. );
  495. });
  496. it('should handle additional configuration options', async () => {
  497. provider = new GoogleChatProvider('gemini-pro', {
  498. config: {
  499. generationConfig: {
  500. temperature: 0.9,
  501. topP: 0.95,
  502. topK: 50,
  503. maxOutputTokens: 200,
  504. stopSequences: ['END'],
  505. },
  506. },
  507. });
  508. const mockResponse = {
  509. data: {
  510. candidates: [{ content: { parts: [{ text: 'response text' }] } }],
  511. },
  512. cached: false,
  513. };
  514. jest.mocked(cache.fetchWithCache).mockResolvedValue(mockResponse as any);
  515. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValue({
  516. contents: [{ role: 'user', parts: [{ text: 'test prompt' }] }],
  517. coerced: false,
  518. systemInstruction: undefined,
  519. });
  520. await provider.callGemini('test prompt');
  521. expect(cache.fetchWithCache).toHaveBeenCalledWith(
  522. expect.any(String),
  523. expect.objectContaining({
  524. body: expect.stringContaining(
  525. '"generationConfig":{"temperature":0.9,"topP":0.95,"topK":50,"maxOutputTokens":200,"stopSequences":["END"]}',
  526. ),
  527. }),
  528. expect.any(Number),
  529. 'json',
  530. false,
  531. );
  532. });
  533. it('should handle API version selection', async () => {
  534. const v1alphaProvider = new GoogleChatProvider('gemini-2.0-flash-thinking-exp');
  535. const v1betaProvider = new GoogleChatProvider('gemini-pro');
  536. const mockResponse = {
  537. data: {
  538. candidates: [{ content: { parts: [{ text: 'response' }] } }],
  539. },
  540. cached: false,
  541. };
  542. jest.mocked(cache.fetchWithCache).mockResolvedValue(mockResponse as any);
  543. jest.mocked(vertexUtil.maybeCoerceToGeminiFormat).mockReturnValue({
  544. contents: [{ role: 'user', parts: [{ text: 'test prompt' }] }],
  545. coerced: false,
  546. systemInstruction: undefined,
  547. });
  548. await v1alphaProvider.callGemini('test prompt');
  549. await v1betaProvider.callGemini('test prompt');
  550. expect(cache.fetchWithCache).toHaveBeenNthCalledWith(
  551. 1,
  552. expect.stringContaining('v1alpha'),
  553. expect.any(Object),
  554. expect.any(Number),
  555. 'json',
  556. false,
  557. );
  558. expect(cache.fetchWithCache).toHaveBeenNthCalledWith(
  559. 2,
  560. expect.stringContaining('v1beta'),
  561. expect.any(Object),
  562. expect.any(Number),
  563. 'json',
  564. false,
  565. );
  566. });
  567. });
  568. });
Tip!

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

Comments

Loading...