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