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

groq.test.ts 13 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
  1. import { clearCache } from '../../src/cache';
  2. import * as fetchModule from '../../src/fetch';
  3. import { GroqProvider } from '../../src/providers/groq';
  4. const GROQ_API_BASE = 'https://api.groq.com/openai/v1';
  5. jest.mock('../../src/util', () => ({
  6. maybeLoadFromExternalFile: jest.fn((x) => x),
  7. renderVarsInObject: jest.fn((x) => x),
  8. }));
  9. jest.mock('../../src/fetch');
  10. describe('Groq', () => {
  11. const mockedFetchWithRetries = jest.mocked(fetchModule.fetchWithRetries);
  12. afterEach(async () => {
  13. await clearCache();
  14. jest.clearAllMocks();
  15. });
  16. describe('GroqProvider', () => {
  17. const provider = new GroqProvider('mixtral-8x7b-32768', {});
  18. it('should initialize with correct model name', () => {
  19. expect(provider.modelName).toBe('mixtral-8x7b-32768');
  20. });
  21. it('should return correct id', () => {
  22. expect(provider.id()).toBe('groq:mixtral-8x7b-32768');
  23. });
  24. it('should return correct string representation', () => {
  25. expect(provider.toString()).toBe('[Groq Provider mixtral-8x7b-32768]');
  26. });
  27. it('should identify reasoning models correctly', () => {
  28. const regularProvider = new GroqProvider('mixtral-8x7b-32768', {});
  29. const deepseekProvider = new GroqProvider('deepseek-r1-distill-llama-70b', {});
  30. const o1Provider = new GroqProvider('o1-mini', {});
  31. expect(regularProvider['isReasoningModel']()).toBe(false);
  32. expect(deepseekProvider['isReasoningModel']()).toBe(true);
  33. expect(o1Provider['isReasoningModel']()).toBe(true);
  34. });
  35. it('should handle temperature support correctly', () => {
  36. const regularProvider = new GroqProvider('mixtral-8x7b-32768', {});
  37. const deepseekProvider = new GroqProvider('deepseek-r1-distill-llama-70b', {});
  38. const o1Provider = new GroqProvider('o1-mini', {});
  39. expect(regularProvider['supportsTemperature']()).toBe(true);
  40. expect(deepseekProvider['supportsTemperature']()).toBe(true);
  41. expect(o1Provider['supportsTemperature']()).toBe(false);
  42. });
  43. it('should serialize to JSON correctly without API key', () => {
  44. const provider = new GroqProvider('mixtral-8x7b-32768', {
  45. config: {
  46. temperature: 0.7,
  47. max_tokens: 100,
  48. },
  49. });
  50. expect(provider.toJSON()).toEqual({
  51. provider: 'groq',
  52. model: 'mixtral-8x7b-32768',
  53. config: {
  54. temperature: 0.7,
  55. max_tokens: 100,
  56. apiKeyEnvar: 'GROQ_API_KEY',
  57. apiBaseUrl: GROQ_API_BASE,
  58. },
  59. });
  60. });
  61. it('should serialize to JSON correctly with API key redacted', () => {
  62. const provider = new GroqProvider('mixtral-8x7b-32768', {
  63. config: {
  64. apiKey: 'secret-api-key',
  65. temperature: 0.7,
  66. },
  67. });
  68. const json = provider.toJSON();
  69. expect(json).toEqual({
  70. provider: 'groq',
  71. model: 'mixtral-8x7b-32768',
  72. config: {
  73. temperature: 0.7,
  74. apiKey: undefined,
  75. apiKeyEnvar: 'GROQ_API_KEY',
  76. apiBaseUrl: GROQ_API_BASE,
  77. },
  78. });
  79. expect(provider['apiKey']).toBe('secret-api-key');
  80. });
  81. it('should handle configuration options correctly', () => {
  82. const provider = new GroqProvider('mixtral-8x7b-32768', {
  83. config: {
  84. systemPrompt: 'You are a helpful assistant',
  85. parallel_tool_calls: true,
  86. reasoning_format: 'markdown',
  87. service_tier: 'premium',
  88. user: 'test-user',
  89. },
  90. });
  91. expect(provider.toJSON().config).toMatchObject({
  92. systemPrompt: 'You are a helpful assistant',
  93. parallel_tool_calls: true,
  94. reasoning_format: 'markdown',
  95. service_tier: 'premium',
  96. user: 'test-user',
  97. });
  98. });
  99. describe('callApi', () => {
  100. beforeEach(() => {
  101. process.env.GROQ_API_KEY = 'test-key';
  102. });
  103. afterEach(() => {
  104. delete process.env.GROQ_API_KEY;
  105. });
  106. it('should call Groq API and return output with correct structure', async () => {
  107. const mockResponse = {
  108. choices: [{ message: { content: 'Test output' } }],
  109. usage: { total_tokens: 10, prompt_tokens: 5, completion_tokens: 5 },
  110. };
  111. const response = new Response(JSON.stringify(mockResponse), {
  112. status: 200,
  113. statusText: 'OK',
  114. headers: new Headers({ 'Content-Type': 'application/json' }),
  115. });
  116. mockedFetchWithRetries.mockResolvedValueOnce(response);
  117. const result = await provider.callApi('Test prompt');
  118. const expectedBody = {
  119. model: 'mixtral-8x7b-32768',
  120. messages: [{ role: 'user', content: 'Test prompt' }],
  121. max_tokens: 1024,
  122. };
  123. expect(mockedFetchWithRetries).toHaveBeenCalledWith(
  124. `${GROQ_API_BASE}/chat/completions`,
  125. {
  126. method: 'POST',
  127. headers: {
  128. 'Content-Type': 'application/json',
  129. Authorization: 'Bearer test-key',
  130. },
  131. body: JSON.stringify(expectedBody),
  132. },
  133. 300000,
  134. undefined,
  135. );
  136. expect(result).toEqual({
  137. output: 'Test output',
  138. tokenUsage: {
  139. total: 10,
  140. prompt: 5,
  141. completion: 5,
  142. },
  143. cached: false,
  144. cost: undefined,
  145. logProbs: undefined,
  146. });
  147. });
  148. it('should use cache by default', async () => {
  149. const mockResponse = {
  150. choices: [{ message: { content: 'Cached output' } }],
  151. usage: { total_tokens: 10, prompt_tokens: 5, completion_tokens: 5 },
  152. };
  153. const response = new Response(JSON.stringify(mockResponse), {
  154. status: 200,
  155. statusText: 'OK',
  156. headers: new Headers({ 'Content-Type': 'application/json' }),
  157. });
  158. mockedFetchWithRetries.mockResolvedValue(response);
  159. await provider.callApi('Test prompt');
  160. const cachedResult = await provider.callApi('Test prompt');
  161. expect(mockedFetchWithRetries).toHaveBeenCalledTimes(1);
  162. expect(cachedResult).toEqual({
  163. output: 'Cached output',
  164. cached: true,
  165. cost: undefined,
  166. logProbs: undefined,
  167. tokenUsage: {
  168. total: 10,
  169. cached: 10,
  170. },
  171. });
  172. });
  173. it('should handle API errors', async () => {
  174. const errorResponse = {
  175. error: {
  176. message: 'API Error',
  177. type: 'invalid_request_error',
  178. },
  179. };
  180. const response = new Response(JSON.stringify(errorResponse), {
  181. status: 400,
  182. statusText: 'Bad Request',
  183. headers: new Headers({ 'Content-Type': 'application/json' }),
  184. });
  185. mockedFetchWithRetries.mockResolvedValueOnce(response);
  186. const result = await provider.callApi('Test prompt');
  187. expect(result.error).toContain('400 Bad Request');
  188. });
  189. it('should handle network errors', async () => {
  190. mockedFetchWithRetries.mockRejectedValueOnce(new Error('Network error'));
  191. const result = await provider.callApi('Test prompt');
  192. expect(result.error).toContain('Network error');
  193. });
  194. it('should handle empty response', async () => {
  195. const mockResponse = {
  196. choices: [{ message: { content: '' } }],
  197. usage: { total_tokens: 10, prompt_tokens: 5, completion_tokens: 5 },
  198. };
  199. const response = new Response(JSON.stringify(mockResponse), {
  200. status: 200,
  201. statusText: 'OK',
  202. headers: new Headers({ 'Content-Type': 'application/json' }),
  203. });
  204. mockedFetchWithRetries.mockResolvedValueOnce(response);
  205. const result = await provider.callApi('Test prompt');
  206. expect(result.output).toBe('');
  207. });
  208. it('should handle tool calls and function callbacks', async () => {
  209. const mockCallback = jest.fn().mockResolvedValue('Function result');
  210. const customProvider = new GroqProvider('llama3-groq-8b-8192-tool-use-preview', {
  211. config: {
  212. functionToolCallbacks: {
  213. test_function: mockCallback,
  214. },
  215. },
  216. });
  217. const mockResponse = {
  218. choices: [
  219. {
  220. message: {
  221. content: null,
  222. tool_calls: [
  223. {
  224. id: 'call_123',
  225. type: 'function',
  226. function: { name: 'test_function', arguments: '{"arg": "value"}' },
  227. },
  228. ],
  229. },
  230. },
  231. ],
  232. usage: { total_tokens: 10, prompt_tokens: 5, completion_tokens: 5 },
  233. };
  234. const response = new Response(JSON.stringify(mockResponse), {
  235. status: 200,
  236. statusText: 'OK',
  237. headers: new Headers({ 'Content-Type': 'application/json' }),
  238. });
  239. mockedFetchWithRetries.mockResolvedValueOnce(response);
  240. const result = await customProvider.callApi('Test prompt');
  241. expect(mockCallback).toHaveBeenCalledWith('{"arg": "value"}');
  242. expect(result.output).toBe('Function result');
  243. });
  244. it('should handle invalid tool calls', async () => {
  245. const customProvider = new GroqProvider('llama3-groq-8b-8192-tool-use-preview', {
  246. config: {
  247. functionToolCallbacks: {},
  248. },
  249. });
  250. const mockResponse = {
  251. choices: [
  252. {
  253. message: {
  254. content: null,
  255. tool_calls: [
  256. {
  257. id: 'call_123',
  258. type: 'function',
  259. function: { name: 'nonexistent_function', arguments: '{}' },
  260. },
  261. ],
  262. },
  263. },
  264. ],
  265. usage: { total_tokens: 10, prompt_tokens: 5, completion_tokens: 5 },
  266. };
  267. const response = new Response(JSON.stringify(mockResponse), {
  268. status: 200,
  269. statusText: 'OK',
  270. headers: new Headers({ 'Content-Type': 'application/json' }),
  271. });
  272. mockedFetchWithRetries.mockResolvedValueOnce(response);
  273. const result = await customProvider.callApi('Test prompt');
  274. expect(result.output).toEqual([
  275. {
  276. id: 'call_123',
  277. type: 'function',
  278. function: { name: 'nonexistent_function', arguments: '{}' },
  279. },
  280. ]);
  281. expect(result.error).toBeUndefined();
  282. });
  283. it('should handle system prompts correctly', async () => {
  284. const providerWithSystem = new GroqProvider('mixtral-8x7b-32768', {
  285. config: {
  286. systemPrompt: 'You are a helpful assistant',
  287. },
  288. });
  289. const mockResponse = {
  290. choices: [{ message: { content: 'Test output' } }],
  291. usage: { total_tokens: 10, prompt_tokens: 5, completion_tokens: 5 },
  292. };
  293. const response = new Response(JSON.stringify(mockResponse), {
  294. status: 200,
  295. statusText: 'OK',
  296. headers: new Headers({ 'Content-Type': 'application/json' }),
  297. });
  298. mockedFetchWithRetries.mockResolvedValueOnce(response);
  299. await providerWithSystem.callApi('Test prompt');
  300. const lastCall = mockedFetchWithRetries.mock.calls[0];
  301. if (!lastCall) {
  302. throw new Error('Expected fetch to have been called');
  303. }
  304. const requestBody = JSON.parse((lastCall[1] as { body: string }).body);
  305. expect(requestBody.messages).toEqual([{ role: 'user', content: 'Test prompt' }]);
  306. });
  307. it('should handle API key from environment variable', async () => {
  308. const originalApiKey = process.env.GROQ_API_KEY;
  309. delete process.env.GROQ_API_KEY;
  310. const mockErrorResponse = new Response(
  311. JSON.stringify({
  312. error: {
  313. message: 'No API key provided',
  314. type: 'auth_error',
  315. },
  316. }),
  317. {
  318. status: 401,
  319. statusText: 'Unauthorized',
  320. headers: new Headers({ 'Content-Type': 'application/json' }),
  321. },
  322. );
  323. mockedFetchWithRetries.mockResolvedValueOnce(mockErrorResponse);
  324. const result = await provider.callApi('Test prompt');
  325. expect(result.error).toContain('401 Unauthorized');
  326. process.env.GROQ_API_KEY = originalApiKey;
  327. });
  328. it('should handle malformed API response', async () => {
  329. const malformedResponse = new Response('{"invalid": json}', {
  330. status: 200,
  331. statusText: 'OK',
  332. headers: new Headers({ 'Content-Type': 'application/json' }),
  333. });
  334. mockedFetchWithRetries.mockResolvedValueOnce(malformedResponse);
  335. const result = await provider.callApi('Test prompt');
  336. expect(result.error).toBeDefined();
  337. });
  338. it('should handle rate limit errors', async () => {
  339. const rateLimitResponse = new Response(
  340. JSON.stringify({
  341. error: {
  342. message: 'Rate limit exceeded',
  343. type: 'rate_limit_error',
  344. },
  345. }),
  346. {
  347. status: 429,
  348. statusText: 'Too Many Requests',
  349. headers: new Headers({ 'Content-Type': 'application/json' }),
  350. },
  351. );
  352. mockedFetchWithRetries.mockResolvedValueOnce(rateLimitResponse);
  353. const result = await provider.callApi('Test prompt');
  354. expect(result.error).toContain('429');
  355. expect(result.error).toContain('Rate limit exceeded');
  356. });
  357. });
  358. });
  359. });
Tip!

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

Comments

Loading...