@ai-sdk/groq 4.0.0-beta.3 → 4.0.0-beta.30

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