ai 3.1.0-canary.2 → 3.1.0-canary.4

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.
@@ -27,15 +27,16 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
27
  ));
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
 
30
- // provider/index.ts
31
- var provider_exports = {};
32
- __export(provider_exports, {
33
- OpenAI: () => OpenAI
30
+ // openai/index.ts
31
+ var openai_exports = {};
32
+ __export(openai_exports, {
33
+ OpenAI: () => OpenAI,
34
+ openai: () => openai
34
35
  });
35
- module.exports = __toCommonJS(provider_exports);
36
+ module.exports = __toCommonJS(openai_exports);
36
37
 
37
38
  // ai-model-specification/errors/api-call-error.ts
38
- var ApiCallError = class extends Error {
39
+ var APICallError = class extends Error {
39
40
  constructor({
40
41
  message,
41
42
  url,
@@ -43,11 +44,15 @@ var ApiCallError = class extends Error {
43
44
  statusCode,
44
45
  responseBody,
45
46
  cause,
46
- isRetryable = statusCode != null && (statusCode === 429 || statusCode >= 500),
47
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
48
+ statusCode === 409 || // conflict
49
+ statusCode === 429 || // too many requests
50
+ statusCode >= 500),
51
+ // server error
47
52
  data
48
53
  }) {
49
54
  super(message);
50
- this.name = "ApiCallError";
55
+ this.name = "AI_APICallError";
51
56
  this.url = url;
52
57
  this.requestBodyValues = requestBodyValues;
53
58
  this.statusCode = statusCode;
@@ -56,6 +61,9 @@ var ApiCallError = class extends Error {
56
61
  this.isRetryable = isRetryable;
57
62
  this.data = data;
58
63
  }
64
+ static isAPICallError(error) {
65
+ return error instanceof Error && error.name === "AI_APICallError" && typeof error.url === "string" && typeof error.requestBodyValues === "object" && (error.statusCode == null || typeof error.statusCode === "number") && (error.responseBody == null || typeof error.responseBody === "string") && (error.cause == null || typeof error.cause === "object") && typeof error.isRetryable === "boolean" && (error.data == null || typeof error.data === "object");
66
+ }
59
67
  toJSON() {
60
68
  return {
61
69
  name: this.name,
@@ -71,6 +79,26 @@ var ApiCallError = class extends Error {
71
79
  }
72
80
  };
73
81
 
82
+ // ai-model-specification/errors/invalid-prompt-error.ts
83
+ var InvalidPromptError = class extends Error {
84
+ constructor({ prompt: prompt2, message }) {
85
+ super(`Invalid prompt: ${message}`);
86
+ this.name = "AI_InvalidPromptError";
87
+ this.prompt = prompt2;
88
+ }
89
+ static isInvalidPromptError(error) {
90
+ return error instanceof Error && error.name === "AI_InvalidPromptError" && prompt != null;
91
+ }
92
+ toJSON() {
93
+ return {
94
+ name: this.name,
95
+ message: this.message,
96
+ stack: this.stack,
97
+ prompt: this.prompt
98
+ };
99
+ }
100
+ };
101
+
74
102
  // ai-model-specification/util/get-error-message.ts
75
103
  function getErrorMessage(error) {
76
104
  if (error == null) {
@@ -85,6 +113,50 @@ function getErrorMessage(error) {
85
113
  return JSON.stringify(error);
86
114
  }
87
115
 
116
+ // ai-model-specification/errors/load-api-key-error.ts
117
+ var LoadAPIKeyError = class extends Error {
118
+ constructor({ message }) {
119
+ super(message);
120
+ this.name = "AI_LoadAPIKeyError";
121
+ }
122
+ static isLoadAPIKeyError(error) {
123
+ return error instanceof Error && error.name === "AI_LoadAPIKeyError";
124
+ }
125
+ toJSON() {
126
+ return {
127
+ name: this.name,
128
+ message: this.message
129
+ };
130
+ }
131
+ };
132
+
133
+ // ai-model-specification/util/load-api-key.ts
134
+ function loadApiKey({
135
+ apiKey,
136
+ environmentVariableName,
137
+ apiKeyParameterName = "apiKey",
138
+ description
139
+ }) {
140
+ if (apiKey != null) {
141
+ return apiKey;
142
+ }
143
+ if (typeof process === "undefined") {
144
+ throw new LoadAPIKeyError({
145
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
146
+ });
147
+ }
148
+ apiKey = process.env[environmentVariableName];
149
+ if (apiKey == null) {
150
+ throw new LoadAPIKeyError({
151
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
152
+ });
153
+ }
154
+ return apiKey;
155
+ }
156
+
157
+ // ai-model-specification/util/parse-json.ts
158
+ var import_secure_json_parse = __toESM(require("secure-json-parse"));
159
+
88
160
  // ai-model-specification/errors/json-parse-error.ts
89
161
  var JSONParseError = class extends Error {
90
162
  constructor({ text, cause }) {
@@ -92,10 +164,13 @@ var JSONParseError = class extends Error {
92
164
  `JSON parsing failed: Text: ${text}.
93
165
  Error message: ${getErrorMessage(cause)}`
94
166
  );
95
- this.name = "JSONParseError";
167
+ this.name = "AI_JSONParseError";
96
168
  this.cause = cause;
97
169
  this.text = text;
98
170
  }
171
+ static isJSONParseError(error) {
172
+ return error instanceof Error && error.name === "AI_JSONParseError" && typeof error.text === "string" && typeof error.cause === "string";
173
+ }
99
174
  toJSON() {
100
175
  return {
101
176
  name: this.name,
@@ -107,20 +182,6 @@ Error message: ${getErrorMessage(cause)}`
107
182
  }
108
183
  };
109
184
 
110
- // ai-model-specification/errors/load-api-key-error.ts
111
- var LoadAPIKeyError = class extends Error {
112
- constructor({ message }) {
113
- super(message);
114
- this.name = "LoadAPIKeyError";
115
- }
116
- toJSON() {
117
- return {
118
- name: this.name,
119
- message: this.message
120
- };
121
- }
122
- };
123
-
124
185
  // ai-model-specification/errors/type-validation-error.ts
125
186
  var TypeValidationError = class extends Error {
126
187
  constructor({ value, cause }) {
@@ -128,10 +189,13 @@ var TypeValidationError = class extends Error {
128
189
  `Type validation failed: Value: ${JSON.stringify(value)}.
129
190
  Error message: ${getErrorMessage(cause)}`
130
191
  );
131
- this.name = "TypeValidationError";
192
+ this.name = "AI_TypeValidationError";
132
193
  this.cause = cause;
133
194
  this.value = value;
134
195
  }
196
+ static isTypeValidationError(error) {
197
+ return error instanceof Error && error.name === "AI_TypeValidationError" && typeof error.value === "string" && typeof error.cause === "string";
198
+ }
135
199
  toJSON() {
136
200
  return {
137
201
  name: this.name,
@@ -143,58 +207,6 @@ Error message: ${getErrorMessage(cause)}`
143
207
  }
144
208
  };
145
209
 
146
- // ai-model-specification/errors/unsupported-functionality-error.ts
147
- var UnsupportedFunctionalityError = class extends Error {
148
- constructor({
149
- provider,
150
- functionality
151
- }) {
152
- super(
153
- `Functionality not supported by the provider. Provider: ${provider}.
154
- Functionality: ${functionality}`
155
- );
156
- this.name = "UnsupportedFunctionalityError";
157
- this.provider = provider;
158
- this.functionality = functionality;
159
- }
160
- toJSON() {
161
- return {
162
- name: this.name,
163
- message: this.message,
164
- stack: this.stack,
165
- provider: this.provider,
166
- functionality: this.functionality
167
- };
168
- }
169
- };
170
-
171
- // ai-model-specification/util/load-api-key.ts
172
- function loadApiKey({
173
- apiKey,
174
- environmentVariableName,
175
- apiKeyParameterName = "apiKey",
176
- description
177
- }) {
178
- if (apiKey != null) {
179
- return apiKey;
180
- }
181
- if (typeof process === "undefined") {
182
- throw new LoadAPIKeyError({
183
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
184
- });
185
- }
186
- apiKey = process.env[environmentVariableName];
187
- if (apiKey == null) {
188
- throw new LoadAPIKeyError({
189
- message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
190
- });
191
- }
192
- return apiKey;
193
- }
194
-
195
- // ai-model-specification/util/parse-json.ts
196
- var import_secure_json_parse = __toESM(require("secure-json-parse"));
197
-
198
210
  // ai-model-specification/util/validate-types.ts
199
211
  function validateTypes({
200
212
  value,
@@ -228,7 +240,7 @@ function safeValidateTypes({
228
240
  } catch (error) {
229
241
  return {
230
242
  success: false,
231
- error: error instanceof TypeValidationError ? error : new TypeValidationError({ value, cause: error })
243
+ error: TypeValidationError.isTypeValidationError(error) ? error : new TypeValidationError({ value, cause: error })
232
244
  };
233
245
  }
234
246
  }
@@ -245,7 +257,7 @@ function parseJSON({
245
257
  }
246
258
  return validateTypes({ value, schema });
247
259
  } catch (error) {
248
- if (error instanceof JSONParseError || error instanceof TypeValidationError) {
260
+ if (JSONParseError.isJSONParseError(error) || TypeValidationError.isTypeValidationError(error)) {
249
261
  throw error;
250
262
  }
251
263
  throw new JSONParseError({ text, cause: error });
@@ -267,7 +279,7 @@ function safeParseJSON({
267
279
  } catch (error) {
268
280
  return {
269
281
  success: false,
270
- error: error instanceof JSONParseError ? error : new JSONParseError({ text, cause: error })
282
+ error: JSONParseError.isJSONParseError(error) ? error : new JSONParseError({ text, cause: error })
271
283
  };
272
284
  }
273
285
  }
@@ -291,8 +303,8 @@ var postJsonToApi = async ({
291
303
  }) => postToApi({
292
304
  url,
293
305
  headers: {
294
- "Content-Type": "application/json",
295
- ...headers
306
+ ...headers,
307
+ "Content-Type": "application/json"
296
308
  },
297
309
  body: {
298
310
  content: JSON.stringify(body),
@@ -311,9 +323,12 @@ var postToApi = async ({
311
323
  abortSignal
312
324
  }) => {
313
325
  try {
326
+ const definedHeaders = Object.fromEntries(
327
+ Object.entries(headers).filter(([_key, value]) => value != null)
328
+ );
314
329
  const response = await fetch(url, {
315
330
  method: "POST",
316
- headers,
331
+ headers: definedHeaders,
317
332
  body: body.content,
318
333
  signal: abortSignal
319
334
  });
@@ -326,11 +341,11 @@ var postToApi = async ({
326
341
  });
327
342
  } catch (error) {
328
343
  if (error instanceof Error) {
329
- if (error.name === "AbortError" || error instanceof ApiCallError) {
344
+ if (error.name === "AbortError" || APICallError.isAPICallError(error)) {
330
345
  throw error;
331
346
  }
332
347
  }
333
- throw new ApiCallError({
348
+ throw new APICallError({
334
349
  message: "Failed to process error response",
335
350
  cause: error,
336
351
  statusCode: response.status,
@@ -347,11 +362,11 @@ var postToApi = async ({
347
362
  });
348
363
  } catch (error) {
349
364
  if (error instanceof Error) {
350
- if (error.name === "AbortError" || error instanceof ApiCallError) {
365
+ if (error.name === "AbortError" || APICallError.isAPICallError(error)) {
351
366
  throw error;
352
367
  }
353
368
  }
354
- throw new ApiCallError({
369
+ throw new APICallError({
355
370
  message: "Failed to process successful response",
356
371
  cause: error,
357
372
  statusCode: response.status,
@@ -368,12 +383,13 @@ var postToApi = async ({
368
383
  if (error instanceof TypeError && error.message === "fetch failed") {
369
384
  const cause = error.cause;
370
385
  if (cause != null) {
371
- throw new ApiCallError({
386
+ throw new APICallError({
372
387
  message: `Cannot connect to API: ${cause.message}`,
373
388
  cause,
374
389
  url,
375
390
  requestBodyValues: body.values,
376
391
  isRetryable: true
392
+ // retry when network error
377
393
  });
378
394
  }
379
395
  }
@@ -390,7 +406,7 @@ var createJsonErrorResponseHandler = ({
390
406
  }) => async ({ response, url, requestBodyValues }) => {
391
407
  const responseBody = await response.text();
392
408
  if (responseBody.trim() === "") {
393
- return new ApiCallError({
409
+ return new APICallError({
394
410
  message: response.statusText,
395
411
  url,
396
412
  requestBodyValues,
@@ -404,7 +420,7 @@ var createJsonErrorResponseHandler = ({
404
420
  text: responseBody,
405
421
  schema: errorSchema
406
422
  });
407
- return new ApiCallError({
423
+ return new APICallError({
408
424
  message: errorToMessage(parsedError),
409
425
  url,
410
426
  requestBodyValues,
@@ -414,7 +430,7 @@ var createJsonErrorResponseHandler = ({
414
430
  isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
415
431
  });
416
432
  } catch (parseError) {
417
- return new ApiCallError({
433
+ return new APICallError({
418
434
  message: response.statusText,
419
435
  url,
420
436
  requestBodyValues,
@@ -452,7 +468,7 @@ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requ
452
468
  schema: responseSchema
453
469
  });
454
470
  if (!parsedResult.success) {
455
- throw new ApiCallError({
471
+ throw new APICallError({
456
472
  message: "Invalid JSON response",
457
473
  cause: parsedResult.error,
458
474
  statusCode: response.status,
@@ -489,14 +505,42 @@ function convertUint8ArrayToBase64(array) {
489
505
  return globalThis.btoa(latin1string);
490
506
  }
491
507
 
492
- // provider/openai/openai-chat-language-model.ts
508
+ // ai-model-specification/errors/unsupported-functionality-error.ts
509
+ var UnsupportedFunctionalityError = class extends Error {
510
+ constructor({
511
+ provider,
512
+ functionality
513
+ }) {
514
+ super(
515
+ `Functionality not supported by the provider. Provider: ${provider}.
516
+ Functionality: ${functionality}`
517
+ );
518
+ this.name = "AI_UnsupportedFunctionalityError";
519
+ this.provider = provider;
520
+ this.functionality = functionality;
521
+ }
522
+ static isUnsupportedFunctionalityError(error) {
523
+ return error instanceof Error && error.name === "AI_UnsupportedFunctionalityError" && typeof error.provider === "string" && typeof error.functionality === "string";
524
+ }
525
+ toJSON() {
526
+ return {
527
+ name: this.name,
528
+ message: this.message,
529
+ stack: this.stack,
530
+ provider: this.provider,
531
+ functionality: this.functionality
532
+ };
533
+ }
534
+ };
535
+
536
+ // openai/openai-chat-language-model.ts
493
537
  var import_nanoid = require("nanoid");
494
538
  var import_zod2 = require("zod");
495
539
 
496
- // provider/openai/convert-to-openai-chat-messages.ts
497
- function convertToOpenAIChatMessages(prompt) {
540
+ // openai/convert-to-openai-chat-messages.ts
541
+ function convertToOpenAIChatMessages(prompt2) {
498
542
  const messages = [];
499
- for (const { role, content } of prompt) {
543
+ for (const { role, content } of prompt2) {
500
544
  switch (role) {
501
545
  case "system": {
502
546
  messages.push({ role: "system", content });
@@ -515,7 +559,7 @@ function convertToOpenAIChatMessages(prompt) {
515
559
  return {
516
560
  type: "image_url",
517
561
  image_url: {
518
- url: `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`
562
+ url: part.image instanceof URL ? part.image.toString() : `data:${(_a = part.mimeType) != null ? _a : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`
519
563
  }
520
564
  };
521
565
  }
@@ -576,7 +620,24 @@ function convertToOpenAIChatMessages(prompt) {
576
620
  return messages;
577
621
  }
578
622
 
579
- // provider/openai/openai-error.ts
623
+ // openai/map-openai-finish-reason.ts
624
+ function mapOpenAIFinishReason(finishReason) {
625
+ switch (finishReason) {
626
+ case "stop":
627
+ return "stop";
628
+ case "length":
629
+ return "length";
630
+ case "content-filter":
631
+ return "content-filter";
632
+ case "function_call":
633
+ case "tool-calls":
634
+ return "tool-calls";
635
+ default:
636
+ return "other";
637
+ }
638
+ }
639
+
640
+ // openai/openai-error.ts
580
641
  var import_zod = require("zod");
581
642
  var openAIErrorDataSchema = import_zod.z.object({
582
643
  error: import_zod.z.object({
@@ -588,28 +649,24 @@ var openAIErrorDataSchema = import_zod.z.object({
588
649
  });
589
650
  var openaiFailedResponseHandler = createJsonErrorResponseHandler({
590
651
  errorSchema: openAIErrorDataSchema,
591
- errorToMessage: (data) => data.error.message,
592
- isRetryable: (response, error) => response.status >= 500 || response.status === 429 && // insufficient_quota is also reported as a 429, but it's not retryable:
593
- (error == null ? void 0 : error.error.type) !== "insufficient_quota"
652
+ errorToMessage: (data) => data.error.message
594
653
  });
595
654
 
596
- // provider/openai/openai-chat-language-model.ts
655
+ // openai/openai-chat-language-model.ts
597
656
  var OpenAIChatLanguageModel = class {
598
- constructor(settings, config) {
657
+ constructor(modelId, settings, config) {
599
658
  this.specificationVersion = "v1";
600
659
  this.defaultObjectGenerationMode = "tool";
660
+ this.modelId = modelId;
601
661
  this.settings = settings;
602
662
  this.config = config;
603
663
  }
604
664
  get provider() {
605
665
  return this.config.provider;
606
666
  }
607
- get modelId() {
608
- return this.settings.id;
609
- }
610
667
  getArgs({
611
668
  mode,
612
- prompt,
669
+ prompt: prompt2,
613
670
  maxTokens,
614
671
  temperature,
615
672
  topP,
@@ -620,8 +677,11 @@ var OpenAIChatLanguageModel = class {
620
677
  var _a;
621
678
  const type = mode.type;
622
679
  const baseArgs = {
680
+ // model id:
681
+ model: this.modelId,
623
682
  // model specific settings:
624
- ...this.config.mapSettings(this.settings),
683
+ logit_bias: this.settings.logitBias,
684
+ user: this.settings.user,
625
685
  // standardized settings:
626
686
  max_tokens: maxTokens,
627
687
  temperature: scale({
@@ -646,7 +706,7 @@ var OpenAIChatLanguageModel = class {
646
706
  }),
647
707
  seed,
648
708
  // messages:
649
- messages: convertToOpenAIChatMessages(prompt)
709
+ messages: convertToOpenAIChatMessages(prompt2)
650
710
  };
651
711
  switch (type) {
652
712
  case "regular": {
@@ -690,49 +750,54 @@ var OpenAIChatLanguageModel = class {
690
750
  }
691
751
  async doGenerate(options) {
692
752
  var _a, _b;
753
+ const args = this.getArgs(options);
693
754
  const response = await postJsonToApi({
694
755
  url: `${this.config.baseUrl}/chat/completions`,
695
- headers: {
696
- Authorization: `Bearer ${this.config.apiKey()}`
697
- },
698
- body: {
699
- ...this.getArgs(options)
700
- },
756
+ headers: this.config.headers(),
757
+ body: args,
701
758
  failedResponseHandler: openaiFailedResponseHandler,
702
759
  successfulResponseHandler: createJsonResponseHandler(
703
760
  openAIChatResponseSchema
704
- )
761
+ ),
762
+ abortSignal: options.abortSignal
705
763
  });
706
- const message = response.choices[0].message;
764
+ const { messages: rawPrompt, ...rawSettings } = args;
765
+ const choice = response.choices[0];
707
766
  return {
708
- text: (_a = message.content) != null ? _a : void 0,
709
- toolCalls: (_b = message.tool_calls) == null ? void 0 : _b.map((toolCall) => ({
767
+ text: (_a = choice.message.content) != null ? _a : void 0,
768
+ toolCalls: (_b = choice.message.tool_calls) == null ? void 0 : _b.map((toolCall) => ({
710
769
  toolCallType: "function",
711
770
  toolCallId: toolCall.id,
712
771
  toolName: toolCall.function.name,
713
772
  args: toolCall.function.arguments
714
773
  })),
774
+ finishReason: mapOpenAIFinishReason(choice.finish_reason),
775
+ usage: {
776
+ promptTokens: response.usage.prompt_tokens,
777
+ completionTokens: response.usage.completion_tokens
778
+ },
779
+ rawCall: { rawPrompt, rawSettings },
715
780
  warnings: []
716
781
  };
717
782
  }
718
783
  async doStream(options) {
784
+ const args = this.getArgs(options);
719
785
  const response = await postJsonToApi({
720
786
  url: `${this.config.baseUrl}/chat/completions`,
721
- headers: {
722
- Authorization: `Bearer ${this.config.apiKey()}`
723
- },
787
+ headers: this.config.headers(),
724
788
  body: {
725
- ...this.getArgs(options),
789
+ ...args,
726
790
  stream: true
727
791
  },
728
792
  failedResponseHandler: openaiFailedResponseHandler,
729
793
  successfulResponseHandler: createEventSourceResponseHandler(
730
794
  openaiChatChunkSchema
731
- )
795
+ ),
796
+ abortSignal: options.abortSignal
732
797
  });
798
+ const { messages: rawPrompt, ...rawSettings } = args;
733
799
  const toolCalls = [];
734
800
  return {
735
- warnings: [],
736
801
  stream: response.pipeThrough(
737
802
  new TransformStream({
738
803
  transform(chunk, controller) {
@@ -786,7 +851,9 @@ var OpenAIChatLanguageModel = class {
786
851
  }
787
852
  }
788
853
  })
789
- )
854
+ ),
855
+ rawCall: { rawPrompt, rawSettings },
856
+ warnings: []
790
857
  };
791
858
  }
792
859
  };
@@ -842,32 +909,34 @@ var openaiChatChunkSchema = import_zod2.z.object({
842
909
  )
843
910
  });
844
911
 
845
- // provider/openai/openai-completion-language-model.ts
912
+ // openai/openai-completion-language-model.ts
846
913
  var import_zod3 = require("zod");
847
914
 
848
- // provider/openai/convert-to-openai-completion-prompt.ts
915
+ // openai/convert-to-openai-completion-prompt.ts
849
916
  function convertToOpenAICompletionPrompt({
850
- prompt,
917
+ prompt: prompt2,
851
918
  inputFormat,
852
919
  provider,
853
920
  user = "user",
854
921
  assistant = "assistant"
855
922
  }) {
856
- if (inputFormat === "prompt" && prompt.length === 1 && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0].type === "text") {
857
- return { prompt: prompt[0].content[0].text };
923
+ if (inputFormat === "prompt" && prompt2.length === 1 && prompt2[0].role === "user" && prompt2[0].content.length === 1 && prompt2[0].content[0].type === "text") {
924
+ return { prompt: prompt2[0].content[0].text };
858
925
  }
859
926
  let text = "";
860
- if (prompt[0].role === "system") {
861
- text += `${prompt[0].content}
927
+ if (prompt2[0].role === "system") {
928
+ text += `${prompt2[0].content}
862
929
 
863
930
  `;
864
- prompt = prompt.slice(1);
931
+ prompt2 = prompt2.slice(1);
865
932
  }
866
- for (const { role, content } of prompt) {
933
+ for (const { role, content } of prompt2) {
867
934
  switch (role) {
868
935
  case "system": {
869
- throw new Error(`Unexpected system message in prompt: ${content}`);
870
- break;
936
+ throw new InvalidPromptError({
937
+ message: "Unexpected system message in prompt: ${content}",
938
+ prompt: prompt2
939
+ });
871
940
  }
872
941
  case "user": {
873
942
  const userMessage = content.map((part) => {
@@ -930,24 +999,22 @@ ${user}:`]
930
999
  };
931
1000
  }
932
1001
 
933
- // provider/openai/openai-completion-language-model.ts
1002
+ // openai/openai-completion-language-model.ts
934
1003
  var OpenAICompletionLanguageModel = class {
935
- constructor(settings, config) {
1004
+ constructor(modelId, settings, config) {
936
1005
  this.specificationVersion = "v1";
937
1006
  this.defaultObjectGenerationMode = void 0;
1007
+ this.modelId = modelId;
938
1008
  this.settings = settings;
939
1009
  this.config = config;
940
1010
  }
941
1011
  get provider() {
942
1012
  return this.config.provider;
943
1013
  }
944
- get modelId() {
945
- return this.settings.id;
946
- }
947
1014
  getArgs({
948
1015
  mode,
949
1016
  inputFormat,
950
- prompt,
1017
+ prompt: prompt2,
951
1018
  maxTokens,
952
1019
  temperature,
953
1020
  topP,
@@ -958,13 +1025,18 @@ var OpenAICompletionLanguageModel = class {
958
1025
  var _a;
959
1026
  const type = mode.type;
960
1027
  const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({
961
- prompt,
1028
+ prompt: prompt2,
962
1029
  inputFormat,
963
1030
  provider: this.provider
964
1031
  });
965
1032
  const baseArgs = {
1033
+ // model id:
1034
+ model: this.modelId,
966
1035
  // model specific settings:
967
- ...this.config.mapSettings(this.settings),
1036
+ echo: this.settings.echo,
1037
+ logit_bias: this.settings.logitBias,
1038
+ suffix: this.settings.suffix,
1039
+ user: this.settings.user,
968
1040
  // standardized settings:
969
1041
  max_tokens: maxTokens,
970
1042
  temperature: scale({
@@ -1028,30 +1100,35 @@ var OpenAICompletionLanguageModel = class {
1028
1100
  }
1029
1101
  }
1030
1102
  async doGenerate(options) {
1103
+ const args = this.getArgs(options);
1031
1104
  const response = await postJsonToApi({
1032
1105
  url: `${this.config.baseUrl}/completions`,
1033
- headers: {
1034
- Authorization: `Bearer ${this.config.apiKey()}`
1035
- },
1036
- body: {
1037
- ...this.getArgs(options)
1038
- },
1106
+ headers: this.config.headers(),
1107
+ body: args,
1039
1108
  failedResponseHandler: openaiFailedResponseHandler,
1040
1109
  successfulResponseHandler: createJsonResponseHandler(
1041
1110
  openAICompletionResponseSchema
1042
- )
1111
+ ),
1112
+ abortSignal: options.abortSignal
1043
1113
  });
1114
+ const { prompt: rawPrompt, ...rawSettings } = args;
1115
+ const choice = response.choices[0];
1044
1116
  return {
1045
- text: response.choices[0].text,
1117
+ text: choice.text,
1118
+ usage: {
1119
+ promptTokens: response.usage.prompt_tokens,
1120
+ completionTokens: response.usage.completion_tokens
1121
+ },
1122
+ finishReason: mapOpenAIFinishReason(choice.finish_reason),
1123
+ rawCall: { rawPrompt, rawSettings },
1046
1124
  warnings: []
1047
1125
  };
1048
1126
  }
1049
1127
  async doStream(options) {
1128
+ const args = this.getArgs(options);
1050
1129
  const response = await postJsonToApi({
1051
1130
  url: `${this.config.baseUrl}/completions`,
1052
- headers: {
1053
- Authorization: `Bearer ${this.config.apiKey()}`
1054
- },
1131
+ headers: this.config.headers(),
1055
1132
  body: {
1056
1133
  ...this.getArgs(options),
1057
1134
  stream: true
@@ -1059,10 +1136,11 @@ var OpenAICompletionLanguageModel = class {
1059
1136
  failedResponseHandler: openaiFailedResponseHandler,
1060
1137
  successfulResponseHandler: createEventSourceResponseHandler(
1061
1138
  openaiCompletionChunkSchema
1062
- )
1139
+ ),
1140
+ abortSignal: options.abortSignal
1063
1141
  });
1142
+ const { prompt: rawPrompt, ...rawSettings } = args;
1064
1143
  return {
1065
- warnings: [],
1066
1144
  stream: response.pipeThrough(
1067
1145
  new TransformStream({
1068
1146
  transform(chunk, controller) {
@@ -1080,7 +1158,9 @@ var OpenAICompletionLanguageModel = class {
1080
1158
  }
1081
1159
  }
1082
1160
  })
1083
- )
1161
+ ),
1162
+ rawCall: { rawPrompt, rawSettings },
1163
+ warnings: []
1084
1164
  };
1085
1165
  }
1086
1166
  };
@@ -1107,50 +1187,45 @@ var openaiCompletionChunkSchema = import_zod3.z.object({
1107
1187
  )
1108
1188
  });
1109
1189
 
1110
- // provider/openai/openai-facade.ts
1190
+ // openai/openai-facade.ts
1111
1191
  var OpenAI = class {
1112
- constructor({ baseUrl, apiKey } = {}) {
1113
- this.baseUrl = baseUrl;
1114
- this.apiKey = apiKey;
1192
+ constructor(options = {}) {
1193
+ this.baseUrl = options.baseUrl;
1194
+ this.apiKey = options.apiKey;
1195
+ this.organization = options.organization;
1115
1196
  }
1116
- chat(settings) {
1197
+ get baseConfig() {
1117
1198
  var _a;
1118
- return new OpenAIChatLanguageModel(settings, {
1119
- provider: "openai.chat",
1199
+ return {
1200
+ organization: this.organization,
1120
1201
  baseUrl: (_a = this.baseUrl) != null ? _a : "https://api.openai.com/v1",
1121
- apiKey: () => loadApiKey({
1122
- apiKey: this.apiKey,
1123
- environmentVariableName: "OPENAI_API_KEY",
1124
- description: "OpenAI"
1125
- }),
1126
- mapSettings: (settings2) => ({
1127
- model: settings2.id,
1128
- logit_bias: settings2.logitBias
1129
- })
1130
- });
1131
- }
1132
- completion(settings) {
1133
- var _a;
1134
- return new OpenAICompletionLanguageModel(
1135
- settings,
1136
- {
1137
- provider: "openai.completion",
1138
- baseUrl: (_a = this.baseUrl) != null ? _a : "https://api.openai.com/v1",
1139
- apiKey: () => loadApiKey({
1202
+ headers: () => ({
1203
+ Authorization: `Bearer ${loadApiKey({
1140
1204
  apiKey: this.apiKey,
1141
1205
  environmentVariableName: "OPENAI_API_KEY",
1142
1206
  description: "OpenAI"
1143
- }),
1144
- mapSettings: (settings2) => ({
1145
- model: settings2.id,
1146
- logit_bias: settings2.logitBias
1147
- })
1148
- }
1149
- );
1207
+ })}`,
1208
+ "OpenAI-Organization": this.organization
1209
+ })
1210
+ };
1211
+ }
1212
+ chat(modelId, settings = {}) {
1213
+ return new OpenAIChatLanguageModel(modelId, settings, {
1214
+ provider: "openai.chat",
1215
+ ...this.baseConfig
1216
+ });
1217
+ }
1218
+ completion(modelId, settings = {}) {
1219
+ return new OpenAICompletionLanguageModel(modelId, settings, {
1220
+ provider: "openai.completion",
1221
+ ...this.baseConfig
1222
+ });
1150
1223
  }
1151
1224
  };
1225
+ var openai = new OpenAI();
1152
1226
  // Annotate the CommonJS export names for ESM import in node:
1153
1227
  0 && (module.exports = {
1154
- OpenAI
1228
+ OpenAI,
1229
+ openai
1155
1230
  });
1156
1231
  //# sourceMappingURL=index.js.map