nah-studio 0.0.1-beta.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.
@@ -0,0 +1,1320 @@
1
+ import { a as Oe, _ as Se, K as z, r as D, Y as L, S as W, M as m, I as H, N as T, m as Ie, g as P, h as U, f as X, i as ee, F as de, ac as Ce, ad as Y, af as qe, w as Re, ag as Te, av as pe, P as u, an as ce, Z as C, U as he, u as A, a9 as N, R as q, O as _, ao as Ne, ah as Ue, a5 as ge, z as $e, T as V, A as B, a2 as Z, Q as Pe, V as je } from "./cli-AoWZGiY6.js";
2
+ function $(e) {
3
+ return e.replace(/[_-]([a-z])/g, (t) => t[1].toUpperCase());
4
+ }
5
+ function Me(e, t) {
6
+ const o = $(e);
7
+ return o !== e && t?.[o] != null ? o : e;
8
+ }
9
+ function F({ rawName: e, providerOptions: t, warnings: o }) {
10
+ const s = $(e);
11
+ s !== e && t?.[e] != null && o.push({
12
+ type: "deprecated",
13
+ setting: `providerOptions key '${e}'`,
14
+ message: `Use '${s}' instead.`
15
+ });
16
+ }
17
+ const E = {
18
+ errorSchema: m({ error: m({
19
+ message: u(),
20
+ type: u().nullish(),
21
+ param: pe().nullish(),
22
+ code: W([u(), _()]).nullish()
23
+ }) }),
24
+ errorToMessage: (e) => e.error.message
25
+ };
26
+ function He(e) {
27
+ if (e == null) return ce();
28
+ const t = e.prompt_tokens ?? 0, o = e.completion_tokens ?? 0, s = e.prompt_tokens_details?.cached_tokens ?? 0, r = e.completion_tokens_details?.reasoning_tokens ?? 0;
29
+ return {
30
+ inputTokens: {
31
+ total: t,
32
+ noCache: t - s,
33
+ cacheRead: s,
34
+ cacheWrite: void 0
35
+ },
36
+ outputTokens: {
37
+ total: o,
38
+ text: Math.max(0, o - r),
39
+ reasoning: r
40
+ },
41
+ raw: e
42
+ };
43
+ }
44
+ function M(e) {
45
+ return e?.providerOptions?.openaiCompatible ?? {};
46
+ }
47
+ function Ae(e) {
48
+ switch (e) {
49
+ case "audio/wav":
50
+ return "wav";
51
+ case "audio/mp3":
52
+ case "audio/mpeg":
53
+ return "mp3";
54
+ default:
55
+ return null;
56
+ }
57
+ }
58
+ function me(e) {
59
+ const t = M(e);
60
+ switch (e.type) {
61
+ case "text":
62
+ return {
63
+ type: "text",
64
+ text: e.text,
65
+ ...t
66
+ };
67
+ case "file":
68
+ switch (e.data.type) {
69
+ case "reference":
70
+ throw new C({ functionality: "file parts with provider references" });
71
+ case "text":
72
+ throw new C({ functionality: "text file parts" });
73
+ case "url":
74
+ case "data": {
75
+ const o = $e(e.mediaType);
76
+ if (o === "image") return {
77
+ type: "image_url",
78
+ image_url: { url: e.data.type === "url" ? e.data.url.toString() : `data:${V({ part: e })};base64,${B(e.data.data)}` },
79
+ ...t
80
+ };
81
+ if (o === "video") return {
82
+ type: "video_url",
83
+ video_url: { url: e.data.type === "url" ? e.data.url.toString() : `data:${V({ part: e })};base64,${B(e.data.data)}` },
84
+ ...t
85
+ };
86
+ if (o === "audio") {
87
+ if (e.data.type === "url") throw new C({ functionality: "audio file parts with URLs" });
88
+ const s = V({ part: e }), r = Ae(s);
89
+ if (r === null) throw new C({ functionality: `audio media type ${s}` });
90
+ return {
91
+ type: "input_audio",
92
+ input_audio: {
93
+ data: B(e.data.data),
94
+ format: r
95
+ },
96
+ ...t
97
+ };
98
+ }
99
+ if (o === "application") {
100
+ if (e.data.type === "url") throw new C({ functionality: "PDF file parts with URLs" });
101
+ const s = V({ part: e });
102
+ if (s !== "application/pdf") throw new C({ functionality: `file part media type ${s}` });
103
+ return {
104
+ type: "file",
105
+ file: {
106
+ filename: e.filename ?? "document.pdf",
107
+ file_data: `data:application/pdf;base64,${B(e.data.data)}`
108
+ },
109
+ ...t
110
+ };
111
+ }
112
+ if (o === "text") return {
113
+ type: "text",
114
+ text: e.data.type === "url" ? e.data.url.toString() : typeof e.data.data == "string" ? new TextDecoder().decode(ge(e.data.data)) : new TextDecoder().decode(e.data.data),
115
+ ...t
116
+ };
117
+ throw new C({ functionality: `file part media type ${e.mediaType}` });
118
+ }
119
+ }
120
+ }
121
+ }
122
+ function Ee(e) {
123
+ if (e.type === "custom") throw new C({ functionality: "custom tool content parts" });
124
+ return me(e);
125
+ }
126
+ function Ke(e, { providerOptionsKey: t = "google", supportsMultiPartToolContent: o = !1 } = {}) {
127
+ const s = [];
128
+ for (const { role: r, content: i, ...f } of e) {
129
+ const d = M({ ...f });
130
+ switch (r) {
131
+ case "system":
132
+ s.push({
133
+ role: "system",
134
+ content: i,
135
+ ...d
136
+ });
137
+ break;
138
+ case "user":
139
+ if (i.length === 1 && i[0].type === "text") {
140
+ s.push({
141
+ role: "user",
142
+ content: i[0].text,
143
+ ...M(i[0])
144
+ });
145
+ break;
146
+ }
147
+ s.push({
148
+ role: "user",
149
+ content: i.map(me),
150
+ ...d
151
+ });
152
+ break;
153
+ case "assistant": {
154
+ let c = "", a = "";
155
+ const l = [];
156
+ for (const n of i) {
157
+ const p = M(n);
158
+ switch (n.type) {
159
+ case "text":
160
+ c += n.text;
161
+ break;
162
+ case "reasoning":
163
+ a += n.text;
164
+ break;
165
+ case "tool-call": {
166
+ const x = n.providerOptions?.[t]?.thoughtSignature ?? n.providerOptions?.google?.thoughtSignature;
167
+ l.push({
168
+ id: n.toolCallId,
169
+ type: "function",
170
+ function: {
171
+ name: n.toolName,
172
+ arguments: JSON.stringify(n.input)
173
+ },
174
+ ...p,
175
+ ...x ? { extra_content: { google: { thought_signature: String(x) } } } : {}
176
+ });
177
+ break;
178
+ }
179
+ }
180
+ }
181
+ s.push({
182
+ role: "assistant",
183
+ content: l.length > 0 ? c || null : c,
184
+ ...a.length > 0 ? { reasoning_content: a } : {},
185
+ tool_calls: l.length > 0 ? l : void 0,
186
+ ...d
187
+ });
188
+ break;
189
+ }
190
+ case "tool":
191
+ for (const c of i) {
192
+ if (c.type === "tool-approval-response") continue;
193
+ const a = c.output;
194
+ let l;
195
+ switch (a.type) {
196
+ case "text":
197
+ case "error-text":
198
+ l = a.value;
199
+ break;
200
+ case "execution-denied":
201
+ l = a.reason ?? "Tool call execution denied.";
202
+ break;
203
+ case "json":
204
+ case "error-json":
205
+ l = JSON.stringify(a.value);
206
+ break;
207
+ case "content":
208
+ l = o ? a.value.map(Ee) : JSON.stringify(a.value);
209
+ }
210
+ const n = M(c);
211
+ s.push({
212
+ role: "tool",
213
+ tool_call_id: c.toolCallId,
214
+ content: l,
215
+ ...n
216
+ });
217
+ }
218
+ break;
219
+ default:
220
+ throw new Error(`Unsupported role: ${r}`);
221
+ }
222
+ }
223
+ return s;
224
+ }
225
+ function te({ id: e, model: t, created: o }) {
226
+ return Y({
227
+ id: e,
228
+ model: t,
229
+ created: o || void 0
230
+ });
231
+ }
232
+ function oe(e) {
233
+ switch (e) {
234
+ case "stop":
235
+ return "stop";
236
+ case "length":
237
+ return "length";
238
+ case "content_filter":
239
+ return "content-filter";
240
+ case "function_call":
241
+ case "tool_calls":
242
+ return "tool-calls";
243
+ default:
244
+ return "other";
245
+ }
246
+ }
247
+ const j = m({
248
+ /**
249
+ * A unique identifier representing your end-user, which can help the provider to
250
+ * monitor and detect abuse.
251
+ */
252
+ user: u().optional(),
253
+ /**
254
+ * Reasoning effort for reasoning models. Defaults to `medium`.
255
+ */
256
+ reasoningEffort: u().optional(),
257
+ /**
258
+ * Controls the verbosity of the generated text. Defaults to `medium`.
259
+ */
260
+ textVerbosity: u().optional(),
261
+ /**
262
+ * Whether to use strict JSON schema validation.
263
+ * When true, the model uses constrained decoding to guarantee schema compliance.
264
+ * Only used when the provider supports structured outputs and a schema is provided.
265
+ *
266
+ * @default true
267
+ */
268
+ strictJsonSchema: he().optional()
269
+ });
270
+ function Ve({ tools: e, toolChoice: t }) {
271
+ e = e?.length ? e : void 0;
272
+ const o = [];
273
+ if (e == null) return {
274
+ tools: void 0,
275
+ toolChoice: void 0,
276
+ toolWarnings: o
277
+ };
278
+ const s = [];
279
+ for (const i of e) i.type === "provider" ? o.push({
280
+ type: "unsupported",
281
+ feature: `provider-defined tool ${i.id}`
282
+ }) : s.push({
283
+ type: "function",
284
+ function: {
285
+ name: i.name,
286
+ description: i.description,
287
+ parameters: i.inputSchema,
288
+ ...i.strict != null ? { strict: i.strict } : {}
289
+ }
290
+ });
291
+ if (t == null) return {
292
+ tools: s,
293
+ toolChoice: void 0,
294
+ toolWarnings: o
295
+ };
296
+ const r = t.type;
297
+ switch (r) {
298
+ case "auto":
299
+ case "none":
300
+ case "required":
301
+ return {
302
+ tools: s,
303
+ toolChoice: r,
304
+ toolWarnings: o
305
+ };
306
+ case "tool":
307
+ return {
308
+ tools: s,
309
+ toolChoice: {
310
+ type: "function",
311
+ function: { name: t.toolName }
312
+ },
313
+ toolWarnings: o
314
+ };
315
+ default:
316
+ throw new C({ functionality: `tool choice type: ${r}` });
317
+ }
318
+ }
319
+ var Be = class fe {
320
+ static [z](t) {
321
+ return D({
322
+ modelId: t.modelId,
323
+ config: t.config
324
+ });
325
+ }
326
+ static [L](t) {
327
+ return new fe(t.modelId, t.config);
328
+ }
329
+ constructor(t, o) {
330
+ this.specificationVersion = "v4", this.modelId = t, this.config = o;
331
+ const s = o.errorStructure ?? E;
332
+ this.chunkSchema = Le(s.errorSchema), this.failedResponseHandler = H(s), this.supportsStructuredOutputs = o.supportsStructuredOutputs ?? !1;
333
+ }
334
+ get provider() {
335
+ return this.config.provider;
336
+ }
337
+ get providerOptionsName() {
338
+ return this.config.provider.split(".")[0].trim();
339
+ }
340
+ get supportedUrls() {
341
+ return this.config.supportedUrls?.() ?? {};
342
+ }
343
+ transformRequestBody(t) {
344
+ return this.config.transformRequestBody?.(t) ?? t;
345
+ }
346
+ convertUsage(t) {
347
+ return this.config.convertUsage?.(t) ?? He(t);
348
+ }
349
+ async getArgs({ prompt: t, maxOutputTokens: o, temperature: s, topP: r, topK: i, frequencyPenalty: f, presencePenalty: d, reasoning: c, providerOptions: a, stopSequences: l, responseFormat: n, seed: p, toolChoice: x, tools: y }) {
350
+ const v = [], k = await T({
351
+ provider: "openai-compatible",
352
+ providerOptions: a,
353
+ schema: j
354
+ });
355
+ k != null && v.push({
356
+ type: "deprecated",
357
+ setting: "providerOptions key 'openai-compatible'",
358
+ message: "Use 'openaiCompatible' instead."
359
+ }), F({
360
+ rawName: this.providerOptionsName,
361
+ providerOptions: a,
362
+ warnings: v
363
+ });
364
+ const b = Object.assign(k ?? {}, await T({
365
+ provider: "openaiCompatible",
366
+ providerOptions: a,
367
+ schema: j
368
+ }) ?? {}, await T({
369
+ provider: this.providerOptionsName,
370
+ providerOptions: a,
371
+ schema: j
372
+ }) ?? {}, await T({
373
+ provider: $(this.providerOptionsName),
374
+ providerOptions: a,
375
+ schema: j
376
+ }) ?? {}), O = b?.strictJsonSchema ?? !0;
377
+ i != null && v.push({
378
+ type: "unsupported",
379
+ feature: "topK"
380
+ }), n?.type === "json" && n.schema != null && !this.supportsStructuredOutputs && v.push({
381
+ type: "unsupported",
382
+ feature: "responseFormat",
383
+ details: "JSON response format schema is only supported with structuredOutputs"
384
+ });
385
+ const { tools: J, toolChoice: h, toolWarnings: g } = Ve({
386
+ tools: y,
387
+ toolChoice: x
388
+ }), w = Me(this.providerOptionsName, a);
389
+ return {
390
+ metadataKey: w,
391
+ args: {
392
+ model: this.modelId,
393
+ user: b.user,
394
+ max_tokens: o,
395
+ temperature: s,
396
+ top_p: r,
397
+ frequency_penalty: f,
398
+ presence_penalty: d,
399
+ response_format: n?.type === "json" ? this.supportsStructuredOutputs === !0 && n.schema != null ? {
400
+ type: "json_schema",
401
+ json_schema: {
402
+ schema: n.schema,
403
+ strict: O,
404
+ name: n.name ?? "response",
405
+ description: n.description
406
+ }
407
+ } : { type: "json_object" } : void 0,
408
+ stop: l,
409
+ seed: p,
410
+ ...Object.fromEntries(Object.entries({
411
+ ...a?.[this.providerOptionsName],
412
+ ...a?.[$(this.providerOptionsName)]
413
+ }).filter(([S]) => !Object.keys(j.shape).includes(S))),
414
+ reasoning_effort: b.reasoningEffort ?? (Ie(c) ? c : void 0),
415
+ verbosity: b.textVerbosity,
416
+ messages: Ke(t, {
417
+ providerOptionsKey: w,
418
+ supportsMultiPartToolContent: this.config.supportsMultiPartToolContent
419
+ }),
420
+ tools: J,
421
+ tool_choice: h
422
+ },
423
+ warnings: [...v, ...g]
424
+ };
425
+ }
426
+ async doGenerate(t) {
427
+ const { args: o, warnings: s, metadataKey: r } = await this.getArgs({ ...t }), i = this.transformRequestBody(o), f = JSON.stringify(i), { responseHeaders: d, value: c, rawValue: a } = await P({
428
+ url: this.config.url({
429
+ path: "/chat/completions",
430
+ modelId: this.modelId
431
+ }),
432
+ headers: U(this.config.headers?.(), t.headers),
433
+ body: i,
434
+ failedResponseHandler: this.failedResponseHandler,
435
+ successfulResponseHandler: A(ze),
436
+ abortSignal: t.abortSignal,
437
+ fetch: this.config.fetch
438
+ }), l = c.choices[0];
439
+ if (l == null) throw new X({
440
+ data: a,
441
+ message: "Response did not contain any choices."
442
+ });
443
+ const n = [];
444
+ n.push(...ne(l.message.content));
445
+ const p = l.message.reasoning_content ?? l.message.reasoning;
446
+ if (p != null && p.length > 0 && n.push({
447
+ type: "reasoning",
448
+ text: p
449
+ }), l.message.tool_calls != null) for (const v of l.message.tool_calls) {
450
+ const k = v.extra_content?.google?.thought_signature;
451
+ n.push({
452
+ type: "tool-call",
453
+ toolCallId: v.id || ee(),
454
+ toolName: v.function.name,
455
+ input: v.function.arguments,
456
+ ...k ? { providerMetadata: { [r]: { thoughtSignature: k } } } : {}
457
+ });
458
+ }
459
+ const x = {
460
+ [r]: {},
461
+ ...await this.config.metadataExtractor?.extractMetadata?.({ parsedBody: a })
462
+ }, y = c.usage?.completion_tokens_details;
463
+ return y?.accepted_prediction_tokens != null && (x[r].acceptedPredictionTokens = y?.accepted_prediction_tokens), y?.rejected_prediction_tokens != null && (x[r].rejectedPredictionTokens = y?.rejected_prediction_tokens), {
464
+ content: n,
465
+ finishReason: {
466
+ unified: oe(l.finish_reason),
467
+ raw: l.finish_reason ?? void 0
468
+ },
469
+ usage: this.convertUsage(c.usage),
470
+ providerMetadata: x,
471
+ request: { body: f },
472
+ response: {
473
+ ...te(c),
474
+ headers: d,
475
+ body: a
476
+ },
477
+ warnings: s
478
+ };
479
+ }
480
+ async doStream(t) {
481
+ const { args: o, warnings: s, metadataKey: r } = await this.getArgs({ ...t }), i = this.transformRequestBody({
482
+ ...o,
483
+ stream: !0,
484
+ stream_options: this.config.includeUsage ? { include_usage: !0 } : void 0
485
+ }), f = this.config.metadataExtractor?.createStreamExtractor(), { responseHeaders: d, value: c } = await P({
486
+ url: this.config.url({
487
+ path: "/chat/completions",
488
+ modelId: this.modelId
489
+ }),
490
+ headers: U(this.config.headers?.(), t.headers),
491
+ body: i,
492
+ failedResponseHandler: this.failedResponseHandler,
493
+ successfulResponseHandler: de(this.chunkSchema),
494
+ abortSignal: t.abortSignal,
495
+ fetch: this.config.fetch
496
+ }), a = r;
497
+ let l;
498
+ const n = /* @__PURE__ */ new Map(), p = /* @__PURE__ */ new Set(), x = (h) => {
499
+ const g = h.index;
500
+ if (g == null || p.has(g)) {
501
+ l.processDelta(h);
502
+ return;
503
+ }
504
+ let w = n.get(g);
505
+ w == null ? (w = {
506
+ id: h.id ?? null,
507
+ bufferedArguments: "",
508
+ extraContent: h.extra_content ?? null
509
+ }, n.set(g, w)) : (w.id == null && h.id != null && (w.id = h.id), w.extraContent == null && h.extra_content != null && (w.extraContent = h.extra_content));
510
+ const S = h.function?.arguments;
511
+ S != null && (w.bufferedArguments += S);
512
+ const R = h.function?.name;
513
+ if (R != null) {
514
+ const K = {
515
+ index: g,
516
+ id: w.id,
517
+ function: {
518
+ name: R,
519
+ arguments: w.bufferedArguments
520
+ },
521
+ extra_content: w.extraContent ?? void 0
522
+ };
523
+ l.processDelta(K), n.delete(g), p.add(g);
524
+ }
525
+ };
526
+ let y, v, k = !1, b = !1, O = !1;
527
+ const J = (h) => this.convertUsage(h);
528
+ return {
529
+ stream: c.pipeThrough(new TransformStream({
530
+ start(h) {
531
+ l = new Ce(h, {
532
+ generateId: ee,
533
+ extractMetadata: (g) => {
534
+ const w = g.extra_content?.google?.thought_signature;
535
+ return w ? { [a]: { thoughtSignature: w } } : void 0;
536
+ },
537
+ buildToolCallProviderMetadata: (g) => g
538
+ }), h.enqueue({
539
+ type: "stream-start",
540
+ warnings: s
541
+ });
542
+ },
543
+ transform(h, g) {
544
+ if (t.includeRawChunks && g.enqueue({
545
+ type: "raw",
546
+ rawValue: h.rawValue
547
+ }), !h.success) {
548
+ y = {
549
+ unified: "error",
550
+ raw: void 0
551
+ }, g.enqueue({
552
+ type: "error",
553
+ error: h.error
554
+ });
555
+ return;
556
+ }
557
+ if (f?.processChunk(h.rawValue), "error" in h.value) {
558
+ y = {
559
+ unified: "error",
560
+ raw: void 0
561
+ }, g.enqueue({
562
+ type: "error",
563
+ error: h.value.error
564
+ });
565
+ return;
566
+ }
567
+ const w = h.value;
568
+ if (!k) {
569
+ const I = te(w);
570
+ Object.values(I).some(Boolean) && (k = !0, g.enqueue({
571
+ type: "response-metadata",
572
+ ...I
573
+ }));
574
+ }
575
+ w.usage != null && (v = w.usage);
576
+ const S = w.choices[0];
577
+ if (S?.finish_reason != null && (y = {
578
+ unified: oe(S.finish_reason),
579
+ raw: S.finish_reason ?? void 0
580
+ }), S?.delta == null) return;
581
+ const R = S.delta, K = (I) => {
582
+ O && (g.enqueue({
583
+ type: "text-end",
584
+ id: "txt-0"
585
+ }), O = !1), b || (g.enqueue({
586
+ type: "reasoning-start",
587
+ id: "reasoning-0"
588
+ }), b = !0), g.enqueue({
589
+ type: "reasoning-delta",
590
+ id: "reasoning-0",
591
+ delta: I
592
+ });
593
+ }, ke = (I) => {
594
+ b && (g.enqueue({
595
+ type: "reasoning-end",
596
+ id: "reasoning-0"
597
+ }), b = !1), O || (g.enqueue({
598
+ type: "text-start",
599
+ id: "txt-0"
600
+ }), O = !0), g.enqueue({
601
+ type: "text-delta",
602
+ id: "txt-0",
603
+ delta: I
604
+ });
605
+ }, Q = R.reasoning_content ?? R.reasoning;
606
+ Q && K(Q);
607
+ for (const I of ne(R.content)) I.type === "reasoning" ? K(I.text) : ke(I.text);
608
+ if (R.tool_calls != null && R.tool_calls.length > 0) {
609
+ b && (g.enqueue({
610
+ type: "reasoning-end",
611
+ id: "reasoning-0"
612
+ }), b = !1);
613
+ for (const I of R.tool_calls) x(I);
614
+ }
615
+ },
616
+ flush(h) {
617
+ b && h.enqueue({
618
+ type: "reasoning-end",
619
+ id: "reasoning-0"
620
+ }), O && h.enqueue({
621
+ type: "text-end",
622
+ id: "txt-0"
623
+ });
624
+ for (const [w, S] of n) l.processDelta({
625
+ index: w,
626
+ id: S.id,
627
+ function: { arguments: S.bufferedArguments }
628
+ });
629
+ n.clear(), l.flush(), y == null && (y = {
630
+ unified: "error",
631
+ raw: void 0
632
+ }, h.enqueue({
633
+ type: "error",
634
+ error: new X({
635
+ data: void 0,
636
+ message: "Response stream ended without a finish reason."
637
+ })
638
+ }));
639
+ const g = {
640
+ [a]: {},
641
+ ...f?.buildMetadata()
642
+ };
643
+ v?.completion_tokens_details?.accepted_prediction_tokens != null && (g[a].acceptedPredictionTokens = v?.completion_tokens_details?.accepted_prediction_tokens), v?.completion_tokens_details?.rejected_prediction_tokens != null && (g[a].rejectedPredictionTokens = v?.completion_tokens_details?.rejected_prediction_tokens), h.enqueue({
644
+ type: "finish",
645
+ finishReason: y,
646
+ usage: J(v),
647
+ providerMetadata: g
648
+ });
649
+ }
650
+ })),
651
+ request: { body: i },
652
+ response: { headers: d }
653
+ };
654
+ }
655
+ };
656
+ const ye = N({
657
+ prompt_tokens: _().nullish(),
658
+ completion_tokens: _().nullish(),
659
+ total_tokens: _().nullish(),
660
+ prompt_tokens_details: N({ cached_tokens: _().nullish() }).nullish(),
661
+ completion_tokens_details: N({
662
+ reasoning_tokens: _().nullish(),
663
+ accepted_prediction_tokens: _().nullish(),
664
+ rejected_prediction_tokens: _().nullish()
665
+ }).nullish()
666
+ }).nullish(), ve = W([u(), q(N({ type: u() }))]).nullish();
667
+ function ne(e) {
668
+ if (e == null) return [];
669
+ if (typeof e == "string") return e.length > 0 ? [{
670
+ type: "text",
671
+ text: e
672
+ }] : [];
673
+ const t = [];
674
+ for (const o of e) if (o.type === "text" && typeof o.text == "string")
675
+ o.text.length > 0 && t.push({
676
+ type: "text",
677
+ text: o.text
678
+ });
679
+ else if (o.type === "thinking" && Array.isArray(o.thinking)) {
680
+ const s = o.thinking.filter((r) => r != null && typeof r == "object" && "type" in r && r.type === "text" && "text" in r && typeof r.text == "string").map((r) => r.text).join("");
681
+ s.length > 0 && t.push({
682
+ type: "reasoning",
683
+ text: s
684
+ });
685
+ }
686
+ return t;
687
+ }
688
+ const ze = N({
689
+ id: u().nullish(),
690
+ created: _().nullish(),
691
+ model: u().nullish(),
692
+ choices: q(m({
693
+ message: m({
694
+ role: Pe("assistant").nullish(),
695
+ content: ve,
696
+ reasoning_content: u().nullish(),
697
+ reasoning: u().nullish(),
698
+ tool_calls: q(m({
699
+ id: u().nullish(),
700
+ function: m({
701
+ name: u(),
702
+ arguments: u()
703
+ }),
704
+ extra_content: m({ google: m({ thought_signature: u().nullish() }).nullish() }).nullish()
705
+ })).nullish()
706
+ }),
707
+ finish_reason: u().nullish()
708
+ })),
709
+ usage: ye
710
+ }), De = N({
711
+ id: u().nullish(),
712
+ created: _().nullish(),
713
+ model: u().nullish(),
714
+ choices: q(m({
715
+ delta: m({
716
+ role: je(["assistant", ""]).nullish(),
717
+ content: ve,
718
+ reasoning_content: u().nullish(),
719
+ reasoning: u().nullish(),
720
+ tool_calls: q(m({
721
+ index: _().nullish(),
722
+ id: u().nullish(),
723
+ function: m({
724
+ name: u().nullish(),
725
+ arguments: u().nullish()
726
+ }),
727
+ extra_content: m({ google: m({ thought_signature: u().nullish() }).nullish() }).nullish()
728
+ })).nullish()
729
+ }).nullish(),
730
+ finish_reason: u().nullish()
731
+ })),
732
+ usage: ye
733
+ }), Le = (e) => W([De, e]);
734
+ function se(e) {
735
+ if (e == null) return ce();
736
+ const t = e.prompt_tokens ?? 0, o = e.completion_tokens ?? 0;
737
+ return {
738
+ inputTokens: {
739
+ total: t,
740
+ noCache: t,
741
+ cacheRead: void 0,
742
+ cacheWrite: void 0
743
+ },
744
+ outputTokens: {
745
+ total: o,
746
+ text: o,
747
+ reasoning: void 0
748
+ },
749
+ raw: e
750
+ };
751
+ }
752
+ function We({ prompt: e, user: t = "user", assistant: o = "assistant" }) {
753
+ let s = "";
754
+ e[0].role === "system" && (s += `${e[0].content}
755
+
756
+ `, e = e.slice(1));
757
+ for (const { role: r, content: i } of e) switch (r) {
758
+ case "system":
759
+ throw new Ne({
760
+ message: "Unexpected system message in prompt: ${content}",
761
+ prompt: e
762
+ });
763
+ case "user": {
764
+ const f = i.map((d) => {
765
+ switch (d.type) {
766
+ case "text":
767
+ return d.text;
768
+ }
769
+ }).filter(Boolean).join("");
770
+ s += `${t}:
771
+ ${f}
772
+
773
+ `;
774
+ break;
775
+ }
776
+ case "assistant": {
777
+ const f = i.map((d) => {
778
+ switch (d.type) {
779
+ case "text":
780
+ return d.text;
781
+ case "tool-call":
782
+ throw new C({ functionality: "tool-call messages" });
783
+ }
784
+ }).join("");
785
+ s += `${o}:
786
+ ${f}
787
+
788
+ `;
789
+ break;
790
+ }
791
+ case "tool":
792
+ throw new C({ functionality: "tool messages" });
793
+ default:
794
+ throw new Error(`Unsupported role: ${r}`);
795
+ }
796
+ return s += `${o}:
797
+ `, {
798
+ prompt: s,
799
+ stopSequences: [`
800
+ ${t}:`]
801
+ };
802
+ }
803
+ function re(e) {
804
+ switch (e) {
805
+ case "stop":
806
+ return "stop";
807
+ case "length":
808
+ return "length";
809
+ case "content_filter":
810
+ return "content-filter";
811
+ case "function_call":
812
+ case "tool_calls":
813
+ return "tool-calls";
814
+ default:
815
+ return "other";
816
+ }
817
+ }
818
+ const ae = m({
819
+ /**
820
+ * Echo back the prompt in addition to the completion.
821
+ */
822
+ echo: he().optional(),
823
+ /**
824
+ * Modify the likelihood of specified tokens appearing in the completion.
825
+ *
826
+ * Accepts a JSON object that maps tokens (specified by their token ID in
827
+ * the GPT tokenizer) to an associated bias value from -100 to 100.
828
+ */
829
+ logitBias: Z(u(), _()).optional(),
830
+ /**
831
+ * The suffix that comes after a completion of inserted text.
832
+ */
833
+ suffix: u().optional(),
834
+ /**
835
+ * A unique identifier representing your end-user, which can help providers to
836
+ * monitor and detect abuse.
837
+ */
838
+ user: u().optional()
839
+ });
840
+ var Fe = class we {
841
+ static [z](t) {
842
+ return D({
843
+ modelId: t.modelId,
844
+ config: t.config
845
+ });
846
+ }
847
+ static [L](t) {
848
+ return new we(t.modelId, t.config);
849
+ }
850
+ constructor(t, o) {
851
+ this.specificationVersion = "v4", this.modelId = t, this.config = o;
852
+ const s = o.errorStructure ?? E;
853
+ this.chunkSchema = Ge(s.errorSchema), this.failedResponseHandler = H(s);
854
+ }
855
+ get provider() {
856
+ return this.config.provider;
857
+ }
858
+ get providerOptionsName() {
859
+ return this.config.provider.split(".")[0].trim();
860
+ }
861
+ get supportedUrls() {
862
+ return this.config.supportedUrls?.() ?? {};
863
+ }
864
+ async getArgs({ prompt: t, maxOutputTokens: o, temperature: s, topP: r, topK: i, frequencyPenalty: f, presencePenalty: d, stopSequences: c, responseFormat: a, seed: l, providerOptions: n, tools: p, toolChoice: x }) {
865
+ const y = [];
866
+ F({
867
+ rawName: this.providerOptionsName,
868
+ providerOptions: n,
869
+ warnings: y
870
+ });
871
+ const v = Object.assign(await T({
872
+ provider: this.providerOptionsName,
873
+ providerOptions: n,
874
+ schema: ae
875
+ }) ?? {}, await T({
876
+ provider: $(this.providerOptionsName),
877
+ providerOptions: n,
878
+ schema: ae
879
+ }) ?? {});
880
+ i != null && y.push({
881
+ type: "unsupported",
882
+ feature: "topK"
883
+ }), p?.length && y.push({
884
+ type: "unsupported",
885
+ feature: "tools"
886
+ }), x != null && y.push({
887
+ type: "unsupported",
888
+ feature: "toolChoice"
889
+ }), a != null && a.type !== "text" && y.push({
890
+ type: "unsupported",
891
+ feature: "responseFormat",
892
+ details: "JSON response format is not supported."
893
+ });
894
+ const { prompt: k, stopSequences: b } = We({ prompt: t }), O = [...b ?? [], ...c ?? []];
895
+ return {
896
+ args: {
897
+ model: this.modelId,
898
+ echo: v.echo,
899
+ logit_bias: v.logitBias,
900
+ suffix: v.suffix,
901
+ user: v.user,
902
+ max_tokens: o,
903
+ temperature: s,
904
+ top_p: r,
905
+ frequency_penalty: f,
906
+ presence_penalty: d,
907
+ seed: l,
908
+ ...n?.[this.providerOptionsName],
909
+ ...n?.[$(this.providerOptionsName)],
910
+ prompt: k,
911
+ stop: O.length > 0 ? O : void 0
912
+ },
913
+ warnings: y
914
+ };
915
+ }
916
+ async doGenerate(t) {
917
+ const { args: o, warnings: s } = await this.getArgs(t), { responseHeaders: r, value: i, rawValue: f } = await P({
918
+ url: this.config.url({
919
+ path: "/completions",
920
+ modelId: this.modelId
921
+ }),
922
+ headers: U(this.config.headers?.(), t.headers),
923
+ body: o,
924
+ failedResponseHandler: this.failedResponseHandler,
925
+ successfulResponseHandler: A(Je),
926
+ abortSignal: t.abortSignal,
927
+ fetch: this.config.fetch
928
+ }), d = i.choices[0], c = [];
929
+ return d.text != null && d.text.length > 0 && c.push({
930
+ type: "text",
931
+ text: d.text
932
+ }), {
933
+ content: c,
934
+ usage: se(i.usage),
935
+ finishReason: {
936
+ unified: re(d.finish_reason),
937
+ raw: d.finish_reason
938
+ },
939
+ request: { body: o },
940
+ response: {
941
+ ...Y(i),
942
+ headers: r,
943
+ body: f
944
+ },
945
+ warnings: s
946
+ };
947
+ }
948
+ async doStream(t) {
949
+ const { args: o, warnings: s } = await this.getArgs(t), r = {
950
+ ...o,
951
+ stream: !0,
952
+ stream_options: this.config.includeUsage ? { include_usage: !0 } : void 0
953
+ }, { responseHeaders: i, value: f } = await P({
954
+ url: this.config.url({
955
+ path: "/completions",
956
+ modelId: this.modelId
957
+ }),
958
+ headers: U(this.config.headers?.(), t.headers),
959
+ body: r,
960
+ failedResponseHandler: this.failedResponseHandler,
961
+ successfulResponseHandler: de(this.chunkSchema),
962
+ abortSignal: t.abortSignal,
963
+ fetch: this.config.fetch
964
+ });
965
+ let d = {
966
+ unified: "other",
967
+ raw: void 0
968
+ }, c, a = !0;
969
+ return {
970
+ stream: f.pipeThrough(new TransformStream({
971
+ start(l) {
972
+ l.enqueue({
973
+ type: "stream-start",
974
+ warnings: s
975
+ });
976
+ },
977
+ transform(l, n) {
978
+ if (t.includeRawChunks && n.enqueue({
979
+ type: "raw",
980
+ rawValue: l.rawValue
981
+ }), !l.success) {
982
+ d = {
983
+ unified: "error",
984
+ raw: void 0
985
+ }, n.enqueue({
986
+ type: "error",
987
+ error: l.error
988
+ });
989
+ return;
990
+ }
991
+ const p = l.value;
992
+ if ("error" in p) {
993
+ d = {
994
+ unified: "error",
995
+ raw: void 0
996
+ }, n.enqueue({
997
+ type: "error",
998
+ error: p.error
999
+ });
1000
+ return;
1001
+ }
1002
+ a && (a = !1, n.enqueue({
1003
+ type: "response-metadata",
1004
+ ...Y(p)
1005
+ }), n.enqueue({
1006
+ type: "text-start",
1007
+ id: "0"
1008
+ })), p.usage != null && (c = p.usage);
1009
+ const x = p.choices[0];
1010
+ x?.finish_reason != null && (d = {
1011
+ unified: re(x.finish_reason),
1012
+ raw: x.finish_reason ?? void 0
1013
+ }), x?.text != null && n.enqueue({
1014
+ type: "text-delta",
1015
+ id: "0",
1016
+ delta: x.text
1017
+ });
1018
+ },
1019
+ flush(l) {
1020
+ a || l.enqueue({
1021
+ type: "text-end",
1022
+ id: "0"
1023
+ }), l.enqueue({
1024
+ type: "finish",
1025
+ finishReason: d,
1026
+ usage: se(c)
1027
+ });
1028
+ }
1029
+ })),
1030
+ request: { body: r },
1031
+ response: { headers: i }
1032
+ };
1033
+ }
1034
+ };
1035
+ const _e = N({
1036
+ prompt_tokens: _(),
1037
+ completion_tokens: _(),
1038
+ total_tokens: _()
1039
+ }), Je = m({
1040
+ id: u().nullish(),
1041
+ created: _().nullish(),
1042
+ model: u().nullish(),
1043
+ choices: q(m({
1044
+ text: u(),
1045
+ finish_reason: u()
1046
+ })),
1047
+ usage: _e.nullish()
1048
+ }), Ge = (e) => W([m({
1049
+ id: u().nullish(),
1050
+ created: _().nullish(),
1051
+ model: u().nullish(),
1052
+ choices: q(m({
1053
+ text: u(),
1054
+ finish_reason: u().nullish(),
1055
+ index: _()
1056
+ })),
1057
+ usage: _e.nullish()
1058
+ }), e]), G = m({
1059
+ /**
1060
+ * The number of dimensions the resulting output embeddings should have.
1061
+ * Only supported in text-embedding-3 and later models.
1062
+ */
1063
+ dimensions: _().optional(),
1064
+ /**
1065
+ * A unique identifier representing your end-user, which can help providers to
1066
+ * monitor and detect abuse.
1067
+ */
1068
+ user: u().optional()
1069
+ });
1070
+ var Ye = class xe {
1071
+ get provider() {
1072
+ return this.config.provider;
1073
+ }
1074
+ get maxEmbeddingsPerCall() {
1075
+ return this.config.maxEmbeddingsPerCall ?? 2048;
1076
+ }
1077
+ get supportsParallelCalls() {
1078
+ return this.config.supportsParallelCalls ?? !0;
1079
+ }
1080
+ static [z](t) {
1081
+ return D({
1082
+ modelId: t.modelId,
1083
+ config: t.config
1084
+ });
1085
+ }
1086
+ static [L](t) {
1087
+ return new xe(t.modelId, t.config);
1088
+ }
1089
+ constructor(t, o) {
1090
+ this.specificationVersion = "v4", this.modelId = t, this.config = o;
1091
+ }
1092
+ get providerOptionsName() {
1093
+ return this.config.provider.split(".")[0].trim();
1094
+ }
1095
+ async doEmbed({ values: t, headers: o, abortSignal: s, providerOptions: r }) {
1096
+ const i = [], f = await T({
1097
+ provider: "openai-compatible",
1098
+ providerOptions: r,
1099
+ schema: G
1100
+ });
1101
+ f != null && i.push({
1102
+ type: "deprecated",
1103
+ setting: "providerOptions key 'openai-compatible'",
1104
+ message: "Use 'openaiCompatible' instead."
1105
+ }), F({
1106
+ rawName: this.providerOptionsName,
1107
+ providerOptions: r,
1108
+ warnings: i
1109
+ });
1110
+ const d = Object.assign(f ?? {}, await T({
1111
+ provider: "openaiCompatible",
1112
+ providerOptions: r,
1113
+ schema: G
1114
+ }) ?? {}, await T({
1115
+ provider: this.providerOptionsName,
1116
+ providerOptions: r,
1117
+ schema: G
1118
+ }) ?? {});
1119
+ if (t.length > this.maxEmbeddingsPerCall) throw new qe({
1120
+ provider: this.provider,
1121
+ modelId: this.modelId,
1122
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
1123
+ values: t
1124
+ });
1125
+ const { responseHeaders: c, value: a, rawValue: l } = await P({
1126
+ url: this.config.url({
1127
+ path: "/embeddings",
1128
+ modelId: this.modelId
1129
+ }),
1130
+ headers: U(this.config.headers?.(), o),
1131
+ body: {
1132
+ model: this.modelId,
1133
+ input: t,
1134
+ encoding_format: "float",
1135
+ dimensions: d.dimensions,
1136
+ user: d.user
1137
+ },
1138
+ failedResponseHandler: H(this.config.errorStructure ?? E),
1139
+ successfulResponseHandler: A(Ze),
1140
+ abortSignal: s,
1141
+ fetch: this.config.fetch
1142
+ });
1143
+ return {
1144
+ warnings: i,
1145
+ embeddings: a.data.map((n) => n.embedding),
1146
+ usage: a.usage ? { tokens: a.usage.prompt_tokens } : void 0,
1147
+ providerMetadata: a.providerMetadata,
1148
+ response: {
1149
+ headers: c,
1150
+ body: l
1151
+ }
1152
+ };
1153
+ }
1154
+ };
1155
+ const Ze = m({
1156
+ data: q(m({ embedding: q(_()) })),
1157
+ usage: m({ prompt_tokens: _() }).nullish(),
1158
+ providerMetadata: Z(u(), Z(u(), pe())).optional()
1159
+ });
1160
+ var Qe = class be {
1161
+ get provider() {
1162
+ return this.config.provider;
1163
+ }
1164
+ /**
1165
+ * The provider options key used to extract provider-specific options.
1166
+ */
1167
+ get providerOptionsKey() {
1168
+ return this.config.provider.split(".")[0].trim();
1169
+ }
1170
+ static [z](t) {
1171
+ return D({
1172
+ modelId: t.modelId,
1173
+ config: t.config
1174
+ });
1175
+ }
1176
+ static [L](t) {
1177
+ return new be(t.modelId, t.config);
1178
+ }
1179
+ constructor(t, o) {
1180
+ this.modelId = t, this.config = o, this.specificationVersion = "v4", this.maxImagesPerCall = 10, this.supportsFileInputs = void 0, this.supportsMaskInputs = void 0;
1181
+ }
1182
+ getArgs(t, o) {
1183
+ return F({
1184
+ rawName: this.providerOptionsKey,
1185
+ providerOptions: t,
1186
+ warnings: o
1187
+ }), {
1188
+ ...t[this.providerOptionsKey],
1189
+ ...t[$(this.providerOptionsKey)]
1190
+ };
1191
+ }
1192
+ async doGenerate({ prompt: t, n: o, size: s, aspectRatio: r, seed: i, providerOptions: f, headers: d, abortSignal: c, files: a, mask: l }) {
1193
+ const n = [];
1194
+ r != null && n.push({
1195
+ type: "unsupported",
1196
+ feature: "aspectRatio",
1197
+ details: "This model does not support aspect ratio. Use `size` instead."
1198
+ }), i != null && n.push({
1199
+ type: "unsupported",
1200
+ feature: "seed"
1201
+ });
1202
+ const p = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date(), x = this.getArgs(f, n);
1203
+ if (a != null && a.length > 0) {
1204
+ const { value: k, responseHeaders: b } = await Re({
1205
+ url: this.config.url({
1206
+ path: "/images/edits",
1207
+ modelId: this.modelId
1208
+ }),
1209
+ headers: U(this.config.headers?.(), d),
1210
+ formData: Te({
1211
+ model: this.modelId,
1212
+ prompt: t,
1213
+ image: await Promise.all(a.map((O) => ue(O))),
1214
+ mask: l != null ? await ue(l) : void 0,
1215
+ n: o,
1216
+ size: s,
1217
+ ...x
1218
+ }),
1219
+ failedResponseHandler: H(this.config.errorStructure ?? E),
1220
+ successfulResponseHandler: A(le),
1221
+ abortSignal: c,
1222
+ fetch: this.config.fetch
1223
+ });
1224
+ return {
1225
+ images: k.data.map((O) => O.b64_json),
1226
+ warnings: n,
1227
+ usage: ie(k.usage),
1228
+ response: {
1229
+ timestamp: p,
1230
+ modelId: this.modelId,
1231
+ headers: b
1232
+ }
1233
+ };
1234
+ }
1235
+ const { value: y, responseHeaders: v } = await P({
1236
+ url: this.config.url({
1237
+ path: "/images/generations",
1238
+ modelId: this.modelId
1239
+ }),
1240
+ headers: U(this.config.headers?.(), d),
1241
+ body: {
1242
+ model: this.modelId,
1243
+ prompt: t,
1244
+ n: o,
1245
+ size: s,
1246
+ ...x
1247
+ },
1248
+ failedResponseHandler: H(this.config.errorStructure ?? E),
1249
+ successfulResponseHandler: A(le),
1250
+ abortSignal: c,
1251
+ fetch: this.config.fetch
1252
+ });
1253
+ return {
1254
+ images: y.data.map((k) => k.b64_json),
1255
+ warnings: n,
1256
+ usage: ie(y.usage),
1257
+ response: {
1258
+ timestamp: p,
1259
+ modelId: this.modelId,
1260
+ headers: v
1261
+ }
1262
+ };
1263
+ }
1264
+ };
1265
+ function ie(e) {
1266
+ return e == null ? void 0 : {
1267
+ inputTokens: e.input_tokens ?? void 0,
1268
+ outputTokens: e.output_tokens ?? void 0,
1269
+ totalTokens: e.total_tokens ?? void 0
1270
+ };
1271
+ }
1272
+ const le = m({
1273
+ data: q(m({ b64_json: u() })),
1274
+ usage: m({
1275
+ input_tokens: _().nullish(),
1276
+ output_tokens: _().nullish(),
1277
+ total_tokens: _().nullish()
1278
+ }).nullish()
1279
+ });
1280
+ async function ue(e) {
1281
+ if (e.type === "url") return Ue(e.url);
1282
+ const t = e.data instanceof Uint8Array ? e.data : ge(e.data);
1283
+ return new Blob([t], { type: e.mediaType });
1284
+ }
1285
+ const Xe = "3.0.62";
1286
+ function tt(e) {
1287
+ const t = Oe(e.baseURL), o = e.name, s = {
1288
+ ...e.apiKey && { Authorization: `Bearer ${e.apiKey}` },
1289
+ ...e.headers
1290
+ }, r = () => Se(s, `ai-sdk-openai-compatible/${Xe}`), i = (p) => ({
1291
+ provider: `${o}.${p}`,
1292
+ url: ({ path: x }) => {
1293
+ const y = new URL(`${t}${x}`);
1294
+ return e.queryParams && (y.search = new URLSearchParams(e.queryParams).toString()), y.toString();
1295
+ },
1296
+ headers: r,
1297
+ fetch: e.fetch
1298
+ }), f = (p) => d(p), d = (p) => new Be(p, {
1299
+ ...i("chat"),
1300
+ includeUsage: e.includeUsage,
1301
+ supportsStructuredOutputs: e.supportsStructuredOutputs,
1302
+ supportsMultiPartToolContent: e.supportsMultiPartToolContent,
1303
+ supportedUrls: e.supportedUrls,
1304
+ transformRequestBody: e.transformRequestBody,
1305
+ metadataExtractor: e.metadataExtractor,
1306
+ convertUsage: e.convertUsage
1307
+ }), c = (p) => new Fe(p, {
1308
+ ...i("completion"),
1309
+ includeUsage: e.includeUsage
1310
+ }), a = (p) => new Ye(p, { ...i("embedding") }), l = (p) => new Qe(p, i("image")), n = (p) => f(p);
1311
+ return n.specificationVersion = "v4", n.languageModel = f, n.chatModel = d, n.completionModel = c, n.embeddingModel = a, n.textEmbeddingModel = a, n.imageModel = l, n;
1312
+ }
1313
+ export {
1314
+ Be as OpenAICompatibleChatLanguageModel,
1315
+ Fe as OpenAICompatibleCompletionLanguageModel,
1316
+ Ye as OpenAICompatibleEmbeddingModel,
1317
+ Qe as OpenAICompatibleImageModel,
1318
+ Xe as VERSION,
1319
+ tt as createOpenAICompatible
1320
+ };