langchain 0.0.167 → 0.0.169

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 (90) hide show
  1. package/README.md +4 -4
  2. package/chat_models/cloudflare_workersai.cjs +1 -0
  3. package/chat_models/cloudflare_workersai.d.ts +1 -0
  4. package/chat_models/cloudflare_workersai.js +1 -0
  5. package/chat_models/fake.cjs +1 -0
  6. package/chat_models/fake.d.ts +1 -0
  7. package/chat_models/fake.js +1 -0
  8. package/chat_models/yandex.cjs +1 -0
  9. package/chat_models/yandex.d.ts +1 -0
  10. package/chat_models/yandex.js +1 -0
  11. package/dist/agents/chat/index.cjs +3 -2
  12. package/dist/agents/chat/index.d.ts +3 -0
  13. package/dist/agents/chat/index.js +3 -2
  14. package/dist/callbacks/handlers/llmonitor.cjs +21 -17
  15. package/dist/callbacks/handlers/llmonitor.js +21 -17
  16. package/dist/chat_models/cloudflare_workersai.cjs +145 -0
  17. package/dist/chat_models/cloudflare_workersai.d.ts +46 -0
  18. package/dist/chat_models/cloudflare_workersai.js +141 -0
  19. package/dist/chat_models/fake.cjs +101 -0
  20. package/dist/chat_models/fake.d.ts +36 -0
  21. package/dist/chat_models/fake.js +97 -0
  22. package/dist/chat_models/yandex.cjs +117 -0
  23. package/dist/chat_models/yandex.d.ts +16 -0
  24. package/dist/chat_models/yandex.js +113 -0
  25. package/dist/evaluation/comparison/prompt.d.ts +2 -2
  26. package/dist/experimental/chains/violation_of_expectations/index.cjs +5 -0
  27. package/dist/experimental/chains/violation_of_expectations/index.d.ts +1 -0
  28. package/dist/experimental/chains/violation_of_expectations/index.js +1 -0
  29. package/dist/experimental/chains/violation_of_expectations/types.cjs +49 -0
  30. package/dist/experimental/chains/violation_of_expectations/types.d.ts +69 -0
  31. package/dist/experimental/chains/violation_of_expectations/types.js +46 -0
  32. package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_chain.cjs +328 -0
  33. package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_chain.d.ts +148 -0
  34. package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_chain.js +324 -0
  35. package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_prompt.cjs +49 -0
  36. package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_prompt.d.ts +5 -0
  37. package/dist/experimental/chains/violation_of_expectations/violation_of_expectations_prompt.js +46 -0
  38. package/dist/llms/cloudflare_workersai.cjs +124 -0
  39. package/dist/llms/cloudflare_workersai.d.ts +49 -0
  40. package/dist/llms/cloudflare_workersai.js +120 -0
  41. package/dist/llms/fake.cjs +82 -0
  42. package/dist/llms/fake.d.ts +31 -0
  43. package/dist/llms/fake.js +78 -0
  44. package/dist/llms/sagemaker_endpoint.cjs +9 -7
  45. package/dist/llms/sagemaker_endpoint.d.ts +3 -3
  46. package/dist/llms/sagemaker_endpoint.js +9 -7
  47. package/dist/load/import_constants.cjs +2 -0
  48. package/dist/load/import_constants.js +2 -0
  49. package/dist/load/import_map.cjs +8 -2
  50. package/dist/load/import_map.d.ts +6 -0
  51. package/dist/load/import_map.js +6 -0
  52. package/dist/retrievers/zep.cjs +29 -3
  53. package/dist/retrievers/zep.d.ts +14 -0
  54. package/dist/retrievers/zep.js +29 -3
  55. package/dist/util/axios-fetch-adapter.cjs +1 -1
  56. package/dist/util/axios-fetch-adapter.js +1 -1
  57. package/dist/util/env.cjs +1 -1
  58. package/dist/util/env.js +1 -1
  59. package/dist/util/event-source-parse.cjs +1 -1
  60. package/dist/util/event-source-parse.js +1 -1
  61. package/dist/vectorstores/closevector/common.cjs +128 -0
  62. package/dist/vectorstores/closevector/common.d.ts +82 -0
  63. package/dist/vectorstores/closevector/common.js +124 -0
  64. package/dist/vectorstores/closevector/node.cjs +109 -0
  65. package/dist/vectorstores/closevector/node.d.ts +83 -0
  66. package/dist/vectorstores/closevector/node.js +105 -0
  67. package/dist/vectorstores/closevector/web.cjs +109 -0
  68. package/dist/vectorstores/closevector/web.d.ts +80 -0
  69. package/dist/vectorstores/closevector/web.js +105 -0
  70. package/dist/vectorstores/faiss.cjs +38 -6
  71. package/dist/vectorstores/faiss.d.ts +14 -2
  72. package/dist/vectorstores/faiss.js +38 -6
  73. package/dist/vectorstores/weaviate.cjs +13 -2
  74. package/dist/vectorstores/weaviate.js +13 -2
  75. package/experimental/chains/violation_of_expectations.cjs +1 -0
  76. package/experimental/chains/violation_of_expectations.d.ts +1 -0
  77. package/experimental/chains/violation_of_expectations.js +1 -0
  78. package/llms/cloudflare_workersai.cjs +1 -0
  79. package/llms/cloudflare_workersai.d.ts +1 -0
  80. package/llms/cloudflare_workersai.js +1 -0
  81. package/llms/fake.cjs +1 -0
  82. package/llms/fake.d.ts +1 -0
  83. package/llms/fake.js +1 -0
  84. package/package.json +92 -13
  85. package/vectorstores/closevector/node.cjs +1 -0
  86. package/vectorstores/closevector/node.d.ts +1 -0
  87. package/vectorstores/closevector/node.js +1 -0
  88. package/vectorstores/closevector/web.cjs +1 -0
  89. package/vectorstores/closevector/web.d.ts +1 -0
  90. package/vectorstores/closevector/web.js +1 -0
@@ -0,0 +1,328 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ViolationOfExpectationsChain = void 0;
4
+ const openai_functions_js_1 = require("../../../output_parsers/openai_functions.cjs");
5
+ const index_js_1 = require("../../../schema/index.cjs");
6
+ const output_parser_js_1 = require("../../../schema/output_parser.cjs");
7
+ const base_js_1 = require("../../../chains/base.cjs");
8
+ const types_js_1 = require("./types.cjs");
9
+ const violation_of_expectations_prompt_js_1 = require("./violation_of_expectations_prompt.cjs");
10
+ /**
11
+ * Chain that generates key insights/facts of a user based on a
12
+ * a chat conversation with an AI.
13
+ */
14
+ class ViolationOfExpectationsChain extends base_js_1.BaseChain {
15
+ static lc_name() {
16
+ return "ViolationOfExpectationsChain";
17
+ }
18
+ _chainType() {
19
+ return "violation_of_expectation_chain";
20
+ }
21
+ get inputKeys() {
22
+ return [this.chatHistoryKey];
23
+ }
24
+ get outputKeys() {
25
+ return [this.thoughtsKey];
26
+ }
27
+ constructor(fields) {
28
+ super(fields);
29
+ Object.defineProperty(this, "chatHistoryKey", {
30
+ enumerable: true,
31
+ configurable: true,
32
+ writable: true,
33
+ value: "chat_history"
34
+ });
35
+ Object.defineProperty(this, "thoughtsKey", {
36
+ enumerable: true,
37
+ configurable: true,
38
+ writable: true,
39
+ value: "thoughts"
40
+ });
41
+ Object.defineProperty(this, "retriever", {
42
+ enumerable: true,
43
+ configurable: true,
44
+ writable: true,
45
+ value: void 0
46
+ });
47
+ Object.defineProperty(this, "llm", {
48
+ enumerable: true,
49
+ configurable: true,
50
+ writable: true,
51
+ value: void 0
52
+ });
53
+ Object.defineProperty(this, "jsonOutputParser", {
54
+ enumerable: true,
55
+ configurable: true,
56
+ writable: true,
57
+ value: void 0
58
+ });
59
+ Object.defineProperty(this, "stringOutputParser", {
60
+ enumerable: true,
61
+ configurable: true,
62
+ writable: true,
63
+ value: void 0
64
+ });
65
+ this.retriever = fields.retriever;
66
+ this.llm = fields.llm;
67
+ this.jsonOutputParser = new openai_functions_js_1.JsonOutputFunctionsParser();
68
+ this.stringOutputParser = new output_parser_js_1.StringOutputParser();
69
+ }
70
+ getChatHistoryString(chatHistory) {
71
+ return chatHistory
72
+ .map((chatMessage) => {
73
+ if (chatMessage._getType() === "human") {
74
+ return `Human: ${chatMessage.content}`;
75
+ }
76
+ else if (chatMessage._getType() === "ai") {
77
+ return `AI: ${chatMessage.content}`;
78
+ }
79
+ else {
80
+ return `${chatMessage.content}`;
81
+ }
82
+ })
83
+ .join("\n");
84
+ }
85
+ removeDuplicateStrings(strings) {
86
+ return [...new Set(strings)];
87
+ }
88
+ /**
89
+ * This method breaks down the chat history into chunks of messages.
90
+ * Each chunk consists of a sequence of messages ending with an AI message and the subsequent user response, if any.
91
+ *
92
+ * @param {BaseMessage[]} chatHistory - The chat history to be chunked.
93
+ *
94
+ * @returns {MessageChunkResult[]} An array of message chunks. Each chunk includes a sequence of messages and the subsequent user response.
95
+ *
96
+ * @description
97
+ * The method iterates over the chat history and pushes each message into a temporary array.
98
+ * When it encounters an AI message, it checks for a subsequent user message.
99
+ * If a user message is found, it is considered as the user response to the AI message.
100
+ * If no user message is found after the AI message, the user response is undefined.
101
+ * The method then pushes the chunk (sequence of messages and user response) into the result array.
102
+ * This process continues until all messages in the chat history have been processed.
103
+ */
104
+ chunkMessagesByAIResponse(chatHistory) {
105
+ const newArray = [];
106
+ const tempArray = [];
107
+ chatHistory.forEach((item, index) => {
108
+ tempArray.push(item);
109
+ if (item._getType() === "ai") {
110
+ let userResponse = chatHistory[index + 1];
111
+ if (!userResponse || userResponse._getType() !== "human") {
112
+ userResponse = undefined;
113
+ }
114
+ newArray.push({
115
+ chunkedMessages: tempArray,
116
+ userResponse: userResponse
117
+ ? new index_js_1.HumanMessage(userResponse)
118
+ : undefined,
119
+ });
120
+ }
121
+ });
122
+ return newArray;
123
+ }
124
+ /**
125
+ * This method processes a chat history to generate insights about the user.
126
+ *
127
+ * @param {ChainValues} values - The input values for the chain. It should contain a key for chat history.
128
+ * @param {CallbackManagerForChainRun} [runManager] - Optional callback manager for the chain run.
129
+ *
130
+ * @returns {Promise<ChainValues>} A promise that resolves to a list of insights about the user.
131
+ *
132
+ * @throws {Error} If the chat history key is not found in the input values or if the chat history is not an array of BaseMessages.
133
+ *
134
+ * @description
135
+ * The method performs the following steps:
136
+ * 1. Checks if the chat history key is present in the input values and if the chat history is an array of BaseMessages.
137
+ * 2. Breaks the chat history into chunks of messages.
138
+ * 3. For each chunk, it generates an initial prediction for the user's next message.
139
+ * 4. For each prediction, it generates insights and prediction violations, and regenerates the prediction based on the violations.
140
+ * 5. For each set of messages, it generates a fact/insight about the user.
141
+ * The method returns a list of these insights.
142
+ */
143
+ async _call(values, runManager) {
144
+ if (!(this.chatHistoryKey in values)) {
145
+ throw new Error(`Chat history key ${this.chatHistoryKey} not found`);
146
+ }
147
+ const chatHistory = values[this.chatHistoryKey];
148
+ const isEveryMessageBaseMessage = chatHistory.every((message) => (0, index_js_1.isBaseMessage)(message));
149
+ if (!isEveryMessageBaseMessage) {
150
+ throw new Error("Chat history must be an array of BaseMessages");
151
+ }
152
+ const messageChunks = this.chunkMessagesByAIResponse(chatHistory);
153
+ // Generate the initial prediction for every user message.
154
+ const userPredictions = await Promise.all(messageChunks.map(async (chatHistoryChunk) => ({
155
+ userPredictions: await this.predictNextUserMessage(chatHistoryChunk.chunkedMessages),
156
+ userResponse: chatHistoryChunk.userResponse,
157
+ runManager,
158
+ })));
159
+ // Generate insights, and prediction violations for every user message.
160
+ // This call also regenerates the prediction based on the violations.
161
+ const predictionViolations = await Promise.all(userPredictions.map((prediction) => this.getPredictionViolations({
162
+ userPredictions: prediction.userPredictions,
163
+ userResponse: prediction.userResponse,
164
+ runManager,
165
+ })));
166
+ // Generate a fact/insight about the user for every set of messages.
167
+ const insights = await Promise.all(predictionViolations.map((violation) => this.generateFacts({
168
+ userResponse: violation.userResponse,
169
+ predictions: {
170
+ revisedPrediction: violation.revisedPrediction,
171
+ explainedPredictionErrors: violation.explainedPredictionErrors,
172
+ },
173
+ })));
174
+ return {
175
+ insights,
176
+ };
177
+ }
178
+ /**
179
+ * This method predicts the next user message based on the chat history.
180
+ *
181
+ * @param {BaseMessage[]} chatHistory - The chat history based on which the next user message is predicted.
182
+ * @param {CallbackManagerForChainRun} [runManager] - Optional callback manager for the chain run.
183
+ *
184
+ * @returns {Promise<PredictNextUserMessageResponse>} A promise that resolves to the predicted next user message, the user state, and any insights.
185
+ *
186
+ * @throws {Error} If the response from the language model does not contain the expected keys: 'userState', 'predictedUserMessage', and 'insights'.
187
+ */
188
+ async predictNextUserMessage(chatHistory, runManager) {
189
+ const messageString = this.getChatHistoryString(chatHistory);
190
+ const llmWithFunctions = this.llm.bind({
191
+ functions: [types_js_1.PREDICT_NEXT_USER_MESSAGE_FUNCTION],
192
+ function_call: { name: types_js_1.PREDICT_NEXT_USER_MESSAGE_FUNCTION.name },
193
+ });
194
+ const chain = violation_of_expectations_prompt_js_1.PREDICT_NEXT_USER_MESSAGE_PROMPT.pipe(llmWithFunctions).pipe(this.jsonOutputParser);
195
+ const res = await chain.invoke({
196
+ chat_history: messageString,
197
+ }, runManager?.getChild("prediction"));
198
+ if (!("userState" in res &&
199
+ "predictedUserMessage" in res &&
200
+ "insights" in res)) {
201
+ throw new Error(`Invalid response from LLM: ${JSON.stringify(res)}`);
202
+ }
203
+ const predictionResponse = res;
204
+ // Query the retriever for relevant insights. Use the generates insights as a query.
205
+ const retrievedDocs = await this.retrieveRelevantInsights(predictionResponse.insights);
206
+ const relevantDocs = this.removeDuplicateStrings([
207
+ ...predictionResponse.insights,
208
+ ...retrievedDocs,
209
+ ]);
210
+ return {
211
+ ...predictionResponse,
212
+ insights: relevantDocs,
213
+ };
214
+ }
215
+ /**
216
+ * Retrieves relevant insights based on the provided insights.
217
+ *
218
+ * @param {Array<string>} insights - An array of insights to be used for retrieving relevant documents.
219
+ *
220
+ * @returns {Promise<Array<string>>} A promise that resolves to an array of relevant insights content.
221
+ */
222
+ async retrieveRelevantInsights(insights) {
223
+ // Only extract the first relevant doc from the retriever. We don't need more than one.
224
+ const relevantInsightsDocuments = await Promise.all(insights.map(async (insight) => {
225
+ const relevantInsight = await this.retriever.getRelevantDocuments(insight);
226
+ return relevantInsight[0];
227
+ }));
228
+ const relevantInsightsContent = relevantInsightsDocuments.map((document) => document.pageContent);
229
+ return relevantInsightsContent;
230
+ }
231
+ /**
232
+ * This method generates prediction violations based on the predicted and actual user responses.
233
+ * It also generates a revised prediction based on the identified violations.
234
+ *
235
+ * @param {Object} params - The parameters for the method.
236
+ * @param {PredictNextUserMessageResponse} params.userPredictions - The predicted user message, user state, and insights.
237
+ * @param {BaseMessage} [params.userResponse] - The actual user response.
238
+ * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.
239
+ *
240
+ * @returns {Promise<{ userResponse: BaseMessage | undefined; revisedPrediction: string; explainedPredictionErrors: Array<string>; }>} A promise that resolves to an object containing the actual user response, the revised prediction, and the explained prediction errors.
241
+ *
242
+ * @throws {Error} If the response from the language model does not contain the expected keys: 'violationExplanation', 'explainedPredictionErrors', and 'accuratePrediction'.
243
+ */
244
+ async getPredictionViolations({ userPredictions, userResponse, runManager, }) {
245
+ const llmWithFunctions = this.llm.bind({
246
+ functions: [types_js_1.PREDICTION_VIOLATIONS_FUNCTION],
247
+ function_call: { name: types_js_1.PREDICTION_VIOLATIONS_FUNCTION.name },
248
+ });
249
+ const chain = violation_of_expectations_prompt_js_1.PREDICTION_VIOLATIONS_PROMPT.pipe(llmWithFunctions).pipe(this.jsonOutputParser);
250
+ const res = (await chain.invoke({
251
+ predicted_output: userPredictions.predictedUserMessage,
252
+ actual_output: userResponse?.content ?? "",
253
+ user_insights: userPredictions.insights.join("\n"),
254
+ }, runManager?.getChild("prediction_violations")));
255
+ // Generate a revised prediction based on violations.
256
+ const revisedPrediction = await this.generateRevisedPrediction({
257
+ originalPrediction: userPredictions.predictedUserMessage,
258
+ explainedPredictionErrors: res.explainedPredictionErrors,
259
+ userInsights: userPredictions.insights,
260
+ runManager,
261
+ });
262
+ return {
263
+ userResponse,
264
+ revisedPrediction,
265
+ explainedPredictionErrors: res.explainedPredictionErrors,
266
+ };
267
+ }
268
+ /**
269
+ * This method generates a revised prediction based on the original prediction, explained prediction errors, and user insights.
270
+ *
271
+ * @param {Object} params - The parameters for the method.
272
+ * @param {string} params.originalPrediction - The original prediction made by the model.
273
+ * @param {Array<string>} params.explainedPredictionErrors - An array of explained prediction errors.
274
+ * @param {Array<string>} params.userInsights - An array of insights about the user.
275
+ * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.
276
+ *
277
+ * @returns {Promise<string>} A promise that resolves to a revised prediction.
278
+ */
279
+ async generateRevisedPrediction({ originalPrediction, explainedPredictionErrors, userInsights, runManager, }) {
280
+ const revisedPredictionChain = violation_of_expectations_prompt_js_1.GENERATE_REVISED_PREDICTION_PROMPT.pipe(this.llm).pipe(this.stringOutputParser);
281
+ const revisedPredictionRes = await revisedPredictionChain.invoke({
282
+ prediction: originalPrediction,
283
+ explained_prediction_errors: explainedPredictionErrors.join("\n"),
284
+ user_insights: userInsights.join("\n"),
285
+ }, runManager?.getChild("prediction_revision"));
286
+ return revisedPredictionRes;
287
+ }
288
+ /**
289
+ * This method generates facts or insights about the user based on the revised prediction, explained prediction errors, and the user's response.
290
+ *
291
+ * @param {Object} params - The parameters for the method.
292
+ * @param {BaseMessage} [params.userResponse] - The actual user response.
293
+ * @param {Object} params.predictions - The revised prediction and explained prediction errors.
294
+ * @param {string} params.predictions.revisedPrediction - The revised prediction made by the model.
295
+ * @param {Array<string>} params.predictions.explainedPredictionErrors - An array of explained prediction errors.
296
+ * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.
297
+ *
298
+ * @returns {Promise<string>} A promise that resolves to a string containing the generated facts or insights about the user.
299
+ */
300
+ async generateFacts({ userResponse, predictions, runManager, }) {
301
+ const chain = violation_of_expectations_prompt_js_1.GENERATE_FACTS_PROMPT.pipe(this.llm).pipe(this.stringOutputParser);
302
+ const res = await chain.invoke({
303
+ prediction_violations: predictions.explainedPredictionErrors.join("\n"),
304
+ prediction: predictions.revisedPrediction,
305
+ user_message: userResponse?.content ?? "",
306
+ }, runManager?.getChild("generate_facts"));
307
+ return res;
308
+ }
309
+ /**
310
+ * Static method that creates a ViolationOfExpectationsChain instance from a
311
+ * ChatOpenAI and retriever. It also accepts optional options
312
+ * to customize the chain.
313
+ *
314
+ * @param llm The ChatOpenAI instance.
315
+ * @param retriever The retriever used for similarity search.
316
+ * @param options Optional options to customize the chain.
317
+ *
318
+ * @returns A new instance of ViolationOfExpectationsChain.
319
+ */
320
+ static fromLLM(llm, retriever, options) {
321
+ return new this({
322
+ retriever,
323
+ llm,
324
+ ...options,
325
+ });
326
+ }
327
+ }
328
+ exports.ViolationOfExpectationsChain = ViolationOfExpectationsChain;
@@ -0,0 +1,148 @@
1
+ import { CallbackManagerForChainRun } from "../../../callbacks/manager.js";
2
+ import { ChatOpenAI } from "../../../chat_models/openai.js";
3
+ import { JsonOutputFunctionsParser } from "../../../output_parsers/openai_functions.js";
4
+ import { BaseMessage, ChainValues } from "../../../schema/index.js";
5
+ import { StringOutputParser } from "../../../schema/output_parser.js";
6
+ import { BaseRetriever } from "../../../schema/retriever.js";
7
+ import { BaseChain, ChainInputs } from "../../../chains/base.js";
8
+ import { MessageChunkResult } from "./types.js";
9
+ /**
10
+ * Interface for the input parameters of the ViolationOfExpectationsChain class.
11
+ */
12
+ export interface ViolationOfExpectationsChainInput extends ChainInputs {
13
+ /**
14
+ * The retriever to use for retrieving stored
15
+ * thoughts and insights.
16
+ */
17
+ retriever: BaseRetriever;
18
+ /**
19
+ * The LLM to use
20
+ */
21
+ llm: ChatOpenAI;
22
+ }
23
+ /**
24
+ * Chain that generates key insights/facts of a user based on a
25
+ * a chat conversation with an AI.
26
+ */
27
+ export declare class ViolationOfExpectationsChain extends BaseChain implements ViolationOfExpectationsChainInput {
28
+ static lc_name(): string;
29
+ _chainType(): string;
30
+ chatHistoryKey: string;
31
+ thoughtsKey: string;
32
+ get inputKeys(): string[];
33
+ get outputKeys(): string[];
34
+ retriever: BaseRetriever;
35
+ llm: ChatOpenAI;
36
+ jsonOutputParser: JsonOutputFunctionsParser;
37
+ stringOutputParser: StringOutputParser;
38
+ constructor(fields: ViolationOfExpectationsChainInput);
39
+ getChatHistoryString(chatHistory: BaseMessage[]): string;
40
+ removeDuplicateStrings(strings: Array<string>): Array<string>;
41
+ /**
42
+ * This method breaks down the chat history into chunks of messages.
43
+ * Each chunk consists of a sequence of messages ending with an AI message and the subsequent user response, if any.
44
+ *
45
+ * @param {BaseMessage[]} chatHistory - The chat history to be chunked.
46
+ *
47
+ * @returns {MessageChunkResult[]} An array of message chunks. Each chunk includes a sequence of messages and the subsequent user response.
48
+ *
49
+ * @description
50
+ * The method iterates over the chat history and pushes each message into a temporary array.
51
+ * When it encounters an AI message, it checks for a subsequent user message.
52
+ * If a user message is found, it is considered as the user response to the AI message.
53
+ * If no user message is found after the AI message, the user response is undefined.
54
+ * The method then pushes the chunk (sequence of messages and user response) into the result array.
55
+ * This process continues until all messages in the chat history have been processed.
56
+ */
57
+ chunkMessagesByAIResponse(chatHistory: BaseMessage[]): MessageChunkResult[];
58
+ /**
59
+ * This method processes a chat history to generate insights about the user.
60
+ *
61
+ * @param {ChainValues} values - The input values for the chain. It should contain a key for chat history.
62
+ * @param {CallbackManagerForChainRun} [runManager] - Optional callback manager for the chain run.
63
+ *
64
+ * @returns {Promise<ChainValues>} A promise that resolves to a list of insights about the user.
65
+ *
66
+ * @throws {Error} If the chat history key is not found in the input values or if the chat history is not an array of BaseMessages.
67
+ *
68
+ * @description
69
+ * The method performs the following steps:
70
+ * 1. Checks if the chat history key is present in the input values and if the chat history is an array of BaseMessages.
71
+ * 2. Breaks the chat history into chunks of messages.
72
+ * 3. For each chunk, it generates an initial prediction for the user's next message.
73
+ * 4. For each prediction, it generates insights and prediction violations, and regenerates the prediction based on the violations.
74
+ * 5. For each set of messages, it generates a fact/insight about the user.
75
+ * The method returns a list of these insights.
76
+ */
77
+ _call(values: ChainValues, runManager?: CallbackManagerForChainRun): Promise<ChainValues>;
78
+ /**
79
+ * This method predicts the next user message based on the chat history.
80
+ *
81
+ * @param {BaseMessage[]} chatHistory - The chat history based on which the next user message is predicted.
82
+ * @param {CallbackManagerForChainRun} [runManager] - Optional callback manager for the chain run.
83
+ *
84
+ * @returns {Promise<PredictNextUserMessageResponse>} A promise that resolves to the predicted next user message, the user state, and any insights.
85
+ *
86
+ * @throws {Error} If the response from the language model does not contain the expected keys: 'userState', 'predictedUserMessage', and 'insights'.
87
+ */
88
+ private predictNextUserMessage;
89
+ /**
90
+ * Retrieves relevant insights based on the provided insights.
91
+ *
92
+ * @param {Array<string>} insights - An array of insights to be used for retrieving relevant documents.
93
+ *
94
+ * @returns {Promise<Array<string>>} A promise that resolves to an array of relevant insights content.
95
+ */
96
+ private retrieveRelevantInsights;
97
+ /**
98
+ * This method generates prediction violations based on the predicted and actual user responses.
99
+ * It also generates a revised prediction based on the identified violations.
100
+ *
101
+ * @param {Object} params - The parameters for the method.
102
+ * @param {PredictNextUserMessageResponse} params.userPredictions - The predicted user message, user state, and insights.
103
+ * @param {BaseMessage} [params.userResponse] - The actual user response.
104
+ * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.
105
+ *
106
+ * @returns {Promise<{ userResponse: BaseMessage | undefined; revisedPrediction: string; explainedPredictionErrors: Array<string>; }>} A promise that resolves to an object containing the actual user response, the revised prediction, and the explained prediction errors.
107
+ *
108
+ * @throws {Error} If the response from the language model does not contain the expected keys: 'violationExplanation', 'explainedPredictionErrors', and 'accuratePrediction'.
109
+ */
110
+ private getPredictionViolations;
111
+ /**
112
+ * This method generates a revised prediction based on the original prediction, explained prediction errors, and user insights.
113
+ *
114
+ * @param {Object} params - The parameters for the method.
115
+ * @param {string} params.originalPrediction - The original prediction made by the model.
116
+ * @param {Array<string>} params.explainedPredictionErrors - An array of explained prediction errors.
117
+ * @param {Array<string>} params.userInsights - An array of insights about the user.
118
+ * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.
119
+ *
120
+ * @returns {Promise<string>} A promise that resolves to a revised prediction.
121
+ */
122
+ private generateRevisedPrediction;
123
+ /**
124
+ * This method generates facts or insights about the user based on the revised prediction, explained prediction errors, and the user's response.
125
+ *
126
+ * @param {Object} params - The parameters for the method.
127
+ * @param {BaseMessage} [params.userResponse] - The actual user response.
128
+ * @param {Object} params.predictions - The revised prediction and explained prediction errors.
129
+ * @param {string} params.predictions.revisedPrediction - The revised prediction made by the model.
130
+ * @param {Array<string>} params.predictions.explainedPredictionErrors - An array of explained prediction errors.
131
+ * @param {CallbackManagerForChainRun} [params.runManager] - Optional callback manager for the chain run.
132
+ *
133
+ * @returns {Promise<string>} A promise that resolves to a string containing the generated facts or insights about the user.
134
+ */
135
+ private generateFacts;
136
+ /**
137
+ * Static method that creates a ViolationOfExpectationsChain instance from a
138
+ * ChatOpenAI and retriever. It also accepts optional options
139
+ * to customize the chain.
140
+ *
141
+ * @param llm The ChatOpenAI instance.
142
+ * @param retriever The retriever used for similarity search.
143
+ * @param options Optional options to customize the chain.
144
+ *
145
+ * @returns A new instance of ViolationOfExpectationsChain.
146
+ */
147
+ static fromLLM(llm: ChatOpenAI, retriever: BaseRetriever, options?: Partial<Omit<ViolationOfExpectationsChainInput, "llm" | "retriever">>): ViolationOfExpectationsChain;
148
+ }