@langchain/core 1.0.0-alpha.4 → 1.0.0-alpha.5

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 (103) hide show
  1. package/dist/agents.d.ts.map +1 -1
  2. package/dist/caches/base.d.ts.map +1 -1
  3. package/dist/callbacks/base.d.ts.map +1 -1
  4. package/dist/language_models/chat_models.d.ts.map +1 -1
  5. package/dist/load/import_map.cjs +1 -1
  6. package/dist/load/import_map.js +1 -1
  7. package/dist/messages/ai.cjs +15 -10
  8. package/dist/messages/ai.cjs.map +1 -1
  9. package/dist/messages/ai.js +15 -10
  10. package/dist/messages/ai.js.map +1 -1
  11. package/dist/messages/base.cjs +8 -1
  12. package/dist/messages/base.cjs.map +1 -1
  13. package/dist/messages/base.js +8 -1
  14. package/dist/messages/base.js.map +1 -1
  15. package/dist/utils/testing/chat_models.cjs +245 -0
  16. package/dist/utils/testing/chat_models.cjs.map +1 -0
  17. package/dist/utils/testing/chat_models.d.cts +134 -0
  18. package/dist/utils/testing/chat_models.d.cts.map +1 -0
  19. package/dist/utils/testing/chat_models.d.ts +134 -0
  20. package/dist/utils/testing/chat_models.d.ts.map +1 -0
  21. package/dist/utils/testing/chat_models.js +243 -0
  22. package/dist/utils/testing/chat_models.js.map +1 -0
  23. package/dist/utils/testing/embeddings.cjs +90 -0
  24. package/dist/utils/testing/embeddings.cjs.map +1 -0
  25. package/dist/utils/testing/embeddings.d.cts +58 -0
  26. package/dist/utils/testing/embeddings.d.cts.map +1 -0
  27. package/dist/utils/testing/embeddings.d.ts +58 -0
  28. package/dist/utils/testing/embeddings.d.ts.map +1 -0
  29. package/dist/utils/testing/embeddings.js +89 -0
  30. package/dist/utils/testing/embeddings.js.map +1 -0
  31. package/dist/utils/testing/index.cjs +42 -655
  32. package/dist/utils/testing/index.cjs.map +1 -1
  33. package/dist/utils/testing/index.d.cts +11 -379
  34. package/dist/utils/testing/index.d.ts +11 -379
  35. package/dist/utils/testing/index.js +10 -623
  36. package/dist/utils/testing/index.js.map +1 -1
  37. package/dist/utils/testing/llms.cjs +59 -0
  38. package/dist/utils/testing/llms.cjs.map +1 -0
  39. package/dist/utils/testing/llms.d.cts +31 -0
  40. package/dist/utils/testing/llms.d.cts.map +1 -0
  41. package/dist/utils/testing/llms.d.ts +31 -0
  42. package/dist/utils/testing/llms.d.ts.map +1 -0
  43. package/dist/utils/testing/llms.js +58 -0
  44. package/dist/utils/testing/llms.js.map +1 -0
  45. package/dist/utils/testing/message_history.cjs +67 -0
  46. package/dist/utils/testing/message_history.cjs.map +1 -0
  47. package/dist/utils/testing/message_history.d.cts +31 -0
  48. package/dist/utils/testing/message_history.d.cts.map +1 -0
  49. package/dist/utils/testing/message_history.d.ts +31 -0
  50. package/dist/utils/testing/message_history.d.ts.map +1 -0
  51. package/dist/utils/testing/message_history.js +65 -0
  52. package/dist/utils/testing/message_history.js.map +1 -0
  53. package/dist/utils/testing/output_parsers.cjs +20 -0
  54. package/dist/utils/testing/output_parsers.cjs.map +1 -0
  55. package/dist/utils/testing/output_parsers.d.cts +16 -0
  56. package/dist/utils/testing/output_parsers.d.cts.map +1 -0
  57. package/dist/utils/testing/output_parsers.d.ts +16 -0
  58. package/dist/utils/testing/output_parsers.d.ts.map +1 -0
  59. package/dist/utils/testing/output_parsers.js +20 -0
  60. package/dist/utils/testing/output_parsers.js.map +1 -0
  61. package/dist/utils/testing/retrievers.cjs +19 -0
  62. package/dist/utils/testing/retrievers.cjs.map +1 -0
  63. package/dist/utils/testing/retrievers.d.cts +17 -0
  64. package/dist/utils/testing/retrievers.d.cts.map +1 -0
  65. package/dist/utils/testing/retrievers.d.ts +17 -0
  66. package/dist/utils/testing/retrievers.d.ts.map +1 -0
  67. package/dist/utils/testing/retrievers.js +19 -0
  68. package/dist/utils/testing/retrievers.js.map +1 -0
  69. package/dist/utils/testing/runnables.cjs +19 -0
  70. package/dist/utils/testing/runnables.cjs.map +1 -0
  71. package/dist/utils/testing/runnables.d.cts +15 -0
  72. package/dist/utils/testing/runnables.d.cts.map +1 -0
  73. package/dist/utils/testing/runnables.d.ts +15 -0
  74. package/dist/utils/testing/runnables.d.ts.map +1 -0
  75. package/dist/utils/testing/runnables.js +19 -0
  76. package/dist/utils/testing/runnables.js.map +1 -0
  77. package/dist/utils/testing/tools.cjs +21 -0
  78. package/dist/utils/testing/tools.cjs.map +1 -0
  79. package/dist/utils/testing/tools.d.cts +21 -0
  80. package/dist/utils/testing/tools.d.cts.map +1 -0
  81. package/dist/utils/testing/tools.d.ts +21 -0
  82. package/dist/utils/testing/tools.d.ts.map +1 -0
  83. package/dist/utils/testing/tools.js +21 -0
  84. package/dist/utils/testing/tools.js.map +1 -0
  85. package/dist/utils/testing/tracers.cjs +25 -0
  86. package/dist/utils/testing/tracers.cjs.map +1 -0
  87. package/dist/utils/testing/tracers.d.cts +15 -0
  88. package/dist/utils/testing/tracers.d.cts.map +1 -0
  89. package/dist/utils/testing/tracers.d.ts +15 -0
  90. package/dist/utils/testing/tracers.d.ts.map +1 -0
  91. package/dist/utils/testing/tracers.js +25 -0
  92. package/dist/utils/testing/tracers.js.map +1 -0
  93. package/dist/utils/testing/vectorstores.cjs +129 -0
  94. package/dist/utils/testing/vectorstores.cjs.map +1 -0
  95. package/dist/utils/testing/vectorstores.d.cts +101 -0
  96. package/dist/utils/testing/vectorstores.d.cts.map +1 -0
  97. package/dist/utils/testing/vectorstores.d.ts +101 -0
  98. package/dist/utils/testing/vectorstores.d.ts.map +1 -0
  99. package/dist/utils/testing/vectorstores.js +129 -0
  100. package/dist/utils/testing/vectorstores.js.map +1 -0
  101. package/package.json +1 -1
  102. package/dist/utils/testing/index.d.cts.map +0 -1
  103. package/dist/utils/testing/index.d.ts.map +0 -1
@@ -1,666 +1,53 @@
1
1
  const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
- const require_ai = require('../../messages/ai.cjs');
3
- const require_human = require('../../messages/human.cjs');
4
- const require_tracers_base = require('../../tracers/base.cjs');
5
- const require_outputs = require('../../outputs.cjs');
6
- const require_utils_json_schema = require('../json_schema.cjs');
7
- const require_base = require('../../runnables/base.cjs');
8
- require('../../messages/index.cjs');
9
- const require_chat_history = require('../../chat_history.cjs');
10
- const require_embeddings = require('../../embeddings.cjs');
11
- const require_retrievers_index = require('../../retrievers/index.cjs');
12
- const require_vectorstores = require('../../vectorstores.cjs');
13
- const require_document = require('../../documents/document.cjs');
14
- const require_language_models_chat_models = require('../../language_models/chat_models.cjs');
15
- const require_language_models_llms = require('../../language_models/llms.cjs');
16
- const require_base$1 = require('../../output_parsers/base.cjs');
17
- const require_tools_index = require('../../tools/index.cjs');
18
- const require_similarities = require('../ml-distance/similarities.cjs');
2
+ const require_chat_models = require('./chat_models.cjs');
3
+ const require_embeddings = require('./embeddings.cjs');
4
+ const require_llms = require('./llms.cjs');
5
+ const require_message_history = require('./message_history.cjs');
6
+ const require_output_parsers = require('./output_parsers.cjs');
7
+ const require_retrievers = require('./retrievers.cjs');
8
+ const require_runnables = require('./runnables.cjs');
9
+ const require_tools = require('./tools.cjs');
10
+ const require_tracers = require('./tracers.cjs');
11
+ const require_vectorstores = require('./vectorstores.cjs');
19
12
 
20
13
  //#region src/utils/testing/index.ts
21
14
  var testing_exports = {};
22
15
  require_rolldown_runtime.__export(testing_exports, {
23
- FakeChatMessageHistory: () => FakeChatMessageHistory,
24
- FakeChatModel: () => FakeChatModel,
25
- FakeEmbeddings: () => FakeEmbeddings,
26
- FakeLLM: () => FakeLLM,
27
- FakeListChatMessageHistory: () => FakeListChatMessageHistory,
28
- FakeListChatModel: () => FakeListChatModel,
29
- FakeRetriever: () => FakeRetriever,
30
- FakeRunnable: () => FakeRunnable,
31
- FakeSplitIntoListParser: () => FakeSplitIntoListParser,
32
- FakeStreamingChatModel: () => FakeStreamingChatModel,
33
- FakeStreamingLLM: () => FakeStreamingLLM,
34
- FakeTool: () => FakeTool,
35
- FakeTracer: () => FakeTracer,
36
- FakeVectorStore: () => FakeVectorStore,
37
- SingleRunExtractor: () => SingleRunExtractor,
38
- SyntheticEmbeddings: () => SyntheticEmbeddings
16
+ FakeChatMessageHistory: () => require_message_history.FakeChatMessageHistory,
17
+ FakeChatModel: () => require_chat_models.FakeChatModel,
18
+ FakeEmbeddings: () => require_embeddings.FakeEmbeddings,
19
+ FakeLLM: () => require_llms.FakeLLM,
20
+ FakeListChatMessageHistory: () => require_message_history.FakeListChatMessageHistory,
21
+ FakeListChatModel: () => require_chat_models.FakeListChatModel,
22
+ FakeRetriever: () => require_retrievers.FakeRetriever,
23
+ FakeRunnable: () => require_runnables.FakeRunnable,
24
+ FakeSplitIntoListParser: () => require_output_parsers.FakeSplitIntoListParser,
25
+ FakeStreamingChatModel: () => require_chat_models.FakeStreamingChatModel,
26
+ FakeStreamingLLM: () => require_llms.FakeStreamingLLM,
27
+ FakeTool: () => require_tools.FakeTool,
28
+ FakeTracer: () => require_message_history.FakeTracer,
29
+ FakeVectorStore: () => require_vectorstores.FakeVectorStore,
30
+ SingleRunExtractor: () => require_tracers.SingleRunExtractor,
31
+ SyntheticEmbeddings: () => require_embeddings.SyntheticEmbeddings
39
32
  });
40
- /**
41
- * Parser for comma-separated values. It splits the input text by commas
42
- * and trims the resulting values.
43
- */
44
- var FakeSplitIntoListParser = class extends require_base$1.BaseOutputParser {
45
- lc_namespace = ["tests", "fake"];
46
- getFormatInstructions() {
47
- return "";
48
- }
49
- async parse(text) {
50
- return text.split(",").map((value) => value.trim());
51
- }
52
- };
53
- var FakeRunnable = class extends require_base.Runnable {
54
- lc_namespace = ["tests", "fake"];
55
- returnOptions;
56
- constructor(fields) {
57
- super(fields);
58
- this.returnOptions = fields.returnOptions;
59
- }
60
- async invoke(input, options) {
61
- if (this.returnOptions) return options ?? {};
62
- return { input };
63
- }
64
- };
65
- var FakeLLM = class extends require_language_models_llms.LLM {
66
- response;
67
- thrownErrorString;
68
- constructor(fields) {
69
- super(fields);
70
- this.response = fields.response;
71
- this.thrownErrorString = fields.thrownErrorString;
72
- }
73
- _llmType() {
74
- return "fake";
75
- }
76
- async _call(prompt, _options, runManager) {
77
- if (this.thrownErrorString) throw new Error(this.thrownErrorString);
78
- const response = this.response ?? prompt;
79
- await runManager?.handleLLMNewToken(response);
80
- return response;
81
- }
82
- };
83
- var FakeStreamingLLM = class extends require_language_models_llms.LLM {
84
- sleep = 50;
85
- responses;
86
- thrownErrorString;
87
- constructor(fields) {
88
- super(fields);
89
- this.sleep = fields.sleep ?? this.sleep;
90
- this.responses = fields.responses;
91
- this.thrownErrorString = fields.thrownErrorString;
92
- }
93
- _llmType() {
94
- return "fake";
95
- }
96
- async _call(prompt) {
97
- if (this.thrownErrorString) throw new Error(this.thrownErrorString);
98
- const response = this.responses?.[0];
99
- this.responses = this.responses?.slice(1);
100
- return response ?? prompt;
101
- }
102
- async *_streamResponseChunks(input, _options, runManager) {
103
- if (this.thrownErrorString) throw new Error(this.thrownErrorString);
104
- const response = this.responses?.[0];
105
- this.responses = this.responses?.slice(1);
106
- for (const c of response ?? input) {
107
- await new Promise((resolve) => setTimeout(resolve, this.sleep));
108
- yield {
109
- text: c,
110
- generationInfo: {}
111
- };
112
- await runManager?.handleLLMNewToken(c);
113
- }
114
- }
115
- };
116
- var FakeChatModel = class extends require_language_models_chat_models.BaseChatModel {
117
- _combineLLMOutput() {
118
- return [];
119
- }
120
- _llmType() {
121
- return "fake";
122
- }
123
- async _generate(messages, options, runManager) {
124
- if (options?.stop?.length) return { generations: [{
125
- message: new require_ai.AIMessage(options.stop[0]),
126
- text: options.stop[0]
127
- }] };
128
- const text = messages.map((m) => {
129
- if (typeof m.content === "string") return m.content;
130
- return JSON.stringify(m.content, null, 2);
131
- }).join("\n");
132
- await runManager?.handleLLMNewToken(text);
133
- return {
134
- generations: [{
135
- message: new require_ai.AIMessage(text),
136
- text
137
- }],
138
- llmOutput: {}
139
- };
140
- }
141
- };
142
- var FakeStreamingChatModel = class FakeStreamingChatModel extends require_language_models_chat_models.BaseChatModel {
143
- sleep = 50;
144
- responses = [];
145
- chunks = [];
146
- toolStyle = "openai";
147
- thrownErrorString;
148
- tools = [];
149
- constructor({ sleep = 50, responses = [], chunks = [], toolStyle = "openai", thrownErrorString,...rest }) {
150
- super(rest);
151
- this.sleep = sleep;
152
- this.responses = responses;
153
- this.chunks = chunks;
154
- this.toolStyle = toolStyle;
155
- this.thrownErrorString = thrownErrorString;
156
- }
157
- _llmType() {
158
- return "fake";
159
- }
160
- bindTools(tools) {
161
- const merged = [...this.tools, ...tools];
162
- const toolDicts = merged.map((t) => {
163
- switch (this.toolStyle) {
164
- case "openai": return {
165
- type: "function",
166
- function: {
167
- name: t.name,
168
- description: t.description,
169
- parameters: require_utils_json_schema.toJsonSchema(t.schema)
170
- }
171
- };
172
- case "anthropic": return {
173
- name: t.name,
174
- description: t.description,
175
- input_schema: require_utils_json_schema.toJsonSchema(t.schema)
176
- };
177
- case "bedrock": return { toolSpec: {
178
- name: t.name,
179
- description: t.description,
180
- inputSchema: require_utils_json_schema.toJsonSchema(t.schema)
181
- } };
182
- case "google": return {
183
- name: t.name,
184
- description: t.description,
185
- parameters: require_utils_json_schema.toJsonSchema(t.schema)
186
- };
187
- default: throw new Error(`Unsupported tool style: ${this.toolStyle}`);
188
- }
189
- });
190
- const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts;
191
- const next = new FakeStreamingChatModel({
192
- sleep: this.sleep,
193
- responses: this.responses,
194
- chunks: this.chunks,
195
- toolStyle: this.toolStyle,
196
- thrownErrorString: this.thrownErrorString
197
- });
198
- next.tools = merged;
199
- return next.withConfig({ tools: wrapped });
200
- }
201
- async _generate(messages, _options, _runManager) {
202
- if (this.thrownErrorString) throw new Error(this.thrownErrorString);
203
- const content = this.responses?.[0]?.content ?? messages[0].content ?? "";
204
- const generation = { generations: [{
205
- text: "",
206
- message: new require_ai.AIMessage({
207
- content,
208
- tool_calls: this.chunks?.[0]?.tool_calls
209
- })
210
- }] };
211
- return generation;
212
- }
213
- async *_streamResponseChunks(_messages, _options, runManager) {
214
- if (this.thrownErrorString) throw new Error(this.thrownErrorString);
215
- if (this.chunks?.length) {
216
- for (const msgChunk of this.chunks) {
217
- const cg = new require_outputs.ChatGenerationChunk({
218
- message: new require_ai.AIMessageChunk({
219
- content: msgChunk.content,
220
- tool_calls: msgChunk.tool_calls,
221
- additional_kwargs: msgChunk.additional_kwargs ?? {}
222
- }),
223
- text: msgChunk.content?.toString() ?? ""
224
- });
225
- yield cg;
226
- await runManager?.handleLLMNewToken(msgChunk.content, void 0, void 0, void 0, void 0, { chunk: cg });
227
- }
228
- return;
229
- }
230
- const fallback = this.responses?.[0] ?? new require_ai.AIMessage(typeof _messages[0].content === "string" ? _messages[0].content : "");
231
- const text = typeof fallback.content === "string" ? fallback.content : "";
232
- for (const ch of text) {
233
- await new Promise((r) => setTimeout(r, this.sleep));
234
- const cg = new require_outputs.ChatGenerationChunk({
235
- message: new require_ai.AIMessageChunk({ content: ch }),
236
- text: ch
237
- });
238
- yield cg;
239
- await runManager?.handleLLMNewToken(ch, void 0, void 0, void 0, void 0, { chunk: cg });
240
- }
241
- }
242
- };
243
- var FakeRetriever = class extends require_retrievers_index.BaseRetriever {
244
- lc_namespace = ["test", "fake"];
245
- output = [new require_document.Document({ pageContent: "foo" }), new require_document.Document({ pageContent: "bar" })];
246
- constructor(fields) {
247
- super();
248
- this.output = fields?.output ?? this.output;
249
- }
250
- async _getRelevantDocuments(_query) {
251
- return this.output;
252
- }
253
- };
254
- /**
255
- * A fake Chat Model that returns a predefined list of responses. It can be used
256
- * for testing purposes.
257
- * @example
258
- * ```typescript
259
- * const chat = new FakeListChatModel({
260
- * responses: ["I'll callback later.", "You 'console' them!"]
261
- * });
262
- *
263
- * const firstMessage = new HumanMessage("You want to hear a JavaScript joke?");
264
- * const secondMessage = new HumanMessage("How do you cheer up a JavaScript developer?");
265
- *
266
- * // Call the chat model with a message and log the response
267
- * const firstResponse = await chat.call([firstMessage]);
268
- * console.log({ firstResponse });
269
- *
270
- * const secondResponse = await chat.call([secondMessage]);
271
- * console.log({ secondResponse });
272
- * ```
273
- */
274
- var FakeListChatModel = class extends require_language_models_chat_models.BaseChatModel {
275
- static lc_name() {
276
- return "FakeListChatModel";
277
- }
278
- lc_serializable = true;
279
- responses;
280
- i = 0;
281
- sleep;
282
- emitCustomEvent = false;
283
- constructor(params) {
284
- super(params);
285
- const { responses, sleep, emitCustomEvent } = params;
286
- this.responses = responses;
287
- this.sleep = sleep;
288
- this.emitCustomEvent = emitCustomEvent ?? this.emitCustomEvent;
289
- }
290
- _combineLLMOutput() {
291
- return [];
292
- }
293
- _llmType() {
294
- return "fake-list";
295
- }
296
- async _generate(_messages, options, runManager) {
297
- await this._sleepIfRequested();
298
- if (options?.thrownErrorString) throw new Error(options.thrownErrorString);
299
- if (this.emitCustomEvent) await runManager?.handleCustomEvent("some_test_event", { someval: true });
300
- if (options?.stop?.length) return { generations: [this._formatGeneration(options.stop[0])] };
301
- else {
302
- const response = this._currentResponse();
303
- this._incrementResponse();
304
- return {
305
- generations: [this._formatGeneration(response)],
306
- llmOutput: {}
307
- };
308
- }
309
- }
310
- _formatGeneration(text) {
311
- return {
312
- message: new require_ai.AIMessage(text),
313
- text
314
- };
315
- }
316
- async *_streamResponseChunks(_messages, options, runManager) {
317
- const response = this._currentResponse();
318
- this._incrementResponse();
319
- if (this.emitCustomEvent) await runManager?.handleCustomEvent("some_test_event", { someval: true });
320
- for await (const text of response) {
321
- await this._sleepIfRequested();
322
- if (options?.thrownErrorString) throw new Error(options.thrownErrorString);
323
- const chunk = this._createResponseChunk(text);
324
- yield chunk;
325
- runManager?.handleLLMNewToken(text);
326
- }
327
- }
328
- async _sleepIfRequested() {
329
- if (this.sleep !== void 0) await this._sleep();
330
- }
331
- async _sleep() {
332
- return new Promise((resolve) => {
333
- setTimeout(() => resolve(), this.sleep);
334
- });
335
- }
336
- _createResponseChunk(text) {
337
- return new require_outputs.ChatGenerationChunk({
338
- message: new require_ai.AIMessageChunk({ content: text }),
339
- text
340
- });
341
- }
342
- _currentResponse() {
343
- return this.responses[this.i];
344
- }
345
- _incrementResponse() {
346
- if (this.i < this.responses.length - 1) this.i += 1;
347
- else this.i = 0;
348
- }
349
- withStructuredOutput(_params, _config) {
350
- return require_base.RunnableLambda.from(async (input) => {
351
- const message = await this.invoke(input);
352
- if (message.tool_calls?.[0]?.args) return message.tool_calls[0].args;
353
- if (typeof message.content === "string") return JSON.parse(message.content);
354
- throw new Error("No structured output found");
355
- });
356
- }
357
- };
358
- var FakeChatMessageHistory = class extends require_chat_history.BaseChatMessageHistory {
359
- lc_namespace = [
360
- "langchain_core",
361
- "message",
362
- "fake"
363
- ];
364
- messages = [];
365
- constructor() {
366
- super();
367
- }
368
- async getMessages() {
369
- return this.messages;
370
- }
371
- async addMessage(message) {
372
- this.messages.push(message);
373
- }
374
- async addUserMessage(message) {
375
- this.messages.push(new require_human.HumanMessage(message));
376
- }
377
- async addAIChatMessage(message) {
378
- this.messages.push(new require_ai.AIMessage(message));
379
- }
380
- async clear() {
381
- this.messages = [];
382
- }
383
- };
384
- var FakeListChatMessageHistory = class extends require_chat_history.BaseListChatMessageHistory {
385
- lc_namespace = [
386
- "langchain_core",
387
- "message",
388
- "fake"
389
- ];
390
- messages = [];
391
- constructor() {
392
- super();
393
- }
394
- async addMessage(message) {
395
- this.messages.push(message);
396
- }
397
- async getMessages() {
398
- return this.messages;
399
- }
400
- };
401
- var FakeTracer = class extends require_tracers_base.BaseTracer {
402
- name = "fake_tracer";
403
- runs = [];
404
- constructor() {
405
- super();
406
- }
407
- persistRun(run) {
408
- this.runs.push(run);
409
- return Promise.resolve();
410
- }
411
- };
412
- var FakeTool = class extends require_tools_index.StructuredTool {
413
- name;
414
- description;
415
- schema;
416
- constructor(fields) {
417
- super(fields);
418
- this.name = fields.name;
419
- this.description = fields.description;
420
- this.schema = fields.schema;
421
- }
422
- async _call(arg, _runManager) {
423
- return JSON.stringify(arg);
424
- }
425
- };
426
- /**
427
- * A class that provides fake embeddings by overriding the embedDocuments
428
- * and embedQuery methods to return fixed values.
429
- */
430
- var FakeEmbeddings = class extends require_embeddings.Embeddings {
431
- constructor(params) {
432
- super(params ?? {});
433
- }
434
- /**
435
- * Generates fixed embeddings for a list of documents.
436
- * @param documents List of documents to generate embeddings for.
437
- * @returns A promise that resolves with a list of fixed embeddings for each document.
438
- */
439
- embedDocuments(documents) {
440
- return Promise.resolve(documents.map(() => [
441
- .1,
442
- .2,
443
- .3,
444
- .4
445
- ]));
446
- }
447
- /**
448
- * Generates a fixed embedding for a query.
449
- * @param _ The query to generate an embedding for.
450
- * @returns A promise that resolves with a fixed embedding for the query.
451
- */
452
- embedQuery(_) {
453
- return Promise.resolve([
454
- .1,
455
- .2,
456
- .3,
457
- .4
458
- ]);
459
- }
460
- };
461
- /**
462
- * A class that provides synthetic embeddings by overriding the
463
- * embedDocuments and embedQuery methods to generate embeddings based on
464
- * the input documents. The embeddings are generated by converting each
465
- * document into chunks, calculating a numerical value for each chunk, and
466
- * returning an array of these values as the embedding.
467
- */
468
- var SyntheticEmbeddings = class extends require_embeddings.Embeddings {
469
- vectorSize;
470
- constructor(params) {
471
- super(params ?? {});
472
- this.vectorSize = params?.vectorSize ?? 4;
473
- }
474
- /**
475
- * Generates synthetic embeddings for a list of documents.
476
- * @param documents List of documents to generate embeddings for.
477
- * @returns A promise that resolves with a list of synthetic embeddings for each document.
478
- */
479
- async embedDocuments(documents) {
480
- return Promise.all(documents.map((doc) => this.embedQuery(doc)));
481
- }
482
- /**
483
- * Generates a synthetic embedding for a document. The document is
484
- * converted into chunks, a numerical value is calculated for each chunk,
485
- * and an array of these values is returned as the embedding.
486
- * @param document The document to generate an embedding for.
487
- * @returns A promise that resolves with a synthetic embedding for the document.
488
- */
489
- async embedQuery(document) {
490
- let doc = document;
491
- doc = doc.toLowerCase().replaceAll(/[^a-z ]/g, "");
492
- const padMod = doc.length % this.vectorSize;
493
- const padGapSize = padMod === 0 ? 0 : this.vectorSize - padMod;
494
- const padSize = doc.length + padGapSize;
495
- doc = doc.padEnd(padSize, " ");
496
- const chunkSize = doc.length / this.vectorSize;
497
- const docChunk = [];
498
- for (let co = 0; co < doc.length; co += chunkSize) docChunk.push(doc.slice(co, co + chunkSize));
499
- const ret = docChunk.map((s) => {
500
- let sum = 0;
501
- for (let co = 0; co < s.length; co += 1) sum += s === " " ? 0 : s.charCodeAt(co);
502
- const ret$1 = sum % 26 / 26;
503
- return ret$1;
504
- });
505
- return ret;
506
- }
507
- };
508
- var SingleRunExtractor = class extends require_tracers_base.BaseTracer {
509
- runPromiseResolver;
510
- runPromise;
511
- /** The name of the callback handler. */
512
- name = "single_run_extractor";
513
- constructor() {
514
- super();
515
- this.runPromise = new Promise((extract) => {
516
- this.runPromiseResolver = extract;
517
- });
518
- }
519
- async persistRun(run) {
520
- this.runPromiseResolver(run);
521
- }
522
- async extract() {
523
- return this.runPromise;
524
- }
525
- };
526
- /**
527
- * Class that extends `VectorStore` to store vectors in memory. Provides
528
- * methods for adding documents, performing similarity searches, and
529
- * creating instances from texts, documents, or an existing index.
530
- */
531
- var FakeVectorStore = class FakeVectorStore extends require_vectorstores.VectorStore {
532
- memoryVectors = [];
533
- similarity;
534
- _vectorstoreType() {
535
- return "memory";
536
- }
537
- constructor(embeddings, { similarity,...rest } = {}) {
538
- super(embeddings, rest);
539
- this.similarity = similarity ?? require_similarities.cosine;
540
- }
541
- /**
542
- * Method to add documents to the memory vector store. It extracts the
543
- * text from each document, generates embeddings for them, and adds the
544
- * resulting vectors to the store.
545
- * @param documents Array of `Document` instances to be added to the store.
546
- * @returns Promise that resolves when all documents have been added.
547
- */
548
- async addDocuments(documents) {
549
- const texts = documents.map(({ pageContent }) => pageContent);
550
- return this.addVectors(await this.embeddings.embedDocuments(texts), documents);
551
- }
552
- /**
553
- * Method to add vectors to the memory vector store. It creates
554
- * `MemoryVector` instances for each vector and document pair and adds
555
- * them to the store.
556
- * @param vectors Array of vectors to be added to the store.
557
- * @param documents Array of `Document` instances corresponding to the vectors.
558
- * @returns Promise that resolves when all vectors have been added.
559
- */
560
- async addVectors(vectors, documents) {
561
- const memoryVectors = vectors.map((embedding, idx) => ({
562
- content: documents[idx].pageContent,
563
- embedding,
564
- metadata: documents[idx].metadata
565
- }));
566
- this.memoryVectors = this.memoryVectors.concat(memoryVectors);
567
- }
568
- /**
569
- * Method to perform a similarity search in the memory vector store. It
570
- * calculates the similarity between the query vector and each vector in
571
- * the store, sorts the results by similarity, and returns the top `k`
572
- * results along with their scores.
573
- * @param query Query vector to compare against the vectors in the store.
574
- * @param k Number of top results to return.
575
- * @param filter Optional filter function to apply to the vectors before performing the search.
576
- * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score.
577
- */
578
- async similaritySearchVectorWithScore(query, k, filter) {
579
- const filterFunction = (memoryVector) => {
580
- if (!filter) return true;
581
- const doc = new require_document.Document({
582
- metadata: memoryVector.metadata,
583
- pageContent: memoryVector.content
584
- });
585
- return filter(doc);
586
- };
587
- const filteredMemoryVectors = this.memoryVectors.filter(filterFunction);
588
- const searches = filteredMemoryVectors.map((vector, index) => ({
589
- similarity: this.similarity(query, vector.embedding),
590
- index
591
- })).sort((a, b) => a.similarity > b.similarity ? -1 : 0).slice(0, k);
592
- const result = searches.map((search) => [new require_document.Document({
593
- metadata: filteredMemoryVectors[search.index].metadata,
594
- pageContent: filteredMemoryVectors[search.index].content
595
- }), search.similarity]);
596
- return result;
597
- }
598
- /**
599
- * Static method to create a `FakeVectorStore` instance from an array of
600
- * texts. It creates a `Document` for each text and metadata pair, and
601
- * adds them to the store.
602
- * @param texts Array of texts to be added to the store.
603
- * @param metadatas Array or single object of metadata corresponding to the texts.
604
- * @param embeddings `Embeddings` instance used to generate embeddings for the texts.
605
- * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance.
606
- * @returns Promise that resolves with a new `FakeVectorStore` instance.
607
- */
608
- static async fromTexts(texts, metadatas, embeddings, dbConfig) {
609
- const docs = [];
610
- for (let i = 0; i < texts.length; i += 1) {
611
- const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
612
- const newDoc = new require_document.Document({
613
- pageContent: texts[i],
614
- metadata
615
- });
616
- docs.push(newDoc);
617
- }
618
- return FakeVectorStore.fromDocuments(docs, embeddings, dbConfig);
619
- }
620
- /**
621
- * Static method to create a `FakeVectorStore` instance from an array of
622
- * `Document` instances. It adds the documents to the store.
623
- * @param docs Array of `Document` instances to be added to the store.
624
- * @param embeddings `Embeddings` instance used to generate embeddings for the documents.
625
- * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance.
626
- * @returns Promise that resolves with a new `FakeVectorStore` instance.
627
- */
628
- static async fromDocuments(docs, embeddings, dbConfig) {
629
- const instance = new this(embeddings, dbConfig);
630
- await instance.addDocuments(docs);
631
- return instance;
632
- }
633
- /**
634
- * Static method to create a `FakeVectorStore` instance from an existing
635
- * index. It creates a new `FakeVectorStore` instance without adding any
636
- * documents or vectors.
637
- * @param embeddings `Embeddings` instance used to generate embeddings for the documents.
638
- * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance.
639
- * @returns Promise that resolves with a new `FakeVectorStore` instance.
640
- */
641
- static async fromExistingIndex(embeddings, dbConfig) {
642
- const instance = new this(embeddings, dbConfig);
643
- return instance;
644
- }
645
- };
646
33
 
647
34
  //#endregion
648
- exports.FakeChatMessageHistory = FakeChatMessageHistory;
649
- exports.FakeChatModel = FakeChatModel;
650
- exports.FakeEmbeddings = FakeEmbeddings;
651
- exports.FakeLLM = FakeLLM;
652
- exports.FakeListChatMessageHistory = FakeListChatMessageHistory;
653
- exports.FakeListChatModel = FakeListChatModel;
654
- exports.FakeRetriever = FakeRetriever;
655
- exports.FakeRunnable = FakeRunnable;
656
- exports.FakeSplitIntoListParser = FakeSplitIntoListParser;
657
- exports.FakeStreamingChatModel = FakeStreamingChatModel;
658
- exports.FakeStreamingLLM = FakeStreamingLLM;
659
- exports.FakeTool = FakeTool;
660
- exports.FakeTracer = FakeTracer;
661
- exports.FakeVectorStore = FakeVectorStore;
662
- exports.SingleRunExtractor = SingleRunExtractor;
663
- exports.SyntheticEmbeddings = SyntheticEmbeddings;
35
+ exports.FakeChatMessageHistory = require_message_history.FakeChatMessageHistory;
36
+ exports.FakeChatModel = require_chat_models.FakeChatModel;
37
+ exports.FakeEmbeddings = require_embeddings.FakeEmbeddings;
38
+ exports.FakeLLM = require_llms.FakeLLM;
39
+ exports.FakeListChatMessageHistory = require_message_history.FakeListChatMessageHistory;
40
+ exports.FakeListChatModel = require_chat_models.FakeListChatModel;
41
+ exports.FakeRetriever = require_retrievers.FakeRetriever;
42
+ exports.FakeRunnable = require_runnables.FakeRunnable;
43
+ exports.FakeSplitIntoListParser = require_output_parsers.FakeSplitIntoListParser;
44
+ exports.FakeStreamingChatModel = require_chat_models.FakeStreamingChatModel;
45
+ exports.FakeStreamingLLM = require_llms.FakeStreamingLLM;
46
+ exports.FakeTool = require_tools.FakeTool;
47
+ exports.FakeTracer = require_message_history.FakeTracer;
48
+ exports.FakeVectorStore = require_vectorstores.FakeVectorStore;
49
+ exports.SingleRunExtractor = require_tracers.SingleRunExtractor;
50
+ exports.SyntheticEmbeddings = require_embeddings.SyntheticEmbeddings;
664
51
  Object.defineProperty(exports, 'testing_exports', {
665
52
  enumerable: true,
666
53
  get: function () {