langchain 0.0.74 → 0.0.76

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 (163) hide show
  1. package/client.cjs +1 -0
  2. package/client.d.ts +1 -0
  3. package/client.js +1 -0
  4. package/dist/base_language/count_tokens.cjs +5 -21
  5. package/dist/base_language/count_tokens.d.ts +1 -6
  6. package/dist/base_language/count_tokens.js +4 -19
  7. package/dist/base_language/index.cjs +16 -24
  8. package/dist/base_language/index.d.ts +22 -3
  9. package/dist/base_language/index.js +17 -25
  10. package/dist/cache/redis.d.ts +3 -1
  11. package/dist/callbacks/base.d.ts +17 -3
  12. package/dist/callbacks/handlers/console.cjs +15 -28
  13. package/dist/callbacks/handlers/console.d.ts +11 -20
  14. package/dist/callbacks/handlers/console.js +14 -27
  15. package/dist/callbacks/handlers/initialize.cjs +8 -3
  16. package/dist/callbacks/handlers/initialize.d.ts +4 -2
  17. package/dist/callbacks/handlers/initialize.js +6 -2
  18. package/dist/callbacks/handlers/tracer.cjs +193 -0
  19. package/dist/callbacks/handlers/tracer.d.ts +65 -0
  20. package/dist/callbacks/handlers/tracer.js +189 -0
  21. package/dist/callbacks/handlers/tracer_langchain.cjs +163 -0
  22. package/dist/callbacks/handlers/tracer_langchain.d.ts +39 -0
  23. package/dist/callbacks/handlers/tracer_langchain.js +159 -0
  24. package/dist/callbacks/handlers/tracer_langchain_v1.cjs +202 -0
  25. package/dist/callbacks/handlers/tracer_langchain_v1.d.ts +57 -0
  26. package/dist/callbacks/handlers/tracer_langchain_v1.js +198 -0
  27. package/dist/callbacks/index.cjs +10 -5
  28. package/dist/callbacks/index.d.ts +5 -3
  29. package/dist/callbacks/index.js +5 -3
  30. package/dist/callbacks/manager.cjs +39 -9
  31. package/dist/callbacks/manager.d.ts +5 -2
  32. package/dist/callbacks/manager.js +40 -10
  33. package/dist/chains/llm_chain.cjs +17 -5
  34. package/dist/chains/llm_chain.d.ts +9 -3
  35. package/dist/chains/llm_chain.js +17 -5
  36. package/dist/chains/question_answering/map_reduce_prompts.cjs +5 -5
  37. package/dist/chains/question_answering/map_reduce_prompts.d.ts +1 -1
  38. package/dist/chains/question_answering/map_reduce_prompts.js +1 -1
  39. package/dist/chains/question_answering/refine_prompts.cjs +5 -5
  40. package/dist/chains/question_answering/refine_prompts.d.ts +1 -1
  41. package/dist/chains/question_answering/refine_prompts.js +1 -1
  42. package/dist/chains/question_answering/stuff_prompts.cjs +2 -2
  43. package/dist/chains/question_answering/stuff_prompts.d.ts +1 -1
  44. package/dist/chains/question_answering/stuff_prompts.js +1 -1
  45. package/dist/chains/sequential_chain.cjs +2 -2
  46. package/dist/chains/sequential_chain.d.ts +2 -2
  47. package/dist/chains/sequential_chain.js +2 -2
  48. package/dist/chains/sql_db/sql_db_prompt.cjs +20 -1
  49. package/dist/chains/sql_db/sql_db_prompt.d.ts +1 -0
  50. package/dist/chains/sql_db/sql_db_prompt.js +19 -0
  51. package/dist/chains/summarization/load.cjs +14 -5
  52. package/dist/chains/summarization/load.d.ts +7 -2
  53. package/dist/chains/summarization/load.js +14 -5
  54. package/dist/chat_models/anthropic.cjs +36 -9
  55. package/dist/chat_models/anthropic.d.ts +6 -3
  56. package/dist/chat_models/anthropic.js +36 -9
  57. package/dist/chat_models/base.cjs +40 -13
  58. package/dist/chat_models/base.d.ts +14 -7
  59. package/dist/chat_models/base.js +41 -14
  60. package/dist/chat_models/openai.cjs +20 -14
  61. package/dist/chat_models/openai.d.ts +2 -1
  62. package/dist/chat_models/openai.js +20 -14
  63. package/dist/client/index.cjs +5 -0
  64. package/dist/client/index.d.ts +1 -0
  65. package/dist/client/index.js +1 -0
  66. package/dist/client/langchainplus.cjs +405 -0
  67. package/dist/client/langchainplus.d.ts +65 -0
  68. package/dist/client/langchainplus.js +398 -0
  69. package/dist/document_loaders/fs/unstructured.cjs +8 -0
  70. package/dist/document_loaders/fs/unstructured.d.ts +3 -0
  71. package/dist/document_loaders/fs/unstructured.js +8 -0
  72. package/dist/document_loaders/web/apify_dataset.cjs +64 -0
  73. package/dist/document_loaders/web/apify_dataset.d.ts +28 -0
  74. package/dist/document_loaders/web/apify_dataset.js +60 -0
  75. package/dist/embeddings/openai.cjs +2 -2
  76. package/dist/embeddings/openai.js +2 -2
  77. package/dist/llms/base.cjs +43 -17
  78. package/dist/llms/base.d.ts +16 -9
  79. package/dist/llms/base.js +44 -18
  80. package/dist/llms/cohere.cjs +3 -2
  81. package/dist/llms/cohere.d.ts +1 -1
  82. package/dist/llms/cohere.js +3 -2
  83. package/dist/llms/hf.cjs +2 -2
  84. package/dist/llms/hf.d.ts +1 -1
  85. package/dist/llms/hf.js +2 -2
  86. package/dist/llms/openai-chat.cjs +13 -14
  87. package/dist/llms/openai-chat.d.ts +2 -1
  88. package/dist/llms/openai-chat.js +13 -14
  89. package/dist/llms/openai.cjs +15 -13
  90. package/dist/llms/openai.d.ts +4 -3
  91. package/dist/llms/openai.js +15 -13
  92. package/dist/llms/replicate.cjs +2 -2
  93. package/dist/llms/replicate.d.ts +1 -1
  94. package/dist/llms/replicate.js +2 -2
  95. package/dist/memory/base.cjs +9 -1
  96. package/dist/memory/base.d.ts +1 -0
  97. package/dist/memory/base.js +7 -0
  98. package/dist/memory/entity_memory.cjs +151 -0
  99. package/dist/memory/entity_memory.d.ts +35 -0
  100. package/dist/memory/entity_memory.js +147 -0
  101. package/dist/memory/index.cjs +5 -1
  102. package/dist/memory/index.d.ts +2 -0
  103. package/dist/memory/index.js +2 -0
  104. package/dist/memory/prompt.cjs +84 -1
  105. package/dist/memory/prompt.d.ts +6 -0
  106. package/dist/memory/prompt.js +83 -0
  107. package/dist/memory/stores/entity/in_memory.cjs +32 -0
  108. package/dist/memory/stores/entity/in_memory.d.ts +10 -0
  109. package/dist/memory/stores/entity/in_memory.js +28 -0
  110. package/dist/prompts/index.cjs +6 -1
  111. package/dist/prompts/index.d.ts +1 -0
  112. package/dist/prompts/index.js +1 -0
  113. package/dist/{chains/prompt_selector.d.ts → prompts/selectors/conditional.d.ts} +4 -4
  114. package/dist/retrievers/document_compressors/chain_extract.cjs +9 -11
  115. package/dist/retrievers/document_compressors/chain_extract.js +9 -11
  116. package/dist/schema/index.cjs +13 -1
  117. package/dist/schema/index.d.ts +19 -0
  118. package/dist/schema/index.js +11 -0
  119. package/dist/stores/message/dynamodb.cjs +8 -6
  120. package/dist/stores/message/dynamodb.js +8 -6
  121. package/dist/stores/message/redis.cjs +69 -0
  122. package/dist/stores/message/redis.d.ts +18 -0
  123. package/dist/stores/message/redis.js +65 -0
  124. package/dist/stores/message/utils.cjs +30 -15
  125. package/dist/stores/message/utils.d.ts +4 -2
  126. package/dist/stores/message/utils.js +28 -14
  127. package/dist/text_splitter.cjs +3 -23
  128. package/dist/text_splitter.d.ts +1 -3
  129. package/dist/text_splitter.js +3 -23
  130. package/dist/tools/webbrowser.cjs +5 -7
  131. package/dist/tools/webbrowser.js +3 -5
  132. package/dist/types/openai-types.d.ts +3 -2
  133. package/dist/util/async_caller.cjs +16 -0
  134. package/dist/util/async_caller.d.ts +4 -0
  135. package/dist/util/async_caller.js +16 -0
  136. package/dist/util/axios-fetch-adapter.cjs +6 -0
  137. package/dist/util/axios-fetch-adapter.js +6 -0
  138. package/dist/util/env.cjs +39 -7
  139. package/dist/util/env.d.ts +19 -0
  140. package/dist/util/env.js +32 -6
  141. package/dist/util/sql_utils.cjs +18 -0
  142. package/dist/util/sql_utils.js +19 -1
  143. package/dist/util/tiktoken.cjs +26 -0
  144. package/dist/util/tiktoken.d.ts +9 -0
  145. package/dist/util/tiktoken.js +21 -0
  146. package/dist/vectorstores/redis.cjs +236 -0
  147. package/dist/vectorstores/redis.d.ts +80 -0
  148. package/dist/vectorstores/redis.js +232 -0
  149. package/document_loaders/web/apify_dataset.cjs +1 -0
  150. package/document_loaders/web/apify_dataset.d.ts +1 -0
  151. package/document_loaders/web/apify_dataset.js +1 -0
  152. package/package.json +41 -5
  153. package/stores/message/redis.cjs +1 -0
  154. package/stores/message/redis.d.ts +1 -0
  155. package/stores/message/redis.js +1 -0
  156. package/vectorstores/redis.cjs +1 -0
  157. package/vectorstores/redis.d.ts +1 -0
  158. package/vectorstores/redis.js +1 -0
  159. package/dist/callbacks/handlers/tracers.cjs +0 -341
  160. package/dist/callbacks/handlers/tracers.d.ts +0 -100
  161. package/dist/callbacks/handlers/tracers.js +0 -336
  162. /package/dist/{chains/prompt_selector.cjs → prompts/selectors/conditional.cjs} +0 -0
  163. /package/dist/{chains/prompt_selector.js → prompts/selectors/conditional.js} +0 -0
@@ -1,8 +1,10 @@
1
- import { BaseChatMessage } from "../../schema/index.js";
2
- export interface StoredMessage {
1
+ import { BaseChatMessage, StoredMessage } from "../../schema/index.js";
2
+ interface StoredMessageV1 {
3
3
  type: string;
4
4
  role: string | undefined;
5
5
  text: string;
6
6
  }
7
+ export declare function mapV1MessageToStoredMessage(message: StoredMessage | StoredMessageV1): StoredMessage;
7
8
  export declare function mapStoredMessagesToChatMessages(messages: StoredMessage[]): BaseChatMessage[];
8
9
  export declare function mapChatMessagesToStoredMessages(messages: BaseChatMessage[]): StoredMessage[];
10
+ export {};
@@ -1,26 +1,40 @@
1
1
  import { AIChatMessage, ChatMessage, HumanChatMessage, SystemChatMessage, } from "../../schema/index.js";
2
+ export function mapV1MessageToStoredMessage(message) {
3
+ // TODO: Remove this mapper when we deprecate the old message format.
4
+ if (message.data !== undefined) {
5
+ return message;
6
+ }
7
+ else {
8
+ const v1Message = message;
9
+ return {
10
+ type: v1Message.type,
11
+ data: {
12
+ content: v1Message.text,
13
+ role: v1Message.role,
14
+ },
15
+ };
16
+ }
17
+ }
2
18
  export function mapStoredMessagesToChatMessages(messages) {
3
19
  return messages.map((message) => {
4
- switch (message.type) {
20
+ const storedMessage = mapV1MessageToStoredMessage(message);
21
+ switch (storedMessage.type) {
5
22
  case "human":
6
- return new HumanChatMessage(message.text);
23
+ return new HumanChatMessage(storedMessage.data.content);
7
24
  case "ai":
8
- return new AIChatMessage(message.text);
25
+ return new AIChatMessage(storedMessage.data.content);
9
26
  case "system":
10
- return new SystemChatMessage(message.text);
11
- default: {
12
- if (message.role === undefined) {
13
- throw new Error("Role must be defined for generic messages");
27
+ return new SystemChatMessage(storedMessage.data.content);
28
+ case "chat":
29
+ if (storedMessage.data?.additional_kwargs?.role === undefined) {
30
+ throw new Error("Role must be defined for chat messages");
14
31
  }
15
- return new ChatMessage(message.text, message.role);
16
- }
32
+ return new ChatMessage(storedMessage.data.content, storedMessage.data.additional_kwargs.role);
33
+ default:
34
+ throw new Error(`Got unexpected type: ${storedMessage.type}`);
17
35
  }
18
36
  });
19
37
  }
20
38
  export function mapChatMessagesToStoredMessages(messages) {
21
- return messages.map((message) => ({
22
- type: message._getType(),
23
- role: "role" in message ? message.role : undefined,
24
- text: message.text,
25
- }));
39
+ return messages.map((message) => message.toJSON());
26
40
  }
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MarkdownTextSplitter = exports.TokenTextSplitter = exports.RecursiveCharacterTextSplitter = exports.CharacterTextSplitter = exports.TextSplitter = void 0;
4
4
  const document_js_1 = require("./document.cjs");
5
+ const tiktoken_js_1 = require("./util/tiktoken.cjs");
5
6
  class TextSplitter {
6
7
  constructor(fields) {
7
8
  Object.defineProperty(this, "chunkSize", {
@@ -221,48 +222,27 @@ class TokenTextSplitter extends TextSplitter {
221
222
  writable: true,
222
223
  value: void 0
223
224
  });
224
- Object.defineProperty(this, "registry", {
225
- enumerable: true,
226
- configurable: true,
227
- writable: true,
228
- value: void 0
229
- });
230
225
  this.encodingName = fields?.encodingName ?? "gpt2";
231
226
  this.allowedSpecial = fields?.allowedSpecial ?? [];
232
227
  this.disallowedSpecial = fields?.disallowedSpecial ?? "all";
233
228
  }
234
229
  async splitText(text) {
235
230
  if (!this.tokenizer) {
236
- const tiktoken = await TokenTextSplitter.imports();
237
- this.tokenizer = tiktoken.get_encoding(this.encodingName);
238
- // We need to register a finalizer to free the tokenizer when the
239
- // splitter is garbage collected.
240
- this.registry = new FinalizationRegistry((t) => t.free());
241
- this.registry.register(this, this.tokenizer);
231
+ this.tokenizer = await (0, tiktoken_js_1.getEncoding)(this.encodingName);
242
232
  }
243
233
  const splits = [];
244
234
  const input_ids = this.tokenizer.encode(text, this.allowedSpecial, this.disallowedSpecial);
245
235
  let start_idx = 0;
246
236
  let cur_idx = Math.min(start_idx + this.chunkSize, input_ids.length);
247
237
  let chunk_ids = input_ids.slice(start_idx, cur_idx);
248
- const decoder = new TextDecoder();
249
238
  while (start_idx < input_ids.length) {
250
- splits.push(decoder.decode(this.tokenizer.decode(chunk_ids)));
239
+ splits.push(this.tokenizer.decode(chunk_ids));
251
240
  start_idx += this.chunkSize - this.chunkOverlap;
252
241
  cur_idx = Math.min(start_idx + this.chunkSize, input_ids.length);
253
242
  chunk_ids = input_ids.slice(start_idx, cur_idx);
254
243
  }
255
244
  return splits;
256
245
  }
257
- static async imports() {
258
- try {
259
- return await import("@dqbd/tiktoken");
260
- }
261
- catch (err) {
262
- console.error(err);
263
- throw new Error("Please install @dqbd/tiktoken as a dependency with, e.g. `npm install -S @dqbd/tiktoken`");
264
- }
265
- }
266
246
  }
267
247
  exports.TokenTextSplitter = TokenTextSplitter;
268
248
  class MarkdownTextSplitter extends RecursiveCharacterTextSplitter {
@@ -1,4 +1,4 @@
1
- import type * as tiktoken from "@dqbd/tiktoken";
1
+ import type * as tiktoken from "js-tiktoken";
2
2
  import { Document } from "./document.js";
3
3
  export interface TextSplitterParams {
4
4
  chunkSize: number;
@@ -43,10 +43,8 @@ export declare class TokenTextSplitter extends TextSplitter implements TokenText
43
43
  allowedSpecial: "all" | Array<string>;
44
44
  disallowedSpecial: "all" | Array<string>;
45
45
  private tokenizer;
46
- private registry;
47
46
  constructor(fields?: Partial<TokenTextSplitterParams>);
48
47
  splitText(text: string): Promise<string[]>;
49
- static imports(): Promise<typeof tiktoken>;
50
48
  }
51
49
  export type MarkdownTextSplitterParams = TextSplitterParams;
52
50
  export declare class MarkdownTextSplitter extends RecursiveCharacterTextSplitter implements MarkdownTextSplitterParams {
@@ -1,4 +1,5 @@
1
1
  import { Document } from "./document.js";
2
+ import { getEncoding } from "./util/tiktoken.js";
2
3
  export class TextSplitter {
3
4
  constructor(fields) {
4
5
  Object.defineProperty(this, "chunkSize", {
@@ -215,48 +216,27 @@ export class TokenTextSplitter extends TextSplitter {
215
216
  writable: true,
216
217
  value: void 0
217
218
  });
218
- Object.defineProperty(this, "registry", {
219
- enumerable: true,
220
- configurable: true,
221
- writable: true,
222
- value: void 0
223
- });
224
219
  this.encodingName = fields?.encodingName ?? "gpt2";
225
220
  this.allowedSpecial = fields?.allowedSpecial ?? [];
226
221
  this.disallowedSpecial = fields?.disallowedSpecial ?? "all";
227
222
  }
228
223
  async splitText(text) {
229
224
  if (!this.tokenizer) {
230
- const tiktoken = await TokenTextSplitter.imports();
231
- this.tokenizer = tiktoken.get_encoding(this.encodingName);
232
- // We need to register a finalizer to free the tokenizer when the
233
- // splitter is garbage collected.
234
- this.registry = new FinalizationRegistry((t) => t.free());
235
- this.registry.register(this, this.tokenizer);
225
+ this.tokenizer = await getEncoding(this.encodingName);
236
226
  }
237
227
  const splits = [];
238
228
  const input_ids = this.tokenizer.encode(text, this.allowedSpecial, this.disallowedSpecial);
239
229
  let start_idx = 0;
240
230
  let cur_idx = Math.min(start_idx + this.chunkSize, input_ids.length);
241
231
  let chunk_ids = input_ids.slice(start_idx, cur_idx);
242
- const decoder = new TextDecoder();
243
232
  while (start_idx < input_ids.length) {
244
- splits.push(decoder.decode(this.tokenizer.decode(chunk_ids)));
233
+ splits.push(this.tokenizer.decode(chunk_ids));
245
234
  start_idx += this.chunkSize - this.chunkOverlap;
246
235
  cur_idx = Math.min(start_idx + this.chunkSize, input_ids.length);
247
236
  chunk_ids = input_ids.slice(start_idx, cur_idx);
248
237
  }
249
238
  return splits;
250
239
  }
251
- static async imports() {
252
- try {
253
- return await import("@dqbd/tiktoken");
254
- }
255
- catch (err) {
256
- console.error(err);
257
- throw new Error("Please install @dqbd/tiktoken as a dependency with, e.g. `npm install -S @dqbd/tiktoken`");
258
- }
259
- }
260
240
  }
261
241
  export class MarkdownTextSplitter extends RecursiveCharacterTextSplitter {
262
242
  constructor(fields) {
@@ -28,13 +28,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.WebBrowser = exports.getText = exports.parseInputs = void 0;
30
30
  const axios_1 = __importDefault(require("axios"));
31
- const browser_or_node_1 = require("browser-or-node");
32
31
  const cheerio = __importStar(require("cheerio"));
32
+ const env_js_1 = require("../util/env.cjs");
33
33
  const text_splitter_js_1 = require("../text_splitter.cjs");
34
34
  const memory_js_1 = require("../vectorstores/memory.cjs");
35
- const base_js_1 = require("../prompts/base.cjs");
36
35
  const document_js_1 = require("../document.cjs");
37
- const base_js_2 = require("./base.cjs");
36
+ const base_js_1 = require("./base.cjs");
38
37
  const axios_fetch_adapter_js_1 = __importDefault(require("../util/axios-fetch-adapter.cjs"));
39
38
  const parseInputs = (inputs) => {
40
39
  const [baseUrl, task] = inputs.split(",").map((input) => {
@@ -134,7 +133,7 @@ const DEFAULT_HEADERS = {
134
133
  "Upgrade-Insecure-Requests": "1",
135
134
  "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/111.0",
136
135
  };
137
- class WebBrowser extends base_js_2.Tool {
136
+ class WebBrowser extends base_js_1.Tool {
138
137
  constructor({ model, headers, embeddings, verbose, callbacks, callbackManager, axiosConfig, }) {
139
138
  super(verbose, callbacks ?? callbackManager);
140
139
  Object.defineProperty(this, "model", {
@@ -178,7 +177,7 @@ class WebBrowser extends base_js_2.Tool {
178
177
  this.headers = headers || DEFAULT_HEADERS;
179
178
  this.axiosConfig = {
180
179
  withCredentials: true,
181
- adapter: browser_or_node_1.isNode ? undefined : axios_fetch_adapter_js_1.default,
180
+ adapter: (0, env_js_1.isNode)() ? undefined : axios_fetch_adapter_js_1.default,
182
181
  ...axiosConfig,
183
182
  };
184
183
  }
@@ -218,8 +217,7 @@ class WebBrowser extends base_js_2.Tool {
218
217
  context = results.map((res) => res.pageContent).join("\n");
219
218
  }
220
219
  const input = `Text:${context}\n\nI need ${doSummary ? "a summary" : task} from the above text, also provide up to 5 markdown links from within that would be of interest (always including URL and text). Links should be provided, if present, in markdown syntax as a list under the heading "Relevant Links:".`;
221
- const res = await this.model.generatePrompt([new base_js_1.StringPromptValue(input)], undefined, runManager?.getChild());
222
- return res.generations[0][0].text;
220
+ return this.model.predict(input, undefined, runManager?.getChild());
223
221
  }
224
222
  }
225
223
  exports.WebBrowser = WebBrowser;
@@ -1,9 +1,8 @@
1
1
  import axiosMod from "axios";
2
- import { isNode } from "browser-or-node";
3
2
  import * as cheerio from "cheerio";
3
+ import { isNode } from "../util/env.js";
4
4
  import { RecursiveCharacterTextSplitter } from "../text_splitter.js";
5
5
  import { MemoryVectorStore } from "../vectorstores/memory.js";
6
- import { StringPromptValue } from "../prompts/base.js";
7
6
  import { Document } from "../document.js";
8
7
  import { Tool } from "./base.js";
9
8
  import fetchAdapter from "../util/axios-fetch-adapter.js";
@@ -147,7 +146,7 @@ export class WebBrowser extends Tool {
147
146
  this.headers = headers || DEFAULT_HEADERS;
148
147
  this.axiosConfig = {
149
148
  withCredentials: true,
150
- adapter: isNode ? undefined : fetchAdapter,
149
+ adapter: isNode() ? undefined : fetchAdapter,
151
150
  ...axiosConfig,
152
151
  };
153
152
  }
@@ -187,7 +186,6 @@ export class WebBrowser extends Tool {
187
186
  context = results.map((res) => res.pageContent).join("\n");
188
187
  }
189
188
  const input = `Text:${context}\n\nI need ${doSummary ? "a summary" : task} from the above text, also provide up to 5 markdown links from within that would be of interest (always including URL and text). Links should be provided, if present, in markdown syntax as a list under the heading "Relevant Links:".`;
190
- const res = await this.model.generatePrompt([new StringPromptValue(input)], undefined, runManager?.getChild());
191
- return res.generations[0][0].text;
189
+ return this.model.predict(input, undefined, runManager?.getChild());
192
190
  }
193
191
  }
@@ -37,9 +37,10 @@ export declare interface OpenAIBaseInput {
37
37
  }
38
38
  export interface OpenAICallOptions extends BaseLanguageModelCallOptions {
39
39
  /**
40
- * List of stop words to use when generating
40
+ * Abort signal to use for cancelling in-flight requests.
41
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
41
42
  */
42
- stop?: string[];
43
+ signal?: AbortSignal;
43
44
  /**
44
45
  * Additional options to pass to the underlying axios request.
45
46
  */
@@ -88,6 +88,22 @@ class AsyncCaller {
88
88
  // but they're quite sensible.
89
89
  }), { throwOnTimeout: true });
90
90
  }
91
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
92
+ callWithOptions(options, callable, ...args) {
93
+ // Note this doesn't cancel the underlying request,
94
+ // when available prefer to use the signal option of the underlying call
95
+ if (options.signal) {
96
+ return Promise.race([
97
+ this.call(callable, ...args),
98
+ new Promise((_, reject) => {
99
+ options.signal?.addEventListener("abort", () => {
100
+ reject(new Error("AbortError"));
101
+ });
102
+ }),
103
+ ]);
104
+ }
105
+ return this.call(callable, ...args);
106
+ }
91
107
  fetch(...args) {
92
108
  return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res))));
93
109
  }
@@ -10,6 +10,9 @@ export interface AsyncCallerParams {
10
10
  */
11
11
  maxRetries?: number;
12
12
  }
13
+ export interface AsyncCallerCallOptions {
14
+ signal?: AbortSignal;
15
+ }
13
16
  /**
14
17
  * A class that can be used to make async calls with concurrency and retry logic.
15
18
  *
@@ -29,5 +32,6 @@ export declare class AsyncCaller {
29
32
  private queue;
30
33
  constructor(params: AsyncCallerParams);
31
34
  call<A extends any[], T extends (...args: A) => Promise<any>>(callable: T, ...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;
35
+ callWithOptions<A extends any[], T extends (...args: A) => Promise<any>>(options: AsyncCallerCallOptions, callable: T, ...args: Parameters<T>): Promise<Awaited<ReturnType<T>>>;
32
36
  fetch(...args: Parameters<typeof fetch>): ReturnType<typeof fetch>;
33
37
  }
@@ -82,6 +82,22 @@ export class AsyncCaller {
82
82
  // but they're quite sensible.
83
83
  }), { throwOnTimeout: true });
84
84
  }
85
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
86
+ callWithOptions(options, callable, ...args) {
87
+ // Note this doesn't cancel the underlying request,
88
+ // when available prefer to use the signal option of the underlying call
89
+ if (options.signal) {
90
+ return Promise.race([
91
+ this.call(callable, ...args),
92
+ new Promise((_, reject) => {
93
+ options.signal?.addEventListener("abort", () => {
94
+ reject(new Error("AbortError"));
95
+ });
96
+ }),
97
+ ]);
98
+ }
99
+ return this.call(callable, ...args);
100
+ }
85
101
  fetch(...args) {
86
102
  return this.call(() => fetch(...args).then((res) => (res.ok ? res : Promise.reject(res))));
87
103
  }
@@ -291,6 +291,12 @@ function createRequest(config) {
291
291
  headers.delete("Content-Type");
292
292
  }
293
293
  }
294
+ // Some `fetch` implementations will override the Content-Type to text/plain
295
+ // when body is a string.
296
+ // See https://github.com/hwchase17/langchainjs/issues/1010
297
+ if (typeof options.body === "string") {
298
+ options.body = new TextEncoder().encode(options.body);
299
+ }
294
300
  if (config.mode) {
295
301
  options.mode = config.mode;
296
302
  }
@@ -285,6 +285,12 @@ function createRequest(config) {
285
285
  headers.delete("Content-Type");
286
286
  }
287
287
  }
288
+ // Some `fetch` implementations will override the Content-Type to text/plain
289
+ // when body is a string.
290
+ // See https://github.com/hwchase17/langchainjs/issues/1010
291
+ if (typeof options.body === "string") {
292
+ options.body = new TextEncoder().encode(options.body);
293
+ }
288
294
  if (config.mode) {
289
295
  options.mode = config.mode;
290
296
  }
package/dist/util/env.cjs CHANGED
@@ -1,22 +1,42 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getEnv = void 0;
4
- const browser_or_node_1 = require("browser-or-node");
3
+ exports.getRuntimeEnvironment = exports.getEnv = exports.isNode = exports.isDeno = exports.isJsDom = exports.isWebWorker = exports.isBrowser = void 0;
4
+ const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
5
+ exports.isBrowser = isBrowser;
6
+ const isWebWorker = () => typeof globalThis === "object" &&
7
+ globalThis.constructor &&
8
+ globalThis.constructor.name === "DedicatedWorkerGlobalScope";
9
+ exports.isWebWorker = isWebWorker;
10
+ const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") ||
11
+ (typeof navigator !== "undefined" &&
12
+ (navigator.userAgent.includes("Node.js") ||
13
+ navigator.userAgent.includes("jsdom")));
14
+ exports.isJsDom = isJsDom;
15
+ // Supabase Edge Function provides a `Deno` global object
16
+ // without `version` property
17
+ const isDeno = () => typeof Deno !== "undefined";
18
+ exports.isDeno = isDeno;
19
+ // Mark not-as-node if in Supabase Edge Function
20
+ const isNode = () => typeof process !== "undefined" &&
21
+ typeof process.versions !== "undefined" &&
22
+ typeof process.versions.node !== "undefined" &&
23
+ !(0, exports.isDeno)();
24
+ exports.isNode = isNode;
5
25
  const getEnv = () => {
6
26
  let env;
7
- if (browser_or_node_1.isBrowser) {
27
+ if ((0, exports.isBrowser)()) {
8
28
  env = "browser";
9
29
  }
10
- else if (browser_or_node_1.isNode) {
30
+ else if ((0, exports.isNode)()) {
11
31
  env = "node";
12
32
  }
13
- else if (browser_or_node_1.isWebWorker) {
33
+ else if ((0, exports.isWebWorker)()) {
14
34
  env = "webworker";
15
35
  }
16
- else if (browser_or_node_1.isJsDom) {
36
+ else if ((0, exports.isJsDom)()) {
17
37
  env = "jsdom";
18
38
  }
19
- else if (browser_or_node_1.isDeno) {
39
+ else if ((0, exports.isDeno)()) {
20
40
  env = "deno";
21
41
  }
22
42
  else {
@@ -25,3 +45,15 @@ const getEnv = () => {
25
45
  return env;
26
46
  };
27
47
  exports.getEnv = getEnv;
48
+ let runtimeEnvironment;
49
+ async function getRuntimeEnvironment() {
50
+ if (runtimeEnvironment === undefined) {
51
+ const env = (0, exports.getEnv)();
52
+ runtimeEnvironment = {
53
+ library: "langchain-js",
54
+ runtime: env,
55
+ };
56
+ }
57
+ return runtimeEnvironment;
58
+ }
59
+ exports.getRuntimeEnvironment = getRuntimeEnvironment;
@@ -1 +1,20 @@
1
+ declare global {
2
+ const Deno: {
3
+ version: {
4
+ deno: string;
5
+ };
6
+ } | undefined;
7
+ }
8
+ export declare const isBrowser: () => boolean;
9
+ export declare const isWebWorker: () => boolean;
10
+ export declare const isJsDom: () => boolean;
11
+ export declare const isDeno: () => boolean;
12
+ export declare const isNode: () => boolean;
1
13
  export declare const getEnv: () => string;
14
+ export type RuntimeEnvironment = {
15
+ library: string;
16
+ libraryVersion?: string;
17
+ runtime: string;
18
+ runtimeVersion?: string;
19
+ };
20
+ export declare function getRuntimeEnvironment(): Promise<RuntimeEnvironment>;
package/dist/util/env.js CHANGED
@@ -1,19 +1,34 @@
1
- import { isBrowser, isNode, isWebWorker, isJsDom, isDeno, } from "browser-or-node";
1
+ export const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
2
+ export const isWebWorker = () => typeof globalThis === "object" &&
3
+ globalThis.constructor &&
4
+ globalThis.constructor.name === "DedicatedWorkerGlobalScope";
5
+ export const isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") ||
6
+ (typeof navigator !== "undefined" &&
7
+ (navigator.userAgent.includes("Node.js") ||
8
+ navigator.userAgent.includes("jsdom")));
9
+ // Supabase Edge Function provides a `Deno` global object
10
+ // without `version` property
11
+ export const isDeno = () => typeof Deno !== "undefined";
12
+ // Mark not-as-node if in Supabase Edge Function
13
+ export const isNode = () => typeof process !== "undefined" &&
14
+ typeof process.versions !== "undefined" &&
15
+ typeof process.versions.node !== "undefined" &&
16
+ !isDeno();
2
17
  export const getEnv = () => {
3
18
  let env;
4
- if (isBrowser) {
19
+ if (isBrowser()) {
5
20
  env = "browser";
6
21
  }
7
- else if (isNode) {
22
+ else if (isNode()) {
8
23
  env = "node";
9
24
  }
10
- else if (isWebWorker) {
25
+ else if (isWebWorker()) {
11
26
  env = "webworker";
12
27
  }
13
- else if (isJsDom) {
28
+ else if (isJsDom()) {
14
29
  env = "jsdom";
15
30
  }
16
- else if (isDeno) {
31
+ else if (isDeno()) {
17
32
  env = "deno";
18
33
  }
19
34
  else {
@@ -21,3 +36,14 @@ export const getEnv = () => {
21
36
  }
22
37
  return env;
23
38
  };
39
+ let runtimeEnvironment;
40
+ export async function getRuntimeEnvironment() {
41
+ if (runtimeEnvironment === undefined) {
42
+ const env = getEnv();
43
+ runtimeEnvironment = {
44
+ library: "langchain-js",
45
+ runtime: env,
46
+ };
47
+ }
48
+ return runtimeEnvironment;
49
+ }
@@ -95,6 +95,18 @@ const getTableAndColumnsName = async (appDataSource) => {
95
95
  const rep = await appDataSource.query(sql);
96
96
  return formatToSqlTable(rep);
97
97
  }
98
+ if (appDataSource.options.type === "mssql") {
99
+ sql =
100
+ "SELECT " +
101
+ "TABLE_NAME AS table_name, " +
102
+ "COLUMN_NAME AS column_name, " +
103
+ "DATA_TYPE AS data_type, " +
104
+ "IS_NULLABLE AS is_nullable " +
105
+ "FROM INFORMATION_SCHEMA.COLUMNS " +
106
+ "ORDER BY TABLE_NAME, ORDINAL_POSITION;";
107
+ const rep = await appDataSource.query(sql);
108
+ return formatToSqlTable(rep);
109
+ }
98
110
  throw new Error("Database type not implemented yet");
99
111
  };
100
112
  exports.getTableAndColumnsName = getTableAndColumnsName;
@@ -137,6 +149,9 @@ const generateTableInfoFromTables = async (tables, appDataSource, nbSampleRow) =
137
149
  const schema = appDataSource.options?.schema ?? "public";
138
150
  sqlSelectInfoQuery = `SELECT * FROM "${schema}"."${currentTable.tableName}" LIMIT ${nbSampleRow};\n`;
139
151
  }
152
+ else if (appDataSource.options.type === "mssql") {
153
+ sqlSelectInfoQuery = `SELECT TOP ${nbSampleRow} * FROM [${currentTable.tableName}];\n`;
154
+ }
140
155
  else {
141
156
  sqlSelectInfoQuery = `SELECT * FROM "${currentTable.tableName}" LIMIT ${nbSampleRow};\n`;
142
157
  }
@@ -170,6 +185,9 @@ const getPromptTemplateFromDataSource = (appDataSource) => {
170
185
  if (appDataSource.options.type === "mysql") {
171
186
  return sql_db_prompt_js_1.SQL_MYSQL_PROMPT;
172
187
  }
188
+ if (appDataSource.options.type === "mssql") {
189
+ return sql_db_prompt_js_1.SQL_MSSQL_PROMPT;
190
+ }
173
191
  return sql_db_prompt_js_1.DEFAULT_SQL_DATABASE_PROMPT;
174
192
  };
175
193
  exports.getPromptTemplateFromDataSource = getPromptTemplateFromDataSource;
@@ -1,4 +1,4 @@
1
- import { DEFAULT_SQL_DATABASE_PROMPT, SQL_MYSQL_PROMPT, SQL_POSTGRES_PROMPT, SQL_SQLITE_PROMPT, } from "../chains/sql_db/sql_db_prompt.js";
1
+ import { DEFAULT_SQL_DATABASE_PROMPT, SQL_MSSQL_PROMPT, SQL_MYSQL_PROMPT, SQL_POSTGRES_PROMPT, SQL_SQLITE_PROMPT, } from "../chains/sql_db/sql_db_prompt.js";
2
2
  export const verifyListTablesExistInDatabase = (tablesFromDatabase, listTables, errorPrefixMsg) => {
3
3
  const onlyTableNames = tablesFromDatabase.map((table) => table.tableName);
4
4
  if (listTables.length > 0) {
@@ -89,6 +89,18 @@ export const getTableAndColumnsName = async (appDataSource) => {
89
89
  const rep = await appDataSource.query(sql);
90
90
  return formatToSqlTable(rep);
91
91
  }
92
+ if (appDataSource.options.type === "mssql") {
93
+ sql =
94
+ "SELECT " +
95
+ "TABLE_NAME AS table_name, " +
96
+ "COLUMN_NAME AS column_name, " +
97
+ "DATA_TYPE AS data_type, " +
98
+ "IS_NULLABLE AS is_nullable " +
99
+ "FROM INFORMATION_SCHEMA.COLUMNS " +
100
+ "ORDER BY TABLE_NAME, ORDINAL_POSITION;";
101
+ const rep = await appDataSource.query(sql);
102
+ return formatToSqlTable(rep);
103
+ }
92
104
  throw new Error("Database type not implemented yet");
93
105
  };
94
106
  const formatSqlResponseToSimpleTableString = (rawResult) => {
@@ -130,6 +142,9 @@ export const generateTableInfoFromTables = async (tables, appDataSource, nbSampl
130
142
  const schema = appDataSource.options?.schema ?? "public";
131
143
  sqlSelectInfoQuery = `SELECT * FROM "${schema}"."${currentTable.tableName}" LIMIT ${nbSampleRow};\n`;
132
144
  }
145
+ else if (appDataSource.options.type === "mssql") {
146
+ sqlSelectInfoQuery = `SELECT TOP ${nbSampleRow} * FROM [${currentTable.tableName}];\n`;
147
+ }
133
148
  else {
134
149
  sqlSelectInfoQuery = `SELECT * FROM "${currentTable.tableName}" LIMIT ${nbSampleRow};\n`;
135
150
  }
@@ -162,5 +177,8 @@ export const getPromptTemplateFromDataSource = (appDataSource) => {
162
177
  if (appDataSource.options.type === "mysql") {
163
178
  return SQL_MYSQL_PROMPT;
164
179
  }
180
+ if (appDataSource.options.type === "mssql") {
181
+ return SQL_MSSQL_PROMPT;
182
+ }
165
183
  return DEFAULT_SQL_DATABASE_PROMPT;
166
184
  };
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.encodingForModel = exports.getEncoding = void 0;
4
+ const lite_1 = require("js-tiktoken/lite");
5
+ const async_caller_js_1 = require("./async_caller.cjs");
6
+ const cache = {};
7
+ const caller = /* #__PURE__ */ new async_caller_js_1.AsyncCaller({});
8
+ async function getEncoding(encoding, options) {
9
+ if (!(encoding in cache)) {
10
+ cache[encoding] = caller
11
+ .fetch(`https://tiktoken.pages.dev/js/${encoding}.json`, {
12
+ signal: options?.signal,
13
+ })
14
+ .then((res) => res.json())
15
+ .catch((e) => {
16
+ delete cache[encoding];
17
+ throw e;
18
+ });
19
+ }
20
+ return new lite_1.Tiktoken(await cache[encoding], options?.extendedSpecialTokens);
21
+ }
22
+ exports.getEncoding = getEncoding;
23
+ async function encodingForModel(model, options) {
24
+ return getEncoding((0, lite_1.getEncodingNameForModel)(model), options);
25
+ }
26
+ exports.encodingForModel = encodingForModel;
@@ -0,0 +1,9 @@
1
+ import { Tiktoken, TiktokenEncoding, TiktokenModel } from "js-tiktoken/lite";
2
+ export declare function getEncoding(encoding: TiktokenEncoding, options?: {
3
+ signal?: AbortSignal;
4
+ extendedSpecialTokens?: Record<string, number>;
5
+ }): Promise<Tiktoken>;
6
+ export declare function encodingForModel(model: TiktokenModel, options?: {
7
+ signal?: AbortSignal;
8
+ extendedSpecialTokens?: Record<string, number>;
9
+ }): Promise<Tiktoken>;