@langchain/core 0.1.5 → 0.1.7

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.
package/README.md CHANGED
@@ -121,7 +121,7 @@ Because all used packages must share the same version of core, we suggest using
121
121
  "license": "MIT",
122
122
  "dependencies": {
123
123
  "@anthropic-ai/sdk": "^0.10.0",
124
- "@langchain/core": "~0.1.2"
124
+ "@langchain/core": "~0.1.5"
125
125
  }
126
126
  }
127
127
  ```
@@ -547,11 +547,6 @@ class CallbackManager extends BaseCallbackManager {
547
547
  if (tracingV2Enabled) {
548
548
  callbackManager.addHandler(await (0, initialize_js_1.getTracingV2CallbackHandler)(), true);
549
549
  }
550
- else {
551
- const session = (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_PROJECT") &&
552
- (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_SESSION");
553
- callbackManager.addHandler(await (0, initialize_js_1.getTracingCallbackHandler)(session), true);
554
- }
555
550
  }
556
551
  }
557
552
  if (inheritableTags || localTags) {
@@ -1,7 +1,7 @@
1
1
  import { v4 as uuidv4 } from "uuid";
2
2
  import { BaseCallbackHandler, } from "./base.js";
3
3
  import { ConsoleCallbackHandler } from "../tracers/console.js";
4
- import { getTracingCallbackHandler, getTracingV2CallbackHandler, } from "../tracers/initialize.js";
4
+ import { getTracingV2CallbackHandler } from "../tracers/initialize.js";
5
5
  import { getBufferString } from "../messages/index.js";
6
6
  import { getEnvironmentVariable } from "../utils/env.js";
7
7
  import { LangChainTracer, } from "../tracers/tracer_langchain.js";
@@ -538,11 +538,6 @@ export class CallbackManager extends BaseCallbackManager {
538
538
  if (tracingV2Enabled) {
539
539
  callbackManager.addHandler(await getTracingV2CallbackHandler(), true);
540
540
  }
541
- else {
542
- const session = getEnvironmentVariable("LANGCHAIN_PROJECT") &&
543
- getEnvironmentVariable("LANGCHAIN_SESSION");
544
- callbackManager.addHandler(await getTracingCallbackHandler(session), true);
545
- }
546
541
  }
547
542
  }
548
543
  if (inheritableTags || localTags) {
@@ -24,7 +24,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
24
24
  return result;
25
25
  };
26
26
  Object.defineProperty(exports, "__esModule", { value: true });
27
- exports.vectorstores = exports.utils__types = exports.utils__tiktoken = exports.utils__testing = exports.utils__stream = exports.utils__math = exports.utils__json_schema = exports.utils__json_patch = exports.utils__hash = exports.utils__env = exports.utils__chunk_array = exports.utils__async_caller = exports.tracers__tracer_langchain = exports.tracers__tracer_langchain_v1 = exports.tracers__run_collector = exports.tracers__log_stream = exports.tracers__initialize = exports.tracers__console = exports.tracers__base = exports.tools = exports.stores = exports.retrievers = exports.runnables = exports.prompt_values = exports.prompts = exports.outputs = exports.output_parsers = exports.messages = exports.memory = exports.load__serializable = exports.language_models__llms = exports.language_models__chat_models = exports.language_models__base = exports.example_selectors = exports.embeddings = exports.documents = exports.chat_history = exports.callbacks__promises = exports.callbacks__manager = exports.callbacks__base = exports.caches = exports.agents = void 0;
27
+ exports.vectorstores = exports.utils__types = exports.utils__tiktoken = exports.utils__testing = exports.utils__stream = exports.utils__math = exports.utils__json_schema = exports.utils__json_patch = exports.utils__hash = exports.utils__env = exports.utils__chunk_array = exports.utils__async_caller = exports.tracers__tracer_langchain = exports.tracers__run_collector = exports.tracers__log_stream = exports.tracers__initialize = exports.tracers__console = exports.tracers__base = exports.tools = exports.stores = exports.retrievers = exports.runnables = exports.prompt_values = exports.prompts = exports.outputs = exports.output_parsers = exports.messages = exports.memory = exports.load__serializable = exports.language_models__llms = exports.language_models__chat_models = exports.language_models__base = exports.example_selectors = exports.embeddings = exports.documents = exports.chat_history = exports.callbacks__promises = exports.callbacks__manager = exports.callbacks__base = exports.caches = exports.agents = void 0;
28
28
  exports.agents = __importStar(require("../agents.cjs"));
29
29
  exports.caches = __importStar(require("../caches.cjs"));
30
30
  exports.callbacks__base = __importStar(require("../callbacks/base.cjs"));
@@ -53,7 +53,6 @@ exports.tracers__console = __importStar(require("../tracers/console.cjs"));
53
53
  exports.tracers__initialize = __importStar(require("../tracers/initialize.cjs"));
54
54
  exports.tracers__log_stream = __importStar(require("../tracers/log_stream.cjs"));
55
55
  exports.tracers__run_collector = __importStar(require("../tracers/run_collector.cjs"));
56
- exports.tracers__tracer_langchain_v1 = __importStar(require("../tracers/tracer_langchain_v1.cjs"));
57
56
  exports.tracers__tracer_langchain = __importStar(require("../tracers/tracer_langchain.cjs"));
58
57
  exports.utils__async_caller = __importStar(require("../utils/async_caller.cjs"));
59
58
  exports.utils__chunk_array = __importStar(require("../utils/chunk_array.cjs"));
@@ -26,7 +26,6 @@ export * as tracers__console from "../tracers/console.js";
26
26
  export * as tracers__initialize from "../tracers/initialize.js";
27
27
  export * as tracers__log_stream from "../tracers/log_stream.js";
28
28
  export * as tracers__run_collector from "../tracers/run_collector.js";
29
- export * as tracers__tracer_langchain_v1 from "../tracers/tracer_langchain_v1.js";
30
29
  export * as tracers__tracer_langchain from "../tracers/tracer_langchain.js";
31
30
  export * as utils__async_caller from "../utils/async_caller.js";
32
31
  export * as utils__chunk_array from "../utils/chunk_array.js";
@@ -27,7 +27,6 @@ export * as tracers__console from "../tracers/console.js";
27
27
  export * as tracers__initialize from "../tracers/initialize.js";
28
28
  export * as tracers__log_stream from "../tracers/log_stream.js";
29
29
  export * as tracers__run_collector from "../tracers/run_collector.js";
30
- export * as tracers__tracer_langchain_v1 from "../tracers/tracer_langchain_v1.js";
31
30
  export * as tracers__tracer_langchain from "../tracers/tracer_langchain.js";
32
31
  export * as utils__async_caller from "../utils/async_caller.js";
33
32
  export * as utils__chunk_array from "../utils/chunk_array.js";
@@ -14,6 +14,9 @@ exports.BasePromptValue = BasePromptValue;
14
14
  * class and overrides the toString and toChatMessages methods.
15
15
  */
16
16
  class StringPromptValue extends BasePromptValue {
17
+ static lc_name() {
18
+ return "StringPromptValue";
19
+ }
17
20
  constructor(value) {
18
21
  super({ value });
19
22
  Object.defineProperty(this, "lc_namespace", {
@@ -22,6 +22,7 @@ export declare abstract class BasePromptValue extends Serializable implements Ba
22
22
  * class and overrides the toString and toChatMessages methods.
23
23
  */
24
24
  export declare class StringPromptValue extends BasePromptValue implements StringPromptValueInterface {
25
+ static lc_name(): string;
25
26
  lc_namespace: string[];
26
27
  lc_serializable: boolean;
27
28
  value: string;
@@ -10,6 +10,9 @@ export class BasePromptValue extends Serializable {
10
10
  * class and overrides the toString and toChatMessages methods.
11
11
  */
12
12
  export class StringPromptValue extends BasePromptValue {
13
+ static lc_name() {
14
+ return "StringPromptValue";
15
+ }
13
16
  constructor(value) {
14
17
  super({ value });
15
18
  Object.defineProperty(this, "lc_namespace", {
@@ -168,7 +168,7 @@ class Runnable extends serializable_js_1.Serializable {
168
168
  return [runnableConfig, callOptions];
169
169
  }
170
170
  async _callWithConfig(func, input, options) {
171
- const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
171
+ const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(options);
172
172
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, options?.runType, undefined, undefined, options?.runName ?? this.getName());
173
173
  let output;
174
174
  try {
@@ -192,7 +192,7 @@ class Runnable extends serializable_js_1.Serializable {
192
192
  */
193
193
  async _batchWithConfig(func, inputs, options, batchOptions) {
194
194
  const optionsList = this._getOptionsList(options ?? {}, inputs.length);
195
- const callbackManagers = await Promise.all(optionsList.map(config_js_1.getCallbackMangerForConfig));
195
+ const callbackManagers = await Promise.all(optionsList.map(config_js_1.getCallbackManagerForConfig));
196
196
  const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), undefined, optionsList[i].runType, undefined, undefined, optionsList[i].runName ?? this.getName())));
197
197
  let outputs;
198
198
  try {
@@ -215,8 +215,7 @@ class Runnable extends serializable_js_1.Serializable {
215
215
  let finalInputSupported = true;
216
216
  let finalOutput;
217
217
  let finalOutputSupported = true;
218
- const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
219
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, undefined, options?.runType, undefined, undefined, options?.runName ?? this.getName());
218
+ const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(options);
220
219
  async function* wrapInputForTracing() {
221
220
  for await (const chunk of inputGenerator) {
222
221
  if (finalInputSupported) {
@@ -237,10 +236,11 @@ class Runnable extends serializable_js_1.Serializable {
237
236
  yield chunk;
238
237
  }
239
238
  }
240
- const wrappedInputGenerator = wrapInputForTracing();
239
+ let runManager;
241
240
  try {
242
- const outputIterator = transformer(wrappedInputGenerator, runManager, options);
243
- for await (const chunk of outputIterator) {
241
+ const pipe = await (0, stream_js_1.pipeGeneratorWithSetup)(transformer, wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, undefined, options?.runType, undefined, undefined, options?.runName ?? this.getName()), options);
242
+ runManager = pipe.setup;
243
+ for await (const chunk of pipe.output) {
244
244
  yield chunk;
245
245
  if (finalOutputSupported) {
246
246
  if (finalOutput === undefined) {
@@ -816,7 +816,7 @@ class RunnableSequence extends Runnable {
816
816
  return [this.first, ...this.middle, this.last];
817
817
  }
818
818
  async invoke(input, options) {
819
- const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
819
+ const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(options);
820
820
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, undefined, undefined, undefined, options?.runName);
821
821
  let nextStepInput = input;
822
822
  let finalOutput;
@@ -838,7 +838,7 @@ class RunnableSequence extends Runnable {
838
838
  }
839
839
  async batch(inputs, options, batchOptions) {
840
840
  const configList = this._getOptionsList(options ?? {}, inputs.length);
841
- const callbackManagers = await Promise.all(configList.map(config_js_1.getCallbackMangerForConfig));
841
+ const callbackManagers = await Promise.all(configList.map(config_js_1.getCallbackManagerForConfig));
842
842
  const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), undefined, undefined, undefined, undefined, configList[i].runName)));
843
843
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
844
844
  let nextStepInputs = inputs;
@@ -859,7 +859,7 @@ class RunnableSequence extends Runnable {
859
859
  return finalOutputs;
860
860
  }
861
861
  async *_streamIterator(input, options) {
862
- const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
862
+ const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(options);
863
863
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, undefined, undefined, undefined, options?.runName);
864
864
  const steps = [this.first, ...this.middle, this.last];
865
865
  let concatSupported = true;
@@ -987,7 +987,7 @@ class RunnableMap extends Runnable {
987
987
  return new RunnableMap({ steps });
988
988
  }
989
989
  async invoke(input, options) {
990
- const callbackManager_ = await (0, config_js_1.getCallbackMangerForConfig)(options);
990
+ const callbackManager_ = await (0, config_js_1.getCallbackManagerForConfig)(options);
991
991
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), {
992
992
  input,
993
993
  }, undefined, undefined, undefined, undefined, options?.runName);
@@ -1284,7 +1284,7 @@ class RunnableAssign extends Runnable {
1284
1284
  // collect mapper keys
1285
1285
  const mapperKeys = this.mapper.getStepsKeys();
1286
1286
  // create two input gens, one for the mapper, one for the input
1287
- const [forPassthrough, forMapper] = (0, stream_js_1.atee)(generator, 2);
1287
+ const [forPassthrough, forMapper] = (0, stream_js_1.atee)(generator);
1288
1288
  // create mapper output gen
1289
1289
  const mapperOutput = this.mapper.transform(forMapper, this._patchConfig(options, runManager?.getChild()));
1290
1290
  // start the mapper
@@ -2,8 +2,8 @@ import pRetry from "p-retry";
2
2
  import { CallbackManager, } from "../callbacks/manager.js";
3
3
  import { LogStreamCallbackHandler, RunLogPatch, } from "../tracers/log_stream.js";
4
4
  import { Serializable } from "../load/serializable.js";
5
- import { IterableReadableStream, concat, atee, } from "../utils/stream.js";
6
- import { DEFAULT_RECURSION_LIMIT, getCallbackMangerForConfig, mergeConfigs, } from "./config.js";
5
+ import { IterableReadableStream, concat, atee, pipeGeneratorWithSetup, } from "../utils/stream.js";
6
+ import { DEFAULT_RECURSION_LIMIT, getCallbackManagerForConfig, mergeConfigs, } from "./config.js";
7
7
  import { AsyncCaller } from "../utils/async_caller.js";
8
8
  import { RootListenersTracer } from "../tracers/root_listener.js";
9
9
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -162,7 +162,7 @@ export class Runnable extends Serializable {
162
162
  return [runnableConfig, callOptions];
163
163
  }
164
164
  async _callWithConfig(func, input, options) {
165
- const callbackManager_ = await getCallbackMangerForConfig(options);
165
+ const callbackManager_ = await getCallbackManagerForConfig(options);
166
166
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, options?.runType, undefined, undefined, options?.runName ?? this.getName());
167
167
  let output;
168
168
  try {
@@ -186,7 +186,7 @@ export class Runnable extends Serializable {
186
186
  */
187
187
  async _batchWithConfig(func, inputs, options, batchOptions) {
188
188
  const optionsList = this._getOptionsList(options ?? {}, inputs.length);
189
- const callbackManagers = await Promise.all(optionsList.map(getCallbackMangerForConfig));
189
+ const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig));
190
190
  const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), undefined, optionsList[i].runType, undefined, undefined, optionsList[i].runName ?? this.getName())));
191
191
  let outputs;
192
192
  try {
@@ -209,8 +209,7 @@ export class Runnable extends Serializable {
209
209
  let finalInputSupported = true;
210
210
  let finalOutput;
211
211
  let finalOutputSupported = true;
212
- const callbackManager_ = await getCallbackMangerForConfig(options);
213
- const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, undefined, options?.runType, undefined, undefined, options?.runName ?? this.getName());
212
+ const callbackManager_ = await getCallbackManagerForConfig(options);
214
213
  async function* wrapInputForTracing() {
215
214
  for await (const chunk of inputGenerator) {
216
215
  if (finalInputSupported) {
@@ -231,10 +230,11 @@ export class Runnable extends Serializable {
231
230
  yield chunk;
232
231
  }
233
232
  }
234
- const wrappedInputGenerator = wrapInputForTracing();
233
+ let runManager;
235
234
  try {
236
- const outputIterator = transformer(wrappedInputGenerator, runManager, options);
237
- for await (const chunk of outputIterator) {
235
+ const pipe = await pipeGeneratorWithSetup(transformer, wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, undefined, options?.runType, undefined, undefined, options?.runName ?? this.getName()), options);
236
+ runManager = pipe.setup;
237
+ for await (const chunk of pipe.output) {
238
238
  yield chunk;
239
239
  if (finalOutputSupported) {
240
240
  if (finalOutput === undefined) {
@@ -806,7 +806,7 @@ export class RunnableSequence extends Runnable {
806
806
  return [this.first, ...this.middle, this.last];
807
807
  }
808
808
  async invoke(input, options) {
809
- const callbackManager_ = await getCallbackMangerForConfig(options);
809
+ const callbackManager_ = await getCallbackManagerForConfig(options);
810
810
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, undefined, undefined, undefined, options?.runName);
811
811
  let nextStepInput = input;
812
812
  let finalOutput;
@@ -828,7 +828,7 @@ export class RunnableSequence extends Runnable {
828
828
  }
829
829
  async batch(inputs, options, batchOptions) {
830
830
  const configList = this._getOptionsList(options ?? {}, inputs.length);
831
- const callbackManagers = await Promise.all(configList.map(getCallbackMangerForConfig));
831
+ const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig));
832
832
  const runManagers = await Promise.all(callbackManagers.map((callbackManager, i) => callbackManager?.handleChainStart(this.toJSON(), _coerceToDict(inputs[i], "input"), undefined, undefined, undefined, undefined, configList[i].runName)));
833
833
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
834
834
  let nextStepInputs = inputs;
@@ -849,7 +849,7 @@ export class RunnableSequence extends Runnable {
849
849
  return finalOutputs;
850
850
  }
851
851
  async *_streamIterator(input, options) {
852
- const callbackManager_ = await getCallbackMangerForConfig(options);
852
+ const callbackManager_ = await getCallbackManagerForConfig(options);
853
853
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), _coerceToDict(input, "input"), undefined, undefined, undefined, undefined, options?.runName);
854
854
  const steps = [this.first, ...this.middle, this.last];
855
855
  let concatSupported = true;
@@ -976,7 +976,7 @@ export class RunnableMap extends Runnable {
976
976
  return new RunnableMap({ steps });
977
977
  }
978
978
  async invoke(input, options) {
979
- const callbackManager_ = await getCallbackMangerForConfig(options);
979
+ const callbackManager_ = await getCallbackManagerForConfig(options);
980
980
  const runManager = await callbackManager_?.handleChainStart(this.toJSON(), {
981
981
  input,
982
982
  }, undefined, undefined, undefined, undefined, options?.runName);
@@ -1268,7 +1268,7 @@ export class RunnableAssign extends Runnable {
1268
1268
  // collect mapper keys
1269
1269
  const mapperKeys = this.mapper.getStepsKeys();
1270
1270
  // create two input gens, one for the mapper, one for the input
1271
- const [forPassthrough, forMapper] = atee(generator, 2);
1271
+ const [forPassthrough, forMapper] = atee(generator);
1272
1272
  // create mapper output gen
1273
1273
  const mapperOutput = this.mapper.transform(forMapper, this._patchConfig(options, runManager?.getChild()));
1274
1274
  // start the mapper
@@ -1,12 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mergeConfigs = exports.getCallbackMangerForConfig = exports.DEFAULT_RECURSION_LIMIT = void 0;
3
+ exports.mergeConfigs = exports.getCallbackManagerForConfig = exports.DEFAULT_RECURSION_LIMIT = void 0;
4
4
  const manager_js_1 = require("../callbacks/manager.cjs");
5
5
  exports.DEFAULT_RECURSION_LIMIT = 25;
6
- async function getCallbackMangerForConfig(config) {
6
+ async function getCallbackManagerForConfig(config) {
7
7
  return manager_js_1.CallbackManager.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata);
8
8
  }
9
- exports.getCallbackMangerForConfig = getCallbackMangerForConfig;
9
+ exports.getCallbackManagerForConfig = getCallbackManagerForConfig;
10
10
  function mergeConfigs(config,
11
11
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
12
12
  options) {
@@ -11,5 +11,5 @@ export interface RunnableConfig extends BaseCallbackConfig {
11
11
  */
12
12
  recursionLimit?: number;
13
13
  }
14
- export declare function getCallbackMangerForConfig(config?: RunnableConfig): Promise<CallbackManager | undefined>;
14
+ export declare function getCallbackManagerForConfig(config?: RunnableConfig): Promise<CallbackManager | undefined>;
15
15
  export declare function mergeConfigs<CallOptions extends RunnableConfig>(config: RunnableConfig, options?: Record<string, any>): Partial<CallOptions>;
@@ -1,6 +1,6 @@
1
1
  import { CallbackManager, } from "../callbacks/manager.js";
2
2
  export const DEFAULT_RECURSION_LIMIT = 25;
3
- export async function getCallbackMangerForConfig(config) {
3
+ export async function getCallbackManagerForConfig(config) {
4
4
  return CallbackManager.configure(config?.callbacks, undefined, config?.tags, undefined, config?.metadata);
5
5
  }
6
6
  export function mergeConfigs(config,
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RunnableWithMessageHistory = exports.RunnableBranch = exports.RouterRunnable = exports.RunnablePassthrough = exports._coerceToRunnable = exports.RunnablePick = exports.RunnableAssign = exports.RunnableWithFallbacks = exports.RunnableLambda = exports.RunnableParallel = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableEach = exports.RunnableBinding = exports.Runnable = void 0;
3
+ exports.RunnableWithMessageHistory = exports.RunnableBranch = exports.RouterRunnable = exports.RunnablePassthrough = exports.getCallbackManagerForConfig = exports._coerceToRunnable = exports.RunnablePick = exports.RunnableAssign = exports.RunnableWithFallbacks = exports.RunnableLambda = exports.RunnableParallel = exports.RunnableMap = exports.RunnableSequence = exports.RunnableRetry = exports.RunnableEach = exports.RunnableBinding = exports.Runnable = void 0;
4
4
  var base_js_1 = require("./base.cjs");
5
5
  Object.defineProperty(exports, "Runnable", { enumerable: true, get: function () { return base_js_1.Runnable; } });
6
6
  Object.defineProperty(exports, "RunnableBinding", { enumerable: true, get: function () { return base_js_1.RunnableBinding; } });
@@ -14,6 +14,8 @@ Object.defineProperty(exports, "RunnableWithFallbacks", { enumerable: true, get:
14
14
  Object.defineProperty(exports, "RunnableAssign", { enumerable: true, get: function () { return base_js_1.RunnableAssign; } });
15
15
  Object.defineProperty(exports, "RunnablePick", { enumerable: true, get: function () { return base_js_1.RunnablePick; } });
16
16
  Object.defineProperty(exports, "_coerceToRunnable", { enumerable: true, get: function () { return base_js_1._coerceToRunnable; } });
17
+ var config_js_1 = require("./config.cjs");
18
+ Object.defineProperty(exports, "getCallbackManagerForConfig", { enumerable: true, get: function () { return config_js_1.getCallbackManagerForConfig; } });
17
19
  var passthrough_js_1 = require("./passthrough.cjs");
18
20
  Object.defineProperty(exports, "RunnablePassthrough", { enumerable: true, get: function () { return passthrough_js_1.RunnablePassthrough; } });
19
21
  var router_js_1 = require("./router.cjs");
@@ -1,5 +1,5 @@
1
1
  export { type RunnableFunc, type RunnableLike, type RunnableBatchOptions, type RunnableRetryFailedAttemptHandler, Runnable, type RunnableInterface, type RunnableBindingArgs, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableParallel, RunnableLambda, RunnableWithFallbacks, RunnableAssign, RunnablePick, _coerceToRunnable, } from "./base.js";
2
- export type { RunnableConfig, getCallbackMangerForConfig } from "./config.js";
2
+ export { type RunnableConfig, getCallbackManagerForConfig } from "./config.js";
3
3
  export { RunnablePassthrough } from "./passthrough.js";
4
4
  export { type RouterInput, RouterRunnable } from "./router.js";
5
5
  export { RunnableBranch, type Branch, type BranchLike } from "./branch.js";
@@ -1,4 +1,5 @@
1
1
  export { Runnable, RunnableBinding, RunnableEach, RunnableRetry, RunnableSequence, RunnableMap, RunnableParallel, RunnableLambda, RunnableWithFallbacks, RunnableAssign, RunnablePick, _coerceToRunnable, } from "./base.js";
2
+ export { getCallbackManagerForConfig } from "./config.js";
2
3
  export { RunnablePassthrough } from "./passthrough.js";
3
4
  export { RouterRunnable } from "./router.js";
4
5
  export { RunnableBranch } from "./branch.js";
@@ -8,6 +8,13 @@ function _coerceToDict(value, defaultKey) {
8
8
  ? value
9
9
  : { [defaultKey]: value };
10
10
  }
11
+ function stripNonAlphanumeric(input) {
12
+ return input.replace(/[-:.]/g, "");
13
+ }
14
+ function convertToDottedOrderFormat(epoch, runId) {
15
+ return (stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}000Z`) +
16
+ runId);
17
+ }
11
18
  class BaseTracer extends base_js_1.BaseCallbackHandler {
12
19
  constructor(_fields) {
13
20
  super(...arguments);
@@ -25,15 +32,31 @@ class BaseTracer extends base_js_1.BaseCallbackHandler {
25
32
  parentRun.child_runs.push(childRun);
26
33
  }
27
34
  async _startTrace(run) {
28
- if (run.parent_run_id !== undefined) {
29
- const parentRun = this.runMap.get(run.parent_run_id);
35
+ const currentDottedOrder = convertToDottedOrderFormat(run.start_time, run.id);
36
+ const storedRun = { ...run };
37
+ if (storedRun.parent_run_id !== undefined) {
38
+ const parentRun = this.runMap.get(storedRun.parent_run_id);
30
39
  if (parentRun) {
31
- this._addChildRun(parentRun, run);
32
- parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order);
40
+ this._addChildRun(parentRun, storedRun);
41
+ parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order);
42
+ storedRun.trace_id = parentRun.trace_id;
43
+ if (parentRun.dotted_order !== undefined) {
44
+ storedRun.dotted_order = [
45
+ parentRun.dotted_order,
46
+ currentDottedOrder,
47
+ ].join(".");
48
+ }
49
+ else {
50
+ console.warn(`Parent run with UUID ${storedRun.parent_run_id} not found.`);
51
+ }
33
52
  }
34
53
  }
35
- this.runMap.set(run.id, run);
36
- await this.onRunCreate?.(run);
54
+ else {
55
+ storedRun.trace_id = storedRun.id;
56
+ storedRun.dotted_order = currentDottedOrder;
57
+ }
58
+ this.runMap.set(storedRun.id, storedRun);
59
+ await this.onRunCreate?.(storedRun);
37
60
  }
38
61
  async _endTrace(run) {
39
62
  const parentRun = run.parent_run_id !== undefined && this.runMap.get(run.parent_run_id);
@@ -18,6 +18,8 @@ export interface Run extends BaseRun {
18
18
  time: string;
19
19
  kwargs?: Record<string, unknown>;
20
20
  }>;
21
+ trace_id?: string;
22
+ dotted_order?: string;
21
23
  }
22
24
  export interface AgentRun extends Run {
23
25
  actions: AgentAction[];
@@ -5,6 +5,13 @@ function _coerceToDict(value, defaultKey) {
5
5
  ? value
6
6
  : { [defaultKey]: value };
7
7
  }
8
+ function stripNonAlphanumeric(input) {
9
+ return input.replace(/[-:.]/g, "");
10
+ }
11
+ function convertToDottedOrderFormat(epoch, runId) {
12
+ return (stripNonAlphanumeric(`${new Date(epoch).toISOString().slice(0, -1)}000Z`) +
13
+ runId);
14
+ }
8
15
  export class BaseTracer extends BaseCallbackHandler {
9
16
  constructor(_fields) {
10
17
  super(...arguments);
@@ -22,15 +29,31 @@ export class BaseTracer extends BaseCallbackHandler {
22
29
  parentRun.child_runs.push(childRun);
23
30
  }
24
31
  async _startTrace(run) {
25
- if (run.parent_run_id !== undefined) {
26
- const parentRun = this.runMap.get(run.parent_run_id);
32
+ const currentDottedOrder = convertToDottedOrderFormat(run.start_time, run.id);
33
+ const storedRun = { ...run };
34
+ if (storedRun.parent_run_id !== undefined) {
35
+ const parentRun = this.runMap.get(storedRun.parent_run_id);
27
36
  if (parentRun) {
28
- this._addChildRun(parentRun, run);
29
- parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order);
37
+ this._addChildRun(parentRun, storedRun);
38
+ parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order);
39
+ storedRun.trace_id = parentRun.trace_id;
40
+ if (parentRun.dotted_order !== undefined) {
41
+ storedRun.dotted_order = [
42
+ parentRun.dotted_order,
43
+ currentDottedOrder,
44
+ ].join(".");
45
+ }
46
+ else {
47
+ console.warn(`Parent run with UUID ${storedRun.parent_run_id} not found.`);
48
+ }
30
49
  }
31
50
  }
32
- this.runMap.set(run.id, run);
33
- await this.onRunCreate?.(run);
51
+ else {
52
+ storedRun.trace_id = storedRun.id;
53
+ storedRun.dotted_order = currentDottedOrder;
54
+ }
55
+ this.runMap.set(storedRun.id, storedRun);
56
+ await this.onRunCreate?.(storedRun);
34
57
  }
35
58
  async _endTrace(run) {
36
59
  const parentRun = run.parent_run_id !== undefined && this.runMap.get(run.parent_run_id);
@@ -1,26 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getTracingV2CallbackHandler = exports.getTracingCallbackHandler = void 0;
3
+ exports.getTracingV2CallbackHandler = void 0;
4
4
  const tracer_langchain_js_1 = require("./tracer_langchain.cjs");
5
- const tracer_langchain_v1_js_1 = require("./tracer_langchain_v1.cjs");
6
- /**
7
- * Function that returns an instance of `LangChainTracerV1`. If a session
8
- * is provided, it loads that session into the tracer; otherwise, it loads
9
- * a default session.
10
- * @param session Optional session to load into the tracer.
11
- * @returns An instance of `LangChainTracerV1`.
12
- */
13
- async function getTracingCallbackHandler(session) {
14
- const tracer = new tracer_langchain_v1_js_1.LangChainTracerV1();
15
- if (session) {
16
- await tracer.loadSession(session);
17
- }
18
- else {
19
- await tracer.loadDefaultSession();
20
- }
21
- return tracer;
22
- }
23
- exports.getTracingCallbackHandler = getTracingCallbackHandler;
24
5
  /**
25
6
  * Function that returns an instance of `LangChainTracer`. It does not
26
7
  * load any session data.
@@ -1,13 +1,4 @@
1
1
  import { LangChainTracer } from "./tracer_langchain.js";
2
- import { LangChainTracerV1 } from "./tracer_langchain_v1.js";
3
- /**
4
- * Function that returns an instance of `LangChainTracerV1`. If a session
5
- * is provided, it loads that session into the tracer; otherwise, it loads
6
- * a default session.
7
- * @param session Optional session to load into the tracer.
8
- * @returns An instance of `LangChainTracerV1`.
9
- */
10
- export declare function getTracingCallbackHandler(session?: string): Promise<LangChainTracerV1>;
11
2
  /**
12
3
  * Function that returns an instance of `LangChainTracer`. It does not
13
4
  * load any session data.
@@ -1,22 +1,4 @@
1
1
  import { LangChainTracer } from "./tracer_langchain.js";
2
- import { LangChainTracerV1 } from "./tracer_langchain_v1.js";
3
- /**
4
- * Function that returns an instance of `LangChainTracerV1`. If a session
5
- * is provided, it loads that session into the tracer; otherwise, it loads
6
- * a default session.
7
- * @param session Optional session to load into the tracer.
8
- * @returns An instance of `LangChainTracerV1`.
9
- */
10
- export async function getTracingCallbackHandler(session) {
11
- const tracer = new LangChainTracerV1();
12
- if (session) {
13
- await tracer.loadSession(session);
14
- }
15
- else {
16
- await tracer.loadDefaultSession();
17
- }
18
- return tracer;
19
- }
20
2
  /**
21
3
  * Function that returns an instance of `LangChainTracer`. It does not
22
4
  * load any session data.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.concat = exports.atee = exports.IterableReadableStream = void 0;
3
+ exports.pipeGeneratorWithSetup = exports.AsyncGeneratorWithSetup = exports.concat = exports.atee = exports.IterableReadableStream = void 0;
4
4
  /*
5
5
  * Support async iterator syntax for ReadableStreams in all environments.
6
6
  * Source: https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
@@ -156,3 +156,63 @@ function concat(first, second) {
156
156
  }
157
157
  }
158
158
  exports.concat = concat;
159
+ class AsyncGeneratorWithSetup {
160
+ constructor(generator, startSetup) {
161
+ Object.defineProperty(this, "generator", {
162
+ enumerable: true,
163
+ configurable: true,
164
+ writable: true,
165
+ value: void 0
166
+ });
167
+ Object.defineProperty(this, "setup", {
168
+ enumerable: true,
169
+ configurable: true,
170
+ writable: true,
171
+ value: void 0
172
+ });
173
+ Object.defineProperty(this, "firstResult", {
174
+ enumerable: true,
175
+ configurable: true,
176
+ writable: true,
177
+ value: void 0
178
+ });
179
+ Object.defineProperty(this, "firstResultUsed", {
180
+ enumerable: true,
181
+ configurable: true,
182
+ writable: true,
183
+ value: false
184
+ });
185
+ this.generator = generator;
186
+ // setup is a promise that resolves only after the first iterator value
187
+ // is available. this is useful when setup of several piped generators
188
+ // needs to happen in logical order, ie. in the order in which input to
189
+ // to each generator is available.
190
+ this.setup = new Promise((resolve, reject) => {
191
+ this.firstResult = generator.next();
192
+ this.firstResult.then(startSetup).then(resolve, reject);
193
+ });
194
+ }
195
+ async next(...args) {
196
+ if (!this.firstResultUsed) {
197
+ this.firstResultUsed = true;
198
+ return this.firstResult;
199
+ }
200
+ return this.generator.next(...args);
201
+ }
202
+ async return(value) {
203
+ return this.generator.return(value);
204
+ }
205
+ async throw(e) {
206
+ return this.generator.throw(e);
207
+ }
208
+ [Symbol.asyncIterator]() {
209
+ return this;
210
+ }
211
+ }
212
+ exports.AsyncGeneratorWithSetup = AsyncGeneratorWithSetup;
213
+ async function pipeGeneratorWithSetup(to, generator, startSetup, ...args) {
214
+ const gen = new AsyncGeneratorWithSetup(generator, startSetup);
215
+ const setup = await gen.setup;
216
+ return { output: to(gen, setup, ...args), setup };
217
+ }
218
+ exports.pipeGeneratorWithSetup = pipeGeneratorWithSetup;
@@ -18,3 +18,18 @@ export declare class IterableReadableStream<T> extends ReadableStream<T> impleme
18
18
  }
19
19
  export declare function atee<T>(iter: AsyncGenerator<T>, length?: number): AsyncGenerator<T>[];
20
20
  export declare function concat<T extends Array<any> | string | number | Record<string, any> | any>(first: T, second: T): T;
21
+ export declare class AsyncGeneratorWithSetup<S = unknown, T = unknown, TReturn = unknown, TNext = unknown> implements AsyncGenerator<T, TReturn, TNext> {
22
+ private generator;
23
+ setup: Promise<S>;
24
+ private firstResult;
25
+ private firstResultUsed;
26
+ constructor(generator: AsyncGenerator<T>, startSetup: () => Promise<S>);
27
+ next(...args: [] | [TNext]): Promise<IteratorResult<T>>;
28
+ return(value: TReturn | PromiseLike<TReturn>): Promise<IteratorResult<T>>;
29
+ throw(e: Error): Promise<IteratorResult<T>>;
30
+ [Symbol.asyncIterator](): this;
31
+ }
32
+ export declare function pipeGeneratorWithSetup<S, A extends unknown[], T, TReturn, TNext, U, UReturn, UNext>(to: (g: AsyncGenerator<T, TReturn, TNext>, s: S, ...args: A) => AsyncGenerator<U, UReturn, UNext>, generator: AsyncGenerator<T, TReturn, TNext>, startSetup: () => Promise<S>, ...args: A): Promise<{
33
+ output: AsyncGenerator<U, UReturn, UNext>;
34
+ setup: Awaited<S>;
35
+ }>;
@@ -150,3 +150,61 @@ export function concat(first, second) {
150
150
  throw new Error(`Cannot concat ${typeof first} and ${typeof second}`);
151
151
  }
152
152
  }
153
+ export class AsyncGeneratorWithSetup {
154
+ constructor(generator, startSetup) {
155
+ Object.defineProperty(this, "generator", {
156
+ enumerable: true,
157
+ configurable: true,
158
+ writable: true,
159
+ value: void 0
160
+ });
161
+ Object.defineProperty(this, "setup", {
162
+ enumerable: true,
163
+ configurable: true,
164
+ writable: true,
165
+ value: void 0
166
+ });
167
+ Object.defineProperty(this, "firstResult", {
168
+ enumerable: true,
169
+ configurable: true,
170
+ writable: true,
171
+ value: void 0
172
+ });
173
+ Object.defineProperty(this, "firstResultUsed", {
174
+ enumerable: true,
175
+ configurable: true,
176
+ writable: true,
177
+ value: false
178
+ });
179
+ this.generator = generator;
180
+ // setup is a promise that resolves only after the first iterator value
181
+ // is available. this is useful when setup of several piped generators
182
+ // needs to happen in logical order, ie. in the order in which input to
183
+ // to each generator is available.
184
+ this.setup = new Promise((resolve, reject) => {
185
+ this.firstResult = generator.next();
186
+ this.firstResult.then(startSetup).then(resolve, reject);
187
+ });
188
+ }
189
+ async next(...args) {
190
+ if (!this.firstResultUsed) {
191
+ this.firstResultUsed = true;
192
+ return this.firstResult;
193
+ }
194
+ return this.generator.next(...args);
195
+ }
196
+ async return(value) {
197
+ return this.generator.return(value);
198
+ }
199
+ async throw(e) {
200
+ return this.generator.throw(e);
201
+ }
202
+ [Symbol.asyncIterator]() {
203
+ return this;
204
+ }
205
+ }
206
+ export async function pipeGeneratorWithSetup(to, generator, startSetup, ...args) {
207
+ const gen = new AsyncGeneratorWithSetup(generator, startSetup);
208
+ const setup = await gen.setup;
209
+ return { output: to(gen, setup, ...args), setup };
210
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/core",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "Core LangChain.js abstractions and schemas",
5
5
  "type": "module",
6
6
  "engines": {
@@ -229,11 +229,6 @@
229
229
  "import": "./tracers/run_collector.js",
230
230
  "require": "./tracers/run_collector.cjs"
231
231
  },
232
- "./tracers/tracer_langchain_v1": {
233
- "types": "./tracers/tracer_langchain_v1.d.ts",
234
- "import": "./tracers/tracer_langchain_v1.js",
235
- "require": "./tracers/tracer_langchain_v1.cjs"
236
- },
237
232
  "./tracers/tracer_langchain": {
238
233
  "types": "./tracers/tracer_langchain.d.ts",
239
234
  "import": "./tracers/tracer_langchain.js",
@@ -390,9 +385,6 @@
390
385
  "tracers/run_collector.cjs",
391
386
  "tracers/run_collector.js",
392
387
  "tracers/run_collector.d.ts",
393
- "tracers/tracer_langchain_v1.cjs",
394
- "tracers/tracer_langchain_v1.js",
395
- "tracers/tracer_langchain_v1.d.ts",
396
388
  "tracers/tracer_langchain.cjs",
397
389
  "tracers/tracer_langchain.js",
398
390
  "tracers/tracer_langchain.d.ts",
@@ -1,199 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LangChainTracerV1 = void 0;
4
- const index_js_1 = require("../messages/index.cjs");
5
- const env_js_1 = require("../utils/env.cjs");
6
- const base_js_1 = require("./base.cjs");
7
- class LangChainTracerV1 extends base_js_1.BaseTracer {
8
- constructor() {
9
- super();
10
- Object.defineProperty(this, "name", {
11
- enumerable: true,
12
- configurable: true,
13
- writable: true,
14
- value: "langchain_tracer"
15
- });
16
- Object.defineProperty(this, "endpoint", {
17
- enumerable: true,
18
- configurable: true,
19
- writable: true,
20
- value: (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_ENDPOINT") || "http://localhost:1984"
21
- });
22
- Object.defineProperty(this, "headers", {
23
- enumerable: true,
24
- configurable: true,
25
- writable: true,
26
- value: {
27
- "Content-Type": "application/json",
28
- }
29
- });
30
- Object.defineProperty(this, "session", {
31
- enumerable: true,
32
- configurable: true,
33
- writable: true,
34
- value: void 0
35
- });
36
- const apiKey = (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_API_KEY");
37
- if (apiKey) {
38
- this.headers["x-api-key"] = apiKey;
39
- }
40
- }
41
- async newSession(sessionName) {
42
- const sessionCreate = {
43
- start_time: Date.now(),
44
- name: sessionName,
45
- };
46
- const session = await this.persistSession(sessionCreate);
47
- this.session = session;
48
- return session;
49
- }
50
- async loadSession(sessionName) {
51
- const endpoint = `${this.endpoint}/sessions?name=${sessionName}`;
52
- return this._handleSessionResponse(endpoint);
53
- }
54
- async loadDefaultSession() {
55
- const endpoint = `${this.endpoint}/sessions?name=default`;
56
- return this._handleSessionResponse(endpoint);
57
- }
58
- async convertV2RunToRun(run) {
59
- const session = this.session ?? (await this.loadDefaultSession());
60
- const serialized = run.serialized;
61
- let runResult;
62
- if (run.run_type === "llm") {
63
- const prompts = run.inputs.prompts
64
- ? run.inputs.prompts
65
- : run.inputs.messages.map((x) => (0, index_js_1.getBufferString)(x));
66
- const llmRun = {
67
- uuid: run.id,
68
- start_time: run.start_time,
69
- end_time: run.end_time,
70
- execution_order: run.execution_order,
71
- child_execution_order: run.child_execution_order,
72
- serialized,
73
- type: run.run_type,
74
- session_id: session.id,
75
- prompts,
76
- response: run.outputs,
77
- };
78
- runResult = llmRun;
79
- }
80
- else if (run.run_type === "chain") {
81
- const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run)));
82
- const chainRun = {
83
- uuid: run.id,
84
- start_time: run.start_time,
85
- end_time: run.end_time,
86
- execution_order: run.execution_order,
87
- child_execution_order: run.child_execution_order,
88
- serialized,
89
- type: run.run_type,
90
- session_id: session.id,
91
- inputs: run.inputs,
92
- outputs: run.outputs,
93
- child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"),
94
- child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"),
95
- child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"),
96
- };
97
- runResult = chainRun;
98
- }
99
- else if (run.run_type === "tool") {
100
- const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run)));
101
- const toolRun = {
102
- uuid: run.id,
103
- start_time: run.start_time,
104
- end_time: run.end_time,
105
- execution_order: run.execution_order,
106
- child_execution_order: run.child_execution_order,
107
- serialized,
108
- type: run.run_type,
109
- session_id: session.id,
110
- tool_input: run.inputs.input,
111
- output: run.outputs?.output,
112
- action: JSON.stringify(serialized),
113
- child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"),
114
- child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"),
115
- child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"),
116
- };
117
- runResult = toolRun;
118
- }
119
- else {
120
- throw new Error(`Unknown run type: ${run.run_type}`);
121
- }
122
- return runResult;
123
- }
124
- async persistRun(run) {
125
- let endpoint;
126
- let v1Run;
127
- if (run.run_type !== undefined) {
128
- v1Run = await this.convertV2RunToRun(run);
129
- }
130
- else {
131
- v1Run = run;
132
- }
133
- if (v1Run.type === "llm") {
134
- endpoint = `${this.endpoint}/llm-runs`;
135
- }
136
- else if (v1Run.type === "chain") {
137
- endpoint = `${this.endpoint}/chain-runs`;
138
- }
139
- else {
140
- endpoint = `${this.endpoint}/tool-runs`;
141
- }
142
- const response = await fetch(endpoint, {
143
- method: "POST",
144
- headers: this.headers,
145
- body: JSON.stringify(v1Run),
146
- });
147
- if (!response.ok) {
148
- console.error(`Failed to persist run: ${response.status} ${response.statusText}`);
149
- }
150
- }
151
- async persistSession(sessionCreate) {
152
- const endpoint = `${this.endpoint}/sessions`;
153
- const response = await fetch(endpoint, {
154
- method: "POST",
155
- headers: this.headers,
156
- body: JSON.stringify(sessionCreate),
157
- });
158
- if (!response.ok) {
159
- console.error(`Failed to persist session: ${response.status} ${response.statusText}, using default session.`);
160
- return {
161
- id: 1,
162
- ...sessionCreate,
163
- };
164
- }
165
- return {
166
- id: (await response.json()).id,
167
- ...sessionCreate,
168
- };
169
- }
170
- async _handleSessionResponse(endpoint) {
171
- const response = await fetch(endpoint, {
172
- method: "GET",
173
- headers: this.headers,
174
- });
175
- let tracerSession;
176
- if (!response.ok) {
177
- console.error(`Failed to load session: ${response.status} ${response.statusText}`);
178
- tracerSession = {
179
- id: 1,
180
- start_time: Date.now(),
181
- };
182
- this.session = tracerSession;
183
- return tracerSession;
184
- }
185
- const resp = (await response.json());
186
- if (resp.length === 0) {
187
- tracerSession = {
188
- id: 1,
189
- start_time: Date.now(),
190
- };
191
- this.session = tracerSession;
192
- return tracerSession;
193
- }
194
- [tracerSession] = resp;
195
- this.session = tracerSession;
196
- return tracerSession;
197
- }
198
- }
199
- exports.LangChainTracerV1 = LangChainTracerV1;
@@ -1,58 +0,0 @@
1
- import type { ChainValues } from "../utils/types.js";
2
- import type { LLMResult } from "../outputs.js";
3
- import { BaseTracer, type RunType, type Run } from "./base.js";
4
- export interface BaseRunV1 {
5
- uuid: string;
6
- parent_uuid?: string;
7
- start_time: number;
8
- end_time?: number;
9
- execution_order: number;
10
- child_execution_order: number;
11
- serialized: {
12
- name: string;
13
- };
14
- session_id: number;
15
- error?: string;
16
- type: RunType;
17
- }
18
- export interface LLMRun extends BaseRunV1 {
19
- prompts: string[];
20
- response?: LLMResult;
21
- }
22
- export interface ChainRun extends BaseRunV1 {
23
- inputs: ChainValues;
24
- outputs?: ChainValues;
25
- child_llm_runs: LLMRun[];
26
- child_chain_runs: ChainRun[];
27
- child_tool_runs: ToolRun[];
28
- }
29
- export interface ToolRun extends BaseRunV1 {
30
- tool_input: string;
31
- output?: string;
32
- action: string;
33
- child_llm_runs: LLMRun[];
34
- child_chain_runs: ChainRun[];
35
- child_tool_runs: ToolRun[];
36
- }
37
- export interface BaseTracerSession {
38
- start_time: number;
39
- name?: string;
40
- }
41
- export type TracerSessionCreate = BaseTracerSession;
42
- export interface TracerSessionV1 extends BaseTracerSession {
43
- id: number;
44
- }
45
- export declare class LangChainTracerV1 extends BaseTracer {
46
- name: string;
47
- protected endpoint: string;
48
- protected headers: Record<string, string>;
49
- protected session: TracerSessionV1;
50
- constructor();
51
- newSession(sessionName?: string): Promise<TracerSessionV1>;
52
- loadSession(sessionName: string): Promise<TracerSessionV1>;
53
- loadDefaultSession(): Promise<TracerSessionV1>;
54
- protected convertV2RunToRun(run: Run): Promise<LLMRun | ChainRun | ToolRun>;
55
- protected persistRun(run: Run | LLMRun | ChainRun | ToolRun): Promise<void>;
56
- protected persistSession(sessionCreate: BaseTracerSession): Promise<TracerSessionV1>;
57
- protected _handleSessionResponse(endpoint: string): Promise<TracerSessionV1>;
58
- }
@@ -1,195 +0,0 @@
1
- import { getBufferString } from "../messages/index.js";
2
- import { getEnvironmentVariable } from "../utils/env.js";
3
- import { BaseTracer } from "./base.js";
4
- export class LangChainTracerV1 extends BaseTracer {
5
- constructor() {
6
- super();
7
- Object.defineProperty(this, "name", {
8
- enumerable: true,
9
- configurable: true,
10
- writable: true,
11
- value: "langchain_tracer"
12
- });
13
- Object.defineProperty(this, "endpoint", {
14
- enumerable: true,
15
- configurable: true,
16
- writable: true,
17
- value: getEnvironmentVariable("LANGCHAIN_ENDPOINT") || "http://localhost:1984"
18
- });
19
- Object.defineProperty(this, "headers", {
20
- enumerable: true,
21
- configurable: true,
22
- writable: true,
23
- value: {
24
- "Content-Type": "application/json",
25
- }
26
- });
27
- Object.defineProperty(this, "session", {
28
- enumerable: true,
29
- configurable: true,
30
- writable: true,
31
- value: void 0
32
- });
33
- const apiKey = getEnvironmentVariable("LANGCHAIN_API_KEY");
34
- if (apiKey) {
35
- this.headers["x-api-key"] = apiKey;
36
- }
37
- }
38
- async newSession(sessionName) {
39
- const sessionCreate = {
40
- start_time: Date.now(),
41
- name: sessionName,
42
- };
43
- const session = await this.persistSession(sessionCreate);
44
- this.session = session;
45
- return session;
46
- }
47
- async loadSession(sessionName) {
48
- const endpoint = `${this.endpoint}/sessions?name=${sessionName}`;
49
- return this._handleSessionResponse(endpoint);
50
- }
51
- async loadDefaultSession() {
52
- const endpoint = `${this.endpoint}/sessions?name=default`;
53
- return this._handleSessionResponse(endpoint);
54
- }
55
- async convertV2RunToRun(run) {
56
- const session = this.session ?? (await this.loadDefaultSession());
57
- const serialized = run.serialized;
58
- let runResult;
59
- if (run.run_type === "llm") {
60
- const prompts = run.inputs.prompts
61
- ? run.inputs.prompts
62
- : run.inputs.messages.map((x) => getBufferString(x));
63
- const llmRun = {
64
- uuid: run.id,
65
- start_time: run.start_time,
66
- end_time: run.end_time,
67
- execution_order: run.execution_order,
68
- child_execution_order: run.child_execution_order,
69
- serialized,
70
- type: run.run_type,
71
- session_id: session.id,
72
- prompts,
73
- response: run.outputs,
74
- };
75
- runResult = llmRun;
76
- }
77
- else if (run.run_type === "chain") {
78
- const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run)));
79
- const chainRun = {
80
- uuid: run.id,
81
- start_time: run.start_time,
82
- end_time: run.end_time,
83
- execution_order: run.execution_order,
84
- child_execution_order: run.child_execution_order,
85
- serialized,
86
- type: run.run_type,
87
- session_id: session.id,
88
- inputs: run.inputs,
89
- outputs: run.outputs,
90
- child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"),
91
- child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"),
92
- child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"),
93
- };
94
- runResult = chainRun;
95
- }
96
- else if (run.run_type === "tool") {
97
- const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run)));
98
- const toolRun = {
99
- uuid: run.id,
100
- start_time: run.start_time,
101
- end_time: run.end_time,
102
- execution_order: run.execution_order,
103
- child_execution_order: run.child_execution_order,
104
- serialized,
105
- type: run.run_type,
106
- session_id: session.id,
107
- tool_input: run.inputs.input,
108
- output: run.outputs?.output,
109
- action: JSON.stringify(serialized),
110
- child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"),
111
- child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"),
112
- child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool"),
113
- };
114
- runResult = toolRun;
115
- }
116
- else {
117
- throw new Error(`Unknown run type: ${run.run_type}`);
118
- }
119
- return runResult;
120
- }
121
- async persistRun(run) {
122
- let endpoint;
123
- let v1Run;
124
- if (run.run_type !== undefined) {
125
- v1Run = await this.convertV2RunToRun(run);
126
- }
127
- else {
128
- v1Run = run;
129
- }
130
- if (v1Run.type === "llm") {
131
- endpoint = `${this.endpoint}/llm-runs`;
132
- }
133
- else if (v1Run.type === "chain") {
134
- endpoint = `${this.endpoint}/chain-runs`;
135
- }
136
- else {
137
- endpoint = `${this.endpoint}/tool-runs`;
138
- }
139
- const response = await fetch(endpoint, {
140
- method: "POST",
141
- headers: this.headers,
142
- body: JSON.stringify(v1Run),
143
- });
144
- if (!response.ok) {
145
- console.error(`Failed to persist run: ${response.status} ${response.statusText}`);
146
- }
147
- }
148
- async persistSession(sessionCreate) {
149
- const endpoint = `${this.endpoint}/sessions`;
150
- const response = await fetch(endpoint, {
151
- method: "POST",
152
- headers: this.headers,
153
- body: JSON.stringify(sessionCreate),
154
- });
155
- if (!response.ok) {
156
- console.error(`Failed to persist session: ${response.status} ${response.statusText}, using default session.`);
157
- return {
158
- id: 1,
159
- ...sessionCreate,
160
- };
161
- }
162
- return {
163
- id: (await response.json()).id,
164
- ...sessionCreate,
165
- };
166
- }
167
- async _handleSessionResponse(endpoint) {
168
- const response = await fetch(endpoint, {
169
- method: "GET",
170
- headers: this.headers,
171
- });
172
- let tracerSession;
173
- if (!response.ok) {
174
- console.error(`Failed to load session: ${response.status} ${response.statusText}`);
175
- tracerSession = {
176
- id: 1,
177
- start_time: Date.now(),
178
- };
179
- this.session = tracerSession;
180
- return tracerSession;
181
- }
182
- const resp = (await response.json());
183
- if (resp.length === 0) {
184
- tracerSession = {
185
- id: 1,
186
- start_time: Date.now(),
187
- };
188
- this.session = tracerSession;
189
- return tracerSession;
190
- }
191
- [tracerSession] = resp;
192
- this.session = tracerSession;
193
- return tracerSession;
194
- }
195
- }
@@ -1 +0,0 @@
1
- module.exports = require('../dist/tracers/tracer_langchain_v1.cjs');
@@ -1 +0,0 @@
1
- export * from '../dist/tracers/tracer_langchain_v1.js'
@@ -1 +0,0 @@
1
- export * from '../dist/tracers/tracer_langchain_v1.js'