@ai-sdk/openai 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,823 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ OpenAI: () => OpenAI,
24
+ createOpenAI: () => createOpenAI,
25
+ openai: () => openai
26
+ });
27
+ module.exports = __toCommonJS(src_exports);
28
+
29
+ // src/openai-facade.ts
30
+ var import_provider_utils5 = require("@ai-sdk/provider-utils");
31
+
32
+ // src/openai-chat-language-model.ts
33
+ var import_provider = require("@ai-sdk/provider");
34
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
35
+ var import_zod2 = require("zod");
36
+
37
+ // src/convert-to-openai-chat-messages.ts
38
+ var import_provider_utils = require("@ai-sdk/provider-utils");
39
+ function convertToOpenAIChatMessages(prompt) {
40
+ const messages = [];
41
+ for (const { role, content } of prompt) {
42
+ switch (role) {
43
+ case "system": {
44
+ messages.push({ role: "system", content });
45
+ break;
46
+ }
47
+ case "user": {
48
+ messages.push({
49
+ role: "user",
50
+ content: content.map((part) => {
51
+ var _a;
52
+ switch (part.type) {
53
+ case "text": {
54
+ return { type: "text", text: part.text };
55
+ }
56
+ case "image": {
57
+ return {
58
+ type: "image_url",
59
+ image_url: {
60
+ url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${(0, import_provider_utils.convertUint8ArrayToBase64)(part.image)}`
61
+ }
62
+ };
63
+ }
64
+ }
65
+ })
66
+ });
67
+ break;
68
+ }
69
+ case "assistant": {
70
+ let text = "";
71
+ const toolCalls = [];
72
+ for (const part of content) {
73
+ switch (part.type) {
74
+ case "text": {
75
+ text += part.text;
76
+ break;
77
+ }
78
+ case "tool-call": {
79
+ toolCalls.push({
80
+ id: part.toolCallId,
81
+ type: "function",
82
+ function: {
83
+ name: part.toolName,
84
+ arguments: JSON.stringify(part.args)
85
+ }
86
+ });
87
+ break;
88
+ }
89
+ default: {
90
+ const _exhaustiveCheck = part;
91
+ throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
92
+ }
93
+ }
94
+ }
95
+ messages.push({
96
+ role: "assistant",
97
+ content: text,
98
+ tool_calls: toolCalls.length > 0 ? toolCalls : void 0
99
+ });
100
+ break;
101
+ }
102
+ case "tool": {
103
+ for (const toolResponse of content) {
104
+ messages.push({
105
+ role: "tool",
106
+ tool_call_id: toolResponse.toolCallId,
107
+ content: JSON.stringify(toolResponse.result)
108
+ });
109
+ }
110
+ break;
111
+ }
112
+ default: {
113
+ const _exhaustiveCheck = role;
114
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
115
+ }
116
+ }
117
+ }
118
+ return messages;
119
+ }
120
+
121
+ // src/map-openai-finish-reason.ts
122
+ function mapOpenAIFinishReason(finishReason) {
123
+ switch (finishReason) {
124
+ case "stop":
125
+ return "stop";
126
+ case "length":
127
+ return "length";
128
+ case "content_filter":
129
+ return "content-filter";
130
+ case "function_call":
131
+ case "tool_calls":
132
+ return "tool-calls";
133
+ default:
134
+ return "other";
135
+ }
136
+ }
137
+
138
+ // src/openai-error.ts
139
+ var import_zod = require("zod");
140
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
141
+ var openAIErrorDataSchema = import_zod.z.object({
142
+ error: import_zod.z.object({
143
+ message: import_zod.z.string(),
144
+ type: import_zod.z.string(),
145
+ param: import_zod.z.any().nullable(),
146
+ code: import_zod.z.string().nullable()
147
+ })
148
+ });
149
+ var openaiFailedResponseHandler = (0, import_provider_utils2.createJsonErrorResponseHandler)({
150
+ errorSchema: openAIErrorDataSchema,
151
+ errorToMessage: (data) => data.error.message
152
+ });
153
+
154
+ // src/openai-chat-language-model.ts
155
+ var OpenAIChatLanguageModel = class {
156
+ constructor(modelId, settings, config) {
157
+ this.specificationVersion = "v1";
158
+ this.defaultObjectGenerationMode = "tool";
159
+ this.modelId = modelId;
160
+ this.settings = settings;
161
+ this.config = config;
162
+ }
163
+ get provider() {
164
+ return this.config.provider;
165
+ }
166
+ getArgs({
167
+ mode,
168
+ prompt,
169
+ maxTokens,
170
+ temperature,
171
+ topP,
172
+ frequencyPenalty,
173
+ presencePenalty,
174
+ seed
175
+ }) {
176
+ var _a;
177
+ const type = mode.type;
178
+ const baseArgs = {
179
+ // model id:
180
+ model: this.modelId,
181
+ // model specific settings:
182
+ logit_bias: this.settings.logitBias,
183
+ user: this.settings.user,
184
+ // standardized settings:
185
+ max_tokens: maxTokens,
186
+ temperature: (0, import_provider_utils3.scale)({
187
+ value: temperature,
188
+ outputMin: 0,
189
+ outputMax: 2
190
+ }),
191
+ top_p: topP,
192
+ frequency_penalty: (0, import_provider_utils3.scale)({
193
+ value: frequencyPenalty,
194
+ inputMin: -1,
195
+ inputMax: 1,
196
+ outputMin: -2,
197
+ outputMax: 2
198
+ }),
199
+ presence_penalty: (0, import_provider_utils3.scale)({
200
+ value: presencePenalty,
201
+ inputMin: -1,
202
+ inputMax: 1,
203
+ outputMin: -2,
204
+ outputMax: 2
205
+ }),
206
+ seed,
207
+ // messages:
208
+ messages: convertToOpenAIChatMessages(prompt)
209
+ };
210
+ switch (type) {
211
+ case "regular": {
212
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
213
+ return {
214
+ ...baseArgs,
215
+ tools: tools == null ? void 0 : tools.map((tool) => ({
216
+ type: "function",
217
+ function: {
218
+ name: tool.name,
219
+ description: tool.description,
220
+ parameters: tool.parameters
221
+ }
222
+ }))
223
+ };
224
+ }
225
+ case "object-json": {
226
+ return {
227
+ ...baseArgs,
228
+ response_format: { type: "json_object" }
229
+ };
230
+ }
231
+ case "object-tool": {
232
+ return {
233
+ ...baseArgs,
234
+ tool_choice: { type: "function", function: { name: mode.tool.name } },
235
+ tools: [
236
+ {
237
+ type: "function",
238
+ function: {
239
+ name: mode.tool.name,
240
+ description: mode.tool.description,
241
+ parameters: mode.tool.parameters
242
+ }
243
+ }
244
+ ]
245
+ };
246
+ }
247
+ case "object-grammar": {
248
+ throw new import_provider.UnsupportedFunctionalityError({
249
+ functionality: "object-grammar mode"
250
+ });
251
+ }
252
+ default: {
253
+ const _exhaustiveCheck = type;
254
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
255
+ }
256
+ }
257
+ }
258
+ async doGenerate(options) {
259
+ var _a, _b;
260
+ const args = this.getArgs(options);
261
+ const response = await (0, import_provider_utils3.postJsonToApi)({
262
+ url: `${this.config.baseURL}/chat/completions`,
263
+ headers: this.config.headers(),
264
+ body: args,
265
+ failedResponseHandler: openaiFailedResponseHandler,
266
+ successfulResponseHandler: (0, import_provider_utils3.createJsonResponseHandler)(
267
+ openAIChatResponseSchema
268
+ ),
269
+ abortSignal: options.abortSignal
270
+ });
271
+ const { messages: rawPrompt, ...rawSettings } = args;
272
+ const choice = response.choices[0];
273
+ return {
274
+ text: (_a = choice.message.content) != null ? _a : void 0,
275
+ toolCalls: (_b = choice.message.tool_calls) == null ? void 0 : _b.map((toolCall) => ({
276
+ toolCallType: "function",
277
+ toolCallId: toolCall.id,
278
+ toolName: toolCall.function.name,
279
+ args: toolCall.function.arguments
280
+ })),
281
+ finishReason: mapOpenAIFinishReason(choice.finish_reason),
282
+ usage: {
283
+ promptTokens: response.usage.prompt_tokens,
284
+ completionTokens: response.usage.completion_tokens
285
+ },
286
+ rawCall: { rawPrompt, rawSettings },
287
+ warnings: []
288
+ };
289
+ }
290
+ async doStream(options) {
291
+ const args = this.getArgs(options);
292
+ const response = await (0, import_provider_utils3.postJsonToApi)({
293
+ url: `${this.config.baseURL}/chat/completions`,
294
+ headers: this.config.headers(),
295
+ body: {
296
+ ...args,
297
+ stream: true
298
+ },
299
+ failedResponseHandler: openaiFailedResponseHandler,
300
+ successfulResponseHandler: (0, import_provider_utils3.createEventSourceResponseHandler)(
301
+ openaiChatChunkSchema
302
+ ),
303
+ abortSignal: options.abortSignal
304
+ });
305
+ const { messages: rawPrompt, ...rawSettings } = args;
306
+ const toolCalls = [];
307
+ let finishReason = "other";
308
+ let usage = {
309
+ promptTokens: Number.NaN,
310
+ completionTokens: Number.NaN
311
+ };
312
+ return {
313
+ stream: response.pipeThrough(
314
+ new TransformStream({
315
+ transform(chunk, controller) {
316
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
317
+ if (!chunk.success) {
318
+ controller.enqueue({ type: "error", error: chunk.error });
319
+ return;
320
+ }
321
+ const value = chunk.value;
322
+ if (value.usage != null) {
323
+ usage = {
324
+ promptTokens: value.usage.prompt_tokens,
325
+ completionTokens: value.usage.completion_tokens
326
+ };
327
+ }
328
+ const choice = value.choices[0];
329
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
330
+ finishReason = mapOpenAIFinishReason(choice.finish_reason);
331
+ }
332
+ if ((choice == null ? void 0 : choice.delta) == null) {
333
+ return;
334
+ }
335
+ const delta = choice.delta;
336
+ if (delta.content != null) {
337
+ controller.enqueue({
338
+ type: "text-delta",
339
+ textDelta: delta.content
340
+ });
341
+ }
342
+ if (delta.tool_calls != null) {
343
+ for (const toolCallDelta of delta.tool_calls) {
344
+ const index = toolCallDelta.index;
345
+ if (toolCalls[index] == null) {
346
+ if (toolCallDelta.type !== "function") {
347
+ throw new import_provider.InvalidResponseDataError({
348
+ data: toolCallDelta,
349
+ message: `Expected 'function' type.`
350
+ });
351
+ }
352
+ if (toolCallDelta.id == null) {
353
+ throw new import_provider.InvalidResponseDataError({
354
+ data: toolCallDelta,
355
+ message: `Expected 'id' to be a string.`
356
+ });
357
+ }
358
+ if (((_a = toolCallDelta.function) == null ? void 0 : _a.name) == null) {
359
+ throw new import_provider.InvalidResponseDataError({
360
+ data: toolCallDelta,
361
+ message: `Expected 'function.name' to be a string.`
362
+ });
363
+ }
364
+ toolCalls[index] = {
365
+ id: toolCallDelta.id,
366
+ type: "function",
367
+ function: {
368
+ name: toolCallDelta.function.name,
369
+ arguments: (_b = toolCallDelta.function.arguments) != null ? _b : ""
370
+ }
371
+ };
372
+ continue;
373
+ }
374
+ const toolCall = toolCalls[index];
375
+ if (((_c = toolCallDelta.function) == null ? void 0 : _c.arguments) != null) {
376
+ toolCall.function.arguments += (_e = (_d = toolCallDelta.function) == null ? void 0 : _d.arguments) != null ? _e : "";
377
+ }
378
+ controller.enqueue({
379
+ type: "tool-call-delta",
380
+ toolCallType: "function",
381
+ toolCallId: toolCall.id,
382
+ toolName: toolCall.function.name,
383
+ argsTextDelta: (_f = toolCallDelta.function.arguments) != null ? _f : ""
384
+ });
385
+ if (((_g = toolCall.function) == null ? void 0 : _g.name) == null || ((_h = toolCall.function) == null ? void 0 : _h.arguments) == null || !(0, import_provider_utils3.isParseableJson)(toolCall.function.arguments)) {
386
+ continue;
387
+ }
388
+ controller.enqueue({
389
+ type: "tool-call",
390
+ toolCallType: "function",
391
+ toolCallId: (_i = toolCall.id) != null ? _i : (0, import_provider_utils3.generateId)(),
392
+ toolName: toolCall.function.name,
393
+ args: toolCall.function.arguments
394
+ });
395
+ }
396
+ }
397
+ },
398
+ flush(controller) {
399
+ controller.enqueue({ type: "finish", finishReason, usage });
400
+ }
401
+ })
402
+ ),
403
+ rawCall: { rawPrompt, rawSettings },
404
+ warnings: []
405
+ };
406
+ }
407
+ };
408
+ var openAIChatResponseSchema = import_zod2.z.object({
409
+ choices: import_zod2.z.array(
410
+ import_zod2.z.object({
411
+ message: import_zod2.z.object({
412
+ role: import_zod2.z.literal("assistant"),
413
+ content: import_zod2.z.string().nullable(),
414
+ tool_calls: import_zod2.z.array(
415
+ import_zod2.z.object({
416
+ id: import_zod2.z.string(),
417
+ type: import_zod2.z.literal("function"),
418
+ function: import_zod2.z.object({
419
+ name: import_zod2.z.string(),
420
+ arguments: import_zod2.z.string()
421
+ })
422
+ })
423
+ ).optional()
424
+ }),
425
+ index: import_zod2.z.number(),
426
+ finish_reason: import_zod2.z.string().optional().nullable()
427
+ })
428
+ ),
429
+ object: import_zod2.z.literal("chat.completion"),
430
+ usage: import_zod2.z.object({
431
+ prompt_tokens: import_zod2.z.number(),
432
+ completion_tokens: import_zod2.z.number()
433
+ })
434
+ });
435
+ var openaiChatChunkSchema = import_zod2.z.object({
436
+ object: import_zod2.z.enum([
437
+ "chat.completion.chunk",
438
+ "chat.completion"
439
+ // support for OpenAI-compatible providers such as Perplexity
440
+ ]),
441
+ choices: import_zod2.z.array(
442
+ import_zod2.z.object({
443
+ delta: import_zod2.z.object({
444
+ role: import_zod2.z.enum(["assistant"]).optional(),
445
+ content: import_zod2.z.string().nullable().optional(),
446
+ tool_calls: import_zod2.z.array(
447
+ import_zod2.z.object({
448
+ index: import_zod2.z.number(),
449
+ id: import_zod2.z.string().optional(),
450
+ type: import_zod2.z.literal("function").optional(),
451
+ function: import_zod2.z.object({
452
+ name: import_zod2.z.string().optional(),
453
+ arguments: import_zod2.z.string().optional()
454
+ })
455
+ })
456
+ ).optional()
457
+ }),
458
+ finish_reason: import_zod2.z.string().nullable().optional(),
459
+ index: import_zod2.z.number()
460
+ })
461
+ ),
462
+ usage: import_zod2.z.object({
463
+ prompt_tokens: import_zod2.z.number(),
464
+ completion_tokens: import_zod2.z.number()
465
+ }).optional().nullable()
466
+ });
467
+
468
+ // src/openai-completion-language-model.ts
469
+ var import_provider3 = require("@ai-sdk/provider");
470
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
471
+ var import_zod3 = require("zod");
472
+
473
+ // src/convert-to-openai-completion-prompt.ts
474
+ var import_provider2 = require("@ai-sdk/provider");
475
+ function convertToOpenAICompletionPrompt({
476
+ prompt,
477
+ inputFormat,
478
+ user = "user",
479
+ assistant = "assistant"
480
+ }) {
481
+ if (inputFormat === "prompt" && prompt.length === 1 && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0].type === "text") {
482
+ return { prompt: prompt[0].content[0].text };
483
+ }
484
+ let text = "";
485
+ if (prompt[0].role === "system") {
486
+ text += `${prompt[0].content}
487
+
488
+ `;
489
+ prompt = prompt.slice(1);
490
+ }
491
+ for (const { role, content } of prompt) {
492
+ switch (role) {
493
+ case "system": {
494
+ throw new import_provider2.InvalidPromptError({
495
+ message: "Unexpected system message in prompt: ${content}",
496
+ prompt
497
+ });
498
+ }
499
+ case "user": {
500
+ const userMessage = content.map((part) => {
501
+ switch (part.type) {
502
+ case "text": {
503
+ return part.text;
504
+ }
505
+ case "image": {
506
+ throw new import_provider2.UnsupportedFunctionalityError({
507
+ functionality: "images"
508
+ });
509
+ }
510
+ }
511
+ }).join("");
512
+ text += `${user}:
513
+ ${userMessage}
514
+
515
+ `;
516
+ break;
517
+ }
518
+ case "assistant": {
519
+ const assistantMessage = content.map((part) => {
520
+ switch (part.type) {
521
+ case "text": {
522
+ return part.text;
523
+ }
524
+ case "tool-call": {
525
+ throw new import_provider2.UnsupportedFunctionalityError({
526
+ functionality: "tool-call messages"
527
+ });
528
+ }
529
+ }
530
+ }).join("");
531
+ text += `${assistant}:
532
+ ${assistantMessage}
533
+
534
+ `;
535
+ break;
536
+ }
537
+ case "tool": {
538
+ throw new import_provider2.UnsupportedFunctionalityError({
539
+ functionality: "tool messages"
540
+ });
541
+ }
542
+ default: {
543
+ const _exhaustiveCheck = role;
544
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
545
+ }
546
+ }
547
+ }
548
+ text += `${assistant}:
549
+ `;
550
+ return {
551
+ prompt: text,
552
+ stopSequences: [`
553
+ ${user}:`]
554
+ };
555
+ }
556
+
557
+ // src/openai-completion-language-model.ts
558
+ var OpenAICompletionLanguageModel = class {
559
+ constructor(modelId, settings, config) {
560
+ this.specificationVersion = "v1";
561
+ this.defaultObjectGenerationMode = void 0;
562
+ this.modelId = modelId;
563
+ this.settings = settings;
564
+ this.config = config;
565
+ }
566
+ get provider() {
567
+ return this.config.provider;
568
+ }
569
+ getArgs({
570
+ mode,
571
+ inputFormat,
572
+ prompt,
573
+ maxTokens,
574
+ temperature,
575
+ topP,
576
+ frequencyPenalty,
577
+ presencePenalty,
578
+ seed
579
+ }) {
580
+ var _a;
581
+ const type = mode.type;
582
+ const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt, inputFormat });
583
+ const baseArgs = {
584
+ // model id:
585
+ model: this.modelId,
586
+ // model specific settings:
587
+ echo: this.settings.echo,
588
+ logit_bias: this.settings.logitBias,
589
+ suffix: this.settings.suffix,
590
+ user: this.settings.user,
591
+ // standardized settings:
592
+ max_tokens: maxTokens,
593
+ temperature: (0, import_provider_utils4.scale)({
594
+ value: temperature,
595
+ outputMin: 0,
596
+ outputMax: 2
597
+ }),
598
+ top_p: topP,
599
+ frequency_penalty: (0, import_provider_utils4.scale)({
600
+ value: frequencyPenalty,
601
+ inputMin: -1,
602
+ inputMax: 1,
603
+ outputMin: -2,
604
+ outputMax: 2
605
+ }),
606
+ presence_penalty: (0, import_provider_utils4.scale)({
607
+ value: presencePenalty,
608
+ inputMin: -1,
609
+ inputMax: 1,
610
+ outputMin: -2,
611
+ outputMax: 2
612
+ }),
613
+ seed,
614
+ // prompt:
615
+ prompt: completionPrompt,
616
+ // stop sequences:
617
+ stop: stopSequences
618
+ };
619
+ switch (type) {
620
+ case "regular": {
621
+ if ((_a = mode.tools) == null ? void 0 : _a.length) {
622
+ throw new import_provider3.UnsupportedFunctionalityError({
623
+ functionality: "tools"
624
+ });
625
+ }
626
+ return baseArgs;
627
+ }
628
+ case "object-json": {
629
+ throw new import_provider3.UnsupportedFunctionalityError({
630
+ functionality: "object-json mode"
631
+ });
632
+ }
633
+ case "object-tool": {
634
+ throw new import_provider3.UnsupportedFunctionalityError({
635
+ functionality: "object-tool mode"
636
+ });
637
+ }
638
+ case "object-grammar": {
639
+ throw new import_provider3.UnsupportedFunctionalityError({
640
+ functionality: "object-grammar mode"
641
+ });
642
+ }
643
+ default: {
644
+ const _exhaustiveCheck = type;
645
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
646
+ }
647
+ }
648
+ }
649
+ async doGenerate(options) {
650
+ const args = this.getArgs(options);
651
+ const response = await (0, import_provider_utils4.postJsonToApi)({
652
+ url: `${this.config.baseURL}/completions`,
653
+ headers: this.config.headers(),
654
+ body: args,
655
+ failedResponseHandler: openaiFailedResponseHandler,
656
+ successfulResponseHandler: (0, import_provider_utils4.createJsonResponseHandler)(
657
+ openAICompletionResponseSchema
658
+ ),
659
+ abortSignal: options.abortSignal
660
+ });
661
+ const { prompt: rawPrompt, ...rawSettings } = args;
662
+ const choice = response.choices[0];
663
+ return {
664
+ text: choice.text,
665
+ usage: {
666
+ promptTokens: response.usage.prompt_tokens,
667
+ completionTokens: response.usage.completion_tokens
668
+ },
669
+ finishReason: mapOpenAIFinishReason(choice.finish_reason),
670
+ rawCall: { rawPrompt, rawSettings },
671
+ warnings: []
672
+ };
673
+ }
674
+ async doStream(options) {
675
+ const args = this.getArgs(options);
676
+ const response = await (0, import_provider_utils4.postJsonToApi)({
677
+ url: `${this.config.baseURL}/completions`,
678
+ headers: this.config.headers(),
679
+ body: {
680
+ ...this.getArgs(options),
681
+ stream: true
682
+ },
683
+ failedResponseHandler: openaiFailedResponseHandler,
684
+ successfulResponseHandler: (0, import_provider_utils4.createEventSourceResponseHandler)(
685
+ openaiCompletionChunkSchema
686
+ ),
687
+ abortSignal: options.abortSignal
688
+ });
689
+ const { prompt: rawPrompt, ...rawSettings } = args;
690
+ let finishReason = "other";
691
+ let usage = {
692
+ promptTokens: Number.NaN,
693
+ completionTokens: Number.NaN
694
+ };
695
+ return {
696
+ stream: response.pipeThrough(
697
+ new TransformStream({
698
+ transform(chunk, controller) {
699
+ if (!chunk.success) {
700
+ controller.enqueue({ type: "error", error: chunk.error });
701
+ return;
702
+ }
703
+ const value = chunk.value;
704
+ if (value.usage != null) {
705
+ usage = {
706
+ promptTokens: value.usage.prompt_tokens,
707
+ completionTokens: value.usage.completion_tokens
708
+ };
709
+ }
710
+ const choice = value.choices[0];
711
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
712
+ finishReason = mapOpenAIFinishReason(choice.finish_reason);
713
+ }
714
+ if ((choice == null ? void 0 : choice.text) != null) {
715
+ controller.enqueue({
716
+ type: "text-delta",
717
+ textDelta: choice.text
718
+ });
719
+ }
720
+ },
721
+ flush(controller) {
722
+ controller.enqueue({ type: "finish", finishReason, usage });
723
+ }
724
+ })
725
+ ),
726
+ rawCall: { rawPrompt, rawSettings },
727
+ warnings: []
728
+ };
729
+ }
730
+ };
731
+ var openAICompletionResponseSchema = import_zod3.z.object({
732
+ choices: import_zod3.z.array(
733
+ import_zod3.z.object({
734
+ text: import_zod3.z.string(),
735
+ finish_reason: import_zod3.z.string()
736
+ })
737
+ ),
738
+ usage: import_zod3.z.object({
739
+ prompt_tokens: import_zod3.z.number(),
740
+ completion_tokens: import_zod3.z.number()
741
+ })
742
+ });
743
+ var openaiCompletionChunkSchema = import_zod3.z.object({
744
+ object: import_zod3.z.literal("text_completion"),
745
+ choices: import_zod3.z.array(
746
+ import_zod3.z.object({
747
+ text: import_zod3.z.string(),
748
+ finish_reason: import_zod3.z.enum(["stop", "length", "content_filter"]).optional().nullable(),
749
+ index: import_zod3.z.number()
750
+ })
751
+ ),
752
+ usage: import_zod3.z.object({
753
+ prompt_tokens: import_zod3.z.number(),
754
+ completion_tokens: import_zod3.z.number()
755
+ }).optional().nullable()
756
+ });
757
+
758
+ // src/openai-facade.ts
759
+ var OpenAI = class {
760
+ /**
761
+ * Creates a new OpenAI provider instance.
762
+ */
763
+ constructor(options = {}) {
764
+ var _a, _b;
765
+ this.baseURL = (_b = (0, import_provider_utils5.withoutTrailingSlash)((_a = options.baseURL) != null ? _a : options.baseUrl)) != null ? _b : "https://api.openai.com/v1";
766
+ this.apiKey = options.apiKey;
767
+ this.organization = options.organization;
768
+ }
769
+ get baseConfig() {
770
+ return {
771
+ organization: this.organization,
772
+ baseURL: this.baseURL,
773
+ headers: () => ({
774
+ Authorization: `Bearer ${(0, import_provider_utils5.loadApiKey)({
775
+ apiKey: this.apiKey,
776
+ environmentVariableName: "OPENAI_API_KEY",
777
+ description: "OpenAI"
778
+ })}`,
779
+ "OpenAI-Organization": this.organization
780
+ })
781
+ };
782
+ }
783
+ chat(modelId, settings = {}) {
784
+ return new OpenAIChatLanguageModel(modelId, settings, {
785
+ provider: "openai.chat",
786
+ ...this.baseConfig
787
+ });
788
+ }
789
+ completion(modelId, settings = {}) {
790
+ return new OpenAICompletionLanguageModel(modelId, settings, {
791
+ provider: "openai.completion",
792
+ ...this.baseConfig
793
+ });
794
+ }
795
+ };
796
+
797
+ // src/openai-provider.ts
798
+ function createOpenAI(options = {}) {
799
+ const openai2 = new OpenAI(options);
800
+ const provider = function(modelId, settings) {
801
+ if (new.target) {
802
+ throw new Error(
803
+ "The OpenAI model function cannot be called with the new keyword."
804
+ );
805
+ }
806
+ if (modelId === "gpt-3.5-turbo-instruct") {
807
+ return openai2.completion(modelId, settings);
808
+ } else {
809
+ return openai2.chat(modelId, settings);
810
+ }
811
+ };
812
+ provider.chat = openai2.chat.bind(openai2);
813
+ provider.completion = openai2.completion.bind(openai2);
814
+ return provider;
815
+ }
816
+ var openai = createOpenAI();
817
+ // Annotate the CommonJS export names for ESM import in node:
818
+ 0 && (module.exports = {
819
+ OpenAI,
820
+ createOpenAI,
821
+ openai
822
+ });
823
+ //# sourceMappingURL=index.js.map