@ai-sdk/groq 0.0.0-013d7476-20250808163325

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.js ADDED
@@ -0,0 +1,863 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ createGroq: () => createGroq,
24
+ groq: () => groq
25
+ });
26
+ module.exports = __toCommonJS(src_exports);
27
+
28
+ // src/groq-provider.ts
29
+ var import_provider4 = require("@ai-sdk/provider");
30
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
31
+
32
+ // src/groq-chat-language-model.ts
33
+ var import_provider3 = require("@ai-sdk/provider");
34
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
35
+ var import_v43 = require("zod/v4");
36
+
37
+ // src/convert-to-groq-chat-messages.ts
38
+ var import_provider = require("@ai-sdk/provider");
39
+ function convertToGroqChatMessages(prompt) {
40
+ const messages = [];
41
+ for (const { role, content } of prompt) {
42
+ switch (role) {
43
+ case "system": {
44
+ messages.push({ role: "system", content });
45
+ break;
46
+ }
47
+ case "user": {
48
+ if (content.length === 1 && content[0].type === "text") {
49
+ messages.push({ role: "user", content: content[0].text });
50
+ break;
51
+ }
52
+ messages.push({
53
+ role: "user",
54
+ content: content.map((part) => {
55
+ switch (part.type) {
56
+ case "text": {
57
+ return { type: "text", text: part.text };
58
+ }
59
+ case "file": {
60
+ if (!part.mediaType.startsWith("image/")) {
61
+ throw new import_provider.UnsupportedFunctionalityError({
62
+ functionality: "Non-image file content parts"
63
+ });
64
+ }
65
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
66
+ return {
67
+ type: "image_url",
68
+ image_url: {
69
+ url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${part.data}`
70
+ }
71
+ };
72
+ }
73
+ }
74
+ })
75
+ });
76
+ break;
77
+ }
78
+ case "assistant": {
79
+ let text = "";
80
+ const toolCalls = [];
81
+ for (const part of content) {
82
+ switch (part.type) {
83
+ case "text": {
84
+ text += part.text;
85
+ break;
86
+ }
87
+ case "tool-call": {
88
+ toolCalls.push({
89
+ id: part.toolCallId,
90
+ type: "function",
91
+ function: {
92
+ name: part.toolName,
93
+ arguments: JSON.stringify(part.input)
94
+ }
95
+ });
96
+ break;
97
+ }
98
+ }
99
+ }
100
+ messages.push({
101
+ role: "assistant",
102
+ content: text,
103
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
104
+ });
105
+ break;
106
+ }
107
+ case "tool": {
108
+ for (const toolResponse of content) {
109
+ const output = toolResponse.output;
110
+ let contentValue;
111
+ switch (output.type) {
112
+ case "text":
113
+ case "error-text":
114
+ contentValue = output.value;
115
+ break;
116
+ case "content":
117
+ case "json":
118
+ case "error-json":
119
+ contentValue = JSON.stringify(output.value);
120
+ break;
121
+ }
122
+ messages.push({
123
+ role: "tool",
124
+ tool_call_id: toolResponse.toolCallId,
125
+ content: contentValue
126
+ });
127
+ }
128
+ break;
129
+ }
130
+ default: {
131
+ const _exhaustiveCheck = role;
132
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
133
+ }
134
+ }
135
+ }
136
+ return messages;
137
+ }
138
+
139
+ // src/get-response-metadata.ts
140
+ function getResponseMetadata({
141
+ id,
142
+ model,
143
+ created
144
+ }) {
145
+ return {
146
+ id: id != null ? id : void 0,
147
+ modelId: model != null ? model : void 0,
148
+ timestamp: created != null ? new Date(created * 1e3) : void 0
149
+ };
150
+ }
151
+
152
+ // src/groq-chat-options.ts
153
+ var import_v4 = require("zod/v4");
154
+ var groqProviderOptions = import_v4.z.object({
155
+ reasoningFormat: import_v4.z.enum(["parsed", "raw", "hidden"]).optional(),
156
+ reasoningEffort: import_v4.z.string().optional(),
157
+ /**
158
+ * Whether to enable parallel function calling during tool use. Default to true.
159
+ */
160
+ parallelToolCalls: import_v4.z.boolean().optional(),
161
+ /**
162
+ * A unique identifier representing your end-user, which can help OpenAI to
163
+ * monitor and detect abuse. Learn more.
164
+ */
165
+ user: import_v4.z.string().optional(),
166
+ /**
167
+ * Whether to use structured outputs.
168
+ *
169
+ * @default true
170
+ */
171
+ structuredOutputs: import_v4.z.boolean().optional()
172
+ });
173
+
174
+ // src/groq-error.ts
175
+ var import_v42 = require("zod/v4");
176
+ var import_provider_utils = require("@ai-sdk/provider-utils");
177
+ var groqErrorDataSchema = import_v42.z.object({
178
+ error: import_v42.z.object({
179
+ message: import_v42.z.string(),
180
+ type: import_v42.z.string()
181
+ })
182
+ });
183
+ var groqFailedResponseHandler = (0, import_provider_utils.createJsonErrorResponseHandler)({
184
+ errorSchema: groqErrorDataSchema,
185
+ errorToMessage: (data) => data.error.message
186
+ });
187
+
188
+ // src/groq-prepare-tools.ts
189
+ var import_provider2 = require("@ai-sdk/provider");
190
+ function prepareTools({
191
+ tools,
192
+ toolChoice
193
+ }) {
194
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
195
+ const toolWarnings = [];
196
+ if (tools == null) {
197
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
198
+ }
199
+ const groqTools = [];
200
+ for (const tool of tools) {
201
+ if (tool.type === "provider-defined") {
202
+ toolWarnings.push({ type: "unsupported-tool", tool });
203
+ } else {
204
+ groqTools.push({
205
+ type: "function",
206
+ function: {
207
+ name: tool.name,
208
+ description: tool.description,
209
+ parameters: tool.inputSchema
210
+ }
211
+ });
212
+ }
213
+ }
214
+ if (toolChoice == null) {
215
+ return { tools: groqTools, toolChoice: void 0, toolWarnings };
216
+ }
217
+ const type = toolChoice.type;
218
+ switch (type) {
219
+ case "auto":
220
+ case "none":
221
+ case "required":
222
+ return { tools: groqTools, toolChoice: type, toolWarnings };
223
+ case "tool":
224
+ return {
225
+ tools: groqTools,
226
+ toolChoice: {
227
+ type: "function",
228
+ function: {
229
+ name: toolChoice.toolName
230
+ }
231
+ },
232
+ toolWarnings
233
+ };
234
+ default: {
235
+ const _exhaustiveCheck = type;
236
+ throw new import_provider2.UnsupportedFunctionalityError({
237
+ functionality: `tool choice type: ${_exhaustiveCheck}`
238
+ });
239
+ }
240
+ }
241
+ }
242
+
243
+ // src/map-groq-finish-reason.ts
244
+ function mapGroqFinishReason(finishReason) {
245
+ switch (finishReason) {
246
+ case "stop":
247
+ return "stop";
248
+ case "length":
249
+ return "length";
250
+ case "content_filter":
251
+ return "content-filter";
252
+ case "function_call":
253
+ case "tool_calls":
254
+ return "tool-calls";
255
+ default:
256
+ return "unknown";
257
+ }
258
+ }
259
+
260
+ // src/groq-chat-language-model.ts
261
+ var GroqChatLanguageModel = class {
262
+ constructor(modelId, config) {
263
+ this.specificationVersion = "v2";
264
+ this.supportedUrls = {
265
+ "image/*": [/^https?:\/\/.*$/]
266
+ };
267
+ this.modelId = modelId;
268
+ this.config = config;
269
+ }
270
+ get provider() {
271
+ return this.config.provider;
272
+ }
273
+ async getArgs({
274
+ prompt,
275
+ maxOutputTokens,
276
+ temperature,
277
+ topP,
278
+ topK,
279
+ frequencyPenalty,
280
+ presencePenalty,
281
+ stopSequences,
282
+ responseFormat,
283
+ seed,
284
+ stream,
285
+ tools,
286
+ toolChoice,
287
+ providerOptions
288
+ }) {
289
+ var _a, _b;
290
+ const warnings = [];
291
+ const groqOptions = await (0, import_provider_utils2.parseProviderOptions)({
292
+ provider: "groq",
293
+ providerOptions,
294
+ schema: groqProviderOptions
295
+ });
296
+ const structuredOutputs = (_a = groqOptions == null ? void 0 : groqOptions.structuredOutputs) != null ? _a : true;
297
+ if (topK != null) {
298
+ warnings.push({
299
+ type: "unsupported-setting",
300
+ setting: "topK"
301
+ });
302
+ }
303
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !structuredOutputs) {
304
+ warnings.push({
305
+ type: "unsupported-setting",
306
+ setting: "responseFormat",
307
+ details: "JSON response format schema is only supported with structuredOutputs"
308
+ });
309
+ }
310
+ const {
311
+ tools: groqTools,
312
+ toolChoice: groqToolChoice,
313
+ toolWarnings
314
+ } = prepareTools({ tools, toolChoice });
315
+ return {
316
+ args: {
317
+ // model id:
318
+ model: this.modelId,
319
+ // model specific settings:
320
+ user: groqOptions == null ? void 0 : groqOptions.user,
321
+ parallel_tool_calls: groqOptions == null ? void 0 : groqOptions.parallelToolCalls,
322
+ // standardized settings:
323
+ max_tokens: maxOutputTokens,
324
+ temperature,
325
+ top_p: topP,
326
+ frequency_penalty: frequencyPenalty,
327
+ presence_penalty: presencePenalty,
328
+ stop: stopSequences,
329
+ seed,
330
+ // response format:
331
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? structuredOutputs && responseFormat.schema != null ? {
332
+ type: "json_schema",
333
+ json_schema: {
334
+ schema: responseFormat.schema,
335
+ name: (_b = responseFormat.name) != null ? _b : "response",
336
+ description: responseFormat.description
337
+ }
338
+ } : { type: "json_object" } : void 0,
339
+ // provider options:
340
+ reasoning_format: groqOptions == null ? void 0 : groqOptions.reasoningFormat,
341
+ reasoning_effort: groqOptions == null ? void 0 : groqOptions.reasoningEffort,
342
+ // messages:
343
+ messages: convertToGroqChatMessages(prompt),
344
+ // tools:
345
+ tools: groqTools,
346
+ tool_choice: groqToolChoice
347
+ },
348
+ warnings: [...warnings, ...toolWarnings]
349
+ };
350
+ }
351
+ async doGenerate(options) {
352
+ var _a, _b, _c, _d, _e, _f, _g;
353
+ const { args, warnings } = await this.getArgs({
354
+ ...options,
355
+ stream: false
356
+ });
357
+ const body = JSON.stringify(args);
358
+ const {
359
+ responseHeaders,
360
+ value: response,
361
+ rawValue: rawResponse
362
+ } = await (0, import_provider_utils2.postJsonToApi)({
363
+ url: this.config.url({
364
+ path: "/chat/completions",
365
+ modelId: this.modelId
366
+ }),
367
+ headers: (0, import_provider_utils2.combineHeaders)(this.config.headers(), options.headers),
368
+ body: args,
369
+ failedResponseHandler: groqFailedResponseHandler,
370
+ successfulResponseHandler: (0, import_provider_utils2.createJsonResponseHandler)(
371
+ groqChatResponseSchema
372
+ ),
373
+ abortSignal: options.abortSignal,
374
+ fetch: this.config.fetch
375
+ });
376
+ const choice = response.choices[0];
377
+ const content = [];
378
+ const text = choice.message.content;
379
+ if (text != null && text.length > 0) {
380
+ content.push({ type: "text", text });
381
+ }
382
+ const reasoning = choice.message.reasoning;
383
+ if (reasoning != null && reasoning.length > 0) {
384
+ content.push({
385
+ type: "reasoning",
386
+ text: reasoning
387
+ });
388
+ }
389
+ if (choice.message.tool_calls != null) {
390
+ for (const toolCall of choice.message.tool_calls) {
391
+ content.push({
392
+ type: "tool-call",
393
+ toolCallId: (_a = toolCall.id) != null ? _a : (0, import_provider_utils2.generateId)(),
394
+ toolName: toolCall.function.name,
395
+ input: toolCall.function.arguments
396
+ });
397
+ }
398
+ }
399
+ return {
400
+ content,
401
+ finishReason: mapGroqFinishReason(choice.finish_reason),
402
+ usage: {
403
+ inputTokens: (_c = (_b = response.usage) == null ? void 0 : _b.prompt_tokens) != null ? _c : void 0,
404
+ outputTokens: (_e = (_d = response.usage) == null ? void 0 : _d.completion_tokens) != null ? _e : void 0,
405
+ totalTokens: (_g = (_f = response.usage) == null ? void 0 : _f.total_tokens) != null ? _g : void 0
406
+ },
407
+ response: {
408
+ ...getResponseMetadata(response),
409
+ headers: responseHeaders,
410
+ body: rawResponse
411
+ },
412
+ warnings,
413
+ request: { body }
414
+ };
415
+ }
416
+ async doStream(options) {
417
+ const { args, warnings } = await this.getArgs({ ...options, stream: true });
418
+ const body = JSON.stringify({ ...args, stream: true });
419
+ const { responseHeaders, value: response } = await (0, import_provider_utils2.postJsonToApi)({
420
+ url: this.config.url({
421
+ path: "/chat/completions",
422
+ modelId: this.modelId
423
+ }),
424
+ headers: (0, import_provider_utils2.combineHeaders)(this.config.headers(), options.headers),
425
+ body: {
426
+ ...args,
427
+ stream: true
428
+ },
429
+ failedResponseHandler: groqFailedResponseHandler,
430
+ successfulResponseHandler: (0, import_provider_utils2.createEventSourceResponseHandler)(groqChatChunkSchema),
431
+ abortSignal: options.abortSignal,
432
+ fetch: this.config.fetch
433
+ });
434
+ const toolCalls = [];
435
+ let finishReason = "unknown";
436
+ const usage = {
437
+ inputTokens: void 0,
438
+ outputTokens: void 0,
439
+ totalTokens: void 0
440
+ };
441
+ let isFirstChunk = true;
442
+ let isActiveText = false;
443
+ let isActiveReasoning = false;
444
+ let providerMetadata;
445
+ return {
446
+ stream: response.pipeThrough(
447
+ new TransformStream({
448
+ start(controller) {
449
+ controller.enqueue({ type: "stream-start", warnings });
450
+ },
451
+ transform(chunk, controller) {
452
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
453
+ if (options.includeRawChunks) {
454
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
455
+ }
456
+ if (!chunk.success) {
457
+ finishReason = "error";
458
+ controller.enqueue({ type: "error", error: chunk.error });
459
+ return;
460
+ }
461
+ const value = chunk.value;
462
+ if ("error" in value) {
463
+ finishReason = "error";
464
+ controller.enqueue({ type: "error", error: value.error });
465
+ return;
466
+ }
467
+ if (isFirstChunk) {
468
+ isFirstChunk = false;
469
+ controller.enqueue({
470
+ type: "response-metadata",
471
+ ...getResponseMetadata(value)
472
+ });
473
+ }
474
+ if (((_a = value.x_groq) == null ? void 0 : _a.usage) != null) {
475
+ usage.inputTokens = (_b = value.x_groq.usage.prompt_tokens) != null ? _b : void 0;
476
+ usage.outputTokens = (_c = value.x_groq.usage.completion_tokens) != null ? _c : void 0;
477
+ usage.totalTokens = (_d = value.x_groq.usage.total_tokens) != null ? _d : void 0;
478
+ }
479
+ const choice = value.choices[0];
480
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
481
+ finishReason = mapGroqFinishReason(choice.finish_reason);
482
+ }
483
+ if ((choice == null ? void 0 : choice.delta) == null) {
484
+ return;
485
+ }
486
+ const delta = choice.delta;
487
+ if (delta.reasoning != null && delta.reasoning.length > 0) {
488
+ if (!isActiveReasoning) {
489
+ controller.enqueue({
490
+ type: "reasoning-start",
491
+ id: "reasoning-0"
492
+ });
493
+ isActiveReasoning = true;
494
+ }
495
+ controller.enqueue({
496
+ type: "reasoning-delta",
497
+ id: "reasoning-0",
498
+ delta: delta.reasoning
499
+ });
500
+ }
501
+ if (delta.content != null && delta.content.length > 0) {
502
+ if (!isActiveText) {
503
+ controller.enqueue({ type: "text-start", id: "txt-0" });
504
+ isActiveText = true;
505
+ }
506
+ controller.enqueue({
507
+ type: "text-delta",
508
+ id: "txt-0",
509
+ delta: delta.content
510
+ });
511
+ }
512
+ if (delta.tool_calls != null) {
513
+ for (const toolCallDelta of delta.tool_calls) {
514
+ const index = toolCallDelta.index;
515
+ if (toolCalls[index] == null) {
516
+ if (toolCallDelta.type !== "function") {
517
+ throw new import_provider3.InvalidResponseDataError({
518
+ data: toolCallDelta,
519
+ message: `Expected 'function' type.`
520
+ });
521
+ }
522
+ if (toolCallDelta.id == null) {
523
+ throw new import_provider3.InvalidResponseDataError({
524
+ data: toolCallDelta,
525
+ message: `Expected 'id' to be a string.`
526
+ });
527
+ }
528
+ if (((_e = toolCallDelta.function) == null ? void 0 : _e.name) == null) {
529
+ throw new import_provider3.InvalidResponseDataError({
530
+ data: toolCallDelta,
531
+ message: `Expected 'function.name' to be a string.`
532
+ });
533
+ }
534
+ controller.enqueue({
535
+ type: "tool-input-start",
536
+ id: toolCallDelta.id,
537
+ toolName: toolCallDelta.function.name
538
+ });
539
+ toolCalls[index] = {
540
+ id: toolCallDelta.id,
541
+ type: "function",
542
+ function: {
543
+ name: toolCallDelta.function.name,
544
+ arguments: (_f = toolCallDelta.function.arguments) != null ? _f : ""
545
+ },
546
+ hasFinished: false
547
+ };
548
+ const toolCall2 = toolCalls[index];
549
+ if (((_g = toolCall2.function) == null ? void 0 : _g.name) != null && ((_h = toolCall2.function) == null ? void 0 : _h.arguments) != null) {
550
+ if (toolCall2.function.arguments.length > 0) {
551
+ controller.enqueue({
552
+ type: "tool-input-delta",
553
+ id: toolCall2.id,
554
+ delta: toolCall2.function.arguments
555
+ });
556
+ }
557
+ if ((0, import_provider_utils2.isParsableJson)(toolCall2.function.arguments)) {
558
+ controller.enqueue({
559
+ type: "tool-input-end",
560
+ id: toolCall2.id
561
+ });
562
+ controller.enqueue({
563
+ type: "tool-call",
564
+ toolCallId: (_i = toolCall2.id) != null ? _i : (0, import_provider_utils2.generateId)(),
565
+ toolName: toolCall2.function.name,
566
+ input: toolCall2.function.arguments
567
+ });
568
+ toolCall2.hasFinished = true;
569
+ }
570
+ }
571
+ continue;
572
+ }
573
+ const toolCall = toolCalls[index];
574
+ if (toolCall.hasFinished) {
575
+ continue;
576
+ }
577
+ if (((_j = toolCallDelta.function) == null ? void 0 : _j.arguments) != null) {
578
+ toolCall.function.arguments += (_l = (_k = toolCallDelta.function) == null ? void 0 : _k.arguments) != null ? _l : "";
579
+ }
580
+ controller.enqueue({
581
+ type: "tool-input-delta",
582
+ id: toolCall.id,
583
+ delta: (_m = toolCallDelta.function.arguments) != null ? _m : ""
584
+ });
585
+ if (((_n = toolCall.function) == null ? void 0 : _n.name) != null && ((_o = toolCall.function) == null ? void 0 : _o.arguments) != null && (0, import_provider_utils2.isParsableJson)(toolCall.function.arguments)) {
586
+ controller.enqueue({
587
+ type: "tool-input-end",
588
+ id: toolCall.id
589
+ });
590
+ controller.enqueue({
591
+ type: "tool-call",
592
+ toolCallId: (_p = toolCall.id) != null ? _p : (0, import_provider_utils2.generateId)(),
593
+ toolName: toolCall.function.name,
594
+ input: toolCall.function.arguments
595
+ });
596
+ toolCall.hasFinished = true;
597
+ }
598
+ }
599
+ }
600
+ },
601
+ flush(controller) {
602
+ if (isActiveReasoning) {
603
+ controller.enqueue({ type: "reasoning-end", id: "reasoning-0" });
604
+ }
605
+ if (isActiveText) {
606
+ controller.enqueue({ type: "text-end", id: "txt-0" });
607
+ }
608
+ controller.enqueue({
609
+ type: "finish",
610
+ finishReason,
611
+ usage,
612
+ ...providerMetadata != null ? { providerMetadata } : {}
613
+ });
614
+ }
615
+ })
616
+ ),
617
+ request: { body },
618
+ response: { headers: responseHeaders }
619
+ };
620
+ }
621
+ };
622
+ var groqChatResponseSchema = import_v43.z.object({
623
+ id: import_v43.z.string().nullish(),
624
+ created: import_v43.z.number().nullish(),
625
+ model: import_v43.z.string().nullish(),
626
+ choices: import_v43.z.array(
627
+ import_v43.z.object({
628
+ message: import_v43.z.object({
629
+ content: import_v43.z.string().nullish(),
630
+ reasoning: import_v43.z.string().nullish(),
631
+ tool_calls: import_v43.z.array(
632
+ import_v43.z.object({
633
+ id: import_v43.z.string().nullish(),
634
+ type: import_v43.z.literal("function"),
635
+ function: import_v43.z.object({
636
+ name: import_v43.z.string(),
637
+ arguments: import_v43.z.string()
638
+ })
639
+ })
640
+ ).nullish()
641
+ }),
642
+ index: import_v43.z.number(),
643
+ finish_reason: import_v43.z.string().nullish()
644
+ })
645
+ ),
646
+ usage: import_v43.z.object({
647
+ prompt_tokens: import_v43.z.number().nullish(),
648
+ completion_tokens: import_v43.z.number().nullish(),
649
+ total_tokens: import_v43.z.number().nullish()
650
+ }).nullish()
651
+ });
652
+ var groqChatChunkSchema = import_v43.z.union([
653
+ import_v43.z.object({
654
+ id: import_v43.z.string().nullish(),
655
+ created: import_v43.z.number().nullish(),
656
+ model: import_v43.z.string().nullish(),
657
+ choices: import_v43.z.array(
658
+ import_v43.z.object({
659
+ delta: import_v43.z.object({
660
+ content: import_v43.z.string().nullish(),
661
+ reasoning: import_v43.z.string().nullish(),
662
+ tool_calls: import_v43.z.array(
663
+ import_v43.z.object({
664
+ index: import_v43.z.number(),
665
+ id: import_v43.z.string().nullish(),
666
+ type: import_v43.z.literal("function").optional(),
667
+ function: import_v43.z.object({
668
+ name: import_v43.z.string().nullish(),
669
+ arguments: import_v43.z.string().nullish()
670
+ })
671
+ })
672
+ ).nullish()
673
+ }).nullish(),
674
+ finish_reason: import_v43.z.string().nullable().optional(),
675
+ index: import_v43.z.number()
676
+ })
677
+ ),
678
+ x_groq: import_v43.z.object({
679
+ usage: import_v43.z.object({
680
+ prompt_tokens: import_v43.z.number().nullish(),
681
+ completion_tokens: import_v43.z.number().nullish(),
682
+ total_tokens: import_v43.z.number().nullish()
683
+ }).nullish()
684
+ }).nullish()
685
+ }),
686
+ groqErrorDataSchema
687
+ ]);
688
+
689
+ // src/groq-transcription-model.ts
690
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
691
+ var import_v44 = require("zod/v4");
692
+ var groqProviderOptionsSchema = import_v44.z.object({
693
+ language: import_v44.z.string().nullish(),
694
+ prompt: import_v44.z.string().nullish(),
695
+ responseFormat: import_v44.z.string().nullish(),
696
+ temperature: import_v44.z.number().min(0).max(1).nullish(),
697
+ timestampGranularities: import_v44.z.array(import_v44.z.string()).nullish()
698
+ });
699
+ var GroqTranscriptionModel = class {
700
+ constructor(modelId, config) {
701
+ this.modelId = modelId;
702
+ this.config = config;
703
+ this.specificationVersion = "v2";
704
+ }
705
+ get provider() {
706
+ return this.config.provider;
707
+ }
708
+ async getArgs({
709
+ audio,
710
+ mediaType,
711
+ providerOptions
712
+ }) {
713
+ var _a, _b, _c, _d, _e;
714
+ const warnings = [];
715
+ const groqOptions = await (0, import_provider_utils3.parseProviderOptions)({
716
+ provider: "groq",
717
+ providerOptions,
718
+ schema: groqProviderOptionsSchema
719
+ });
720
+ const formData = new FormData();
721
+ const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([(0, import_provider_utils3.convertBase64ToUint8Array)(audio)]);
722
+ formData.append("model", this.modelId);
723
+ formData.append("file", new File([blob], "audio", { type: mediaType }));
724
+ if (groqOptions) {
725
+ const transcriptionModelOptions = {
726
+ language: (_a = groqOptions.language) != null ? _a : void 0,
727
+ prompt: (_b = groqOptions.prompt) != null ? _b : void 0,
728
+ response_format: (_c = groqOptions.responseFormat) != null ? _c : void 0,
729
+ temperature: (_d = groqOptions.temperature) != null ? _d : void 0,
730
+ timestamp_granularities: (_e = groqOptions.timestampGranularities) != null ? _e : void 0
731
+ };
732
+ for (const key in transcriptionModelOptions) {
733
+ const value = transcriptionModelOptions[key];
734
+ if (value !== void 0) {
735
+ formData.append(key, String(value));
736
+ }
737
+ }
738
+ }
739
+ return {
740
+ formData,
741
+ warnings
742
+ };
743
+ }
744
+ async doGenerate(options) {
745
+ var _a, _b, _c, _d, _e;
746
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
747
+ const { formData, warnings } = await this.getArgs(options);
748
+ const {
749
+ value: response,
750
+ responseHeaders,
751
+ rawValue: rawResponse
752
+ } = await (0, import_provider_utils3.postFormDataToApi)({
753
+ url: this.config.url({
754
+ path: "/audio/transcriptions",
755
+ modelId: this.modelId
756
+ }),
757
+ headers: (0, import_provider_utils3.combineHeaders)(this.config.headers(), options.headers),
758
+ formData,
759
+ failedResponseHandler: groqFailedResponseHandler,
760
+ successfulResponseHandler: (0, import_provider_utils3.createJsonResponseHandler)(
761
+ groqTranscriptionResponseSchema
762
+ ),
763
+ abortSignal: options.abortSignal,
764
+ fetch: this.config.fetch
765
+ });
766
+ return {
767
+ text: response.text,
768
+ segments: (_e = (_d = response.segments) == null ? void 0 : _d.map((segment) => ({
769
+ text: segment.text,
770
+ startSecond: segment.start,
771
+ endSecond: segment.end
772
+ }))) != null ? _e : [],
773
+ language: response.language,
774
+ durationInSeconds: response.duration,
775
+ warnings,
776
+ response: {
777
+ timestamp: currentDate,
778
+ modelId: this.modelId,
779
+ headers: responseHeaders,
780
+ body: rawResponse
781
+ }
782
+ };
783
+ }
784
+ };
785
+ var groqTranscriptionResponseSchema = import_v44.z.object({
786
+ task: import_v44.z.string(),
787
+ language: import_v44.z.string(),
788
+ duration: import_v44.z.number(),
789
+ text: import_v44.z.string(),
790
+ segments: import_v44.z.array(
791
+ import_v44.z.object({
792
+ id: import_v44.z.number(),
793
+ seek: import_v44.z.number(),
794
+ start: import_v44.z.number(),
795
+ end: import_v44.z.number(),
796
+ text: import_v44.z.string(),
797
+ tokens: import_v44.z.array(import_v44.z.number()),
798
+ temperature: import_v44.z.number(),
799
+ avg_logprob: import_v44.z.number(),
800
+ compression_ratio: import_v44.z.number(),
801
+ no_speech_prob: import_v44.z.number()
802
+ })
803
+ ),
804
+ x_groq: import_v44.z.object({
805
+ id: import_v44.z.string()
806
+ })
807
+ });
808
+
809
+ // src/groq-provider.ts
810
+ function createGroq(options = {}) {
811
+ var _a;
812
+ const baseURL = (_a = (0, import_provider_utils4.withoutTrailingSlash)(options.baseURL)) != null ? _a : "https://api.groq.com/openai/v1";
813
+ const getHeaders = () => ({
814
+ Authorization: `Bearer ${(0, import_provider_utils4.loadApiKey)({
815
+ apiKey: options.apiKey,
816
+ environmentVariableName: "GROQ_API_KEY",
817
+ description: "Groq"
818
+ })}`,
819
+ ...options.headers
820
+ });
821
+ const createChatModel = (modelId) => new GroqChatLanguageModel(modelId, {
822
+ provider: "groq.chat",
823
+ url: ({ path }) => `${baseURL}${path}`,
824
+ headers: getHeaders,
825
+ fetch: options.fetch
826
+ });
827
+ const createLanguageModel = (modelId) => {
828
+ if (new.target) {
829
+ throw new Error(
830
+ "The Groq model function cannot be called with the new keyword."
831
+ );
832
+ }
833
+ return createChatModel(modelId);
834
+ };
835
+ const createTranscriptionModel = (modelId) => {
836
+ return new GroqTranscriptionModel(modelId, {
837
+ provider: "groq.transcription",
838
+ url: ({ path }) => `${baseURL}${path}`,
839
+ headers: getHeaders,
840
+ fetch: options.fetch
841
+ });
842
+ };
843
+ const provider = function(modelId) {
844
+ return createLanguageModel(modelId);
845
+ };
846
+ provider.languageModel = createLanguageModel;
847
+ provider.chat = createChatModel;
848
+ provider.textEmbeddingModel = (modelId) => {
849
+ throw new import_provider4.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
850
+ };
851
+ provider.imageModel = (modelId) => {
852
+ throw new import_provider4.NoSuchModelError({ modelId, modelType: "imageModel" });
853
+ };
854
+ provider.transcription = createTranscriptionModel;
855
+ return provider;
856
+ }
857
+ var groq = createGroq();
858
+ // Annotate the CommonJS export names for ESM import in node:
859
+ 0 && (module.exports = {
860
+ createGroq,
861
+ groq
862
+ });
863
+ //# sourceMappingURL=index.js.map