@untiny/qwen-ai-provider 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,1292 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ VERSION: () => VERSION2,
34
+ createQwen: () => createQwen,
35
+ qwen: () => qwen
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/qwen-provider.ts
40
+ var import_provider6 = require("@ai-sdk/provider");
41
+ var import_provider_utils10 = require("@ai-sdk/provider-utils");
42
+
43
+ // src/chat/qwen-chat-language-model.ts
44
+ var import_provider3 = require("@ai-sdk/provider");
45
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
46
+
47
+ // src/qwen-error.ts
48
+ var import_provider_utils = require("@ai-sdk/provider-utils");
49
+ var import_zod = __toESM(require("zod"));
50
+ var qwenErrorDataSchema = import_zod.default.object({
51
+ object: import_zod.default.literal("error"),
52
+ message: import_zod.default.string(),
53
+ type: import_zod.default.string(),
54
+ param: import_zod.default.string().nullable(),
55
+ code: import_zod.default.string().nullable()
56
+ });
57
+ var qwenFailedResponseHandler = (0, import_provider_utils.createJsonErrorResponseHandler)({
58
+ errorSchema: qwenErrorDataSchema,
59
+ errorToMessage: (data) => data.message
60
+ });
61
+
62
+ // src/get-response-metadata.ts
63
+ function getResponseMetadata({
64
+ id,
65
+ model,
66
+ created
67
+ }) {
68
+ return {
69
+ id: id != null ? id : void 0,
70
+ modelId: model != null ? model : void 0,
71
+ timestamp: created != null ? new Date(created * 1e3) : void 0
72
+ };
73
+ }
74
+
75
+ // src/map-qwen-finish-reason.ts
76
+ function mapQwenFinishReason(finishReason) {
77
+ switch (finishReason) {
78
+ case "stop":
79
+ return "stop";
80
+ case "length":
81
+ return "length";
82
+ case "content_filter":
83
+ return "content-filter";
84
+ case "function_call":
85
+ case "tool_calls":
86
+ return "tool-calls";
87
+ default:
88
+ return "other";
89
+ }
90
+ }
91
+
92
+ // src/chat/convert-qwen-chat-usage.ts
93
+ function convertQwenChatUsage(usage) {
94
+ var _a, _b, _c, _d;
95
+ if (!usage) {
96
+ return {
97
+ inputTokens: {
98
+ total: void 0,
99
+ noCache: void 0,
100
+ cacheRead: void 0,
101
+ cacheWrite: void 0
102
+ },
103
+ outputTokens: {
104
+ total: void 0,
105
+ text: void 0,
106
+ reasoning: void 0
107
+ },
108
+ raw: void 0
109
+ };
110
+ }
111
+ const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;
112
+ const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
113
+ const cachedTokens = (_d = (_c = usage.prompt_tokens_details) == null ? void 0 : _c.cached_tokens) != null ? _d : 0;
114
+ return {
115
+ inputTokens: {
116
+ total: promptTokens,
117
+ noCache: promptTokens - cachedTokens,
118
+ cacheRead: cachedTokens,
119
+ cacheWrite: void 0
120
+ },
121
+ outputTokens: {
122
+ total: completionTokens,
123
+ text: void 0,
124
+ reasoning: void 0
125
+ },
126
+ raw: usage
127
+ };
128
+ }
129
+
130
+ // src/chat/convert-to-qwen-chat-messages.ts
131
+ var import_provider = require("@ai-sdk/provider");
132
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
133
+ function contentToAssistantMessage(content) {
134
+ var _a;
135
+ const message = {
136
+ role: "assistant",
137
+ content: ""
138
+ };
139
+ for (const part of content) {
140
+ switch (part.type) {
141
+ case "text": {
142
+ message.content += part.text;
143
+ break;
144
+ }
145
+ case "tool-call": {
146
+ (_a = message.tool_calls) != null ? _a : message.tool_calls = [];
147
+ message.tool_calls.push({
148
+ id: part.toolCallId,
149
+ type: "function",
150
+ function: {
151
+ name: part.toolName,
152
+ arguments: JSON.stringify(part.input)
153
+ },
154
+ index: message.tool_calls.length
155
+ });
156
+ break;
157
+ }
158
+ }
159
+ }
160
+ return message;
161
+ }
162
+ function contentToSystemMessage(content) {
163
+ return { role: "system", content };
164
+ }
165
+ function contentToToolMessage(content) {
166
+ var _a;
167
+ const messages = [];
168
+ for (const toolResponse of content) {
169
+ if (toolResponse.type === "tool-approval-response") {
170
+ continue;
171
+ }
172
+ const output = toolResponse.output;
173
+ let contentValue;
174
+ switch (output.type) {
175
+ case "text":
176
+ case "error-text":
177
+ contentValue = output.value;
178
+ break;
179
+ case "execution-denied":
180
+ contentValue = (_a = output.reason) != null ? _a : "Tool execution denied.";
181
+ break;
182
+ case "content":
183
+ case "json":
184
+ case "error-json":
185
+ contentValue = JSON.stringify(output.value);
186
+ break;
187
+ }
188
+ messages.push({
189
+ role: "tool",
190
+ tool_call_id: toolResponse.toolCallId,
191
+ content: contentValue
192
+ });
193
+ }
194
+ return messages;
195
+ }
196
+ function contentToUserMessage(content) {
197
+ if (content.length === 1 && content[0].type === "text") {
198
+ return {
199
+ role: "user",
200
+ content: content[0].text
201
+ };
202
+ }
203
+ const contents = [];
204
+ for (const part of content) {
205
+ if (part.type === "text") {
206
+ contents.push({ type: "text", text: part.text });
207
+ } else if (part.mediaType.startsWith("image/")) {
208
+ const data = part.data instanceof URL ? part.data.toString() : (0, import_provider_utils2.convertToBase64)(part.data);
209
+ const url = data.startsWith("http") || data.startsWith("data:") ? data : `data:${part.mediaType};base64,${data}`;
210
+ contents.push({
211
+ type: "image_url",
212
+ image_url: { url }
213
+ });
214
+ } else if (part.mediaType.startsWith("audio/")) {
215
+ const data = part.data instanceof URL ? part.data.toString() : (0, import_provider_utils2.convertToBase64)(part.data);
216
+ const url = data.startsWith("http") || data.startsWith("data:") ? data : `data:${part.mediaType};base64,${data}`;
217
+ switch (part.mediaType) {
218
+ case "audio/wav": {
219
+ contents.push({
220
+ type: "input_audio",
221
+ input_audio: {
222
+ data: url,
223
+ format: "wav"
224
+ }
225
+ });
226
+ break;
227
+ }
228
+ case "audio/mp3":
229
+ case "audio/mpeg": {
230
+ contents.push({
231
+ type: "input_audio",
232
+ input_audio: {
233
+ data: url,
234
+ format: "mp3"
235
+ }
236
+ });
237
+ break;
238
+ }
239
+ default: {
240
+ throw new import_provider.UnsupportedFunctionalityError({
241
+ functionality: `audio content parts with media type ${part.mediaType}`
242
+ });
243
+ }
244
+ }
245
+ } else {
246
+ throw new import_provider.UnsupportedFunctionalityError({
247
+ functionality: `file part media type ${part.mediaType}`
248
+ });
249
+ }
250
+ }
251
+ return {
252
+ role: "user",
253
+ content: contents
254
+ };
255
+ }
256
+ function convertToQwenChatMessages(options) {
257
+ const messages = [];
258
+ const warnings = [];
259
+ for (const { role, content } of options.prompt) {
260
+ switch (role) {
261
+ case "system": {
262
+ messages.push(contentToSystemMessage(content));
263
+ break;
264
+ }
265
+ case "user": {
266
+ messages.push(contentToUserMessage(content));
267
+ break;
268
+ }
269
+ case "assistant": {
270
+ messages.push(contentToAssistantMessage(content));
271
+ break;
272
+ }
273
+ case "tool": {
274
+ messages.push(...contentToToolMessage(content));
275
+ break;
276
+ }
277
+ default: {
278
+ const _exhaustiveCheck = role;
279
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
280
+ }
281
+ }
282
+ }
283
+ return { messages, warnings };
284
+ }
285
+
286
+ // src/chat/qwen-chat-api.ts
287
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
288
+ var import_zod2 = __toESM(require("zod"));
289
+ var qwenChatUsageSchema = import_zod2.default.object({
290
+ prompt_tokens: import_zod2.default.number().nullish(),
291
+ completion_tokens: import_zod2.default.number().nullish(),
292
+ total_tokens: import_zod2.default.number().nullish(),
293
+ prompt_tokens_details: import_zod2.default.object({
294
+ cached_tokens: import_zod2.default.number().nullish()
295
+ }).nullish()
296
+ }).nullish();
297
+ var qwenChatResponseSchema = (0, import_provider_utils3.lazySchema)(
298
+ () => (0, import_provider_utils3.zodSchema)(
299
+ import_zod2.default.object({
300
+ id: import_zod2.default.string().nullish(),
301
+ created: import_zod2.default.number().nullish(),
302
+ model: import_zod2.default.string().nullish(),
303
+ choices: import_zod2.default.array(
304
+ import_zod2.default.object({
305
+ finish_reason: import_zod2.default.string().nullish(),
306
+ index: import_zod2.default.number(),
307
+ message: import_zod2.default.object({
308
+ role: import_zod2.default.literal("assistant").nullish(),
309
+ content: import_zod2.default.string().nullish(),
310
+ reasoning_content: import_zod2.default.string().nullish(),
311
+ tool_calls: import_zod2.default.array(
312
+ import_zod2.default.object({
313
+ id: import_zod2.default.string().nullish(),
314
+ type: import_zod2.default.literal("function"),
315
+ function: import_zod2.default.object({
316
+ name: import_zod2.default.string(),
317
+ arguments: import_zod2.default.string()
318
+ })
319
+ })
320
+ )
321
+ })
322
+ })
323
+ ),
324
+ usage: qwenChatUsageSchema
325
+ })
326
+ )
327
+ );
328
+ var qwenChatChunkSchema = (0, import_provider_utils3.lazySchema)(
329
+ () => (0, import_provider_utils3.zodSchema)(
330
+ import_zod2.default.union([
331
+ import_zod2.default.object({
332
+ id: import_zod2.default.string().nullish(),
333
+ created: import_zod2.default.number().nullish(),
334
+ model: import_zod2.default.string().nullish(),
335
+ choices: import_zod2.default.array(
336
+ import_zod2.default.object({
337
+ delta: import_zod2.default.object({
338
+ role: import_zod2.default.enum(["assistant"]).nullish(),
339
+ content: import_zod2.default.string().nullish(),
340
+ reasoning_content: import_zod2.default.string().nullish(),
341
+ tool_calls: import_zod2.default.array(
342
+ import_zod2.default.object({
343
+ index: import_zod2.default.number(),
344
+ id: import_zod2.default.string().nullish(),
345
+ type: import_zod2.default.literal("function").nullish(),
346
+ function: import_zod2.default.object({
347
+ name: import_zod2.default.string().nullish(),
348
+ arguments: import_zod2.default.string().nullish()
349
+ })
350
+ })
351
+ ).nullish()
352
+ }),
353
+ finish_reason: import_zod2.default.string().nullish(),
354
+ index: import_zod2.default.number()
355
+ })
356
+ ),
357
+ usage: qwenChatUsageSchema
358
+ }),
359
+ qwenErrorDataSchema
360
+ ])
361
+ )
362
+ );
363
+
364
+ // src/chat/qwen-chat-prepare-tools.ts
365
+ var import_provider2 = require("@ai-sdk/provider");
366
+ function prepareChatTools({
367
+ tools,
368
+ toolChoice
369
+ }) {
370
+ var _a;
371
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
372
+ const toolWarnings = [];
373
+ if (tools == null) {
374
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
375
+ }
376
+ const chatTools = [];
377
+ for (const tool of tools) {
378
+ if (tool.type === "function") {
379
+ chatTools.push({
380
+ type: "function",
381
+ function: {
382
+ name: tool.name,
383
+ description: (_a = tool.description) != null ? _a : "",
384
+ parameters: tool.inputSchema,
385
+ ...tool.strict != null ? { strict: tool.strict } : {}
386
+ }
387
+ });
388
+ } else {
389
+ toolWarnings.push({
390
+ type: "unsupported",
391
+ feature: `tool type: ${tool.type}`
392
+ });
393
+ }
394
+ }
395
+ if (toolChoice == null) {
396
+ return { tools: chatTools, toolChoice: void 0, toolWarnings };
397
+ }
398
+ const type = toolChoice.type;
399
+ switch (type) {
400
+ case "auto":
401
+ case "none":
402
+ case "required":
403
+ return { tools: chatTools, toolChoice: type, toolWarnings };
404
+ case "tool":
405
+ return {
406
+ tools: chatTools,
407
+ toolChoice: {
408
+ type: "function",
409
+ function: {
410
+ name: toolChoice.toolName
411
+ }
412
+ },
413
+ toolWarnings
414
+ };
415
+ default: {
416
+ const _exhaustiveCheck = type;
417
+ throw new import_provider2.UnsupportedFunctionalityError({
418
+ functionality: `tool choice type: ${_exhaustiveCheck}`
419
+ });
420
+ }
421
+ }
422
+ }
423
+
424
+ // src/chat/qwen-chat-language-model.ts
425
+ var QwenChatLanguageModel = class {
426
+ constructor(modelId, config) {
427
+ this.specificationVersion = "v3";
428
+ this.supportedUrls = {
429
+ "image/*": [/^https?:\/\/.*$/]
430
+ };
431
+ this.modelId = modelId;
432
+ this.config = config;
433
+ }
434
+ get provider() {
435
+ return this.config.provider;
436
+ }
437
+ async getArgs(options) {
438
+ var _a, _b;
439
+ const { messages, warnings } = convertToQwenChatMessages(options);
440
+ const args = {
441
+ model: this.modelId,
442
+ messages,
443
+ max_tokens: options.maxOutputTokens,
444
+ temperature: options.temperature,
445
+ stop: options.stopSequences,
446
+ top_p: options.topP,
447
+ top_k: options.topK,
448
+ presence_penalty: options.presencePenalty,
449
+ frequency_penalty: options.frequencyPenalty,
450
+ seed: options.seed
451
+ };
452
+ if (((_a = options.responseFormat) == null ? void 0 : _a.type) === "json") {
453
+ if (options.responseFormat.schema != null) {
454
+ args.response_format = {
455
+ type: "json_schema",
456
+ json_schema: {
457
+ schema: options.responseFormat.schema,
458
+ name: (_b = options.responseFormat.name) != null ? _b : "response",
459
+ description: options.responseFormat.description
460
+ }
461
+ };
462
+ } else {
463
+ args.response_format = { type: "json_object" };
464
+ }
465
+ }
466
+ const { tools, toolChoice, toolWarnings } = prepareChatTools({
467
+ tools: options.tools,
468
+ toolChoice: options.toolChoice
469
+ });
470
+ args.tools = tools;
471
+ args.tool_choice = toolChoice;
472
+ warnings.push(...toolWarnings);
473
+ return { warnings, args };
474
+ }
475
+ async doGenerate(options) {
476
+ var _a, _b, _c;
477
+ const { warnings, args: body } = await this.getArgs(options);
478
+ const {
479
+ responseHeaders,
480
+ value: response,
481
+ rawValue: rawResponse
482
+ } = await (0, import_provider_utils4.postJsonToApi)({
483
+ url: this.config.url({
484
+ path: "/chat/completions",
485
+ modelId: this.modelId
486
+ }),
487
+ headers: (0, import_provider_utils4.combineHeaders)(this.config.headers(), options.headers),
488
+ body,
489
+ failedResponseHandler: qwenFailedResponseHandler,
490
+ successfulResponseHandler: (0, import_provider_utils4.createJsonResponseHandler)(qwenChatResponseSchema),
491
+ abortSignal: options.abortSignal,
492
+ fetch: this.config.fetch
493
+ });
494
+ const choice = response.choices[0];
495
+ const content = [];
496
+ const reasoning = choice.message.reasoning_content;
497
+ if (reasoning != null && reasoning.length > 0) {
498
+ content.push({
499
+ type: "reasoning",
500
+ text: reasoning
501
+ });
502
+ }
503
+ const text = choice.message.content;
504
+ if (text != null && text.length > 0) {
505
+ content.push({ type: "text", text });
506
+ }
507
+ for (const toolCall of (_a = choice.message.tool_calls) != null ? _a : []) {
508
+ content.push({
509
+ type: "tool-call",
510
+ toolCallId: (_b = toolCall.id) != null ? _b : (0, import_provider_utils4.generateId)(),
511
+ toolName: toolCall.function.name,
512
+ input: toolCall.function.arguments
513
+ });
514
+ }
515
+ return {
516
+ content,
517
+ finishReason: {
518
+ unified: mapQwenFinishReason(choice.finish_reason),
519
+ raw: (_c = choice.finish_reason) != null ? _c : void 0
520
+ },
521
+ usage: convertQwenChatUsage(response.usage),
522
+ request: { body },
523
+ response: {
524
+ ...getResponseMetadata(response),
525
+ headers: responseHeaders,
526
+ body: rawResponse
527
+ },
528
+ warnings,
529
+ providerMetadata: {
530
+ qwen: {}
531
+ }
532
+ };
533
+ }
534
+ async doStream(options) {
535
+ const { warnings, args } = await this.getArgs(options);
536
+ const body = {
537
+ ...args,
538
+ stream: true,
539
+ stream_options: {
540
+ include_usage: true
541
+ }
542
+ };
543
+ const { responseHeaders, value: response } = await (0, import_provider_utils4.postJsonToApi)({
544
+ url: this.config.url({
545
+ path: "/chat/completions",
546
+ modelId: this.modelId
547
+ }),
548
+ headers: (0, import_provider_utils4.combineHeaders)(this.config.headers(), options.headers),
549
+ body,
550
+ failedResponseHandler: qwenFailedResponseHandler,
551
+ successfulResponseHandler: (0, import_provider_utils4.createEventSourceResponseHandler)(qwenChatChunkSchema),
552
+ abortSignal: options.abortSignal,
553
+ fetch: this.config.fetch
554
+ });
555
+ const toolCalls = [];
556
+ let finishReason = {
557
+ unified: "other",
558
+ raw: void 0
559
+ };
560
+ let usage;
561
+ let isFirstChunk = true;
562
+ let isActiveReasoning = false;
563
+ let isActiveText = false;
564
+ let textId;
565
+ let reasoningId;
566
+ return {
567
+ stream: response.pipeThrough(
568
+ new TransformStream({
569
+ start(controller) {
570
+ controller.enqueue({ type: "stream-start", warnings });
571
+ },
572
+ transform(chunk, controller) {
573
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
574
+ if (options.includeRawChunks) {
575
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
576
+ }
577
+ if (!chunk.success) {
578
+ finishReason = { unified: "error", raw: void 0 };
579
+ controller.enqueue({ type: "error", error: chunk.error });
580
+ return;
581
+ }
582
+ const value = chunk.value;
583
+ if ("object" in value) {
584
+ finishReason = { unified: "error", raw: void 0 };
585
+ controller.enqueue({
586
+ type: "error",
587
+ error: value.message
588
+ });
589
+ return;
590
+ }
591
+ if (isFirstChunk) {
592
+ isFirstChunk = false;
593
+ controller.enqueue({
594
+ type: "response-metadata",
595
+ ...getResponseMetadata(value)
596
+ });
597
+ }
598
+ if (value.usage != null) {
599
+ usage = value.usage;
600
+ }
601
+ const choice = value.choices[0];
602
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
603
+ finishReason = {
604
+ unified: mapQwenFinishReason(choice.finish_reason),
605
+ raw: choice.finish_reason
606
+ };
607
+ }
608
+ if ((choice == null ? void 0 : choice.delta) == null) {
609
+ return;
610
+ }
611
+ const delta = choice.delta;
612
+ const reasoningContent = delta.reasoning_content;
613
+ if (reasoningContent) {
614
+ if (!isActiveReasoning) {
615
+ reasoningId = (0, import_provider_utils4.generateId)();
616
+ controller.enqueue({
617
+ type: "reasoning-start",
618
+ id: reasoningId
619
+ });
620
+ isActiveReasoning = true;
621
+ }
622
+ controller.enqueue({
623
+ type: "reasoning-delta",
624
+ id: reasoningId,
625
+ delta: reasoningContent
626
+ });
627
+ }
628
+ if (delta.content) {
629
+ if (!isActiveText) {
630
+ textId = (0, import_provider_utils4.generateId)();
631
+ controller.enqueue({ type: "text-start", id: textId });
632
+ isActiveText = true;
633
+ }
634
+ if (isActiveReasoning) {
635
+ controller.enqueue({
636
+ type: "reasoning-end",
637
+ id: reasoningId
638
+ });
639
+ isActiveReasoning = false;
640
+ }
641
+ controller.enqueue({
642
+ type: "text-delta",
643
+ id: textId,
644
+ delta: delta.content
645
+ });
646
+ }
647
+ if (delta.tool_calls != null) {
648
+ if (isActiveReasoning) {
649
+ controller.enqueue({
650
+ type: "reasoning-end",
651
+ id: reasoningId
652
+ });
653
+ isActiveReasoning = false;
654
+ }
655
+ for (const toolCallDelta of delta.tool_calls) {
656
+ const index = toolCallDelta.index;
657
+ if (toolCalls[index] == null) {
658
+ if (toolCallDelta.id == null) {
659
+ throw new import_provider3.InvalidResponseDataError({
660
+ data: toolCallDelta,
661
+ message: `Expected 'id' to be a string.`
662
+ });
663
+ }
664
+ if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
665
+ throw new import_provider3.InvalidResponseDataError({
666
+ data: toolCallDelta,
667
+ message: `Expected 'function.name' to be a string.`
668
+ });
669
+ }
670
+ controller.enqueue({
671
+ type: "tool-input-start",
672
+ id: toolCallDelta.id,
673
+ toolName: toolCallDelta.function.name
674
+ });
675
+ toolCalls[index] = {
676
+ id: toolCallDelta.id,
677
+ type: "function",
678
+ function: {
679
+ name: toolCallDelta.function.name,
680
+ arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
681
+ },
682
+ hasFinished: false
683
+ };
684
+ const toolCall2 = toolCalls[index];
685
+ if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null) {
686
+ if (toolCall2.function.arguments.length > 0) {
687
+ controller.enqueue({
688
+ type: "tool-input-delta",
689
+ id: toolCall2.id,
690
+ delta: toolCall2.function.arguments
691
+ });
692
+ }
693
+ if ((0, import_provider_utils4.isParsableJson)(toolCall2.function.arguments)) {
694
+ controller.enqueue({
695
+ type: "tool-input-end",
696
+ id: toolCall2.id
697
+ });
698
+ controller.enqueue({
699
+ type: "tool-call",
700
+ toolCallId: (_e = toolCall2.id) != null ? _e : (0, import_provider_utils4.generateId)(),
701
+ toolName: toolCall2.function.name,
702
+ input: toolCall2.function.arguments
703
+ });
704
+ toolCall2.hasFinished = true;
705
+ }
706
+ }
707
+ continue;
708
+ }
709
+ const toolCall = toolCalls[index];
710
+ if (toolCall.hasFinished) {
711
+ continue;
712
+ }
713
+ if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) {
714
+ toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : "";
715
+ }
716
+ controller.enqueue({
717
+ type: "tool-input-delta",
718
+ id: toolCall.id,
719
+ delta: (_i = toolCallDelta.function.arguments) != null ? _i : ""
720
+ });
721
+ if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && (0, import_provider_utils4.isParsableJson)(toolCall.function.arguments)) {
722
+ controller.enqueue({
723
+ type: "tool-input-end",
724
+ id: toolCall.id
725
+ });
726
+ controller.enqueue({
727
+ type: "tool-call",
728
+ toolCallId: (_l = toolCall.id) != null ? _l : (0, import_provider_utils4.generateId)(),
729
+ toolName: toolCall.function.name,
730
+ input: toolCall.function.arguments
731
+ });
732
+ toolCall.hasFinished = true;
733
+ }
734
+ }
735
+ }
736
+ },
737
+ flush(controller) {
738
+ var _a;
739
+ if (isActiveReasoning) {
740
+ controller.enqueue({ type: "reasoning-end", id: reasoningId });
741
+ }
742
+ if (isActiveText) {
743
+ controller.enqueue({ type: "text-end", id: textId });
744
+ }
745
+ for (const toolCall of toolCalls.filter((toolCall2) => !toolCall2.hasFinished)) {
746
+ controller.enqueue({
747
+ type: "tool-input-end",
748
+ id: toolCall.id
749
+ });
750
+ controller.enqueue({
751
+ type: "tool-call",
752
+ toolCallId: (_a = toolCall.id) != null ? _a : (0, import_provider_utils4.generateId)(),
753
+ toolName: toolCall.function.name,
754
+ input: toolCall.function.arguments
755
+ });
756
+ }
757
+ controller.enqueue({
758
+ type: "finish",
759
+ finishReason,
760
+ usage: convertQwenChatUsage(usage),
761
+ providerMetadata: {
762
+ qwen: {}
763
+ }
764
+ });
765
+ }
766
+ })
767
+ ),
768
+ request: { body },
769
+ response: { headers: responseHeaders }
770
+ };
771
+ }
772
+ };
773
+
774
+ // src/completion/qwen-completion-language-model.ts
775
+ var import_provider_utils6 = require("@ai-sdk/provider-utils");
776
+
777
+ // src/completion/convert-qwen-completion-usage.ts
778
+ function convertQwenCompletionUsage(usage) {
779
+ var _a, _b, _c, _d;
780
+ if (usage == null) {
781
+ return {
782
+ inputTokens: {
783
+ total: void 0,
784
+ noCache: void 0,
785
+ cacheRead: void 0,
786
+ cacheWrite: void 0
787
+ },
788
+ outputTokens: {
789
+ total: void 0,
790
+ text: void 0,
791
+ reasoning: void 0
792
+ },
793
+ raw: void 0
794
+ };
795
+ }
796
+ const promptTokens = (_a = usage.prompt_tokens) != null ? _a : 0;
797
+ const completionTokens = (_b = usage.completion_tokens) != null ? _b : 0;
798
+ return {
799
+ inputTokens: {
800
+ total: (_c = usage.prompt_tokens) != null ? _c : void 0,
801
+ noCache: promptTokens,
802
+ cacheRead: void 0,
803
+ cacheWrite: void 0
804
+ },
805
+ outputTokens: {
806
+ total: (_d = usage.completion_tokens) != null ? _d : void 0,
807
+ text: completionTokens,
808
+ reasoning: void 0
809
+ },
810
+ raw: usage
811
+ };
812
+ }
813
+
814
+ // src/completion/convert-to-qwen-completion-prompt.ts
815
+ var import_provider4 = require("@ai-sdk/provider");
816
+ function convertToQwenCompletionPrompt({
817
+ prompt,
818
+ user = "user",
819
+ assistant = "assistant"
820
+ }) {
821
+ let text = "";
822
+ if (prompt[0].role === "system") {
823
+ text += `${prompt[0].content}
824
+
825
+ `;
826
+ prompt = prompt.slice(1);
827
+ }
828
+ for (const { role, content } of prompt) {
829
+ switch (role) {
830
+ case "system": {
831
+ throw new import_provider4.InvalidPromptError({
832
+ message: `Unexpected system message in prompt: ${content}`,
833
+ prompt
834
+ });
835
+ }
836
+ case "user": {
837
+ const userMessage = content.filter((part) => part.type === "text").map((part) => part.text).filter(Boolean).join("");
838
+ text += `${user}:
839
+ ${userMessage}
840
+
841
+ `;
842
+ break;
843
+ }
844
+ case "assistant": {
845
+ const assistantMessage = content.map((part) => {
846
+ switch (part.type) {
847
+ case "text": {
848
+ return part.text;
849
+ }
850
+ case "tool-call": {
851
+ throw new import_provider4.UnsupportedFunctionalityError({
852
+ functionality: "tool-call messages"
853
+ });
854
+ }
855
+ default: {
856
+ return "";
857
+ }
858
+ }
859
+ }).join("");
860
+ text += `${assistant}:
861
+ ${assistantMessage}
862
+
863
+ `;
864
+ break;
865
+ }
866
+ case "tool": {
867
+ throw new import_provider4.UnsupportedFunctionalityError({
868
+ functionality: "tool messages"
869
+ });
870
+ }
871
+ default: {
872
+ const _exhaustiveCheck = role;
873
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
874
+ }
875
+ }
876
+ }
877
+ text += `${assistant}:
878
+ `;
879
+ return {
880
+ prompt: text,
881
+ stopSequences: [`
882
+ ${user}:`]
883
+ };
884
+ }
885
+
886
+ // src/completion/qwen-completion-api.ts
887
+ var import_provider_utils5 = require("@ai-sdk/provider-utils");
888
+ var import_zod3 = require("zod");
889
+ var qwenCompletionResponseSchema = (0, import_provider_utils5.lazySchema)(
890
+ () => (0, import_provider_utils5.zodSchema)(
891
+ import_zod3.z.object({
892
+ id: import_zod3.z.string().nullish(),
893
+ created: import_zod3.z.number().nullish(),
894
+ model: import_zod3.z.string().nullish(),
895
+ choices: import_zod3.z.array(
896
+ import_zod3.z.object({
897
+ text: import_zod3.z.string(),
898
+ finish_reason: import_zod3.z.string().nullish()
899
+ })
900
+ ),
901
+ usage: import_zod3.z.object({
902
+ prompt_tokens: import_zod3.z.number(),
903
+ completion_tokens: import_zod3.z.number(),
904
+ total_tokens: import_zod3.z.number()
905
+ }).nullish()
906
+ })
907
+ )
908
+ );
909
+ var qwenCompletionChunkSchema = (0, import_provider_utils5.lazySchema)(
910
+ () => (0, import_provider_utils5.zodSchema)(
911
+ import_zod3.z.union([
912
+ import_zod3.z.object({
913
+ id: import_zod3.z.string().nullish(),
914
+ created: import_zod3.z.number().nullish(),
915
+ model: import_zod3.z.string().nullish(),
916
+ choices: import_zod3.z.array(
917
+ import_zod3.z.object({
918
+ text: import_zod3.z.string(),
919
+ finish_reason: import_zod3.z.string().nullish(),
920
+ index: import_zod3.z.number()
921
+ })
922
+ ),
923
+ usage: import_zod3.z.object({
924
+ prompt_tokens: import_zod3.z.number(),
925
+ completion_tokens: import_zod3.z.number(),
926
+ total_tokens: import_zod3.z.number()
927
+ }).nullish()
928
+ }),
929
+ qwenErrorDataSchema
930
+ ])
931
+ )
932
+ );
933
+
934
+ // src/completion/qwen-completion-language-model.ts
935
+ var QwenCompletionLanguageModel = class {
936
+ constructor(modelId, config) {
937
+ this.specificationVersion = "v3";
938
+ this.supportedUrls = {
939
+ // No URLs are supported for completion models.
940
+ };
941
+ this.modelId = modelId;
942
+ this.config = config;
943
+ }
944
+ get provider() {
945
+ return this.config.provider;
946
+ }
947
+ async getArgs({
948
+ prompt,
949
+ maxOutputTokens,
950
+ temperature,
951
+ topP,
952
+ topK,
953
+ presencePenalty,
954
+ stopSequences: userStopSequences,
955
+ responseFormat,
956
+ tools,
957
+ toolChoice,
958
+ seed
959
+ }) {
960
+ const warnings = [];
961
+ if (topK != null) {
962
+ warnings.push({ type: "unsupported", feature: "topK" });
963
+ }
964
+ if (tools == null ? void 0 : tools.length) {
965
+ warnings.push({ type: "unsupported", feature: "tools" });
966
+ }
967
+ if (toolChoice != null) {
968
+ warnings.push({ type: "unsupported", feature: "toolChoice" });
969
+ }
970
+ if (responseFormat != null && responseFormat.type !== "text") {
971
+ warnings.push({
972
+ type: "unsupported",
973
+ feature: "responseFormat",
974
+ details: "JSON response format is not supported."
975
+ });
976
+ }
977
+ const { prompt: completionPrompt, stopSequences } = convertToQwenCompletionPrompt({ prompt });
978
+ const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []];
979
+ const args = {
980
+ // model id:
981
+ model: this.modelId,
982
+ // standardized settings:
983
+ max_tokens: maxOutputTokens,
984
+ temperature,
985
+ top_p: topP,
986
+ presence_penalty: presencePenalty,
987
+ seed,
988
+ // prompt:
989
+ prompt: completionPrompt,
990
+ // stop sequences:
991
+ stop: stop.length > 0 ? stop : void 0
992
+ };
993
+ return { args, warnings };
994
+ }
995
+ async doGenerate(options) {
996
+ var _a;
997
+ const { args, warnings } = await this.getArgs(options);
998
+ const {
999
+ responseHeaders,
1000
+ value: response,
1001
+ rawValue: rawResponse
1002
+ } = await (0, import_provider_utils6.postJsonToApi)({
1003
+ url: this.config.url({
1004
+ path: "/completions",
1005
+ modelId: this.modelId
1006
+ }),
1007
+ headers: (0, import_provider_utils6.combineHeaders)(this.config.headers(), options.headers),
1008
+ body: args,
1009
+ failedResponseHandler: qwenFailedResponseHandler,
1010
+ successfulResponseHandler: (0, import_provider_utils6.createJsonResponseHandler)(qwenCompletionResponseSchema),
1011
+ abortSignal: options.abortSignal,
1012
+ fetch: this.config.fetch
1013
+ });
1014
+ const choice = response.choices[0];
1015
+ const providerMetadata = { qwen: {} };
1016
+ return {
1017
+ content: [{ type: "text", text: choice.text }],
1018
+ usage: convertQwenCompletionUsage(response.usage),
1019
+ finishReason: {
1020
+ unified: mapQwenFinishReason(choice.finish_reason),
1021
+ raw: (_a = choice.finish_reason) != null ? _a : void 0
1022
+ },
1023
+ request: { body: args },
1024
+ response: {
1025
+ ...getResponseMetadata(response),
1026
+ headers: responseHeaders,
1027
+ body: rawResponse
1028
+ },
1029
+ providerMetadata,
1030
+ warnings
1031
+ };
1032
+ }
1033
+ async doStream(options) {
1034
+ const { args, warnings } = await this.getArgs(options);
1035
+ const body = {
1036
+ ...args,
1037
+ stream: true,
1038
+ stream_options: {
1039
+ include_usage: true
1040
+ }
1041
+ };
1042
+ const { responseHeaders, value: response } = await (0, import_provider_utils6.postJsonToApi)({
1043
+ url: this.config.url({
1044
+ path: "/completions",
1045
+ modelId: this.modelId
1046
+ }),
1047
+ headers: (0, import_provider_utils6.combineHeaders)(this.config.headers(), options.headers),
1048
+ body,
1049
+ failedResponseHandler: qwenFailedResponseHandler,
1050
+ successfulResponseHandler: (0, import_provider_utils6.createEventSourceResponseHandler)(qwenCompletionChunkSchema),
1051
+ abortSignal: options.abortSignal,
1052
+ fetch: this.config.fetch
1053
+ });
1054
+ let finishReason = {
1055
+ unified: "other",
1056
+ raw: void 0
1057
+ };
1058
+ const providerMetadata = { qwen: {} };
1059
+ let usage;
1060
+ let isFirstChunk = true;
1061
+ return {
1062
+ stream: response.pipeThrough(
1063
+ new TransformStream({
1064
+ start(controller) {
1065
+ controller.enqueue({ type: "stream-start", warnings });
1066
+ },
1067
+ transform(chunk, controller) {
1068
+ if (options.includeRawChunks) {
1069
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1070
+ }
1071
+ if (!chunk.success) {
1072
+ finishReason = { unified: "error", raw: void 0 };
1073
+ controller.enqueue({ type: "error", error: chunk.error });
1074
+ return;
1075
+ }
1076
+ const value = chunk.value;
1077
+ if ("object" in value) {
1078
+ finishReason = { unified: "error", raw: void 0 };
1079
+ controller.enqueue({ type: "error", error: value.message });
1080
+ return;
1081
+ }
1082
+ if (isFirstChunk) {
1083
+ isFirstChunk = false;
1084
+ controller.enqueue({
1085
+ type: "response-metadata",
1086
+ ...getResponseMetadata(value)
1087
+ });
1088
+ controller.enqueue({ type: "text-start", id: "0" });
1089
+ }
1090
+ if (value.usage != null) {
1091
+ usage = value.usage;
1092
+ }
1093
+ const choice = value.choices[0];
1094
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
1095
+ finishReason = {
1096
+ unified: mapQwenFinishReason(choice.finish_reason),
1097
+ raw: choice.finish_reason
1098
+ };
1099
+ }
1100
+ if ((choice == null ? void 0 : choice.text) != null && choice.text.length > 0) {
1101
+ controller.enqueue({
1102
+ type: "text-delta",
1103
+ id: "0",
1104
+ delta: choice.text
1105
+ });
1106
+ }
1107
+ },
1108
+ flush(controller) {
1109
+ if (!isFirstChunk) {
1110
+ controller.enqueue({ type: "text-end", id: "0" });
1111
+ }
1112
+ controller.enqueue({
1113
+ type: "finish",
1114
+ finishReason,
1115
+ providerMetadata,
1116
+ usage: convertQwenCompletionUsage(usage)
1117
+ });
1118
+ }
1119
+ })
1120
+ ),
1121
+ request: { body },
1122
+ response: { headers: responseHeaders }
1123
+ };
1124
+ }
1125
+ };
1126
+
1127
+ // src/embedding/qwen-embedding-model.ts
1128
+ var import_provider5 = require("@ai-sdk/provider");
1129
+ var import_provider_utils9 = require("@ai-sdk/provider-utils");
1130
+
1131
+ // src/embedding/qwen-embedding-api.ts
1132
+ var import_provider_utils7 = require("@ai-sdk/provider-utils");
1133
+ var import_zod4 = require("zod");
1134
+ var qwenTextEmbeddingResponseSchema = (0, import_provider_utils7.lazySchema)(
1135
+ () => (0, import_provider_utils7.zodSchema)(
1136
+ import_zod4.z.object({
1137
+ data: import_zod4.z.array(import_zod4.z.object({ embedding: import_zod4.z.array(import_zod4.z.number()) })),
1138
+ usage: import_zod4.z.object({ prompt_tokens: import_zod4.z.number() }).nullish()
1139
+ })
1140
+ )
1141
+ );
1142
+
1143
+ // src/embedding/qwen-embedding-options.ts
1144
+ var import_provider_utils8 = require("@ai-sdk/provider-utils");
1145
+ var import_zod5 = __toESM(require("zod"));
1146
+ var qwenEmbeddingProviderOptions = (0, import_provider_utils8.lazySchema)(
1147
+ () => (0, import_provider_utils8.zodSchema)(
1148
+ import_zod5.default.object({
1149
+ /**
1150
+ The number of dimensions the resulting output embeddings should have.
1151
+ Only supported in text-embedding-3 and later models.
1152
+ */
1153
+ dimensions: import_zod5.default.number().optional()
1154
+ })
1155
+ )
1156
+ );
1157
+
1158
+ // src/embedding/qwen-embedding-model.ts
1159
+ var QwenEmbeddingModel = class {
1160
+ constructor(modelId, config) {
1161
+ this.specificationVersion = "v3";
1162
+ this.maxEmbeddingsPerCall = 2048;
1163
+ this.supportsParallelCalls = true;
1164
+ this.modelId = modelId;
1165
+ this.config = config;
1166
+ }
1167
+ get provider() {
1168
+ return this.config.provider;
1169
+ }
1170
+ async doEmbed({
1171
+ values,
1172
+ headers,
1173
+ abortSignal,
1174
+ providerOptions
1175
+ }) {
1176
+ var _a;
1177
+ if (values.length > this.maxEmbeddingsPerCall) {
1178
+ throw new import_provider5.TooManyEmbeddingValuesForCallError({
1179
+ provider: this.provider,
1180
+ modelId: this.modelId,
1181
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
1182
+ values
1183
+ });
1184
+ }
1185
+ const qwenOptions = (_a = await (0, import_provider_utils9.parseProviderOptions)({
1186
+ provider: "qwen",
1187
+ providerOptions,
1188
+ schema: qwenEmbeddingProviderOptions
1189
+ })) != null ? _a : {};
1190
+ const {
1191
+ responseHeaders,
1192
+ value: response,
1193
+ rawValue
1194
+ } = await (0, import_provider_utils9.postJsonToApi)({
1195
+ url: this.config.url({
1196
+ path: "/embeddings",
1197
+ modelId: this.modelId
1198
+ }),
1199
+ headers: (0, import_provider_utils9.combineHeaders)(this.config.headers(), headers),
1200
+ body: {
1201
+ model: this.modelId,
1202
+ input: values,
1203
+ encoding_format: "float",
1204
+ dimensions: qwenOptions.dimensions
1205
+ },
1206
+ failedResponseHandler: qwenFailedResponseHandler,
1207
+ successfulResponseHandler: (0, import_provider_utils9.createJsonResponseHandler)(qwenTextEmbeddingResponseSchema),
1208
+ abortSignal,
1209
+ fetch: this.config.fetch
1210
+ });
1211
+ return {
1212
+ warnings: [],
1213
+ embeddings: response.data.map((item) => item.embedding),
1214
+ usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
1215
+ response: { headers: responseHeaders, body: rawValue }
1216
+ };
1217
+ }
1218
+ };
1219
+
1220
+ // src/qwen-provider.ts
1221
+ function createQwen(options) {
1222
+ var _a;
1223
+ const baseURL = (_a = (0, import_provider_utils10.withoutTrailingSlash)(options == null ? void 0 : options.baseURL)) != null ? _a : "https://dashscope.aliyuncs.com/compatible-mode/v1";
1224
+ const getHeaders = () => {
1225
+ const apiKey = (0, import_provider_utils10.loadApiKey)({
1226
+ apiKey: options == null ? void 0 : options.apiKey,
1227
+ environmentVariableName: "DASHSCOPE_API_KEY",
1228
+ description: "Qwen API key"
1229
+ });
1230
+ return (0, import_provider_utils10.withUserAgentSuffix)(
1231
+ {
1232
+ Authorization: `Bearer ${apiKey}`,
1233
+ ...options == null ? void 0 : options.headers
1234
+ },
1235
+ `ai-sdk/qwen/${import_provider_utils10.VERSION}`
1236
+ );
1237
+ };
1238
+ const createChatModel = (modelId) => {
1239
+ return new QwenChatLanguageModel(modelId, {
1240
+ provider: "qwen.chat",
1241
+ baseURL,
1242
+ headers: getHeaders,
1243
+ fetch: options == null ? void 0 : options.fetch,
1244
+ url: ({ path }) => `${baseURL}${path}`
1245
+ });
1246
+ };
1247
+ const createCompletionModel = (modelId) => {
1248
+ return new QwenCompletionLanguageModel(modelId, {
1249
+ provider: `qwen.completion`,
1250
+ url: ({ path }) => `${baseURL}${path}`,
1251
+ headers: getHeaders,
1252
+ fetch: options == null ? void 0 : options.fetch
1253
+ });
1254
+ };
1255
+ const createEmbeddingModel = (modelId) => {
1256
+ return new QwenEmbeddingModel(modelId, {
1257
+ provider: `qwen.embedding`,
1258
+ url: ({ path }) => `${baseURL}${path}`,
1259
+ headers: getHeaders,
1260
+ fetch: options == null ? void 0 : options.fetch
1261
+ });
1262
+ };
1263
+ const provider = (modelId) => {
1264
+ if (new.target) {
1265
+ throw new Error("The Qwen model function cannot be called with the new keyword.");
1266
+ }
1267
+ return createChatModel(modelId);
1268
+ };
1269
+ provider.specificationVersion = "v3";
1270
+ provider.languageModel = createChatModel;
1271
+ provider.chat = createChatModel;
1272
+ provider.completion = createCompletionModel;
1273
+ provider.embedding = createEmbeddingModel;
1274
+ provider.embeddingModel = createEmbeddingModel;
1275
+ provider.textEmbedding = createEmbeddingModel;
1276
+ provider.textEmbeddingModel = createEmbeddingModel;
1277
+ provider.imageModel = (modelId) => {
1278
+ throw new import_provider6.NoSuchModelError({ modelId, modelType: "imageModel" });
1279
+ };
1280
+ return provider;
1281
+ }
1282
+ var qwen = createQwen();
1283
+
1284
+ // src/version.ts
1285
+ var VERSION2 = true ? "0.0.1" : "0.0.0-test";
1286
+ // Annotate the CommonJS export names for ESM import in node:
1287
+ 0 && (module.exports = {
1288
+ VERSION,
1289
+ createQwen,
1290
+ qwen
1291
+ });
1292
+ //# sourceMappingURL=index.js.map