@langchain/core 0.2.15 → 0.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/caches.cjs +1 -1
  2. package/caches.d.cts +1 -1
  3. package/caches.d.ts +1 -1
  4. package/caches.js +1 -1
  5. package/callbacks/dispatch/web.cjs +1 -0
  6. package/callbacks/dispatch/web.d.cts +1 -0
  7. package/callbacks/dispatch/web.d.ts +1 -0
  8. package/callbacks/dispatch/web.js +1 -0
  9. package/callbacks/dispatch.cjs +1 -0
  10. package/callbacks/dispatch.d.cts +1 -0
  11. package/callbacks/dispatch.d.ts +1 -0
  12. package/callbacks/dispatch.js +1 -0
  13. package/dist/{caches.cjs → caches/base.cjs} +6 -6
  14. package/dist/{caches.d.ts → caches/base.d.ts} +7 -7
  15. package/dist/{caches.js → caches/base.js} +6 -6
  16. package/dist/caches/tests/in_memory_cache.test.d.ts +1 -0
  17. package/dist/caches/tests/in_memory_cache.test.js +33 -0
  18. package/dist/callbacks/base.cjs +8 -0
  19. package/dist/callbacks/base.d.ts +16 -10
  20. package/dist/callbacks/base.js +8 -0
  21. package/dist/callbacks/dispatch/index.cjs +49 -0
  22. package/dist/callbacks/dispatch/index.d.ts +35 -0
  23. package/dist/callbacks/dispatch/index.js +45 -0
  24. package/dist/callbacks/dispatch/web.cjs +61 -0
  25. package/dist/callbacks/dispatch/web.d.ts +32 -0
  26. package/dist/callbacks/dispatch/web.js +57 -0
  27. package/dist/callbacks/manager.cjs +20 -0
  28. package/dist/callbacks/manager.d.ts +2 -1
  29. package/dist/callbacks/manager.js +20 -0
  30. package/dist/language_models/base.cjs +4 -4
  31. package/dist/language_models/base.d.ts +2 -2
  32. package/dist/language_models/base.js +1 -1
  33. package/dist/language_models/chat_models.d.ts +22 -5
  34. package/dist/language_models/llms.d.ts +1 -1
  35. package/dist/language_models/tests/chat_models.test.js +33 -0
  36. package/dist/load/import_map.cjs +2 -2
  37. package/dist/load/import_map.d.ts +2 -2
  38. package/dist/load/import_map.js +2 -2
  39. package/dist/messages/ai.cjs +19 -0
  40. package/dist/messages/ai.d.ts +2 -0
  41. package/dist/messages/ai.js +19 -0
  42. package/dist/messages/base.cjs +95 -5
  43. package/dist/messages/base.d.ts +5 -1
  44. package/dist/messages/base.js +93 -4
  45. package/dist/messages/chat.cjs +12 -0
  46. package/dist/messages/chat.d.ts +2 -0
  47. package/dist/messages/chat.js +12 -0
  48. package/dist/messages/index.cjs +1 -0
  49. package/dist/messages/index.d.ts +2 -1
  50. package/dist/messages/index.js +1 -0
  51. package/dist/messages/modifier.cjs +35 -0
  52. package/dist/messages/modifier.d.ts +19 -0
  53. package/dist/messages/modifier.js +31 -0
  54. package/dist/messages/tests/base_message.test.js +134 -2
  55. package/dist/messages/tests/message_utils.test.js +54 -2
  56. package/dist/messages/tool.cjs +45 -0
  57. package/dist/messages/tool.d.ts +29 -0
  58. package/dist/messages/tool.js +46 -1
  59. package/dist/messages/transformers.cjs +6 -0
  60. package/dist/messages/transformers.d.ts +3 -2
  61. package/dist/messages/transformers.js +6 -0
  62. package/dist/messages/utils.cjs +5 -1
  63. package/dist/messages/utils.js +5 -1
  64. package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +2 -0
  65. package/dist/output_parsers/openai_tools/json_output_tools_parsers.js +2 -0
  66. package/dist/runnables/base.cjs +104 -1
  67. package/dist/runnables/base.d.ts +50 -0
  68. package/dist/runnables/base.js +101 -0
  69. package/dist/runnables/index.cjs +2 -1
  70. package/dist/runnables/index.d.ts +1 -1
  71. package/dist/runnables/index.js +1 -1
  72. package/dist/runnables/tests/runnable_stream_events.test.js +1 -1
  73. package/dist/runnables/tests/runnable_stream_events_v2.test.js +106 -1
  74. package/dist/runnables/tests/runnable_tools.test.d.ts +1 -0
  75. package/dist/runnables/tests/runnable_tools.test.js +149 -0
  76. package/dist/{tools.cjs → tools/index.cjs} +135 -47
  77. package/dist/{tools.d.ts → tools/index.d.ts} +76 -47
  78. package/dist/{tools.js → tools/index.js} +134 -45
  79. package/dist/tools/tests/tools.test.d.ts +1 -0
  80. package/dist/tools/tests/tools.test.js +85 -0
  81. package/dist/tools/utils.cjs +28 -0
  82. package/dist/tools/utils.d.ts +11 -0
  83. package/dist/tools/utils.js +23 -0
  84. package/dist/tracers/base.cjs +1 -0
  85. package/dist/tracers/base.d.ts +1 -1
  86. package/dist/tracers/base.js +1 -0
  87. package/dist/tracers/event_stream.cjs +15 -0
  88. package/dist/tracers/event_stream.d.ts +1 -0
  89. package/dist/tracers/event_stream.js +15 -0
  90. package/dist/types/zod.cjs +2 -0
  91. package/dist/types/zod.d.ts +2 -0
  92. package/dist/types/zod.js +1 -0
  93. package/dist/utils/function_calling.cjs +38 -10
  94. package/dist/utils/function_calling.d.ts +32 -11
  95. package/dist/utils/function_calling.js +36 -9
  96. package/dist/utils/testing/index.cjs +10 -3
  97. package/dist/utils/testing/index.d.ts +1 -1
  98. package/dist/utils/testing/index.js +9 -2
  99. package/package.json +28 -1
  100. package/tools.cjs +1 -1
  101. package/tools.d.cts +1 -1
  102. package/tools.d.ts +1 -1
  103. package/tools.js +1 -1
@@ -93,7 +93,7 @@ export declare class CallbackManagerForChainRun extends BaseRunManager implement
93
93
  export declare class CallbackManagerForToolRun extends BaseRunManager implements BaseCallbackManagerMethods {
94
94
  getChild(tag?: string): CallbackManager;
95
95
  handleToolError(err: Error | unknown): Promise<void>;
96
- handleToolEnd(output: string): Promise<void>;
96
+ handleToolEnd(output: any): Promise<void>;
97
97
  }
98
98
  /**
99
99
  * @example
@@ -141,6 +141,7 @@ export declare class CallbackManager extends BaseCallbackManager implements Base
141
141
  handleChainStart(chain: Serialized, inputs: ChainValues, runId?: string, runType?: string | undefined, _tags?: string[] | undefined, _metadata?: Record<string, unknown> | undefined, runName?: string | undefined): Promise<CallbackManagerForChainRun>;
142
142
  handleToolStart(tool: Serialized, input: string, runId?: string, _parentRunId?: string | undefined, _tags?: string[] | undefined, _metadata?: Record<string, unknown> | undefined, runName?: string | undefined): Promise<CallbackManagerForToolRun>;
143
143
  handleRetrieverStart(retriever: Serialized, query: string, runId?: string, _parentRunId?: string | undefined, _tags?: string[] | undefined, _metadata?: Record<string, unknown> | undefined, runName?: string | undefined): Promise<CallbackManagerForRetrieverRun>;
144
+ handleCustomEvent?(eventName: string, data: any, runId: string, _tags?: string[], _metadata?: Record<string, any>): Promise<any>;
144
145
  addHandler(handler: BaseCallbackHandler, inherit?: boolean): void;
145
146
  removeHandler(handler: BaseCallbackHandler): void;
146
147
  setHandlers(handlers: BaseCallbackHandler[], inherit?: boolean): void;
@@ -299,6 +299,7 @@ export class CallbackManagerForToolRun extends BaseRunManager {
299
299
  }
300
300
  }, handler.awaitHandlers)));
301
301
  }
302
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
302
303
  async handleToolEnd(output) {
303
304
  await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
304
305
  if (!handler.ignoreAgent) {
@@ -496,6 +497,25 @@ export class CallbackManager extends BaseCallbackManager {
496
497
  }, handler.awaitHandlers)));
497
498
  return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId);
498
499
  }
500
+ async handleCustomEvent(eventName,
501
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
502
+ data, runId, _tags,
503
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
504
+ _metadata) {
505
+ await Promise.all(this.handlers.map((handler) => consumeCallback(async () => {
506
+ if (!handler.ignoreCustomEvent) {
507
+ try {
508
+ await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata);
509
+ }
510
+ catch (err) {
511
+ console.error(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`);
512
+ if (handler.raiseError) {
513
+ throw err;
514
+ }
515
+ }
516
+ }
517
+ }, handler.awaitHandlers)));
518
+ }
499
519
  addHandler(handler, inherit = true) {
500
520
  this.handlers.push(handler);
501
521
  if (inherit) {
@@ -1,12 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BaseLanguageModel = exports.BaseLangChain = exports.calculateMaxTokens = exports.isOpenAITool = exports.getModelContextSize = exports.getEmbeddingContextSize = exports.getModelNameForTiktoken = void 0;
4
- const caches_js_1 = require("../caches.cjs");
4
+ const base_js_1 = require("../caches/base.cjs");
5
5
  const prompt_values_js_1 = require("../prompt_values.cjs");
6
6
  const utils_js_1 = require("../messages/utils.cjs");
7
7
  const async_caller_js_1 = require("../utils/async_caller.cjs");
8
8
  const tiktoken_js_1 = require("../utils/tiktoken.cjs");
9
- const base_js_1 = require("../runnables/base.cjs");
9
+ const base_js_2 = require("../runnables/base.cjs");
10
10
  // https://www.npmjs.com/package/js-tiktoken
11
11
  const getModelNameForTiktoken = (modelName) => {
12
12
  if (modelName.startsWith("gpt-3.5-turbo-16k")) {
@@ -102,7 +102,7 @@ const getVerbosity = () => false;
102
102
  /**
103
103
  * Base class for language models, chains, tools.
104
104
  */
105
- class BaseLangChain extends base_js_1.Runnable {
105
+ class BaseLangChain extends base_js_2.Runnable {
106
106
  get lc_attributes() {
107
107
  return {
108
108
  callbacks: undefined,
@@ -186,7 +186,7 @@ class BaseLanguageModel extends BaseLangChain {
186
186
  this.cache = params.cache;
187
187
  }
188
188
  else if (params.cache) {
189
- this.cache = caches_js_1.InMemoryCache.global();
189
+ this.cache = base_js_1.InMemoryCache.global();
190
190
  }
191
191
  else {
192
192
  this.cache = undefined;
@@ -1,6 +1,6 @@
1
1
  import type { TiktokenModel } from "js-tiktoken/lite";
2
2
  import { z } from "zod";
3
- import { type BaseCache } from "../caches.js";
3
+ import { type BaseCache } from "../caches/base.js";
4
4
  import { type BasePromptValueInterface } from "../prompt_values.js";
5
5
  import { type BaseMessage, type BaseMessageLike, type MessageContent } from "../messages/base.js";
6
6
  import { type LLMResult } from "../outputs.js";
@@ -186,7 +186,7 @@ export declare abstract class BaseLanguageModel<RunOutput = any, CallOptions ext
186
186
  * @param callOptions Call options for the model
187
187
  * @returns A unique cache key.
188
188
  */
189
- protected _getSerializedCacheKeyParametersForCall({ config, ...callOptions }: CallOptions & {
189
+ _getSerializedCacheKeyParametersForCall({ config, ...callOptions }: CallOptions & {
190
190
  config?: RunnableConfig;
191
191
  }): string;
192
192
  /**
@@ -1,4 +1,4 @@
1
- import { InMemoryCache } from "../caches.js";
1
+ import { InMemoryCache } from "../caches/base.js";
2
2
  import { StringPromptValue, ChatPromptValue, } from "../prompt_values.js";
3
3
  import { coerceMessageLikeToMessage } from "../messages/utils.js";
4
4
  import { AsyncCaller } from "../utils/async_caller.js";
@@ -5,9 +5,10 @@ import { LLMResult, ChatGenerationChunk, type ChatResult, type Generation } from
5
5
  import { BaseLanguageModel, StructuredOutputMethodOptions, ToolDefinition, type BaseLanguageModelCallOptions, type BaseLanguageModelInput, type BaseLanguageModelParams } from "./base.js";
6
6
  import { type CallbackManagerForLLMRun, type Callbacks } from "../callbacks/manager.js";
7
7
  import type { RunnableConfig } from "../runnables/config.js";
8
- import type { BaseCache } from "../caches.js";
9
- import { StructuredToolInterface } from "../tools.js";
10
- import { Runnable } from "../runnables/base.js";
8
+ import type { BaseCache } from "../caches/base.js";
9
+ import { StructuredToolInterface } from "../tools/index.js";
10
+ import { Runnable, RunnableToolLike } from "../runnables/base.js";
11
+ type ToolChoice = string | Record<string, any> | "auto" | "any";
11
12
  /**
12
13
  * Represents a serialized chat model.
13
14
  */
@@ -29,7 +30,23 @@ export type BaseChatModelParams = BaseLanguageModelParams;
29
30
  /**
30
31
  * Represents the call options for a base chat model.
31
32
  */
32
- export type BaseChatModelCallOptions = BaseLanguageModelCallOptions;
33
+ export type BaseChatModelCallOptions = BaseLanguageModelCallOptions & {
34
+ /**
35
+ * Specifies how the chat model should use tools.
36
+ * @default undefined
37
+ *
38
+ * Possible values:
39
+ * - "auto": The model may choose to use any of the provided tools, or none.
40
+ * - "any": The model must use one of the provided tools.
41
+ * - "none": The model must not use any tools.
42
+ * - A string (not "auto", "any", or "none"): The name of a specific tool the model must use.
43
+ * - An object: A custom schema specifying tool choice parameters. Specific to the provider.
44
+ *
45
+ * Note: Not all providers support tool_choice. An error will be thrown
46
+ * if used with an unsupported model.
47
+ */
48
+ tool_choice?: ToolChoice;
49
+ };
33
50
  /**
34
51
  * Creates a transform stream for encoding chat message chunks.
35
52
  * @deprecated Use {@link BytesOutputParser} instead
@@ -69,7 +86,7 @@ export declare abstract class BaseChatModel<CallOptions extends BaseChatModelCal
69
86
  * matching the provider's specific tool schema.
70
87
  * @param kwargs Any additional parameters to bind.
71
88
  */
72
- bindTools?(tools: (StructuredToolInterface | Record<string, unknown> | ToolDefinition)[], kwargs?: Partial<CallOptions>): Runnable<BaseLanguageModelInput, OutputMessageType, CallOptions>;
89
+ bindTools?(tools: (StructuredToolInterface | Record<string, unknown> | ToolDefinition | RunnableToolLike)[], kwargs?: Partial<CallOptions>): Runnable<BaseLanguageModelInput, OutputMessageType, CallOptions>;
73
90
  /**
74
91
  * Invokes the chat model with a single input.
75
92
  * @param input The input for the language model.
@@ -4,7 +4,7 @@ import { type LLMResult, type Generation, GenerationChunk } from "../outputs.js"
4
4
  import { type BaseCallbackConfig, type CallbackManagerForLLMRun, type Callbacks } from "../callbacks/manager.js";
5
5
  import { BaseLanguageModel, type BaseLanguageModelCallOptions, type BaseLanguageModelInput, type BaseLanguageModelParams } from "./base.js";
6
6
  import type { RunnableConfig } from "../runnables/config.js";
7
- import type { BaseCache } from "../caches.js";
7
+ import type { BaseCache } from "../caches/base.js";
8
8
  export type SerializedLLM = {
9
9
  _model: string;
10
10
  _type: string;
@@ -3,6 +3,8 @@ import { test } from "@jest/globals";
3
3
  import { z } from "zod";
4
4
  import { zodToJsonSchema } from "zod-to-json-schema";
5
5
  import { FakeChatModel, FakeListChatModel } from "../../utils/testing/index.js";
6
+ import { HumanMessage } from "../../messages/human.js";
7
+ import { getBufferString } from "../../messages/utils.js";
6
8
  test("Test ChatModel accepts array shorthand for messages", async () => {
7
9
  const model = new FakeChatModel({});
8
10
  const response = await model.invoke([["human", "Hello there!"]]);
@@ -169,3 +171,34 @@ test("Test ChatModel withStructuredOutput new syntax and includeRaw", async () =
169
171
  // No error
170
172
  console.log(response.parsed);
171
173
  });
174
+ test("Test ChatModel can cache complex messages", async () => {
175
+ const model = new FakeChatModel({
176
+ cache: true,
177
+ });
178
+ if (!model.cache) {
179
+ throw new Error("Cache not enabled");
180
+ }
181
+ const contentToCache = [
182
+ {
183
+ type: "text",
184
+ text: "Hello there!",
185
+ },
186
+ ];
187
+ const humanMessage = new HumanMessage({
188
+ content: contentToCache,
189
+ });
190
+ const prompt = getBufferString([humanMessage]);
191
+ const llmKey = model._getSerializedCacheKeyParametersForCall({});
192
+ // Invoke model to trigger cache update
193
+ await model.invoke([humanMessage]);
194
+ const value = await model.cache.lookup(prompt, llmKey);
195
+ expect(value).toBeDefined();
196
+ if (!value)
197
+ return;
198
+ expect(value[0].text).toEqual(JSON.stringify(contentToCache, null, 2));
199
+ expect("message" in value[0]).toBeTruthy();
200
+ if (!("message" in value[0]))
201
+ return;
202
+ const cachedMsg = value[0].message;
203
+ expect(cachedMsg.content).toEqual(JSON.stringify(contentToCache, null, 2));
204
+ });
@@ -26,7 +26,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
26
26
  Object.defineProperty(exports, "__esModule", { value: true });
27
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__function_calling = exports.utils__env = exports.utils__chunk_array = exports.utils__async_caller = exports.tracers__tracer_langchain_v1 = 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
- exports.caches = __importStar(require("../caches.cjs"));
29
+ exports.caches = __importStar(require("../caches/base.cjs"));
30
30
  exports.callbacks__base = __importStar(require("../callbacks/base.cjs"));
31
31
  exports.callbacks__manager = __importStar(require("../callbacks/manager.cjs"));
32
32
  exports.callbacks__promises = __importStar(require("../callbacks/promises.cjs"));
@@ -47,7 +47,7 @@ exports.prompt_values = __importStar(require("../prompt_values.cjs"));
47
47
  exports.runnables = __importStar(require("../runnables/index.cjs"));
48
48
  exports.retrievers = __importStar(require("../retrievers/index.cjs"));
49
49
  exports.stores = __importStar(require("../stores.cjs"));
50
- exports.tools = __importStar(require("../tools.cjs"));
50
+ exports.tools = __importStar(require("../tools/index.cjs"));
51
51
  exports.tracers__base = __importStar(require("../tracers/base.cjs"));
52
52
  exports.tracers__console = __importStar(require("../tracers/console.cjs"));
53
53
  exports.tracers__initialize = __importStar(require("../tracers/initialize.cjs"));
@@ -1,5 +1,5 @@
1
1
  export * as agents from "../agents.js";
2
- export * as caches from "../caches.js";
2
+ export * as caches from "../caches/base.js";
3
3
  export * as callbacks__base from "../callbacks/base.js";
4
4
  export * as callbacks__manager from "../callbacks/manager.js";
5
5
  export * as callbacks__promises from "../callbacks/promises.js";
@@ -20,7 +20,7 @@ export * as prompt_values from "../prompt_values.js";
20
20
  export * as runnables from "../runnables/index.js";
21
21
  export * as retrievers from "../retrievers/index.js";
22
22
  export * as stores from "../stores.js";
23
- export * as tools from "../tools.js";
23
+ export * as tools from "../tools/index.js";
24
24
  export * as tracers__base from "../tracers/base.js";
25
25
  export * as tracers__console from "../tracers/console.js";
26
26
  export * as tracers__initialize from "../tracers/initialize.js";
@@ -1,6 +1,6 @@
1
1
  // Auto-generated by `scripts/create-entrypoints.js`. Do not edit manually.
2
2
  export * as agents from "../agents.js";
3
- export * as caches from "../caches.js";
3
+ export * as caches from "../caches/base.js";
4
4
  export * as callbacks__base from "../callbacks/base.js";
5
5
  export * as callbacks__manager from "../callbacks/manager.js";
6
6
  export * as callbacks__promises from "../callbacks/promises.js";
@@ -21,7 +21,7 @@ export * as prompt_values from "../prompt_values.js";
21
21
  export * as runnables from "../runnables/index.js";
22
22
  export * as retrievers from "../retrievers/index.js";
23
23
  export * as stores from "../stores.js";
24
- export * as tools from "../tools.js";
24
+ export * as tools from "../tools/index.js";
25
25
  export * as tracers__base from "../tracers/base.js";
26
26
  export * as tracers__console from "../tracers/console.js";
27
27
  export * as tracers__initialize from "../tracers/initialize.js";
@@ -98,6 +98,14 @@ class AIMessage extends base_js_1.BaseMessage {
98
98
  _getType() {
99
99
  return "ai";
100
100
  }
101
+ get _printableFields() {
102
+ return {
103
+ ...super._printableFields,
104
+ tool_calls: this.tool_calls,
105
+ invalid_tool_calls: this.invalid_tool_calls,
106
+ usage_metadata: this.usage_metadata,
107
+ };
108
+ }
101
109
  }
102
110
  exports.AIMessage = AIMessage;
103
111
  function isAIMessage(x) {
@@ -141,6 +149,7 @@ class AIMessageChunk extends base_js_1.BaseMessageChunk {
141
149
  name: toolCallChunk.name ?? "",
142
150
  args: parsedArgs,
143
151
  id: toolCallChunk.id,
152
+ type: "tool_call",
144
153
  });
145
154
  }
146
155
  catch (e) {
@@ -149,6 +158,7 @@ class AIMessageChunk extends base_js_1.BaseMessageChunk {
149
158
  args: toolCallChunk.args,
150
159
  id: toolCallChunk.id,
151
160
  error: "Malformed args.",
161
+ type: "invalid_tool_call",
152
162
  });
153
163
  }
154
164
  }
@@ -213,6 +223,15 @@ class AIMessageChunk extends base_js_1.BaseMessageChunk {
213
223
  _getType() {
214
224
  return "ai";
215
225
  }
226
+ get _printableFields() {
227
+ return {
228
+ ...super._printableFields,
229
+ tool_calls: this.tool_calls,
230
+ tool_call_chunks: this.tool_call_chunks,
231
+ invalid_tool_calls: this.invalid_tool_calls,
232
+ usage_metadata: this.usage_metadata,
233
+ };
234
+ }
216
235
  concat(chunk) {
217
236
  const combinedFields = {
218
237
  content: (0, base_js_1.mergeContent)(this.content, chunk.content),
@@ -38,6 +38,7 @@ export declare class AIMessage extends BaseMessage {
38
38
  kwargs?: Record<string, unknown>);
39
39
  static lc_name(): string;
40
40
  _getType(): MessageType;
41
+ get _printableFields(): Record<string, unknown>;
41
42
  }
42
43
  export declare function isAIMessage(x: BaseMessage): x is AIMessage;
43
44
  export type AIMessageChunkFields = AIMessageFields & {
@@ -59,5 +60,6 @@ export declare class AIMessageChunk extends BaseMessageChunk {
59
60
  get lc_aliases(): Record<string, string>;
60
61
  static lc_name(): string;
61
62
  _getType(): MessageType;
63
+ get _printableFields(): Record<string, unknown>;
62
64
  concat(chunk: AIMessageChunk): AIMessageChunk;
63
65
  }
@@ -95,6 +95,14 @@ export class AIMessage extends BaseMessage {
95
95
  _getType() {
96
96
  return "ai";
97
97
  }
98
+ get _printableFields() {
99
+ return {
100
+ ...super._printableFields,
101
+ tool_calls: this.tool_calls,
102
+ invalid_tool_calls: this.invalid_tool_calls,
103
+ usage_metadata: this.usage_metadata,
104
+ };
105
+ }
98
106
  }
99
107
  export function isAIMessage(x) {
100
108
  return x._getType() === "ai";
@@ -136,6 +144,7 @@ export class AIMessageChunk extends BaseMessageChunk {
136
144
  name: toolCallChunk.name ?? "",
137
145
  args: parsedArgs,
138
146
  id: toolCallChunk.id,
147
+ type: "tool_call",
139
148
  });
140
149
  }
141
150
  catch (e) {
@@ -144,6 +153,7 @@ export class AIMessageChunk extends BaseMessageChunk {
144
153
  args: toolCallChunk.args,
145
154
  id: toolCallChunk.id,
146
155
  error: "Malformed args.",
156
+ type: "invalid_tool_call",
147
157
  });
148
158
  }
149
159
  }
@@ -208,6 +218,15 @@ export class AIMessageChunk extends BaseMessageChunk {
208
218
  _getType() {
209
219
  return "ai";
210
220
  }
221
+ get _printableFields() {
222
+ return {
223
+ ...super._printableFields,
224
+ tool_calls: this.tool_calls,
225
+ tool_call_chunks: this.tool_call_chunks,
226
+ invalid_tool_calls: this.invalid_tool_calls,
227
+ usage_metadata: this.usage_metadata,
228
+ };
229
+ }
211
230
  concat(chunk) {
212
231
  const combinedFields = {
213
232
  content: mergeContent(this.content, chunk.content),
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isBaseMessageChunk = exports.isBaseMessage = exports.BaseMessageChunk = exports._mergeLists = exports._mergeDicts = exports.isOpenAIToolCallArray = exports.BaseMessage = exports.mergeContent = void 0;
3
+ exports.isBaseMessageChunk = exports.isBaseMessage = exports.BaseMessageChunk = exports._mergeObj = exports._mergeLists = exports._mergeDicts = exports.isOpenAIToolCallArray = exports.BaseMessage = exports.mergeContent = void 0;
4
4
  const serializable_js_1 = require("../load/serializable.cjs");
5
5
  function mergeContent(firstContent, secondContent) {
6
6
  // If first content is a string
@@ -14,8 +14,10 @@ function mergeContent(firstContent, secondContent) {
14
14
  // If both are arrays
15
15
  }
16
16
  else if (Array.isArray(secondContent)) {
17
- return [...firstContent, ...secondContent];
18
- // If the first content is a list and second is a string
17
+ return (_mergeLists(firstContent, secondContent) ?? [
18
+ ...firstContent,
19
+ ...secondContent,
20
+ ]);
19
21
  }
20
22
  else {
21
23
  // Otherwise, add the second content as a new element of the list
@@ -23,6 +25,30 @@ function mergeContent(firstContent, secondContent) {
23
25
  }
24
26
  }
25
27
  exports.mergeContent = mergeContent;
28
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
29
+ function stringifyWithDepthLimit(obj, depthLimit) {
30
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
+ function helper(obj, currentDepth) {
32
+ if (typeof obj !== "object" || obj === null || obj === undefined) {
33
+ return obj;
34
+ }
35
+ if (currentDepth >= depthLimit) {
36
+ if (Array.isArray(obj)) {
37
+ return "[Array]";
38
+ }
39
+ return "[Object]";
40
+ }
41
+ if (Array.isArray(obj)) {
42
+ return obj.map((item) => helper(item, currentDepth + 1));
43
+ }
44
+ const result = {};
45
+ for (const key of Object.keys(obj)) {
46
+ result[key] = helper(obj[key], currentDepth + 1);
47
+ }
48
+ return result;
49
+ }
50
+ return JSON.stringify(helper(obj, 0), null, 2);
51
+ }
26
52
  /**
27
53
  * Base class for all types of messages in a conversation. It includes
28
54
  * properties like `content`, `name`, and `additional_kwargs`. It also
@@ -127,6 +153,32 @@ class BaseMessage extends serializable_js_1.Serializable {
127
153
  .kwargs,
128
154
  };
129
155
  }
156
+ static lc_name() {
157
+ return "BaseMessage";
158
+ }
159
+ // Can't be protected for silly reasons
160
+ get _printableFields() {
161
+ return {
162
+ id: this.id,
163
+ content: this.content,
164
+ name: this.name,
165
+ additional_kwargs: this.additional_kwargs,
166
+ response_metadata: this.response_metadata,
167
+ };
168
+ }
169
+ get [Symbol.toStringTag]() {
170
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
171
+ return this.constructor.lc_name();
172
+ }
173
+ // Override the default behavior of console.log
174
+ [Symbol.for("nodejs.util.inspect.custom")](depth) {
175
+ if (depth === null) {
176
+ return this;
177
+ }
178
+ const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth));
179
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
180
+ return `${this.constructor.lc_name()} ${printable}`;
181
+ }
130
182
  }
131
183
  exports.BaseMessage = BaseMessage;
132
184
  function isOpenAIToolCallArray(value) {
@@ -154,9 +206,13 @@ right
154
206
  throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`);
155
207
  }
156
208
  else if (typeof merged[key] === "string") {
157
- merged[key] = merged[key] + value;
209
+ if (key === "type") {
210
+ // Do not merge 'type' fields
211
+ continue;
212
+ }
213
+ merged[key] += value;
158
214
  }
159
- else if (!Array.isArray(merged[key]) && typeof merged[key] === "object") {
215
+ else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) {
160
216
  merged[key] = _mergeDicts(merged[key], value);
161
217
  }
162
218
  else if (Array.isArray(merged[key])) {
@@ -194,6 +250,12 @@ function _mergeLists(left, right) {
194
250
  merged.push(item);
195
251
  }
196
252
  }
253
+ else if (typeof item === "object" &&
254
+ "text" in item &&
255
+ item.text === "") {
256
+ // No-op - skip empty text blocks
257
+ continue;
258
+ }
197
259
  else {
198
260
  merged.push(item);
199
261
  }
@@ -202,6 +264,34 @@ function _mergeLists(left, right) {
202
264
  }
203
265
  }
204
266
  exports._mergeLists = _mergeLists;
267
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
268
+ function _mergeObj(left, right) {
269
+ if (!left && !right) {
270
+ throw new Error("Cannot merge two undefined objects.");
271
+ }
272
+ if (!left || !right) {
273
+ return left || right;
274
+ }
275
+ else if (typeof left !== typeof right) {
276
+ throw new Error(`Cannot merge objects of different types.\nLeft ${typeof left}\nRight ${typeof right}`);
277
+ }
278
+ else if (typeof left === "string" && typeof right === "string") {
279
+ return (left + right);
280
+ }
281
+ else if (Array.isArray(left) && Array.isArray(right)) {
282
+ return _mergeLists(left, right);
283
+ }
284
+ else if (typeof left === "object" && typeof right === "object") {
285
+ return _mergeDicts(left, right);
286
+ }
287
+ else if (left === right) {
288
+ return left;
289
+ }
290
+ else {
291
+ throw new Error(`Can not merge objects of different types.\nLeft ${left}\nRight ${right}`);
292
+ }
293
+ }
294
+ exports._mergeObj = _mergeObj;
205
295
  /**
206
296
  * Represents a chunk of a message, which can be concatenated with other
207
297
  * message chunks. It includes a method `_merge_kwargs_dict()` for merging
@@ -23,7 +23,7 @@ export interface StoredMessageV1 {
23
23
  role: string | undefined;
24
24
  text: string;
25
25
  }
26
- export type MessageType = "human" | "ai" | "generic" | "system" | "function" | "tool";
26
+ export type MessageType = "human" | "ai" | "generic" | "system" | "function" | "tool" | "remove";
27
27
  export type ImageDetail = "auto" | "low" | "high";
28
28
  export type MessageContentText = {
29
29
  type: "text";
@@ -123,6 +123,9 @@ export declare abstract class BaseMessage extends Serializable implements BaseMe
123
123
  /** @deprecated */
124
124
  kwargs?: Record<string, unknown>);
125
125
  toDict(): StoredMessage;
126
+ static lc_name(): string;
127
+ get _printableFields(): Record<string, unknown>;
128
+ get [Symbol.toStringTag](): any;
126
129
  }
127
130
  export type OpenAIToolCall = ToolCall & {
128
131
  index: number;
@@ -130,6 +133,7 @@ export type OpenAIToolCall = ToolCall & {
130
133
  export declare function isOpenAIToolCallArray(value?: unknown): value is OpenAIToolCall[];
131
134
  export declare function _mergeDicts(left: Record<string, any>, right: Record<string, any>): Record<string, any>;
132
135
  export declare function _mergeLists(left?: any[], right?: any[]): any[] | undefined;
136
+ export declare function _mergeObj<T = any>(left: T | undefined, right: T | undefined): T;
133
137
  /**
134
138
  * Represents a chunk of a message, which can be concatenated with other
135
139
  * message chunks. It includes a method `_merge_kwargs_dict()` for merging