@langchain/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/legacy.js ADDED
@@ -0,0 +1,444 @@
1
+ import { OpenAI as OpenAIClient } from "openai";
2
+ import { GenerationChunk } from "@langchain/core/outputs";
3
+ import { getEnvironmentVariable } from "@langchain/core/utils/env";
4
+ import { LLM } from "@langchain/core/language_models/llms";
5
+ import { getEndpoint } from "./utils/azure.js";
6
+ import { wrapOpenAIClientError } from "./utils/openai.js";
7
+ /**
8
+ * Wrapper around OpenAI large language models that use the Chat endpoint.
9
+ *
10
+ * To use you should have the `openai` package installed, with the
11
+ * `OPENAI_API_KEY` environment variable set.
12
+ *
13
+ * To use with Azure you should have the `openai` package installed, with the
14
+ * `AZURE_OPENAI_API_KEY`,
15
+ * `AZURE_OPENAI_API_INSTANCE_NAME`,
16
+ * `AZURE_OPENAI_API_DEPLOYMENT_NAME`
17
+ * and `AZURE_OPENAI_API_VERSION` environment variable set.
18
+ *
19
+ * @remarks
20
+ * Any parameters that are valid to be passed to {@link
21
+ * https://platform.openai.com/docs/api-reference/chat/create |
22
+ * `openai.createCompletion`} can be passed through {@link modelKwargs}, even
23
+ * if not explicitly available on this class.
24
+ *
25
+ * @augments BaseLLM
26
+ * @augments OpenAIInput
27
+ * @augments AzureOpenAIChatInput
28
+ * @example
29
+ * ```typescript
30
+ * const model = new OpenAIChat({
31
+ * prefixMessages: [
32
+ * {
33
+ * role: "system",
34
+ * content: "You are a helpful assistant that answers in pirate language",
35
+ * },
36
+ * ],
37
+ * maxTokens: 50,
38
+ * });
39
+ *
40
+ * const res = await model.call(
41
+ * "What would be a good company name for a company that makes colorful socks?"
42
+ * );
43
+ * console.log({ res });
44
+ * ```
45
+ */
46
+ export class OpenAIChat extends LLM {
47
+ static lc_name() {
48
+ return "OpenAIChat";
49
+ }
50
+ get callKeys() {
51
+ return [...super.callKeys, "options", "promptIndex"];
52
+ }
53
+ get lc_secrets() {
54
+ return {
55
+ openAIApiKey: "OPENAI_API_KEY",
56
+ azureOpenAIApiKey: "AZURE_OPENAI_API_KEY",
57
+ organization: "OPENAI_ORGANIZATION",
58
+ };
59
+ }
60
+ get lc_aliases() {
61
+ return {
62
+ modelName: "model",
63
+ openAIApiKey: "openai_api_key",
64
+ azureOpenAIApiVersion: "azure_openai_api_version",
65
+ azureOpenAIApiKey: "azure_openai_api_key",
66
+ azureOpenAIApiInstanceName: "azure_openai_api_instance_name",
67
+ azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name",
68
+ };
69
+ }
70
+ constructor(fields,
71
+ /** @deprecated */
72
+ configuration) {
73
+ super(fields ?? {});
74
+ Object.defineProperty(this, "lc_serializable", {
75
+ enumerable: true,
76
+ configurable: true,
77
+ writable: true,
78
+ value: true
79
+ });
80
+ Object.defineProperty(this, "temperature", {
81
+ enumerable: true,
82
+ configurable: true,
83
+ writable: true,
84
+ value: 1
85
+ });
86
+ Object.defineProperty(this, "topP", {
87
+ enumerable: true,
88
+ configurable: true,
89
+ writable: true,
90
+ value: 1
91
+ });
92
+ Object.defineProperty(this, "frequencyPenalty", {
93
+ enumerable: true,
94
+ configurable: true,
95
+ writable: true,
96
+ value: 0
97
+ });
98
+ Object.defineProperty(this, "presencePenalty", {
99
+ enumerable: true,
100
+ configurable: true,
101
+ writable: true,
102
+ value: 0
103
+ });
104
+ Object.defineProperty(this, "n", {
105
+ enumerable: true,
106
+ configurable: true,
107
+ writable: true,
108
+ value: 1
109
+ });
110
+ Object.defineProperty(this, "logitBias", {
111
+ enumerable: true,
112
+ configurable: true,
113
+ writable: true,
114
+ value: void 0
115
+ });
116
+ Object.defineProperty(this, "maxTokens", {
117
+ enumerable: true,
118
+ configurable: true,
119
+ writable: true,
120
+ value: void 0
121
+ });
122
+ Object.defineProperty(this, "modelName", {
123
+ enumerable: true,
124
+ configurable: true,
125
+ writable: true,
126
+ value: "gpt-3.5-turbo"
127
+ });
128
+ Object.defineProperty(this, "prefixMessages", {
129
+ enumerable: true,
130
+ configurable: true,
131
+ writable: true,
132
+ value: void 0
133
+ });
134
+ Object.defineProperty(this, "modelKwargs", {
135
+ enumerable: true,
136
+ configurable: true,
137
+ writable: true,
138
+ value: void 0
139
+ });
140
+ Object.defineProperty(this, "timeout", {
141
+ enumerable: true,
142
+ configurable: true,
143
+ writable: true,
144
+ value: void 0
145
+ });
146
+ Object.defineProperty(this, "stop", {
147
+ enumerable: true,
148
+ configurable: true,
149
+ writable: true,
150
+ value: void 0
151
+ });
152
+ Object.defineProperty(this, "user", {
153
+ enumerable: true,
154
+ configurable: true,
155
+ writable: true,
156
+ value: void 0
157
+ });
158
+ Object.defineProperty(this, "streaming", {
159
+ enumerable: true,
160
+ configurable: true,
161
+ writable: true,
162
+ value: false
163
+ });
164
+ Object.defineProperty(this, "openAIApiKey", {
165
+ enumerable: true,
166
+ configurable: true,
167
+ writable: true,
168
+ value: void 0
169
+ });
170
+ Object.defineProperty(this, "azureOpenAIApiVersion", {
171
+ enumerable: true,
172
+ configurable: true,
173
+ writable: true,
174
+ value: void 0
175
+ });
176
+ Object.defineProperty(this, "azureOpenAIApiKey", {
177
+ enumerable: true,
178
+ configurable: true,
179
+ writable: true,
180
+ value: void 0
181
+ });
182
+ Object.defineProperty(this, "azureOpenAIApiInstanceName", {
183
+ enumerable: true,
184
+ configurable: true,
185
+ writable: true,
186
+ value: void 0
187
+ });
188
+ Object.defineProperty(this, "azureOpenAIApiDeploymentName", {
189
+ enumerable: true,
190
+ configurable: true,
191
+ writable: true,
192
+ value: void 0
193
+ });
194
+ Object.defineProperty(this, "azureOpenAIBasePath", {
195
+ enumerable: true,
196
+ configurable: true,
197
+ writable: true,
198
+ value: void 0
199
+ });
200
+ Object.defineProperty(this, "organization", {
201
+ enumerable: true,
202
+ configurable: true,
203
+ writable: true,
204
+ value: void 0
205
+ });
206
+ Object.defineProperty(this, "client", {
207
+ enumerable: true,
208
+ configurable: true,
209
+ writable: true,
210
+ value: void 0
211
+ });
212
+ Object.defineProperty(this, "clientConfig", {
213
+ enumerable: true,
214
+ configurable: true,
215
+ writable: true,
216
+ value: void 0
217
+ });
218
+ this.openAIApiKey =
219
+ fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY");
220
+ this.azureOpenAIApiKey =
221
+ fields?.azureOpenAIApiKey ??
222
+ getEnvironmentVariable("AZURE_OPENAI_API_KEY");
223
+ if (!this.azureOpenAIApiKey && !this.openAIApiKey) {
224
+ throw new Error("OpenAI or Azure OpenAI API key not found");
225
+ }
226
+ this.azureOpenAIApiInstanceName =
227
+ fields?.azureOpenAIApiInstanceName ??
228
+ getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME");
229
+ this.azureOpenAIApiDeploymentName =
230
+ (fields?.azureOpenAIApiCompletionsDeploymentName ||
231
+ fields?.azureOpenAIApiDeploymentName) ??
232
+ (getEnvironmentVariable("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") ||
233
+ getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME"));
234
+ this.azureOpenAIApiVersion =
235
+ fields?.azureOpenAIApiVersion ??
236
+ getEnvironmentVariable("AZURE_OPENAI_API_VERSION");
237
+ this.azureOpenAIBasePath =
238
+ fields?.azureOpenAIBasePath ??
239
+ getEnvironmentVariable("AZURE_OPENAI_BASE_PATH");
240
+ this.organization =
241
+ fields?.configuration?.organization ??
242
+ getEnvironmentVariable("OPENAI_ORGANIZATION");
243
+ this.modelName = fields?.modelName ?? this.modelName;
244
+ this.prefixMessages = fields?.prefixMessages ?? this.prefixMessages;
245
+ this.modelKwargs = fields?.modelKwargs ?? {};
246
+ this.timeout = fields?.timeout;
247
+ this.temperature = fields?.temperature ?? this.temperature;
248
+ this.topP = fields?.topP ?? this.topP;
249
+ this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;
250
+ this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;
251
+ this.n = fields?.n ?? this.n;
252
+ this.logitBias = fields?.logitBias;
253
+ this.maxTokens = fields?.maxTokens;
254
+ this.stop = fields?.stop;
255
+ this.user = fields?.user;
256
+ this.streaming = fields?.streaming ?? false;
257
+ if (this.n > 1) {
258
+ throw new Error("Cannot use n > 1 in OpenAIChat LLM. Use ChatOpenAI Chat Model instead.");
259
+ }
260
+ if (this.azureOpenAIApiKey) {
261
+ if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) {
262
+ throw new Error("Azure OpenAI API instance name not found");
263
+ }
264
+ if (!this.azureOpenAIApiDeploymentName) {
265
+ throw new Error("Azure OpenAI API deployment name not found");
266
+ }
267
+ if (!this.azureOpenAIApiVersion) {
268
+ throw new Error("Azure OpenAI API version not found");
269
+ }
270
+ this.openAIApiKey = this.openAIApiKey ?? "";
271
+ }
272
+ this.clientConfig = {
273
+ apiKey: this.openAIApiKey,
274
+ organization: this.organization,
275
+ baseURL: configuration?.basePath ?? fields?.configuration?.basePath,
276
+ dangerouslyAllowBrowser: true,
277
+ defaultHeaders: configuration?.baseOptions?.headers ??
278
+ fields?.configuration?.baseOptions?.headers,
279
+ defaultQuery: configuration?.baseOptions?.params ??
280
+ fields?.configuration?.baseOptions?.params,
281
+ ...configuration,
282
+ ...fields?.configuration,
283
+ };
284
+ }
285
+ /**
286
+ * Get the parameters used to invoke the model
287
+ */
288
+ invocationParams(options) {
289
+ return {
290
+ model: this.modelName,
291
+ temperature: this.temperature,
292
+ top_p: this.topP,
293
+ frequency_penalty: this.frequencyPenalty,
294
+ presence_penalty: this.presencePenalty,
295
+ n: this.n,
296
+ logit_bias: this.logitBias,
297
+ max_tokens: this.maxTokens === -1 ? undefined : this.maxTokens,
298
+ stop: options?.stop ?? this.stop,
299
+ user: this.user,
300
+ stream: this.streaming,
301
+ ...this.modelKwargs,
302
+ };
303
+ }
304
+ /** @ignore */
305
+ _identifyingParams() {
306
+ return {
307
+ model_name: this.modelName,
308
+ ...this.invocationParams(),
309
+ ...this.clientConfig,
310
+ };
311
+ }
312
+ /**
313
+ * Get the identifying parameters for the model
314
+ */
315
+ identifyingParams() {
316
+ return {
317
+ model_name: this.modelName,
318
+ ...this.invocationParams(),
319
+ ...this.clientConfig,
320
+ };
321
+ }
322
+ /**
323
+ * Formats the messages for the OpenAI API.
324
+ * @param prompt The prompt to be formatted.
325
+ * @returns Array of formatted messages.
326
+ */
327
+ formatMessages(prompt) {
328
+ const message = {
329
+ role: "user",
330
+ content: prompt,
331
+ };
332
+ return this.prefixMessages ? [...this.prefixMessages, message] : [message];
333
+ }
334
+ async *_streamResponseChunks(prompt, options, runManager) {
335
+ const params = {
336
+ ...this.invocationParams(options),
337
+ messages: this.formatMessages(prompt),
338
+ stream: true,
339
+ };
340
+ const stream = await this.completionWithRetry(params, options);
341
+ for await (const data of stream) {
342
+ const choice = data?.choices[0];
343
+ if (!choice) {
344
+ continue;
345
+ }
346
+ const { delta } = choice;
347
+ const generationChunk = new GenerationChunk({
348
+ text: delta.content ?? "",
349
+ });
350
+ yield generationChunk;
351
+ const newTokenIndices = {
352
+ prompt: options.promptIndex ?? 0,
353
+ completion: choice.index ?? 0,
354
+ };
355
+ // eslint-disable-next-line no-void
356
+ void runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices);
357
+ }
358
+ if (options.signal?.aborted) {
359
+ throw new Error("AbortError");
360
+ }
361
+ }
362
+ /** @ignore */
363
+ async _call(prompt, options, runManager) {
364
+ const params = this.invocationParams(options);
365
+ if (params.stream) {
366
+ const stream = await this._streamResponseChunks(prompt, options, runManager);
367
+ let finalChunk;
368
+ for await (const chunk of stream) {
369
+ if (finalChunk === undefined) {
370
+ finalChunk = chunk;
371
+ }
372
+ else {
373
+ finalChunk = finalChunk.concat(chunk);
374
+ }
375
+ }
376
+ return finalChunk?.text ?? "";
377
+ }
378
+ else {
379
+ const response = await this.completionWithRetry({
380
+ ...params,
381
+ stream: false,
382
+ messages: this.formatMessages(prompt),
383
+ }, {
384
+ signal: options.signal,
385
+ ...options.options,
386
+ });
387
+ return response?.choices[0]?.message?.content ?? "";
388
+ }
389
+ }
390
+ async completionWithRetry(request, options) {
391
+ const requestOptions = this._getClientOptions(options);
392
+ return this.caller.call(async () => {
393
+ try {
394
+ const res = await this.client.chat.completions.create(request, requestOptions);
395
+ return res;
396
+ }
397
+ catch (e) {
398
+ const error = wrapOpenAIClientError(e);
399
+ throw error;
400
+ }
401
+ });
402
+ }
403
+ /** @ignore */
404
+ _getClientOptions(options) {
405
+ if (!this.client) {
406
+ const openAIEndpointConfig = {
407
+ azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName,
408
+ azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName,
409
+ azureOpenAIApiKey: this.azureOpenAIApiKey,
410
+ azureOpenAIBasePath: this.azureOpenAIBasePath,
411
+ baseURL: this.clientConfig.baseURL,
412
+ };
413
+ const endpoint = getEndpoint(openAIEndpointConfig);
414
+ const params = {
415
+ ...this.clientConfig,
416
+ baseURL: endpoint,
417
+ timeout: this.timeout,
418
+ maxRetries: 0,
419
+ };
420
+ if (!params.baseURL) {
421
+ delete params.baseURL;
422
+ }
423
+ this.client = new OpenAIClient(params);
424
+ }
425
+ const requestOptions = {
426
+ ...this.clientConfig,
427
+ ...options,
428
+ };
429
+ if (this.azureOpenAIApiKey) {
430
+ requestOptions.headers = {
431
+ "api-key": this.azureOpenAIApiKey,
432
+ ...requestOptions.headers,
433
+ };
434
+ requestOptions.query = {
435
+ "api-version": this.azureOpenAIApiVersion,
436
+ ...requestOptions.query,
437
+ };
438
+ }
439
+ return requestOptions;
440
+ }
441
+ _llmType() {
442
+ return "openai";
443
+ }
444
+ }