@elizaos/core 1.7.0 → 1.7.1-alpha.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.
@@ -25505,6 +25505,34 @@ function mapKeys(fields, mapper, map) {
25505
25505
  return mapped;
25506
25506
  }
25507
25507
 
25508
+ // ../../node_modules/@langchain/core/dist/load/validation.js
25509
+ var LC_ESCAPED_KEY = "__lc_escaped__";
25510
+ function needsEscaping(obj) {
25511
+ return "lc" in obj || Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj;
25512
+ }
25513
+ function escapeObject(obj) {
25514
+ return { [LC_ESCAPED_KEY]: obj };
25515
+ }
25516
+ function isSerializableLike(obj) {
25517
+ return obj !== null && typeof obj === "object" && "lc_serializable" in obj && typeof obj.toJSON === "function";
25518
+ }
25519
+ function escapeIfNeeded(value) {
25520
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
25521
+ if (isSerializableLike(value))
25522
+ return value;
25523
+ const record = value;
25524
+ if (needsEscaping(record))
25525
+ return escapeObject(record);
25526
+ const result = {};
25527
+ for (const [key, val] of Object.entries(record))
25528
+ result[key] = escapeIfNeeded(val);
25529
+ return result;
25530
+ }
25531
+ if (Array.isArray(value))
25532
+ return value.map((item) => escapeIfNeeded(item));
25533
+ return value;
25534
+ }
25535
+
25508
25536
  // ../../node_modules/@langchain/core/dist/load/serializable.js
25509
25537
  var serializable_exports = {};
25510
25538
  __export(serializable_exports, {
@@ -25604,11 +25632,16 @@ var Serializable = class Serializable2 {
25604
25632
  if (last in read && read[last] !== undefined)
25605
25633
  write[last] = write[last] || read[last];
25606
25634
  });
25635
+ const escapedKwargs = {};
25636
+ for (const [key, value] of Object.entries(kwargs))
25637
+ escapedKwargs[key] = escapeIfNeeded(value);
25638
+ const kwargsWithSecrets = Object.keys(secrets).length ? replaceSecrets(escapedKwargs, secrets) : escapedKwargs;
25639
+ const processedKwargs = mapKeys(kwargsWithSecrets, keyToJson, aliases);
25607
25640
  return {
25608
25641
  lc: 1,
25609
25642
  type: "constructor",
25610
25643
  id: this.lc_id,
25611
- kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases)
25644
+ kwargs: processedKwargs
25612
25645
  };
25613
25646
  }
25614
25647
  toJSONNotImplemented() {
@@ -26351,7 +26384,7 @@ function convertToPrettyString(message) {
26351
26384
  lines.push(` Call ID: ${tc.id}`);
26352
26385
  lines.push(" Args:");
26353
26386
  for (const [key, value] of Object.entries(tc.args))
26354
- lines.push(` ${key}: ${value}`);
26387
+ lines.push(` ${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`);
26355
26388
  }
26356
26389
  }
26357
26390
  }
@@ -26598,10 +26631,10 @@ function _mergeLists(left, right) {
26598
26631
  }
26599
26632
  }
26600
26633
  function _mergeObj(left, right) {
26601
- if (!left && !right)
26602
- throw new Error("Cannot merge two undefined objects.");
26603
- if (!left || !right)
26604
- return left || right;
26634
+ if (left === undefined && right === undefined)
26635
+ return;
26636
+ if (left === undefined || right === undefined)
26637
+ return left ?? right;
26605
26638
  else if (typeof left !== typeof right)
26606
26639
  throw new Error(`Cannot merge objects of different types.
26607
26640
  Left ${typeof left}
@@ -27420,6 +27453,117 @@ function mergeUsageMetadata(a, b) {
27420
27453
  }
27421
27454
 
27422
27455
  // ../../node_modules/@langchain/core/dist/messages/ai.js
27456
+ var AIMessage = class extends BaseMessage {
27457
+ type = "ai";
27458
+ tool_calls = [];
27459
+ invalid_tool_calls = [];
27460
+ usage_metadata;
27461
+ get lc_aliases() {
27462
+ return {
27463
+ ...super.lc_aliases,
27464
+ tool_calls: "tool_calls",
27465
+ invalid_tool_calls: "invalid_tool_calls"
27466
+ };
27467
+ }
27468
+ constructor(fields) {
27469
+ let initParams;
27470
+ if (typeof fields === "string" || Array.isArray(fields))
27471
+ initParams = {
27472
+ content: fields,
27473
+ tool_calls: [],
27474
+ invalid_tool_calls: [],
27475
+ additional_kwargs: {}
27476
+ };
27477
+ else {
27478
+ initParams = fields;
27479
+ const rawToolCalls = initParams.additional_kwargs?.tool_calls;
27480
+ const toolCalls = initParams.tool_calls;
27481
+ if (!(rawToolCalls == null) && rawToolCalls.length > 0 && (toolCalls === undefined || toolCalls.length === 0))
27482
+ console.warn([
27483
+ "New LangChain packages are available that more efficiently handle",
27484
+ `tool calling.
27485
+
27486
+ Please upgrade your packages to versions that set`,
27487
+ "message tool calls. e.g., `pnpm install @langchain/anthropic`,",
27488
+ "pnpm install @langchain/openai`, etc."
27489
+ ].join(" "));
27490
+ try {
27491
+ if (!(rawToolCalls == null) && toolCalls === undefined) {
27492
+ const [toolCalls$1, invalidToolCalls] = defaultToolCallParser(rawToolCalls);
27493
+ initParams.tool_calls = toolCalls$1 ?? [];
27494
+ initParams.invalid_tool_calls = invalidToolCalls ?? [];
27495
+ } else {
27496
+ initParams.tool_calls = initParams.tool_calls ?? [];
27497
+ initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? [];
27498
+ }
27499
+ } catch {
27500
+ initParams.tool_calls = [];
27501
+ initParams.invalid_tool_calls = [];
27502
+ }
27503
+ if (initParams.response_metadata !== undefined && "output_version" in initParams.response_metadata && initParams.response_metadata.output_version === "v1") {
27504
+ initParams.contentBlocks = initParams.content;
27505
+ initParams.content = undefined;
27506
+ }
27507
+ if (initParams.contentBlocks !== undefined) {
27508
+ initParams.contentBlocks.push(...initParams.tool_calls.map((toolCall) => ({
27509
+ type: "tool_call",
27510
+ id: toolCall.id,
27511
+ name: toolCall.name,
27512
+ args: toolCall.args
27513
+ })));
27514
+ const missingToolCalls = initParams.contentBlocks.filter((block) => block.type === "tool_call").filter((block) => !initParams.tool_calls?.some((toolCall) => toolCall.id === block.id && toolCall.name === block.name));
27515
+ if (missingToolCalls.length > 0)
27516
+ initParams.tool_calls = missingToolCalls.map((block) => ({
27517
+ type: "tool_call",
27518
+ id: block.id,
27519
+ name: block.name,
27520
+ args: block.args
27521
+ }));
27522
+ }
27523
+ }
27524
+ super(initParams);
27525
+ if (typeof initParams !== "string") {
27526
+ this.tool_calls = initParams.tool_calls ?? this.tool_calls;
27527
+ this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls;
27528
+ }
27529
+ this.usage_metadata = initParams.usage_metadata;
27530
+ }
27531
+ static lc_name() {
27532
+ return "AIMessage";
27533
+ }
27534
+ get contentBlocks() {
27535
+ if (this.response_metadata && "output_version" in this.response_metadata && this.response_metadata.output_version === "v1")
27536
+ return this.content;
27537
+ if (this.response_metadata && "model_provider" in this.response_metadata && typeof this.response_metadata.model_provider === "string") {
27538
+ const translator = getTranslator(this.response_metadata.model_provider);
27539
+ if (translator)
27540
+ return translator.translateContent(this);
27541
+ }
27542
+ const blocks = super.contentBlocks;
27543
+ if (this.tool_calls) {
27544
+ const missingToolCalls = this.tool_calls.filter((block) => !blocks.some((b) => b.id === block.id && b.name === block.name));
27545
+ blocks.push(...missingToolCalls.map((block) => ({
27546
+ ...block,
27547
+ type: "tool_call",
27548
+ id: block.id,
27549
+ name: block.name,
27550
+ args: block.args
27551
+ })));
27552
+ }
27553
+ return blocks;
27554
+ }
27555
+ get _printableFields() {
27556
+ return {
27557
+ ...super._printableFields,
27558
+ tool_calls: this.tool_calls,
27559
+ invalid_tool_calls: this.invalid_tool_calls,
27560
+ usage_metadata: this.usage_metadata
27561
+ };
27562
+ }
27563
+ static isInstance(obj) {
27564
+ return super.isInstance(obj) && obj.type === "ai";
27565
+ }
27566
+ };
27423
27567
  var AIMessageChunk = class extends BaseMessageChunk {
27424
27568
  type = "ai";
27425
27569
  tool_calls = [];
@@ -27745,7 +27889,7 @@ var BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass {
27745
27889
  static fromMethods(methods) {
27746
27890
 
27747
27891
  class Handler extends BaseCallbackHandler {
27748
- name = v4();
27892
+ name = v7();
27749
27893
  constructor() {
27750
27894
  super();
27751
27895
  Object.assign(this, methods);
@@ -27859,7 +28003,7 @@ function uuid7FromTime(timestamp) {
27859
28003
  return v72({ msecs, seq: 0 });
27860
28004
  }
27861
28005
  // ../../node_modules/langsmith/dist/index.js
27862
- var __version__ = "0.3.82";
28006
+ var __version__ = "0.4.2";
27863
28007
 
27864
28008
  // ../../node_modules/langsmith/dist/utils/env.js
27865
28009
  var globalEnv;
@@ -28823,6 +28967,23 @@ class LangSmithConflictError extends Error {
28823
28967
  this.status = 409;
28824
28968
  }
28825
28969
  }
28970
+
28971
+ class LangSmithNotFoundError extends Error {
28972
+ constructor(message) {
28973
+ super(message);
28974
+ Object.defineProperty(this, "status", {
28975
+ enumerable: true,
28976
+ configurable: true,
28977
+ writable: true,
28978
+ value: undefined
28979
+ });
28980
+ this.name = "LangSmithNotFoundError";
28981
+ this.status = 404;
28982
+ }
28983
+ }
28984
+ function isLangSmithNotFoundError(error) {
28985
+ return error != null && typeof error === "object" && "name" in error && error?.name === "LangSmithNotFoundError";
28986
+ }
28826
28987
  async function raiseForStatus(response, context, consumeOnSuccess) {
28827
28988
  let errorBody;
28828
28989
  if (response.ok) {
@@ -28852,6 +29013,9 @@ async function raiseForStatus(response, context, consumeOnSuccess) {
28852
29013
  }
28853
29014
  }
28854
29015
  const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Message: ${errorBody}`;
29016
+ if (response.status === 404) {
29017
+ throw new LangSmithNotFoundError(fullMessage);
29018
+ }
28855
29019
  if (response.status === 409) {
28856
29020
  throw new LangSmithConflictError(fullMessage);
28857
29021
  }
@@ -29030,7 +29194,10 @@ function replaceGetterValues(replacer) {
29030
29194
  }
29031
29195
 
29032
29196
  // ../../node_modules/langsmith/dist/client.js
29033
- function mergeRuntimeEnvIntoRun(run, cachedEnvVars) {
29197
+ function mergeRuntimeEnvIntoRun(run, cachedEnvVars, omitTracedRuntimeInfo) {
29198
+ if (omitTracedRuntimeInfo) {
29199
+ return run;
29200
+ }
29034
29201
  const runtimeEnv = getRuntimeEnvironment2();
29035
29202
  const envVars = cachedEnvVars ?? getLangSmithEnvVarsMetadata();
29036
29203
  const extra = run.extra ?? {};
@@ -29250,6 +29417,12 @@ class Client {
29250
29417
  writable: true,
29251
29418
  value: undefined
29252
29419
  });
29420
+ Object.defineProperty(this, "omitTracedRuntimeInfo", {
29421
+ enumerable: true,
29422
+ configurable: true,
29423
+ writable: true,
29424
+ value: undefined
29425
+ });
29253
29426
  Object.defineProperty(this, "tracingSampleRate", {
29254
29427
  enumerable: true,
29255
29428
  configurable: true,
@@ -29364,6 +29537,12 @@ class Client {
29364
29537
  writable: true,
29365
29538
  value: false
29366
29539
  });
29540
+ Object.defineProperty(this, "_multipartDisabled", {
29541
+ enumerable: true,
29542
+ configurable: true,
29543
+ writable: true,
29544
+ value: false
29545
+ });
29367
29546
  Object.defineProperty(this, "debug", {
29368
29547
  enumerable: true,
29369
29548
  configurable: true,
@@ -29405,6 +29584,7 @@ class Client {
29405
29584
  });
29406
29585
  this.hideInputs = config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs;
29407
29586
  this.hideOutputs = config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs;
29587
+ this.omitTracedRuntimeInfo = config.omitTracedRuntimeInfo ?? false;
29408
29588
  this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing;
29409
29589
  this.autoBatchQueue = new AutoBatchQueue(maxMemory);
29410
29590
  this.blockOnRootRunFinalization = config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization;
@@ -29628,11 +29808,11 @@ class Client {
29628
29808
  }
29629
29809
  async _getBatchSizeLimitBytes() {
29630
29810
  const serverInfo = await this._ensureServerInfo();
29631
- return this.batchSizeBytesLimit ?? serverInfo.batch_ingest_config?.size_limit_bytes ?? DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES;
29811
+ return this.batchSizeBytesLimit ?? serverInfo?.batch_ingest_config?.size_limit_bytes ?? DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES;
29632
29812
  }
29633
29813
  async _getBatchSizeLimit() {
29634
29814
  const serverInfo = await this._ensureServerInfo();
29635
- return this.batchSizeLimit ?? serverInfo.batch_ingest_config?.size_limit ?? DEFAULT_BATCH_SIZE_LIMIT;
29815
+ return this.batchSizeLimit ?? serverInfo?.batch_ingest_config?.size_limit ?? DEFAULT_BATCH_SIZE_LIMIT;
29636
29816
  }
29637
29817
  async _getDatasetExamplesMultiPartSupport() {
29638
29818
  const serverInfo = await this._ensureServerInfo();
@@ -29687,13 +29867,26 @@ class Client {
29687
29867
  runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item)
29688
29868
  };
29689
29869
  const serverInfo = await this._ensureServerInfo();
29690
- if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) {
29870
+ const useMultipart = !this._multipartDisabled && (serverInfo?.batch_ingest_config?.use_multipart_endpoint ?? true);
29871
+ if (useMultipart) {
29691
29872
  const useGzip = serverInfo?.instance_flags?.gzip_body_enabled;
29692
- await this.multipartIngestRuns(ingestParams, {
29693
- ...options,
29694
- useGzip,
29695
- sizeBytes: batchSizeBytes
29696
- });
29873
+ try {
29874
+ await this.multipartIngestRuns(ingestParams, {
29875
+ ...options,
29876
+ useGzip,
29877
+ sizeBytes: batchSizeBytes
29878
+ });
29879
+ } catch (e) {
29880
+ if (isLangSmithNotFoundError(e)) {
29881
+ this._multipartDisabled = true;
29882
+ await this.batchIngestRuns(ingestParams, {
29883
+ ...options,
29884
+ sizeBytes: batchSizeBytes
29885
+ });
29886
+ } else {
29887
+ throw e;
29888
+ }
29889
+ }
29697
29890
  } else {
29698
29891
  await this.batchIngestRuns(ingestParams, {
29699
29892
  ...options,
@@ -29735,7 +29928,7 @@ class Client {
29735
29928
  async processRunOperation(item) {
29736
29929
  clearTimeout(this.autoBatchTimeout);
29737
29930
  this.autoBatchTimeout = undefined;
29738
- item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata);
29931
+ item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo);
29739
29932
  const itemPromise = this.autoBatchQueue.push(item);
29740
29933
  if (this.manualFlushMode) {
29741
29934
  return itemPromise;
@@ -29850,7 +30043,7 @@ class Client {
29850
30043
  }).catch(console.error);
29851
30044
  return;
29852
30045
  }
29853
- const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata);
30046
+ const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo);
29854
30047
  if (options?.apiKey !== undefined) {
29855
30048
  headers["x-api-key"] = options.apiKey;
29856
30049
  }
@@ -30166,6 +30359,9 @@ class Client {
30166
30359
  res = await sendWithRetry(buildBuffered);
30167
30360
  }
30168
30361
  } catch (e) {
30362
+ if (isLangSmithNotFoundError(e)) {
30363
+ throw e;
30364
+ }
30169
30365
  console.warn(`${e.message.trim()}
30170
30366
 
30171
30367
  Context: ${context}`);
@@ -31338,6 +31534,39 @@ Message: ${Array.isArray(result.detail) ? result.detail.join(`
31338
31534
  return res;
31339
31535
  });
31340
31536
  }
31537
+ async deleteExamples(exampleIds, options) {
31538
+ exampleIds.forEach((id) => assertUuid(id));
31539
+ if (options?.hardDelete) {
31540
+ const path = this._getPlatformEndpointPath("datasets/examples/delete");
31541
+ await this.caller.call(async () => {
31542
+ const res = await this._fetch(`${this.apiUrl}${path}`, {
31543
+ method: "POST",
31544
+ headers: { ...this.headers, "Content-Type": "application/json" },
31545
+ body: JSON.stringify({
31546
+ example_ids: exampleIds,
31547
+ hard_delete: true
31548
+ }),
31549
+ signal: AbortSignal.timeout(this.timeout_ms),
31550
+ ...this.fetchOptions
31551
+ });
31552
+ await raiseForStatus(res, "hard delete examples", true);
31553
+ return res;
31554
+ });
31555
+ } else {
31556
+ const params = new URLSearchParams;
31557
+ exampleIds.forEach((id) => params.append("example_ids", id));
31558
+ await this.caller.call(async () => {
31559
+ const res = await this._fetch(`${this.apiUrl}/examples?${params.toString()}`, {
31560
+ method: "DELETE",
31561
+ headers: this.headers,
31562
+ signal: AbortSignal.timeout(this.timeout_ms),
31563
+ ...this.fetchOptions
31564
+ });
31565
+ await raiseForStatus(res, "delete examples", true);
31566
+ return res;
31567
+ });
31568
+ }
31569
+ }
31341
31570
  async updateExample(exampleIdOrUpdate, update) {
31342
31571
  let exampleId;
31343
31572
  if (update) {
@@ -31457,23 +31686,6 @@ Message: ${Array.isArray(result.detail) ? result.detail.join(`
31457
31686
  return res;
31458
31687
  });
31459
31688
  }
31460
- async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns, referenceExample } = { loadChildRuns: false }) {
31461
- warnOnce("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");
31462
- let run_;
31463
- if (typeof run === "string") {
31464
- run_ = await this.readRun(run, { loadChildRuns });
31465
- } else if (typeof run === "object" && "id" in run) {
31466
- run_ = run;
31467
- } else {
31468
- throw new Error(`Invalid run type: ${typeof run}`);
31469
- }
31470
- if (run_.reference_example_id !== null && run_.reference_example_id !== undefined) {
31471
- referenceExample = await this.readExample(run_.reference_example_id);
31472
- }
31473
- const feedbackResult = await evaluator.evaluateRun(run_, referenceExample);
31474
- const [_, feedbacks] = await this._logEvaluationFeedback(feedbackResult, run_, sourceInfo);
31475
- return feedbacks[0];
31476
- }
31477
31689
  async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId }) {
31478
31690
  if (!runId && !projectId) {
31479
31691
  throw new Error("One of runId or projectId must be provided");
@@ -32333,6 +32545,7 @@ Message: ${Array.isArray(result.detail) ? result.detail.join(`
32333
32545
  console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches.");
32334
32546
  return Promise.resolve();
32335
32547
  }
32548
+ await new Promise((resolve) => setTimeout(resolve, 1));
32336
32549
  await Promise.all([
32337
32550
  ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise),
32338
32551
  this.batchIngestCaller.queue.onIdle()
@@ -32357,6 +32570,7 @@ var isTracingEnabled = (tracingEnabled) => {
32357
32570
 
32358
32571
  // ../../node_modules/langsmith/dist/singletons/constants.js
32359
32572
  var _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables");
32573
+ var _LC_CHILD_RUN_END_PROMISES_KEY = Symbol.for("lc:child_run_end_promises");
32360
32574
  var _REPLICA_TRACE_ROOTS_KEY = Symbol.for("langsmith:replica_trace_roots");
32361
32575
 
32362
32576
  // ../../node_modules/langsmith/dist/utils/context_vars.js
@@ -32950,6 +33164,7 @@ class RunTree {
32950
33164
  await childRun.postRun(false);
32951
33165
  }
32952
33166
  }
33167
+ this.child_runs = [];
32953
33168
  } catch (error) {
32954
33169
  console.error(`Error in postRun for run ${this.id}:`, error);
32955
33170
  }
@@ -33022,6 +33237,7 @@ class RunTree {
33022
33237
  console.error(`Error in patchRun for run ${this.id}`, error);
33023
33238
  }
33024
33239
  }
33240
+ this.child_runs = [];
33025
33241
  }
33026
33242
  toJSON() {
33027
33243
  return this._convertToCreate(this, undefined, false);
@@ -33154,7 +33370,8 @@ function isCallbackManagerLike(x) {
33154
33370
  return typeof x === "object" && x != null && Array.isArray(x.handlers);
33155
33371
  }
33156
33372
  function isRunnableConfigLike(x) {
33157
- return x != null && typeof x.callbacks === "object" && (containsLangChainTracerLike(x.callbacks?.handlers) || containsLangChainTracerLike(x.callbacks));
33373
+ const callbacks = x?.callbacks;
33374
+ return x != null && typeof callbacks === "object" && (containsLangChainTracerLike(callbacks?.handlers) || containsLangChainTracerLike(callbacks));
33158
33375
  }
33159
33376
  function _getWriteReplicasFromEnv() {
33160
33377
  const envVar = getEnvironmentVariable2("LANGSMITH_RUNS_ENDPOINTS");
@@ -33295,7 +33512,7 @@ ${error.stack}` : "");
33295
33512
  const { dottedOrder: currentDottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(new Date(run.start_time).getTime(), run.id, run.execution_order);
33296
33513
  const storedRun = { ...run };
33297
33514
  const parentRun = this.getRunById(storedRun.parent_run_id);
33298
- if (storedRun.parent_run_id !== undefined) {
33515
+ if (storedRun.parent_run_id !== undefined)
33299
33516
  if (parentRun) {
33300
33517
  this._addChildRun(parentRun, storedRun);
33301
33518
  parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order);
@@ -33304,8 +33521,9 @@ ${error.stack}` : "");
33304
33521
  storedRun.dotted_order = [parentRun.dotted_order, currentDottedOrder].join(".");
33305
33522
  storedRun._serialized_start_time = microsecondPrecisionDatestring;
33306
33523
  }
33307
- }
33308
- } else {
33524
+ } else
33525
+ storedRun.parent_run_id = undefined;
33526
+ else {
33309
33527
  storedRun.trace_id = storedRun.id;
33310
33528
  storedRun.dotted_order = currentDottedOrder;
33311
33529
  storedRun._serialized_start_time = microsecondPrecisionDatestring;
@@ -33438,7 +33656,7 @@ ${error.stack}` : "");
33438
33656
  await this._endTrace(run);
33439
33657
  return run;
33440
33658
  }
33441
- _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {
33659
+ _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name, extra) {
33442
33660
  const execution_order = this._getExecutionOrder(parentRunId);
33443
33661
  const start_time = Date.now();
33444
33662
  const run = {
@@ -33456,7 +33674,10 @@ ${error.stack}` : "");
33456
33674
  child_execution_order: execution_order,
33457
33675
  run_type: runType ?? "chain",
33458
33676
  child_runs: [],
33459
- extra: metadata ? { metadata } : {},
33677
+ extra: metadata ? {
33678
+ ...extra,
33679
+ metadata
33680
+ } : { ...extra },
33460
33681
  tags: tags || []
33461
33682
  };
33462
33683
  return this._addRunToRunMap(run);
@@ -33827,6 +34048,14 @@ function isTraceableFunction(x) {
33827
34048
  // ../../node_modules/@langchain/core/dist/tracers/tracer_langchain.js
33828
34049
  var tracer_langchain_exports = {};
33829
34050
  __export(tracer_langchain_exports, { LangChainTracer: () => LangChainTracer });
34051
+ function _getUsageMetadataFromGenerations(generations) {
34052
+ let output = undefined;
34053
+ for (const generationBatch of generations)
34054
+ for (const generation of generationBatch)
34055
+ if (AIMessage.isInstance(generation.message) && generation.message.usage_metadata !== undefined)
34056
+ output = mergeUsageMetadata(output, generation.message.usage_metadata);
34057
+ return output;
34058
+ }
33830
34059
  var LangChainTracer = class LangChainTracer2 extends BaseTracer {
33831
34060
  name = "langchain_tracer";
33832
34061
  projectName;
@@ -33847,12 +34076,29 @@ var LangChainTracer = class LangChainTracer2 extends BaseTracer {
33847
34076
  }
33848
34077
  async persistRun(_run) {}
33849
34078
  async onRunCreate(run) {
33850
- const runTree = this.getRunTreeWithTracingConfig(run.id);
33851
- await runTree?.postRun();
34079
+ if (!run.extra?.lc_defers_inputs) {
34080
+ const runTree = this.getRunTreeWithTracingConfig(run.id);
34081
+ await runTree?.postRun();
34082
+ }
33852
34083
  }
33853
34084
  async onRunUpdate(run) {
33854
34085
  const runTree = this.getRunTreeWithTracingConfig(run.id);
33855
- await runTree?.patchRun();
34086
+ if (run.extra?.lc_defers_inputs)
34087
+ await runTree?.postRun();
34088
+ else
34089
+ await runTree?.patchRun();
34090
+ }
34091
+ onLLMEnd(run) {
34092
+ const outputs = run.outputs;
34093
+ if (outputs?.generations) {
34094
+ const usageMetadata = _getUsageMetadataFromGenerations(outputs.generations);
34095
+ if (usageMetadata !== undefined) {
34096
+ run.extra = run.extra ?? {};
34097
+ const metadata = run.extra.metadata ?? {};
34098
+ metadata.usage_metadata = usageMetadata;
34099
+ run.extra.metadata = metadata;
34100
+ }
34101
+ }
33856
34102
  }
33857
34103
  getRun(id) {
33858
34104
  return this.runTreeMap.get(id);
@@ -34246,7 +34492,7 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34246
34492
  }
34247
34493
  async handleLLMStart(llm, prompts, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34248
34494
  return Promise.all(prompts.map(async (prompt, idx) => {
34249
- const runId_ = idx === 0 && runId ? runId : v4();
34495
+ const runId_ = idx === 0 && runId ? runId : v7();
34250
34496
  await Promise.all(this.handlers.map((handler) => {
34251
34497
  if (handler.ignoreLLM)
34252
34498
  return;
@@ -34268,7 +34514,7 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34268
34514
  }
34269
34515
  async handleChatModelStart(llm, messages, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34270
34516
  return Promise.all(messages.map(async (messageGroup, idx) => {
34271
- const runId_ = idx === 0 && runId ? runId : v4();
34517
+ const runId_ = idx === 0 && runId ? runId : v7();
34272
34518
  await Promise.all(this.handlers.map((handler) => {
34273
34519
  if (handler.ignoreLLM)
34274
34520
  return;
@@ -34293,15 +34539,15 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34293
34539
  return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
34294
34540
  }));
34295
34541
  }
34296
- async handleChainStart(chain, inputs, runId = v4(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34542
+ async handleChainStart(chain, inputs, runId = v7(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined, _parentRunId = undefined, extra = undefined) {
34297
34543
  await Promise.all(this.handlers.map((handler) => {
34298
34544
  if (handler.ignoreChain)
34299
34545
  return;
34300
34546
  if (isBaseTracer(handler))
34301
- handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);
34547
+ handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName, extra);
34302
34548
  return consumeCallback(async () => {
34303
34549
  try {
34304
- await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);
34550
+ await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName, extra);
34305
34551
  } catch (err) {
34306
34552
  const logFunction = handler.raiseError ? console.error : console.warn;
34307
34553
  logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`);
@@ -34312,7 +34558,7 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34312
34558
  }));
34313
34559
  return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
34314
34560
  }
34315
- async handleToolStart(tool, input, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34561
+ async handleToolStart(tool, input, runId = v7(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34316
34562
  await Promise.all(this.handlers.map((handler) => {
34317
34563
  if (handler.ignoreAgent)
34318
34564
  return;
@@ -34331,7 +34577,7 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34331
34577
  }));
34332
34578
  return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
34333
34579
  }
34334
- async handleRetrieverStart(retriever, query, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34580
+ async handleRetrieverStart(retriever, query, runId = v7(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34335
34581
  await Promise.all(this.handlers.map((handler) => {
34336
34582
  if (handler.ignoreRetriever)
34337
34583
  return;
@@ -34429,7 +34675,7 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34429
34675
  static fromHandlers(handlers) {
34430
34676
 
34431
34677
  class Handler extends BaseCallbackHandler {
34432
- name = v4();
34678
+ name = v7();
34433
34679
  constructor() {
34434
34680
  super();
34435
34681
  Object.assign(this, handlers);
@@ -34688,7 +34934,12 @@ function ensureConfig(config) {
34688
34934
  if (empty.timeout !== undefined) {
34689
34935
  if (empty.timeout <= 0)
34690
34936
  throw new Error("Timeout must be a positive number");
34691
- const timeoutSignal = AbortSignal.timeout(empty.timeout);
34937
+ const originalTimeoutMs = empty.timeout;
34938
+ const timeoutSignal = AbortSignal.timeout(originalTimeoutMs);
34939
+ if (!empty.metadata)
34940
+ empty.metadata = {};
34941
+ if (empty.metadata.timeoutMs === undefined)
34942
+ empty.metadata.timeoutMs = originalTimeoutMs;
34692
34943
  if (empty.signal !== undefined) {
34693
34944
  if ("any" in AbortSignal)
34694
34945
  empty.signal = AbortSignal.any([empty.signal, timeoutSignal]);
@@ -35074,12 +35325,19 @@ __export(core_exports, {
35074
35325
  });
35075
35326
  var JsonPatchError = PatchError;
35076
35327
  var deepClone = _deepClone;
35328
+ function isDangerousKey(key) {
35329
+ return Object.getOwnPropertyNames(Object.prototype).includes(key);
35330
+ }
35077
35331
  var objOps = {
35078
35332
  add: function(obj, key, document2) {
35333
+ if (isDangerousKey(key))
35334
+ throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");
35079
35335
  obj[key] = this.value;
35080
35336
  return { newDocument: document2 };
35081
35337
  },
35082
35338
  remove: function(obj, key, document2) {
35339
+ if (isDangerousKey(key))
35340
+ throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");
35083
35341
  var removed = obj[key];
35084
35342
  delete obj[key];
35085
35343
  return {
@@ -35088,6 +35346,8 @@ var objOps = {
35088
35346
  };
35089
35347
  },
35090
35348
  replace: function(obj, key, document2) {
35349
+ if (isDangerousKey(key))
35350
+ throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons");
35091
35351
  var removed = obj[key];
35092
35352
  obj[key] = this.value;
35093
35353
  return {
@@ -35711,6 +35971,7 @@ var EventStreamCallbackHandler = class extends BaseTracer {
35711
35971
  transformStream;
35712
35972
  writer;
35713
35973
  receiveStream;
35974
+ readableStreamClosed = false;
35714
35975
  name = "event_stream_tracer";
35715
35976
  lc_prefer_streaming = true;
35716
35977
  constructor(fields) {
@@ -35725,7 +35986,9 @@ var EventStreamCallbackHandler = class extends BaseTracer {
35725
35986
  this.excludeNames = fields?.excludeNames;
35726
35987
  this.excludeTypes = fields?.excludeTypes;
35727
35988
  this.excludeTags = fields?.excludeTags;
35728
- this.transformStream = new TransformStream;
35989
+ this.transformStream = new TransformStream({ flush: () => {
35990
+ this.readableStreamClosed = true;
35991
+ } });
35729
35992
  this.writer = this.transformStream.writable.getWriter();
35730
35993
  this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable);
35731
35994
  }
@@ -35803,6 +36066,8 @@ var EventStreamCallbackHandler = class extends BaseTracer {
35803
36066
  }
35804
36067
  }
35805
36068
  async send(payload, run) {
36069
+ if (this.readableStreamClosed)
36070
+ return;
35806
36071
  if (this._includeRun(run))
35807
36072
  await this.writer.write(payload);
35808
36073
  }
@@ -36540,7 +36805,7 @@ function interopZodTransformInputSchemaImpl(schema, recursive, cache) {
36540
36805
  outputSchema = interopZodTransformInputSchemaImpl(schema._zod.def.in, recursive, cache);
36541
36806
  if (recursive) {
36542
36807
  if (isZodObjectV4(outputSchema)) {
36543
- const outputShape = outputSchema._zod.def.shape;
36808
+ const outputShape = {};
36544
36809
  for (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape))
36545
36810
  outputShape[key] = interopZodTransformInputSchemaImpl(keySchema, recursive, cache);
36546
36811
  outputSchema = clone(outputSchema, {
@@ -36631,16 +36896,24 @@ graph TD;
36631
36896
  edgeGroups[commonPrefix].push(edge);
36632
36897
  }
36633
36898
  const seenSubgraphs = /* @__PURE__ */ new Set;
36899
+ function sortPrefixesByDepth(prefixes) {
36900
+ return [...prefixes].sort((a, b) => {
36901
+ return a.split(":").length - b.split(":").length;
36902
+ });
36903
+ }
36634
36904
  function addSubgraph(edges$1, prefix) {
36635
36905
  const selfLoop = edges$1.length === 1 && edges$1[0].source === edges$1[0].target;
36636
36906
  if (prefix && !selfLoop) {
36637
36907
  const subgraph = prefix.split(":").pop();
36638
- if (seenSubgraphs.has(subgraph))
36639
- throw new Error(`Found duplicate subgraph '${subgraph}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);
36640
- seenSubgraphs.add(subgraph);
36908
+ if (seenSubgraphs.has(prefix))
36909
+ throw new Error(`Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);
36910
+ seenSubgraphs.add(prefix);
36641
36911
  mermaidGraph += ` subgraph ${subgraph}
36642
36912
  `;
36643
36913
  }
36914
+ const nestedPrefixes = sortPrefixesByDepth(Object.keys(edgeGroups).filter((nestedPrefix) => nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix && nestedPrefix.split(":").length === prefix.split(":").length + 1));
36915
+ for (const nestedPrefix of nestedPrefixes)
36916
+ addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);
36644
36917
  for (const edge of edges$1) {
36645
36918
  const { source, target, data, conditional } = edge;
36646
36919
  let edgeLabel = "";
@@ -36655,9 +36928,6 @@ graph TD;
36655
36928
  mermaidGraph += ` ${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};
36656
36929
  `;
36657
36930
  }
36658
- for (const nestedPrefix in edgeGroups)
36659
- if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix)
36660
- addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);
36661
36931
  if (prefix && !selfLoop)
36662
36932
  mermaidGraph += ` end
36663
36933
  `;
@@ -38980,14 +39250,14 @@ __export(json_schema_exports, {
38980
39250
  toJsonSchema: () => toJsonSchema,
38981
39251
  validatesOnlyStrings: () => validatesOnlyStrings
38982
39252
  });
38983
- function toJsonSchema(schema) {
39253
+ function toJsonSchema(schema, params) {
38984
39254
  if (isZodSchemaV4(schema)) {
38985
39255
  const inputSchema = interopZodTransformInputSchema(schema, true);
38986
39256
  if (isZodObjectV4(inputSchema)) {
38987
39257
  const strictSchema = interopZodObjectStrict(inputSchema, true);
38988
- return toJSONSchema(strictSchema);
39258
+ return toJSONSchema(strictSchema, params);
38989
39259
  } else
38990
- return toJSONSchema(schema);
39260
+ return toJSONSchema(schema, params);
38991
39261
  }
38992
39262
  if (isZodSchemaV3(schema))
38993
39263
  return zodToJsonSchema(schema);
@@ -39452,7 +39722,7 @@ var Runnable = class extends Serializable {
39452
39722
  }
39453
39723
  let runManager;
39454
39724
  try {
39455
- const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, undefined, undefined, config.runName ?? this.getName()), options?.signal, config);
39725
+ const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, undefined, undefined, config.runName ?? this.getName(), undefined, { lc_defers_inputs: true }), options?.signal, config);
39456
39726
  delete config.runId;
39457
39727
  runManager = pipe.setup;
39458
39728
  const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler);
@@ -50944,5 +51214,5 @@ export {
50944
51214
  ActionStreamFilter
50945
51215
  };
50946
51216
 
50947
- //# debugId=7435777E3B16550264756E2164756E21
51217
+ //# debugId=108305E81D5AB81564756E2164756E21
50948
51218
  //# sourceMappingURL=index.node.js.map