@ai-sdk/groq 0.0.1

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