langchain 0.0.75 → 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 (114) hide show
  1. package/dist/base_language/count_tokens.cjs +5 -21
  2. package/dist/base_language/count_tokens.d.ts +1 -6
  3. package/dist/base_language/count_tokens.js +4 -19
  4. package/dist/base_language/index.cjs +10 -24
  5. package/dist/base_language/index.d.ts +3 -2
  6. package/dist/base_language/index.js +11 -25
  7. package/dist/cache/redis.d.ts +3 -1
  8. package/dist/callbacks/base.d.ts +4 -4
  9. package/dist/callbacks/handlers/initialize.cjs +2 -9
  10. package/dist/callbacks/handlers/initialize.d.ts +1 -1
  11. package/dist/callbacks/handlers/initialize.js +2 -9
  12. package/dist/callbacks/handlers/tracer.cjs +11 -22
  13. package/dist/callbacks/handlers/tracer.d.ts +2 -2
  14. package/dist/callbacks/handlers/tracer.js +11 -22
  15. package/dist/callbacks/handlers/tracer_langchain.cjs +52 -91
  16. package/dist/callbacks/handlers/tracer_langchain.d.ts +12 -9
  17. package/dist/callbacks/handlers/tracer_langchain.js +52 -68
  18. package/dist/callbacks/handlers/tracer_langchain_v1.cjs +5 -1
  19. package/dist/callbacks/handlers/tracer_langchain_v1.js +5 -1
  20. package/dist/callbacks/manager.cjs +10 -10
  21. package/dist/callbacks/manager.d.ts +2 -2
  22. package/dist/callbacks/manager.js +10 -10
  23. package/dist/chains/question_answering/map_reduce_prompts.cjs +5 -5
  24. package/dist/chains/question_answering/map_reduce_prompts.d.ts +1 -1
  25. package/dist/chains/question_answering/map_reduce_prompts.js +1 -1
  26. package/dist/chains/question_answering/refine_prompts.cjs +5 -5
  27. package/dist/chains/question_answering/refine_prompts.d.ts +1 -1
  28. package/dist/chains/question_answering/refine_prompts.js +1 -1
  29. package/dist/chains/question_answering/stuff_prompts.cjs +2 -2
  30. package/dist/chains/question_answering/stuff_prompts.d.ts +1 -1
  31. package/dist/chains/question_answering/stuff_prompts.js +1 -1
  32. package/dist/chains/sequential_chain.cjs +2 -2
  33. package/dist/chains/sequential_chain.d.ts +2 -2
  34. package/dist/chains/sequential_chain.js +2 -2
  35. package/dist/chains/sql_db/sql_db_prompt.cjs +20 -1
  36. package/dist/chains/sql_db/sql_db_prompt.d.ts +1 -0
  37. package/dist/chains/sql_db/sql_db_prompt.js +19 -0
  38. package/dist/chat_models/base.cjs +17 -1
  39. package/dist/chat_models/base.d.ts +6 -0
  40. package/dist/chat_models/base.js +18 -2
  41. package/dist/chat_models/openai.cjs +2 -2
  42. package/dist/chat_models/openai.js +2 -2
  43. package/dist/client/langchainplus.cjs +90 -29
  44. package/dist/client/langchainplus.d.ts +7 -5
  45. package/dist/client/langchainplus.js +90 -29
  46. package/dist/document_loaders/fs/unstructured.cjs +8 -0
  47. package/dist/document_loaders/fs/unstructured.d.ts +3 -0
  48. package/dist/document_loaders/fs/unstructured.js +8 -0
  49. package/dist/document_loaders/web/apify_dataset.cjs +64 -0
  50. package/dist/document_loaders/web/apify_dataset.d.ts +28 -0
  51. package/dist/document_loaders/web/apify_dataset.js +60 -0
  52. package/dist/embeddings/openai.cjs +2 -2
  53. package/dist/embeddings/openai.js +2 -2
  54. package/dist/llms/base.cjs +18 -1
  55. package/dist/llms/base.d.ts +7 -1
  56. package/dist/llms/base.js +19 -2
  57. package/dist/llms/openai-chat.cjs +2 -2
  58. package/dist/llms/openai-chat.js +2 -2
  59. package/dist/llms/openai.cjs +2 -2
  60. package/dist/llms/openai.js +2 -2
  61. package/dist/memory/base.cjs +9 -1
  62. package/dist/memory/base.d.ts +1 -0
  63. package/dist/memory/base.js +7 -0
  64. package/dist/memory/entity_memory.cjs +151 -0
  65. package/dist/memory/entity_memory.d.ts +35 -0
  66. package/dist/memory/entity_memory.js +147 -0
  67. package/dist/memory/index.cjs +5 -1
  68. package/dist/memory/index.d.ts +2 -0
  69. package/dist/memory/index.js +2 -0
  70. package/dist/memory/prompt.cjs +84 -1
  71. package/dist/memory/prompt.d.ts +6 -0
  72. package/dist/memory/prompt.js +83 -0
  73. package/dist/memory/stores/entity/in_memory.cjs +32 -0
  74. package/dist/memory/stores/entity/in_memory.d.ts +10 -0
  75. package/dist/memory/stores/entity/in_memory.js +28 -0
  76. package/dist/prompts/index.cjs +6 -1
  77. package/dist/prompts/index.d.ts +1 -0
  78. package/dist/prompts/index.js +1 -0
  79. package/dist/{chains/prompt_selector.d.ts → prompts/selectors/conditional.d.ts} +4 -4
  80. package/dist/schema/index.cjs +13 -1
  81. package/dist/schema/index.d.ts +17 -0
  82. package/dist/schema/index.js +11 -0
  83. package/dist/stores/message/dynamodb.cjs +8 -6
  84. package/dist/stores/message/dynamodb.js +8 -6
  85. package/dist/stores/message/redis.cjs +5 -3
  86. package/dist/stores/message/redis.js +5 -3
  87. package/dist/stores/message/utils.cjs +30 -15
  88. package/dist/stores/message/utils.d.ts +4 -2
  89. package/dist/stores/message/utils.js +28 -14
  90. package/dist/text_splitter.cjs +3 -23
  91. package/dist/text_splitter.d.ts +1 -3
  92. package/dist/text_splitter.js +3 -23
  93. package/dist/tools/webbrowser.cjs +5 -7
  94. package/dist/tools/webbrowser.js +3 -5
  95. package/dist/util/env.cjs +39 -7
  96. package/dist/util/env.d.ts +19 -0
  97. package/dist/util/env.js +32 -6
  98. package/dist/util/sql_utils.cjs +18 -0
  99. package/dist/util/sql_utils.js +19 -1
  100. package/dist/util/tiktoken.cjs +26 -0
  101. package/dist/util/tiktoken.d.ts +9 -0
  102. package/dist/util/tiktoken.js +21 -0
  103. package/dist/vectorstores/redis.cjs +236 -0
  104. package/dist/vectorstores/redis.d.ts +80 -0
  105. package/dist/vectorstores/redis.js +232 -0
  106. package/document_loaders/web/apify_dataset.cjs +1 -0
  107. package/document_loaders/web/apify_dataset.d.ts +1 -0
  108. package/document_loaders/web/apify_dataset.js +1 -0
  109. package/package.json +25 -5
  110. package/vectorstores/redis.cjs +1 -0
  111. package/vectorstores/redis.d.ts +1 -0
  112. package/vectorstores/redis.js +1 -0
  113. /package/dist/{chains/prompt_selector.cjs → prompts/selectors/conditional.cjs} +0 -0
  114. /package/dist/{chains/prompt_selector.js → prompts/selectors/conditional.js} +0 -0
@@ -1,5 +1,5 @@
1
1
  import { PromptTemplate, ChatPromptTemplate } from "../../prompts/index.js";
2
- import { ConditionalPromptSelector } from "../prompt_selector.js";
2
+ import { ConditionalPromptSelector } from "../../prompts/selectors/conditional.js";
3
3
  export declare const DEFAULT_REFINE_PROMPT_TMPL = "The original question is as follows: {question}\nWe have provided an existing answer: {existing_answer}\nWe have the opportunity to refine the existing answer\n(only if needed) with some more context below.\n------------\n{context}\n------------\nGiven the new context, refine the original answer to better answer the question. \nIf the context isn't useful, return the original answer.";
4
4
  export declare const DEFAULT_REFINE_PROMPT: PromptTemplate;
5
5
  export declare const CHAT_REFINE_PROMPT: ChatPromptTemplate;
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable spaced-comment */
2
2
  import { PromptTemplate, ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate, } from "../../prompts/index.js";
3
- import { ConditionalPromptSelector, isChatModel } from "../prompt_selector.js";
3
+ import { ConditionalPromptSelector, isChatModel, } from "../../prompts/selectors/conditional.js";
4
4
  export const DEFAULT_REFINE_PROMPT_TMPL = `The original question is as follows: {question}
5
5
  We have provided an existing answer: {existing_answer}
6
6
  We have the opportunity to refine the existing answer
@@ -4,7 +4,7 @@ exports.QA_PROMPT_SELECTOR = exports.DEFAULT_QA_PROMPT = void 0;
4
4
  /* eslint-disable spaced-comment */
5
5
  const prompt_js_1 = require("../../prompts/prompt.cjs");
6
6
  const chat_js_1 = require("../../prompts/chat.cjs");
7
- const prompt_selector_js_1 = require("../prompt_selector.cjs");
7
+ const conditional_js_1 = require("../../prompts/selectors/conditional.cjs");
8
8
  exports.DEFAULT_QA_PROMPT = new prompt_js_1.PromptTemplate({
9
9
  template: "Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:",
10
10
  inputVariables: ["context", "question"],
@@ -19,4 +19,4 @@ const messages = [
19
19
  ];
20
20
  const CHAT_PROMPT =
21
21
  /*#__PURE__*/ chat_js_1.ChatPromptTemplate.fromPromptMessages(messages);
22
- exports.QA_PROMPT_SELECTOR = new prompt_selector_js_1.ConditionalPromptSelector(exports.DEFAULT_QA_PROMPT, [[prompt_selector_js_1.isChatModel, CHAT_PROMPT]]);
22
+ exports.QA_PROMPT_SELECTOR = new conditional_js_1.ConditionalPromptSelector(exports.DEFAULT_QA_PROMPT, [[conditional_js_1.isChatModel, CHAT_PROMPT]]);
@@ -1,4 +1,4 @@
1
1
  import { PromptTemplate } from "../../prompts/prompt.js";
2
- import { ConditionalPromptSelector } from "../prompt_selector.js";
2
+ import { ConditionalPromptSelector } from "../../prompts/selectors/conditional.js";
3
3
  export declare const DEFAULT_QA_PROMPT: PromptTemplate;
4
4
  export declare const QA_PROMPT_SELECTOR: ConditionalPromptSelector;
@@ -1,7 +1,7 @@
1
1
  /* eslint-disable spaced-comment */
2
2
  import { PromptTemplate } from "../../prompts/prompt.js";
3
3
  import { ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, } from "../../prompts/chat.js";
4
- import { ConditionalPromptSelector, isChatModel } from "../prompt_selector.js";
4
+ import { ConditionalPromptSelector, isChatModel, } from "../../prompts/selectors/conditional.js";
5
5
  export const DEFAULT_QA_PROMPT = /*#__PURE__*/ new PromptTemplate({
6
6
  template: "Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:",
7
7
  inputVariables: ["context", "question"],
@@ -168,8 +168,8 @@ exports.SequentialChain = SequentialChain;
168
168
  * Play Synopsis:
169
169
  * {synopsis}
170
170
  * Review from a New York Times play critic of the above play:`
171
- * const reviewPromptTempalte = new PromptTemplate({ template: reviewTemplate, inputVariables: ["synopsis"] });
172
- * const reviewChain = new LLMChain({ llm: reviewLLM, prompt: reviewPromptTempalte });
171
+ * const reviewPromptTemplate = new PromptTemplate({ template: reviewTemplate, inputVariables: ["synopsis"] });
172
+ * const reviewChain = new LLMChain({ llm: reviewLLM, prompt: reviewPromptTemplate });
173
173
  *
174
174
  * const overallChain = new SimpleSequentialChain({chains: [synopsisChain, reviewChain], verbose:true})
175
175
  * const review = await overallChain.run("Tragedy at sunset on the beach")
@@ -65,8 +65,8 @@ export interface SimpleSequentialChainInput extends ChainInputs {
65
65
  * Play Synopsis:
66
66
  * {synopsis}
67
67
  * Review from a New York Times play critic of the above play:`
68
- * const reviewPromptTempalte = new PromptTemplate({ template: reviewTemplate, inputVariables: ["synopsis"] });
69
- * const reviewChain = new LLMChain({ llm: reviewLLM, prompt: reviewPromptTempalte });
68
+ * const reviewPromptTemplate = new PromptTemplate({ template: reviewTemplate, inputVariables: ["synopsis"] });
69
+ * const reviewChain = new LLMChain({ llm: reviewLLM, prompt: reviewPromptTemplate });
70
70
  *
71
71
  * const overallChain = new SimpleSequentialChain({chains: [synopsisChain, reviewChain], verbose:true})
72
72
  * const review = await overallChain.run("Tragedy at sunset on the beach")
@@ -164,8 +164,8 @@ export class SequentialChain extends BaseChain {
164
164
  * Play Synopsis:
165
165
  * {synopsis}
166
166
  * Review from a New York Times play critic of the above play:`
167
- * const reviewPromptTempalte = new PromptTemplate({ template: reviewTemplate, inputVariables: ["synopsis"] });
168
- * const reviewChain = new LLMChain({ llm: reviewLLM, prompt: reviewPromptTempalte });
167
+ * const reviewPromptTemplate = new PromptTemplate({ template: reviewTemplate, inputVariables: ["synopsis"] });
168
+ * const reviewChain = new LLMChain({ llm: reviewLLM, prompt: reviewPromptTemplate });
169
169
  *
170
170
  * const overallChain = new SimpleSequentialChain({chains: [synopsisChain, reviewChain], verbose:true})
171
171
  * const review = await overallChain.run("Tragedy at sunset on the beach")
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SQL_MYSQL_PROMPT = exports.SQL_SQLITE_PROMPT = exports.SQL_POSTGRES_PROMPT = exports.DEFAULT_SQL_DATABASE_PROMPT = void 0;
3
+ exports.SQL_MSSQL_PROMPT = exports.SQL_MYSQL_PROMPT = exports.SQL_SQLITE_PROMPT = exports.SQL_POSTGRES_PROMPT = exports.DEFAULT_SQL_DATABASE_PROMPT = void 0;
4
4
  /* eslint-disable spaced-comment */
5
5
  const prompt_js_1 = require("../../prompts/prompt.cjs");
6
6
  exports.DEFAULT_SQL_DATABASE_PROMPT = new prompt_js_1.PromptTemplate({
@@ -81,3 +81,22 @@ Only use the following tables:
81
81
  Question: {input}`,
82
82
  inputVariables: ["dialect", "table_info", "input", "top_k"],
83
83
  });
84
+ exports.SQL_MSSQL_PROMPT = new prompt_js_1.PromptTemplate({
85
+ template: `You are an MS SQL expert. Given an input question, first create a syntactically correct MS SQL query to run, then look at the results of the query and return the answer to the input question.
86
+ Unless the user specifies in the question a specific number of examples to obtain, query for at most {top_k} results using the TOP clause as per MS SQL. You can order the results to return the most informative data in the database.
87
+ Never query for all columns from a table. You must query only the columns that are needed to answer the question. Wrap each column name in square brackets ([]) to denote them as delimited identifiers.
88
+ Pay attention to use only the column names you can see in the tables below. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.
89
+
90
+ Use the following format:
91
+
92
+ Question: "Question here"
93
+ SQLQuery: "SQL Query to run"
94
+ SQLResult: "Result of the SQLQuery"
95
+ Answer: "Final answer here"
96
+
97
+ Only use the following tables:
98
+ {table_info}
99
+
100
+ Question: {input}`,
101
+ inputVariables: ["dialect", "table_info", "input", "top_k"],
102
+ });
@@ -3,3 +3,4 @@ export declare const DEFAULT_SQL_DATABASE_PROMPT: PromptTemplate;
3
3
  export declare const SQL_POSTGRES_PROMPT: PromptTemplate;
4
4
  export declare const SQL_SQLITE_PROMPT: PromptTemplate;
5
5
  export declare const SQL_MYSQL_PROMPT: PromptTemplate;
6
+ export declare const SQL_MSSQL_PROMPT: PromptTemplate;
@@ -78,3 +78,22 @@ Only use the following tables:
78
78
  Question: {input}`,
79
79
  inputVariables: ["dialect", "table_info", "input", "top_k"],
80
80
  });
81
+ export const SQL_MSSQL_PROMPT = /*#__PURE__*/ new PromptTemplate({
82
+ template: `You are an MS SQL expert. Given an input question, first create a syntactically correct MS SQL query to run, then look at the results of the query and return the answer to the input question.
83
+ Unless the user specifies in the question a specific number of examples to obtain, query for at most {top_k} results using the TOP clause as per MS SQL. You can order the results to return the most informative data in the database.
84
+ Never query for all columns from a table. You must query only the columns that are needed to answer the question. Wrap each column name in square brackets ([]) to denote them as delimited identifiers.
85
+ Pay attention to use only the column names you can see in the tables below. Be careful to not query for columns that do not exist. Also, pay attention to which column is in which table.
86
+
87
+ Use the following format:
88
+
89
+ Question: "Question here"
90
+ SQLQuery: "SQL Query to run"
91
+ SQLResult: "Result of the SQLQuery"
92
+ Answer: "Final answer here"
93
+
94
+ Only use the following tables:
95
+ {table_info}
96
+
97
+ Question: {input}`,
98
+ inputVariables: ["dialect", "table_info", "input", "top_k"],
99
+ });
@@ -25,7 +25,8 @@ class BaseChatModel extends index_js_2.BaseLanguageModel {
25
25
  parsedOptions = options ?? {};
26
26
  }
27
27
  const callbackManager_ = await manager_js_1.CallbackManager.configure(callbacks, this.callbacks, { verbose: this.verbose });
28
- const runManager = await callbackManager_?.handleChatModelStart({ name: this._llmType() }, messages);
28
+ const invocationParams = { invocation_params: this?.invocationParams() };
29
+ const runManager = await callbackManager_?.handleChatModelStart({ name: this._llmType() }, messages, undefined, undefined, invocationParams);
29
30
  try {
30
31
  const results = await Promise.all(messages.map((messageList) => this._generate(messageList, parsedOptions, runManager)));
31
32
  for (const result of results) {
@@ -52,6 +53,13 @@ class BaseChatModel extends index_js_2.BaseLanguageModel {
52
53
  });
53
54
  return output;
54
55
  }
56
+ /**
57
+ * Get the parameters used to invoke the model
58
+ */
59
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
60
+ invocationParams() {
61
+ return {};
62
+ }
55
63
  _modelType() {
56
64
  return "base_chat_model";
57
65
  }
@@ -68,6 +76,14 @@ class BaseChatModel extends index_js_2.BaseLanguageModel {
68
76
  const promptMessages = promptValue.toChatMessages();
69
77
  return this.call(promptMessages, options, callbacks);
70
78
  }
79
+ async predictMessages(messages, options, callbacks) {
80
+ return this.call(messages, options, callbacks);
81
+ }
82
+ async predict(text, options, callbacks) {
83
+ const message = new index_js_1.HumanChatMessage(text);
84
+ const result = await this.call([message], options, callbacks);
85
+ return result.text;
86
+ }
71
87
  }
72
88
  exports.BaseChatModel = BaseChatModel;
73
89
  class SimpleChatModel extends BaseChatModel {
@@ -17,12 +17,18 @@ export declare abstract class BaseChatModel extends BaseLanguageModel {
17
17
  constructor(fields: BaseChatModelParams);
18
18
  abstract _combineLLMOutput?(...llmOutputs: LLMResult["llmOutput"][]): LLMResult["llmOutput"];
19
19
  generate(messages: BaseChatMessage[][], options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<LLMResult>;
20
+ /**
21
+ * Get the parameters used to invoke the model
22
+ */
23
+ invocationParams(): any;
20
24
  _modelType(): string;
21
25
  abstract _llmType(): string;
22
26
  generatePrompt(promptValues: BasePromptValue[], options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<LLMResult>;
23
27
  abstract _generate(messages: BaseChatMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;
24
28
  call(messages: BaseChatMessage[], options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<BaseChatMessage>;
25
29
  callPrompt(promptValue: BasePromptValue, options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<BaseChatMessage>;
30
+ predictMessages(messages: BaseChatMessage[], options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<BaseChatMessage>;
31
+ predict(text: string, options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<string>;
26
32
  }
27
33
  export declare abstract class SimpleChatModel extends BaseChatModel {
28
34
  abstract _call(messages: BaseChatMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): Promise<string>;
@@ -1,4 +1,4 @@
1
- import { AIChatMessage, RUN_KEY, } from "../schema/index.js";
1
+ import { AIChatMessage, HumanChatMessage, RUN_KEY, } from "../schema/index.js";
2
2
  import { BaseLanguageModel, } from "../base_language/index.js";
3
3
  import { CallbackManager, } from "../callbacks/manager.js";
4
4
  export class BaseChatModel extends BaseLanguageModel {
@@ -22,7 +22,8 @@ export class BaseChatModel extends BaseLanguageModel {
22
22
  parsedOptions = options ?? {};
23
23
  }
24
24
  const callbackManager_ = await CallbackManager.configure(callbacks, this.callbacks, { verbose: this.verbose });
25
- const runManager = await callbackManager_?.handleChatModelStart({ name: this._llmType() }, messages);
25
+ const invocationParams = { invocation_params: this?.invocationParams() };
26
+ const runManager = await callbackManager_?.handleChatModelStart({ name: this._llmType() }, messages, undefined, undefined, invocationParams);
26
27
  try {
27
28
  const results = await Promise.all(messages.map((messageList) => this._generate(messageList, parsedOptions, runManager)));
28
29
  for (const result of results) {
@@ -49,6 +50,13 @@ export class BaseChatModel extends BaseLanguageModel {
49
50
  });
50
51
  return output;
51
52
  }
53
+ /**
54
+ * Get the parameters used to invoke the model
55
+ */
56
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
57
+ invocationParams() {
58
+ return {};
59
+ }
52
60
  _modelType() {
53
61
  return "base_chat_model";
54
62
  }
@@ -65,6 +73,14 @@ export class BaseChatModel extends BaseLanguageModel {
65
73
  const promptMessages = promptValue.toChatMessages();
66
74
  return this.call(promptMessages, options, callbacks);
67
75
  }
76
+ async predictMessages(messages, options, callbacks) {
77
+ return this.call(messages, options, callbacks);
78
+ }
79
+ async predict(text, options, callbacks) {
80
+ const message = new HumanChatMessage(text);
81
+ const result = await this.call([message], options, callbacks);
82
+ return result.text;
83
+ }
68
84
  }
69
85
  export class SimpleChatModel extends BaseChatModel {
70
86
  async _generate(messages, options, runManager) {
@@ -4,8 +4,8 @@ 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");
8
7
  const openai_1 = require("openai");
8
+ const env_js_1 = require("../util/env.cjs");
9
9
  const axios_fetch_adapter_js_1 = __importDefault(require("../util/axios-fetch-adapter.cjs"));
10
10
  const base_js_1 = require("./base.cjs");
11
11
  const index_js_1 = require("../schema/index.cjs");
@@ -422,7 +422,7 @@ class ChatOpenAI extends base_js_1.BaseChatModel {
422
422
  this.client = new openai_1.OpenAIApi(clientConfig);
423
423
  }
424
424
  const axiosOptions = {
425
- adapter: browser_or_node_1.isNode ? undefined : axios_fetch_adapter_js_1.default,
425
+ adapter: (0, env_js_1.isNode)() ? undefined : axios_fetch_adapter_js_1.default,
426
426
  ...this.clientConfig.baseOptions,
427
427
  ...options,
428
428
  };
@@ -1,5 +1,5 @@
1
- import { isNode } from "browser-or-node";
2
1
  import { Configuration, OpenAIApi, } from "openai";
2
+ import { isNode } from "../util/env.js";
3
3
  import fetchAdapter from "../util/axios-fetch-adapter.js";
4
4
  import { BaseChatModel } from "./base.js";
5
5
  import { AIChatMessage, ChatMessage, HumanChatMessage, SystemChatMessage, } from "../schema/index.js";
@@ -416,7 +416,7 @@ export class ChatOpenAI extends BaseChatModel {
416
416
  this.client = new OpenAIApi(clientConfig);
417
417
  }
418
418
  const axiosOptions = {
419
- adapter: isNode ? undefined : fetchAdapter,
419
+ adapter: isNode() ? undefined : fetchAdapter,
420
420
  ...this.clientConfig.baseOptions,
421
421
  ...options,
422
422
  };
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.LangChainPlusClient = exports.isChain = exports.isChatModel = exports.isLLM = void 0;
4
4
  const tracer_langchain_js_1 = require("../callbacks/handlers/tracer_langchain.cjs");
5
+ const utils_js_1 = require("../stores/message/utils.cjs");
5
6
  // utility functions
6
7
  const isLocalhost = (url) => {
7
8
  const strippedUrl = url.replace("http://", "").replace("https://", "");
@@ -55,11 +56,29 @@ function isChatModel(llm) {
55
56
  blm?._modelType() === "base_chat_model");
56
57
  }
57
58
  exports.isChatModel = isChatModel;
58
- function isChain(llm) {
59
- const bch = llm;
59
+ async function isChain(llm) {
60
+ if (isLLM(llm)) {
61
+ return false;
62
+ }
63
+ const bchFactory = llm;
64
+ const bch = await bchFactory();
60
65
  return (typeof bch?._chainType === "function" && bch?._chainType() !== undefined);
61
66
  }
62
67
  exports.isChain = isChain;
68
+ async function getModelOrFactoryType(llm) {
69
+ if (isLLM(llm)) {
70
+ return "llm";
71
+ }
72
+ if (isChatModel(llm)) {
73
+ return "chatModel";
74
+ }
75
+ const bchFactory = llm;
76
+ const bch = await bchFactory();
77
+ if (typeof bch?._chainType === "function") {
78
+ return "chainFactory";
79
+ }
80
+ throw new Error("Unknown model or factory type");
81
+ }
63
82
  class LangChainPlusClient {
64
83
  constructor(apiUrl, tenantId, apiKey) {
65
84
  Object.defineProperty(this, "apiKey", {
@@ -151,6 +170,26 @@ class LangChainPlusClient {
151
170
  const result = await response.json();
152
171
  return result;
153
172
  }
173
+ async createDataset(name, description) {
174
+ const response = await fetch(`${this.apiUrl}/datasets`, {
175
+ method: "POST",
176
+ headers: { ...this.headers, "Content-Type": "application/json" },
177
+ body: JSON.stringify({
178
+ name,
179
+ description,
180
+ tenant_id: this.tenantId,
181
+ }),
182
+ });
183
+ if (!response.ok) {
184
+ const result = await response.json();
185
+ if (result.detail && result.detail.includes("already exists")) {
186
+ throw new Error(`Dataset ${name} already exists`);
187
+ }
188
+ throw new Error(`Failed to create dataset ${response.status} ${response.statusText}`);
189
+ }
190
+ const result = await response.json();
191
+ return result;
192
+ }
154
193
  async readDataset(datasetId, datasetName) {
155
194
  let path = "/datasets";
156
195
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -286,58 +325,80 @@ class LangChainPlusClient {
286
325
  return result;
287
326
  }
288
327
  async runLLM(example, tracer, llm, numRepetitions = 1) {
289
- const results = [];
290
- for (let i = 0; i < numRepetitions; i += 1) {
328
+ const results = await Promise.all(Array.from({ length: numRepetitions }).map(async () => {
291
329
  try {
292
- const prompts = example.inputs.prompts;
293
- results.push(await llm.generate(prompts, undefined, [tracer]));
330
+ const prompt = example.inputs.prompt;
331
+ return llm.generate([prompt], undefined, [tracer]);
294
332
  }
295
333
  catch (e) {
296
334
  console.error(e);
297
- results.push(stringifyError(e));
335
+ return stringifyError(e);
298
336
  }
299
- }
337
+ }));
300
338
  return results;
301
339
  }
302
- async runChain(example, tracer, chain, numRepetitions = 1) {
303
- const results = [];
304
- for (let i = 0; i < numRepetitions; i += 1) {
340
+ async runChain(example, tracer, chainFactory, numRepetitions = 1) {
341
+ const results = await Promise.all(Array.from({ length: numRepetitions }).map(async () => {
305
342
  try {
306
- results.push(await chain.call(example.inputs, [tracer]));
343
+ const chain = await chainFactory();
344
+ return chain.call(example.inputs, [tracer]);
307
345
  }
308
346
  catch (e) {
309
347
  console.error(e);
310
- results.push(stringifyError(e));
348
+ return stringifyError(e);
311
349
  }
312
- }
350
+ }));
351
+ return results;
352
+ }
353
+ async runChatModel(example, tracer, chatModel, numRepetitions = 1) {
354
+ const results = await Promise.all(Array.from({ length: numRepetitions }).map(async () => {
355
+ try {
356
+ const messages = example.inputs.messages;
357
+ return chatModel.generate([(0, utils_js_1.mapStoredMessagesToChatMessages)(messages)], undefined, [tracer]);
358
+ }
359
+ catch (e) {
360
+ console.error(e);
361
+ return stringifyError(e);
362
+ }
363
+ }));
313
364
  return results;
314
365
  }
315
- async runOnDataset(datasetName, llmOrChain, numRepetitions = 1, sessionName = undefined) {
366
+ async runOnDataset(datasetName, llmOrChainFactory, numRepetitions = 1, sessionName = undefined) {
316
367
  const examples = await this.listExamples(undefined, datasetName);
317
- let sessionName_ = sessionName;
368
+ let sessionName_;
318
369
  if (sessionName === undefined) {
319
370
  const currentTime = new Date().toISOString();
320
- sessionName_ = `${datasetName}-${llmOrChain.constructor.name}-${currentTime}`;
371
+ sessionName_ = `${datasetName}-${llmOrChainFactory.constructor.name}-${currentTime}`;
372
+ }
373
+ else {
374
+ sessionName_ = sessionName;
321
375
  }
322
376
  const results = {};
323
- const tracer = new tracer_langchain_js_1.LangChainTracer();
324
- await tracer.newSession(sessionName_);
325
- for (const example of examples) {
326
- if (isLLM(llmOrChain)) {
327
- const llmResult = await this.runLLM(example, tracer, llmOrChain, numRepetitions);
377
+ const modelOrFactoryType = await getModelOrFactoryType(llmOrChainFactory);
378
+ await Promise.all(examples.map(async (example) => {
379
+ const tracer = new tracer_langchain_js_1.LangChainTracer({
380
+ exampleId: example.id,
381
+ sessionName: sessionName_,
382
+ });
383
+ if (modelOrFactoryType === "llm") {
384
+ const llm = llmOrChainFactory;
385
+ const llmResult = await this.runLLM(example, tracer, llm, numRepetitions);
328
386
  results[example.id] = llmResult;
329
387
  }
330
- else if (isChain(llmOrChain)) {
331
- const ChainResult = await this.runChain(example, tracer, llmOrChain, numRepetitions);
332
- results[example.id] = ChainResult;
388
+ else if (modelOrFactoryType === "chainFactory") {
389
+ const chainFactory = llmOrChainFactory;
390
+ const chainResult = await this.runChain(example, tracer, chainFactory, numRepetitions);
391
+ results[example.id] = chainResult;
333
392
  }
334
- else if (isChatModel(llmOrChain)) {
335
- throw new Error("Chat models not yet supported");
393
+ else if (modelOrFactoryType === "chatModel") {
394
+ const chatModel = llmOrChainFactory;
395
+ const chatModelResult = await this.runChatModel(example, tracer, chatModel, numRepetitions);
396
+ results[example.id] = chatModelResult;
336
397
  }
337
398
  else {
338
- throw new Error(` llm or chain type: ${llmOrChain}`);
399
+ throw new Error(` llm or chain type: ${llmOrChainFactory}`);
339
400
  }
340
- }
401
+ }));
341
402
  return results;
342
403
  }
343
404
  }
@@ -36,9 +36,9 @@ export interface Example extends BaseExample {
36
36
  runs: RunResult[];
37
37
  }
38
38
  export type DatasetRunResults = Record<string, (string | LLMResult | ChainValues)[]>;
39
- export declare function isLLM(llm: BaseLanguageModel | BaseChain): llm is BaseLLM;
40
- export declare function isChatModel(llm: BaseLanguageModel): llm is BaseChatModel;
41
- export declare function isChain(llm: BaseLanguageModel | BaseChain): llm is BaseChain;
39
+ export declare function isLLM(llm: BaseLanguageModel | (() => Promise<BaseChain>)): llm is BaseLLM;
40
+ export declare function isChatModel(llm: BaseLanguageModel | (() => Promise<BaseChain>)): llm is BaseChatModel;
41
+ export declare function isChain(llm: BaseLanguageModel | (() => Promise<BaseChain>)): Promise<boolean>;
42
42
  export declare class LangChainPlusClient {
43
43
  private apiKey?;
44
44
  private apiUrl;
@@ -50,6 +50,7 @@ export declare class LangChainPlusClient {
50
50
  private get queryParams();
51
51
  private _get;
52
52
  uploadCsv(csvFile: Blob, fileName: string, description: string, inputKeys: string[], outputKeys: string[]): Promise<Dataset>;
53
+ createDataset(name: string, description: string): Promise<Dataset>;
53
54
  readDataset(datasetId: string | undefined, datasetName: string | undefined): Promise<Dataset>;
54
55
  listDatasets(limit?: number): Promise<Dataset[]>;
55
56
  deleteDataset(datasetId: string | undefined, datasetName: string | undefined): Promise<Dataset>;
@@ -58,6 +59,7 @@ export declare class LangChainPlusClient {
58
59
  listExamples(datasetId?: string | undefined, datasetName?: string | undefined): Promise<Example[]>;
59
60
  deleteExample(exampleId: string): Promise<Example>;
60
61
  protected runLLM(example: Example, tracer: LangChainTracer, llm: BaseLLM, numRepetitions?: number): Promise<(LLMResult | string)[]>;
61
- protected runChain(example: Example, tracer: LangChainTracer, chain: BaseChain, numRepetitions?: number): Promise<(ChainValues | string)[]>;
62
- runOnDataset(datasetName: string, llmOrChain: BaseLanguageModel | BaseChain, numRepetitions?: number, sessionName?: string | undefined): Promise<DatasetRunResults>;
62
+ protected runChain(example: Example, tracer: LangChainTracer, chainFactory: () => Promise<BaseChain>, numRepetitions?: number): Promise<(ChainValues | string)[]>;
63
+ protected runChatModel(example: Example, tracer: LangChainTracer, chatModel: BaseChatModel, numRepetitions?: number): Promise<(LLMResult | string)[]>;
64
+ runOnDataset(datasetName: string, llmOrChainFactory: BaseLanguageModel | (() => Promise<BaseChain>), numRepetitions?: number, sessionName?: string | undefined): Promise<DatasetRunResults>;
63
65
  }