@elizaos/core 1.7.1-alpha.1 → 1.7.1-alpha.10

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,34 +25505,6 @@ 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
-
25536
25508
  // ../../node_modules/@langchain/core/dist/load/serializable.js
25537
25509
  var serializable_exports = {};
25538
25510
  __export(serializable_exports, {
@@ -25632,16 +25604,11 @@ var Serializable = class Serializable2 {
25632
25604
  if (last in read && read[last] !== undefined)
25633
25605
  write[last] = write[last] || read[last];
25634
25606
  });
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);
25640
25607
  return {
25641
25608
  lc: 1,
25642
25609
  type: "constructor",
25643
25610
  id: this.lc_id,
25644
- kwargs: processedKwargs
25611
+ kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases)
25645
25612
  };
25646
25613
  }
25647
25614
  toJSONNotImplemented() {
@@ -26384,7 +26351,7 @@ function convertToPrettyString(message) {
26384
26351
  lines.push(` Call ID: ${tc.id}`);
26385
26352
  lines.push(" Args:");
26386
26353
  for (const [key, value] of Object.entries(tc.args))
26387
- lines.push(` ${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`);
26354
+ lines.push(` ${key}: ${value}`);
26388
26355
  }
26389
26356
  }
26390
26357
  }
@@ -26631,10 +26598,10 @@ function _mergeLists(left, right) {
26631
26598
  }
26632
26599
  }
26633
26600
  function _mergeObj(left, right) {
26634
- if (left === undefined && right === undefined)
26635
- return;
26636
- if (left === undefined || right === undefined)
26637
- return left ?? right;
26601
+ if (!left && !right)
26602
+ throw new Error("Cannot merge two undefined objects.");
26603
+ if (!left || !right)
26604
+ return left || right;
26638
26605
  else if (typeof left !== typeof right)
26639
26606
  throw new Error(`Cannot merge objects of different types.
26640
26607
  Left ${typeof left}
@@ -27453,117 +27420,6 @@ function mergeUsageMetadata(a, b) {
27453
27420
  }
27454
27421
 
27455
27422
  // ../../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
- };
27567
27423
  var AIMessageChunk = class extends BaseMessageChunk {
27568
27424
  type = "ai";
27569
27425
  tool_calls = [];
@@ -27889,7 +27745,7 @@ var BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass {
27889
27745
  static fromMethods(methods) {
27890
27746
 
27891
27747
  class Handler extends BaseCallbackHandler {
27892
- name = v7();
27748
+ name = v4();
27893
27749
  constructor() {
27894
27750
  super();
27895
27751
  Object.assign(this, methods);
@@ -28003,7 +27859,7 @@ function uuid7FromTime(timestamp) {
28003
27859
  return v72({ msecs, seq: 0 });
28004
27860
  }
28005
27861
  // ../../node_modules/langsmith/dist/index.js
28006
- var __version__ = "0.4.2";
27862
+ var __version__ = "0.3.82";
28007
27863
 
28008
27864
  // ../../node_modules/langsmith/dist/utils/env.js
28009
27865
  var globalEnv;
@@ -28967,23 +28823,6 @@ class LangSmithConflictError extends Error {
28967
28823
  this.status = 409;
28968
28824
  }
28969
28825
  }
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
- }
28987
28826
  async function raiseForStatus(response, context, consumeOnSuccess) {
28988
28827
  let errorBody;
28989
28828
  if (response.ok) {
@@ -29013,9 +28852,6 @@ async function raiseForStatus(response, context, consumeOnSuccess) {
29013
28852
  }
29014
28853
  }
29015
28854
  const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Message: ${errorBody}`;
29016
- if (response.status === 404) {
29017
- throw new LangSmithNotFoundError(fullMessage);
29018
- }
29019
28855
  if (response.status === 409) {
29020
28856
  throw new LangSmithConflictError(fullMessage);
29021
28857
  }
@@ -29194,10 +29030,7 @@ function replaceGetterValues(replacer) {
29194
29030
  }
29195
29031
 
29196
29032
  // ../../node_modules/langsmith/dist/client.js
29197
- function mergeRuntimeEnvIntoRun(run, cachedEnvVars, omitTracedRuntimeInfo) {
29198
- if (omitTracedRuntimeInfo) {
29199
- return run;
29200
- }
29033
+ function mergeRuntimeEnvIntoRun(run, cachedEnvVars) {
29201
29034
  const runtimeEnv = getRuntimeEnvironment2();
29202
29035
  const envVars = cachedEnvVars ?? getLangSmithEnvVarsMetadata();
29203
29036
  const extra = run.extra ?? {};
@@ -29417,12 +29250,6 @@ class Client {
29417
29250
  writable: true,
29418
29251
  value: undefined
29419
29252
  });
29420
- Object.defineProperty(this, "omitTracedRuntimeInfo", {
29421
- enumerable: true,
29422
- configurable: true,
29423
- writable: true,
29424
- value: undefined
29425
- });
29426
29253
  Object.defineProperty(this, "tracingSampleRate", {
29427
29254
  enumerable: true,
29428
29255
  configurable: true,
@@ -29537,12 +29364,6 @@ class Client {
29537
29364
  writable: true,
29538
29365
  value: false
29539
29366
  });
29540
- Object.defineProperty(this, "_multipartDisabled", {
29541
- enumerable: true,
29542
- configurable: true,
29543
- writable: true,
29544
- value: false
29545
- });
29546
29367
  Object.defineProperty(this, "debug", {
29547
29368
  enumerable: true,
29548
29369
  configurable: true,
@@ -29584,7 +29405,6 @@ class Client {
29584
29405
  });
29585
29406
  this.hideInputs = config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs;
29586
29407
  this.hideOutputs = config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs;
29587
- this.omitTracedRuntimeInfo = config.omitTracedRuntimeInfo ?? false;
29588
29408
  this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing;
29589
29409
  this.autoBatchQueue = new AutoBatchQueue(maxMemory);
29590
29410
  this.blockOnRootRunFinalization = config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization;
@@ -29808,11 +29628,11 @@ class Client {
29808
29628
  }
29809
29629
  async _getBatchSizeLimitBytes() {
29810
29630
  const serverInfo = await this._ensureServerInfo();
29811
- return this.batchSizeBytesLimit ?? serverInfo?.batch_ingest_config?.size_limit_bytes ?? DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES;
29631
+ return this.batchSizeBytesLimit ?? serverInfo.batch_ingest_config?.size_limit_bytes ?? DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES;
29812
29632
  }
29813
29633
  async _getBatchSizeLimit() {
29814
29634
  const serverInfo = await this._ensureServerInfo();
29815
- return this.batchSizeLimit ?? serverInfo?.batch_ingest_config?.size_limit ?? DEFAULT_BATCH_SIZE_LIMIT;
29635
+ return this.batchSizeLimit ?? serverInfo.batch_ingest_config?.size_limit ?? DEFAULT_BATCH_SIZE_LIMIT;
29816
29636
  }
29817
29637
  async _getDatasetExamplesMultiPartSupport() {
29818
29638
  const serverInfo = await this._ensureServerInfo();
@@ -29867,26 +29687,13 @@ class Client {
29867
29687
  runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item)
29868
29688
  };
29869
29689
  const serverInfo = await this._ensureServerInfo();
29870
- const useMultipart = !this._multipartDisabled && (serverInfo?.batch_ingest_config?.use_multipart_endpoint ?? true);
29871
- if (useMultipart) {
29690
+ if (serverInfo?.batch_ingest_config?.use_multipart_endpoint) {
29872
29691
  const useGzip = serverInfo?.instance_flags?.gzip_body_enabled;
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
- }
29692
+ await this.multipartIngestRuns(ingestParams, {
29693
+ ...options,
29694
+ useGzip,
29695
+ sizeBytes: batchSizeBytes
29696
+ });
29890
29697
  } else {
29891
29698
  await this.batchIngestRuns(ingestParams, {
29892
29699
  ...options,
@@ -29928,7 +29735,7 @@ class Client {
29928
29735
  async processRunOperation(item) {
29929
29736
  clearTimeout(this.autoBatchTimeout);
29930
29737
  this.autoBatchTimeout = undefined;
29931
- item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo);
29738
+ item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata);
29932
29739
  const itemPromise = this.autoBatchQueue.push(item);
29933
29740
  if (this.manualFlushMode) {
29934
29741
  return itemPromise;
@@ -30043,7 +29850,7 @@ class Client {
30043
29850
  }).catch(console.error);
30044
29851
  return;
30045
29852
  }
30046
- const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo);
29853
+ const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata);
30047
29854
  if (options?.apiKey !== undefined) {
30048
29855
  headers["x-api-key"] = options.apiKey;
30049
29856
  }
@@ -30359,9 +30166,6 @@ class Client {
30359
30166
  res = await sendWithRetry(buildBuffered);
30360
30167
  }
30361
30168
  } catch (e) {
30362
- if (isLangSmithNotFoundError(e)) {
30363
- throw e;
30364
- }
30365
30169
  console.warn(`${e.message.trim()}
30366
30170
 
30367
30171
  Context: ${context}`);
@@ -31534,39 +31338,6 @@ Message: ${Array.isArray(result.detail) ? result.detail.join(`
31534
31338
  return res;
31535
31339
  });
31536
31340
  }
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
- }
31570
31341
  async updateExample(exampleIdOrUpdate, update) {
31571
31342
  let exampleId;
31572
31343
  if (update) {
@@ -31686,6 +31457,23 @@ Message: ${Array.isArray(result.detail) ? result.detail.join(`
31686
31457
  return res;
31687
31458
  });
31688
31459
  }
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
+ }
31689
31477
  async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId }) {
31690
31478
  if (!runId && !projectId) {
31691
31479
  throw new Error("One of runId or projectId must be provided");
@@ -32545,7 +32333,6 @@ Message: ${Array.isArray(result.detail) ? result.detail.join(`
32545
32333
  console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches.");
32546
32334
  return Promise.resolve();
32547
32335
  }
32548
- await new Promise((resolve) => setTimeout(resolve, 1));
32549
32336
  await Promise.all([
32550
32337
  ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise),
32551
32338
  this.batchIngestCaller.queue.onIdle()
@@ -32570,7 +32357,6 @@ var isTracingEnabled = (tracingEnabled) => {
32570
32357
 
32571
32358
  // ../../node_modules/langsmith/dist/singletons/constants.js
32572
32359
  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");
32574
32360
  var _REPLICA_TRACE_ROOTS_KEY = Symbol.for("langsmith:replica_trace_roots");
32575
32361
 
32576
32362
  // ../../node_modules/langsmith/dist/utils/context_vars.js
@@ -33164,7 +32950,6 @@ class RunTree {
33164
32950
  await childRun.postRun(false);
33165
32951
  }
33166
32952
  }
33167
- this.child_runs = [];
33168
32953
  } catch (error) {
33169
32954
  console.error(`Error in postRun for run ${this.id}:`, error);
33170
32955
  }
@@ -33237,7 +33022,6 @@ class RunTree {
33237
33022
  console.error(`Error in patchRun for run ${this.id}`, error);
33238
33023
  }
33239
33024
  }
33240
- this.child_runs = [];
33241
33025
  }
33242
33026
  toJSON() {
33243
33027
  return this._convertToCreate(this, undefined, false);
@@ -33370,8 +33154,7 @@ function isCallbackManagerLike(x) {
33370
33154
  return typeof x === "object" && x != null && Array.isArray(x.handlers);
33371
33155
  }
33372
33156
  function isRunnableConfigLike(x) {
33373
- const callbacks = x?.callbacks;
33374
- return x != null && typeof callbacks === "object" && (containsLangChainTracerLike(callbacks?.handlers) || containsLangChainTracerLike(callbacks));
33157
+ return x != null && typeof x.callbacks === "object" && (containsLangChainTracerLike(x.callbacks?.handlers) || containsLangChainTracerLike(x.callbacks));
33375
33158
  }
33376
33159
  function _getWriteReplicasFromEnv() {
33377
33160
  const envVar = getEnvironmentVariable2("LANGSMITH_RUNS_ENDPOINTS");
@@ -33512,7 +33295,7 @@ ${error.stack}` : "");
33512
33295
  const { dottedOrder: currentDottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(new Date(run.start_time).getTime(), run.id, run.execution_order);
33513
33296
  const storedRun = { ...run };
33514
33297
  const parentRun = this.getRunById(storedRun.parent_run_id);
33515
- if (storedRun.parent_run_id !== undefined)
33298
+ if (storedRun.parent_run_id !== undefined) {
33516
33299
  if (parentRun) {
33517
33300
  this._addChildRun(parentRun, storedRun);
33518
33301
  parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order);
@@ -33521,9 +33304,8 @@ ${error.stack}` : "");
33521
33304
  storedRun.dotted_order = [parentRun.dotted_order, currentDottedOrder].join(".");
33522
33305
  storedRun._serialized_start_time = microsecondPrecisionDatestring;
33523
33306
  }
33524
- } else
33525
- storedRun.parent_run_id = undefined;
33526
- else {
33307
+ }
33308
+ } else {
33527
33309
  storedRun.trace_id = storedRun.id;
33528
33310
  storedRun.dotted_order = currentDottedOrder;
33529
33311
  storedRun._serialized_start_time = microsecondPrecisionDatestring;
@@ -33656,7 +33438,7 @@ ${error.stack}` : "");
33656
33438
  await this._endTrace(run);
33657
33439
  return run;
33658
33440
  }
33659
- _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name, extra) {
33441
+ _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {
33660
33442
  const execution_order = this._getExecutionOrder(parentRunId);
33661
33443
  const start_time = Date.now();
33662
33444
  const run = {
@@ -33674,10 +33456,7 @@ ${error.stack}` : "");
33674
33456
  child_execution_order: execution_order,
33675
33457
  run_type: runType ?? "chain",
33676
33458
  child_runs: [],
33677
- extra: metadata ? {
33678
- ...extra,
33679
- metadata
33680
- } : { ...extra },
33459
+ extra: metadata ? { metadata } : {},
33681
33460
  tags: tags || []
33682
33461
  };
33683
33462
  return this._addRunToRunMap(run);
@@ -34048,14 +33827,6 @@ function isTraceableFunction(x) {
34048
33827
  // ../../node_modules/@langchain/core/dist/tracers/tracer_langchain.js
34049
33828
  var tracer_langchain_exports = {};
34050
33829
  __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
- }
34059
33830
  var LangChainTracer = class LangChainTracer2 extends BaseTracer {
34060
33831
  name = "langchain_tracer";
34061
33832
  projectName;
@@ -34076,29 +33847,12 @@ var LangChainTracer = class LangChainTracer2 extends BaseTracer {
34076
33847
  }
34077
33848
  async persistRun(_run) {}
34078
33849
  async onRunCreate(run) {
34079
- if (!run.extra?.lc_defers_inputs) {
34080
- const runTree = this.getRunTreeWithTracingConfig(run.id);
34081
- await runTree?.postRun();
34082
- }
33850
+ const runTree = this.getRunTreeWithTracingConfig(run.id);
33851
+ await runTree?.postRun();
34083
33852
  }
34084
33853
  async onRunUpdate(run) {
34085
33854
  const runTree = this.getRunTreeWithTracingConfig(run.id);
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
- }
33855
+ await runTree?.patchRun();
34102
33856
  }
34103
33857
  getRun(id) {
34104
33858
  return this.runTreeMap.get(id);
@@ -34492,7 +34246,7 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34492
34246
  }
34493
34247
  async handleLLMStart(llm, prompts, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34494
34248
  return Promise.all(prompts.map(async (prompt, idx) => {
34495
- const runId_ = idx === 0 && runId ? runId : v7();
34249
+ const runId_ = idx === 0 && runId ? runId : v4();
34496
34250
  await Promise.all(this.handlers.map((handler) => {
34497
34251
  if (handler.ignoreLLM)
34498
34252
  return;
@@ -34514,7 +34268,7 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34514
34268
  }
34515
34269
  async handleChatModelStart(llm, messages, runId = undefined, _parentRunId = undefined, extraParams = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34516
34270
  return Promise.all(messages.map(async (messageGroup, idx) => {
34517
- const runId_ = idx === 0 && runId ? runId : v7();
34271
+ const runId_ = idx === 0 && runId ? runId : v4();
34518
34272
  await Promise.all(this.handlers.map((handler) => {
34519
34273
  if (handler.ignoreLLM)
34520
34274
  return;
@@ -34539,15 +34293,15 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34539
34293
  return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
34540
34294
  }));
34541
34295
  }
34542
- async handleChainStart(chain, inputs, runId = v7(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined, _parentRunId = undefined, extra = undefined) {
34296
+ async handleChainStart(chain, inputs, runId = v4(), runType = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34543
34297
  await Promise.all(this.handlers.map((handler) => {
34544
34298
  if (handler.ignoreChain)
34545
34299
  return;
34546
34300
  if (isBaseTracer(handler))
34547
- handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName, extra);
34301
+ handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);
34548
34302
  return consumeCallback(async () => {
34549
34303
  try {
34550
- await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName, extra);
34304
+ await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName);
34551
34305
  } catch (err) {
34552
34306
  const logFunction = handler.raiseError ? console.error : console.warn;
34553
34307
  logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`);
@@ -34558,7 +34312,7 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34558
34312
  }));
34559
34313
  return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
34560
34314
  }
34561
- async handleToolStart(tool, input, runId = v7(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34315
+ async handleToolStart(tool, input, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34562
34316
  await Promise.all(this.handlers.map((handler) => {
34563
34317
  if (handler.ignoreAgent)
34564
34318
  return;
@@ -34577,7 +34331,7 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34577
34331
  }));
34578
34332
  return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
34579
34333
  }
34580
- async handleRetrieverStart(retriever, query, runId = v7(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34334
+ async handleRetrieverStart(retriever, query, runId = v4(), _parentRunId = undefined, _tags = undefined, _metadata = undefined, runName = undefined) {
34581
34335
  await Promise.all(this.handlers.map((handler) => {
34582
34336
  if (handler.ignoreRetriever)
34583
34337
  return;
@@ -34675,7 +34429,7 @@ var CallbackManager = class CallbackManager2 extends BaseCallbackManager {
34675
34429
  static fromHandlers(handlers) {
34676
34430
 
34677
34431
  class Handler extends BaseCallbackHandler {
34678
- name = v7();
34432
+ name = v4();
34679
34433
  constructor() {
34680
34434
  super();
34681
34435
  Object.assign(this, handlers);
@@ -34934,12 +34688,7 @@ function ensureConfig(config) {
34934
34688
  if (empty.timeout !== undefined) {
34935
34689
  if (empty.timeout <= 0)
34936
34690
  throw new Error("Timeout must be a positive number");
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;
34691
+ const timeoutSignal = AbortSignal.timeout(empty.timeout);
34943
34692
  if (empty.signal !== undefined) {
34944
34693
  if ("any" in AbortSignal)
34945
34694
  empty.signal = AbortSignal.any([empty.signal, timeoutSignal]);
@@ -35325,19 +35074,12 @@ __export(core_exports, {
35325
35074
  });
35326
35075
  var JsonPatchError = PatchError;
35327
35076
  var deepClone = _deepClone;
35328
- function isDangerousKey(key) {
35329
- return Object.getOwnPropertyNames(Object.prototype).includes(key);
35330
- }
35331
35077
  var objOps = {
35332
35078
  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");
35335
35079
  obj[key] = this.value;
35336
35080
  return { newDocument: document2 };
35337
35081
  },
35338
35082
  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");
35341
35083
  var removed = obj[key];
35342
35084
  delete obj[key];
35343
35085
  return {
@@ -35346,8 +35088,6 @@ var objOps = {
35346
35088
  };
35347
35089
  },
35348
35090
  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");
35351
35091
  var removed = obj[key];
35352
35092
  obj[key] = this.value;
35353
35093
  return {
@@ -35971,7 +35711,6 @@ var EventStreamCallbackHandler = class extends BaseTracer {
35971
35711
  transformStream;
35972
35712
  writer;
35973
35713
  receiveStream;
35974
- readableStreamClosed = false;
35975
35714
  name = "event_stream_tracer";
35976
35715
  lc_prefer_streaming = true;
35977
35716
  constructor(fields) {
@@ -35986,9 +35725,7 @@ var EventStreamCallbackHandler = class extends BaseTracer {
35986
35725
  this.excludeNames = fields?.excludeNames;
35987
35726
  this.excludeTypes = fields?.excludeTypes;
35988
35727
  this.excludeTags = fields?.excludeTags;
35989
- this.transformStream = new TransformStream({ flush: () => {
35990
- this.readableStreamClosed = true;
35991
- } });
35728
+ this.transformStream = new TransformStream;
35992
35729
  this.writer = this.transformStream.writable.getWriter();
35993
35730
  this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable);
35994
35731
  }
@@ -36066,8 +35803,6 @@ var EventStreamCallbackHandler = class extends BaseTracer {
36066
35803
  }
36067
35804
  }
36068
35805
  async send(payload, run) {
36069
- if (this.readableStreamClosed)
36070
- return;
36071
35806
  if (this._includeRun(run))
36072
35807
  await this.writer.write(payload);
36073
35808
  }
@@ -36805,7 +36540,7 @@ function interopZodTransformInputSchemaImpl(schema, recursive, cache) {
36805
36540
  outputSchema = interopZodTransformInputSchemaImpl(schema._zod.def.in, recursive, cache);
36806
36541
  if (recursive) {
36807
36542
  if (isZodObjectV4(outputSchema)) {
36808
- const outputShape = {};
36543
+ const outputShape = outputSchema._zod.def.shape;
36809
36544
  for (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape))
36810
36545
  outputShape[key] = interopZodTransformInputSchemaImpl(keySchema, recursive, cache);
36811
36546
  outputSchema = clone(outputSchema, {
@@ -36896,24 +36631,16 @@ graph TD;
36896
36631
  edgeGroups[commonPrefix].push(edge);
36897
36632
  }
36898
36633
  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
- }
36904
36634
  function addSubgraph(edges$1, prefix) {
36905
36635
  const selfLoop = edges$1.length === 1 && edges$1[0].source === edges$1[0].target;
36906
36636
  if (prefix && !selfLoop) {
36907
36637
  const subgraph = prefix.split(":").pop();
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);
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);
36911
36641
  mermaidGraph += ` subgraph ${subgraph}
36912
36642
  `;
36913
36643
  }
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);
36917
36644
  for (const edge of edges$1) {
36918
36645
  const { source, target, data, conditional } = edge;
36919
36646
  let edgeLabel = "";
@@ -36928,6 +36655,9 @@ graph TD;
36928
36655
  mermaidGraph += ` ${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};
36929
36656
  `;
36930
36657
  }
36658
+ for (const nestedPrefix in edgeGroups)
36659
+ if (nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix)
36660
+ addSubgraph(edgeGroups[nestedPrefix], nestedPrefix);
36931
36661
  if (prefix && !selfLoop)
36932
36662
  mermaidGraph += ` end
36933
36663
  `;
@@ -39250,14 +38980,14 @@ __export(json_schema_exports, {
39250
38980
  toJsonSchema: () => toJsonSchema,
39251
38981
  validatesOnlyStrings: () => validatesOnlyStrings
39252
38982
  });
39253
- function toJsonSchema(schema, params) {
38983
+ function toJsonSchema(schema) {
39254
38984
  if (isZodSchemaV4(schema)) {
39255
38985
  const inputSchema = interopZodTransformInputSchema(schema, true);
39256
38986
  if (isZodObjectV4(inputSchema)) {
39257
38987
  const strictSchema = interopZodObjectStrict(inputSchema, true);
39258
- return toJSONSchema(strictSchema, params);
38988
+ return toJSONSchema(strictSchema);
39259
38989
  } else
39260
- return toJSONSchema(schema, params);
38990
+ return toJSONSchema(schema);
39261
38991
  }
39262
38992
  if (isZodSchemaV3(schema))
39263
38993
  return zodToJsonSchema(schema);
@@ -39722,7 +39452,7 @@ var Runnable = class extends Serializable {
39722
39452
  }
39723
39453
  let runManager;
39724
39454
  try {
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);
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);
39726
39456
  delete config.runId;
39727
39457
  runManager = pipe.setup;
39728
39458
  const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler);
@@ -46804,43 +46534,81 @@ class DefaultMessageService {
46804
46534
  runtime.logger.warn({ src: "service:message", iteration: iterationCount }, "No providers or action specified, forcing completion");
46805
46535
  break;
46806
46536
  }
46807
- for (const providerName of providersArray) {
46808
- if (typeof providerName !== "string")
46809
- continue;
46537
+ const PROVIDERS_TOTAL_TIMEOUT_MS = parseInt(String(runtime.getSetting("PROVIDERS_TOTAL_TIMEOUT_MS") || "1000"));
46538
+ const completedProviders = new Set;
46539
+ const providerPromises = providersArray.filter((name) => typeof name === "string").map(async (providerName) => {
46810
46540
  const provider = runtime.providers.find((p) => p.name === providerName);
46811
46541
  if (!provider) {
46812
46542
  runtime.logger.warn({ src: "service:message", providerName }, "Provider not found");
46813
- traceActionResult.push({
46814
- data: { actionName: providerName },
46815
- success: false,
46816
- error: `Provider not found: ${providerName}`
46817
- });
46818
- continue;
46543
+ completedProviders.add(providerName);
46544
+ return { providerName, success: false, error: `Provider not found: ${providerName}` };
46819
46545
  }
46820
- const providerResult = await provider.get(runtime, message, state);
46821
- if (!providerResult) {
46822
- runtime.logger.warn({ src: "service:message", providerName }, "Provider returned no result");
46823
- traceActionResult.push({
46824
- data: { actionName: providerName },
46825
- success: false,
46826
- error: `Provider returned no result`
46827
- });
46828
- continue;
46546
+ try {
46547
+ const providerResult = await provider.get(runtime, message, state);
46548
+ completedProviders.add(providerName);
46549
+ if (!providerResult) {
46550
+ runtime.logger.warn({ src: "service:message", providerName }, "Provider returned no result");
46551
+ return { providerName, success: false, error: "Provider returned no result" };
46552
+ }
46553
+ const success = !!providerResult.text;
46554
+ return {
46555
+ providerName,
46556
+ success,
46557
+ text: success ? providerResult.text : undefined,
46558
+ error: success ? undefined : "Provider returned no result"
46559
+ };
46560
+ } catch (err) {
46561
+ completedProviders.add(providerName);
46562
+ const errorMsg = err instanceof Error ? err.message : String(err);
46563
+ runtime.logger.error({ src: "service:message", providerName, error: errorMsg }, "Provider execution failed");
46564
+ return { providerName, success: false, error: errorMsg };
46829
46565
  }
46830
- const success = !!providerResult.text;
46831
- traceActionResult.push({
46832
- data: { actionName: providerName },
46833
- success,
46834
- text: success ? providerResult.text : undefined,
46835
- error: success ? undefined : "Provider returned no result"
46836
- });
46566
+ });
46567
+ let timeoutId;
46568
+ const timeoutPromise = new Promise((resolve) => {
46569
+ timeoutId = setTimeout(() => resolve("timeout"), PROVIDERS_TOTAL_TIMEOUT_MS);
46570
+ });
46571
+ const allProvidersPromise = Promise.allSettled(providerPromises);
46572
+ const raceResult = await Promise.race([allProvidersPromise, timeoutPromise]);
46573
+ clearTimeout(timeoutId);
46574
+ if (raceResult === "timeout") {
46575
+ const allProviderNames = providersArray.filter((name) => typeof name === "string");
46576
+ const pendingProviders = allProviderNames.filter((name) => !completedProviders.has(name));
46577
+ runtime.logger.error({
46578
+ src: "service:message",
46579
+ timeoutMs: PROVIDERS_TOTAL_TIMEOUT_MS,
46580
+ pendingProviders,
46581
+ completedProviders: Array.from(completedProviders)
46582
+ }, `Providers took too long (>${PROVIDERS_TOTAL_TIMEOUT_MS}ms) - slow providers: ${pendingProviders.join(", ")}`);
46837
46583
  if (callback) {
46838
46584
  await callback({
46839
- text: `\uD83D\uDD0E Provider executed: ${providerName}`,
46840
- actions: [providerName],
46841
- thought: typeof thought === "string" ? thought : ""
46585
+ text: "Providers took too long to respond. Please optimize your providers or use caching.",
46586
+ actions: [],
46587
+ thought: "Provider timeout - pipeline aborted"
46842
46588
  });
46843
46589
  }
46590
+ return { responseContent: null, responseMessages: [], state, mode: "none" };
46591
+ }
46592
+ const providerResults = raceResult;
46593
+ for (const result of providerResults) {
46594
+ if (result.status === "fulfilled") {
46595
+ const { providerName, success, text, error } = result.value;
46596
+ traceActionResult.push({
46597
+ data: { actionName: providerName },
46598
+ success,
46599
+ text,
46600
+ error
46601
+ });
46602
+ if (callback) {
46603
+ await callback({
46604
+ text: `\uD83D\uDD0E Provider executed: ${providerName}`,
46605
+ actions: [providerName],
46606
+ thought: typeof thought === "string" ? thought : ""
46607
+ });
46608
+ }
46609
+ } else {
46610
+ runtime.logger.error({ src: "service:message", error: result.reason || "Unknown provider failure" }, "Unexpected provider promise rejection");
46611
+ }
46844
46612
  }
46845
46613
  if (action) {
46846
46614
  const actionContent = {
@@ -49130,6 +48898,41 @@ class AgentRuntime {
49130
48898
  modelSettings.presencePenalty = presencePenalty;
49131
48899
  return Object.keys(modelSettings).length > 0 ? modelSettings : null;
49132
48900
  }
48901
+ logModelCall(modelType, modelKey, params, promptContent, elapsedTime, provider, response) {
48902
+ if (modelKey !== ModelType.TEXT_EMBEDDING && promptContent) {
48903
+ if (this.currentActionContext) {
48904
+ this.currentActionContext.prompts.push({
48905
+ modelType: modelKey,
48906
+ prompt: promptContent,
48907
+ timestamp: Date.now()
48908
+ });
48909
+ }
48910
+ }
48911
+ this.adapter.log({
48912
+ entityId: this.agentId,
48913
+ roomId: this.currentRoomId ?? this.agentId,
48914
+ body: {
48915
+ modelType,
48916
+ modelKey,
48917
+ params: {
48918
+ ...typeof params === "object" && !Array.isArray(params) && params ? params : {},
48919
+ prompt: promptContent
48920
+ },
48921
+ prompt: promptContent,
48922
+ systemPrompt: this.character?.system || null,
48923
+ runId: this.getCurrentRunId(),
48924
+ timestamp: Date.now(),
48925
+ executionTime: elapsedTime,
48926
+ provider: provider || this.models.get(modelKey)?.[0]?.provider || "unknown",
48927
+ actionContext: this.currentActionContext ? {
48928
+ actionName: this.currentActionContext.actionName,
48929
+ actionId: this.currentActionContext.actionId
48930
+ } : undefined,
48931
+ response: Array.isArray(response) && response.every((x) => typeof x === "number") ? "[array]" : response
48932
+ },
48933
+ type: `useModel:${modelKey}`
48934
+ });
48935
+ }
49133
48936
  async useModel(modelType, params, provider) {
49134
48937
  const modelKey = typeof modelType === "string" ? modelType : ModelType[modelType];
49135
48938
  const paramsObj = params;
@@ -49224,6 +49027,7 @@ class AgentRuntime {
49224
49027
  duration: Number(elapsedTime2.toFixed(2)),
49225
49028
  streaming: true
49226
49029
  }, "Model output (stream with callback complete)");
49030
+ this.logModelCall(modelType, modelKey, params, promptContent, elapsedTime2, provider, fullText);
49227
49031
  return fullText;
49228
49032
  }
49229
49033
  const elapsedTime = (typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now()) - startTime;
@@ -49233,39 +49037,7 @@ class AgentRuntime {
49233
49037
  model: modelKey,
49234
49038
  duration: Number(elapsedTime.toFixed(2))
49235
49039
  }, "Model output");
49236
- if (modelKey !== ModelType.TEXT_EMBEDDING && promptContent) {
49237
- if (this.currentActionContext) {
49238
- this.currentActionContext.prompts.push({
49239
- modelType: modelKey,
49240
- prompt: promptContent,
49241
- timestamp: Date.now()
49242
- });
49243
- }
49244
- }
49245
- this.adapter.log({
49246
- entityId: this.agentId,
49247
- roomId: this.currentRoomId ?? this.agentId,
49248
- body: {
49249
- modelType,
49250
- modelKey,
49251
- params: {
49252
- ...typeof params === "object" && !Array.isArray(params) && params ? params : {},
49253
- prompt: promptContent
49254
- },
49255
- prompt: promptContent,
49256
- systemPrompt: this.character?.system || null,
49257
- runId: this.getCurrentRunId(),
49258
- timestamp: Date.now(),
49259
- executionTime: elapsedTime,
49260
- provider: provider || this.models.get(modelKey)?.[0]?.provider || "unknown",
49261
- actionContext: this.currentActionContext ? {
49262
- actionName: this.currentActionContext.actionName,
49263
- actionId: this.currentActionContext.actionId
49264
- } : undefined,
49265
- response: Array.isArray(response) && response.every((x) => typeof x === "number") ? "[array]" : response
49266
- },
49267
- type: `useModel:${modelKey}`
49268
- });
49040
+ this.logModelCall(modelType, modelKey, params, promptContent, elapsedTime, provider, response);
49269
49041
  return response;
49270
49042
  }
49271
49043
  async generateText(input, options) {
@@ -51214,5 +50986,5 @@ export {
51214
50986
  ActionStreamFilter
51215
50987
  };
51216
50988
 
51217
- //# debugId=108305E81D5AB81564756E2164756E21
50989
+ //# debugId=EE3A137370E73D0264756E2164756E21
51218
50990
  //# sourceMappingURL=index.node.js.map