@ai-sdk/groq 4.0.0-beta.22 → 4.0.0-beta.23

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 DELETED
@@ -1,1061 +0,0 @@
1
- // src/groq-provider.ts
2
- import {
3
- NoSuchModelError
4
- } from "@ai-sdk/provider";
5
- import {
6
- loadApiKey,
7
- withoutTrailingSlash,
8
- withUserAgentSuffix
9
- } from "@ai-sdk/provider-utils";
10
-
11
- // src/groq-chat-language-model.ts
12
- import {
13
- InvalidResponseDataError
14
- } from "@ai-sdk/provider";
15
- import {
16
- combineHeaders,
17
- createEventSourceResponseHandler,
18
- createJsonResponseHandler,
19
- generateId,
20
- isCustomReasoning,
21
- isParsableJson,
22
- mapReasoningToProviderEffort,
23
- parseProviderOptions,
24
- postJsonToApi
25
- } from "@ai-sdk/provider-utils";
26
- import { z as z3 } from "zod/v4";
27
-
28
- // src/convert-groq-usage.ts
29
- function convertGroqUsage(usage) {
30
- var _a, _b, _c, _d;
31
- if (usage == null) {
32
- return {
33
- inputTokens: {
34
- total: void 0,
35
- noCache: void 0,
36
- cacheRead: void 0,
37
- cacheWrite: void 0
38
- },
39
- outputTokens: {
40
- total: void 0,
41
- text: void 0,
42
- reasoning: void 0
43
- },
44
- raw: void 0
45
- };
46
- }
47
- const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;
48
- const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
49
- const reasoningTokens = (_d = (_c = usage.completion_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : void 0;
50
- const textTokens = reasoningTokens != null ? completionTokens - reasoningTokens : completionTokens;
51
- return {
52
- inputTokens: {
53
- total: promptTokens,
54
- noCache: promptTokens,
55
- cacheRead: void 0,
56
- cacheWrite: void 0
57
- },
58
- outputTokens: {
59
- total: completionTokens,
60
- text: textTokens,
61
- reasoning: reasoningTokens
62
- },
63
- raw: usage
64
- };
65
- }
66
-
67
- // src/convert-to-groq-chat-messages.ts
68
- import {
69
- UnsupportedFunctionalityError
70
- } from "@ai-sdk/provider";
71
- import { convertToBase64, isProviderReference } from "@ai-sdk/provider-utils";
72
- function convertToGroqChatMessages(prompt) {
73
- var _a;
74
- const messages = [];
75
- for (const { role, content } of prompt) {
76
- switch (role) {
77
- case "system": {
78
- messages.push({ role: "system", content });
79
- break;
80
- }
81
- case "user": {
82
- if (content.length === 1 && content[0].type === "text") {
83
- messages.push({ role: "user", content: content[0].text });
84
- break;
85
- }
86
- messages.push({
87
- role: "user",
88
- content: content.map((part) => {
89
- switch (part.type) {
90
- case "text": {
91
- return { type: "text", text: part.text };
92
- }
93
- case "file": {
94
- if (isProviderReference(part.data)) {
95
- throw new UnsupportedFunctionalityError({
96
- functionality: "file parts with provider references"
97
- });
98
- }
99
- if (!part.mediaType.startsWith("image/")) {
100
- throw new UnsupportedFunctionalityError({
101
- functionality: "Non-image file content parts"
102
- });
103
- }
104
- const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
105
- return {
106
- type: "image_url",
107
- image_url: {
108
- url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`
109
- }
110
- };
111
- }
112
- }
113
- })
114
- });
115
- break;
116
- }
117
- case "assistant": {
118
- let text = "";
119
- let reasoning = "";
120
- const toolCalls = [];
121
- for (const part of content) {
122
- switch (part.type) {
123
- // groq supports reasoning for tool-calls in multi-turn conversations
124
- // https://github.com/vercel/ai/issues/7860
125
- case "reasoning": {
126
- reasoning += part.text;
127
- break;
128
- }
129
- case "text": {
130
- text += part.text;
131
- break;
132
- }
133
- case "tool-call": {
134
- toolCalls.push({
135
- id: part.toolCallId,
136
- type: "function",
137
- function: {
138
- name: part.toolName,
139
- arguments: JSON.stringify(part.input)
140
- }
141
- });
142
- break;
143
- }
144
- }
145
- }
146
- messages.push({
147
- role: "assistant",
148
- content: text,
149
- ...reasoning.length > 0 ? { reasoning } : null,
150
- ...toolCalls.length > 0 ? { tool_calls: toolCalls } : null
151
- });
152
- break;
153
- }
154
- case "tool": {
155
- for (const toolResponse of content) {
156
- if (toolResponse.type === "tool-approval-response") {
157
- continue;
158
- }
159
- const output = toolResponse.output;
160
- let contentValue;
161
- switch (output.type) {
162
- case "text":
163
- case "error-text":
164
- contentValue = output.value;
165
- break;
166
- case "execution-denied":
167
- contentValue = (_a = output.reason) != null ? _a : "Tool execution denied.";
168
- break;
169
- case "content":
170
- case "json":
171
- case "error-json":
172
- contentValue = JSON.stringify(output.value);
173
- break;
174
- }
175
- messages.push({
176
- role: "tool",
177
- tool_call_id: toolResponse.toolCallId,
178
- content: contentValue
179
- });
180
- }
181
- break;
182
- }
183
- default: {
184
- const _exhaustiveCheck = role;
185
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
186
- }
187
- }
188
- }
189
- return messages;
190
- }
191
-
192
- // src/get-response-metadata.ts
193
- function getResponseMetadata({
194
- id,
195
- model,
196
- created
197
- }) {
198
- return {
199
- id: id != null ? id : void 0,
200
- modelId: model != null ? model : void 0,
201
- timestamp: created != null ? new Date(created * 1e3) : void 0
202
- };
203
- }
204
-
205
- // src/groq-chat-options.ts
206
- import { z } from "zod/v4";
207
- var groqLanguageModelOptions = z.object({
208
- reasoningFormat: z.enum(["parsed", "raw", "hidden"]).optional(),
209
- /**
210
- * Specifies the reasoning effort level for model inference.
211
- * @see https://console.groq.com/docs/reasoning#reasoning-effort
212
- */
213
- reasoningEffort: z.enum(["none", "default", "low", "medium", "high"]).optional(),
214
- /**
215
- * Whether to enable parallel function calling during tool use. Default to true.
216
- */
217
- parallelToolCalls: z.boolean().optional(),
218
- /**
219
- * A unique identifier representing your end-user, which can help OpenAI to
220
- * monitor and detect abuse. Learn more.
221
- */
222
- user: z.string().optional(),
223
- /**
224
- * Whether to use structured outputs.
225
- *
226
- * @default true
227
- */
228
- structuredOutputs: z.boolean().optional(),
229
- /**
230
- * Whether to use strict JSON schema validation.
231
- * When true, the model uses constrained decoding to guarantee schema compliance.
232
- * Only used when structured outputs are enabled and a schema is provided.
233
- *
234
- * @default true
235
- */
236
- strictJsonSchema: z.boolean().optional(),
237
- /**
238
- * Service tier for the request.
239
- * - 'on_demand': Default tier with consistent performance and fairness
240
- * - 'performance': Prioritized tier for latency-sensitive workloads
241
- * - 'flex': Higher throughput tier optimized for workloads that can handle occasional request failures
242
- * - 'auto': Uses on_demand rate limits, then falls back to flex tier if exceeded
243
- *
244
- * @default 'on_demand'
245
- */
246
- serviceTier: z.enum(["on_demand", "performance", "flex", "auto"]).optional()
247
- });
248
-
249
- // src/groq-error.ts
250
- import { z as z2 } from "zod/v4";
251
- import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
252
- var groqErrorDataSchema = z2.object({
253
- error: z2.object({
254
- message: z2.string(),
255
- type: z2.string()
256
- })
257
- });
258
- var groqFailedResponseHandler = createJsonErrorResponseHandler({
259
- errorSchema: groqErrorDataSchema,
260
- errorToMessage: (data) => data.error.message
261
- });
262
-
263
- // src/groq-prepare-tools.ts
264
- import {
265
- UnsupportedFunctionalityError as UnsupportedFunctionalityError2
266
- } from "@ai-sdk/provider";
267
-
268
- // src/groq-browser-search-models.ts
269
- var BROWSER_SEARCH_SUPPORTED_MODELS = [
270
- "openai/gpt-oss-20b",
271
- "openai/gpt-oss-120b"
272
- ];
273
- function isBrowserSearchSupportedModel(modelId) {
274
- return BROWSER_SEARCH_SUPPORTED_MODELS.includes(modelId);
275
- }
276
- function getSupportedModelsString() {
277
- return BROWSER_SEARCH_SUPPORTED_MODELS.join(", ");
278
- }
279
-
280
- // src/groq-prepare-tools.ts
281
- function prepareTools({
282
- tools,
283
- toolChoice,
284
- modelId
285
- }) {
286
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
287
- const toolWarnings = [];
288
- if (tools == null) {
289
- return { tools: void 0, toolChoice: void 0, toolWarnings };
290
- }
291
- const groqTools2 = [];
292
- for (const tool of tools) {
293
- if (tool.type === "provider") {
294
- if (tool.id === "groq.browser_search") {
295
- if (!isBrowserSearchSupportedModel(modelId)) {
296
- toolWarnings.push({
297
- type: "unsupported",
298
- feature: `provider-defined tool ${tool.id}`,
299
- details: `Browser search is only supported on the following models: ${getSupportedModelsString()}. Current model: ${modelId}`
300
- });
301
- } else {
302
- groqTools2.push({
303
- type: "browser_search"
304
- });
305
- }
306
- } else {
307
- toolWarnings.push({
308
- type: "unsupported",
309
- feature: `provider-defined tool ${tool.id}`
310
- });
311
- }
312
- } else {
313
- groqTools2.push({
314
- type: "function",
315
- function: {
316
- name: tool.name,
317
- description: tool.description,
318
- parameters: tool.inputSchema,
319
- ...tool.strict != null ? { strict: tool.strict } : {}
320
- }
321
- });
322
- }
323
- }
324
- if (toolChoice == null) {
325
- return { tools: groqTools2, toolChoice: void 0, toolWarnings };
326
- }
327
- const type = toolChoice.type;
328
- switch (type) {
329
- case "auto":
330
- case "none":
331
- case "required":
332
- return { tools: groqTools2, toolChoice: type, toolWarnings };
333
- case "tool":
334
- return {
335
- tools: groqTools2,
336
- toolChoice: {
337
- type: "function",
338
- function: {
339
- name: toolChoice.toolName
340
- }
341
- },
342
- toolWarnings
343
- };
344
- default: {
345
- const _exhaustiveCheck = type;
346
- throw new UnsupportedFunctionalityError2({
347
- functionality: `tool choice type: ${_exhaustiveCheck}`
348
- });
349
- }
350
- }
351
- }
352
-
353
- // src/map-groq-finish-reason.ts
354
- function mapGroqFinishReason(finishReason) {
355
- switch (finishReason) {
356
- case "stop":
357
- return "stop";
358
- case "length":
359
- return "length";
360
- case "content_filter":
361
- return "content-filter";
362
- case "function_call":
363
- case "tool_calls":
364
- return "tool-calls";
365
- default:
366
- return "other";
367
- }
368
- }
369
-
370
- // src/groq-chat-language-model.ts
371
- var GroqChatLanguageModel = class {
372
- constructor(modelId, config) {
373
- this.specificationVersion = "v4";
374
- this.supportedUrls = {
375
- "image/*": [/^https?:\/\/.*$/]
376
- };
377
- this.modelId = modelId;
378
- this.config = config;
379
- }
380
- get provider() {
381
- return this.config.provider;
382
- }
383
- async getArgs({
384
- prompt,
385
- maxOutputTokens,
386
- temperature,
387
- topP,
388
- topK,
389
- frequencyPenalty,
390
- presencePenalty,
391
- stopSequences,
392
- responseFormat,
393
- seed,
394
- reasoning,
395
- tools,
396
- toolChoice,
397
- providerOptions
398
- }) {
399
- var _a, _b, _c, _d;
400
- const warnings = [];
401
- const groqOptions = await parseProviderOptions({
402
- provider: "groq",
403
- providerOptions,
404
- schema: groqLanguageModelOptions
405
- });
406
- const structuredOutputs = (_a = groqOptions == null ? void 0 : groqOptions.structuredOutputs) != null ? _a : true;
407
- const strictJsonSchema = (_b = groqOptions == null ? void 0 : groqOptions.strictJsonSchema) != null ? _b : true;
408
- if (topK != null) {
409
- warnings.push({ type: "unsupported", feature: "topK" });
410
- }
411
- if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !structuredOutputs) {
412
- warnings.push({
413
- type: "unsupported",
414
- feature: "responseFormat",
415
- details: "JSON response format schema is only supported with structuredOutputs"
416
- });
417
- }
418
- const {
419
- tools: groqTools2,
420
- toolChoice: groqToolChoice,
421
- toolWarnings
422
- } = prepareTools({ tools, toolChoice, modelId: this.modelId });
423
- return {
424
- args: {
425
- // model id:
426
- model: this.modelId,
427
- // model specific settings:
428
- user: groqOptions == null ? void 0 : groqOptions.user,
429
- parallel_tool_calls: groqOptions == null ? void 0 : groqOptions.parallelToolCalls,
430
- // standardized settings:
431
- max_tokens: maxOutputTokens,
432
- temperature,
433
- top_p: topP,
434
- frequency_penalty: frequencyPenalty,
435
- presence_penalty: presencePenalty,
436
- stop: stopSequences,
437
- seed,
438
- // response format:
439
- response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? structuredOutputs && responseFormat.schema != null ? {
440
- type: "json_schema",
441
- json_schema: {
442
- schema: responseFormat.schema,
443
- strict: strictJsonSchema,
444
- name: (_c = responseFormat.name) != null ? _c : "response",
445
- description: responseFormat.description
446
- }
447
- } : { type: "json_object" } : void 0,
448
- // provider options:
449
- reasoning_format: groqOptions == null ? void 0 : groqOptions.reasoningFormat,
450
- reasoning_effort: (_d = groqOptions == null ? void 0 : groqOptions.reasoningEffort) != null ? _d : isCustomReasoning(reasoning) && reasoning !== "none" ? mapReasoningToProviderEffort({
451
- reasoning,
452
- effortMap: {
453
- minimal: "low",
454
- low: "low",
455
- medium: "medium",
456
- high: "high",
457
- xhigh: "high"
458
- },
459
- warnings
460
- }) : void 0,
461
- service_tier: groqOptions == null ? void 0 : groqOptions.serviceTier,
462
- // messages:
463
- messages: convertToGroqChatMessages(prompt),
464
- // tools:
465
- tools: groqTools2,
466
- tool_choice: groqToolChoice
467
- },
468
- warnings: [...warnings, ...toolWarnings]
469
- };
470
- }
471
- async doGenerate(options) {
472
- var _a, _b;
473
- const { args, warnings } = await this.getArgs(options);
474
- const body = JSON.stringify(args);
475
- const {
476
- responseHeaders,
477
- value: response,
478
- rawValue: rawResponse
479
- } = await postJsonToApi({
480
- url: this.config.url({
481
- path: "/chat/completions",
482
- modelId: this.modelId
483
- }),
484
- headers: combineHeaders(this.config.headers(), options.headers),
485
- body: args,
486
- failedResponseHandler: groqFailedResponseHandler,
487
- successfulResponseHandler: createJsonResponseHandler(
488
- groqChatResponseSchema
489
- ),
490
- abortSignal: options.abortSignal,
491
- fetch: this.config.fetch
492
- });
493
- const choice = response.choices[0];
494
- const content = [];
495
- const text = choice.message.content;
496
- if (text != null && text.length > 0) {
497
- content.push({ type: "text", text });
498
- }
499
- const reasoning = choice.message.reasoning;
500
- if (reasoning != null && reasoning.length > 0) {
501
- content.push({
502
- type: "reasoning",
503
- text: reasoning
504
- });
505
- }
506
- if (choice.message.tool_calls != null) {
507
- for (const toolCall of choice.message.tool_calls) {
508
- content.push({
509
- type: "tool-call",
510
- toolCallId: (_a = toolCall.id) != null ? _a : generateId(),
511
- toolName: toolCall.function.name,
512
- input: toolCall.function.arguments
513
- });
514
- }
515
- }
516
- return {
517
- content,
518
- finishReason: {
519
- unified: mapGroqFinishReason(choice.finish_reason),
520
- raw: (_b = choice.finish_reason) != null ? _b : void 0
521
- },
522
- usage: convertGroqUsage(response.usage),
523
- response: {
524
- ...getResponseMetadata(response),
525
- headers: responseHeaders,
526
- body: rawResponse
527
- },
528
- warnings,
529
- request: { body }
530
- };
531
- }
532
- async doStream(options) {
533
- const { args, warnings } = await this.getArgs(options);
534
- const body = { ...args, stream: true };
535
- const { responseHeaders, value: response } = await postJsonToApi({
536
- url: this.config.url({
537
- path: "/chat/completions",
538
- modelId: this.modelId
539
- }),
540
- headers: combineHeaders(this.config.headers(), options.headers),
541
- body,
542
- failedResponseHandler: groqFailedResponseHandler,
543
- successfulResponseHandler: createEventSourceResponseHandler(groqChatChunkSchema),
544
- abortSignal: options.abortSignal,
545
- fetch: this.config.fetch
546
- });
547
- const toolCalls = [];
548
- let finishReason = {
549
- unified: "other",
550
- raw: void 0
551
- };
552
- let usage = void 0;
553
- let isFirstChunk = true;
554
- let isActiveText = false;
555
- let isActiveReasoning = false;
556
- let providerMetadata;
557
- return {
558
- stream: response.pipeThrough(
559
- new TransformStream({
560
- start(controller) {
561
- controller.enqueue({ type: "stream-start", warnings });
562
- },
563
- transform(chunk, controller) {
564
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
565
- if (options.includeRawChunks) {
566
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
567
- }
568
- if (!chunk.success) {
569
- finishReason = {
570
- unified: "error",
571
- raw: void 0
572
- };
573
- controller.enqueue({ type: "error", error: chunk.error });
574
- return;
575
- }
576
- const value = chunk.value;
577
- if ("error" in value) {
578
- finishReason = {
579
- unified: "error",
580
- raw: void 0
581
- };
582
- controller.enqueue({ type: "error", error: value.error });
583
- return;
584
- }
585
- if (isFirstChunk) {
586
- isFirstChunk = false;
587
- controller.enqueue({
588
- type: "response-metadata",
589
- ...getResponseMetadata(value)
590
- });
591
- }
592
- if (((_a = value.x_groq) == null ? void 0 : _a.usage) != null) {
593
- usage = value.x_groq.usage;
594
- }
595
- const choice = value.choices[0];
596
- if ((choice == null ? void 0 : choice.finish_reason) != null) {
597
- finishReason = {
598
- unified: mapGroqFinishReason(choice.finish_reason),
599
- raw: choice.finish_reason
600
- };
601
- }
602
- if ((choice == null ? void 0 : choice.delta) == null) {
603
- return;
604
- }
605
- const delta = choice.delta;
606
- if (delta.reasoning != null && delta.reasoning.length > 0) {
607
- if (!isActiveReasoning) {
608
- controller.enqueue({
609
- type: "reasoning-start",
610
- id: "reasoning-0"
611
- });
612
- isActiveReasoning = true;
613
- }
614
- controller.enqueue({
615
- type: "reasoning-delta",
616
- id: "reasoning-0",
617
- delta: delta.reasoning
618
- });
619
- }
620
- if (delta.content != null && delta.content.length > 0) {
621
- if (isActiveReasoning) {
622
- controller.enqueue({
623
- type: "reasoning-end",
624
- id: "reasoning-0"
625
- });
626
- isActiveReasoning = false;
627
- }
628
- if (!isActiveText) {
629
- controller.enqueue({ type: "text-start", id: "txt-0" });
630
- isActiveText = true;
631
- }
632
- controller.enqueue({
633
- type: "text-delta",
634
- id: "txt-0",
635
- delta: delta.content
636
- });
637
- }
638
- if (delta.tool_calls != null) {
639
- if (isActiveReasoning) {
640
- controller.enqueue({
641
- type: "reasoning-end",
642
- id: "reasoning-0"
643
- });
644
- isActiveReasoning = false;
645
- }
646
- for (const toolCallDelta of delta.tool_calls) {
647
- const index = toolCallDelta.index;
648
- if (toolCalls[index] == null) {
649
- if (toolCallDelta.type !== "function") {
650
- throw new InvalidResponseDataError({
651
- data: toolCallDelta,
652
- message: `Expected 'function' type.`
653
- });
654
- }
655
- if (toolCallDelta.id == null) {
656
- throw new InvalidResponseDataError({
657
- data: toolCallDelta,
658
- message: `Expected 'id' to be a string.`
659
- });
660
- }
661
- if (((_b = toolCallDelta.function) == null ? void 0 : _b.name) == null) {
662
- throw new InvalidResponseDataError({
663
- data: toolCallDelta,
664
- message: `Expected 'function.name' to be a string.`
665
- });
666
- }
667
- controller.enqueue({
668
- type: "tool-input-start",
669
- id: toolCallDelta.id,
670
- toolName: toolCallDelta.function.name
671
- });
672
- toolCalls[index] = {
673
- id: toolCallDelta.id,
674
- type: "function",
675
- function: {
676
- name: toolCallDelta.function.name,
677
- arguments: (_c = toolCallDelta.function.arguments) != null ? _c : ""
678
- },
679
- hasFinished: false
680
- };
681
- const toolCall2 = toolCalls[index];
682
- if (((_d = toolCall2.function) == null ? void 0 : _d.name) != null && ((_e = toolCall2.function) == null ? void 0 : _e.arguments) != null) {
683
- if (toolCall2.function.arguments.length > 0) {
684
- controller.enqueue({
685
- type: "tool-input-delta",
686
- id: toolCall2.id,
687
- delta: toolCall2.function.arguments
688
- });
689
- }
690
- if (isParsableJson(toolCall2.function.arguments)) {
691
- controller.enqueue({
692
- type: "tool-input-end",
693
- id: toolCall2.id
694
- });
695
- controller.enqueue({
696
- type: "tool-call",
697
- toolCallId: (_f = toolCall2.id) != null ? _f : generateId(),
698
- toolName: toolCall2.function.name,
699
- input: toolCall2.function.arguments
700
- });
701
- toolCall2.hasFinished = true;
702
- }
703
- }
704
- continue;
705
- }
706
- const toolCall = toolCalls[index];
707
- if (toolCall.hasFinished) {
708
- continue;
709
- }
710
- if (((_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null) {
711
- toolCall.function.arguments += (_i = (_h = toolCallDelta.function) == null ? void 0 : _h.arguments) != null ? _i : "";
712
- }
713
- controller.enqueue({
714
- type: "tool-input-delta",
715
- id: toolCall.id,
716
- delta: (_j = toolCallDelta.function.arguments) != null ? _j : ""
717
- });
718
- if (((_k = toolCall.function) == null ? void 0 : _k.name) != null && ((_l = toolCall.function) == null ? void 0 : _l.arguments) != null && isParsableJson(toolCall.function.arguments)) {
719
- controller.enqueue({
720
- type: "tool-input-end",
721
- id: toolCall.id
722
- });
723
- controller.enqueue({
724
- type: "tool-call",
725
- toolCallId: (_m = toolCall.id) != null ? _m : generateId(),
726
- toolName: toolCall.function.name,
727
- input: toolCall.function.arguments
728
- });
729
- toolCall.hasFinished = true;
730
- }
731
- }
732
- }
733
- },
734
- flush(controller) {
735
- if (isActiveReasoning) {
736
- controller.enqueue({ type: "reasoning-end", id: "reasoning-0" });
737
- }
738
- if (isActiveText) {
739
- controller.enqueue({ type: "text-end", id: "txt-0" });
740
- }
741
- controller.enqueue({
742
- type: "finish",
743
- finishReason,
744
- usage: convertGroqUsage(usage),
745
- ...providerMetadata != null ? { providerMetadata } : {}
746
- });
747
- }
748
- })
749
- ),
750
- request: { body: JSON.stringify(body) },
751
- response: { headers: responseHeaders }
752
- };
753
- }
754
- };
755
- var groqChatResponseSchema = z3.object({
756
- id: z3.string().nullish(),
757
- created: z3.number().nullish(),
758
- model: z3.string().nullish(),
759
- choices: z3.array(
760
- z3.object({
761
- message: z3.object({
762
- content: z3.string().nullish(),
763
- reasoning: z3.string().nullish(),
764
- tool_calls: z3.array(
765
- z3.object({
766
- id: z3.string().nullish(),
767
- type: z3.literal("function"),
768
- function: z3.object({
769
- name: z3.string(),
770
- arguments: z3.string()
771
- })
772
- })
773
- ).nullish()
774
- }),
775
- index: z3.number(),
776
- finish_reason: z3.string().nullish()
777
- })
778
- ),
779
- usage: z3.object({
780
- prompt_tokens: z3.number().nullish(),
781
- completion_tokens: z3.number().nullish(),
782
- total_tokens: z3.number().nullish(),
783
- prompt_tokens_details: z3.object({
784
- cached_tokens: z3.number().nullish()
785
- }).nullish(),
786
- completion_tokens_details: z3.object({
787
- reasoning_tokens: z3.number().nullish()
788
- }).nullish()
789
- }).nullish()
790
- });
791
- var groqChatChunkSchema = z3.union([
792
- z3.object({
793
- id: z3.string().nullish(),
794
- created: z3.number().nullish(),
795
- model: z3.string().nullish(),
796
- choices: z3.array(
797
- z3.object({
798
- delta: z3.object({
799
- content: z3.string().nullish(),
800
- reasoning: z3.string().nullish(),
801
- tool_calls: z3.array(
802
- z3.object({
803
- index: z3.number(),
804
- id: z3.string().nullish(),
805
- type: z3.literal("function").optional(),
806
- function: z3.object({
807
- name: z3.string().nullish(),
808
- arguments: z3.string().nullish()
809
- })
810
- })
811
- ).nullish()
812
- }).nullish(),
813
- finish_reason: z3.string().nullable().optional(),
814
- index: z3.number()
815
- })
816
- ),
817
- x_groq: z3.object({
818
- usage: z3.object({
819
- prompt_tokens: z3.number().nullish(),
820
- completion_tokens: z3.number().nullish(),
821
- total_tokens: z3.number().nullish(),
822
- prompt_tokens_details: z3.object({
823
- cached_tokens: z3.number().nullish()
824
- }).nullish(),
825
- completion_tokens_details: z3.object({
826
- reasoning_tokens: z3.number().nullish()
827
- }).nullish()
828
- }).nullish()
829
- }).nullish()
830
- }),
831
- groqErrorDataSchema
832
- ]);
833
-
834
- // src/groq-transcription-model.ts
835
- import {
836
- combineHeaders as combineHeaders2,
837
- convertBase64ToUint8Array,
838
- createJsonResponseHandler as createJsonResponseHandler2,
839
- mediaTypeToExtension,
840
- parseProviderOptions as parseProviderOptions2,
841
- postFormDataToApi
842
- } from "@ai-sdk/provider-utils";
843
- import { z as z5 } from "zod/v4";
844
-
845
- // src/groq-transcription-options.ts
846
- import { lazySchema, zodSchema } from "@ai-sdk/provider-utils";
847
- import { z as z4 } from "zod/v4";
848
- var groqTranscriptionModelOptions = lazySchema(
849
- () => zodSchema(
850
- z4.object({
851
- language: z4.string().nullish(),
852
- prompt: z4.string().nullish(),
853
- responseFormat: z4.string().nullish(),
854
- temperature: z4.number().min(0).max(1).nullish(),
855
- timestampGranularities: z4.array(z4.string()).nullish()
856
- })
857
- )
858
- );
859
-
860
- // src/groq-transcription-model.ts
861
- var GroqTranscriptionModel = class {
862
- constructor(modelId, config) {
863
- this.modelId = modelId;
864
- this.config = config;
865
- this.specificationVersion = "v4";
866
- }
867
- get provider() {
868
- return this.config.provider;
869
- }
870
- async getArgs({
871
- audio,
872
- mediaType,
873
- providerOptions
874
- }) {
875
- var _a, _b, _c, _d, _e;
876
- const warnings = [];
877
- const groqOptions = await parseProviderOptions2({
878
- provider: "groq",
879
- providerOptions,
880
- schema: groqTranscriptionModelOptions
881
- });
882
- const formData = new FormData();
883
- const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]);
884
- formData.append("model", this.modelId);
885
- const fileExtension = mediaTypeToExtension(mediaType);
886
- formData.append(
887
- "file",
888
- new File([blob], "audio", { type: mediaType }),
889
- `audio.${fileExtension}`
890
- );
891
- if (groqOptions) {
892
- const transcriptionModelOptions = {
893
- language: (_a = groqOptions.language) != null ? _a : void 0,
894
- prompt: (_b = groqOptions.prompt) != null ? _b : void 0,
895
- response_format: (_c = groqOptions.responseFormat) != null ? _c : void 0,
896
- temperature: (_d = groqOptions.temperature) != null ? _d : void 0,
897
- timestamp_granularities: (_e = groqOptions.timestampGranularities) != null ? _e : void 0
898
- };
899
- for (const key in transcriptionModelOptions) {
900
- const value = transcriptionModelOptions[key];
901
- if (value !== void 0) {
902
- if (Array.isArray(value)) {
903
- for (const item of value) {
904
- formData.append(`${key}[]`, String(item));
905
- }
906
- } else {
907
- formData.append(key, String(value));
908
- }
909
- }
910
- }
911
- }
912
- return {
913
- formData,
914
- warnings
915
- };
916
- }
917
- async doGenerate(options) {
918
- var _a, _b, _c, _d, _e, _f, _g;
919
- const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
920
- const { formData, warnings } = await this.getArgs(options);
921
- const {
922
- value: response,
923
- responseHeaders,
924
- rawValue: rawResponse
925
- } = await postFormDataToApi({
926
- url: this.config.url({
927
- path: "/audio/transcriptions",
928
- modelId: this.modelId
929
- }),
930
- headers: combineHeaders2(this.config.headers(), options.headers),
931
- formData,
932
- failedResponseHandler: groqFailedResponseHandler,
933
- successfulResponseHandler: createJsonResponseHandler2(
934
- groqTranscriptionResponseSchema
935
- ),
936
- abortSignal: options.abortSignal,
937
- fetch: this.config.fetch
938
- });
939
- return {
940
- text: response.text,
941
- segments: (_e = (_d = response.segments) == null ? void 0 : _d.map((segment) => ({
942
- text: segment.text,
943
- startSecond: segment.start,
944
- endSecond: segment.end
945
- }))) != null ? _e : [],
946
- language: (_f = response.language) != null ? _f : void 0,
947
- durationInSeconds: (_g = response.duration) != null ? _g : void 0,
948
- warnings,
949
- response: {
950
- timestamp: currentDate,
951
- modelId: this.modelId,
952
- headers: responseHeaders,
953
- body: rawResponse
954
- }
955
- };
956
- }
957
- };
958
- var groqTranscriptionResponseSchema = z5.object({
959
- text: z5.string(),
960
- x_groq: z5.object({
961
- id: z5.string()
962
- }),
963
- // additional properties are returned when `response_format: 'verbose_json'` is
964
- task: z5.string().nullish(),
965
- language: z5.string().nullish(),
966
- duration: z5.number().nullish(),
967
- segments: z5.array(
968
- z5.object({
969
- id: z5.number(),
970
- seek: z5.number(),
971
- start: z5.number(),
972
- end: z5.number(),
973
- text: z5.string(),
974
- tokens: z5.array(z5.number()),
975
- temperature: z5.number(),
976
- avg_logprob: z5.number(),
977
- compression_ratio: z5.number(),
978
- no_speech_prob: z5.number()
979
- })
980
- ).nullish()
981
- });
982
-
983
- // src/tool/browser-search.ts
984
- import { createProviderToolFactory } from "@ai-sdk/provider-utils";
985
- import { z as z6 } from "zod/v4";
986
- var browserSearch = createProviderToolFactory({
987
- id: "groq.browser_search",
988
- inputSchema: z6.object({})
989
- });
990
-
991
- // src/groq-tools.ts
992
- var groqTools = {
993
- browserSearch
994
- };
995
-
996
- // src/version.ts
997
- var VERSION = true ? "4.0.0-beta.22" : "0.0.0-test";
998
-
999
- // src/groq-provider.ts
1000
- function createGroq(options = {}) {
1001
- var _a;
1002
- const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.groq.com/openai/v1";
1003
- const getHeaders = () => withUserAgentSuffix(
1004
- {
1005
- Authorization: `Bearer ${loadApiKey({
1006
- apiKey: options.apiKey,
1007
- environmentVariableName: "GROQ_API_KEY",
1008
- description: "Groq"
1009
- })}`,
1010
- ...options.headers
1011
- },
1012
- `ai-sdk/groq/${VERSION}`
1013
- );
1014
- const createChatModel = (modelId) => new GroqChatLanguageModel(modelId, {
1015
- provider: "groq.chat",
1016
- url: ({ path }) => `${baseURL}${path}`,
1017
- headers: getHeaders,
1018
- fetch: options.fetch
1019
- });
1020
- const createLanguageModel = (modelId) => {
1021
- if (new.target) {
1022
- throw new Error(
1023
- "The Groq model function cannot be called with the new keyword."
1024
- );
1025
- }
1026
- return createChatModel(modelId);
1027
- };
1028
- const createTranscriptionModel = (modelId) => {
1029
- return new GroqTranscriptionModel(modelId, {
1030
- provider: "groq.transcription",
1031
- url: ({ path }) => `${baseURL}${path}`,
1032
- headers: getHeaders,
1033
- fetch: options.fetch
1034
- });
1035
- };
1036
- const provider = function(modelId) {
1037
- return createLanguageModel(modelId);
1038
- };
1039
- provider.specificationVersion = "v4";
1040
- provider.languageModel = createLanguageModel;
1041
- provider.chat = createChatModel;
1042
- provider.embeddingModel = (modelId) => {
1043
- throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
1044
- };
1045
- provider.textEmbeddingModel = provider.embeddingModel;
1046
- provider.imageModel = (modelId) => {
1047
- throw new NoSuchModelError({ modelId, modelType: "imageModel" });
1048
- };
1049
- provider.transcription = createTranscriptionModel;
1050
- provider.transcriptionModel = createTranscriptionModel;
1051
- provider.tools = groqTools;
1052
- return provider;
1053
- }
1054
- var groq = createGroq();
1055
- export {
1056
- VERSION,
1057
- browserSearch,
1058
- createGroq,
1059
- groq
1060
- };
1061
- //# sourceMappingURL=index.mjs.map