@langchain/core 0.2.0 → 0.2.1

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 (113) hide show
  1. package/dist/callbacks/tests/callbacks.test.d.ts +1 -0
  2. package/dist/callbacks/tests/callbacks.test.js +492 -0
  3. package/dist/callbacks/tests/manager.int.test.d.ts +1 -0
  4. package/dist/callbacks/tests/manager.int.test.js +29 -0
  5. package/dist/callbacks/tests/run_collector.test.d.ts +1 -0
  6. package/dist/callbacks/tests/run_collector.test.js +58 -0
  7. package/dist/chat_history.cjs +13 -0
  8. package/dist/chat_history.d.ts +9 -0
  9. package/dist/chat_history.js +13 -0
  10. package/dist/language_models/chat_models.d.ts +2 -2
  11. package/dist/language_models/tests/chat_models.test.d.ts +1 -0
  12. package/dist/language_models/tests/chat_models.test.js +154 -0
  13. package/dist/language_models/tests/count_tokens.test.d.ts +1 -0
  14. package/dist/language_models/tests/count_tokens.test.js +19 -0
  15. package/dist/language_models/tests/llms.test.d.ts +1 -0
  16. package/dist/language_models/tests/llms.test.js +39 -0
  17. package/dist/messages/tests/base_message.test.d.ts +1 -0
  18. package/dist/messages/tests/base_message.test.js +97 -0
  19. package/dist/output_parsers/openai_tools/tests/json_output_tools_parser.test.d.ts +1 -0
  20. package/dist/output_parsers/openai_tools/tests/json_output_tools_parser.test.js +81 -0
  21. package/dist/output_parsers/tests/json.test.d.ts +1 -0
  22. package/dist/output_parsers/tests/json.test.js +427 -0
  23. package/dist/output_parsers/tests/output_parser.test.d.ts +1 -0
  24. package/dist/output_parsers/tests/output_parser.test.js +78 -0
  25. package/dist/output_parsers/tests/string.test.d.ts +1 -0
  26. package/dist/output_parsers/tests/string.test.js +68 -0
  27. package/dist/output_parsers/tests/structured.test.d.ts +1 -0
  28. package/dist/output_parsers/tests/structured.test.js +166 -0
  29. package/dist/output_parsers/tests/xml.test.d.ts +1 -0
  30. package/dist/output_parsers/tests/xml.test.js +81 -0
  31. package/dist/prompts/tests/chat.mustache.test.d.ts +1 -0
  32. package/dist/prompts/tests/chat.mustache.test.js +61 -0
  33. package/dist/prompts/tests/chat.test.d.ts +1 -0
  34. package/dist/prompts/tests/chat.test.js +507 -0
  35. package/dist/prompts/tests/few_shot.test.d.ts +1 -0
  36. package/dist/prompts/tests/few_shot.test.js +224 -0
  37. package/dist/prompts/tests/pipeline.test.d.ts +1 -0
  38. package/dist/prompts/tests/pipeline.test.js +101 -0
  39. package/dist/prompts/tests/prompt.mustache.test.d.ts +1 -0
  40. package/dist/prompts/tests/prompt.mustache.test.js +85 -0
  41. package/dist/prompts/tests/prompt.test.d.ts +1 -0
  42. package/dist/prompts/tests/prompt.test.js +78 -0
  43. package/dist/prompts/tests/structured.test.d.ts +1 -0
  44. package/dist/prompts/tests/structured.test.js +37 -0
  45. package/dist/prompts/tests/template.test.d.ts +1 -0
  46. package/dist/prompts/tests/template.test.js +24 -0
  47. package/dist/runnables/base.cjs +87 -6
  48. package/dist/runnables/base.d.ts +45 -26
  49. package/dist/runnables/base.js +87 -6
  50. package/dist/runnables/history.cjs +87 -32
  51. package/dist/runnables/history.d.ts +1 -1
  52. package/dist/runnables/history.js +87 -32
  53. package/dist/runnables/remote.cjs +2 -2
  54. package/dist/runnables/remote.d.ts +3 -3
  55. package/dist/runnables/remote.js +2 -2
  56. package/dist/runnables/tests/runnable.test.d.ts +1 -0
  57. package/dist/runnables/tests/runnable.test.js +491 -0
  58. package/dist/runnables/tests/runnable_binding.test.d.ts +1 -0
  59. package/dist/runnables/tests/runnable_binding.test.js +46 -0
  60. package/dist/runnables/tests/runnable_branch.test.d.ts +1 -0
  61. package/dist/runnables/tests/runnable_branch.test.js +116 -0
  62. package/dist/runnables/tests/runnable_graph.test.d.ts +1 -0
  63. package/dist/runnables/tests/runnable_graph.test.js +84 -0
  64. package/dist/runnables/tests/runnable_history.test.d.ts +1 -0
  65. package/dist/runnables/tests/runnable_history.test.js +177 -0
  66. package/dist/runnables/tests/runnable_interface.test.d.ts +1 -0
  67. package/dist/runnables/tests/runnable_interface.test.js +209 -0
  68. package/dist/runnables/tests/runnable_map.test.d.ts +1 -0
  69. package/dist/runnables/tests/runnable_map.test.js +238 -0
  70. package/dist/runnables/tests/runnable_passthrough.test.d.ts +1 -0
  71. package/dist/runnables/tests/runnable_passthrough.test.js +96 -0
  72. package/dist/runnables/tests/runnable_remote.int.test.d.ts +1 -0
  73. package/dist/runnables/tests/runnable_remote.int.test.js +138 -0
  74. package/dist/runnables/tests/runnable_remote.test.d.ts +1 -0
  75. package/dist/runnables/tests/runnable_remote.test.js +200 -0
  76. package/dist/runnables/tests/runnable_retry.test.d.ts +1 -0
  77. package/dist/runnables/tests/runnable_retry.test.js +125 -0
  78. package/dist/runnables/tests/runnable_stream_events.test.d.ts +1 -0
  79. package/dist/runnables/tests/runnable_stream_events.test.js +1013 -0
  80. package/dist/runnables/tests/runnable_stream_events_v2.test.d.ts +1 -0
  81. package/dist/runnables/tests/runnable_stream_events_v2.test.js +973 -0
  82. package/dist/runnables/tests/runnable_stream_log.test.d.ts +1 -0
  83. package/dist/runnables/tests/runnable_stream_log.test.js +282 -0
  84. package/dist/runnables/tests/runnable_tracing.int.test.d.ts +1 -0
  85. package/dist/runnables/tests/runnable_tracing.int.test.js +37 -0
  86. package/dist/runnables/tests/runnable_with_fallbacks.test.d.ts +1 -0
  87. package/dist/runnables/tests/runnable_with_fallbacks.test.js +36 -0
  88. package/dist/runnables/utils.d.ts +1 -1
  89. package/dist/singletons/tests/async_local_storage.test.d.ts +1 -0
  90. package/dist/singletons/tests/async_local_storage.test.js +120 -0
  91. package/dist/structured_query/tests/utils.test.d.ts +1 -0
  92. package/dist/structured_query/tests/utils.test.js +47 -0
  93. package/dist/tracers/event_stream.cjs +493 -0
  94. package/dist/tracers/event_stream.d.ts +137 -0
  95. package/dist/tracers/event_stream.js +489 -0
  96. package/dist/tracers/log_stream.d.ts +2 -77
  97. package/dist/tracers/tests/langchain_tracer.int.test.d.ts +1 -0
  98. package/dist/tracers/tests/langchain_tracer.int.test.js +74 -0
  99. package/dist/tracers/tests/tracer.test.d.ts +1 -0
  100. package/dist/tracers/tests/tracer.test.js +378 -0
  101. package/dist/utils/testing/tests/chatfake.test.d.ts +1 -0
  102. package/dist/utils/testing/tests/chatfake.test.js +112 -0
  103. package/dist/utils/tests/async_caller.test.d.ts +1 -0
  104. package/dist/utils/tests/async_caller.test.js +27 -0
  105. package/dist/utils/tests/enviroment.test.d.ts +1 -0
  106. package/dist/utils/tests/enviroment.test.js +6 -0
  107. package/dist/utils/tests/function_calling.test.d.ts +1 -0
  108. package/dist/utils/tests/function_calling.test.js +107 -0
  109. package/dist/utils/tests/math_utils.test.d.ts +1 -0
  110. package/dist/utils/tests/math_utils.test.js +139 -0
  111. package/dist/utils/tests/polyfill_stream.test.d.ts +1 -0
  112. package/dist/utils/tests/polyfill_stream.test.js +15 -0
  113. package/package.json +6 -6
@@ -0,0 +1,493 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EventStreamCallbackHandler = void 0;
4
+ const base_js_1 = require("./base.cjs");
5
+ const stream_js_1 = require("../utils/stream.cjs");
6
+ const ai_js_1 = require("../messages/ai.cjs");
7
+ const outputs_js_1 = require("../outputs.cjs");
8
+ function assignName({ name, serialized, }) {
9
+ if (name !== undefined) {
10
+ return name;
11
+ }
12
+ if (serialized?.name !== undefined) {
13
+ return serialized.name;
14
+ }
15
+ else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {
16
+ return serialized.id[serialized.id.length - 1];
17
+ }
18
+ return "Unnamed";
19
+ }
20
+ /**
21
+ * Class that extends the `BaseTracer` class from the
22
+ * `langchain.callbacks.tracers.base` module. It represents a callback
23
+ * handler that logs the execution of runs and emits `RunLog` instances to a
24
+ * `RunLogStream`.
25
+ */
26
+ class EventStreamCallbackHandler extends base_js_1.BaseTracer {
27
+ constructor(fields) {
28
+ super({ _awaitHandler: true, ...fields });
29
+ Object.defineProperty(this, "autoClose", {
30
+ enumerable: true,
31
+ configurable: true,
32
+ writable: true,
33
+ value: true
34
+ });
35
+ Object.defineProperty(this, "includeNames", {
36
+ enumerable: true,
37
+ configurable: true,
38
+ writable: true,
39
+ value: void 0
40
+ });
41
+ Object.defineProperty(this, "includeTypes", {
42
+ enumerable: true,
43
+ configurable: true,
44
+ writable: true,
45
+ value: void 0
46
+ });
47
+ Object.defineProperty(this, "includeTags", {
48
+ enumerable: true,
49
+ configurable: true,
50
+ writable: true,
51
+ value: void 0
52
+ });
53
+ Object.defineProperty(this, "excludeNames", {
54
+ enumerable: true,
55
+ configurable: true,
56
+ writable: true,
57
+ value: void 0
58
+ });
59
+ Object.defineProperty(this, "excludeTypes", {
60
+ enumerable: true,
61
+ configurable: true,
62
+ writable: true,
63
+ value: void 0
64
+ });
65
+ Object.defineProperty(this, "excludeTags", {
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ value: void 0
70
+ });
71
+ Object.defineProperty(this, "rootId", {
72
+ enumerable: true,
73
+ configurable: true,
74
+ writable: true,
75
+ value: void 0
76
+ });
77
+ Object.defineProperty(this, "runInfoMap", {
78
+ enumerable: true,
79
+ configurable: true,
80
+ writable: true,
81
+ value: new Map()
82
+ });
83
+ Object.defineProperty(this, "tappedPromises", {
84
+ enumerable: true,
85
+ configurable: true,
86
+ writable: true,
87
+ value: new Map()
88
+ });
89
+ Object.defineProperty(this, "transformStream", {
90
+ enumerable: true,
91
+ configurable: true,
92
+ writable: true,
93
+ value: void 0
94
+ });
95
+ Object.defineProperty(this, "writer", {
96
+ enumerable: true,
97
+ configurable: true,
98
+ writable: true,
99
+ value: void 0
100
+ });
101
+ Object.defineProperty(this, "receiveStream", {
102
+ enumerable: true,
103
+ configurable: true,
104
+ writable: true,
105
+ value: void 0
106
+ });
107
+ Object.defineProperty(this, "name", {
108
+ enumerable: true,
109
+ configurable: true,
110
+ writable: true,
111
+ value: "event_stream_tracer"
112
+ });
113
+ this.autoClose = fields?.autoClose ?? true;
114
+ this.includeNames = fields?.includeNames;
115
+ this.includeTypes = fields?.includeTypes;
116
+ this.includeTags = fields?.includeTags;
117
+ this.excludeNames = fields?.excludeNames;
118
+ this.excludeTypes = fields?.excludeTypes;
119
+ this.excludeTags = fields?.excludeTags;
120
+ this.transformStream = new TransformStream();
121
+ this.writer = this.transformStream.writable.getWriter();
122
+ this.receiveStream = stream_js_1.IterableReadableStream.fromReadableStream(this.transformStream.readable);
123
+ }
124
+ [Symbol.asyncIterator]() {
125
+ return this.receiveStream;
126
+ }
127
+ async persistRun(_run) {
128
+ // This is a legacy method only called once for an entire run tree
129
+ // and is therefore not useful here
130
+ }
131
+ _includeRun(run) {
132
+ const runTags = run.tags ?? [];
133
+ let include = this.includeNames === undefined &&
134
+ this.includeTags === undefined &&
135
+ this.includeTypes === undefined;
136
+ if (this.includeNames !== undefined) {
137
+ include = include || this.includeNames.includes(run.name);
138
+ }
139
+ if (this.includeTypes !== undefined) {
140
+ include = include || this.includeTypes.includes(run.runType);
141
+ }
142
+ if (this.includeTags !== undefined) {
143
+ include =
144
+ include ||
145
+ runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;
146
+ }
147
+ if (this.excludeNames !== undefined) {
148
+ include = include && !this.excludeNames.includes(run.name);
149
+ }
150
+ if (this.excludeTypes !== undefined) {
151
+ include = include && !this.excludeTypes.includes(run.runType);
152
+ }
153
+ if (this.excludeTags !== undefined) {
154
+ include =
155
+ include && runTags.every((tag) => !this.excludeTags?.includes(tag));
156
+ }
157
+ return include;
158
+ }
159
+ async *tapOutputIterable(runId, outputStream) {
160
+ const firstChunk = await outputStream.next();
161
+ if (firstChunk.done) {
162
+ return;
163
+ }
164
+ const runInfo = this.runInfoMap.get(runId);
165
+ // run has finished, don't issue any stream events
166
+ if (runInfo === undefined) {
167
+ yield firstChunk.value;
168
+ return;
169
+ }
170
+ let tappedPromise = this.tappedPromises.get(runId);
171
+ // if we are the first to tap, issue stream events
172
+ if (tappedPromise === undefined) {
173
+ let tappedPromiseResolver;
174
+ tappedPromise = new Promise((resolve) => {
175
+ tappedPromiseResolver = resolve;
176
+ });
177
+ this.tappedPromises.set(runId, tappedPromise);
178
+ try {
179
+ const event = {
180
+ event: `on_${runInfo.runType}_stream`,
181
+ run_id: runId,
182
+ name: runInfo.name,
183
+ tags: runInfo.tags,
184
+ metadata: runInfo.metadata,
185
+ data: {},
186
+ };
187
+ await this.send({
188
+ ...event,
189
+ data: { chunk: firstChunk.value },
190
+ }, runInfo);
191
+ yield firstChunk.value;
192
+ for await (const chunk of outputStream) {
193
+ // Don't yield tool and retriever stream events
194
+ if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") {
195
+ await this.send({
196
+ ...event,
197
+ data: {
198
+ chunk,
199
+ },
200
+ }, runInfo);
201
+ }
202
+ yield chunk;
203
+ }
204
+ }
205
+ finally {
206
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
207
+ tappedPromiseResolver();
208
+ }
209
+ }
210
+ else {
211
+ // otherwise just pass through
212
+ yield firstChunk.value;
213
+ for await (const chunk of outputStream) {
214
+ yield chunk;
215
+ }
216
+ }
217
+ }
218
+ async send(payload, run) {
219
+ if (this._includeRun(run)) {
220
+ await this.writer.write(payload);
221
+ }
222
+ }
223
+ async sendEndEvent(payload, run) {
224
+ const tappedPromise = this.tappedPromises.get(payload.run_id);
225
+ if (tappedPromise !== undefined) {
226
+ void tappedPromise.then(() => {
227
+ void this.send(payload, run);
228
+ });
229
+ }
230
+ else {
231
+ await this.send(payload, run);
232
+ }
233
+ }
234
+ async onLLMStart(run) {
235
+ const runName = assignName(run);
236
+ const runType = run.inputs.messages !== undefined ? "chat_model" : "llm";
237
+ const runInfo = {
238
+ tags: run.tags ?? [],
239
+ metadata: run.extra?.metadata ?? {},
240
+ name: runName,
241
+ runType,
242
+ inputs: run.inputs,
243
+ };
244
+ this.runInfoMap.set(run.id, runInfo);
245
+ const eventName = `on_${runType}_start`;
246
+ await this.send({
247
+ event: eventName,
248
+ data: {
249
+ input: run.inputs,
250
+ },
251
+ name: runName,
252
+ tags: run.tags ?? [],
253
+ run_id: run.id,
254
+ metadata: run.extra?.metadata ?? {},
255
+ }, runInfo);
256
+ }
257
+ async onLLMNewToken(run, token,
258
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
259
+ kwargs) {
260
+ const runInfo = this.runInfoMap.get(run.id);
261
+ let chunk;
262
+ let eventName;
263
+ if (runInfo === undefined) {
264
+ throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);
265
+ }
266
+ if (runInfo.runType === "chat_model") {
267
+ eventName = "on_chat_model_stream";
268
+ if (kwargs?.chunk === undefined) {
269
+ chunk = new ai_js_1.AIMessageChunk({ content: token });
270
+ }
271
+ else {
272
+ chunk = kwargs.chunk.message;
273
+ }
274
+ }
275
+ else if (runInfo.runType === "llm") {
276
+ eventName = "on_llm_stream";
277
+ if (kwargs?.chunk === undefined) {
278
+ chunk = new outputs_js_1.GenerationChunk({ text: token });
279
+ }
280
+ else {
281
+ chunk = kwargs.chunk;
282
+ }
283
+ }
284
+ else {
285
+ throw new Error(`Unexpected run type ${runInfo.runType}`);
286
+ }
287
+ await this.send({
288
+ event: eventName,
289
+ data: {
290
+ chunk,
291
+ },
292
+ run_id: run.id,
293
+ name: runInfo.name,
294
+ tags: runInfo.tags,
295
+ metadata: runInfo.metadata,
296
+ }, runInfo);
297
+ }
298
+ async onLLMEnd(run) {
299
+ const runInfo = this.runInfoMap.get(run.id);
300
+ this.runInfoMap.delete(run.id);
301
+ let eventName;
302
+ if (runInfo === undefined) {
303
+ throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);
304
+ }
305
+ const generations = run.outputs?.generations;
306
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
307
+ let output;
308
+ if (runInfo.runType === "chat_model") {
309
+ for (const generation of generations ?? []) {
310
+ if (output !== undefined) {
311
+ break;
312
+ }
313
+ output = generation[0]?.message;
314
+ }
315
+ eventName = "on_chat_model_end";
316
+ }
317
+ else if (runInfo.runType === "llm") {
318
+ output = {
319
+ generations: generations?.map((generation) => {
320
+ return generation.map((chunk) => {
321
+ return {
322
+ text: chunk.text,
323
+ generationInfo: chunk.generationInfo,
324
+ };
325
+ });
326
+ }),
327
+ llmOutput: run.outputs?.llmOutput ?? {},
328
+ };
329
+ eventName = "on_llm_end";
330
+ }
331
+ else {
332
+ throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);
333
+ }
334
+ await this.sendEndEvent({
335
+ event: eventName,
336
+ data: {
337
+ output,
338
+ input: runInfo.inputs,
339
+ },
340
+ run_id: run.id,
341
+ name: runInfo.name,
342
+ tags: runInfo.tags,
343
+ metadata: runInfo.metadata,
344
+ }, runInfo);
345
+ }
346
+ async onChainStart(run) {
347
+ const runName = assignName(run);
348
+ const runType = run.run_type ?? "chain";
349
+ const runInfo = {
350
+ tags: run.tags ?? [],
351
+ metadata: run.extra?.metadata ?? {},
352
+ name: runName,
353
+ runType: run.run_type,
354
+ };
355
+ let eventData = {};
356
+ // Workaround Runnable core code not sending input when transform streaming.
357
+ if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) {
358
+ eventData = {};
359
+ runInfo.inputs = {};
360
+ }
361
+ else if (run.inputs.input !== undefined) {
362
+ eventData.input = run.inputs.input;
363
+ runInfo.inputs = run.inputs.input;
364
+ }
365
+ else {
366
+ eventData.input = run.inputs;
367
+ runInfo.inputs = run.inputs;
368
+ }
369
+ this.runInfoMap.set(run.id, runInfo);
370
+ await this.send({
371
+ event: `on_${runType}_start`,
372
+ data: eventData,
373
+ name: runName,
374
+ tags: run.tags ?? [],
375
+ run_id: run.id,
376
+ metadata: run.extra?.metadata ?? {},
377
+ }, runInfo);
378
+ }
379
+ async onChainEnd(run) {
380
+ const runInfo = this.runInfoMap.get(run.id);
381
+ this.runInfoMap.delete(run.id);
382
+ if (runInfo === undefined) {
383
+ throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);
384
+ }
385
+ const eventName = `on_${run.run_type}_end`;
386
+ const inputs = run.inputs ?? runInfo.inputs ?? {};
387
+ const outputs = run.outputs?.output ?? run.outputs;
388
+ const data = {
389
+ output: outputs,
390
+ input: inputs,
391
+ };
392
+ if (inputs.input && Object.keys(inputs).length === 1) {
393
+ data.input = inputs.input;
394
+ runInfo.inputs = inputs.input;
395
+ }
396
+ await this.sendEndEvent({
397
+ event: eventName,
398
+ data,
399
+ run_id: run.id,
400
+ name: runInfo.name,
401
+ tags: runInfo.tags,
402
+ metadata: runInfo.metadata ?? {},
403
+ }, runInfo);
404
+ }
405
+ async onToolStart(run) {
406
+ const runName = assignName(run);
407
+ const runInfo = {
408
+ tags: run.tags ?? [],
409
+ metadata: run.extra?.metadata ?? {},
410
+ name: runName,
411
+ runType: "tool",
412
+ inputs: run.inputs ?? {},
413
+ };
414
+ this.runInfoMap.set(run.id, runInfo);
415
+ await this.send({
416
+ event: "on_tool_start",
417
+ data: {
418
+ input: run.inputs ?? {},
419
+ },
420
+ name: runName,
421
+ run_id: run.id,
422
+ tags: run.tags ?? [],
423
+ metadata: run.extra?.metadata ?? {},
424
+ }, runInfo);
425
+ }
426
+ async onToolEnd(run) {
427
+ const runInfo = this.runInfoMap.get(run.id);
428
+ this.runInfoMap.delete(run.id);
429
+ if (runInfo === undefined) {
430
+ throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);
431
+ }
432
+ if (runInfo.inputs === undefined) {
433
+ throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`);
434
+ }
435
+ const output = run.outputs?.output === undefined ? run.outputs : run.outputs.output;
436
+ await this.sendEndEvent({
437
+ event: "on_tool_end",
438
+ data: {
439
+ output,
440
+ input: runInfo.inputs,
441
+ },
442
+ run_id: run.id,
443
+ name: runInfo.name,
444
+ tags: runInfo.tags,
445
+ metadata: runInfo.metadata,
446
+ }, runInfo);
447
+ }
448
+ async onRetrieverStart(run) {
449
+ const runName = assignName(run);
450
+ const runType = "retriever";
451
+ const runInfo = {
452
+ tags: run.tags ?? [],
453
+ metadata: run.extra?.metadata ?? {},
454
+ name: runName,
455
+ runType,
456
+ inputs: {
457
+ query: run.inputs.query,
458
+ },
459
+ };
460
+ this.runInfoMap.set(run.id, runInfo);
461
+ await this.send({
462
+ event: "on_retriever_start",
463
+ data: {
464
+ input: {
465
+ query: run.inputs.query,
466
+ },
467
+ },
468
+ name: runName,
469
+ tags: run.tags ?? [],
470
+ run_id: run.id,
471
+ metadata: run.extra?.metadata ?? {},
472
+ }, runInfo);
473
+ }
474
+ async onRetrieverEnd(run) {
475
+ const runInfo = this.runInfoMap.get(run.id);
476
+ this.runInfoMap.delete(run.id);
477
+ if (runInfo === undefined) {
478
+ throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);
479
+ }
480
+ await this.sendEndEvent({
481
+ event: "on_retriever_end",
482
+ data: {
483
+ output: run.outputs?.documents ?? run.outputs,
484
+ input: runInfo.inputs,
485
+ },
486
+ run_id: run.id,
487
+ name: runInfo.name,
488
+ tags: runInfo.tags,
489
+ metadata: runInfo.metadata,
490
+ }, runInfo);
491
+ }
492
+ }
493
+ exports.EventStreamCallbackHandler = EventStreamCallbackHandler;
@@ -0,0 +1,137 @@
1
+ import { BaseTracer, type Run } from "./base.js";
2
+ import { BaseCallbackHandlerInput } from "../callbacks/base.js";
3
+ import { IterableReadableStream } from "../utils/stream.js";
4
+ /**
5
+ * Data associated with a StreamEvent.
6
+ */
7
+ export type StreamEventData = {
8
+ /**
9
+ * The input passed to the runnable that generated the event.
10
+ * Inputs will sometimes be available at the *START* of the runnable, and
11
+ * sometimes at the *END* of the runnable.
12
+ * If a runnable is able to stream its inputs, then its input by definition
13
+ * won't be known until the *END* of the runnable when it has finished streaming
14
+ * its inputs.
15
+ */
16
+ input?: any;
17
+ /**
18
+ * The output of the runnable that generated the event.
19
+ * Outputs will only be available at the *END* of the runnable.
20
+ * For most runnables, this field can be inferred from the `chunk` field,
21
+ * though there might be some exceptions for special cased runnables (e.g., like
22
+ * chat models), which may return more information.
23
+ */
24
+ output?: any;
25
+ /**
26
+ * A streaming chunk from the output that generated the event.
27
+ * chunks support addition in general, and adding them up should result
28
+ * in the output of the runnable that generated the event.
29
+ */
30
+ chunk?: any;
31
+ };
32
+ /**
33
+ * A streaming event.
34
+ *
35
+ * Schema of a streaming event which is produced from the streamEvents method.
36
+ */
37
+ export type StreamEvent = {
38
+ /**
39
+ * Event names are of the format: on_[runnable_type]_(start|stream|end).
40
+ *
41
+ * Runnable types are one of:
42
+ * - llm - used by non chat models
43
+ * - chat_model - used by chat models
44
+ * - prompt -- e.g., ChatPromptTemplate
45
+ * - tool -- LangChain tools
46
+ * - chain - most Runnables are of this type
47
+ *
48
+ * Further, the events are categorized as one of:
49
+ * - start - when the runnable starts
50
+ * - stream - when the runnable is streaming
51
+ * - end - when the runnable ends
52
+ *
53
+ * start, stream and end are associated with slightly different `data` payload.
54
+ *
55
+ * Please see the documentation for `EventData` for more details.
56
+ */
57
+ event: string;
58
+ /** The name of the runnable that generated the event. */
59
+ name: string;
60
+ /**
61
+ * An randomly generated ID to keep track of the execution of the given runnable.
62
+ *
63
+ * Each child runnable that gets invoked as part of the execution of a parent runnable
64
+ * is assigned its own unique ID.
65
+ */
66
+ run_id: string;
67
+ /**
68
+ * Tags associated with the runnable that generated this event.
69
+ * Tags are always inherited from parent runnables.
70
+ */
71
+ tags?: string[];
72
+ /** Metadata associated with the runnable that generated this event. */
73
+ metadata: Record<string, any>;
74
+ /**
75
+ * Event data.
76
+ *
77
+ * The contents of the event data depend on the event type.
78
+ */
79
+ data: StreamEventData;
80
+ };
81
+ type RunInfo = {
82
+ name: string;
83
+ tags: string[];
84
+ metadata: Record<string, any>;
85
+ runType: string;
86
+ inputs?: Record<string, any>;
87
+ };
88
+ export interface EventStreamCallbackHandlerInput extends BaseCallbackHandlerInput {
89
+ autoClose?: boolean;
90
+ includeNames?: string[];
91
+ includeTypes?: string[];
92
+ includeTags?: string[];
93
+ excludeNames?: string[];
94
+ excludeTypes?: string[];
95
+ excludeTags?: string[];
96
+ }
97
+ /**
98
+ * Class that extends the `BaseTracer` class from the
99
+ * `langchain.callbacks.tracers.base` module. It represents a callback
100
+ * handler that logs the execution of runs and emits `RunLog` instances to a
101
+ * `RunLogStream`.
102
+ */
103
+ export declare class EventStreamCallbackHandler extends BaseTracer {
104
+ protected autoClose: boolean;
105
+ protected includeNames?: string[];
106
+ protected includeTypes?: string[];
107
+ protected includeTags?: string[];
108
+ protected excludeNames?: string[];
109
+ protected excludeTypes?: string[];
110
+ protected excludeTags?: string[];
111
+ protected rootId?: string;
112
+ private runInfoMap;
113
+ private tappedPromises;
114
+ protected transformStream: TransformStream;
115
+ writer: WritableStreamDefaultWriter;
116
+ receiveStream: IterableReadableStream<StreamEvent>;
117
+ name: string;
118
+ constructor(fields?: EventStreamCallbackHandlerInput);
119
+ [Symbol.asyncIterator](): IterableReadableStream<StreamEvent>;
120
+ protected persistRun(_run: Run): Promise<void>;
121
+ _includeRun(run: RunInfo): boolean;
122
+ tapOutputIterable<T>(runId: string, outputStream: AsyncGenerator<T>): AsyncGenerator<T>;
123
+ send(payload: StreamEvent, run: RunInfo): Promise<void>;
124
+ sendEndEvent(payload: StreamEvent, run: RunInfo): Promise<void>;
125
+ onLLMStart(run: Run): Promise<void>;
126
+ onLLMNewToken(run: Run, token: string, kwargs?: {
127
+ chunk: any;
128
+ }): Promise<void>;
129
+ onLLMEnd(run: Run): Promise<void>;
130
+ onChainStart(run: Run): Promise<void>;
131
+ onChainEnd(run: Run): Promise<void>;
132
+ onToolStart(run: Run): Promise<void>;
133
+ onToolEnd(run: Run): Promise<void>;
134
+ onRetrieverStart(run: Run): Promise<void>;
135
+ onRetrieverEnd(run: Run): Promise<void>;
136
+ }
137
+ export {};