@langchain/core 0.1.27-rc.0 → 0.1.27-rc.2

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.
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports._RootEventFilter = void 0;
4
+ /**
5
+ * Utility to filter the root event in the streamEvents implementation.
6
+ * This is simply binding the arguments to the namespace to make save on
7
+ * a bit of typing in the streamEvents implementation.
8
+ *
9
+ * TODO: Refactor and remove.
10
+ */
11
+ class _RootEventFilter {
12
+ constructor(fields) {
13
+ Object.defineProperty(this, "includeNames", {
14
+ enumerable: true,
15
+ configurable: true,
16
+ writable: true,
17
+ value: void 0
18
+ });
19
+ Object.defineProperty(this, "includeTypes", {
20
+ enumerable: true,
21
+ configurable: true,
22
+ writable: true,
23
+ value: void 0
24
+ });
25
+ Object.defineProperty(this, "includeTags", {
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true,
29
+ value: void 0
30
+ });
31
+ Object.defineProperty(this, "excludeNames", {
32
+ enumerable: true,
33
+ configurable: true,
34
+ writable: true,
35
+ value: void 0
36
+ });
37
+ Object.defineProperty(this, "excludeTypes", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: void 0
42
+ });
43
+ Object.defineProperty(this, "excludeTags", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: void 0
48
+ });
49
+ this.includeNames = fields.includeNames;
50
+ this.includeTypes = fields.includeTypes;
51
+ this.includeTags = fields.includeTags;
52
+ this.excludeNames = fields.excludeNames;
53
+ this.excludeTypes = fields.excludeTypes;
54
+ this.excludeTags = fields.excludeTags;
55
+ }
56
+ includeEvent(event, rootType) {
57
+ let include = this.includeNames === undefined &&
58
+ this.includeTypes === undefined &&
59
+ this.includeTags === undefined;
60
+ const eventTags = event.tags ?? [];
61
+ if (this.includeNames !== undefined) {
62
+ include = include || this.includeNames.includes(event.name);
63
+ }
64
+ if (this.includeTypes !== undefined) {
65
+ include = include || this.includeTypes.includes(rootType);
66
+ }
67
+ if (this.includeTags !== undefined) {
68
+ include =
69
+ include || eventTags.some((tag) => this.includeTags?.includes(tag));
70
+ }
71
+ if (this.excludeNames !== undefined) {
72
+ include = include && !this.excludeNames.includes(event.name);
73
+ }
74
+ if (this.excludeTypes !== undefined) {
75
+ include = include && !this.excludeTypes.includes(rootType);
76
+ }
77
+ if (this.excludeTags !== undefined) {
78
+ include =
79
+ include && eventTags.every((tag) => !this.excludeTags?.includes(tag));
80
+ }
81
+ return include;
82
+ }
83
+ }
84
+ exports._RootEventFilter = _RootEventFilter;
@@ -0,0 +1,25 @@
1
+ import { StreamEvent } from "../tracers/log_stream.js";
2
+ /**
3
+ * Utility to filter the root event in the streamEvents implementation.
4
+ * This is simply binding the arguments to the namespace to make save on
5
+ * a bit of typing in the streamEvents implementation.
6
+ *
7
+ * TODO: Refactor and remove.
8
+ */
9
+ export declare class _RootEventFilter {
10
+ includeNames?: string[];
11
+ includeTypes?: string[];
12
+ includeTags?: string[];
13
+ excludeNames?: string[];
14
+ excludeTypes?: string[];
15
+ excludeTags?: string[];
16
+ constructor(fields: {
17
+ includeNames?: string[];
18
+ includeTypes?: string[];
19
+ includeTags?: string[];
20
+ excludeNames?: string[];
21
+ excludeTypes?: string[];
22
+ excludeTags?: string[];
23
+ });
24
+ includeEvent(event: StreamEvent, rootType: string): boolean;
25
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Utility to filter the root event in the streamEvents implementation.
3
+ * This is simply binding the arguments to the namespace to make save on
4
+ * a bit of typing in the streamEvents implementation.
5
+ *
6
+ * TODO: Refactor and remove.
7
+ */
8
+ export class _RootEventFilter {
9
+ constructor(fields) {
10
+ Object.defineProperty(this, "includeNames", {
11
+ enumerable: true,
12
+ configurable: true,
13
+ writable: true,
14
+ value: void 0
15
+ });
16
+ Object.defineProperty(this, "includeTypes", {
17
+ enumerable: true,
18
+ configurable: true,
19
+ writable: true,
20
+ value: void 0
21
+ });
22
+ Object.defineProperty(this, "includeTags", {
23
+ enumerable: true,
24
+ configurable: true,
25
+ writable: true,
26
+ value: void 0
27
+ });
28
+ Object.defineProperty(this, "excludeNames", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: void 0
33
+ });
34
+ Object.defineProperty(this, "excludeTypes", {
35
+ enumerable: true,
36
+ configurable: true,
37
+ writable: true,
38
+ value: void 0
39
+ });
40
+ Object.defineProperty(this, "excludeTags", {
41
+ enumerable: true,
42
+ configurable: true,
43
+ writable: true,
44
+ value: void 0
45
+ });
46
+ this.includeNames = fields.includeNames;
47
+ this.includeTypes = fields.includeTypes;
48
+ this.includeTags = fields.includeTags;
49
+ this.excludeNames = fields.excludeNames;
50
+ this.excludeTypes = fields.excludeTypes;
51
+ this.excludeTags = fields.excludeTags;
52
+ }
53
+ includeEvent(event, rootType) {
54
+ let include = this.includeNames === undefined &&
55
+ this.includeTypes === undefined &&
56
+ this.includeTags === undefined;
57
+ const eventTags = event.tags ?? [];
58
+ if (this.includeNames !== undefined) {
59
+ include = include || this.includeNames.includes(event.name);
60
+ }
61
+ if (this.includeTypes !== undefined) {
62
+ include = include || this.includeTypes.includes(rootType);
63
+ }
64
+ if (this.includeTags !== undefined) {
65
+ include =
66
+ include || eventTags.some((tag) => this.includeTags?.includes(tag));
67
+ }
68
+ if (this.excludeNames !== undefined) {
69
+ include = include && !this.excludeNames.includes(event.name);
70
+ }
71
+ if (this.excludeTypes !== undefined) {
72
+ include = include && !this.excludeTypes.includes(rootType);
73
+ }
74
+ if (this.excludeTags !== undefined) {
75
+ include =
76
+ include && eventTags.every((tag) => !this.excludeTags?.includes(tag));
77
+ }
78
+ return include;
79
+ }
80
+ }
@@ -400,7 +400,7 @@ class BaseTracer extends base_js_1.BaseCallbackHandler {
400
400
  time: new Date().toISOString(),
401
401
  kwargs: { token, idx, chunk: fields?.chunk },
402
402
  });
403
- await this.onLLMNewToken?.(run, token);
403
+ await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk });
404
404
  return run;
405
405
  }
406
406
  }
@@ -71,5 +71,7 @@ export declare abstract class BaseTracer extends BaseCallbackHandler {
71
71
  onRetrieverEnd?(run: Run): void | Promise<void>;
72
72
  onRetrieverError?(run: Run): void | Promise<void>;
73
73
  onText?(run: Run): void | Promise<void>;
74
- onLLMNewToken?(run: Run, token: string): void | Promise<void>;
74
+ onLLMNewToken?(run: Run, token: string, kwargs?: {
75
+ chunk: any;
76
+ }): void | Promise<void>;
75
77
  }
@@ -397,7 +397,7 @@ export class BaseTracer extends BaseCallbackHandler {
397
397
  time: new Date().toISOString(),
398
398
  kwargs: { token, idx, chunk: fields?.chunk },
399
399
  });
400
- await this.onLLMNewToken?.(run, token);
400
+ await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk });
401
401
  return run;
402
402
  }
403
403
  }
@@ -4,6 +4,7 @@ exports.LogStreamCallbackHandler = exports.RunLog = exports.RunLogPatch = void 0
4
4
  const index_js_1 = require("../utils/fast-json-patch/index.cjs");
5
5
  const base_js_1 = require("./base.cjs");
6
6
  const stream_js_1 = require("../utils/stream.cjs");
7
+ const index_js_2 = require("../messages/index.cjs");
7
8
  /**
8
9
  * List of jsonpatch JSONPatchOperations, which describe how to create the run state
9
10
  * from an empty dict. This is the minimal representation of the log, designed to
@@ -19,7 +20,7 @@ class RunLogPatch {
19
20
  writable: true,
20
21
  value: void 0
21
22
  });
22
- this.ops = fields.ops;
23
+ this.ops = fields.ops ?? [];
23
24
  }
24
25
  concat(other) {
25
26
  const ops = this.ops.concat(other.ops);
@@ -48,8 +49,69 @@ class RunLog extends RunLogPatch {
48
49
  const states = (0, index_js_1.applyPatch)(this.state, other.ops);
49
50
  return new RunLog({ ops, state: states[states.length - 1].newDocument });
50
51
  }
52
+ static fromRunLogPatch(patch) {
53
+ const states = (0, index_js_1.applyPatch)({}, patch.ops);
54
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
55
+ return new RunLog({
56
+ ops: patch.ops,
57
+ state: states[states.length - 1].newDocument,
58
+ });
59
+ }
51
60
  }
52
61
  exports.RunLog = RunLog;
62
+ /**
63
+ * Extract standardized inputs from a run.
64
+ *
65
+ * Standardizes the inputs based on the type of the runnable used.
66
+ *
67
+ * @param run - Run object
68
+ * @param schemaFormat - The schema format to use.
69
+ *
70
+ * @returns Valid inputs are only dict. By conventions, inputs always represented
71
+ * invocation using named arguments.
72
+ * A null means that the input is not yet known!
73
+ */
74
+ async function _getStandardizedInputs(run, schemaFormat) {
75
+ if (schemaFormat === "original") {
76
+ throw new Error("Do not assign inputs with original schema drop the key for now. " +
77
+ "When inputs are added to streamLog they should be added with " +
78
+ "standardized schema for streaming events.");
79
+ }
80
+ const { inputs } = run;
81
+ if (["retriever", "llm", "prompt"].includes(run.run_type)) {
82
+ return inputs;
83
+ }
84
+ if (Object.keys(inputs).length === 1 && inputs?.input === "") {
85
+ return undefined;
86
+ }
87
+ // new style chains
88
+ // These nest an additional 'input' key inside the 'inputs' to make sure
89
+ // the input is always a dict. We need to unpack and user the inner value.
90
+ // We should try to fix this in Runnables and callbacks/tracers
91
+ // Runnables should be using a null type here not a placeholder
92
+ // dict.
93
+ return inputs.input;
94
+ }
95
+ async function _getStandardizedOutputs(run, schemaFormat) {
96
+ const { outputs } = run;
97
+ if (schemaFormat === "original") {
98
+ // Return the old schema, without standardizing anything
99
+ return outputs;
100
+ }
101
+ if (["retriever", "llm", "prompt"].includes(run.run_type)) {
102
+ return outputs;
103
+ }
104
+ // TODO: Remove this hacky check
105
+ if (outputs !== undefined &&
106
+ Object.keys(outputs).length === 1 &&
107
+ outputs?.output !== undefined) {
108
+ return outputs.output;
109
+ }
110
+ return outputs;
111
+ }
112
+ function isChatGenerationChunk(x) {
113
+ return x !== undefined && x.message !== undefined;
114
+ }
53
115
  /**
54
116
  * Class that extends the `BaseTracer` class from the
55
117
  * `langchain.callbacks.tracers.base` module. It represents a callback
@@ -101,6 +163,12 @@ class LogStreamCallbackHandler extends base_js_1.BaseTracer {
101
163
  writable: true,
102
164
  value: void 0
103
165
  });
166
+ Object.defineProperty(this, "_schemaFormat", {
167
+ enumerable: true,
168
+ configurable: true,
169
+ writable: true,
170
+ value: "original"
171
+ });
104
172
  Object.defineProperty(this, "rootId", {
105
173
  enumerable: true,
106
174
  configurable: true,
@@ -150,6 +218,7 @@ class LogStreamCallbackHandler extends base_js_1.BaseTracer {
150
218
  this.excludeNames = fields?.excludeNames;
151
219
  this.excludeTypes = fields?.excludeTypes;
152
220
  this.excludeTags = fields?.excludeTags;
221
+ this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat;
153
222
  this.transformStream = new TransformStream();
154
223
  this.writer = this.transformStream.writable.getWriter();
155
224
  this.receiveStream = stream_js_1.IterableReadableStream.fromReadableStream(this.transformStream.readable);
@@ -225,6 +294,8 @@ class LogStreamCallbackHandler extends base_js_1.BaseTracer {
225
294
  path: "",
226
295
  value: {
227
296
  id: run.id,
297
+ name: run.name,
298
+ type: run.run_type,
228
299
  streamed_output: [],
229
300
  final_output: undefined,
230
301
  logs: {},
@@ -255,6 +326,9 @@ class LogStreamCallbackHandler extends base_js_1.BaseTracer {
255
326
  final_output: undefined,
256
327
  end_time: undefined,
257
328
  };
329
+ if (this._schemaFormat === "streaming_events") {
330
+ logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat);
331
+ }
258
332
  await this.writer.write(new RunLogPatch({
259
333
  ops: [
260
334
  {
@@ -271,13 +345,19 @@ class LogStreamCallbackHandler extends base_js_1.BaseTracer {
271
345
  if (runName === undefined) {
272
346
  return;
273
347
  }
274
- const ops = [
275
- {
276
- op: "add",
277
- path: `/logs/${runName}/final_output`,
278
- value: run.outputs,
279
- },
280
- ];
348
+ const ops = [];
349
+ if (this._schemaFormat === "streaming_events") {
350
+ ops.push({
351
+ op: "replace",
352
+ path: `/logs/${runName}/inputs`,
353
+ value: await _getStandardizedInputs(run, this._schemaFormat),
354
+ });
355
+ }
356
+ ops.push({
357
+ op: "add",
358
+ path: `/logs/${runName}/final_output`,
359
+ value: await _getStandardizedOutputs(run, this._schemaFormat),
360
+ });
281
361
  if (run.end_time !== undefined) {
282
362
  ops.push({
283
363
  op: "add",
@@ -295,7 +375,7 @@ class LogStreamCallbackHandler extends base_js_1.BaseTracer {
295
375
  {
296
376
  op: "replace",
297
377
  path: "/final_output",
298
- value: run.outputs,
378
+ value: await _getStandardizedOutputs(run, this._schemaFormat),
299
379
  },
300
380
  ],
301
381
  });
@@ -306,11 +386,25 @@ class LogStreamCallbackHandler extends base_js_1.BaseTracer {
306
386
  }
307
387
  }
308
388
  }
309
- async onLLMNewToken(run, token) {
389
+ async onLLMNewToken(run, token, kwargs) {
310
390
  const runName = this.keyMapByRunId[run.id];
311
391
  if (runName === undefined) {
312
392
  return;
313
393
  }
394
+ // TODO: Remove hack
395
+ const isChatModel = run.inputs.messages !== undefined;
396
+ let streamedOutputValue;
397
+ if (isChatModel) {
398
+ if (isChatGenerationChunk(kwargs?.chunk)) {
399
+ streamedOutputValue = kwargs?.chunk;
400
+ }
401
+ else {
402
+ streamedOutputValue = new index_js_2.AIMessageChunk(token);
403
+ }
404
+ }
405
+ else {
406
+ streamedOutputValue = token;
407
+ }
314
408
  const patch = new RunLogPatch({
315
409
  ops: [
316
410
  {
@@ -318,6 +412,11 @@ class LogStreamCallbackHandler extends base_js_1.BaseTracer {
318
412
  path: `/logs/${runName}/streamed_output_str/-`,
319
413
  value: token,
320
414
  },
415
+ {
416
+ op: "add",
417
+ path: `/logs/${runName}/streamed_output/-`,
418
+ value: streamedOutputValue,
419
+ },
321
420
  ],
322
421
  });
323
422
  await this.writer.write(patch);
@@ -1,6 +1,6 @@
1
1
  import { type Operation as JSONPatchOperation } from "../utils/fast-json-patch/index.js";
2
2
  import { BaseTracer, type Run } from "./base.js";
3
- import { BaseCallbackHandlerInput } from "../callbacks/base.js";
3
+ import { BaseCallbackHandlerInput, HandleLLMNewTokenCallbackFields } from "../callbacks/base.js";
4
4
  import { IterableReadableStream } from "../utils/stream.js";
5
5
  /**
6
6
  * Interface that represents the structure of a log entry in the
@@ -23,6 +23,8 @@ export type LogEntry = {
23
23
  streamed_output: any[];
24
24
  /** List of LLM tokens streamed by this run, if applicable. */
25
25
  streamed_output_str: string[];
26
+ /** Inputs to this run. Not available currently via streamLog. */
27
+ inputs?: any;
26
28
  /** Final output of this run. Only available after the run has finished successfully. */
27
29
  final_output?: any;
28
30
  /** ISO-8601 timestamp of when the run ended. Only available after the run has finished. */
@@ -40,6 +42,10 @@ export type RunState = {
40
42
  * If filters were supplied, this list will contain only the runs that matched the filters.
41
43
  */
42
44
  logs: Record<string, LogEntry>;
45
+ /** Name of the object being run. */
46
+ name: string;
47
+ /** Type of the object being run, eg. prompt, chain, llm, etc. */
48
+ type: string;
43
49
  };
44
50
  /**
45
51
  * List of jsonpatch JSONPatchOperations, which describe how to create the run state
@@ -51,18 +57,97 @@ export type RunState = {
51
57
  export declare class RunLogPatch {
52
58
  ops: JSONPatchOperation[];
53
59
  constructor(fields: {
54
- ops: JSONPatchOperation[];
60
+ ops?: JSONPatchOperation[];
55
61
  });
56
62
  concat(other: RunLogPatch): RunLog;
57
63
  }
58
64
  export declare class RunLog extends RunLogPatch {
59
65
  state: RunState;
60
66
  constructor(fields: {
61
- ops: JSONPatchOperation[];
67
+ ops?: JSONPatchOperation[];
62
68
  state: RunState;
63
69
  });
64
70
  concat(other: RunLogPatch): RunLog;
71
+ static fromRunLogPatch(patch: RunLogPatch): RunLog;
65
72
  }
73
+ /**
74
+ * Data associated with a StreamEvent.
75
+ */
76
+ export type StreamEventData = {
77
+ /**
78
+ * The input passed to the runnable that generated the event.
79
+ * Inputs will sometimes be available at the *START* of the runnable, and
80
+ * sometimes at the *END* of the runnable.
81
+ * If a runnable is able to stream its inputs, then its input by definition
82
+ * won't be known until the *END* of the runnable when it has finished streaming
83
+ * its inputs.
84
+ */
85
+ input?: any;
86
+ /**
87
+ * The output of the runnable that generated the event.
88
+ * Outputs will only be available at the *END* of the runnable.
89
+ * For most runnables, this field can be inferred from the `chunk` field,
90
+ * though there might be some exceptions for special cased runnables (e.g., like
91
+ * chat models), which may return more information.
92
+ */
93
+ output?: any;
94
+ /**
95
+ * A streaming chunk from the output that generated the event.
96
+ * chunks support addition in general, and adding them up should result
97
+ * in the output of the runnable that generated the event.
98
+ */
99
+ chunk?: any;
100
+ };
101
+ /**
102
+ * A streaming event.
103
+ *
104
+ * Schema of a streaming event which is produced from the astream_events method.
105
+ */
106
+ export type StreamEvent = {
107
+ /**
108
+ * Event names are of the format: on_[runnable_type]_(start|stream|end).
109
+ *
110
+ * Runnable types are one of:
111
+ * - llm - used by non chat models
112
+ * - chat_model - used by chat models
113
+ * - prompt -- e.g., ChatPromptTemplate
114
+ * - tool -- from tools defined via @tool decorator or inheriting from Tool/BaseTool
115
+ * - chain - most Runnables are of this type
116
+ *
117
+ * Further, the events are categorized as one of:
118
+ * - start - when the runnable starts
119
+ * - stream - when the runnable is streaming
120
+ * - end - when the runnable ends
121
+ *
122
+ * start, stream and end are associated with slightly different `data` payload.
123
+ *
124
+ * Please see the documentation for `EventData` for more details.
125
+ */
126
+ event: string;
127
+ /** The name of the runnable that generated the event. */
128
+ name: string;
129
+ /**
130
+ * An randomly generated ID to keep track of the execution of the given runnable.
131
+ *
132
+ * Each child runnable that gets invoked as part of the execution of a parent runnable
133
+ * is assigned its own unique ID.
134
+ */
135
+ run_id: string;
136
+ /**
137
+ * Tags associated with the runnable that generated this event.
138
+ * Tags are always inherited from parent runnables.
139
+ */
140
+ tags?: string[];
141
+ /** Metadata associated with the runnable that generated this event. */
142
+ metadata: Record<string, any>;
143
+ /**
144
+ * Event data.
145
+ *
146
+ * The contents of the event data depend on the event type.
147
+ */
148
+ data: StreamEventData;
149
+ };
150
+ export type SchemaFormat = "original" | "streaming_events";
66
151
  export interface LogStreamCallbackHandlerInput extends BaseCallbackHandlerInput {
67
152
  autoClose?: boolean;
68
153
  includeNames?: string[];
@@ -71,6 +156,7 @@ export interface LogStreamCallbackHandlerInput extends BaseCallbackHandlerInput
71
156
  excludeNames?: string[];
72
157
  excludeTypes?: string[];
73
158
  excludeTags?: string[];
159
+ _schemaFormat?: SchemaFormat;
74
160
  }
75
161
  /**
76
162
  * Class that extends the `BaseTracer` class from the
@@ -86,6 +172,7 @@ export declare class LogStreamCallbackHandler extends BaseTracer {
86
172
  protected excludeNames?: string[];
87
173
  protected excludeTypes?: string[];
88
174
  protected excludeTags?: string[];
175
+ protected _schemaFormat: SchemaFormat;
89
176
  protected rootId?: string;
90
177
  private keyMapByRunId;
91
178
  private counterMapByRunName;
@@ -100,5 +187,5 @@ export declare class LogStreamCallbackHandler extends BaseTracer {
100
187
  tapOutputIterable<T>(runId: string, output: AsyncGenerator<T>): AsyncGenerator<T>;
101
188
  onRunCreate(run: Run): Promise<void>;
102
189
  onRunUpdate(run: Run): Promise<void>;
103
- onLLMNewToken(run: Run, token: string): Promise<void>;
190
+ onLLMNewToken(run: Run, token: string, kwargs?: HandleLLMNewTokenCallbackFields): Promise<void>;
104
191
  }