langchain 0.0.69 → 0.0.71

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 (71) hide show
  1. package/dist/agents/mrkl/prompt.cjs +1 -1
  2. package/dist/agents/mrkl/prompt.d.ts +1 -1
  3. package/dist/agents/mrkl/prompt.js +1 -1
  4. package/dist/callbacks/base.cjs +25 -2
  5. package/dist/callbacks/base.js +2 -2
  6. package/dist/chains/llm_chain.d.ts +7 -7
  7. package/dist/chains/question_answering/load.cjs +14 -40
  8. package/dist/chains/question_answering/load.d.ts +3 -3
  9. package/dist/chains/question_answering/load.js +16 -42
  10. package/dist/chains/sql_db/sql_db_chain.cjs +4 -0
  11. package/dist/chains/sql_db/sql_db_chain.d.ts +3 -1
  12. package/dist/chains/sql_db/sql_db_chain.js +4 -0
  13. package/dist/chains/sql_db/sql_db_prompt.cjs +58 -1
  14. package/dist/chains/sql_db/sql_db_prompt.d.ts +3 -0
  15. package/dist/chains/sql_db/sql_db_prompt.js +57 -0
  16. package/dist/chat_models/openai.cjs +89 -4
  17. package/dist/chat_models/openai.d.ts +18 -53
  18. package/dist/chat_models/openai.js +90 -5
  19. package/dist/document_loaders/fs/directory.d.ts +5 -6
  20. package/dist/document_loaders/fs/pdf.d.ts +1 -1
  21. package/dist/document_loaders/fs/unstructured.cjs +68 -49
  22. package/dist/document_loaders/fs/unstructured.d.ts +16 -11
  23. package/dist/document_loaders/fs/unstructured.js +69 -50
  24. package/dist/document_loaders/web/s3.cjs +2 -1
  25. package/dist/document_loaders/web/s3.js +2 -1
  26. package/dist/embeddings/openai.cjs +86 -6
  27. package/dist/embeddings/openai.d.ts +7 -2
  28. package/dist/embeddings/openai.js +86 -6
  29. package/dist/llms/openai-chat.cjs +97 -6
  30. package/dist/llms/openai-chat.d.ts +22 -58
  31. package/dist/llms/openai-chat.js +97 -6
  32. package/dist/llms/openai.cjs +94 -5
  33. package/dist/llms/openai.d.ts +18 -59
  34. package/dist/llms/openai.js +95 -6
  35. package/dist/memory/base.cjs +1 -1
  36. package/dist/memory/base.js +1 -1
  37. package/dist/memory/index.cjs +3 -1
  38. package/dist/memory/index.d.ts +1 -0
  39. package/dist/memory/index.js +1 -0
  40. package/dist/memory/vector_store.cjs +61 -0
  41. package/dist/memory/vector_store.d.ts +19 -0
  42. package/dist/memory/vector_store.js +57 -0
  43. package/dist/output_parsers/combining.cjs +15 -4
  44. package/dist/output_parsers/combining.d.ts +1 -0
  45. package/dist/output_parsers/combining.js +15 -4
  46. package/dist/output_parsers/structured.cjs +10 -5
  47. package/dist/output_parsers/structured.js +10 -5
  48. package/dist/retrievers/time_weighted.d.ts +1 -1
  49. package/dist/tools/webbrowser.cjs +1 -1
  50. package/dist/tools/webbrowser.js +1 -1
  51. package/dist/util/sql_utils.cjs +15 -1
  52. package/dist/util/sql_utils.d.ts +2 -0
  53. package/dist/util/sql_utils.js +13 -0
  54. package/dist/vectorstores/chroma.cjs +25 -2
  55. package/dist/vectorstores/chroma.js +2 -2
  56. package/dist/vectorstores/milvus.cjs +25 -2
  57. package/dist/vectorstores/milvus.js +2 -2
  58. package/dist/vectorstores/myscale.cjs +26 -3
  59. package/dist/vectorstores/myscale.js +3 -3
  60. package/dist/vectorstores/opensearch.cjs +25 -2
  61. package/dist/vectorstores/opensearch.js +2 -2
  62. package/dist/vectorstores/pinecone.cjs +25 -2
  63. package/dist/vectorstores/pinecone.js +2 -2
  64. package/dist/vectorstores/prisma.cjs +1 -1
  65. package/dist/vectorstores/prisma.js +2 -1
  66. package/dist/vectorstores/supabase.cjs +13 -1
  67. package/dist/vectorstores/supabase.d.ts +6 -1
  68. package/dist/vectorstores/supabase.js +13 -1
  69. package/dist/vectorstores/weaviate.cjs +25 -2
  70. package/dist/vectorstores/weaviate.js +2 -2
  71. package/package.json +5 -5
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ChatOpenAI = void 0;
7
+ const browser_or_node_1 = require("browser-or-node");
7
8
  const openai_1 = require("openai");
8
9
  const axios_fetch_adapter_js_1 = __importDefault(require("../util/axios-fetch-adapter.cjs"));
9
10
  const base_js_1 = require("./base.cjs");
@@ -39,6 +40,12 @@ function openAIResponseToChatMessage(role, text) {
39
40
  * To use you should have the `openai` package installed, with the
40
41
  * `OPENAI_API_KEY` environment variable set.
41
42
  *
43
+ * To use with Azure you should have the `openai` package installed, with the
44
+ * `AZURE_OPENAI_API_KEY`,
45
+ * `AZURE_OPENAI_API_INSTANCE_NAME`,
46
+ * `AZURE_OPENAI_API_DEPLOYMENT_NAME`
47
+ * and `AZURE_OPENAI_API_VERSION` environment variable set.
48
+ *
42
49
  * @remarks
43
50
  * Any parameters that are valid to be passed to {@link
44
51
  * https://platform.openai.com/docs/api-reference/chat/create |
@@ -120,6 +127,30 @@ class ChatOpenAI extends base_js_1.BaseChatModel {
120
127
  writable: true,
121
128
  value: void 0
122
129
  });
130
+ Object.defineProperty(this, "azureOpenAIApiVersion", {
131
+ enumerable: true,
132
+ configurable: true,
133
+ writable: true,
134
+ value: void 0
135
+ });
136
+ Object.defineProperty(this, "azureOpenAIApiKey", {
137
+ enumerable: true,
138
+ configurable: true,
139
+ writable: true,
140
+ value: void 0
141
+ });
142
+ Object.defineProperty(this, "azureOpenAIApiInstanceName", {
143
+ enumerable: true,
144
+ configurable: true,
145
+ writable: true,
146
+ value: void 0
147
+ });
148
+ Object.defineProperty(this, "azureOpenAIApiDeploymentName", {
149
+ enumerable: true,
150
+ configurable: true,
151
+ writable: true,
152
+ value: void 0
153
+ });
123
154
  Object.defineProperty(this, "client", {
124
155
  enumerable: true,
125
156
  configurable: true,
@@ -137,9 +168,29 @@ class ChatOpenAI extends base_js_1.BaseChatModel {
137
168
  ? // eslint-disable-next-line no-process-env
138
169
  process.env?.OPENAI_API_KEY
139
170
  : undefined);
140
- if (!apiKey) {
141
- throw new Error("OpenAI API key not found");
171
+ const azureApiKey = fields?.azureOpenAIApiKey ??
172
+ (typeof process !== "undefined"
173
+ ? // eslint-disable-next-line no-process-env
174
+ process.env?.AZURE_OPENAI_API_KEY
175
+ : undefined);
176
+ if (!azureApiKey && !apiKey) {
177
+ throw new Error("(Azure) OpenAI API key not found");
142
178
  }
179
+ const azureApiInstanceName = fields?.azureOpenAIApiInstanceName ??
180
+ (typeof process !== "undefined"
181
+ ? // eslint-disable-next-line no-process-env
182
+ process.env?.AZURE_OPENAI_API_INSTANCE_NAME
183
+ : undefined);
184
+ const azureApiDeploymentName = fields?.azureOpenAIApiDeploymentName ??
185
+ (typeof process !== "undefined"
186
+ ? // eslint-disable-next-line no-process-env
187
+ process.env?.AZURE_OPENAI_API_DEPLOYMENT_NAME
188
+ : undefined);
189
+ const azureApiVersion = fields?.azureOpenAIApiVersion ??
190
+ (typeof process !== "undefined"
191
+ ? // eslint-disable-next-line no-process-env
192
+ process.env?.AZURE_OPENAI_API_VERSION
193
+ : undefined);
143
194
  this.modelName = fields?.modelName ?? this.modelName;
144
195
  this.modelKwargs = fields?.modelKwargs ?? {};
145
196
  this.timeout = fields?.timeout;
@@ -152,9 +203,24 @@ class ChatOpenAI extends base_js_1.BaseChatModel {
152
203
  this.logitBias = fields?.logitBias;
153
204
  this.stop = fields?.stop;
154
205
  this.streaming = fields?.streaming ?? false;
206
+ this.azureOpenAIApiVersion = azureApiVersion;
207
+ this.azureOpenAIApiKey = azureApiKey;
208
+ this.azureOpenAIApiInstanceName = azureApiInstanceName;
209
+ this.azureOpenAIApiDeploymentName = azureApiDeploymentName;
155
210
  if (this.streaming && this.n > 1) {
156
211
  throw new Error("Cannot stream results when n > 1");
157
212
  }
213
+ if (this.azureOpenAIApiKey) {
214
+ if (!this.azureOpenAIApiInstanceName) {
215
+ throw new Error("Azure OpenAI API instance name not found");
216
+ }
217
+ if (!this.azureOpenAIApiDeploymentName) {
218
+ throw new Error("Azure OpenAI API deployment name not found");
219
+ }
220
+ if (!this.azureOpenAIApiVersion) {
221
+ throw new Error("Azure OpenAI API version not found");
222
+ }
223
+ }
158
224
  this.clientConfig = {
159
225
  apiKey,
160
226
  ...configuration,
@@ -220,6 +286,7 @@ class ChatOpenAI extends base_js_1.BaseChatModel {
220
286
  messages: messagesMapped,
221
287
  }, {
222
288
  ...options,
289
+ adapter: axios_fetch_adapter_js_1.default,
223
290
  responseType: "stream",
224
291
  onmessage: (event) => {
225
292
  if (event.data?.trim?.() === "[DONE]") {
@@ -321,18 +388,36 @@ class ChatOpenAI extends base_js_1.BaseChatModel {
321
388
  /** @ignore */
322
389
  async completionWithRetry(request, options) {
323
390
  if (!this.client) {
391
+ const endpoint = this.azureOpenAIApiKey
392
+ ? `https://${this.azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${this.azureOpenAIApiDeploymentName}`
393
+ : this.clientConfig.basePath;
324
394
  const clientConfig = new openai_1.Configuration({
325
395
  ...this.clientConfig,
396
+ basePath: endpoint,
326
397
  baseOptions: {
327
398
  timeout: this.timeout,
328
- adapter: axios_fetch_adapter_js_1.default,
329
399
  ...this.clientConfig.baseOptions,
330
400
  },
331
401
  });
332
402
  this.client = new openai_1.OpenAIApi(clientConfig);
333
403
  }
404
+ const axiosOptions = {
405
+ adapter: browser_or_node_1.isNode ? undefined : axios_fetch_adapter_js_1.default,
406
+ ...this.clientConfig.baseOptions,
407
+ ...options,
408
+ };
409
+ if (this.azureOpenAIApiKey) {
410
+ axiosOptions.headers = {
411
+ "api-key": this.azureOpenAIApiKey,
412
+ ...axiosOptions.headers,
413
+ };
414
+ axiosOptions.params = {
415
+ "api-version": this.azureOpenAIApiVersion,
416
+ ...axiosOptions.params,
417
+ };
418
+ }
334
419
  return this.caller
335
- .call(this.client.createChatCompletion.bind(this.client), request, options)
420
+ .call(this.client.createChatCompletion.bind(this.client), request, axiosOptions)
336
421
  .then((res) => res.data);
337
422
  }
338
423
  _llmType() {
@@ -1,9 +1,10 @@
1
1
  import { CreateChatCompletionRequest, ConfigurationParameters, CreateChatCompletionResponse } from "openai";
2
- import type { AxiosRequestConfig } from "axios";
2
+ import { AzureOpenAIInput, OpenAICallOptions, OpenAIChatInput } from "../types/open-ai-types.js";
3
3
  import type { StreamingAxiosConfiguration } from "../util/axios-types.js";
4
- import { BaseChatModel, BaseChatModelCallOptions, BaseChatModelParams } from "./base.js";
4
+ import { BaseChatModel, BaseChatModelParams } from "./base.js";
5
5
  import { BaseChatMessage, ChatResult } from "../schema/index.js";
6
6
  import { CallbackManagerForLLMRun } from "../callbacks/manager.js";
7
+ export { OpenAICallOptions, OpenAIChatInput, AzureOpenAIInput };
7
8
  interface TokenUsage {
8
9
  completionTokens?: number;
9
10
  promptTokens?: number;
@@ -12,65 +13,26 @@ interface TokenUsage {
12
13
  interface OpenAILLMOutput {
13
14
  tokenUsage: TokenUsage;
14
15
  }
15
- export interface OpenAIInput {
16
- /** Sampling temperature to use, between 0 and 2, defaults to 1 */
17
- temperature: number;
18
- /** Total probability mass of tokens to consider at each step, between 0 and 1, defaults to 1 */
19
- topP: number;
20
- /** Penalizes repeated tokens according to frequency */
21
- frequencyPenalty: number;
22
- /** Penalizes repeated tokens */
23
- presencePenalty: number;
24
- /** Number of chat completions to generate for each prompt */
25
- n: number;
26
- /** Dictionary used to adjust the probability of specific tokens being generated */
27
- logitBias?: Record<string, number>;
28
- /** Whether to stream the results or not. Enabling disables tokenUsage reporting */
29
- streaming: boolean;
30
- /**
31
- * Maximum number of tokens to generate in the completion. If not specified,
32
- * defaults to the maximum number of tokens allowed by the model.
33
- */
34
- maxTokens?: number;
35
- /** Model name to use */
36
- modelName: string;
37
- /** Holds any additional parameters that are valid to pass to {@link
38
- * https://platform.openai.com/docs/api-reference/completions/create |
39
- * `openai.create`} that are not explicitly specified on this class.
40
- */
41
- modelKwargs?: Kwargs;
42
- /** List of stop words to use when generating */
43
- stop?: string[];
44
- /**
45
- * Timeout to use when making requests to OpenAI.
46
- */
47
- timeout?: number;
48
- }
49
- export interface ChatOpenAICallOptions extends BaseChatModelCallOptions {
50
- /**
51
- * List of stop words to use when generating
52
- */
53
- stop?: string[];
54
- /**
55
- * Additional options to pass to the underlying axios request.
56
- */
57
- options?: AxiosRequestConfig;
58
- }
59
- type Kwargs = Record<string, any>;
60
16
  /**
61
17
  * Wrapper around OpenAI large language models that use the Chat endpoint.
62
18
  *
63
19
  * To use you should have the `openai` package installed, with the
64
20
  * `OPENAI_API_KEY` environment variable set.
65
21
  *
22
+ * To use with Azure you should have the `openai` package installed, with the
23
+ * `AZURE_OPENAI_API_KEY`,
24
+ * `AZURE_OPENAI_API_INSTANCE_NAME`,
25
+ * `AZURE_OPENAI_API_DEPLOYMENT_NAME`
26
+ * and `AZURE_OPENAI_API_VERSION` environment variable set.
27
+ *
66
28
  * @remarks
67
29
  * Any parameters that are valid to be passed to {@link
68
30
  * https://platform.openai.com/docs/api-reference/chat/create |
69
31
  * `openai.createCompletion`} can be passed through {@link modelKwargs}, even
70
32
  * if not explicitly available on this class.
71
33
  */
72
- export declare class ChatOpenAI extends BaseChatModel implements OpenAIInput {
73
- CallOptions: ChatOpenAICallOptions;
34
+ export declare class ChatOpenAI extends BaseChatModel implements OpenAIChatInput, AzureOpenAIInput {
35
+ CallOptions: OpenAICallOptions;
74
36
  temperature: number;
75
37
  topP: number;
76
38
  frequencyPenalty: number;
@@ -78,14 +40,18 @@ export declare class ChatOpenAI extends BaseChatModel implements OpenAIInput {
78
40
  n: number;
79
41
  logitBias?: Record<string, number>;
80
42
  modelName: string;
81
- modelKwargs?: Kwargs;
43
+ modelKwargs?: OpenAIChatInput["modelKwargs"];
82
44
  stop?: string[];
83
45
  timeout?: number;
84
46
  streaming: boolean;
85
47
  maxTokens?: number;
48
+ azureOpenAIApiVersion?: string;
49
+ azureOpenAIApiKey?: string;
50
+ azureOpenAIApiInstanceName?: string;
51
+ azureOpenAIApiDeploymentName?: string;
86
52
  private client;
87
53
  private clientConfig;
88
- constructor(fields?: Partial<OpenAIInput> & BaseChatModelParams & {
54
+ constructor(fields?: Partial<OpenAIChatInput> & Partial<AzureOpenAIInput> & BaseChatModelParams & {
89
55
  concurrency?: number;
90
56
  cache?: boolean;
91
57
  openAIApiKey?: string;
@@ -93,7 +59,7 @@ export declare class ChatOpenAI extends BaseChatModel implements OpenAIInput {
93
59
  /**
94
60
  * Get the parameters used to invoke the model
95
61
  */
96
- invocationParams(): Omit<CreateChatCompletionRequest, "messages"> & Kwargs;
62
+ invocationParams(): Omit<CreateChatCompletionRequest, "messages">;
97
63
  /** @ignore */
98
64
  _identifyingParams(): {
99
65
  apiKey?: string | Promise<string> | ((name: string) => string) | ((name: string) => Promise<string>) | undefined;
@@ -154,4 +120,3 @@ export declare class ChatOpenAI extends BaseChatModel implements OpenAIInput {
154
120
  /** @ignore */
155
121
  _combineLLMOutput(...llmOutputs: OpenAILLMOutput[]): OpenAILLMOutput;
156
122
  }
157
- export {};
@@ -1,6 +1,7 @@
1
+ import { isNode } from "browser-or-node";
1
2
  import { Configuration, OpenAIApi, } from "openai";
2
3
  import fetchAdapter from "../util/axios-fetch-adapter.js";
3
- import { BaseChatModel, } from "./base.js";
4
+ import { BaseChatModel } from "./base.js";
4
5
  import { AIChatMessage, ChatMessage, HumanChatMessage, SystemChatMessage, } from "../schema/index.js";
5
6
  import { getModelNameForTiktoken } from "../base_language/count_tokens.js";
6
7
  function messageTypeToOpenAIRole(type) {
@@ -33,6 +34,12 @@ function openAIResponseToChatMessage(role, text) {
33
34
  * To use you should have the `openai` package installed, with the
34
35
  * `OPENAI_API_KEY` environment variable set.
35
36
  *
37
+ * To use with Azure you should have the `openai` package installed, with the
38
+ * `AZURE_OPENAI_API_KEY`,
39
+ * `AZURE_OPENAI_API_INSTANCE_NAME`,
40
+ * `AZURE_OPENAI_API_DEPLOYMENT_NAME`
41
+ * and `AZURE_OPENAI_API_VERSION` environment variable set.
42
+ *
36
43
  * @remarks
37
44
  * Any parameters that are valid to be passed to {@link
38
45
  * https://platform.openai.com/docs/api-reference/chat/create |
@@ -114,6 +121,30 @@ export class ChatOpenAI extends BaseChatModel {
114
121
  writable: true,
115
122
  value: void 0
116
123
  });
124
+ Object.defineProperty(this, "azureOpenAIApiVersion", {
125
+ enumerable: true,
126
+ configurable: true,
127
+ writable: true,
128
+ value: void 0
129
+ });
130
+ Object.defineProperty(this, "azureOpenAIApiKey", {
131
+ enumerable: true,
132
+ configurable: true,
133
+ writable: true,
134
+ value: void 0
135
+ });
136
+ Object.defineProperty(this, "azureOpenAIApiInstanceName", {
137
+ enumerable: true,
138
+ configurable: true,
139
+ writable: true,
140
+ value: void 0
141
+ });
142
+ Object.defineProperty(this, "azureOpenAIApiDeploymentName", {
143
+ enumerable: true,
144
+ configurable: true,
145
+ writable: true,
146
+ value: void 0
147
+ });
117
148
  Object.defineProperty(this, "client", {
118
149
  enumerable: true,
119
150
  configurable: true,
@@ -131,9 +162,29 @@ export class ChatOpenAI extends BaseChatModel {
131
162
  ? // eslint-disable-next-line no-process-env
132
163
  process.env?.OPENAI_API_KEY
133
164
  : undefined);
134
- if (!apiKey) {
135
- throw new Error("OpenAI API key not found");
165
+ const azureApiKey = fields?.azureOpenAIApiKey ??
166
+ (typeof process !== "undefined"
167
+ ? // eslint-disable-next-line no-process-env
168
+ process.env?.AZURE_OPENAI_API_KEY
169
+ : undefined);
170
+ if (!azureApiKey && !apiKey) {
171
+ throw new Error("(Azure) OpenAI API key not found");
136
172
  }
173
+ const azureApiInstanceName = fields?.azureOpenAIApiInstanceName ??
174
+ (typeof process !== "undefined"
175
+ ? // eslint-disable-next-line no-process-env
176
+ process.env?.AZURE_OPENAI_API_INSTANCE_NAME
177
+ : undefined);
178
+ const azureApiDeploymentName = fields?.azureOpenAIApiDeploymentName ??
179
+ (typeof process !== "undefined"
180
+ ? // eslint-disable-next-line no-process-env
181
+ process.env?.AZURE_OPENAI_API_DEPLOYMENT_NAME
182
+ : undefined);
183
+ const azureApiVersion = fields?.azureOpenAIApiVersion ??
184
+ (typeof process !== "undefined"
185
+ ? // eslint-disable-next-line no-process-env
186
+ process.env?.AZURE_OPENAI_API_VERSION
187
+ : undefined);
137
188
  this.modelName = fields?.modelName ?? this.modelName;
138
189
  this.modelKwargs = fields?.modelKwargs ?? {};
139
190
  this.timeout = fields?.timeout;
@@ -146,9 +197,24 @@ export class ChatOpenAI extends BaseChatModel {
146
197
  this.logitBias = fields?.logitBias;
147
198
  this.stop = fields?.stop;
148
199
  this.streaming = fields?.streaming ?? false;
200
+ this.azureOpenAIApiVersion = azureApiVersion;
201
+ this.azureOpenAIApiKey = azureApiKey;
202
+ this.azureOpenAIApiInstanceName = azureApiInstanceName;
203
+ this.azureOpenAIApiDeploymentName = azureApiDeploymentName;
149
204
  if (this.streaming && this.n > 1) {
150
205
  throw new Error("Cannot stream results when n > 1");
151
206
  }
207
+ if (this.azureOpenAIApiKey) {
208
+ if (!this.azureOpenAIApiInstanceName) {
209
+ throw new Error("Azure OpenAI API instance name not found");
210
+ }
211
+ if (!this.azureOpenAIApiDeploymentName) {
212
+ throw new Error("Azure OpenAI API deployment name not found");
213
+ }
214
+ if (!this.azureOpenAIApiVersion) {
215
+ throw new Error("Azure OpenAI API version not found");
216
+ }
217
+ }
152
218
  this.clientConfig = {
153
219
  apiKey,
154
220
  ...configuration,
@@ -214,6 +280,7 @@ export class ChatOpenAI extends BaseChatModel {
214
280
  messages: messagesMapped,
215
281
  }, {
216
282
  ...options,
283
+ adapter: fetchAdapter,
217
284
  responseType: "stream",
218
285
  onmessage: (event) => {
219
286
  if (event.data?.trim?.() === "[DONE]") {
@@ -315,18 +382,36 @@ export class ChatOpenAI extends BaseChatModel {
315
382
  /** @ignore */
316
383
  async completionWithRetry(request, options) {
317
384
  if (!this.client) {
385
+ const endpoint = this.azureOpenAIApiKey
386
+ ? `https://${this.azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${this.azureOpenAIApiDeploymentName}`
387
+ : this.clientConfig.basePath;
318
388
  const clientConfig = new Configuration({
319
389
  ...this.clientConfig,
390
+ basePath: endpoint,
320
391
  baseOptions: {
321
392
  timeout: this.timeout,
322
- adapter: fetchAdapter,
323
393
  ...this.clientConfig.baseOptions,
324
394
  },
325
395
  });
326
396
  this.client = new OpenAIApi(clientConfig);
327
397
  }
398
+ const axiosOptions = {
399
+ adapter: isNode ? undefined : fetchAdapter,
400
+ ...this.clientConfig.baseOptions,
401
+ ...options,
402
+ };
403
+ if (this.azureOpenAIApiKey) {
404
+ axiosOptions.headers = {
405
+ "api-key": this.azureOpenAIApiKey,
406
+ ...axiosOptions.headers,
407
+ };
408
+ axiosOptions.params = {
409
+ "api-version": this.azureOpenAIApiVersion,
410
+ ...axiosOptions.params,
411
+ };
412
+ }
328
413
  return this.caller
329
- .call(this.client.createChatCompletion.bind(this.client), request, options)
414
+ .call(this.client.createChatCompletion.bind(this.client), request, axiosOptions)
330
415
  .then((res) => res.data);
331
416
  }
332
417
  _llmType() {
@@ -10,16 +10,15 @@ export declare const UnknownHandling: {
10
10
  readonly Error: "error";
11
11
  };
12
12
  export type UnknownHandling = (typeof UnknownHandling)[keyof typeof UnknownHandling];
13
+ export interface LoadersMapping {
14
+ [extension: string]: (filePath: string) => BaseDocumentLoader;
15
+ }
13
16
  export declare class DirectoryLoader extends BaseDocumentLoader {
14
17
  directoryPath: string;
15
- loaders: {
16
- [extension: string]: (filePath: string) => BaseDocumentLoader;
17
- };
18
+ loaders: LoadersMapping;
18
19
  recursive: boolean;
19
20
  unknown: UnknownHandling;
20
- constructor(directoryPath: string, loaders: {
21
- [extension: string]: (filePath: string) => BaseDocumentLoader;
22
- }, recursive?: boolean, unknown?: UnknownHandling);
21
+ constructor(directoryPath: string, loaders: LoadersMapping, recursive?: boolean, unknown?: UnknownHandling);
23
22
  load(): Promise<Document[]>;
24
23
  static imports(): Promise<{
25
24
  readdir: typeof ReaddirT;
@@ -1,5 +1,5 @@
1
+ /// <reference path="../../../src/types/pdf-parse.d.ts" />
1
2
  /// <reference types="node" resolution-mode="require"/>
2
- /// <reference types="types/pdf-parse.js" />
3
3
  import { Document } from "../../document.js";
4
4
  import { BufferLoader } from "./buffer.js";
5
5
  export declare class PDFLoader extends BufferLoader {
@@ -6,23 +6,54 @@ Object.defineProperty(exports, "UnknownHandling", { enumerable: true, get: funct
6
6
  const env_js_1 = require("../../util/env.cjs");
7
7
  const document_js_1 = require("../../document.cjs");
8
8
  const base_js_1 = require("../base.cjs");
9
+ const UNSTRUCTURED_API_FILETYPES = [
10
+ ".txt",
11
+ ".text",
12
+ ".pdf",
13
+ ".docx",
14
+ ".doc",
15
+ ".jpg",
16
+ ".jpeg",
17
+ ".eml",
18
+ ".html",
19
+ ".md",
20
+ ".pptx",
21
+ ".ppt",
22
+ ".msg",
23
+ ];
9
24
  class UnstructuredLoader extends base_js_1.BaseDocumentLoader {
10
- constructor(webPath, filePath) {
25
+ constructor(filePathOrLegacyApiUrl, optionsOrLegacyFilePath = {}) {
11
26
  super();
12
- Object.defineProperty(this, "webPath", {
27
+ Object.defineProperty(this, "filePath", {
13
28
  enumerable: true,
14
29
  configurable: true,
15
30
  writable: true,
16
- value: webPath
31
+ value: void 0
17
32
  });
18
- Object.defineProperty(this, "filePath", {
33
+ Object.defineProperty(this, "apiUrl", {
19
34
  enumerable: true,
20
35
  configurable: true,
21
36
  writable: true,
22
- value: filePath
37
+ value: "https://api.unstructured.io/general/v0/general"
23
38
  });
24
- this.filePath = filePath;
25
- this.webPath = webPath;
39
+ Object.defineProperty(this, "apiKey", {
40
+ enumerable: true,
41
+ configurable: true,
42
+ writable: true,
43
+ value: void 0
44
+ });
45
+ // Temporary shim to avoid breaking existing users
46
+ // Remove when API keys are enforced by Unstructured and existing code will break anyway
47
+ const isLegacySyntax = typeof optionsOrLegacyFilePath === "string";
48
+ if (isLegacySyntax) {
49
+ this.filePath = optionsOrLegacyFilePath;
50
+ this.apiUrl = filePathOrLegacyApiUrl;
51
+ }
52
+ else {
53
+ this.filePath = filePathOrLegacyApiUrl;
54
+ this.apiKey = optionsOrLegacyFilePath.apiKey;
55
+ this.apiUrl = optionsOrLegacyFilePath.apiUrl ?? this.apiUrl;
56
+ }
26
57
  }
27
58
  async _partition() {
28
59
  const { readFile, basename } = await this.imports();
@@ -33,9 +64,13 @@ class UnstructuredLoader extends base_js_1.BaseDocumentLoader {
33
64
  // worried about this for now.
34
65
  const formData = new FormData();
35
66
  formData.append("files", new Blob([buffer]), fileName);
36
- const response = await fetch(this.webPath, {
67
+ const headers = {
68
+ "UNSTRUCTURED-API-KEY": this.apiKey ?? "",
69
+ };
70
+ const response = await fetch(this.apiUrl, {
37
71
  method: "POST",
38
72
  body: formData,
73
+ headers,
39
74
  });
40
75
  if (!response.ok) {
41
76
  throw new Error(`Failed to partition file ${this.filePath} with error ${response.status} and message ${await response.text()}`);
@@ -75,47 +110,31 @@ class UnstructuredLoader extends base_js_1.BaseDocumentLoader {
75
110
  }
76
111
  exports.UnstructuredLoader = UnstructuredLoader;
77
112
  class UnstructuredDirectoryLoader extends directory_js_1.DirectoryLoader {
78
- constructor(webPath, directoryPath, recursive = true, unknown = directory_js_1.UnknownHandling.Warn) {
79
- const loaders = {
80
- ".txt": (p) => new UnstructuredLoader(webPath, p),
81
- ".text": (p) => new UnstructuredLoader(webPath, p),
82
- ".pdf": (p) => new UnstructuredLoader(webPath, p),
83
- ".docx": (p) => new UnstructuredLoader(webPath, p),
84
- ".doc": (p) => new UnstructuredLoader(webPath, p),
85
- ".jpg": (p) => new UnstructuredLoader(webPath, p),
86
- ".jpeg": (p) => new UnstructuredLoader(webPath, p),
87
- ".eml": (p) => new UnstructuredLoader(webPath, p),
88
- ".html": (p) => new UnstructuredLoader(webPath, p),
89
- ".md": (p) => new UnstructuredLoader(webPath, p),
90
- ".pptx": (p) => new UnstructuredLoader(webPath, p),
91
- ".ppt": (p) => new UnstructuredLoader(webPath, p),
92
- ".msg": (p) => new UnstructuredLoader(webPath, p),
93
- };
94
- super(directoryPath, loaders, recursive, unknown);
95
- Object.defineProperty(this, "webPath", {
96
- enumerable: true,
97
- configurable: true,
98
- writable: true,
99
- value: webPath
100
- });
101
- Object.defineProperty(this, "directoryPath", {
102
- enumerable: true,
103
- configurable: true,
104
- writable: true,
105
- value: directoryPath
106
- });
107
- Object.defineProperty(this, "recursive", {
108
- enumerable: true,
109
- configurable: true,
110
- writable: true,
111
- value: recursive
112
- });
113
- Object.defineProperty(this, "unknown", {
114
- enumerable: true,
115
- configurable: true,
116
- writable: true,
117
- value: unknown
118
- });
113
+ constructor(directoryPathOrLegacyApiUrl, optionsOrLegacyDirectoryPath, legacyOptionRecursive = true, legacyOptionUnknown = directory_js_1.UnknownHandling.Warn) {
114
+ let directoryPath;
115
+ let options;
116
+ // Temporary shim to avoid breaking existing users
117
+ // Remove when API keys are enforced by Unstructured and existing code will break anyway
118
+ const isLegacySyntax = typeof optionsOrLegacyDirectoryPath === "string";
119
+ if (isLegacySyntax) {
120
+ directoryPath = optionsOrLegacyDirectoryPath;
121
+ options = {
122
+ apiUrl: directoryPathOrLegacyApiUrl,
123
+ recursive: legacyOptionRecursive,
124
+ unknown: legacyOptionUnknown,
125
+ };
126
+ }
127
+ else {
128
+ directoryPath = directoryPathOrLegacyApiUrl;
129
+ options = optionsOrLegacyDirectoryPath;
130
+ }
131
+ const loader = (p) => new UnstructuredLoader(p, options);
132
+ const loaders = UNSTRUCTURED_API_FILETYPES.reduce((loadersObject, filetype) => {
133
+ // eslint-disable-next-line no-param-reassign
134
+ loadersObject[filetype] = loader;
135
+ return loadersObject;
136
+ }, {});
137
+ super(directoryPath, loaders, options.recursive, options.unknown);
119
138
  }
120
139
  }
121
140
  exports.UnstructuredDirectoryLoader = UnstructuredDirectoryLoader;
@@ -1,33 +1,38 @@
1
1
  /// <reference types="node" resolution-mode="require"/>
2
2
  /// <reference types="node" resolution-mode="require"/>
3
3
  import type { basename as BasenameT } from "node:path";
4
- import type { readFile as ReaFileT } from "node:fs/promises";
4
+ import type { readFile as ReadFileT } from "node:fs/promises";
5
5
  import { DirectoryLoader, UnknownHandling } from "./directory.js";
6
6
  import { Document } from "../../document.js";
7
7
  import { BaseDocumentLoader } from "../base.js";
8
- interface Element {
8
+ type Element = {
9
9
  type: string;
10
10
  text: string;
11
11
  metadata: {
12
12
  [key: string]: unknown;
13
13
  };
14
- }
14
+ };
15
+ type UnstructuredLoaderOptions = {
16
+ apiKey?: string;
17
+ apiUrl?: string;
18
+ };
19
+ type UnstructuredDirectoryLoaderOptions = UnstructuredLoaderOptions & {
20
+ recursive?: boolean;
21
+ unknown?: UnknownHandling;
22
+ };
15
23
  export declare class UnstructuredLoader extends BaseDocumentLoader {
16
- webPath: string;
17
24
  filePath: string;
18
- constructor(webPath: string, filePath: string);
25
+ private apiUrl;
26
+ private apiKey?;
27
+ constructor(filePathOrLegacyApiUrl: string, optionsOrLegacyFilePath?: UnstructuredLoaderOptions | string);
19
28
  _partition(): Promise<Element[]>;
20
29
  load(): Promise<Document[]>;
21
30
  imports(): Promise<{
22
- readFile: typeof ReaFileT;
31
+ readFile: typeof ReadFileT;
23
32
  basename: typeof BasenameT;
24
33
  }>;
25
34
  }
26
35
  export declare class UnstructuredDirectoryLoader extends DirectoryLoader {
27
- webPath: string;
28
- directoryPath: string;
29
- recursive: boolean;
30
- unknown: UnknownHandling;
31
- constructor(webPath: string, directoryPath: string, recursive?: boolean, unknown?: UnknownHandling);
36
+ constructor(directoryPathOrLegacyApiUrl: string, optionsOrLegacyDirectoryPath: UnstructuredDirectoryLoaderOptions | string, legacyOptionRecursive?: boolean, legacyOptionUnknown?: UnknownHandling);
32
37
  }
33
38
  export { UnknownHandling };