@ai-sdk/moonshotai 0.0.20 → 0.0.24

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 CHANGED
@@ -26,12 +26,15 @@ __export(index_exports, {
26
26
  module.exports = __toCommonJS(index_exports);
27
27
 
28
28
  // src/moonshotai-provider.ts
29
- var import_provider = require("@ai-sdk/provider");
30
- var import_provider_utils = require("@ai-sdk/provider-utils");
31
- var import_v4 = require("zod/v4");
29
+ var import_provider3 = require("@ai-sdk/provider");
30
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
31
+ var import_v43 = require("zod/v4");
32
32
 
33
33
  // src/moonshotai-chat-language-model.ts
34
34
  var import_openai_compatible = require("@ai-sdk/openai-compatible");
35
+ var import_provider2 = require("@ai-sdk/provider");
36
+ var import_provider_utils = require("@ai-sdk/provider-utils");
37
+ var import_v42 = require("zod/v4");
35
38
 
36
39
  // src/convert-moonshotai-chat-usage.ts
37
40
  function convertMoonshotAIChatUsage(usage) {
@@ -54,37 +57,767 @@ function convertMoonshotAIChatUsage(usage) {
54
57
  };
55
58
  }
56
59
 
60
+ // src/moonshotai-chat-metadata-extractor.ts
61
+ function isRecord(value) {
62
+ return value != null && typeof value === "object" && !Array.isArray(value);
63
+ }
64
+ function getFirstChoice(value) {
65
+ const choices = value.choices;
66
+ return Array.isArray(choices) && isRecord(choices[0]) ? choices[0] : void 0;
67
+ }
68
+ function getToolCallTypes(value) {
69
+ if (!Array.isArray(value)) {
70
+ return void 0;
71
+ }
72
+ return value.flatMap(
73
+ (toolCall) => isRecord(toolCall) && toolCall.type === "function" ? [toolCall.type] : []
74
+ );
75
+ }
76
+ function extractMetadata(value) {
77
+ if (!isRecord(value)) {
78
+ return {};
79
+ }
80
+ const choice = getFirstChoice(value);
81
+ const message = choice != null && isRecord(choice.message) ? choice.message : void 0;
82
+ const toolCallTypes = getToolCallTypes(message == null ? void 0 : message.tool_calls);
83
+ return {
84
+ ...value.object === "chat.completion" && {
85
+ responseObject: value.object
86
+ },
87
+ ...typeof (choice == null ? void 0 : choice.index) === "number" && {
88
+ choiceIndex: choice.index
89
+ },
90
+ ...(message == null ? void 0 : message.role) === "assistant" && {
91
+ messageRole: message.role
92
+ },
93
+ ...toolCallTypes != null && { toolCallTypes }
94
+ };
95
+ }
96
+ var moonshotAIChatMetadataExtractor = {
97
+ async extractMetadata({ parsedBody }) {
98
+ return { moonshotai: extractMetadata(parsedBody) };
99
+ },
100
+ createStreamExtractor() {
101
+ let responseObject;
102
+ let choiceIndex;
103
+ let messageRole;
104
+ const toolCallTypes = /* @__PURE__ */ new Map();
105
+ return {
106
+ processChunk(parsedChunk) {
107
+ if (!isRecord(parsedChunk)) {
108
+ return;
109
+ }
110
+ if (parsedChunk.object === "chat.completion.chunk") {
111
+ responseObject = parsedChunk.object;
112
+ }
113
+ const choice = getFirstChoice(parsedChunk);
114
+ if (typeof (choice == null ? void 0 : choice.index) === "number") {
115
+ choiceIndex = choice.index;
116
+ }
117
+ const delta = choice != null && isRecord(choice.delta) ? choice.delta : void 0;
118
+ if ((delta == null ? void 0 : delta.role) === "assistant") {
119
+ messageRole = delta.role;
120
+ }
121
+ if (Array.isArray(delta == null ? void 0 : delta.tool_calls)) {
122
+ for (const [fallbackIndex, toolCall] of delta.tool_calls.entries()) {
123
+ if (!isRecord(toolCall) || toolCall.type !== "function") {
124
+ continue;
125
+ }
126
+ const index = typeof toolCall.index === "number" ? toolCall.index : fallbackIndex;
127
+ toolCallTypes.set(index, toolCall.type);
128
+ }
129
+ }
130
+ },
131
+ buildMetadata() {
132
+ return {
133
+ moonshotai: {
134
+ ...responseObject != null && { responseObject },
135
+ ...choiceIndex != null && { choiceIndex },
136
+ ...messageRole != null && { messageRole },
137
+ ...toolCallTypes.size > 0 && {
138
+ toolCallTypes: [...toolCallTypes.entries()].sort(([left], [right]) => left - right).map(([, type]) => type)
139
+ }
140
+ }
141
+ };
142
+ }
143
+ };
144
+ }
145
+ };
146
+
147
+ // src/moonshotai-chat-options.ts
148
+ var import_v4 = require("zod/v4");
149
+ function getMoonshotAIModelFamily(modelId) {
150
+ if (modelId === "kimi-k2.5") return "kimi-k2.5";
151
+ if (modelId === "kimi-k2.6") return "kimi-k2.6";
152
+ if (modelId === "kimi-k2.7-code" || modelId === "kimi-k2.7-code-highspeed") {
153
+ return "kimi-k2.7";
154
+ }
155
+ if (modelId === "kimi-k3") return "kimi-k3";
156
+ if (modelId.startsWith("moonshot-v1-")) return "moonshot-v1";
157
+ return "unknown";
158
+ }
159
+ function isMoonshotAIKimiModel(modelId) {
160
+ return getMoonshotAIModelFamily(modelId).startsWith("kimi-");
161
+ }
162
+ var moonshotaiProviderOptions = import_v4.z.object({
163
+ /**
164
+ * Whether to use strict JSON schema validation for structured outputs.
165
+ *
166
+ * @default true
167
+ */
168
+ strictJsonSchema: import_v4.z.boolean().optional(),
169
+ /**
170
+ * Whether to return log probabilities for generated tokens.
171
+ */
172
+ logprobs: import_v4.z.boolean().optional(),
173
+ /**
174
+ * Number of most likely tokens to return at each token position.
175
+ *
176
+ * Setting this option automatically enables `logprobs`.
177
+ */
178
+ topLogprobs: import_v4.z.number().int().min(0).max(20).optional(),
179
+ /**
180
+ * Reasoning effort for Kimi K3. Supports `low`, `high`, and `max`;
181
+ * defaults to `max`.
182
+ */
183
+ reasoningEffort: import_v4.z.enum(["low", "high", "max"]).optional(),
184
+ /**
185
+ * Static predicted content that can accelerate responses when much of the
186
+ * output is known ahead of time.
187
+ */
188
+ prediction: import_v4.z.object({
189
+ type: import_v4.z.literal("content"),
190
+ content: import_v4.z.union([
191
+ import_v4.z.string(),
192
+ import_v4.z.array(import_v4.z.object({ type: import_v4.z.literal("text"), text: import_v4.z.string() }))
193
+ ])
194
+ }).optional(),
195
+ /**
196
+ * Thinking configuration for Kimi K2.x models. Kimi K2.5 and K2.6 support
197
+ * enabling or disabling thinking. Kimi K2.7 Code always has thinking
198
+ * enabled.
199
+ */
200
+ thinking: import_v4.z.object({
201
+ type: import_v4.z.enum(["enabled", "disabled"]).optional(),
202
+ /**
203
+ * @deprecated Moonshot Chat Completions does not support thinking
204
+ * budgets. Accepted for backwards compatibility, then omitted with a
205
+ * warning.
206
+ */
207
+ budgetTokens: import_v4.z.number().int().min(1024).optional()
208
+ }).optional(),
209
+ /**
210
+ * Controls preserved reasoning behavior in multi-turn conversations.
211
+ * `disabled` and `interleaved` are compatibility values that leave the
212
+ * request unchanged. `preserved` maps to `thinking.keep: 'all'` for Kimi
213
+ * K2.6. Kimi K2.7 and K3 preserve reasoning by default.
214
+ */
215
+ reasoningHistory: import_v4.z.enum(["disabled", "interleaved", "preserved"]).optional()
216
+ });
217
+ var moonshotaiMessageProviderOptions = import_v4.z.object({
218
+ /**
219
+ * The name of the participant represented by the message.
220
+ *
221
+ * Supported on system, user, and assistant messages.
222
+ */
223
+ name: import_v4.z.string().optional()
224
+ });
225
+ var moonshotaiAssistantMessageProviderOptions = moonshotaiMessageProviderOptions.extend({
226
+ /**
227
+ * Whether the assistant message content is a partial response that Moonshot
228
+ * should continue. Only supported on the final assistant message and cannot
229
+ * be combined with JSON object response format.
230
+ */
231
+ partial: import_v4.z.literal(true).optional()
232
+ });
233
+ var moonshotaiDynamicToolSchema = import_v4.z.object({
234
+ type: import_v4.z.literal("function"),
235
+ name: import_v4.z.string(),
236
+ description: import_v4.z.string().optional(),
237
+ inputSchema: import_v4.z.record(import_v4.z.string(), import_v4.z.unknown()),
238
+ strict: import_v4.z.boolean().optional()
239
+ });
240
+ var moonshotaiAllMessageProviderOptions = moonshotaiAssistantMessageProviderOptions.extend({
241
+ /** Function tools to load at this point in a Kimi K3 conversation. */
242
+ tools: import_v4.z.array(moonshotaiDynamicToolSchema).optional()
243
+ });
244
+
245
+ // src/normalize-json-schema-for-mfjs.ts
246
+ var import_provider = require("@ai-sdk/provider");
247
+ var SCHEMA_ARRAY_KEYS = ["allOf", "anyOf", "oneOf", "prefixItems"];
248
+ var SCHEMA_MAP_KEYS = [
249
+ "properties",
250
+ "patternProperties",
251
+ "$defs",
252
+ "dependentSchemas"
253
+ ];
254
+ var SCHEMA_SINGLE_KEYS = [
255
+ "additionalProperties",
256
+ "propertyNames",
257
+ "items",
258
+ "contains",
259
+ "not",
260
+ "if",
261
+ "then",
262
+ "else"
263
+ ];
264
+ function isRecord2(value) {
265
+ return value != null && typeof value === "object" && !Array.isArray(value);
266
+ }
267
+ function normalizeJsonSchemaForMFJS(schema) {
268
+ return normalizeDefinition(schema, true);
269
+ }
270
+ function normalizeDefinition(definition, isRoot) {
271
+ if (typeof definition === "boolean" || !isRecord2(definition)) {
272
+ if (isRoot) {
273
+ throw new import_provider.UnsupportedFunctionalityError({
274
+ functionality: 'tool parameters must be a JSON Schema object with type "object" for moonshotai (MFJS)'
275
+ });
276
+ }
277
+ return definition;
278
+ }
279
+ if (isRoot && definition.type !== "object") {
280
+ throw new import_provider.UnsupportedFunctionalityError({
281
+ functionality: 'tool parameters must be a JSON Schema object with type "object" for moonshotai (MFJS)'
282
+ });
283
+ }
284
+ const result = { ...definition };
285
+ if (Array.isArray(result.items)) {
286
+ const tuple = result.items;
287
+ result.prefixItems = [
288
+ ...Array.isArray(result.prefixItems) ? result.prefixItems : [],
289
+ ...tuple.map((item) => normalizeDefinition(item, false))
290
+ ];
291
+ delete result.items;
292
+ } else if (isRecord2(result.items)) {
293
+ result.items = normalizeDefinition(result.items, false);
294
+ }
295
+ if (typeof result.type === "string" && Array.isArray(result.anyOf)) {
296
+ const parentType = result.type;
297
+ delete result.type;
298
+ result.anyOf = result.anyOf.map(
299
+ (branch) => isRecord2(branch) && branch.type == null ? { type: parentType, ...branch } : branch
300
+ );
301
+ }
302
+ for (const key of SCHEMA_ARRAY_KEYS) {
303
+ const value = result[key];
304
+ if (Array.isArray(value)) {
305
+ result[key] = value.map((item) => normalizeDefinition(item, false));
306
+ }
307
+ }
308
+ for (const key of SCHEMA_MAP_KEYS) {
309
+ const value = result[key];
310
+ if (isRecord2(value)) {
311
+ result[key] = Object.fromEntries(
312
+ Object.entries(value).map(([key2, item]) => [
313
+ key2,
314
+ normalizeDefinition(item, false)
315
+ ])
316
+ );
317
+ }
318
+ }
319
+ for (const key of SCHEMA_SINGLE_KEYS) {
320
+ const value = result[key];
321
+ if (isRecord2(value) || typeof value === "boolean") {
322
+ result[key] = normalizeDefinition(value, false);
323
+ }
324
+ }
325
+ return result;
326
+ }
327
+
57
328
  // src/moonshotai-chat-language-model.ts
329
+ function transformMoonshotRequestBody(args) {
330
+ var _a, _b, _c;
331
+ const {
332
+ strictJsonSchema,
333
+ max_tokens: maxTokens,
334
+ logprobs,
335
+ topLogprobs,
336
+ ...transformedArgs
337
+ } = args;
338
+ const moonshotArgs = {
339
+ ...transformedArgs,
340
+ ...(logprobs === true || topLogprobs != null) && { logprobs: true },
341
+ ...topLogprobs != null && { top_logprobs: topLogprobs },
342
+ ...maxTokens != null ? { max_completion_tokens: maxTokens } : {}
343
+ };
344
+ if (Array.isArray(moonshotArgs.messages)) {
345
+ moonshotArgs.messages = moonshotArgs.messages.map(
346
+ (message) => {
347
+ if (message.role !== "system" || !Array.isArray(message.tools)) {
348
+ return message;
349
+ }
350
+ const { content: _content, ...dynamicToolMessage } = message;
351
+ return dynamicToolMessage;
352
+ }
353
+ );
354
+ }
355
+ const responseFormat = moonshotArgs.response_format;
356
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json_object" && ((_a = moonshotArgs.messages) == null ? void 0 : _a.some(
357
+ (message) => message.partial === true
358
+ ))) {
359
+ throw new import_provider2.InvalidPromptError({
360
+ prompt: args.messages,
361
+ message: "Moonshot AI Partial Mode cannot be combined with JSON object response format."
362
+ });
363
+ }
364
+ if ((responseFormat == null ? void 0 : responseFormat.type) !== "json_schema" || ((_b = responseFormat.json_schema) == null ? void 0 : _b.schema) == null) {
365
+ return moonshotArgs;
366
+ }
367
+ const { $schema: _$schema, ...schemaWithoutDollarSchema } = responseFormat.json_schema.schema;
368
+ return {
369
+ ...moonshotArgs,
370
+ response_format: {
371
+ type: "json_schema",
372
+ json_schema: {
373
+ name: (_c = responseFormat.json_schema.name) != null ? _c : "response",
374
+ strict: strictJsonSchema != null ? strictJsonSchema : true,
375
+ schema: normalizeJsonSchemaForMFJS(schemaWithoutDollarSchema)
376
+ }
377
+ }
378
+ };
379
+ }
380
+ var moonshotAIValidatedOptionsSchema = moonshotaiProviderOptions.pick({
381
+ logprobs: true,
382
+ topLogprobs: true,
383
+ prediction: true
384
+ });
385
+ async function validateProviderOptions(options) {
386
+ await (0, import_provider_utils.parseProviderOptions)({
387
+ provider: "moonshotai",
388
+ providerOptions: options.providerOptions,
389
+ schema: moonshotAIValidatedOptionsSchema
390
+ });
391
+ }
392
+ async function prepareMessageOptions({
393
+ modelId,
394
+ options
395
+ }) {
396
+ var _a, _b, _c, _d;
397
+ const prompt = [];
398
+ const warnings = [];
399
+ for (const [index, message] of options.prompt.entries()) {
400
+ const messageOptions = await (0, import_provider_utils.parseProviderOptions)({
401
+ provider: "moonshotai",
402
+ providerOptions: message.providerOptions,
403
+ schema: moonshotaiAllMessageProviderOptions
404
+ });
405
+ if ((messageOptions == null ? void 0 : messageOptions.partial) === true && message.role !== "assistant") {
406
+ throw new import_provider2.InvalidPromptError({
407
+ prompt: options.prompt,
408
+ message: "Moonshot AI Partial Mode requires `partial: true` on an assistant message."
409
+ });
410
+ }
411
+ if ((messageOptions == null ? void 0 : messageOptions.tools) != null && message.role !== "system") {
412
+ throw new import_provider2.InvalidPromptError({
413
+ prompt: options.prompt,
414
+ message: "Moonshot dynamic tools must be configured on a system message."
415
+ });
416
+ }
417
+ if ((messageOptions == null ? void 0 : messageOptions.partial) === true && index !== options.prompt.length - 1) {
418
+ throw new import_provider2.InvalidPromptError({
419
+ prompt: options.prompt,
420
+ message: "Moonshot AI Partial Mode requires the partial assistant message to be the final message."
421
+ });
422
+ }
423
+ if (((_a = messageOptions == null ? void 0 : messageOptions.tools) == null ? void 0 : _a.length) && message.role === "system") {
424
+ if (message.content.length > 0) {
425
+ throw new import_provider2.InvalidPromptError({
426
+ prompt: options.prompt,
427
+ message: "A Moonshot dynamic-tool system message must use empty content because the API forbids content alongside tools."
428
+ });
429
+ }
430
+ const modelFamily = getMoonshotAIModelFamily(modelId);
431
+ if (modelFamily !== "kimi-k3" && modelFamily !== "unknown") {
432
+ warnings.push({
433
+ type: "other",
434
+ message: `Moonshot documents dynamic tool loading only for Kimi K3. The dynamic system message has been omitted for model "${modelId}".`
435
+ });
436
+ continue;
437
+ }
438
+ prompt.push({
439
+ ...message,
440
+ providerOptions: {
441
+ ...message.providerOptions,
442
+ openaiCompatible: {
443
+ ...(_b = message.providerOptions) == null ? void 0 : _b.openaiCompatible,
444
+ tools: messageOptions.tools.map((tool) => ({
445
+ type: "function",
446
+ function: {
447
+ name: tool.name,
448
+ ...tool.description != null ? { description: tool.description } : {},
449
+ parameters: normalizeJsonSchemaForMFJS(
450
+ tool.inputSchema
451
+ ),
452
+ ...tool.strict != null ? { strict: tool.strict } : {}
453
+ }
454
+ }))
455
+ }
456
+ }
457
+ });
458
+ continue;
459
+ }
460
+ if ((messageOptions == null ? void 0 : messageOptions.name) == null && (messageOptions == null ? void 0 : messageOptions.partial) !== true) {
461
+ prompt.push(message);
462
+ continue;
463
+ }
464
+ if (message.role === "tool" && (messageOptions == null ? void 0 : messageOptions.name) != null) {
465
+ warnings.push({
466
+ type: "other",
467
+ message: "Moonshot AI does not support message names on tool messages. The name has been omitted."
468
+ });
469
+ prompt.push(message);
470
+ continue;
471
+ }
472
+ const openAICompatibleOptions = {
473
+ ...(_c = message.providerOptions) == null ? void 0 : _c.openaiCompatible,
474
+ ...messageOptions.name != null && { name: messageOptions.name },
475
+ ...messageOptions.partial === true && { partial: true }
476
+ };
477
+ if (message.role === "user" && message.content.length === 1 && message.content[0].type === "text") {
478
+ const textPart = message.content[0];
479
+ prompt.push({
480
+ ...message,
481
+ content: [
482
+ {
483
+ ...textPart,
484
+ providerOptions: {
485
+ ...textPart.providerOptions,
486
+ openaiCompatible: {
487
+ ...openAICompatibleOptions,
488
+ ...(_d = textPart.providerOptions) == null ? void 0 : _d.openaiCompatible,
489
+ ...messageOptions.name != null && {
490
+ name: messageOptions.name
491
+ }
492
+ }
493
+ }
494
+ }
495
+ ]
496
+ });
497
+ continue;
498
+ }
499
+ prompt.push({
500
+ ...message,
501
+ providerOptions: {
502
+ ...message.providerOptions,
503
+ openaiCompatible: openAICompatibleOptions
504
+ }
505
+ });
506
+ }
507
+ return {
508
+ options: { ...options, prompt },
509
+ warnings
510
+ };
511
+ }
512
+ var moonshotAIChatLogprobSchema = import_v42.z.object({
513
+ token: import_v42.z.string(),
514
+ logprob: import_v42.z.number(),
515
+ bytes: import_v42.z.array(import_v42.z.number()).nullable(),
516
+ top_logprobs: import_v42.z.array(
517
+ import_v42.z.object({
518
+ token: import_v42.z.string(),
519
+ logprob: import_v42.z.number(),
520
+ bytes: import_v42.z.array(import_v42.z.number()).nullable()
521
+ })
522
+ )
523
+ });
524
+ var moonshotAIChatLogprobsSchema = import_v42.z.object({
525
+ content: import_v42.z.array(moonshotAIChatLogprobSchema).nullish()
526
+ }).nullish();
527
+ function extractMoonshotAIChatLogprobs(value) {
528
+ var _a, _b, _c;
529
+ const result = moonshotAIChatLogprobsSchema.safeParse(
530
+ (_b = (_a = value == null ? void 0 : value.choices) == null ? void 0 : _a[0]) == null ? void 0 : _b.logprobs
531
+ );
532
+ return result.success ? (_c = result.data) != null ? _c : void 0 : void 0;
533
+ }
534
+ function prepareSamplingOptions({
535
+ modelId,
536
+ options
537
+ }) {
538
+ if (!isMoonshotAIKimiModel(modelId)) {
539
+ return { options, warnings: [] };
540
+ }
541
+ const warnings = [];
542
+ const samplingSettings = [
543
+ ["temperature", options.temperature],
544
+ ["topP", options.topP],
545
+ ["frequencyPenalty", options.frequencyPenalty],
546
+ ["presencePenalty", options.presencePenalty]
547
+ ];
548
+ for (const [setting, value] of samplingSettings) {
549
+ if (value != null) {
550
+ warnings.push({
551
+ type: "unsupported-setting",
552
+ setting,
553
+ details: `${setting} is fixed by model "${modelId}" and has been omitted.`
554
+ });
555
+ }
556
+ }
557
+ return {
558
+ options: {
559
+ ...options,
560
+ temperature: void 0,
561
+ topP: void 0,
562
+ frequencyPenalty: void 0,
563
+ presencePenalty: void 0
564
+ },
565
+ warnings
566
+ };
567
+ }
568
+ function prepareToolChoiceOptions({
569
+ modelId,
570
+ options
571
+ }) {
572
+ var _a;
573
+ if (((_a = options.toolChoice) == null ? void 0 : _a.type) !== "required" || !["kimi-k2.6", "kimi-k2.7"].includes(getMoonshotAIModelFamily(modelId))) {
574
+ return { options, warnings: [] };
575
+ }
576
+ return {
577
+ options: { ...options, toolChoice: void 0 },
578
+ warnings: [
579
+ {
580
+ type: "unsupported-setting",
581
+ setting: "toolChoice",
582
+ details: `toolChoice "required" is not supported by model "${modelId}" and has been omitted; use "auto" or select a specific tool instead.`
583
+ }
584
+ ]
585
+ };
586
+ }
587
+ function prepareReasoningOptions({
588
+ modelId,
589
+ options
590
+ }) {
591
+ var _a;
592
+ const providerOptions = (_a = options.providerOptions) == null ? void 0 : _a.moonshotai;
593
+ if (providerOptions == null || typeof providerOptions !== "object" || Array.isArray(providerOptions)) {
594
+ return { options, warnings: [] };
595
+ }
596
+ const moonshotOptions = providerOptions;
597
+ const {
598
+ reasoningEffort: requestedReasoningEffort,
599
+ thinking: requestedThinking,
600
+ reasoningHistory,
601
+ ...otherMoonshotOptions
602
+ } = moonshotOptions;
603
+ const preserveReasoning = reasoningHistory === "preserved";
604
+ const warnings = [];
605
+ if ((requestedThinking == null ? void 0 : requestedThinking.budgetTokens) != null) {
606
+ warnings.push({
607
+ type: "other",
608
+ message: "providerOptions.moonshotai.thinking.budgetTokens is deprecated because Moonshot Chat Completions does not support budget_tokens. The option has been omitted."
609
+ });
610
+ }
611
+ let thinking;
612
+ let reasoningEffort;
613
+ const warnUnsupportedReasoningEffort = () => {
614
+ if (requestedReasoningEffort != null) {
615
+ warnings.push({
616
+ type: "unsupported-setting",
617
+ setting: "providerOptions",
618
+ details: `providerOptions.moonshotai.reasoningEffort is only supported by Kimi K3 and has been omitted for model "${modelId}".`
619
+ });
620
+ }
621
+ };
622
+ switch (getMoonshotAIModelFamily(modelId)) {
623
+ case "kimi-k3": {
624
+ if (requestedThinking != null) {
625
+ warnings.push({
626
+ type: "unsupported-setting",
627
+ setting: "providerOptions",
628
+ details: "Kimi K3 always reasons and does not accept providerOptions.moonshotai.thinking. The option has been omitted."
629
+ });
630
+ }
631
+ reasoningEffort = requestedReasoningEffort;
632
+ break;
633
+ }
634
+ case "kimi-k2.7": {
635
+ warnUnsupportedReasoningEffort();
636
+ if ((requestedThinking == null ? void 0 : requestedThinking.type) === "disabled") {
637
+ warnings.push({
638
+ type: "unsupported-setting",
639
+ setting: "providerOptions",
640
+ details: "Kimi K2.7 thinking cannot be disabled. providerOptions.moonshotai.thinking has been omitted."
641
+ });
642
+ } else if ((requestedThinking == null ? void 0 : requestedThinking.type) === "enabled") {
643
+ thinking = { type: "enabled" };
644
+ }
645
+ break;
646
+ }
647
+ case "kimi-k2.6": {
648
+ warnUnsupportedReasoningEffort();
649
+ const thinkingType = requestedThinking == null ? void 0 : requestedThinking.type;
650
+ if (thinkingType != null || preserveReasoning) {
651
+ thinking = {
652
+ type: thinkingType != null ? thinkingType : "enabled",
653
+ ...preserveReasoning ? { keep: "all" } : {}
654
+ };
655
+ }
656
+ break;
657
+ }
658
+ case "kimi-k2.5": {
659
+ warnUnsupportedReasoningEffort();
660
+ if ((requestedThinking == null ? void 0 : requestedThinking.type) != null) {
661
+ thinking = { type: requestedThinking.type };
662
+ }
663
+ if (preserveReasoning) {
664
+ warnings.push({
665
+ type: "unsupported-setting",
666
+ setting: "providerOptions",
667
+ details: `providerOptions.moonshotai.reasoningHistory 'preserved' is not supported by model "${modelId}" and has been omitted.`
668
+ });
669
+ }
670
+ break;
671
+ }
672
+ case "moonshot-v1": {
673
+ warnUnsupportedReasoningEffort();
674
+ if (requestedThinking != null) {
675
+ warnings.push({
676
+ type: "unsupported-setting",
677
+ setting: "providerOptions",
678
+ details: `providerOptions.moonshotai.thinking is not supported by model "${modelId}" and has been omitted.`
679
+ });
680
+ }
681
+ if (preserveReasoning) {
682
+ warnings.push({
683
+ type: "unsupported-setting",
684
+ setting: "providerOptions",
685
+ details: `providerOptions.moonshotai.reasoningHistory 'preserved' is not supported by model "${modelId}" and has been omitted.`
686
+ });
687
+ }
688
+ break;
689
+ }
690
+ case "unknown": {
691
+ reasoningEffort = requestedReasoningEffort;
692
+ if ((requestedThinking == null ? void 0 : requestedThinking.type) != null) {
693
+ thinking = { type: requestedThinking.type };
694
+ }
695
+ if (preserveReasoning) {
696
+ warnings.push({
697
+ type: "unsupported-setting",
698
+ setting: "providerOptions",
699
+ details: `providerOptions.moonshotai.reasoningHistory 'preserved' is not supported by model "${modelId}" and has been omitted.`
700
+ });
701
+ }
702
+ break;
703
+ }
704
+ }
705
+ return {
706
+ options: {
707
+ ...options,
708
+ providerOptions: {
709
+ ...options.providerOptions,
710
+ moonshotai: {
711
+ ...otherMoonshotOptions,
712
+ ...reasoningEffort != null ? { reasoningEffort } : {},
713
+ ...thinking != null ? { thinking } : {}
714
+ }
715
+ }
716
+ },
717
+ warnings
718
+ };
719
+ }
58
720
  var MoonshotAIChatLanguageModel = class extends import_openai_compatible.OpenAICompatibleChatLanguageModel {
59
721
  constructor(modelId, config) {
60
- super(modelId, config);
722
+ super(modelId, {
723
+ ...config,
724
+ metadataExtractor: moonshotAIChatMetadataExtractor,
725
+ transformRequestBody: (args) => {
726
+ var _a, _b;
727
+ return transformMoonshotRequestBody(
728
+ (_b = (_a = config.transformRequestBody) == null ? void 0 : _a.call(config, args)) != null ? _b : args
729
+ );
730
+ }
731
+ });
61
732
  }
62
733
  async doGenerate(options) {
63
- var _a, _b;
64
- const result = await super.doGenerate(options);
734
+ var _a, _b, _c, _d;
735
+ const { options: messageOptions, warnings: messageWarnings } = await prepareMessageOptions({ modelId: this.modelId, options });
736
+ await validateProviderOptions(messageOptions);
737
+ const { options: samplingOptions, warnings: samplingWarnings } = prepareSamplingOptions({
738
+ modelId: this.modelId,
739
+ options: messageOptions
740
+ });
741
+ const { options: sanitizedOptions, warnings: reasoningWarnings } = prepareReasoningOptions({
742
+ modelId: this.modelId,
743
+ options: samplingOptions
744
+ });
745
+ const { options: toolChoiceOptions, warnings: toolChoiceWarnings } = prepareToolChoiceOptions({
746
+ modelId: this.modelId,
747
+ options: sanitizedOptions
748
+ });
749
+ const result = await super.doGenerate(toolChoiceOptions);
65
750
  const usage = (_b = (_a = result.response) == null ? void 0 : _a.body) == null ? void 0 : _b.usage;
751
+ const logprobs = extractMoonshotAIChatLogprobs((_c = result.response) == null ? void 0 : _c.body);
66
752
  return {
67
753
  ...result,
68
- usage: convertMoonshotAIChatUsage(usage)
754
+ usage: convertMoonshotAIChatUsage(usage),
755
+ providerMetadata: {
756
+ ...result.providerMetadata,
757
+ moonshotai: {
758
+ ...(_d = result.providerMetadata) == null ? void 0 : _d.moonshotai,
759
+ ...logprobs != null && { logprobs }
760
+ }
761
+ },
762
+ warnings: [
763
+ ...result.warnings,
764
+ ...messageWarnings,
765
+ ...samplingWarnings,
766
+ ...reasoningWarnings,
767
+ ...toolChoiceWarnings
768
+ ]
69
769
  };
70
770
  }
71
771
  async doStream(options) {
772
+ const { options: messageOptions, warnings: messageWarnings } = await prepareMessageOptions({ modelId: this.modelId, options });
773
+ await validateProviderOptions(messageOptions);
72
774
  const originalIncludeRawChunks = options.includeRawChunks;
775
+ const { options: samplingOptions, warnings: samplingWarnings } = prepareSamplingOptions({
776
+ modelId: this.modelId,
777
+ options: messageOptions
778
+ });
779
+ const { options: sanitizedOptions, warnings: reasoningWarnings } = prepareReasoningOptions({
780
+ modelId: this.modelId,
781
+ options: samplingOptions
782
+ });
783
+ const { options: toolChoiceOptions, warnings: toolChoiceWarnings } = prepareToolChoiceOptions({
784
+ modelId: this.modelId,
785
+ options: sanitizedOptions
786
+ });
73
787
  const result = await super.doStream({
74
- ...options,
788
+ ...toolChoiceOptions,
75
789
  includeRawChunks: true
76
790
  });
77
791
  let rawUsage = void 0;
792
+ const contentLogprobs = [];
78
793
  return {
79
794
  ...result,
80
795
  stream: result.stream.pipeThrough(
81
796
  new TransformStream({
82
797
  transform(chunk, controller) {
798
+ var _a;
799
+ if (chunk.type === "stream-start") {
800
+ controller.enqueue({
801
+ ...chunk,
802
+ warnings: [
803
+ ...chunk.warnings,
804
+ ...messageWarnings,
805
+ ...samplingWarnings,
806
+ ...reasoningWarnings,
807
+ ...toolChoiceWarnings
808
+ ]
809
+ });
810
+ return;
811
+ }
83
812
  if (chunk.type === "raw") {
84
813
  const rawValue = chunk.rawValue;
85
814
  if ((rawValue == null ? void 0 : rawValue.usage) != null) {
86
815
  rawUsage = rawValue.usage;
87
816
  }
817
+ const logprobs = extractMoonshotAIChatLogprobs(rawValue);
818
+ if ((logprobs == null ? void 0 : logprobs.content) != null) {
819
+ contentLogprobs.push(...logprobs.content);
820
+ }
88
821
  if (originalIncludeRawChunks) {
89
822
  controller.enqueue(chunk);
90
823
  }
@@ -93,7 +826,16 @@ var MoonshotAIChatLanguageModel = class extends import_openai_compatible.OpenAIC
93
826
  if (chunk.type === "finish") {
94
827
  controller.enqueue({
95
828
  ...chunk,
96
- usage: rawUsage ? convertMoonshotAIChatUsage(rawUsage) : chunk.usage
829
+ usage: rawUsage ? convertMoonshotAIChatUsage(rawUsage) : chunk.usage,
830
+ providerMetadata: {
831
+ ...chunk.providerMetadata,
832
+ moonshotai: {
833
+ ...(_a = chunk.providerMetadata) == null ? void 0 : _a.moonshotai,
834
+ ...contentLogprobs.length > 0 && {
835
+ logprobs: { content: contentLogprobs }
836
+ }
837
+ }
838
+ }
97
839
  });
98
840
  return;
99
841
  }
@@ -106,13 +848,14 @@ var MoonshotAIChatLanguageModel = class extends import_openai_compatible.OpenAIC
106
848
  };
107
849
 
108
850
  // src/version.ts
109
- var VERSION = true ? "0.0.20" : "0.0.0-test";
851
+ var VERSION = true ? "0.0.24" : "0.0.0-test";
110
852
 
111
853
  // src/moonshotai-provider.ts
112
- var moonshotaiErrorSchema = import_v4.z.object({
113
- error: import_v4.z.object({
114
- message: import_v4.z.string(),
115
- type: import_v4.z.string().nullish()
854
+ var moonshotaiErrorSchema = import_v43.z.object({
855
+ error: import_v43.z.object({
856
+ message: import_v43.z.string(),
857
+ type: import_v43.z.string().nullish(),
858
+ code: import_v43.z.string().nullish()
116
859
  })
117
860
  });
118
861
  var moonshotaiErrorStructure = {
@@ -120,12 +863,15 @@ var moonshotaiErrorStructure = {
120
863
  errorToMessage: (data) => data.error.message
121
864
  };
122
865
  var defaultBaseURL = "https://api.moonshot.ai/v1";
866
+ function getModelStructuredOutputSupport(modelId) {
867
+ return modelId.startsWith("kimi-k") || modelId === "moonshot-v1-8k" || modelId === "moonshot-v1-32k" || modelId === "moonshot-v1-128k" || modelId === "moonshot-v1-auto" || modelId === "moonshot-v1-8k-vision-preview" || modelId === "moonshot-v1-32k-vision-preview" || modelId === "moonshot-v1-128k-vision-preview";
868
+ }
123
869
  function createMoonshotAI(options = {}) {
124
870
  var _a;
125
- const baseURL = (0, import_provider_utils.withoutTrailingSlash)((_a = options.baseURL) != null ? _a : defaultBaseURL);
126
- const getHeaders = () => (0, import_provider_utils.withUserAgentSuffix)(
871
+ const baseURL = (0, import_provider_utils2.withoutTrailingSlash)((_a = options.baseURL) != null ? _a : defaultBaseURL);
872
+ const getHeaders = () => (0, import_provider_utils2.withUserAgentSuffix)(
127
873
  {
128
- Authorization: `Bearer ${(0, import_provider_utils.loadApiKey)({
874
+ Authorization: `Bearer ${(0, import_provider_utils2.loadApiKey)({
129
875
  apiKey: options.apiKey,
130
876
  environmentVariableName: "MOONSHOT_API_KEY",
131
877
  description: "Moonshot API key"
@@ -144,7 +890,8 @@ function createMoonshotAI(options = {}) {
144
890
  return new MoonshotAIChatLanguageModel(modelId, {
145
891
  ...getCommonModelConfig("chat"),
146
892
  includeUsage: true,
147
- errorStructure: moonshotaiErrorStructure
893
+ errorStructure: moonshotaiErrorStructure,
894
+ supportsStructuredOutputs: getModelStructuredOutputSupport(modelId)
148
895
  });
149
896
  };
150
897
  const provider = (modelId) => createChatModel(modelId);
@@ -152,10 +899,10 @@ function createMoonshotAI(options = {}) {
152
899
  provider.chatModel = createChatModel;
153
900
  provider.languageModel = createChatModel;
154
901
  provider.textEmbeddingModel = (modelId) => {
155
- throw new import_provider.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
902
+ throw new import_provider3.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
156
903
  };
157
904
  provider.imageModel = (modelId) => {
158
- throw new import_provider.NoSuchModelError({ modelId, modelType: "imageModel" });
905
+ throw new import_provider3.NoSuchModelError({ modelId, modelType: "imageModel" });
159
906
  };
160
907
  return provider;
161
908
  }