@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/LICENSE +21 -0
- package/README.md +1 -0
- package/dist/chat_models.cjs +700 -0
- package/dist/chat_models.d.ts +141 -0
- package/dist/chat_models.js +695 -0
- package/dist/embeddings.cjs +243 -0
- package/dist/embeddings.d.ts +82 -0
- package/dist/embeddings.js +239 -0
- package/dist/index.cjs +26 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/legacy.cjs +448 -0
- package/dist/legacy.d.ts +124 -0
- package/dist/legacy.js +444 -0
- package/dist/llms.cjs +531 -0
- package/dist/llms.d.ts +126 -0
- package/dist/llms.js +527 -0
- package/dist/types.cjs +2 -0
- package/dist/types.d.ts +135 -0
- package/dist/types.js +1 -0
- package/dist/utils/azure.cjs +44 -0
- package/dist/utils/azure.d.ts +30 -0
- package/dist/utils/azure.js +40 -0
- package/dist/utils/chunk.cjs +11 -0
- package/dist/utils/chunk.d.ts +1 -0
- package/dist/utils/chunk.js +7 -0
- package/dist/utils/openai-format-fndef.cjs +81 -0
- package/dist/utils/openai-format-fndef.d.ts +44 -0
- package/dist/utils/openai-format-fndef.js +77 -0
- package/dist/utils/openai.cjs +59 -0
- package/dist/utils/openai.d.ts +12 -0
- package/dist/utils/openai.js +52 -0
- package/index.cjs +1 -0
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/package.json +90 -0
package/dist/llms.js
ADDED
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
import { OpenAI as OpenAIClient } from "openai";
|
|
2
|
+
import { calculateMaxTokens } from "@langchain/core/language_models/base";
|
|
3
|
+
import { GenerationChunk } from "@langchain/core/outputs";
|
|
4
|
+
import { getEnvironmentVariable } from "@langchain/core/utils/env";
|
|
5
|
+
import { BaseLLM, } from "@langchain/core/language_models/llms";
|
|
6
|
+
import { getEndpoint } from "./utils/azure.js";
|
|
7
|
+
import { chunkArray } from "./utils/chunk.js";
|
|
8
|
+
import { OpenAIChat } from "./legacy.js";
|
|
9
|
+
import { wrapOpenAIClientError } from "./utils/openai.js";
|
|
10
|
+
export { OpenAIChat };
|
|
11
|
+
/**
|
|
12
|
+
* Wrapper around OpenAI large language models.
|
|
13
|
+
*
|
|
14
|
+
* To use you should have the `openai` package installed, with the
|
|
15
|
+
* `OPENAI_API_KEY` environment variable set.
|
|
16
|
+
*
|
|
17
|
+
* To use with Azure you should have the `openai` package installed, with the
|
|
18
|
+
* `AZURE_OPENAI_API_KEY`,
|
|
19
|
+
* `AZURE_OPENAI_API_INSTANCE_NAME`,
|
|
20
|
+
* `AZURE_OPENAI_API_DEPLOYMENT_NAME`
|
|
21
|
+
* and `AZURE_OPENAI_API_VERSION` environment variable set.
|
|
22
|
+
*
|
|
23
|
+
* @remarks
|
|
24
|
+
* Any parameters that are valid to be passed to {@link
|
|
25
|
+
* https://platform.openai.com/docs/api-reference/completions/create |
|
|
26
|
+
* `openai.createCompletion`} can be passed through {@link modelKwargs}, even
|
|
27
|
+
* if not explicitly available on this class.
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* const model = new OpenAI({
|
|
31
|
+
* modelName: "gpt-4",
|
|
32
|
+
* temperature: 0.7,
|
|
33
|
+
* maxTokens: 1000,
|
|
34
|
+
* maxRetries: 5,
|
|
35
|
+
* });
|
|
36
|
+
*
|
|
37
|
+
* const res = await model.call(
|
|
38
|
+
* "Question: What would be a good company name for a company that makes colorful socks?\nAnswer:"
|
|
39
|
+
* );
|
|
40
|
+
* console.log({ res });
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export class OpenAI extends BaseLLM {
|
|
44
|
+
static lc_name() {
|
|
45
|
+
return "OpenAI";
|
|
46
|
+
}
|
|
47
|
+
get callKeys() {
|
|
48
|
+
return [...super.callKeys, "options"];
|
|
49
|
+
}
|
|
50
|
+
get lc_secrets() {
|
|
51
|
+
return {
|
|
52
|
+
openAIApiKey: "OPENAI_API_KEY",
|
|
53
|
+
azureOpenAIApiKey: "AZURE_OPENAI_API_KEY",
|
|
54
|
+
organization: "OPENAI_ORGANIZATION",
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
get lc_aliases() {
|
|
58
|
+
return {
|
|
59
|
+
modelName: "model",
|
|
60
|
+
openAIApiKey: "openai_api_key",
|
|
61
|
+
azureOpenAIApiVersion: "azure_openai_api_version",
|
|
62
|
+
azureOpenAIApiKey: "azure_openai_api_key",
|
|
63
|
+
azureOpenAIApiInstanceName: "azure_openai_api_instance_name",
|
|
64
|
+
azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name",
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
constructor(fields,
|
|
68
|
+
/** @deprecated */
|
|
69
|
+
configuration) {
|
|
70
|
+
if ((fields?.modelName?.startsWith("gpt-3.5-turbo") ||
|
|
71
|
+
fields?.modelName?.startsWith("gpt-4")) &&
|
|
72
|
+
!fields?.modelName?.includes("-instruct")) {
|
|
73
|
+
// eslint-disable-next-line no-constructor-return
|
|
74
|
+
return new OpenAIChat(fields, configuration);
|
|
75
|
+
}
|
|
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: 0.7
|
|
88
|
+
});
|
|
89
|
+
Object.defineProperty(this, "maxTokens", {
|
|
90
|
+
enumerable: true,
|
|
91
|
+
configurable: true,
|
|
92
|
+
writable: true,
|
|
93
|
+
value: 256
|
|
94
|
+
});
|
|
95
|
+
Object.defineProperty(this, "topP", {
|
|
96
|
+
enumerable: true,
|
|
97
|
+
configurable: true,
|
|
98
|
+
writable: true,
|
|
99
|
+
value: 1
|
|
100
|
+
});
|
|
101
|
+
Object.defineProperty(this, "frequencyPenalty", {
|
|
102
|
+
enumerable: true,
|
|
103
|
+
configurable: true,
|
|
104
|
+
writable: true,
|
|
105
|
+
value: 0
|
|
106
|
+
});
|
|
107
|
+
Object.defineProperty(this, "presencePenalty", {
|
|
108
|
+
enumerable: true,
|
|
109
|
+
configurable: true,
|
|
110
|
+
writable: true,
|
|
111
|
+
value: 0
|
|
112
|
+
});
|
|
113
|
+
Object.defineProperty(this, "n", {
|
|
114
|
+
enumerable: true,
|
|
115
|
+
configurable: true,
|
|
116
|
+
writable: true,
|
|
117
|
+
value: 1
|
|
118
|
+
});
|
|
119
|
+
Object.defineProperty(this, "bestOf", {
|
|
120
|
+
enumerable: true,
|
|
121
|
+
configurable: true,
|
|
122
|
+
writable: true,
|
|
123
|
+
value: void 0
|
|
124
|
+
});
|
|
125
|
+
Object.defineProperty(this, "logitBias", {
|
|
126
|
+
enumerable: true,
|
|
127
|
+
configurable: true,
|
|
128
|
+
writable: true,
|
|
129
|
+
value: void 0
|
|
130
|
+
});
|
|
131
|
+
Object.defineProperty(this, "modelName", {
|
|
132
|
+
enumerable: true,
|
|
133
|
+
configurable: true,
|
|
134
|
+
writable: true,
|
|
135
|
+
value: "gpt-3.5-turbo-instruct"
|
|
136
|
+
});
|
|
137
|
+
Object.defineProperty(this, "modelKwargs", {
|
|
138
|
+
enumerable: true,
|
|
139
|
+
configurable: true,
|
|
140
|
+
writable: true,
|
|
141
|
+
value: void 0
|
|
142
|
+
});
|
|
143
|
+
Object.defineProperty(this, "batchSize", {
|
|
144
|
+
enumerable: true,
|
|
145
|
+
configurable: true,
|
|
146
|
+
writable: true,
|
|
147
|
+
value: 20
|
|
148
|
+
});
|
|
149
|
+
Object.defineProperty(this, "timeout", {
|
|
150
|
+
enumerable: true,
|
|
151
|
+
configurable: true,
|
|
152
|
+
writable: true,
|
|
153
|
+
value: void 0
|
|
154
|
+
});
|
|
155
|
+
Object.defineProperty(this, "stop", {
|
|
156
|
+
enumerable: true,
|
|
157
|
+
configurable: true,
|
|
158
|
+
writable: true,
|
|
159
|
+
value: void 0
|
|
160
|
+
});
|
|
161
|
+
Object.defineProperty(this, "user", {
|
|
162
|
+
enumerable: true,
|
|
163
|
+
configurable: true,
|
|
164
|
+
writable: true,
|
|
165
|
+
value: void 0
|
|
166
|
+
});
|
|
167
|
+
Object.defineProperty(this, "streaming", {
|
|
168
|
+
enumerable: true,
|
|
169
|
+
configurable: true,
|
|
170
|
+
writable: true,
|
|
171
|
+
value: false
|
|
172
|
+
});
|
|
173
|
+
Object.defineProperty(this, "openAIApiKey", {
|
|
174
|
+
enumerable: true,
|
|
175
|
+
configurable: true,
|
|
176
|
+
writable: true,
|
|
177
|
+
value: void 0
|
|
178
|
+
});
|
|
179
|
+
Object.defineProperty(this, "azureOpenAIApiVersion", {
|
|
180
|
+
enumerable: true,
|
|
181
|
+
configurable: true,
|
|
182
|
+
writable: true,
|
|
183
|
+
value: void 0
|
|
184
|
+
});
|
|
185
|
+
Object.defineProperty(this, "azureOpenAIApiKey", {
|
|
186
|
+
enumerable: true,
|
|
187
|
+
configurable: true,
|
|
188
|
+
writable: true,
|
|
189
|
+
value: void 0
|
|
190
|
+
});
|
|
191
|
+
Object.defineProperty(this, "azureOpenAIApiInstanceName", {
|
|
192
|
+
enumerable: true,
|
|
193
|
+
configurable: true,
|
|
194
|
+
writable: true,
|
|
195
|
+
value: void 0
|
|
196
|
+
});
|
|
197
|
+
Object.defineProperty(this, "azureOpenAIApiDeploymentName", {
|
|
198
|
+
enumerable: true,
|
|
199
|
+
configurable: true,
|
|
200
|
+
writable: true,
|
|
201
|
+
value: void 0
|
|
202
|
+
});
|
|
203
|
+
Object.defineProperty(this, "azureOpenAIBasePath", {
|
|
204
|
+
enumerable: true,
|
|
205
|
+
configurable: true,
|
|
206
|
+
writable: true,
|
|
207
|
+
value: void 0
|
|
208
|
+
});
|
|
209
|
+
Object.defineProperty(this, "organization", {
|
|
210
|
+
enumerable: true,
|
|
211
|
+
configurable: true,
|
|
212
|
+
writable: true,
|
|
213
|
+
value: void 0
|
|
214
|
+
});
|
|
215
|
+
Object.defineProperty(this, "client", {
|
|
216
|
+
enumerable: true,
|
|
217
|
+
configurable: true,
|
|
218
|
+
writable: true,
|
|
219
|
+
value: void 0
|
|
220
|
+
});
|
|
221
|
+
Object.defineProperty(this, "clientConfig", {
|
|
222
|
+
enumerable: true,
|
|
223
|
+
configurable: true,
|
|
224
|
+
writable: true,
|
|
225
|
+
value: void 0
|
|
226
|
+
});
|
|
227
|
+
this.openAIApiKey =
|
|
228
|
+
fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY");
|
|
229
|
+
this.azureOpenAIApiKey =
|
|
230
|
+
fields?.azureOpenAIApiKey ??
|
|
231
|
+
getEnvironmentVariable("AZURE_OPENAI_API_KEY");
|
|
232
|
+
if (!this.azureOpenAIApiKey && !this.openAIApiKey) {
|
|
233
|
+
throw new Error("OpenAI or Azure OpenAI API key not found");
|
|
234
|
+
}
|
|
235
|
+
this.azureOpenAIApiInstanceName =
|
|
236
|
+
fields?.azureOpenAIApiInstanceName ??
|
|
237
|
+
getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME");
|
|
238
|
+
this.azureOpenAIApiDeploymentName =
|
|
239
|
+
(fields?.azureOpenAIApiCompletionsDeploymentName ||
|
|
240
|
+
fields?.azureOpenAIApiDeploymentName) ??
|
|
241
|
+
(getEnvironmentVariable("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") ||
|
|
242
|
+
getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME"));
|
|
243
|
+
this.azureOpenAIApiVersion =
|
|
244
|
+
fields?.azureOpenAIApiVersion ??
|
|
245
|
+
getEnvironmentVariable("AZURE_OPENAI_API_VERSION");
|
|
246
|
+
this.azureOpenAIBasePath =
|
|
247
|
+
fields?.azureOpenAIBasePath ??
|
|
248
|
+
getEnvironmentVariable("AZURE_OPENAI_BASE_PATH");
|
|
249
|
+
this.organization =
|
|
250
|
+
fields?.configuration?.organization ??
|
|
251
|
+
getEnvironmentVariable("OPENAI_ORGANIZATION");
|
|
252
|
+
this.modelName = fields?.modelName ?? this.modelName;
|
|
253
|
+
this.modelKwargs = fields?.modelKwargs ?? {};
|
|
254
|
+
this.batchSize = fields?.batchSize ?? this.batchSize;
|
|
255
|
+
this.timeout = fields?.timeout;
|
|
256
|
+
this.temperature = fields?.temperature ?? this.temperature;
|
|
257
|
+
this.maxTokens = fields?.maxTokens ?? this.maxTokens;
|
|
258
|
+
this.topP = fields?.topP ?? this.topP;
|
|
259
|
+
this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;
|
|
260
|
+
this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;
|
|
261
|
+
this.n = fields?.n ?? this.n;
|
|
262
|
+
this.bestOf = fields?.bestOf ?? this.bestOf;
|
|
263
|
+
this.logitBias = fields?.logitBias;
|
|
264
|
+
this.stop = fields?.stop;
|
|
265
|
+
this.user = fields?.user;
|
|
266
|
+
this.streaming = fields?.streaming ?? false;
|
|
267
|
+
if (this.streaming && this.bestOf && this.bestOf > 1) {
|
|
268
|
+
throw new Error("Cannot stream results when bestOf > 1");
|
|
269
|
+
}
|
|
270
|
+
if (this.azureOpenAIApiKey) {
|
|
271
|
+
if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) {
|
|
272
|
+
throw new Error("Azure OpenAI API instance name not found");
|
|
273
|
+
}
|
|
274
|
+
if (!this.azureOpenAIApiDeploymentName) {
|
|
275
|
+
throw new Error("Azure OpenAI API deployment name not found");
|
|
276
|
+
}
|
|
277
|
+
if (!this.azureOpenAIApiVersion) {
|
|
278
|
+
throw new Error("Azure OpenAI API version not found");
|
|
279
|
+
}
|
|
280
|
+
this.openAIApiKey = this.openAIApiKey ?? "";
|
|
281
|
+
}
|
|
282
|
+
this.clientConfig = {
|
|
283
|
+
apiKey: this.openAIApiKey,
|
|
284
|
+
organization: this.organization,
|
|
285
|
+
baseURL: configuration?.basePath ?? fields?.configuration?.basePath,
|
|
286
|
+
dangerouslyAllowBrowser: true,
|
|
287
|
+
defaultHeaders: configuration?.baseOptions?.headers ??
|
|
288
|
+
fields?.configuration?.baseOptions?.headers,
|
|
289
|
+
defaultQuery: configuration?.baseOptions?.params ??
|
|
290
|
+
fields?.configuration?.baseOptions?.params,
|
|
291
|
+
...configuration,
|
|
292
|
+
...fields?.configuration,
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Get the parameters used to invoke the model
|
|
297
|
+
*/
|
|
298
|
+
invocationParams(options) {
|
|
299
|
+
return {
|
|
300
|
+
model: this.modelName,
|
|
301
|
+
temperature: this.temperature,
|
|
302
|
+
max_tokens: this.maxTokens,
|
|
303
|
+
top_p: this.topP,
|
|
304
|
+
frequency_penalty: this.frequencyPenalty,
|
|
305
|
+
presence_penalty: this.presencePenalty,
|
|
306
|
+
n: this.n,
|
|
307
|
+
best_of: this.bestOf,
|
|
308
|
+
logit_bias: this.logitBias,
|
|
309
|
+
stop: options?.stop ?? this.stop,
|
|
310
|
+
user: this.user,
|
|
311
|
+
stream: this.streaming,
|
|
312
|
+
...this.modelKwargs,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
/** @ignore */
|
|
316
|
+
_identifyingParams() {
|
|
317
|
+
return {
|
|
318
|
+
model_name: this.modelName,
|
|
319
|
+
...this.invocationParams(),
|
|
320
|
+
...this.clientConfig,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Get the identifying parameters for the model
|
|
325
|
+
*/
|
|
326
|
+
identifyingParams() {
|
|
327
|
+
return this._identifyingParams();
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Call out to OpenAI's endpoint with k unique prompts
|
|
331
|
+
*
|
|
332
|
+
* @param [prompts] - The prompts to pass into the model.
|
|
333
|
+
* @param [options] - Optional list of stop words to use when generating.
|
|
334
|
+
* @param [runManager] - Optional callback manager to use when generating.
|
|
335
|
+
*
|
|
336
|
+
* @returns The full LLM output.
|
|
337
|
+
*
|
|
338
|
+
* @example
|
|
339
|
+
* ```ts
|
|
340
|
+
* import { OpenAI } from "langchain/llms/openai";
|
|
341
|
+
* const openai = new OpenAI();
|
|
342
|
+
* const response = await openai.generate(["Tell me a joke."]);
|
|
343
|
+
* ```
|
|
344
|
+
*/
|
|
345
|
+
async _generate(prompts, options, runManager) {
|
|
346
|
+
const subPrompts = chunkArray(prompts, this.batchSize);
|
|
347
|
+
const choices = [];
|
|
348
|
+
const tokenUsage = {};
|
|
349
|
+
const params = this.invocationParams(options);
|
|
350
|
+
if (params.max_tokens === -1) {
|
|
351
|
+
if (prompts.length !== 1) {
|
|
352
|
+
throw new Error("max_tokens set to -1 not supported for multiple inputs");
|
|
353
|
+
}
|
|
354
|
+
params.max_tokens = await calculateMaxTokens({
|
|
355
|
+
prompt: prompts[0],
|
|
356
|
+
// Cast here to allow for other models that may not fit the union
|
|
357
|
+
modelName: this.modelName,
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
for (let i = 0; i < subPrompts.length; i += 1) {
|
|
361
|
+
const data = params.stream
|
|
362
|
+
? await (async () => {
|
|
363
|
+
const choices = [];
|
|
364
|
+
let response;
|
|
365
|
+
const stream = await this.completionWithRetry({
|
|
366
|
+
...params,
|
|
367
|
+
stream: true,
|
|
368
|
+
prompt: subPrompts[i],
|
|
369
|
+
}, options);
|
|
370
|
+
for await (const message of stream) {
|
|
371
|
+
// on the first message set the response properties
|
|
372
|
+
if (!response) {
|
|
373
|
+
response = {
|
|
374
|
+
id: message.id,
|
|
375
|
+
object: message.object,
|
|
376
|
+
created: message.created,
|
|
377
|
+
model: message.model,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
// on all messages, update choice
|
|
381
|
+
for (const part of message.choices) {
|
|
382
|
+
if (!choices[part.index]) {
|
|
383
|
+
choices[part.index] = part;
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
const choice = choices[part.index];
|
|
387
|
+
choice.text += part.text;
|
|
388
|
+
choice.finish_reason = part.finish_reason;
|
|
389
|
+
choice.logprobs = part.logprobs;
|
|
390
|
+
}
|
|
391
|
+
void runManager?.handleLLMNewToken(part.text, {
|
|
392
|
+
prompt: Math.floor(part.index / this.n),
|
|
393
|
+
completion: part.index % this.n,
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
if (options.signal?.aborted) {
|
|
398
|
+
throw new Error("AbortError");
|
|
399
|
+
}
|
|
400
|
+
return { ...response, choices };
|
|
401
|
+
})()
|
|
402
|
+
: await this.completionWithRetry({
|
|
403
|
+
...params,
|
|
404
|
+
stream: false,
|
|
405
|
+
prompt: subPrompts[i],
|
|
406
|
+
}, {
|
|
407
|
+
signal: options.signal,
|
|
408
|
+
...options.options,
|
|
409
|
+
});
|
|
410
|
+
choices.push(...data.choices);
|
|
411
|
+
const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data.usage
|
|
412
|
+
? data.usage
|
|
413
|
+
: {
|
|
414
|
+
completion_tokens: undefined,
|
|
415
|
+
prompt_tokens: undefined,
|
|
416
|
+
total_tokens: undefined,
|
|
417
|
+
};
|
|
418
|
+
if (completionTokens) {
|
|
419
|
+
tokenUsage.completionTokens =
|
|
420
|
+
(tokenUsage.completionTokens ?? 0) + completionTokens;
|
|
421
|
+
}
|
|
422
|
+
if (promptTokens) {
|
|
423
|
+
tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens;
|
|
424
|
+
}
|
|
425
|
+
if (totalTokens) {
|
|
426
|
+
tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
const generations = chunkArray(choices, this.n).map((promptChoices) => promptChoices.map((choice) => ({
|
|
430
|
+
text: choice.text ?? "",
|
|
431
|
+
generationInfo: {
|
|
432
|
+
finishReason: choice.finish_reason,
|
|
433
|
+
logprobs: choice.logprobs,
|
|
434
|
+
},
|
|
435
|
+
})));
|
|
436
|
+
return {
|
|
437
|
+
generations,
|
|
438
|
+
llmOutput: { tokenUsage },
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
// TODO(jacoblee): Refactor with _generate(..., {stream: true}) implementation?
|
|
442
|
+
async *_streamResponseChunks(input, options, runManager) {
|
|
443
|
+
const params = {
|
|
444
|
+
...this.invocationParams(options),
|
|
445
|
+
prompt: input,
|
|
446
|
+
stream: true,
|
|
447
|
+
};
|
|
448
|
+
const stream = await this.completionWithRetry(params, options);
|
|
449
|
+
for await (const data of stream) {
|
|
450
|
+
const choice = data?.choices[0];
|
|
451
|
+
if (!choice) {
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
const chunk = new GenerationChunk({
|
|
455
|
+
text: choice.text,
|
|
456
|
+
generationInfo: {
|
|
457
|
+
finishReason: choice.finish_reason,
|
|
458
|
+
},
|
|
459
|
+
});
|
|
460
|
+
yield chunk;
|
|
461
|
+
// eslint-disable-next-line no-void
|
|
462
|
+
void runManager?.handleLLMNewToken(chunk.text ?? "");
|
|
463
|
+
}
|
|
464
|
+
if (options.signal?.aborted) {
|
|
465
|
+
throw new Error("AbortError");
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
async completionWithRetry(request, options) {
|
|
469
|
+
const requestOptions = this._getClientOptions(options);
|
|
470
|
+
return this.caller.call(async () => {
|
|
471
|
+
try {
|
|
472
|
+
const res = await this.client.completions.create(request, requestOptions);
|
|
473
|
+
return res;
|
|
474
|
+
}
|
|
475
|
+
catch (e) {
|
|
476
|
+
const error = wrapOpenAIClientError(e);
|
|
477
|
+
throw error;
|
|
478
|
+
}
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Calls the OpenAI API with retry logic in case of failures.
|
|
483
|
+
* @param request The request to send to the OpenAI API.
|
|
484
|
+
* @param options Optional configuration for the API call.
|
|
485
|
+
* @returns The response from the OpenAI API.
|
|
486
|
+
*/
|
|
487
|
+
_getClientOptions(options) {
|
|
488
|
+
if (!this.client) {
|
|
489
|
+
const openAIEndpointConfig = {
|
|
490
|
+
azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName,
|
|
491
|
+
azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName,
|
|
492
|
+
azureOpenAIApiKey: this.azureOpenAIApiKey,
|
|
493
|
+
azureOpenAIBasePath: this.azureOpenAIBasePath,
|
|
494
|
+
baseURL: this.clientConfig.baseURL,
|
|
495
|
+
};
|
|
496
|
+
const endpoint = getEndpoint(openAIEndpointConfig);
|
|
497
|
+
const params = {
|
|
498
|
+
...this.clientConfig,
|
|
499
|
+
baseURL: endpoint,
|
|
500
|
+
timeout: this.timeout,
|
|
501
|
+
maxRetries: 0,
|
|
502
|
+
};
|
|
503
|
+
if (!params.baseURL) {
|
|
504
|
+
delete params.baseURL;
|
|
505
|
+
}
|
|
506
|
+
this.client = new OpenAIClient(params);
|
|
507
|
+
}
|
|
508
|
+
const requestOptions = {
|
|
509
|
+
...this.clientConfig,
|
|
510
|
+
...options,
|
|
511
|
+
};
|
|
512
|
+
if (this.azureOpenAIApiKey) {
|
|
513
|
+
requestOptions.headers = {
|
|
514
|
+
"api-key": this.azureOpenAIApiKey,
|
|
515
|
+
...requestOptions.headers,
|
|
516
|
+
};
|
|
517
|
+
requestOptions.query = {
|
|
518
|
+
"api-version": this.azureOpenAIApiVersion,
|
|
519
|
+
...requestOptions.query,
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
return requestOptions;
|
|
523
|
+
}
|
|
524
|
+
_llmType() {
|
|
525
|
+
return "openai";
|
|
526
|
+
}
|
|
527
|
+
}
|
package/dist/types.cjs
ADDED
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { OpenAI as OpenAIClient } from "openai";
|
|
2
|
+
import { TiktokenModel } from "js-tiktoken/lite";
|
|
3
|
+
import type { BaseLanguageModelCallOptions } from "@langchain/core/language_models/base";
|
|
4
|
+
export type { TiktokenModel };
|
|
5
|
+
export declare interface OpenAIBaseInput {
|
|
6
|
+
/** Sampling temperature to use */
|
|
7
|
+
temperature: number;
|
|
8
|
+
/**
|
|
9
|
+
* Maximum number of tokens to generate in the completion. -1 returns as many
|
|
10
|
+
* tokens as possible given the prompt and the model's maximum context size.
|
|
11
|
+
*/
|
|
12
|
+
maxTokens?: number;
|
|
13
|
+
/** Total probability mass of tokens to consider at each step */
|
|
14
|
+
topP: number;
|
|
15
|
+
/** Penalizes repeated tokens according to frequency */
|
|
16
|
+
frequencyPenalty: number;
|
|
17
|
+
/** Penalizes repeated tokens */
|
|
18
|
+
presencePenalty: number;
|
|
19
|
+
/** Number of completions to generate for each prompt */
|
|
20
|
+
n: number;
|
|
21
|
+
/** Dictionary used to adjust the probability of specific tokens being generated */
|
|
22
|
+
logitBias?: Record<string, number>;
|
|
23
|
+
/** Unique string identifier representing your end-user, which can help OpenAI to monitor and detect abuse. */
|
|
24
|
+
user?: string;
|
|
25
|
+
/** Whether to stream the results or not. Enabling disables tokenUsage reporting */
|
|
26
|
+
streaming: boolean;
|
|
27
|
+
/** Model name to use */
|
|
28
|
+
modelName: string;
|
|
29
|
+
/** Holds any additional parameters that are valid to pass to {@link
|
|
30
|
+
* https://platform.openai.com/docs/api-reference/completions/create |
|
|
31
|
+
* `openai.createCompletion`} that are not explicitly specified on this class.
|
|
32
|
+
*/
|
|
33
|
+
modelKwargs?: Record<string, any>;
|
|
34
|
+
/** List of stop words to use when generating */
|
|
35
|
+
stop?: string[];
|
|
36
|
+
/**
|
|
37
|
+
* Timeout to use when making requests to OpenAI.
|
|
38
|
+
*/
|
|
39
|
+
timeout?: number;
|
|
40
|
+
/**
|
|
41
|
+
* API key to use when making requests to OpenAI. Defaults to the value of
|
|
42
|
+
* `OPENAI_API_KEY` environment variable.
|
|
43
|
+
*/
|
|
44
|
+
openAIApiKey?: string;
|
|
45
|
+
}
|
|
46
|
+
export type OpenAICoreRequestOptions<Req extends object = Record<string, unknown>> = {
|
|
47
|
+
path?: string;
|
|
48
|
+
query?: Req | undefined;
|
|
49
|
+
body?: Req | undefined;
|
|
50
|
+
headers?: Record<string, string | null | undefined> | undefined;
|
|
51
|
+
maxRetries?: number;
|
|
52
|
+
stream?: boolean | undefined;
|
|
53
|
+
timeout?: number;
|
|
54
|
+
httpAgent?: any;
|
|
55
|
+
signal?: AbortSignal | undefined | null;
|
|
56
|
+
idempotencyKey?: string;
|
|
57
|
+
};
|
|
58
|
+
export interface OpenAICallOptions extends BaseLanguageModelCallOptions {
|
|
59
|
+
/**
|
|
60
|
+
* Additional options to pass to the underlying axios request.
|
|
61
|
+
*/
|
|
62
|
+
options?: OpenAICoreRequestOptions;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Input to OpenAI class.
|
|
66
|
+
*/
|
|
67
|
+
export declare interface OpenAIInput extends OpenAIBaseInput {
|
|
68
|
+
/** Generates `bestOf` completions server side and returns the "best" */
|
|
69
|
+
bestOf?: number;
|
|
70
|
+
/** Batch size to use when passing multiple documents to generate */
|
|
71
|
+
batchSize: number;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* @deprecated Use "baseURL", "defaultHeaders", and "defaultParams" instead.
|
|
75
|
+
*/
|
|
76
|
+
export interface LegacyOpenAIInput {
|
|
77
|
+
/** @deprecated Use baseURL instead */
|
|
78
|
+
basePath?: string;
|
|
79
|
+
/** @deprecated Use defaultHeaders and defaultQuery instead */
|
|
80
|
+
baseOptions?: {
|
|
81
|
+
headers?: Record<string, string>;
|
|
82
|
+
params?: Record<string, string>;
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
export interface OpenAIChatInput extends OpenAIBaseInput {
|
|
86
|
+
/** ChatGPT messages to pass as a prefix to the prompt */
|
|
87
|
+
prefixMessages?: OpenAIClient.Chat.CreateChatCompletionRequestMessage[];
|
|
88
|
+
}
|
|
89
|
+
export declare interface AzureOpenAIInput {
|
|
90
|
+
/**
|
|
91
|
+
* API version to use when making requests to Azure OpenAI.
|
|
92
|
+
*/
|
|
93
|
+
azureOpenAIApiVersion?: string;
|
|
94
|
+
/**
|
|
95
|
+
* API key to use when making requests to Azure OpenAI.
|
|
96
|
+
*/
|
|
97
|
+
azureOpenAIApiKey?: string;
|
|
98
|
+
/**
|
|
99
|
+
* Azure OpenAI API instance name to use when making requests to Azure OpenAI.
|
|
100
|
+
* this is the name of the instance you created in the Azure portal.
|
|
101
|
+
* e.g. "my-openai-instance"
|
|
102
|
+
* this will be used in the endpoint URL: https://my-openai-instance.openai.azure.com/openai/deployments/{DeploymentName}/
|
|
103
|
+
*/
|
|
104
|
+
azureOpenAIApiInstanceName?: string;
|
|
105
|
+
/**
|
|
106
|
+
* Azure OpenAI API deployment name to use for completions when making requests to Azure OpenAI.
|
|
107
|
+
* This is the name of the deployment you created in the Azure portal.
|
|
108
|
+
* e.g. "my-openai-deployment"
|
|
109
|
+
* this will be used in the endpoint URL: https://{InstanceName}.openai.azure.com/openai/deployments/my-openai-deployment/
|
|
110
|
+
*/
|
|
111
|
+
azureOpenAIApiDeploymentName?: string;
|
|
112
|
+
/**
|
|
113
|
+
* Azure OpenAI API deployment name to use for embedding when making requests to Azure OpenAI.
|
|
114
|
+
* This is the name of the deployment you created in the Azure portal.
|
|
115
|
+
* This will fallback to azureOpenAIApiDeploymentName if not provided.
|
|
116
|
+
* e.g. "my-openai-deployment"
|
|
117
|
+
* this will be used in the endpoint URL: https://{InstanceName}.openai.azure.com/openai/deployments/my-openai-deployment/
|
|
118
|
+
*/
|
|
119
|
+
azureOpenAIApiEmbeddingsDeploymentName?: string;
|
|
120
|
+
/**
|
|
121
|
+
* Azure OpenAI API deployment name to use for completions when making requests to Azure OpenAI.
|
|
122
|
+
* Completions are only available for gpt-3.5-turbo and text-davinci-003 deployments.
|
|
123
|
+
* This is the name of the deployment you created in the Azure portal.
|
|
124
|
+
* This will fallback to azureOpenAIApiDeploymentName if not provided.
|
|
125
|
+
* e.g. "my-openai-deployment"
|
|
126
|
+
* this will be used in the endpoint URL: https://{InstanceName}.openai.azure.com/openai/deployments/my-openai-deployment/
|
|
127
|
+
*/
|
|
128
|
+
azureOpenAIApiCompletionsDeploymentName?: string;
|
|
129
|
+
/**
|
|
130
|
+
* Custom endpoint for Azure OpenAI API. This is useful in case you have a deployment in another region.
|
|
131
|
+
* e.g. setting this value to "https://westeurope.api.cognitive.microsoft.com/openai/deployments"
|
|
132
|
+
* will be result in the endpoint URL: https://westeurope.api.cognitive.microsoft.com/openai/deployments/{DeploymentName}/
|
|
133
|
+
*/
|
|
134
|
+
azureOpenAIBasePath?: string;
|
|
135
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|