modelfusion 0.27.0 → 0.27.1

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.
Files changed (128) hide show
  1. package/index.cjs +1 -0
  2. package/index.d.ts +1 -0
  3. package/index.js +1 -0
  4. package/model-function/ApiConfiguration.d.ts +14 -0
  5. package/model-function/BasicApiConfiguration.cjs +35 -0
  6. package/model-function/BasicApiConfiguration.d.ts +15 -0
  7. package/model-function/BasicApiConfiguration.js +31 -0
  8. package/model-function/index.cjs +2 -0
  9. package/model-function/index.d.ts +2 -0
  10. package/model-function/index.js +2 -0
  11. package/model-provider/automatic1111/Automatic1111ApiConfiguration.cjs +14 -0
  12. package/model-provider/automatic1111/Automatic1111ApiConfiguration.d.ts +10 -0
  13. package/model-provider/automatic1111/Automatic1111ApiConfiguration.js +10 -0
  14. package/model-provider/automatic1111/Automatic1111ImageGenerationModel.cjs +10 -7
  15. package/model-provider/automatic1111/Automatic1111ImageGenerationModel.d.ts +2 -5
  16. package/model-provider/automatic1111/Automatic1111ImageGenerationModel.js +10 -7
  17. package/model-provider/automatic1111/index.cjs +1 -0
  18. package/model-provider/automatic1111/index.d.ts +1 -0
  19. package/model-provider/automatic1111/index.js +1 -0
  20. package/model-provider/cohere/CohereApiConfiguration.cjs +29 -0
  21. package/model-provider/cohere/CohereApiConfiguration.d.ts +13 -0
  22. package/model-provider/cohere/CohereApiConfiguration.js +25 -0
  23. package/model-provider/cohere/CohereTextEmbeddingModel.cjs +11 -38
  24. package/model-provider/cohere/CohereTextEmbeddingModel.d.ts +2 -11
  25. package/model-provider/cohere/CohereTextEmbeddingModel.js +11 -38
  26. package/model-provider/cohere/CohereTextGenerationModel.cjs +7 -36
  27. package/model-provider/cohere/CohereTextGenerationModel.d.ts +2 -11
  28. package/model-provider/cohere/CohereTextGenerationModel.js +7 -36
  29. package/model-provider/cohere/CohereTokenizer.cjs +11 -33
  30. package/model-provider/cohere/CohereTokenizer.d.ts +4 -9
  31. package/model-provider/cohere/CohereTokenizer.js +11 -33
  32. package/model-provider/cohere/index.cjs +1 -0
  33. package/model-provider/cohere/index.d.ts +1 -0
  34. package/model-provider/cohere/index.js +1 -0
  35. package/model-provider/elevenlabs/ElevenLabsApiConfiguration.cjs +29 -0
  36. package/model-provider/elevenlabs/ElevenLabsApiConfiguration.d.ts +13 -0
  37. package/model-provider/elevenlabs/ElevenLabsApiConfiguration.js +25 -0
  38. package/model-provider/elevenlabs/ElevenLabsSpeechSynthesisModel.cjs +22 -32
  39. package/model-provider/elevenlabs/ElevenLabsSpeechSynthesisModel.d.ts +8 -8
  40. package/model-provider/elevenlabs/ElevenLabsSpeechSynthesisModel.js +22 -32
  41. package/model-provider/elevenlabs/index.cjs +1 -0
  42. package/model-provider/elevenlabs/index.d.ts +1 -0
  43. package/model-provider/elevenlabs/index.js +1 -0
  44. package/model-provider/huggingface/HuggingFaceApiConfiguration.cjs +29 -0
  45. package/model-provider/huggingface/HuggingFaceApiConfiguration.d.ts +13 -0
  46. package/model-provider/huggingface/HuggingFaceApiConfiguration.js +25 -0
  47. package/model-provider/huggingface/HuggingFaceError.cjs +3 -2
  48. package/model-provider/huggingface/HuggingFaceError.d.ts +3 -3
  49. package/model-provider/huggingface/HuggingFaceError.js +3 -2
  50. package/model-provider/huggingface/HuggingFaceTextEmbeddingModel.cjs +15 -21
  51. package/model-provider/huggingface/HuggingFaceTextEmbeddingModel.d.ts +3 -8
  52. package/model-provider/huggingface/HuggingFaceTextEmbeddingModel.js +15 -21
  53. package/model-provider/huggingface/HuggingFaceTextGenerationModel.cjs +7 -36
  54. package/model-provider/huggingface/HuggingFaceTextGenerationModel.d.ts +2 -7
  55. package/model-provider/huggingface/HuggingFaceTextGenerationModel.js +7 -36
  56. package/model-provider/huggingface/index.cjs +1 -0
  57. package/model-provider/huggingface/index.d.ts +1 -0
  58. package/model-provider/huggingface/index.js +1 -0
  59. package/model-provider/llamacpp/LlamaCppApiConfiguration.cjs +14 -0
  60. package/model-provider/llamacpp/LlamaCppApiConfiguration.d.ts +10 -0
  61. package/model-provider/llamacpp/LlamaCppApiConfiguration.js +10 -0
  62. package/model-provider/llamacpp/LlamaCppTextEmbeddingModel.cjs +11 -12
  63. package/model-provider/llamacpp/LlamaCppTextEmbeddingModel.d.ts +2 -9
  64. package/model-provider/llamacpp/LlamaCppTextEmbeddingModel.js +11 -12
  65. package/model-provider/llamacpp/LlamaCppTextGenerationModel.cjs +9 -10
  66. package/model-provider/llamacpp/LlamaCppTextGenerationModel.d.ts +2 -9
  67. package/model-provider/llamacpp/LlamaCppTextGenerationModel.js +9 -10
  68. package/model-provider/llamacpp/LlamaCppTokenizer.cjs +10 -8
  69. package/model-provider/llamacpp/LlamaCppTokenizer.d.ts +4 -10
  70. package/model-provider/llamacpp/LlamaCppTokenizer.js +10 -8
  71. package/model-provider/llamacpp/index.cjs +1 -0
  72. package/model-provider/llamacpp/index.d.ts +1 -0
  73. package/model-provider/llamacpp/index.js +1 -0
  74. package/model-provider/lmnt/LmntApiConfiguration.cjs +29 -0
  75. package/model-provider/lmnt/LmntApiConfiguration.d.ts +13 -0
  76. package/model-provider/lmnt/LmntApiConfiguration.js +25 -0
  77. package/model-provider/lmnt/LmntSpeechSynthesisModel.cjs +18 -34
  78. package/model-provider/lmnt/LmntSpeechSynthesisModel.d.ts +8 -8
  79. package/model-provider/lmnt/LmntSpeechSynthesisModel.js +18 -34
  80. package/model-provider/lmnt/index.cjs +1 -0
  81. package/model-provider/lmnt/index.d.ts +1 -0
  82. package/model-provider/lmnt/index.js +1 -0
  83. package/model-provider/openai/AzureOpenAIApiConfiguration.cjs +62 -0
  84. package/model-provider/openai/AzureOpenAIApiConfiguration.d.ts +26 -0
  85. package/model-provider/openai/AzureOpenAIApiConfiguration.js +58 -0
  86. package/model-provider/openai/OpenAIApiConfiguration.cjs +31 -0
  87. package/model-provider/openai/OpenAIApiConfiguration.d.ts +13 -0
  88. package/model-provider/openai/OpenAIApiConfiguration.js +27 -0
  89. package/model-provider/openai/OpenAIImageGenerationModel.cjs +16 -20
  90. package/model-provider/openai/OpenAIImageGenerationModel.d.ts +4 -4
  91. package/model-provider/openai/OpenAIImageGenerationModel.js +16 -20
  92. package/model-provider/openai/OpenAITextEmbeddingModel.cjs +16 -35
  93. package/model-provider/openai/OpenAITextEmbeddingModel.d.ts +2 -7
  94. package/model-provider/openai/OpenAITextEmbeddingModel.js +16 -35
  95. package/model-provider/openai/OpenAITextGenerationModel.cjs +6 -33
  96. package/model-provider/openai/OpenAITextGenerationModel.d.ts +4 -5
  97. package/model-provider/openai/OpenAITextGenerationModel.js +6 -33
  98. package/model-provider/openai/OpenAITranscriptionModel.cjs +16 -39
  99. package/model-provider/openai/OpenAITranscriptionModel.d.ts +4 -11
  100. package/model-provider/openai/OpenAITranscriptionModel.js +16 -39
  101. package/model-provider/openai/chat/OpenAIChatModel.cjs +9 -17
  102. package/model-provider/openai/chat/OpenAIChatModel.d.ts +4 -5
  103. package/model-provider/openai/chat/OpenAIChatModel.js +9 -17
  104. package/model-provider/openai/index.cjs +2 -1
  105. package/model-provider/openai/index.d.ts +2 -1
  106. package/model-provider/openai/index.js +2 -1
  107. package/model-provider/stability/StabilityApiConfiguration.cjs +31 -0
  108. package/model-provider/stability/StabilityApiConfiguration.d.ts +13 -0
  109. package/model-provider/stability/StabilityApiConfiguration.js +27 -0
  110. package/model-provider/stability/StabilityImageGenerationModel.cjs +12 -46
  111. package/model-provider/stability/StabilityImageGenerationModel.d.ts +2 -7
  112. package/model-provider/stability/StabilityImageGenerationModel.js +12 -46
  113. package/model-provider/stability/index.cjs +1 -0
  114. package/model-provider/stability/index.d.ts +1 -0
  115. package/model-provider/stability/index.js +1 -0
  116. package/observability/helicone/HeliconeOpenAIApiConfiguration.cjs +45 -0
  117. package/observability/helicone/HeliconeOpenAIApiConfiguration.d.ts +15 -0
  118. package/observability/helicone/HeliconeOpenAIApiConfiguration.js +41 -0
  119. package/observability/index.cjs +17 -0
  120. package/observability/index.d.ts +1 -0
  121. package/observability/index.js +1 -0
  122. package/package.json +1 -1
  123. package/util/api/loadApiKey.cjs +11 -0
  124. package/util/api/loadApiKey.d.ts +6 -0
  125. package/util/api/loadApiKey.js +7 -0
  126. package/model-provider/openai/OpenAIModelSettings.d.ts +0 -8
  127. /package/{model-provider/openai/OpenAIModelSettings.cjs → model-function/ApiConfiguration.cjs} +0 -0
  128. /package/{model-provider/openai/OpenAIModelSettings.js → model-function/ApiConfiguration.js} +0 -0
@@ -3,6 +3,7 @@ import { AbstractModel } from "../../model-function/AbstractModel.js";
3
3
  import { countTokens } from "../../model-function/tokenize-text/countTokens.js";
4
4
  import { callWithRetryAndThrottle } from "../../util/api/callWithRetryAndThrottle.js";
5
5
  import { createJsonResponseHandler, postJsonToApi, } from "../../util/api/postToApi.js";
6
+ import { OpenAIApiConfiguration } from "./OpenAIApiConfiguration.js";
6
7
  import { failedOpenAICallResponseHandler } from "./OpenAIError.js";
7
8
  import { TikTokenTokenizer } from "./TikTokenTokenizer.js";
8
9
  export const OPENAI_TEXT_EMBEDDING_MODELS = {
@@ -78,36 +79,32 @@ export class OpenAITextEmbeddingModel extends AbstractModel {
78
79
  get modelName() {
79
80
  return this.settings.model;
80
81
  }
81
- get apiKey() {
82
- const apiKey = this.settings.apiKey ?? process.env.OPENAI_API_KEY;
83
- if (apiKey == null) {
84
- throw new Error(`OpenAI API key is missing. Pass it as an argument to the constructor or set it as an environment variable named OPENAI_API_KEY.`);
85
- }
86
- return apiKey;
87
- }
88
82
  async countTokens(input) {
89
83
  return countTokens(this.tokenizer, input);
90
84
  }
91
85
  async callAPI(text, options) {
92
86
  const run = options?.run;
93
87
  const settings = options?.settings;
94
- const callSettings = Object.assign({
95
- apiKey: this.apiKey,
88
+ const combinedSettings = {
89
+ ...this.settings,
90
+ ...settings,
91
+ };
92
+ const callSettings = {
96
93
  user: this.settings.isUserIdForwardingEnabled ? run?.userId : undefined,
97
- }, this.settings, settings, {
94
+ // Copied settings:
95
+ ...combinedSettings,
96
+ // other settings:
98
97
  abortSignal: run?.abortSignal,
99
98
  input: text,
100
- });
99
+ };
101
100
  return callWithRetryAndThrottle({
102
- retry: this.settings.retry,
103
- throttle: this.settings.throttle,
101
+ retry: callSettings.api?.retry,
102
+ throttle: callSettings.api?.throttle,
104
103
  call: async () => callOpenAITextEmbeddingAPI(callSettings),
105
104
  });
106
105
  }
107
106
  get settingsForEvent() {
108
- return {
109
- baseUrl: this.settings.baseUrl,
110
- };
107
+ return {};
111
108
  }
112
109
  generateEmbeddingResponse(texts, options) {
113
110
  if (texts.length > this.maxTextsPerCall) {
@@ -137,26 +134,10 @@ const openAITextEmbeddingResponseSchema = z.object({
137
134
  total_tokens: z.number(),
138
135
  }),
139
136
  });
140
- /**
141
- * Call the OpenAI Embedding API to generate an embedding for the given input.
142
- *
143
- * @see https://platform.openai.com/docs/api-reference/embeddings
144
- *
145
- * @example
146
- * const response = await callOpenAITextEmbeddingAPI({
147
- * apiKey: OPENAI_API_KEY,
148
- * model: "text-embedding-ada-002",
149
- * input: "At first, Nox didn't know what to do with the pup.",
150
- * });
151
- *
152
- * console.log(response.data[0].embedding);
153
- */
154
- async function callOpenAITextEmbeddingAPI({ baseUrl = "https://api.openai.com/v1", abortSignal, apiKey, model, input, user, }) {
137
+ async function callOpenAITextEmbeddingAPI({ api = new OpenAIApiConfiguration(), abortSignal, model, input, user, }) {
155
138
  return postJsonToApi({
156
- url: `${baseUrl}/embeddings`,
157
- headers: {
158
- Authorization: `Bearer ${apiKey}`,
159
- },
139
+ url: api.assembleUrl("/embeddings"),
140
+ headers: api.headers,
160
141
  body: {
161
142
  model,
162
143
  input,
@@ -13,6 +13,7 @@ const countTokens_js_1 = require("../../model-function/tokenize-text/countTokens
13
13
  const PromptFormatTextGenerationModel_js_1 = require("../../prompt/PromptFormatTextGenerationModel.cjs");
14
14
  const callWithRetryAndThrottle_js_1 = require("../../util/api/callWithRetryAndThrottle.cjs");
15
15
  const postToApi_js_1 = require("../../util/api/postToApi.cjs");
16
+ const OpenAIApiConfiguration_js_1 = require("./OpenAIApiConfiguration.cjs");
16
17
  const OpenAIError_js_1 = require("./OpenAIError.cjs");
17
18
  const TikTokenTokenizer_js_1 = require("./TikTokenTokenizer.cjs");
18
19
  /**
@@ -152,13 +153,6 @@ class OpenAITextGenerationModel extends AbstractModel_js_1.AbstractModel {
152
153
  get modelName() {
153
154
  return this.settings.model;
154
155
  }
155
- get apiKey() {
156
- const apiKey = this.settings.apiKey ?? process.env.OPENAI_API_KEY;
157
- if (apiKey == null) {
158
- throw new Error(`OpenAI API key is missing. Pass it as an argument to the constructor or set it as an environment variable named OPENAI_API_KEY.`);
159
- }
160
- return apiKey;
161
- }
162
156
  async countPromptTokens(input) {
163
157
  return (0, countTokens_js_1.countTokens)(this.tokenizer, input);
164
158
  }
@@ -169,7 +163,6 @@ class OpenAITextGenerationModel extends AbstractModel_js_1.AbstractModel {
169
163
  ...settings,
170
164
  };
171
165
  const callSettings = {
172
- apiKey: this.apiKey,
173
166
  user: this.settings.isUserIdForwardingEnabled ? run?.userId : undefined,
174
167
  // Copied settings:
175
168
  ...combinedSettings,
@@ -182,8 +175,8 @@ class OpenAITextGenerationModel extends AbstractModel_js_1.AbstractModel {
182
175
  responseFormat,
183
176
  };
184
177
  return (0, callWithRetryAndThrottle_js_1.callWithRetryAndThrottle)({
185
- retry: callSettings.retry,
186
- throttle: callSettings.throttle,
178
+ retry: callSettings.api?.retry,
179
+ throttle: callSettings.api?.throttle,
187
180
  call: async () => callOpenAITextGenerationAPI(callSettings),
188
181
  });
189
182
  }
@@ -191,7 +184,6 @@ class OpenAITextGenerationModel extends AbstractModel_js_1.AbstractModel {
191
184
  const eventSettingProperties = [
192
185
  "maxCompletionTokens",
193
186
  "stopSequences",
194
- "baseUrl",
195
187
  "suffix",
196
188
  "temperature",
197
189
  "topP",
@@ -260,29 +252,10 @@ const openAITextGenerationResponseSchema = zod_1.default.object({
260
252
  total_tokens: zod_1.default.number(),
261
253
  }),
262
254
  });
263
- /**
264
- * Call the OpenAI Text Completion API to generate a text completion for the given prompt.
265
- *
266
- * @see https://platform.openai.com/docs/api-reference/completions/create
267
- *
268
- * @example
269
- * const response = await callOpenAITextGenerationAPI({
270
- * apiKey: OPENAI_API_KEY,
271
- * model: "text-davinci-003",
272
- * prompt: "Write a short story about a robot learning to love:\n\n",
273
- * temperature: 0.7,
274
- * maxTokens: 500,
275
- * });
276
- *
277
- * console.log(response.choices[0].text);
278
- */
279
- async function callOpenAITextGenerationAPI({ baseUrl = "https://api.openai.com/v1", headers, abortSignal, responseFormat, apiKey, model, prompt, suffix, maxTokens, temperature, topP, n, logprobs, echo, stop, presencePenalty, frequencyPenalty, bestOf, logitBias, user, }) {
255
+ async function callOpenAITextGenerationAPI({ api = new OpenAIApiConfiguration_js_1.OpenAIApiConfiguration(), abortSignal, responseFormat, model, prompt, suffix, maxTokens, temperature, topP, n, logprobs, echo, stop, presencePenalty, frequencyPenalty, bestOf, logitBias, user, }) {
280
256
  return (0, postToApi_js_1.postJsonToApi)({
281
- url: `${baseUrl}/completions`,
282
- headers: {
283
- ...headers,
284
- Authorization: `Bearer ${apiKey}`,
285
- },
257
+ url: api.assembleUrl("/completions"),
258
+ headers: api.headers,
286
259
  body: {
287
260
  stream: responseFormat.stream,
288
261
  model,
@@ -1,13 +1,13 @@
1
1
  import z from "zod";
2
2
  import { AbstractModel } from "../../model-function/AbstractModel.js";
3
3
  import { ModelFunctionOptions } from "../../model-function/ModelFunctionOptions.js";
4
+ import { ApiConfiguration } from "../../model-function/ApiConfiguration.js";
4
5
  import { DeltaEvent } from "../../model-function/generate-text/DeltaEvent.js";
5
6
  import { TextGenerationModel, TextGenerationModelSettings } from "../../model-function/generate-text/TextGenerationModel.js";
6
7
  import { PromptFormat } from "../../prompt/PromptFormat.js";
7
8
  import { PromptFormatTextGenerationModel } from "../../prompt/PromptFormatTextGenerationModel.js";
8
9
  import { ResponseHandler } from "../../util/api/postToApi.js";
9
10
  import { OpenAIImageGenerationCallSettings } from "./OpenAIImageGenerationModel.js";
10
- import { OpenAIModelSettings } from "./OpenAIModelSettings.js";
11
11
  import { TikTokenTokenizer } from "./TikTokenTokenizer.js";
12
12
  /**
13
13
  * @see https://platform.openai.com/docs/models/
@@ -81,8 +81,8 @@ export declare const calculateOpenAITextGenerationCostInMillicents: ({ model, re
81
81
  response: OpenAITextGenerationResponse;
82
82
  }) => number;
83
83
  export interface OpenAITextGenerationCallSettings {
84
+ api?: ApiConfiguration;
84
85
  model: OpenAITextGenerationModelType;
85
- headers?: Record<string, string>;
86
86
  suffix?: string;
87
87
  maxTokens?: number;
88
88
  temperature?: number;
@@ -96,7 +96,7 @@ export interface OpenAITextGenerationCallSettings {
96
96
  bestOf?: number;
97
97
  logitBias?: Record<number, number>;
98
98
  }
99
- export interface OpenAITextGenerationModelSettings extends TextGenerationModelSettings, OpenAIModelSettings, Omit<OpenAITextGenerationCallSettings, "stop" | "maxTokens"> {
99
+ export interface OpenAITextGenerationModelSettings extends TextGenerationModelSettings, Omit<OpenAITextGenerationCallSettings, "stop" | "maxTokens"> {
100
100
  isUserIdForwardingEnabled?: boolean;
101
101
  }
102
102
  /**
@@ -123,11 +123,10 @@ export declare class OpenAITextGenerationModel extends AbstractModel<OpenAITextG
123
123
  get modelName(): OpenAITextGenerationModelType;
124
124
  readonly contextWindowSize: number;
125
125
  readonly tokenizer: TikTokenTokenizer;
126
- private get apiKey();
127
126
  countPromptTokens(input: string): Promise<number>;
128
127
  callAPI<RESULT>(prompt: string, options: {
129
128
  responseFormat: OpenAITextResponseFormatType<RESULT>;
130
- } & ModelFunctionOptions<Partial<OpenAIImageGenerationCallSettings & OpenAIModelSettings & {
129
+ } & ModelFunctionOptions<Partial<OpenAIImageGenerationCallSettings & {
131
130
  user?: string;
132
131
  }>>): Promise<RESULT>;
133
132
  get settingsForEvent(): Partial<OpenAITextGenerationModelSettings>;
@@ -7,6 +7,7 @@ import { countTokens } from "../../model-function/tokenize-text/countTokens.js";
7
7
  import { PromptFormatTextGenerationModel } from "../../prompt/PromptFormatTextGenerationModel.js";
8
8
  import { callWithRetryAndThrottle } from "../../util/api/callWithRetryAndThrottle.js";
9
9
  import { createJsonResponseHandler, postJsonToApi, } from "../../util/api/postToApi.js";
10
+ import { OpenAIApiConfiguration } from "./OpenAIApiConfiguration.js";
10
11
  import { failedOpenAICallResponseHandler } from "./OpenAIError.js";
11
12
  import { TikTokenTokenizer } from "./TikTokenTokenizer.js";
12
13
  /**
@@ -143,13 +144,6 @@ export class OpenAITextGenerationModel extends AbstractModel {
143
144
  get modelName() {
144
145
  return this.settings.model;
145
146
  }
146
- get apiKey() {
147
- const apiKey = this.settings.apiKey ?? process.env.OPENAI_API_KEY;
148
- if (apiKey == null) {
149
- throw new Error(`OpenAI API key is missing. Pass it as an argument to the constructor or set it as an environment variable named OPENAI_API_KEY.`);
150
- }
151
- return apiKey;
152
- }
153
147
  async countPromptTokens(input) {
154
148
  return countTokens(this.tokenizer, input);
155
149
  }
@@ -160,7 +154,6 @@ export class OpenAITextGenerationModel extends AbstractModel {
160
154
  ...settings,
161
155
  };
162
156
  const callSettings = {
163
- apiKey: this.apiKey,
164
157
  user: this.settings.isUserIdForwardingEnabled ? run?.userId : undefined,
165
158
  // Copied settings:
166
159
  ...combinedSettings,
@@ -173,8 +166,8 @@ export class OpenAITextGenerationModel extends AbstractModel {
173
166
  responseFormat,
174
167
  };
175
168
  return callWithRetryAndThrottle({
176
- retry: callSettings.retry,
177
- throttle: callSettings.throttle,
169
+ retry: callSettings.api?.retry,
170
+ throttle: callSettings.api?.throttle,
178
171
  call: async () => callOpenAITextGenerationAPI(callSettings),
179
172
  });
180
173
  }
@@ -182,7 +175,6 @@ export class OpenAITextGenerationModel extends AbstractModel {
182
175
  const eventSettingProperties = [
183
176
  "maxCompletionTokens",
184
177
  "stopSequences",
185
- "baseUrl",
186
178
  "suffix",
187
179
  "temperature",
188
180
  "topP",
@@ -250,29 +242,10 @@ const openAITextGenerationResponseSchema = z.object({
250
242
  total_tokens: z.number(),
251
243
  }),
252
244
  });
253
- /**
254
- * Call the OpenAI Text Completion API to generate a text completion for the given prompt.
255
- *
256
- * @see https://platform.openai.com/docs/api-reference/completions/create
257
- *
258
- * @example
259
- * const response = await callOpenAITextGenerationAPI({
260
- * apiKey: OPENAI_API_KEY,
261
- * model: "text-davinci-003",
262
- * prompt: "Write a short story about a robot learning to love:\n\n",
263
- * temperature: 0.7,
264
- * maxTokens: 500,
265
- * });
266
- *
267
- * console.log(response.choices[0].text);
268
- */
269
- async function callOpenAITextGenerationAPI({ baseUrl = "https://api.openai.com/v1", headers, abortSignal, responseFormat, apiKey, model, prompt, suffix, maxTokens, temperature, topP, n, logprobs, echo, stop, presencePenalty, frequencyPenalty, bestOf, logitBias, user, }) {
245
+ async function callOpenAITextGenerationAPI({ api = new OpenAIApiConfiguration(), abortSignal, responseFormat, model, prompt, suffix, maxTokens, temperature, topP, n, logprobs, echo, stop, presencePenalty, frequencyPenalty, bestOf, logitBias, user, }) {
270
246
  return postJsonToApi({
271
- url: `${baseUrl}/completions`,
272
- headers: {
273
- ...headers,
274
- Authorization: `Bearer ${apiKey}`,
275
- },
247
+ url: api.assembleUrl("/completions"),
248
+ headers: api.headers,
276
249
  body: {
277
250
  stream: responseFormat.stream,
278
251
  model,
@@ -8,6 +8,7 @@ const zod_1 = __importDefault(require("zod"));
8
8
  const AbstractModel_js_1 = require("../../model-function/AbstractModel.cjs");
9
9
  const callWithRetryAndThrottle_js_1 = require("../../util/api/callWithRetryAndThrottle.cjs");
10
10
  const postToApi_js_1 = require("../../util/api/postToApi.cjs");
11
+ const OpenAIApiConfiguration_js_1 = require("./OpenAIApiConfiguration.cjs");
11
12
  const OpenAIError_js_1 = require("./OpenAIError.cjs");
12
13
  /**
13
14
  * @see https://openai.com/pricing
@@ -66,62 +67,40 @@ class OpenAITranscriptionModel extends AbstractModel_js_1.AbstractModel {
66
67
  extractTranscriptionText(response) {
67
68
  return response.text;
68
69
  }
69
- get apiKey() {
70
- const apiKey = this.settings.apiKey ?? process.env.OPENAI_API_KEY;
71
- if (apiKey == null) {
72
- throw new Error(`OpenAI API key is missing. Pass it as an argument to the constructor or set it as an environment variable named OPENAI_API_KEY.`);
73
- }
74
- return apiKey;
75
- }
76
70
  async callAPI(data, options) {
77
71
  const run = options?.run;
78
72
  const settings = options?.settings;
79
73
  const responseFormat = options?.responseFormat;
80
- const callSettings = Object.assign({
81
- apiKey: this.apiKey,
82
- }, this.settings, settings, {
74
+ const combinedSettings = {
75
+ ...this.settings,
76
+ ...settings,
77
+ };
78
+ const callSettings = {
79
+ // Copied settings:
80
+ ...combinedSettings,
81
+ // other settings:
83
82
  abortSignal: run?.abortSignal,
84
83
  file: {
85
84
  name: `audio.${data.type}`,
86
85
  data: data.data,
87
86
  },
88
87
  responseFormat,
89
- });
88
+ };
90
89
  return (0, callWithRetryAndThrottle_js_1.callWithRetryAndThrottle)({
91
- retry: this.settings.retry,
92
- throttle: this.settings.throttle,
90
+ retry: callSettings.api?.retry,
91
+ throttle: callSettings.api?.throttle,
93
92
  call: async () => callOpenAITranscriptionAPI(callSettings),
94
93
  });
95
94
  }
96
- getEventSettingProperties() {
97
- return ["baseUrl"];
98
- }
99
95
  get settingsForEvent() {
100
- const eventSettingProperties = ["baseUrl"];
101
- return Object.fromEntries(Object.entries(this.settings).filter(([key]) => eventSettingProperties.includes(key)));
96
+ return {};
102
97
  }
103
98
  withSettings(additionalSettings) {
104
99
  return new OpenAITranscriptionModel(Object.assign({}, this.settings, additionalSettings));
105
100
  }
106
101
  }
107
102
  exports.OpenAITranscriptionModel = OpenAITranscriptionModel;
108
- /**
109
- * Call the OpenAI Transcription API to generate a transcription from an audio file.
110
- *
111
- * @see https://platform.openai.com/docs/api-reference/audio/create
112
- *
113
- * @example
114
- * const transcriptionResponse = await callOpenAITranscriptionAPI({
115
- * apiKey: openAiApiKey,
116
- * model: "whisper-1",
117
- * file: {
118
- * name: "audio.mp3",
119
- * data: fileData, // Buffer
120
- * },
121
- * responseFormat: callOpenAITranscriptionAPI.responseFormat.json,
122
- * });
123
- */
124
- async function callOpenAITranscriptionAPI({ baseUrl = "https://api.openai.com/v1", abortSignal, apiKey, model, file, prompt, responseFormat, temperature, language, }) {
103
+ async function callOpenAITranscriptionAPI({ api = new OpenAIApiConfiguration_js_1.OpenAIApiConfiguration(), abortSignal, model, file, prompt, responseFormat, temperature, language, }) {
125
104
  const formData = new FormData();
126
105
  formData.append("file", new Blob([file.data]), file.name);
127
106
  formData.append("model", model);
@@ -138,10 +117,8 @@ async function callOpenAITranscriptionAPI({ baseUrl = "https://api.openai.com/v1
138
117
  formData.append("language", language);
139
118
  }
140
119
  return (0, postToApi_js_1.postToApi)({
141
- url: `${baseUrl}/audio/transcriptions`,
142
- headers: {
143
- Authorization: `Bearer ${apiKey}`,
144
- },
120
+ url: api.assembleUrl("/audio/transcriptions"),
121
+ headers: api.headers,
145
122
  body: {
146
123
  content: formData,
147
124
  values: {
@@ -2,11 +2,9 @@
2
2
  import z from "zod";
3
3
  import { AbstractModel } from "../../model-function/AbstractModel.js";
4
4
  import { ModelFunctionOptions } from "../../model-function/ModelFunctionOptions.js";
5
+ import { ApiConfiguration } from "../../model-function/ApiConfiguration.js";
5
6
  import { TranscriptionModel, TranscriptionModelSettings } from "../../model-function/transcribe-speech/TranscriptionModel.js";
6
- import { RetryFunction } from "../../util/api/RetryFunction.js";
7
- import { ThrottleFunction } from "../../util/api/ThrottleFunction.js";
8
7
  import { ResponseHandler } from "../../util/api/postToApi.js";
9
- import { OpenAIModelSettings } from "./OpenAIModelSettings.js";
10
8
  /**
11
9
  * @see https://openai.com/pricing
12
10
  */
@@ -21,11 +19,8 @@ export declare const calculateOpenAITranscriptionCostInMillicents: ({ model, res
21
19
  response: OpenAITranscriptionVerboseJsonResponse;
22
20
  }) => number | null;
23
21
  export interface OpenAITranscriptionModelSettings extends TranscriptionModelSettings {
22
+ api?: ApiConfiguration;
24
23
  model: OpenAITranscriptionModelType;
25
- baseUrl?: string;
26
- apiKey?: string;
27
- retry?: RetryFunction;
28
- throttle?: ThrottleFunction;
29
24
  }
30
25
  export type OpenAITranscriptionInput = {
31
26
  type: "mp3" | "mp4" | "mpeg" | "mpga" | "m3a" | "wav" | "webm";
@@ -51,13 +46,11 @@ export declare class OpenAITranscriptionModel extends AbstractModel<OpenAITransc
51
46
  constructor(settings: OpenAITranscriptionModelSettings);
52
47
  readonly provider: "openai";
53
48
  get modelName(): "whisper-1";
54
- generateTranscriptionResponse(data: OpenAITranscriptionInput, options?: ModelFunctionOptions<Partial<OpenAITranscriptionModelSettings & OpenAIModelSettings>>): PromiseLike<OpenAITranscriptionVerboseJsonResponse>;
49
+ generateTranscriptionResponse(data: OpenAITranscriptionInput, options?: ModelFunctionOptions<Partial<OpenAITranscriptionModelSettings>>): PromiseLike<OpenAITranscriptionVerboseJsonResponse>;
55
50
  extractTranscriptionText(response: OpenAITranscriptionVerboseJsonResponse): string;
56
- private get apiKey();
57
51
  callAPI<RESULT>(data: OpenAITranscriptionInput, options: {
58
52
  responseFormat: OpenAITranscriptionResponseFormatType<RESULT>;
59
- } & ModelFunctionOptions<Partial<OpenAITranscriptionModelSettings & OpenAIModelSettings>>): Promise<RESULT>;
60
- getEventSettingProperties(): (keyof OpenAITranscriptionModelSettings)[];
53
+ } & ModelFunctionOptions<Partial<OpenAITranscriptionModelSettings>>): Promise<RESULT>;
61
54
  get settingsForEvent(): Partial<OpenAITranscriptionModelSettings>;
62
55
  withSettings(additionalSettings: OpenAITranscriptionModelSettings): this;
63
56
  }
@@ -2,6 +2,7 @@ import z from "zod";
2
2
  import { AbstractModel } from "../../model-function/AbstractModel.js";
3
3
  import { callWithRetryAndThrottle } from "../../util/api/callWithRetryAndThrottle.js";
4
4
  import { createJsonResponseHandler, createTextResponseHandler, postToApi, } from "../../util/api/postToApi.js";
5
+ import { OpenAIApiConfiguration } from "./OpenAIApiConfiguration.js";
5
6
  import { failedOpenAICallResponseHandler } from "./OpenAIError.js";
6
7
  /**
7
8
  * @see https://openai.com/pricing
@@ -59,61 +60,39 @@ export class OpenAITranscriptionModel extends AbstractModel {
59
60
  extractTranscriptionText(response) {
60
61
  return response.text;
61
62
  }
62
- get apiKey() {
63
- const apiKey = this.settings.apiKey ?? process.env.OPENAI_API_KEY;
64
- if (apiKey == null) {
65
- throw new Error(`OpenAI API key is missing. Pass it as an argument to the constructor or set it as an environment variable named OPENAI_API_KEY.`);
66
- }
67
- return apiKey;
68
- }
69
63
  async callAPI(data, options) {
70
64
  const run = options?.run;
71
65
  const settings = options?.settings;
72
66
  const responseFormat = options?.responseFormat;
73
- const callSettings = Object.assign({
74
- apiKey: this.apiKey,
75
- }, this.settings, settings, {
67
+ const combinedSettings = {
68
+ ...this.settings,
69
+ ...settings,
70
+ };
71
+ const callSettings = {
72
+ // Copied settings:
73
+ ...combinedSettings,
74
+ // other settings:
76
75
  abortSignal: run?.abortSignal,
77
76
  file: {
78
77
  name: `audio.${data.type}`,
79
78
  data: data.data,
80
79
  },
81
80
  responseFormat,
82
- });
81
+ };
83
82
  return callWithRetryAndThrottle({
84
- retry: this.settings.retry,
85
- throttle: this.settings.throttle,
83
+ retry: callSettings.api?.retry,
84
+ throttle: callSettings.api?.throttle,
86
85
  call: async () => callOpenAITranscriptionAPI(callSettings),
87
86
  });
88
87
  }
89
- getEventSettingProperties() {
90
- return ["baseUrl"];
91
- }
92
88
  get settingsForEvent() {
93
- const eventSettingProperties = ["baseUrl"];
94
- return Object.fromEntries(Object.entries(this.settings).filter(([key]) => eventSettingProperties.includes(key)));
89
+ return {};
95
90
  }
96
91
  withSettings(additionalSettings) {
97
92
  return new OpenAITranscriptionModel(Object.assign({}, this.settings, additionalSettings));
98
93
  }
99
94
  }
100
- /**
101
- * Call the OpenAI Transcription API to generate a transcription from an audio file.
102
- *
103
- * @see https://platform.openai.com/docs/api-reference/audio/create
104
- *
105
- * @example
106
- * const transcriptionResponse = await callOpenAITranscriptionAPI({
107
- * apiKey: openAiApiKey,
108
- * model: "whisper-1",
109
- * file: {
110
- * name: "audio.mp3",
111
- * data: fileData, // Buffer
112
- * },
113
- * responseFormat: callOpenAITranscriptionAPI.responseFormat.json,
114
- * });
115
- */
116
- async function callOpenAITranscriptionAPI({ baseUrl = "https://api.openai.com/v1", abortSignal, apiKey, model, file, prompt, responseFormat, temperature, language, }) {
95
+ async function callOpenAITranscriptionAPI({ api = new OpenAIApiConfiguration(), abortSignal, model, file, prompt, responseFormat, temperature, language, }) {
117
96
  const formData = new FormData();
118
97
  formData.append("file", new Blob([file.data]), file.name);
119
98
  formData.append("model", model);
@@ -130,10 +109,8 @@ async function callOpenAITranscriptionAPI({ baseUrl = "https://api.openai.com/v1
130
109
  formData.append("language", language);
131
110
  }
132
111
  return postToApi({
133
- url: `${baseUrl}/audio/transcriptions`,
134
- headers: {
135
- Authorization: `Bearer ${apiKey}`,
136
- },
112
+ url: api.assembleUrl("/audio/transcriptions"),
113
+ headers: api.headers,
137
114
  body: {
138
115
  content: formData,
139
116
  values: {
@@ -10,6 +10,7 @@ const AbstractModel_js_1 = require("../../../model-function/AbstractModel.cjs");
10
10
  const PromptFormatTextGenerationModel_js_1 = require("../../../prompt/PromptFormatTextGenerationModel.cjs");
11
11
  const callWithRetryAndThrottle_js_1 = require("../../../util/api/callWithRetryAndThrottle.cjs");
12
12
  const postToApi_js_1 = require("../../../util/api/postToApi.cjs");
13
+ const OpenAIApiConfiguration_js_1 = require("../OpenAIApiConfiguration.cjs");
13
14
  const OpenAIError_js_1 = require("../OpenAIError.cjs");
14
15
  const TikTokenTokenizer_js_1 = require("../TikTokenTokenizer.cjs");
15
16
  const OpenAIChatStreamIterable_js_1 = require("./OpenAIChatStreamIterable.cjs");
@@ -170,13 +171,6 @@ class OpenAIChatModel extends AbstractModel_js_1.AbstractModel {
170
171
  get modelName() {
171
172
  return this.settings.model;
172
173
  }
173
- get apiKey() {
174
- const apiKey = this.settings.apiKey ?? process.env.OPENAI_API_KEY;
175
- if (apiKey == null) {
176
- throw new Error(`OpenAI API key is missing. Pass it as an argument to the constructor or set it as an environment variable named OPENAI_API_KEY.`);
177
- }
178
- return apiKey;
179
- }
180
174
  /**
181
175
  * Counts the prompt tokens required for the messages. This includes the message base tokens
182
176
  * and the prompt base tokens.
@@ -194,18 +188,20 @@ class OpenAIChatModel extends AbstractModel_js_1.AbstractModel {
194
188
  ...settings,
195
189
  };
196
190
  const callSettings = {
197
- apiKey: this.apiKey,
198
191
  user: this.settings.isUserIdForwardingEnabled ? run?.userId : undefined,
192
+ // Copied settings:
199
193
  ...combinedSettings,
194
+ // map to OpenAI API names:
200
195
  stop: combinedSettings.stopSequences,
201
196
  maxTokens: combinedSettings.maxCompletionTokens,
197
+ // other settings:
202
198
  abortSignal: run?.abortSignal,
203
199
  messages,
204
200
  responseFormat,
205
201
  };
206
202
  return (0, callWithRetryAndThrottle_js_1.callWithRetryAndThrottle)({
207
- retry: callSettings.retry,
208
- throttle: callSettings.throttle,
203
+ retry: callSettings.api?.retry,
204
+ throttle: callSettings.api?.throttle,
209
205
  call: async () => callOpenAIChatCompletionAPI(callSettings),
210
206
  });
211
207
  }
@@ -213,7 +209,6 @@ class OpenAIChatModel extends AbstractModel_js_1.AbstractModel {
213
209
  const eventSettingProperties = [
214
210
  "stopSequences",
215
211
  "maxCompletionTokens",
216
- "baseUrl",
217
212
  "functions",
218
213
  "functionCall",
219
214
  "temperature",
@@ -310,13 +305,10 @@ const openAIChatResponseSchema = zod_1.default.object({
310
305
  total_tokens: zod_1.default.number(),
311
306
  }),
312
307
  });
313
- async function callOpenAIChatCompletionAPI({ baseUrl = "https://api.openai.com/v1", headers, abortSignal, responseFormat, apiKey, model, messages, functions, functionCall, temperature, topP, n, stop, maxTokens, presencePenalty, frequencyPenalty, logitBias, user, }) {
308
+ async function callOpenAIChatCompletionAPI({ api = new OpenAIApiConfiguration_js_1.OpenAIApiConfiguration(), abortSignal, responseFormat, model, messages, functions, functionCall, temperature, topP, n, stop, maxTokens, presencePenalty, frequencyPenalty, logitBias, user, }) {
314
309
  return (0, postToApi_js_1.postJsonToApi)({
315
- url: `${baseUrl}/chat/completions`,
316
- headers: {
317
- ...headers,
318
- Authorization: `Bearer ${apiKey}`,
319
- },
310
+ url: api.assembleUrl("/chat/completions"),
311
+ headers: api.headers,
320
312
  body: {
321
313
  stream: responseFormat.stream,
322
314
  model,
@@ -1,6 +1,7 @@
1
1
  import z from "zod";
2
2
  import { AbstractModel } from "../../../model-function/AbstractModel.js";
3
3
  import { ModelFunctionOptions } from "../../../model-function/ModelFunctionOptions.js";
4
+ import { ApiConfiguration } from "../../../model-function/ApiConfiguration.js";
4
5
  import { JsonGenerationModel } from "../../../model-function/generate-json/JsonGenerationModel.js";
5
6
  import { JsonOrTextGenerationModel } from "../../../model-function/generate-json/JsonOrTextGenerationModel.js";
6
7
  import { DeltaEvent } from "../../../model-function/generate-text/DeltaEvent.js";
@@ -8,7 +9,6 @@ import { TextGenerationModel, TextGenerationModelSettings } from "../../../model
8
9
  import { PromptFormat } from "../../../prompt/PromptFormat.js";
9
10
  import { PromptFormatTextGenerationModel } from "../../../prompt/PromptFormatTextGenerationModel.js";
10
11
  import { ResponseHandler } from "../../../util/api/postToApi.js";
11
- import { OpenAIModelSettings } from "../OpenAIModelSettings.js";
12
12
  import { TikTokenTokenizer } from "../TikTokenTokenizer.js";
13
13
  import { OpenAIChatMessage } from "./OpenAIChatMessage.js";
14
14
  import { OpenAIChatAutoFunctionPrompt, OpenAIChatSingleFunctionPrompt, OpenAIFunctionDescription } from "./OpenAIChatPrompt.js";
@@ -91,8 +91,8 @@ export declare const calculateOpenAIChatCostInMillicents: ({ model, response, }:
91
91
  response: OpenAIChatResponse;
92
92
  }) => number;
93
93
  export interface OpenAIChatCallSettings {
94
+ api?: ApiConfiguration;
94
95
  model: OpenAIChatModelType;
95
- headers?: Record<string, string>;
96
96
  functions?: Array<{
97
97
  name: string;
98
98
  description?: string;
@@ -110,7 +110,7 @@ export interface OpenAIChatCallSettings {
110
110
  frequencyPenalty?: number;
111
111
  logitBias?: Record<number, number>;
112
112
  }
113
- export interface OpenAIChatSettings extends TextGenerationModelSettings, OpenAIModelSettings, Omit<OpenAIChatCallSettings, "stop" | "maxTokens"> {
113
+ export interface OpenAIChatSettings extends TextGenerationModelSettings, Omit<OpenAIChatCallSettings, "stop" | "maxTokens"> {
114
114
  isUserIdForwardingEnabled?: boolean;
115
115
  }
116
116
  /**
@@ -138,7 +138,6 @@ export declare class OpenAIChatModel extends AbstractModel<OpenAIChatSettings> i
138
138
  get modelName(): OpenAIChatModelType;
139
139
  readonly contextWindowSize: number;
140
140
  readonly tokenizer: TikTokenTokenizer;
141
- private get apiKey();
142
141
  /**
143
142
  * Counts the prompt tokens required for the messages. This includes the message base tokens
144
143
  * and the prompt base tokens.
@@ -146,7 +145,7 @@ export declare class OpenAIChatModel extends AbstractModel<OpenAIChatSettings> i
146
145
  countPromptTokens(messages: OpenAIChatMessage[]): Promise<number>;
147
146
  callAPI<RESULT>(messages: Array<OpenAIChatMessage>, options: {
148
147
  responseFormat: OpenAIChatResponseFormatType<RESULT>;
149
- } & ModelFunctionOptions<Partial<OpenAIChatCallSettings & OpenAIModelSettings & {
148
+ } & ModelFunctionOptions<Partial<OpenAIChatCallSettings & {
150
149
  user?: string;
151
150
  }>>): Promise<RESULT>;
152
151
  get settingsForEvent(): Partial<OpenAIChatSettings>;