@ai-sdk/groq 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,635 @@
1
+ // src/groq-provider.ts
2
+ import {
3
+ NoSuchModelError
4
+ } from "@ai-sdk/provider";
5
+ import {
6
+ loadApiKey,
7
+ withoutTrailingSlash
8
+ } from "@ai-sdk/provider-utils";
9
+
10
+ // src/groq-chat-language-model.ts
11
+ import {
12
+ InvalidResponseDataError
13
+ } from "@ai-sdk/provider";
14
+ import {
15
+ combineHeaders,
16
+ createEventSourceResponseHandler,
17
+ createJsonResponseHandler,
18
+ generateId,
19
+ isParsableJson,
20
+ postJsonToApi
21
+ } from "@ai-sdk/provider-utils";
22
+ import { z as z2 } from "zod";
23
+
24
+ // src/convert-to-groq-chat-messages.ts
25
+ import {
26
+ UnsupportedFunctionalityError
27
+ } from "@ai-sdk/provider";
28
+ import { convertUint8ArrayToBase64 } from "@ai-sdk/provider-utils";
29
+ function convertToGroqChatMessages(prompt) {
30
+ const messages = [];
31
+ for (const { role, content } of prompt) {
32
+ switch (role) {
33
+ case "system": {
34
+ messages.push({ role: "system", content });
35
+ break;
36
+ }
37
+ case "user": {
38
+ if (content.length === 1 && content[0].type === "text") {
39
+ messages.push({ role: "user", content: content[0].text });
40
+ break;
41
+ }
42
+ messages.push({
43
+ role: "user",
44
+ content: content.map((part) => {
45
+ var _a;
46
+ switch (part.type) {
47
+ case "text": {
48
+ return { type: "text", text: part.text };
49
+ }
50
+ case "image": {
51
+ return {
52
+ type: "image_url",
53
+ image_url: {
54
+ url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`
55
+ }
56
+ };
57
+ }
58
+ case "file": {
59
+ throw new UnsupportedFunctionalityError({
60
+ functionality: "File content parts in user messages"
61
+ });
62
+ }
63
+ }
64
+ })
65
+ });
66
+ break;
67
+ }
68
+ case "assistant": {
69
+ let text = "";
70
+ const toolCalls = [];
71
+ for (const part of content) {
72
+ switch (part.type) {
73
+ case "text": {
74
+ text += part.text;
75
+ break;
76
+ }
77
+ case "tool-call": {
78
+ toolCalls.push({
79
+ id: part.toolCallId,
80
+ type: "function",
81
+ function: {
82
+ name: part.toolName,
83
+ arguments: JSON.stringify(part.args)
84
+ }
85
+ });
86
+ break;
87
+ }
88
+ default: {
89
+ const _exhaustiveCheck = part;
90
+ throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
91
+ }
92
+ }
93
+ }
94
+ messages.push({
95
+ role: "assistant",
96
+ content: text,
97
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
98
+ });
99
+ break;
100
+ }
101
+ case "tool": {
102
+ for (const toolResponse of content) {
103
+ messages.push({
104
+ role: "tool",
105
+ tool_call_id: toolResponse.toolCallId,
106
+ content: JSON.stringify(toolResponse.result)
107
+ });
108
+ }
109
+ break;
110
+ }
111
+ default: {
112
+ const _exhaustiveCheck = role;
113
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
114
+ }
115
+ }
116
+ }
117
+ return messages;
118
+ }
119
+
120
+ // src/get-response-metadata.ts
121
+ function getResponseMetadata({
122
+ id,
123
+ model,
124
+ created
125
+ }) {
126
+ return {
127
+ id: id != null ? id : void 0,
128
+ modelId: model != null ? model : void 0,
129
+ timestamp: created != null ? new Date(created * 1e3) : void 0
130
+ };
131
+ }
132
+
133
+ // src/groq-error.ts
134
+ import { z } from "zod";
135
+ import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
136
+ var groqErrorDataSchema = z.object({
137
+ error: z.object({
138
+ message: z.string(),
139
+ type: z.string()
140
+ })
141
+ });
142
+ var groqFailedResponseHandler = createJsonErrorResponseHandler({
143
+ errorSchema: groqErrorDataSchema,
144
+ errorToMessage: (data) => data.error.message
145
+ });
146
+
147
+ // src/map-groq-finish-reason.ts
148
+ function mapGroqFinishReason(finishReason) {
149
+ switch (finishReason) {
150
+ case "stop":
151
+ return "stop";
152
+ case "length":
153
+ return "length";
154
+ case "content_filter":
155
+ return "content-filter";
156
+ case "function_call":
157
+ case "tool_calls":
158
+ return "tool-calls";
159
+ default:
160
+ return "unknown";
161
+ }
162
+ }
163
+
164
+ // src/groq-chat-language-model.ts
165
+ var GroqChatLanguageModel = class {
166
+ constructor(modelId, settings, config) {
167
+ this.specificationVersion = "v1";
168
+ this.supportsStructuredOutputs = false;
169
+ this.defaultObjectGenerationMode = "json";
170
+ this.modelId = modelId;
171
+ this.settings = settings;
172
+ this.config = config;
173
+ }
174
+ get provider() {
175
+ return this.config.provider;
176
+ }
177
+ get supportsImageUrls() {
178
+ return !this.settings.downloadImages;
179
+ }
180
+ getArgs({
181
+ mode,
182
+ prompt,
183
+ maxTokens,
184
+ temperature,
185
+ topP,
186
+ topK,
187
+ frequencyPenalty,
188
+ presencePenalty,
189
+ stopSequences,
190
+ responseFormat,
191
+ seed,
192
+ stream
193
+ }) {
194
+ const type = mode.type;
195
+ const warnings = [];
196
+ if (topK != null) {
197
+ warnings.push({
198
+ type: "unsupported-setting",
199
+ setting: "topK"
200
+ });
201
+ }
202
+ if (responseFormat != null && responseFormat.type === "json" && responseFormat.schema != null) {
203
+ warnings.push({
204
+ type: "unsupported-setting",
205
+ setting: "responseFormat",
206
+ details: "JSON response format schema is not supported"
207
+ });
208
+ }
209
+ const baseArgs = {
210
+ // model id:
211
+ model: this.modelId,
212
+ // model specific settings:
213
+ user: this.settings.user,
214
+ parallel_tool_calls: this.settings.parallelToolCalls,
215
+ // standardized settings:
216
+ max_tokens: maxTokens,
217
+ temperature,
218
+ top_p: topP,
219
+ frequency_penalty: frequencyPenalty,
220
+ presence_penalty: presencePenalty,
221
+ stop: stopSequences,
222
+ seed,
223
+ // response format:
224
+ response_format: (
225
+ // json object response format is not supported for streaming:
226
+ stream === false && (responseFormat == null ? void 0 : responseFormat.type) === "json" ? { type: "json_object" } : void 0
227
+ ),
228
+ // messages:
229
+ messages: convertToGroqChatMessages(prompt)
230
+ };
231
+ switch (type) {
232
+ case "regular": {
233
+ return {
234
+ args: {
235
+ ...baseArgs,
236
+ ...prepareToolsAndToolChoice({ mode })
237
+ },
238
+ warnings
239
+ };
240
+ }
241
+ case "object-json": {
242
+ return {
243
+ args: {
244
+ ...baseArgs,
245
+ response_format: (
246
+ // json object response format is not supported for streaming:
247
+ stream === false ? { type: "json_object" } : void 0
248
+ )
249
+ },
250
+ warnings
251
+ };
252
+ }
253
+ case "object-tool": {
254
+ return {
255
+ args: {
256
+ ...baseArgs,
257
+ tool_choice: {
258
+ type: "function",
259
+ function: { name: mode.tool.name }
260
+ },
261
+ tools: [
262
+ {
263
+ type: "function",
264
+ function: {
265
+ name: mode.tool.name,
266
+ description: mode.tool.description,
267
+ parameters: mode.tool.parameters
268
+ }
269
+ }
270
+ ]
271
+ },
272
+ warnings
273
+ };
274
+ }
275
+ default: {
276
+ const _exhaustiveCheck = type;
277
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
278
+ }
279
+ }
280
+ }
281
+ async doGenerate(options) {
282
+ var _a, _b, _c, _d, _e, _f;
283
+ const { args, warnings } = this.getArgs({ ...options, stream: false });
284
+ const { responseHeaders, value: response } = await postJsonToApi({
285
+ url: this.config.url({
286
+ path: "/chat/completions",
287
+ modelId: this.modelId
288
+ }),
289
+ headers: combineHeaders(this.config.headers(), options.headers),
290
+ body: args,
291
+ failedResponseHandler: groqFailedResponseHandler,
292
+ successfulResponseHandler: createJsonResponseHandler(
293
+ groqChatResponseSchema
294
+ ),
295
+ abortSignal: options.abortSignal,
296
+ fetch: this.config.fetch
297
+ });
298
+ const { messages: rawPrompt, ...rawSettings } = args;
299
+ const choice = response.choices[0];
300
+ return {
301
+ text: (_a = choice.message.content) != null ? _a : void 0,
302
+ toolCalls: (_b = choice.message.tool_calls) == null ? void 0 : _b.map((toolCall) => {
303
+ var _a2;
304
+ return {
305
+ toolCallType: "function",
306
+ toolCallId: (_a2 = toolCall.id) != null ? _a2 : generateId(),
307
+ toolName: toolCall.function.name,
308
+ args: toolCall.function.arguments
309
+ };
310
+ }),
311
+ finishReason: mapGroqFinishReason(choice.finish_reason),
312
+ usage: {
313
+ promptTokens: (_d = (_c = response.usage) == null ? void 0 : _c.prompt_tokens) != null ? _d : NaN,
314
+ completionTokens: (_f = (_e = response.usage) == null ? void 0 : _e.completion_tokens) != null ? _f : NaN
315
+ },
316
+ rawCall: { rawPrompt, rawSettings },
317
+ rawResponse: { headers: responseHeaders },
318
+ response: getResponseMetadata(response),
319
+ warnings
320
+ };
321
+ }
322
+ async doStream(options) {
323
+ const { args, warnings } = this.getArgs({ ...options, stream: true });
324
+ const { responseHeaders, value: response } = await postJsonToApi({
325
+ url: this.config.url({
326
+ path: "/chat/completions",
327
+ modelId: this.modelId
328
+ }),
329
+ headers: combineHeaders(this.config.headers(), options.headers),
330
+ body: {
331
+ ...args,
332
+ stream: true
333
+ },
334
+ failedResponseHandler: groqFailedResponseHandler,
335
+ successfulResponseHandler: createEventSourceResponseHandler(groqChatChunkSchema),
336
+ abortSignal: options.abortSignal,
337
+ fetch: this.config.fetch
338
+ });
339
+ const { messages: rawPrompt, ...rawSettings } = args;
340
+ const toolCalls = [];
341
+ let finishReason = "unknown";
342
+ let usage = {
343
+ promptTokens: void 0,
344
+ completionTokens: void 0
345
+ };
346
+ let isFirstChunk = true;
347
+ let providerMetadata;
348
+ return {
349
+ stream: response.pipeThrough(
350
+ new TransformStream({
351
+ transform(chunk, controller) {
352
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
353
+ if (!chunk.success) {
354
+ finishReason = "error";
355
+ controller.enqueue({ type: "error", error: chunk.error });
356
+ return;
357
+ }
358
+ const value = chunk.value;
359
+ if ("error" in value) {
360
+ finishReason = "error";
361
+ controller.enqueue({ type: "error", error: value.error });
362
+ return;
363
+ }
364
+ if (isFirstChunk) {
365
+ isFirstChunk = false;
366
+ controller.enqueue({
367
+ type: "response-metadata",
368
+ ...getResponseMetadata(value)
369
+ });
370
+ }
371
+ if (((_a = value.x_groq) == null ? void 0 : _a.usage) != null) {
372
+ usage = {
373
+ promptTokens: (_b = value.x_groq.usage.prompt_tokens) != null ? _b : void 0,
374
+ completionTokens: (_c = value.x_groq.usage.completion_tokens) != null ? _c : void 0
375
+ };
376
+ }
377
+ const choice = value.choices[0];
378
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
379
+ finishReason = mapGroqFinishReason(choice.finish_reason);
380
+ }
381
+ if ((choice == null ? void 0 : choice.delta) == null) {
382
+ return;
383
+ }
384
+ const delta = choice.delta;
385
+ if (delta.content != null) {
386
+ controller.enqueue({
387
+ type: "text-delta",
388
+ textDelta: delta.content
389
+ });
390
+ }
391
+ if (delta.tool_calls != null) {
392
+ for (const toolCallDelta of delta.tool_calls) {
393
+ const index = toolCallDelta.index;
394
+ if (toolCalls[index] == null) {
395
+ if (toolCallDelta.type !== "function") {
396
+ throw new InvalidResponseDataError({
397
+ data: toolCallDelta,
398
+ message: `Expected 'function' type.`
399
+ });
400
+ }
401
+ if (toolCallDelta.id == null) {
402
+ throw new InvalidResponseDataError({
403
+ data: toolCallDelta,
404
+ message: `Expected 'id' to be a string.`
405
+ });
406
+ }
407
+ if (((_d = toolCallDelta.function) == null ? void 0 : _d.name) == null) {
408
+ throw new InvalidResponseDataError({
409
+ data: toolCallDelta,
410
+ message: `Expected 'function.name' to be a string.`
411
+ });
412
+ }
413
+ toolCalls[index] = {
414
+ id: toolCallDelta.id,
415
+ type: "function",
416
+ function: {
417
+ name: toolCallDelta.function.name,
418
+ arguments: (_e = toolCallDelta.function.arguments) != null ? _e : ""
419
+ }
420
+ };
421
+ const toolCall2 = toolCalls[index];
422
+ if (((_f = toolCall2.function) == null ? void 0 : _f.name) != null && ((_g = toolCall2.function) == null ? void 0 : _g.arguments) != null) {
423
+ if (toolCall2.function.arguments.length > 0) {
424
+ controller.enqueue({
425
+ type: "tool-call-delta",
426
+ toolCallType: "function",
427
+ toolCallId: toolCall2.id,
428
+ toolName: toolCall2.function.name,
429
+ argsTextDelta: toolCall2.function.arguments
430
+ });
431
+ }
432
+ if (isParsableJson(toolCall2.function.arguments)) {
433
+ controller.enqueue({
434
+ type: "tool-call",
435
+ toolCallType: "function",
436
+ toolCallId: (_h = toolCall2.id) != null ? _h : generateId(),
437
+ toolName: toolCall2.function.name,
438
+ args: toolCall2.function.arguments
439
+ });
440
+ }
441
+ }
442
+ continue;
443
+ }
444
+ const toolCall = toolCalls[index];
445
+ if (((_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null) {
446
+ toolCall.function.arguments += (_k = (_j = toolCallDelta.function) == null ? void 0 : _j.arguments) != null ? _k : "";
447
+ }
448
+ controller.enqueue({
449
+ type: "tool-call-delta",
450
+ toolCallType: "function",
451
+ toolCallId: toolCall.id,
452
+ toolName: toolCall.function.name,
453
+ argsTextDelta: (_l = toolCallDelta.function.arguments) != null ? _l : ""
454
+ });
455
+ if (((_m = toolCall.function) == null ? void 0 : _m.name) != null && ((_n = toolCall.function) == null ? void 0 : _n.arguments) != null && isParsableJson(toolCall.function.arguments)) {
456
+ controller.enqueue({
457
+ type: "tool-call",
458
+ toolCallType: "function",
459
+ toolCallId: (_o = toolCall.id) != null ? _o : generateId(),
460
+ toolName: toolCall.function.name,
461
+ args: toolCall.function.arguments
462
+ });
463
+ }
464
+ }
465
+ }
466
+ },
467
+ flush(controller) {
468
+ var _a, _b;
469
+ controller.enqueue({
470
+ type: "finish",
471
+ finishReason,
472
+ usage: {
473
+ promptTokens: (_a = usage.promptTokens) != null ? _a : NaN,
474
+ completionTokens: (_b = usage.completionTokens) != null ? _b : NaN
475
+ },
476
+ ...providerMetadata != null ? { providerMetadata } : {}
477
+ });
478
+ }
479
+ })
480
+ ),
481
+ rawCall: { rawPrompt, rawSettings },
482
+ rawResponse: { headers: responseHeaders },
483
+ warnings
484
+ };
485
+ }
486
+ };
487
+ var groqChatResponseSchema = z2.object({
488
+ id: z2.string().nullish(),
489
+ created: z2.number().nullish(),
490
+ model: z2.string().nullish(),
491
+ choices: z2.array(
492
+ z2.object({
493
+ message: z2.object({
494
+ role: z2.literal("assistant").nullish(),
495
+ content: z2.string().nullish(),
496
+ tool_calls: z2.array(
497
+ z2.object({
498
+ id: z2.string().nullish(),
499
+ type: z2.literal("function"),
500
+ function: z2.object({
501
+ name: z2.string(),
502
+ arguments: z2.string()
503
+ })
504
+ })
505
+ ).nullish()
506
+ }),
507
+ index: z2.number(),
508
+ finish_reason: z2.string().nullish()
509
+ })
510
+ ),
511
+ usage: z2.object({
512
+ prompt_tokens: z2.number().nullish(),
513
+ completion_tokens: z2.number().nullish()
514
+ }).nullish()
515
+ });
516
+ var groqChatChunkSchema = z2.union([
517
+ z2.object({
518
+ id: z2.string().nullish(),
519
+ created: z2.number().nullish(),
520
+ model: z2.string().nullish(),
521
+ choices: z2.array(
522
+ z2.object({
523
+ delta: z2.object({
524
+ role: z2.enum(["assistant"]).nullish(),
525
+ content: z2.string().nullish(),
526
+ tool_calls: z2.array(
527
+ z2.object({
528
+ index: z2.number(),
529
+ id: z2.string().nullish(),
530
+ type: z2.literal("function").optional(),
531
+ function: z2.object({
532
+ name: z2.string().nullish(),
533
+ arguments: z2.string().nullish()
534
+ })
535
+ })
536
+ ).nullish()
537
+ }).nullish(),
538
+ finish_reason: z2.string().nullable().optional(),
539
+ index: z2.number()
540
+ })
541
+ ),
542
+ x_groq: z2.object({
543
+ usage: z2.object({
544
+ prompt_tokens: z2.number().nullish(),
545
+ completion_tokens: z2.number().nullish()
546
+ }).nullish()
547
+ }).nullish()
548
+ }),
549
+ groqErrorDataSchema
550
+ ]);
551
+ function prepareToolsAndToolChoice({
552
+ mode
553
+ }) {
554
+ var _a;
555
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
556
+ if (tools == null) {
557
+ return { tools: void 0, tool_choice: void 0 };
558
+ }
559
+ const toolChoice = mode.toolChoice;
560
+ const mappedTools = tools.map((tool) => ({
561
+ type: "function",
562
+ function: {
563
+ name: tool.name,
564
+ description: tool.description,
565
+ parameters: tool.parameters
566
+ }
567
+ }));
568
+ if (toolChoice == null) {
569
+ return { tools: mappedTools, tool_choice: void 0 };
570
+ }
571
+ const type = toolChoice.type;
572
+ switch (type) {
573
+ case "auto":
574
+ case "none":
575
+ case "required":
576
+ return { tools: mappedTools, tool_choice: type };
577
+ case "tool":
578
+ return {
579
+ tools: mappedTools,
580
+ tool_choice: {
581
+ type: "function",
582
+ function: {
583
+ name: toolChoice.toolName
584
+ }
585
+ }
586
+ };
587
+ default: {
588
+ const _exhaustiveCheck = type;
589
+ throw new Error(`Unsupported tool choice type: ${_exhaustiveCheck}`);
590
+ }
591
+ }
592
+ }
593
+
594
+ // src/groq-provider.ts
595
+ function createGroq(options = {}) {
596
+ var _a;
597
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.groq.com/openai/v1";
598
+ const getHeaders = () => ({
599
+ Authorization: `Bearer ${loadApiKey({
600
+ apiKey: options.apiKey,
601
+ environmentVariableName: "GROQ_API_KEY",
602
+ description: "Groq"
603
+ })}`,
604
+ ...options.headers
605
+ });
606
+ const createChatModel = (modelId, settings = {}) => new GroqChatLanguageModel(modelId, settings, {
607
+ provider: "groq.chat",
608
+ url: ({ path }) => `${baseURL}${path}`,
609
+ headers: getHeaders,
610
+ fetch: options.fetch
611
+ });
612
+ const createLanguageModel = (modelId, settings) => {
613
+ if (new.target) {
614
+ throw new Error(
615
+ "The Groq model function cannot be called with the new keyword."
616
+ );
617
+ }
618
+ return createChatModel(modelId, settings);
619
+ };
620
+ const provider = function(modelId, settings) {
621
+ return createLanguageModel(modelId, settings);
622
+ };
623
+ provider.languageModel = createLanguageModel;
624
+ provider.chat = createChatModel;
625
+ provider.textEmbeddingModel = (modelId) => {
626
+ throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
627
+ };
628
+ return provider;
629
+ }
630
+ var groq = createGroq();
631
+ export {
632
+ createGroq,
633
+ groq
634
+ };
635
+ //# sourceMappingURL=index.mjs.map