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