@ai-sdk/openai 0.0.0

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,786 @@
1
+ // src/openai-facade.ts
2
+ import { loadApiKey } 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.literal("chat.completion.chunk"),
419
+ choices: z2.array(
420
+ z2.object({
421
+ delta: z2.object({
422
+ role: z2.enum(["assistant"]).optional(),
423
+ content: z2.string().nullable().optional(),
424
+ tool_calls: z2.array(
425
+ z2.object({
426
+ index: z2.number(),
427
+ id: z2.string().optional(),
428
+ type: z2.literal("function").optional(),
429
+ function: z2.object({
430
+ name: z2.string().optional(),
431
+ arguments: z2.string().optional()
432
+ })
433
+ })
434
+ ).optional()
435
+ }),
436
+ finish_reason: z2.string().nullable().optional(),
437
+ index: z2.number()
438
+ })
439
+ ),
440
+ usage: z2.object({
441
+ prompt_tokens: z2.number(),
442
+ completion_tokens: z2.number()
443
+ }).optional().nullable()
444
+ });
445
+
446
+ // src/openai-completion-language-model.ts
447
+ import {
448
+ UnsupportedFunctionalityError as UnsupportedFunctionalityError3
449
+ } from "@ai-sdk/provider";
450
+ import {
451
+ createEventSourceResponseHandler as createEventSourceResponseHandler2,
452
+ createJsonResponseHandler as createJsonResponseHandler2,
453
+ postJsonToApi as postJsonToApi2,
454
+ scale as scale2
455
+ } from "@ai-sdk/provider-utils";
456
+ import { z as z3 } from "zod";
457
+
458
+ // src/convert-to-openai-completion-prompt.ts
459
+ import {
460
+ InvalidPromptError,
461
+ UnsupportedFunctionalityError as UnsupportedFunctionalityError2
462
+ } from "@ai-sdk/provider";
463
+ function convertToOpenAICompletionPrompt({
464
+ prompt,
465
+ inputFormat,
466
+ user = "user",
467
+ assistant = "assistant"
468
+ }) {
469
+ if (inputFormat === "prompt" && prompt.length === 1 && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0].type === "text") {
470
+ return { prompt: prompt[0].content[0].text };
471
+ }
472
+ let text = "";
473
+ if (prompt[0].role === "system") {
474
+ text += `${prompt[0].content}
475
+
476
+ `;
477
+ prompt = prompt.slice(1);
478
+ }
479
+ for (const { role, content } of prompt) {
480
+ switch (role) {
481
+ case "system": {
482
+ throw new InvalidPromptError({
483
+ message: "Unexpected system message in prompt: ${content}",
484
+ prompt
485
+ });
486
+ }
487
+ case "user": {
488
+ const userMessage = content.map((part) => {
489
+ switch (part.type) {
490
+ case "text": {
491
+ return part.text;
492
+ }
493
+ case "image": {
494
+ throw new UnsupportedFunctionalityError2({
495
+ functionality: "images"
496
+ });
497
+ }
498
+ }
499
+ }).join("");
500
+ text += `${user}:
501
+ ${userMessage}
502
+
503
+ `;
504
+ break;
505
+ }
506
+ case "assistant": {
507
+ const assistantMessage = content.map((part) => {
508
+ switch (part.type) {
509
+ case "text": {
510
+ return part.text;
511
+ }
512
+ case "tool-call": {
513
+ throw new UnsupportedFunctionalityError2({
514
+ functionality: "tool-call messages"
515
+ });
516
+ }
517
+ }
518
+ }).join("");
519
+ text += `${assistant}:
520
+ ${assistantMessage}
521
+
522
+ `;
523
+ break;
524
+ }
525
+ case "tool": {
526
+ throw new UnsupportedFunctionalityError2({
527
+ functionality: "tool messages"
528
+ });
529
+ }
530
+ default: {
531
+ const _exhaustiveCheck = role;
532
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
533
+ }
534
+ }
535
+ }
536
+ text += `${assistant}:
537
+ `;
538
+ return {
539
+ prompt: text,
540
+ stopSequences: [`
541
+ ${user}:`]
542
+ };
543
+ }
544
+
545
+ // src/openai-completion-language-model.ts
546
+ var OpenAICompletionLanguageModel = class {
547
+ constructor(modelId, settings, config) {
548
+ this.specificationVersion = "v1";
549
+ this.defaultObjectGenerationMode = void 0;
550
+ this.modelId = modelId;
551
+ this.settings = settings;
552
+ this.config = config;
553
+ }
554
+ get provider() {
555
+ return this.config.provider;
556
+ }
557
+ getArgs({
558
+ mode,
559
+ inputFormat,
560
+ prompt,
561
+ maxTokens,
562
+ temperature,
563
+ topP,
564
+ frequencyPenalty,
565
+ presencePenalty,
566
+ seed
567
+ }) {
568
+ var _a;
569
+ const type = mode.type;
570
+ const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt, inputFormat });
571
+ const baseArgs = {
572
+ // model id:
573
+ model: this.modelId,
574
+ // model specific settings:
575
+ echo: this.settings.echo,
576
+ logit_bias: this.settings.logitBias,
577
+ suffix: this.settings.suffix,
578
+ user: this.settings.user,
579
+ // standardized settings:
580
+ max_tokens: maxTokens,
581
+ temperature: scale2({
582
+ value: temperature,
583
+ outputMin: 0,
584
+ outputMax: 2
585
+ }),
586
+ top_p: topP,
587
+ frequency_penalty: scale2({
588
+ value: frequencyPenalty,
589
+ inputMin: -1,
590
+ inputMax: 1,
591
+ outputMin: -2,
592
+ outputMax: 2
593
+ }),
594
+ presence_penalty: scale2({
595
+ value: presencePenalty,
596
+ inputMin: -1,
597
+ inputMax: 1,
598
+ outputMin: -2,
599
+ outputMax: 2
600
+ }),
601
+ seed,
602
+ // prompt:
603
+ prompt: completionPrompt,
604
+ // stop sequences:
605
+ stop: stopSequences
606
+ };
607
+ switch (type) {
608
+ case "regular": {
609
+ if ((_a = mode.tools) == null ? void 0 : _a.length) {
610
+ throw new UnsupportedFunctionalityError3({
611
+ functionality: "tools"
612
+ });
613
+ }
614
+ return baseArgs;
615
+ }
616
+ case "object-json": {
617
+ throw new UnsupportedFunctionalityError3({
618
+ functionality: "object-json mode"
619
+ });
620
+ }
621
+ case "object-tool": {
622
+ throw new UnsupportedFunctionalityError3({
623
+ functionality: "object-tool mode"
624
+ });
625
+ }
626
+ case "object-grammar": {
627
+ throw new UnsupportedFunctionalityError3({
628
+ functionality: "object-grammar mode"
629
+ });
630
+ }
631
+ default: {
632
+ const _exhaustiveCheck = type;
633
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
634
+ }
635
+ }
636
+ }
637
+ async doGenerate(options) {
638
+ const args = this.getArgs(options);
639
+ const response = await postJsonToApi2({
640
+ url: `${this.config.baseUrl}/completions`,
641
+ headers: this.config.headers(),
642
+ body: args,
643
+ failedResponseHandler: openaiFailedResponseHandler,
644
+ successfulResponseHandler: createJsonResponseHandler2(
645
+ openAICompletionResponseSchema
646
+ ),
647
+ abortSignal: options.abortSignal
648
+ });
649
+ const { prompt: rawPrompt, ...rawSettings } = args;
650
+ const choice = response.choices[0];
651
+ return {
652
+ text: choice.text,
653
+ usage: {
654
+ promptTokens: response.usage.prompt_tokens,
655
+ completionTokens: response.usage.completion_tokens
656
+ },
657
+ finishReason: mapOpenAIFinishReason(choice.finish_reason),
658
+ rawCall: { rawPrompt, rawSettings },
659
+ warnings: []
660
+ };
661
+ }
662
+ async doStream(options) {
663
+ const args = this.getArgs(options);
664
+ const response = await postJsonToApi2({
665
+ url: `${this.config.baseUrl}/completions`,
666
+ headers: this.config.headers(),
667
+ body: {
668
+ ...this.getArgs(options),
669
+ stream: true
670
+ },
671
+ failedResponseHandler: openaiFailedResponseHandler,
672
+ successfulResponseHandler: createEventSourceResponseHandler2(
673
+ openaiCompletionChunkSchema
674
+ ),
675
+ abortSignal: options.abortSignal
676
+ });
677
+ const { prompt: rawPrompt, ...rawSettings } = args;
678
+ let finishReason = "other";
679
+ let usage = {
680
+ promptTokens: Number.NaN,
681
+ completionTokens: Number.NaN
682
+ };
683
+ return {
684
+ stream: response.pipeThrough(
685
+ new TransformStream({
686
+ transform(chunk, controller) {
687
+ if (!chunk.success) {
688
+ controller.enqueue({ type: "error", error: chunk.error });
689
+ return;
690
+ }
691
+ const value = chunk.value;
692
+ if (value.usage != null) {
693
+ usage = {
694
+ promptTokens: value.usage.prompt_tokens,
695
+ completionTokens: value.usage.completion_tokens
696
+ };
697
+ }
698
+ const choice = value.choices[0];
699
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
700
+ finishReason = mapOpenAIFinishReason(choice.finish_reason);
701
+ }
702
+ if ((choice == null ? void 0 : choice.text) != null) {
703
+ controller.enqueue({
704
+ type: "text-delta",
705
+ textDelta: choice.text
706
+ });
707
+ }
708
+ },
709
+ flush(controller) {
710
+ controller.enqueue({ type: "finish", finishReason, usage });
711
+ }
712
+ })
713
+ ),
714
+ rawCall: { rawPrompt, rawSettings },
715
+ warnings: []
716
+ };
717
+ }
718
+ };
719
+ var openAICompletionResponseSchema = z3.object({
720
+ choices: z3.array(
721
+ z3.object({
722
+ text: z3.string(),
723
+ finish_reason: z3.string()
724
+ })
725
+ ),
726
+ usage: z3.object({
727
+ prompt_tokens: z3.number(),
728
+ completion_tokens: z3.number()
729
+ })
730
+ });
731
+ var openaiCompletionChunkSchema = z3.object({
732
+ object: z3.literal("text_completion"),
733
+ choices: z3.array(
734
+ z3.object({
735
+ text: z3.string(),
736
+ finish_reason: z3.enum(["stop", "length", "content_filter"]).optional().nullable(),
737
+ index: z3.number()
738
+ })
739
+ ),
740
+ usage: z3.object({
741
+ prompt_tokens: z3.number(),
742
+ completion_tokens: z3.number()
743
+ }).optional().nullable()
744
+ });
745
+
746
+ // src/openai-facade.ts
747
+ var OpenAI = class {
748
+ constructor(options = {}) {
749
+ this.baseUrl = options.baseUrl;
750
+ this.apiKey = options.apiKey;
751
+ this.organization = options.organization;
752
+ }
753
+ get baseConfig() {
754
+ var _a;
755
+ return {
756
+ organization: this.organization,
757
+ baseUrl: (_a = this.baseUrl) != null ? _a : "https://api.openai.com/v1",
758
+ headers: () => ({
759
+ Authorization: `Bearer ${loadApiKey({
760
+ apiKey: this.apiKey,
761
+ environmentVariableName: "OPENAI_API_KEY",
762
+ description: "OpenAI"
763
+ })}`,
764
+ "OpenAI-Organization": this.organization
765
+ })
766
+ };
767
+ }
768
+ chat(modelId, settings = {}) {
769
+ return new OpenAIChatLanguageModel(modelId, settings, {
770
+ provider: "openai.chat",
771
+ ...this.baseConfig
772
+ });
773
+ }
774
+ completion(modelId, settings = {}) {
775
+ return new OpenAICompletionLanguageModel(modelId, settings, {
776
+ provider: "openai.completion",
777
+ ...this.baseConfig
778
+ });
779
+ }
780
+ };
781
+ var openai = new OpenAI();
782
+ export {
783
+ OpenAI,
784
+ openai
785
+ };
786
+ //# sourceMappingURL=index.mjs.map