release-note 0.0.3 → 0.0.5

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