-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
embeddings.ts
315 lines (271 loc) Β· 9.65 KB
/
embeddings.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import { type ClientOptions, OpenAI as OpenAIClient } from "openai";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
import {
AzureOpenAIInput,
OpenAICoreRequestOptions,
LegacyOpenAIInput,
} from "./types.js";
import { getEndpoint, OpenAIEndpointConfig } from "./utils/azure.js";
import { wrapOpenAIClientError } from "./utils/openai.js";
/**
* Interface for OpenAIEmbeddings parameters. Extends EmbeddingsParams and
* defines additional parameters specific to the OpenAIEmbeddings class.
*/
export interface OpenAIEmbeddingsParams extends EmbeddingsParams {
/**
* Model name to use
* Alias for `model`
*/
modelName: string;
/** Model name to use */
model: string;
/**
* The number of dimensions the resulting output embeddings should have.
* Only supported in `text-embedding-3` and later models.
*/
dimensions?: number;
/**
* Timeout to use when making requests to OpenAI.
*/
timeout?: number;
/**
* The maximum number of documents to embed in a single request. This is
* limited by the OpenAI API to a maximum of 2048.
*/
batchSize?: number;
/**
* Whether to strip new lines from the input text. This is recommended by
* OpenAI for older models, but may not be suitable for all use cases.
* See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500
*/
stripNewLines?: boolean;
}
/**
* Class for generating embeddings using the OpenAI API. Extends the
* Embeddings class and implements OpenAIEmbeddingsParams and
* AzureOpenAIInput.
* @example
* ```typescript
* // Embed a query using OpenAIEmbeddings to generate embeddings for a given text
* const model = new OpenAIEmbeddings();
* const res = await model.embedQuery(
* "What would be a good company name for a company that makes colorful socks?",
* );
* console.log({ res });
*
* ```
*/
export class OpenAIEmbeddings
extends Embeddings
implements OpenAIEmbeddingsParams, AzureOpenAIInput
{
modelName = "text-embedding-ada-002";
model = "text-embedding-ada-002";
batchSize = 512;
// TODO: Update to `false` on next minor release (see: https://github.com/langchain-ai/langchainjs/pull/3612)
stripNewLines = true;
/**
* The number of dimensions the resulting output embeddings should have.
* Only supported in `text-embedding-3` and later models.
*/
dimensions?: number;
timeout?: number;
azureOpenAIApiVersion?: string;
azureOpenAIApiKey?: string;
azureADTokenProvider?: () => Promise<string>;
azureOpenAIApiInstanceName?: string;
azureOpenAIApiDeploymentName?: string;
azureOpenAIBasePath?: string;
organization?: string;
protected client: OpenAIClient;
protected clientConfig: ClientOptions;
constructor(
fields?: Partial<OpenAIEmbeddingsParams> &
Partial<AzureOpenAIInput> & {
verbose?: boolean;
/**
* The OpenAI API key to use.
* Alias for `apiKey`.
*/
openAIApiKey?: string;
/** The OpenAI API key to use. */
apiKey?: string;
configuration?: ClientOptions;
},
configuration?: ClientOptions & LegacyOpenAIInput
) {
const fieldsWithDefaults = { maxConcurrency: 2, ...fields };
super(fieldsWithDefaults);
let apiKey =
fieldsWithDefaults?.apiKey ??
fieldsWithDefaults?.openAIApiKey ??
getEnvironmentVariable("OPENAI_API_KEY");
const azureApiKey =
fieldsWithDefaults?.azureOpenAIApiKey ??
getEnvironmentVariable("AZURE_OPENAI_API_KEY");
this.azureADTokenProvider = fields?.azureADTokenProvider ?? undefined;
if (!azureApiKey && !apiKey && !this.azureADTokenProvider) {
throw new Error(
"OpenAI or Azure OpenAI API key or Token Provider not found"
);
}
const azureApiInstanceName =
fieldsWithDefaults?.azureOpenAIApiInstanceName ??
getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME");
const azureApiDeploymentName =
(fieldsWithDefaults?.azureOpenAIApiEmbeddingsDeploymentName ||
fieldsWithDefaults?.azureOpenAIApiDeploymentName) ??
(getEnvironmentVariable("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME") ||
getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME"));
const azureApiVersion =
fieldsWithDefaults?.azureOpenAIApiVersion ??
getEnvironmentVariable("AZURE_OPENAI_API_VERSION");
this.azureOpenAIBasePath =
fieldsWithDefaults?.azureOpenAIBasePath ??
getEnvironmentVariable("AZURE_OPENAI_BASE_PATH");
this.organization =
fieldsWithDefaults?.configuration?.organization ??
getEnvironmentVariable("OPENAI_ORGANIZATION");
this.modelName =
fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model;
this.model = this.modelName;
this.batchSize =
fieldsWithDefaults?.batchSize ?? (azureApiKey ? 1 : this.batchSize);
this.stripNewLines =
fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;
this.timeout = fieldsWithDefaults?.timeout;
this.dimensions = fieldsWithDefaults?.dimensions;
this.azureOpenAIApiVersion = azureApiVersion;
this.azureOpenAIApiKey = azureApiKey;
this.azureOpenAIApiInstanceName = azureApiInstanceName;
this.azureOpenAIApiDeploymentName = azureApiDeploymentName;
if (this.azureOpenAIApiKey || this.azureADTokenProvider) {
if (!this.azureOpenAIApiInstanceName && !this.azureOpenAIBasePath) {
throw new Error("Azure OpenAI API instance name not found");
}
if (!this.azureOpenAIApiDeploymentName) {
throw new Error("Azure OpenAI API deployment name not found");
}
if (!this.azureOpenAIApiVersion) {
throw new Error("Azure OpenAI API version not found");
}
apiKey = apiKey ?? "";
}
this.clientConfig = {
apiKey,
organization: this.organization,
baseURL: configuration?.basePath,
dangerouslyAllowBrowser: true,
defaultHeaders: configuration?.baseOptions?.headers,
defaultQuery: configuration?.baseOptions?.params,
...configuration,
...fields?.configuration,
};
}
/**
* Method to generate embeddings for an array of documents. Splits the
* documents into batches and makes requests to the OpenAI API to generate
* embeddings.
* @param texts Array of documents to generate embeddings for.
* @returns Promise that resolves to a 2D array of embeddings for each document.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
const batches = chunkArray(
this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts,
this.batchSize
);
const batchRequests = batches.map((batch) => {
const params: OpenAIClient.EmbeddingCreateParams = {
model: this.model,
input: batch,
};
if (this.dimensions) {
params.dimensions = this.dimensions;
}
return this.embeddingWithRetry(params);
});
const batchResponses = await Promise.all(batchRequests);
const embeddings: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batch = batches[i];
const { data: batchResponse } = batchResponses[i];
for (let j = 0; j < batch.length; j += 1) {
embeddings.push(batchResponse[j].embedding);
}
}
return embeddings;
}
/**
* Method to generate an embedding for a single document. Calls the
* embeddingWithRetry method with the document as the input.
* @param text Document to generate an embedding for.
* @returns Promise that resolves to an embedding for the document.
*/
async embedQuery(text: string): Promise<number[]> {
const params: OpenAIClient.EmbeddingCreateParams = {
model: this.model,
input: this.stripNewLines ? text.replace(/\n/g, " ") : text,
};
if (this.dimensions) {
params.dimensions = this.dimensions;
}
const { data } = await this.embeddingWithRetry(params);
return data[0].embedding;
}
/**
* Private method to make a request to the OpenAI API to generate
* embeddings. Handles the retry logic and returns the response from the
* API.
* @param request Request to send to the OpenAI API.
* @returns Promise that resolves to the response from the API.
*/
protected async embeddingWithRetry(
request: OpenAIClient.EmbeddingCreateParams
) {
if (!this.client) {
const openAIEndpointConfig: OpenAIEndpointConfig = {
azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName,
azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName,
azureOpenAIApiKey: this.azureOpenAIApiKey,
azureOpenAIBasePath: this.azureOpenAIBasePath,
baseURL: this.clientConfig.baseURL,
};
const endpoint = getEndpoint(openAIEndpointConfig);
const params = {
...this.clientConfig,
baseURL: endpoint,
timeout: this.timeout,
maxRetries: 0,
};
if (!params.baseURL) {
delete params.baseURL;
}
this.client = new OpenAIClient(params);
}
const requestOptions: OpenAICoreRequestOptions = {};
if (this.azureOpenAIApiKey) {
requestOptions.headers = {
"api-key": this.azureOpenAIApiKey,
...requestOptions.headers,
};
requestOptions.query = {
"api-version": this.azureOpenAIApiVersion,
...requestOptions.query,
};
}
return this.caller.call(async () => {
try {
const res = await this.client.embeddings.create(
request,
requestOptions
);
return res;
} catch (e) {
const error = wrapOpenAIClientError(e);
throw error;
}
});
}
}