@langchain/core 1.1.45 → 1.1.47

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 (56) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/callbacks/base.d.cts.map +1 -1
  3. package/dist/callbacks/base.d.ts.map +1 -1
  4. package/dist/language_models/base.cjs +1 -1
  5. package/dist/language_models/base.js +1 -1
  6. package/dist/language_models/chat_models.cjs +1 -0
  7. package/dist/language_models/chat_models.cjs.map +1 -1
  8. package/dist/language_models/chat_models.d.cts.map +1 -1
  9. package/dist/language_models/chat_models.d.ts.map +1 -1
  10. package/dist/language_models/chat_models.js +1 -0
  11. package/dist/language_models/chat_models.js.map +1 -1
  12. package/dist/load/map_keys.cjs +13 -7
  13. package/dist/load/map_keys.cjs.map +1 -1
  14. package/dist/load/map_keys.d.cts.map +1 -1
  15. package/dist/load/map_keys.d.ts.map +1 -1
  16. package/dist/load/map_keys.js +11 -2
  17. package/dist/load/map_keys.js.map +1 -1
  18. package/dist/messages/base.cjs +10 -0
  19. package/dist/messages/base.cjs.map +1 -1
  20. package/dist/messages/base.d.cts.map +1 -1
  21. package/dist/messages/base.d.ts.map +1 -1
  22. package/dist/messages/base.js +10 -0
  23. package/dist/messages/base.js.map +1 -1
  24. package/dist/testing/fake_model_builder.cjs +10 -9
  25. package/dist/testing/fake_model_builder.cjs.map +1 -1
  26. package/dist/testing/fake_model_builder.d.cts +1 -2
  27. package/dist/testing/fake_model_builder.d.cts.map +1 -1
  28. package/dist/testing/fake_model_builder.d.ts +1 -2
  29. package/dist/testing/fake_model_builder.d.ts.map +1 -1
  30. package/dist/testing/fake_model_builder.js +10 -9
  31. package/dist/testing/fake_model_builder.js.map +1 -1
  32. package/dist/tracers/console.cjs +30 -4
  33. package/dist/tracers/console.cjs.map +1 -1
  34. package/dist/tracers/console.d.cts.map +1 -1
  35. package/dist/tracers/console.d.ts.map +1 -1
  36. package/dist/tracers/console.js +28 -1
  37. package/dist/tracers/console.js.map +1 -1
  38. package/dist/utils/uuid/index.cjs +3 -0
  39. package/dist/utils/uuid/index.cjs.map +1 -1
  40. package/dist/utils/uuid/index.d.cts +2 -1
  41. package/dist/utils/uuid/index.d.ts +2 -1
  42. package/dist/utils/uuid/index.js +3 -1
  43. package/dist/utils/uuid/index.js.map +1 -1
  44. package/dist/utils/uuid/v1ToV6.cjs +14 -0
  45. package/dist/utils/uuid/v1ToV6.cjs.map +1 -0
  46. package/dist/utils/uuid/v1ToV6.js +14 -0
  47. package/dist/utils/uuid/v1ToV6.js.map +1 -0
  48. package/dist/utils/uuid/v6.cjs +23 -0
  49. package/dist/utils/uuid/v6.cjs.map +1 -0
  50. package/dist/utils/uuid/v6.d.cts +8 -0
  51. package/dist/utils/uuid/v6.d.cts.map +1 -0
  52. package/dist/utils/uuid/v6.d.ts +8 -0
  53. package/dist/utils/uuid/v6.d.ts.map +1 -0
  54. package/dist/utils/uuid/v6.js +23 -0
  55. package/dist/utils/uuid/v6.js.map +1 -0
  56. package/package.json +1 -6
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../src/messages/base.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { isDataContentBlock } from \"./content/data.js\";\nimport { convertToV1FromAnthropicInput } from \"./block_translators/anthropic.js\";\nimport { convertToV1FromDataContent } from \"./block_translators/data.js\";\nimport { convertToV1FromChatCompletionsInput } from \"./block_translators/openai.js\";\nimport {\n $InferMessageContent,\n $InferResponseMetadata,\n MessageStructure,\n MessageType,\n isMessage,\n Message,\n} from \"./message.js\";\nimport {\n convertToFormattedString,\n type MessageStringFormat,\n} from \"./format.js\";\n\n/** @internal */\nconst MESSAGE_SYMBOL: symbol = Symbol.for(\"langchain.message\");\n\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n response_metadata?: Record<string, any>;\n id?: string;\n}\n\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\n\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\n\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\n\nexport type MessageContent = string | Array<ContentBlock>;\n\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\nexport type BaseMessageFields<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> = Pick<Message, \"id\" | \"name\"> & {\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\n\n/**\n * Normalize non-string `firstContent` to a block array for merge/spread.\n * Some serializers (e.g. Anthropic-style) yield a single block object instead of a one-element array;\n * spreading that object as an array throws (\"is not iterable\").\n */\nfunction contentBlocksFromNonStringFirst(\n firstContent: MessageContent\n): ContentBlock[] {\n if (Array.isArray(firstContent)) {\n return firstContent;\n }\n if (typeof firstContent === \"string\") {\n return firstContent === \"\" ? [] : [{ type: \"text\", text: firstContent }];\n }\n if (firstContent == null) {\n return [];\n }\n return [firstContent as ContentBlock];\n}\n\nexport function mergeContent(\n firstContent: MessageContent,\n secondContent: MessageContent\n): MessageContent {\n // If first content is a string\n if (typeof firstContent === \"string\") {\n if (firstContent === \"\") {\n return secondContent;\n }\n if (typeof secondContent === \"string\") {\n return firstContent + secondContent;\n } else if (Array.isArray(secondContent) && secondContent.length === 0) {\n return firstContent;\n } else if (\n Array.isArray(secondContent) &&\n secondContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n {\n type: \"text\",\n source_type: \"text\",\n text: firstContent,\n },\n ...secondContent,\n ];\n } else {\n return [{ type: \"text\", text: firstContent }, ...secondContent];\n }\n // If both are arrays\n } else if (Array.isArray(secondContent)) {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return _mergeLists(left, secondContent) ?? [...left, ...secondContent];\n } else {\n if (secondContent === \"\") {\n return firstContent;\n } else if (\n Array.isArray(firstContent) &&\n firstContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n ...firstContent,\n {\n type: \"file\",\n source_type: \"text\",\n text: secondContent,\n },\n ];\n } else {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return [...left, { type: \"text\", text: secondContent }];\n }\n }\n}\n\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport function _mergeStatus(\n left?: \"success\" | \"error\",\n right?: \"success\" | \"error\"\n): \"success\" | \"error\" | undefined {\n if (left === \"error\" || right === \"error\") {\n return \"error\";\n }\n return \"success\";\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringifyWithDepthLimit(obj: any, depthLimit: number): string {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n function helper(obj: any, currentDepth: number): any {\n if (typeof obj !== \"object\" || obj === null || obj === undefined) {\n return obj;\n }\n if (currentDepth >= depthLimit) {\n if (Array.isArray(obj)) {\n return \"[Array]\";\n }\n return \"[Object]\";\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => helper(item, currentDepth + 1));\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = helper(obj[key], currentDepth + 1);\n }\n return result;\n }\n\n return JSON.stringify(helper(obj, 0), null, 2);\n}\n\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport abstract class BaseMessage<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n>\n extends Serializable\n implements Message<TStructure, TRole>\n{\n lc_namespace = [\"langchain_core\", \"messages\"];\n\n lc_serializable = true;\n\n get lc_aliases(): Record<string, string> {\n // exclude snake case conversion to pascal case\n return {\n additional_kwargs: \"additional_kwargs\",\n response_metadata: \"response_metadata\",\n };\n }\n\n readonly [MESSAGE_SYMBOL] = true as const;\n\n abstract readonly type: TRole;\n\n id?: string;\n\n /** @inheritdoc */\n name?: string;\n\n content: $InferMessageContent<TStructure, TRole>;\n\n additional_kwargs: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]\n >;\n\n response_metadata: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"response_metadata\"]\n >;\n\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType {\n return this.type;\n }\n\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType {\n return this._getType();\n }\n\n constructor(\n arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>\n ) {\n const fields: BaseMessageFields<TStructure, TRole> =\n typeof arg === \"string\" || Array.isArray(arg)\n ? ({ content: arg } as BaseMessageFields<TStructure, TRole>)\n : arg;\n if (!fields.additional_kwargs) {\n fields.additional_kwargs = {};\n }\n if (!fields.response_metadata) {\n fields.response_metadata = {};\n }\n super(fields);\n this.name = fields.name;\n if (fields.content === undefined && fields.contentBlocks !== undefined) {\n this.content = fields.contentBlocks as $InferMessageContent<\n TStructure,\n TRole\n >;\n this.response_metadata = {\n output_version: \"v1\",\n ...fields.response_metadata,\n };\n } else if (fields.content !== undefined) {\n this.content = fields.content ?? [];\n this.response_metadata = fields.response_metadata;\n } else {\n this.content = [] as $InferMessageContent<TStructure, TRole>;\n this.response_metadata = fields.response_metadata;\n }\n this.additional_kwargs = fields.additional_kwargs;\n this.id = fields.id;\n }\n\n /** Get text content of the message. */\n get text(): string {\n if (typeof this.content === \"string\") {\n return this.content;\n }\n if (!Array.isArray(this.content)) return \"\";\n return this.content\n .map((c) => {\n if (typeof c === \"string\") return c;\n if (c.type === \"text\") return c.text;\n return \"\";\n })\n .join(\"\");\n }\n\n get contentBlocks(): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock> =\n typeof this.content === \"string\"\n ? [{ type: \"text\", text: this.content }]\n : this.content;\n const parsingSteps = [\n convertToV1FromDataContent,\n convertToV1FromChatCompletionsInput,\n convertToV1FromAnthropicInput,\n ];\n const parsedBlocks = parsingSteps.reduce(\n (blocks, step) => step(blocks),\n blocks\n );\n return parsedBlocks as Array<ContentBlock.Standard>;\n }\n\n toDict(): StoredMessage {\n return {\n type: this.getType(),\n data: (this.toJSON() as SerializedConstructor)\n .kwargs as StoredMessageData,\n };\n }\n\n static lc_name() {\n return \"BaseMessage\";\n }\n\n // Can't be protected for silly reasons\n get _printableFields(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n name: this.name,\n additional_kwargs: this.additional_kwargs,\n response_metadata: this.response_metadata,\n };\n }\n\n static isInstance(obj: unknown): obj is BaseMessage {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n MESSAGE_SYMBOL in obj &&\n (obj as Record<symbol, unknown>)[MESSAGE_SYMBOL] === true &&\n isMessage(obj)\n );\n }\n\n // this private method is used to update the ID for the runtime\n // value as well as in lc_kwargs for serialisation\n _updateId(value: string | undefined) {\n this.id = value;\n\n // lc_attributes wouldn't work here, because jest compares the\n // whole object\n this.lc_kwargs.id = value;\n }\n\n get [Symbol.toStringTag]() {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.constructor as any).lc_name();\n }\n\n // Override the default behavior of console.log\n [Symbol.for(\"nodejs.util.inspect.custom\")](depth: number | null) {\n if (depth === null) {\n return this;\n }\n const printable = stringifyWithDepthLimit(\n this._printableFields,\n Math.max(4, depth)\n );\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return `${(this.constructor as any).lc_name()} ${printable}`;\n }\n\n toFormattedString(format: MessageStringFormat = \"pretty\"): string {\n return convertToFormattedString(this, format);\n }\n}\n\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n\n index?: number;\n};\n\nexport function isOpenAIToolCallArray(\n value?: unknown\n): value is OpenAIToolCall[] {\n return (\n Array.isArray(value) &&\n value.every((v) => typeof (v as OpenAIToolCall).index === \"number\")\n );\n}\n\n/**\n * Default keys that should be preserved (not merged) when concatenating message chunks.\n * These are identification and timestamp fields that shouldn't be summed or concatenated.\n */\nexport const DEFAULT_MERGE_IGNORE_KEYS: readonly string[] = [\n \"index\", // Used for identification in tool calls, not accumulation\n \"created\", // Timestamp field\n \"timestamp\", // Timestamp field\n] as const;\n\n/**\n * Options for controlling merge behavior in `_mergeDicts`.\n */\nexport interface MergeDictsOptions {\n /**\n * Keys to ignore during merging. When a key is in this list:\n * - For numeric values: the original value is preserved (not summed)\n * - For string values: the original value is preserved (not concatenated)\n *\n * Defaults to `DEFAULT_MERGE_IGNORE_KEYS` which includes 'index', 'created', 'timestamp'.\n *\n * @example\n * // Extend defaults with custom keys\n * { ignoreKeys: [...DEFAULT_MERGE_IGNORE_KEYS, 'role', 'customField'] }\n */\n ignoreKeys?: readonly string[];\n}\n\nexport function _mergeDicts(\n /**\n * The left dictionary to merge.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n left: Record<string, any> | undefined,\n /**\n * The right dictionary to merge.\n * @type {Record<string, any>}\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n right: Record<string, any> | undefined,\n /**\n * The options for the merge.\n */\n options?: MergeDictsOptions\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> | undefined {\n /**\n * The keys to ignore during merging.\n */\n const ignoreKeys = options?.ignoreKeys ?? DEFAULT_MERGE_IGNORE_KEYS;\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n }\n const merged = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (merged[key] == null) {\n merged[key] = value;\n } else if (value == null) {\n continue;\n } else if (\n typeof merged[key] !== typeof value ||\n Array.isArray(merged[key]) !== Array.isArray(value)\n ) {\n throw new Error(\n `field[${key}] already exists in the message chunk, but with a different type.`\n );\n } else if (typeof merged[key] === \"string\") {\n if (key === \"type\") {\n // Do not merge 'type' fields\n continue;\n } else if (\n [\"id\", \"name\", \"output_version\", \"model_provider\"].includes(key)\n ) {\n // Keep the incoming value for these fields if its defined\n if (value) {\n merged[key] = value;\n }\n } else if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n } else {\n merged[key] += value;\n }\n } else if (typeof merged[key] === \"number\") {\n if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n }\n merged[key] = merged[key] + value;\n } else if (typeof merged[key] === \"object\" && !Array.isArray(merged[key])) {\n merged[key] = _mergeDicts(merged[key], value, options);\n } else if (Array.isArray(merged[key])) {\n merged[key] = _mergeLists(merged[key], value, options);\n } else if (merged[key] === value) {\n continue;\n } else {\n console.warn(\n `field[${key}] already exists in this message chunk and value has unsupported type.`\n );\n }\n }\n return merged;\n}\n\nfunction isMergeableIndex(index: unknown): index is number | string {\n return typeof index === \"number\" || typeof index === \"string\";\n}\n\nfunction hasMergeableIndex(\n value: unknown\n): value is { index: number | string } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"index\" in value)) return false;\n return isMergeableIndex(value.index);\n}\n\nfunction hasMergeableId(value: unknown): value is { id: string | number } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"id\" in value)) return false;\n const id = (value as Record<string, unknown>).id;\n return id != null && id !== \"\";\n}\n\n/**\n * Find the index of an existing item in `merged` that should be merged with\n * `item`, based on index and/or id matching.\n *\n * Matching priority:\n * 1. Both have index → match on index (+ id when both present)\n * 2. Neither has index, both have id → match on id alone\n * 3. Otherwise → no match (item should be appended)\n */\nfunction _findMergeTarget<Content extends ContentBlock>(\n merged: Content[],\n item: Content\n): number {\n const itemHasIndex = hasMergeableIndex(item);\n const itemHasId = hasMergeableId(item);\n\n if (!itemHasIndex && !itemHasId) return -1;\n\n return merged.findIndex((leftItem) => {\n const leftHasIndex = hasMergeableIndex(leftItem);\n const leftHasId = hasMergeableId(leftItem);\n\n if (itemHasIndex && leftHasIndex) {\n // Both have index: match on index, with id as tiebreaker\n const indicesMatch = leftItem.index === item.index;\n if (!indicesMatch) return false;\n if (leftHasId && itemHasId) return leftItem.id === item.id;\n return true; // indices match, one or both missing id\n }\n\n if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) {\n // Neither has index: fall back to id-only matching. Handles providers\n // that don't include `index` on streaming tool call deltas.\n return leftItem.id === item.id;\n }\n\n return false;\n });\n}\n\nexport function _mergeLists<Content extends ContentBlock>(\n left?: Content[],\n right?: Content[],\n options?: MergeDictsOptions\n): Content[] | undefined {\n if (left == null && right == null) {\n return undefined;\n } else if (left == null || right == null) {\n return left || right;\n } else {\n const merged = [...left];\n for (const item of right) {\n const toMerge = _findMergeTarget(merged, item);\n if (toMerge !== -1) {\n merged[toMerge] = _mergeDicts(\n merged[toMerge],\n item,\n options\n ) as Content;\n } else if (\n typeof item === \"object\" &&\n item !== null &&\n \"text\" in item &&\n item.text === \"\"\n ) {\n continue;\n } else {\n merged.push(item);\n }\n }\n return merged;\n }\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _mergeObj<T = any>(\n left: T | undefined,\n right: T | undefined,\n options?: MergeDictsOptions\n): T | undefined {\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n } else if (typeof left !== typeof right) {\n throw new Error(\n `Cannot merge objects of different types.\\nLeft ${typeof left}\\nRight ${typeof right}`\n );\n } else if (typeof left === \"string\" && typeof right === \"string\") {\n return (left + right) as T;\n } else if (Array.isArray(left) && Array.isArray(right)) {\n return _mergeLists(left, right, options) as T;\n } else if (typeof left === \"object\" && typeof right === \"object\") {\n return _mergeDicts(\n left as Record<string, unknown>,\n right as Record<string, unknown>,\n options\n ) as T;\n } else if (left === right) {\n return left;\n } else {\n throw new Error(\n `Can not merge objects of different types.\\nLeft ${left}\\nRight ${right}`\n );\n }\n}\n\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport abstract class BaseMessageChunk<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n\n static isInstance(obj: unknown): obj is BaseMessageChunk {\n if (!super.isInstance(obj)) {\n return false;\n }\n // Check if obj is an instance of BaseMessageChunk by traversing the prototype chain\n let proto = Object.getPrototypeOf(obj);\n while (proto !== null) {\n if (proto === BaseMessageChunk.prototype) {\n return true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n }\n}\n\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\n\nexport function _isMessageFieldWithRole(\n x: BaseMessageLike\n): x is MessageFieldWithRole {\n return typeof (x as MessageFieldWithRole).role === \"string\";\n}\n\nexport type BaseMessageLike =\n | BaseMessage\n | MessageFieldWithRole\n | [MessageType, MessageContent]\n | string\n /**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n } & BaseMessageFields &\n Record<string, unknown>)\n | SerializedConstructor;\n\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport function isBaseMessage(\n messageLike?: unknown\n): messageLike is BaseMessage {\n return typeof (messageLike as BaseMessage)?._getType === \"function\";\n}\n\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport function isBaseMessageChunk(\n messageLike?: unknown\n): messageLike is BaseMessageChunk {\n return BaseMessageChunk.isInstance(messageLike);\n}\n"],"mappings":";;;;;;;;;AAoBA,MAAM,iBAAyB,OAAO,IAAI,oBAAoB;;;;;;AA0E9D,SAAS,gCACP,cACgB;AAChB,KAAI,MAAM,QAAQ,aAAa,CAC7B,QAAO;AAET,KAAI,OAAO,iBAAiB,SAC1B,QAAO,iBAAiB,KAAK,EAAE,GAAG,CAAC;EAAE,MAAM;EAAQ,MAAM;EAAc,CAAC;AAE1E,KAAI,gBAAgB,KAClB,QAAO,EAAE;AAEX,QAAO,CAAC,aAA6B;;AAGvC,SAAgB,aACd,cACA,eACgB;AAEhB,KAAI,OAAO,iBAAiB,UAAU;AACpC,MAAI,iBAAiB,GACnB,QAAO;AAET,MAAI,OAAO,kBAAkB,SAC3B,QAAO,eAAe;WACb,MAAM,QAAQ,cAAc,IAAI,cAAc,WAAW,EAClE,QAAO;WAEP,MAAM,QAAQ,cAAc,IAC5B,cAAc,MAAM,MAAM,mBAAmB,EAAE,CAAC,CAEhD,QAAO,CACL;GACE,MAAM;GACN,aAAa;GACb,MAAM;GACP,EACD,GAAG,cACJ;MAED,QAAO,CAAC;GAAE,MA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W,IAAI,CACxB,QAAO;EAGT,IAAI,QAAQ,OAAO,eAAe,IAAI;AACtC,SAAO,UAAU,MAAM;AACrB,OAAI,UAAU,iBAAiB,UAC7B,QAAO;AAET,WAAQ,OAAO,eAAe,MAAM;;AAEtC,SAAO;;;AAUX,SAAgB,wBACd,GAC2B;AAC3B,QAAO,OAAQ,EAA2B,SAAS;;;;;AAoBrD,SAAgB,cACd,aAC4B;AAC5B,QAAO,OAAQ,aAA6B,aAAa;;;;;AAM3D,SAAgB,mBACd,aACiC;AACjC,QAAO,iBAAiB,WAAW,YAAY"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../src/messages/base.ts"],"sourcesContent":["import { Serializable, SerializedConstructor } from \"../load/serializable.js\";\nimport { ContentBlock } from \"./content/index.js\";\nimport { isDataContentBlock } from \"./content/data.js\";\nimport { convertToV1FromAnthropicInput } from \"./block_translators/anthropic.js\";\nimport { convertToV1FromDataContent } from \"./block_translators/data.js\";\nimport { convertToV1FromChatCompletionsInput } from \"./block_translators/openai.js\";\nimport {\n $InferMessageContent,\n $InferResponseMetadata,\n MessageStructure,\n MessageType,\n isMessage,\n Message,\n} from \"./message.js\";\nimport {\n convertToFormattedString,\n type MessageStringFormat,\n} from \"./format.js\";\n\n/** @internal */\nconst MESSAGE_SYMBOL: symbol = Symbol.for(\"langchain.message\");\n\nexport interface StoredMessageData {\n content: string;\n role: string | undefined;\n name: string | undefined;\n tool_call_id: string | undefined;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n additional_kwargs?: Record<string, any>;\n /** Response metadata. For example: response headers, logprobs, token counts, model name. */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n response_metadata?: Record<string, any>;\n id?: string;\n}\n\nexport interface StoredMessage {\n type: string;\n data: StoredMessageData;\n}\n\nexport interface StoredGeneration {\n text: string;\n message?: StoredMessage;\n}\n\nexport interface StoredMessageV1 {\n type: string;\n role: string | undefined;\n text: string;\n}\n\nexport type MessageContent = string | Array<ContentBlock>;\n\nexport interface FunctionCall {\n /**\n * The arguments to call the function with, as generated by the model in JSON\n * format. Note that the model does not always generate valid JSON, and may\n * hallucinate parameters not defined by your function schema. Validate the\n * arguments in your code before calling your function.\n */\n arguments: string;\n\n /**\n * The name of the function to call.\n */\n name: string;\n}\n\nexport type BaseMessageFields<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> = Pick<Message, \"id\" | \"name\"> & {\n content?: $InferMessageContent<TStructure, TRole>;\n contentBlocks?: Array<ContentBlock.Standard>;\n /** @deprecated */\n additional_kwargs?: {\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n function_call?: FunctionCall;\n /**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\n tool_calls?: OpenAIToolCall[];\n [key: string]: unknown;\n };\n response_metadata?: Partial<$InferResponseMetadata<TStructure, TRole>>;\n};\n\n/**\n * Normalize non-string `firstContent` to a block array for merge/spread.\n * Some serializers (e.g. Anthropic-style) yield a single block object instead of a one-element array;\n * spreading that object as an array throws (\"is not iterable\").\n */\nfunction contentBlocksFromNonStringFirst(\n firstContent: MessageContent\n): ContentBlock[] {\n if (Array.isArray(firstContent)) {\n return firstContent;\n }\n if (typeof firstContent === \"string\") {\n return firstContent === \"\" ? [] : [{ type: \"text\", text: firstContent }];\n }\n if (firstContent == null) {\n return [];\n }\n return [firstContent as ContentBlock];\n}\n\nexport function mergeContent(\n firstContent: MessageContent,\n secondContent: MessageContent\n): MessageContent {\n // If first content is a string\n if (typeof firstContent === \"string\") {\n if (firstContent === \"\") {\n return secondContent;\n }\n if (typeof secondContent === \"string\") {\n return firstContent + secondContent;\n } else if (Array.isArray(secondContent) && secondContent.length === 0) {\n return firstContent;\n } else if (\n Array.isArray(secondContent) &&\n secondContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n {\n type: \"text\",\n source_type: \"text\",\n text: firstContent,\n },\n ...secondContent,\n ];\n } else {\n return [{ type: \"text\", text: firstContent }, ...secondContent];\n }\n // If both are arrays\n } else if (Array.isArray(secondContent)) {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return _mergeLists(left, secondContent) ?? [...left, ...secondContent];\n } else {\n if (secondContent === \"\") {\n return firstContent;\n } else if (\n Array.isArray(firstContent) &&\n firstContent.some((c) => isDataContentBlock(c))\n ) {\n return [\n ...firstContent,\n {\n type: \"file\",\n source_type: \"text\",\n text: secondContent,\n },\n ];\n } else {\n const left = contentBlocksFromNonStringFirst(firstContent);\n return [...left, { type: \"text\", text: secondContent }];\n }\n }\n}\n\n/**\n * 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else\n * it will return 'success'.\n *\n * @param {\"success\" | \"error\" | undefined} left The existing value to 'merge' with the new value.\n * @param {\"success\" | \"error\" | undefined} right The new value to 'merge' with the existing value\n * @returns {\"success\" | \"error\"} The 'merged' value.\n */\nexport function _mergeStatus(\n left?: \"success\" | \"error\",\n right?: \"success\" | \"error\"\n): \"success\" | \"error\" | undefined {\n if (left === \"error\" || right === \"error\") {\n return \"error\";\n }\n return \"success\";\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction stringifyWithDepthLimit(obj: any, depthLimit: number): string {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n function helper(obj: any, currentDepth: number): any {\n if (typeof obj !== \"object\" || obj === null || obj === undefined) {\n return obj;\n }\n if (currentDepth >= depthLimit) {\n if (Array.isArray(obj)) {\n return \"[Array]\";\n }\n return \"[Object]\";\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => helper(item, currentDepth + 1));\n }\n\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n result[key] = helper(obj[key], currentDepth + 1);\n }\n return result;\n }\n\n return JSON.stringify(helper(obj, 0), null, 2);\n}\n\n/**\n * Base class for all types of messages in a conversation. It includes\n * properties like `content`, `name`, and `additional_kwargs`. It also\n * includes methods like `toDict()` and `_getType()`.\n */\nexport abstract class BaseMessage<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n>\n extends Serializable\n implements Message<TStructure, TRole>\n{\n lc_namespace = [\"langchain_core\", \"messages\"];\n\n lc_serializable = true;\n\n get lc_aliases(): Record<string, string> {\n // exclude snake case conversion to pascal case\n return {\n additional_kwargs: \"additional_kwargs\",\n response_metadata: \"response_metadata\",\n };\n }\n\n readonly [MESSAGE_SYMBOL] = true as const;\n\n abstract readonly type: TRole;\n\n id?: string;\n\n /** @inheritdoc */\n name?: string;\n\n content: $InferMessageContent<TStructure, TRole>;\n\n additional_kwargs: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"additional_kwargs\"]\n >;\n\n response_metadata: NonNullable<\n BaseMessageFields<TStructure, TRole>[\"response_metadata\"]\n >;\n\n /**\n * @deprecated Use .getType() instead or import the proper typeguard.\n * For example:\n *\n * ```ts\n * import { isAIMessage } from \"@langchain/core/messages\";\n *\n * const message = new AIMessage(\"Hello!\");\n * isAIMessage(message); // true\n * ```\n */\n _getType(): MessageType {\n return this.type;\n }\n\n /**\n * @deprecated Use .type instead\n * The type of the message.\n */\n getType(): MessageType {\n return this._getType();\n }\n\n constructor(\n arg:\n | $InferMessageContent<TStructure, TRole>\n | BaseMessageFields<TStructure, TRole>\n ) {\n const fields: BaseMessageFields<TStructure, TRole> =\n typeof arg === \"string\" || Array.isArray(arg)\n ? ({ content: arg } as BaseMessageFields<TStructure, TRole>)\n : arg;\n if (!fields.additional_kwargs) {\n fields.additional_kwargs = {};\n }\n if (!fields.response_metadata) {\n fields.response_metadata = {};\n }\n super(fields);\n this.name = fields.name;\n if (fields.content === undefined && fields.contentBlocks !== undefined) {\n this.content = fields.contentBlocks as $InferMessageContent<\n TStructure,\n TRole\n >;\n this.response_metadata = {\n output_version: \"v1\",\n ...fields.response_metadata,\n };\n } else if (fields.content !== undefined) {\n this.content = fields.content ?? [];\n this.response_metadata = fields.response_metadata;\n } else {\n this.content = [] as $InferMessageContent<TStructure, TRole>;\n this.response_metadata = fields.response_metadata;\n }\n this.additional_kwargs = fields.additional_kwargs;\n this.id = fields.id;\n }\n\n /** Get text content of the message. */\n get text(): string {\n if (typeof this.content === \"string\") {\n return this.content;\n }\n if (!Array.isArray(this.content)) return \"\";\n return this.content\n .map((c) => {\n if (typeof c === \"string\") return c;\n if (c.type === \"text\") return c.text;\n return \"\";\n })\n .join(\"\");\n }\n\n get contentBlocks(): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock> =\n typeof this.content === \"string\"\n ? [{ type: \"text\", text: this.content }]\n : this.content;\n const parsingSteps = [\n convertToV1FromDataContent,\n convertToV1FromChatCompletionsInput,\n convertToV1FromAnthropicInput,\n ];\n const parsedBlocks = parsingSteps.reduce(\n (blocks, step) => step(blocks),\n blocks\n );\n return parsedBlocks as Array<ContentBlock.Standard>;\n }\n\n toDict(): StoredMessage {\n return {\n type: this.getType(),\n data: (this.toJSON() as SerializedConstructor)\n .kwargs as StoredMessageData,\n };\n }\n\n static lc_name() {\n return \"BaseMessage\";\n }\n\n // Can't be protected for silly reasons\n get _printableFields(): Record<string, unknown> {\n return {\n id: this.id,\n content: this.content,\n name: this.name,\n additional_kwargs: this.additional_kwargs,\n response_metadata: this.response_metadata,\n };\n }\n\n static isInstance(obj: unknown): obj is BaseMessage {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n MESSAGE_SYMBOL in obj &&\n (obj as Record<symbol, unknown>)[MESSAGE_SYMBOL] === true &&\n isMessage(obj)\n );\n }\n\n // this private method is used to update the ID for the runtime\n // value as well as in lc_kwargs for serialisation\n _updateId(value: string | undefined) {\n this.id = value;\n\n // lc_attributes wouldn't work here, because jest compares the\n // whole object\n this.lc_kwargs.id = value;\n }\n\n get [Symbol.toStringTag]() {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (this.constructor as any).lc_name();\n }\n\n // Override the default behavior of console.log\n [Symbol.for(\"nodejs.util.inspect.custom\")](depth: number | null) {\n if (depth === null) {\n return this;\n }\n const printable = stringifyWithDepthLimit(\n this._printableFields,\n Math.max(4, depth)\n );\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return `${(this.constructor as any).lc_name()} ${printable}`;\n }\n\n toFormattedString(format: MessageStringFormat = \"pretty\"): string {\n return convertToFormattedString(this, format);\n }\n}\n\n/**\n * @deprecated Use \"tool_calls\" field on AIMessages instead\n */\nexport type OpenAIToolCall = {\n /**\n * The ID of the tool call.\n */\n id: string;\n\n /**\n * The function that the model called.\n */\n function: FunctionCall;\n\n /**\n * The type of the tool. Currently, only `function` is supported.\n */\n type: \"function\";\n\n index?: number;\n};\n\nexport function isOpenAIToolCallArray(\n value?: unknown\n): value is OpenAIToolCall[] {\n return (\n Array.isArray(value) &&\n value.every((v) => typeof (v as OpenAIToolCall).index === \"number\")\n );\n}\n\n/**\n * Default keys that should be preserved (not merged) when concatenating message chunks.\n * These are identification and timestamp fields that shouldn't be summed or concatenated.\n */\nexport const DEFAULT_MERGE_IGNORE_KEYS: readonly string[] = [\n \"index\", // Used for identification in tool calls, not accumulation\n \"created\", // Timestamp field\n \"timestamp\", // Timestamp field\n] as const;\n\n/**\n * Options for controlling merge behavior in `_mergeDicts`.\n */\nexport interface MergeDictsOptions {\n /**\n * Keys to ignore during merging. When a key is in this list:\n * - For numeric values: the original value is preserved (not summed)\n * - For string values: the original value is preserved (not concatenated)\n *\n * Defaults to `DEFAULT_MERGE_IGNORE_KEYS` which includes 'index', 'created', 'timestamp'.\n *\n * @example\n * // Extend defaults with custom keys\n * { ignoreKeys: [...DEFAULT_MERGE_IGNORE_KEYS, 'role', 'customField'] }\n */\n ignoreKeys?: readonly string[];\n}\n\nexport function _mergeDicts(\n /**\n * The left dictionary to merge.\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n left: Record<string, any> | undefined,\n /**\n * The right dictionary to merge.\n * @type {Record<string, any>}\n */\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n right: Record<string, any> | undefined,\n /**\n * The options for the merge.\n */\n options?: MergeDictsOptions\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> | undefined {\n /**\n * The keys to ignore during merging.\n */\n const ignoreKeys = options?.ignoreKeys ?? DEFAULT_MERGE_IGNORE_KEYS;\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n }\n const merged = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (merged[key] == null) {\n merged[key] = value;\n } else if (value == null) {\n continue;\n } else if (\n typeof merged[key] !== typeof value ||\n Array.isArray(merged[key]) !== Array.isArray(value)\n ) {\n throw new Error(\n `field[${key}] already exists in the message chunk, but with a different type.`\n );\n } else if (typeof merged[key] === \"string\") {\n if (key === \"type\") {\n // Do not merge 'type' fields\n continue;\n } else if (\n [\"id\", \"name\", \"output_version\", \"model_provider\"].includes(key)\n ) {\n // Keep the incoming value for these fields if its defined\n if (value) {\n merged[key] = value;\n }\n } else if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n } else {\n merged[key] += value;\n }\n } else if (typeof merged[key] === \"number\") {\n if (ignoreKeys.includes(key)) {\n // Preserve the original value for ignored keys\n continue;\n }\n merged[key] = merged[key] + value;\n } else if (typeof merged[key] === \"object\" && !Array.isArray(merged[key])) {\n merged[key] = _mergeDicts(merged[key], value, options);\n } else if (Array.isArray(merged[key])) {\n merged[key] = _mergeLists(merged[key], value, options);\n } else if (merged[key] === value) {\n continue;\n } else {\n console.warn(\n `field[${key}] already exists in this message chunk and value has unsupported type.`\n );\n }\n }\n return merged;\n}\n\nfunction isMergeableIndex(index: unknown): index is number | string {\n return typeof index === \"number\" || typeof index === \"string\";\n}\n\nfunction hasMergeableIndex(\n value: unknown\n): value is { index: number | string } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"index\" in value)) return false;\n return isMergeableIndex(value.index);\n}\n\nfunction hasMergeableId(value: unknown): value is { id: string | number } {\n if (typeof value !== \"object\" || value === null) return false;\n if (!(\"id\" in value)) return false;\n const id = (value as Record<string, unknown>).id;\n return id != null && id !== \"\";\n}\n\nfunction getMergeableTypeBase(type: string): string {\n return type.endsWith(\"_delta\") ? type.slice(0, -\"_delta\".length) : type;\n}\n\nfunction hasMismatchedMergeableType(left: unknown, right: unknown): boolean {\n if (typeof left !== \"object\" || left === null) return false;\n if (typeof right !== \"object\" || right === null) return false;\n if (!(\"type\" in left) || !(\"type\" in right)) return false;\n\n return (\n typeof left.type === \"string\" &&\n typeof right.type === \"string\" &&\n getMergeableTypeBase(left.type) !== getMergeableTypeBase(right.type)\n );\n}\n\n/**\n * Find the index of an existing item in `merged` that should be merged with\n * `item`, based on index and/or id matching.\n *\n * Matching priority:\n * 1. Both have index → match on index (+ id when both present)\n * 2. Neither has index, both have id → match on id alone\n * 3. Otherwise → no match (item should be appended)\n */\nfunction _findMergeTarget<Content extends ContentBlock>(\n merged: Content[],\n item: Content\n): number {\n const itemHasIndex = hasMergeableIndex(item);\n const itemHasId = hasMergeableId(item);\n\n if (!itemHasIndex && !itemHasId) return -1;\n\n return merged.findIndex((leftItem) => {\n const leftHasIndex = hasMergeableIndex(leftItem);\n const leftHasId = hasMergeableId(leftItem);\n\n if (itemHasIndex && leftHasIndex) {\n // Both have index: match on index, with id as tiebreaker\n const indicesMatch = leftItem.index === item.index;\n if (!indicesMatch) return false;\n if (hasMismatchedMergeableType(leftItem, item)) return false;\n if (leftHasId && itemHasId) return leftItem.id === item.id;\n return true; // indices match, one or both missing id\n }\n\n if (!itemHasIndex && !leftHasIndex && itemHasId && leftHasId) {\n // Neither has index: fall back to id-only matching. Handles providers\n // that don't include `index` on streaming tool call deltas.\n return leftItem.id === item.id;\n }\n\n return false;\n });\n}\n\nexport function _mergeLists<Content extends ContentBlock>(\n left?: Content[],\n right?: Content[],\n options?: MergeDictsOptions\n): Content[] | undefined {\n if (left == null && right == null) {\n return undefined;\n } else if (left == null || right == null) {\n return left || right;\n } else {\n const merged = [...left];\n for (const item of right) {\n const toMerge = _findMergeTarget(merged, item);\n if (toMerge !== -1) {\n merged[toMerge] = _mergeDicts(\n merged[toMerge],\n item,\n options\n ) as Content;\n } else if (\n typeof item === \"object\" &&\n item !== null &&\n \"text\" in item &&\n item.text === \"\"\n ) {\n continue;\n } else {\n merged.push(item);\n }\n }\n return merged;\n }\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _mergeObj<T = any>(\n left: T | undefined,\n right: T | undefined,\n options?: MergeDictsOptions\n): T | undefined {\n if (left == null && right == null) {\n return undefined;\n }\n if (left == null || right == null) {\n return left ?? right;\n } else if (typeof left !== typeof right) {\n throw new Error(\n `Cannot merge objects of different types.\\nLeft ${typeof left}\\nRight ${typeof right}`\n );\n } else if (typeof left === \"string\" && typeof right === \"string\") {\n return (left + right) as T;\n } else if (Array.isArray(left) && Array.isArray(right)) {\n return _mergeLists(left, right, options) as T;\n } else if (typeof left === \"object\" && typeof right === \"object\") {\n return _mergeDicts(\n left as Record<string, unknown>,\n right as Record<string, unknown>,\n options\n ) as T;\n } else if (left === right) {\n return left;\n } else {\n throw new Error(\n `Can not merge objects of different types.\\nLeft ${left}\\nRight ${right}`\n );\n }\n}\n\n/**\n * Represents a chunk of a message, which can be concatenated with other\n * message chunks. It includes a method `_merge_kwargs_dict()` for merging\n * additional keyword arguments from another `BaseMessageChunk` into this\n * one. It also overrides the `__add__()` method to support concatenation\n * of `BaseMessageChunk` instances.\n */\nexport abstract class BaseMessageChunk<\n TStructure extends MessageStructure = MessageStructure,\n TRole extends MessageType = MessageType,\n> extends BaseMessage<TStructure, TRole> {\n abstract concat(chunk: BaseMessageChunk): BaseMessageChunk<TStructure, TRole>;\n\n static isInstance(obj: unknown): obj is BaseMessageChunk {\n if (!super.isInstance(obj)) {\n return false;\n }\n // Check if obj is an instance of BaseMessageChunk by traversing the prototype chain\n let proto = Object.getPrototypeOf(obj);\n while (proto !== null) {\n if (proto === BaseMessageChunk.prototype) {\n return true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n }\n}\n\nexport type MessageFieldWithRole = {\n role: MessageType;\n content: MessageContent;\n name?: string;\n} & Record<string, unknown>;\n\nexport function _isMessageFieldWithRole(\n x: BaseMessageLike\n): x is MessageFieldWithRole {\n return typeof (x as MessageFieldWithRole).role === \"string\";\n}\n\nexport type BaseMessageLike =\n | BaseMessage\n | MessageFieldWithRole\n | [MessageType, MessageContent]\n | string\n /**\n * @deprecated Specifying \"type\" is deprecated and will be removed in 0.4.0.\n */\n | ({\n type: MessageType | \"user\" | \"assistant\" | \"placeholder\";\n } & BaseMessageFields &\n Record<string, unknown>)\n | SerializedConstructor;\n\n/**\n * @deprecated Use {@link BaseMessage.isInstance} instead\n */\nexport function isBaseMessage(\n messageLike?: unknown\n): messageLike is BaseMessage {\n return typeof (messageLike as BaseMessage)?._getType === \"function\";\n}\n\n/**\n * @deprecated Use {@link BaseMessageChunk.isInstance} instead\n */\nexport function isBaseMessageChunk(\n messageLike?: unknown\n): messageLike is BaseMessageChunk {\n return BaseMessageChunk.isInstance(messageLike);\n}\n"],"mappings":";;;;;;;;;AAoBA,MAAM,iBAAyB,OAAO,IAAI,oBAAoB;;;;;;AA0E9D,SAAS,gCACP,cACgB;AAChB,KAAI,MAAM,QAAQ,aAAa,CAC7B,QAAO;AAET,KAAI,OAAO,iBAAiB,SAC1B,QAAO,iBAAiB,KAAK,EAAE,GAAG,CAAC;EAAE,MAAM;EAAQ,MAAM;EAAc,CAAC;AAE1E,KAAI,gBAAgB,KAClB,QAAO,EAAE;AAEX,QAAO,CAAC,aAA6B;;AAGvC,SAAgB,aACd,cACA,eACgB;AAEhB,KAAI,OAAO,iBAAiB,UAAU;AACpC,MAAI,iBAAiB,GACnB,QAAO;AAET,MAAI,OAAO,kBAAkB,SAC3B,QAAO,eAAe;WACb,MAAM,QAAQ,cAAc,IAAI,cAAc,WAAW,EAClE,QAAO;WAEP,MAAM,QAAQ,cAAc,IAC5B,cAAc,MAAM,MAAM,mBAAmB,EAAE,CAAC,CAEhD,QAAO,CACL;GACE,MAAM;GACN,aAAa;GACb,MAAM;GACP,EACD,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ACN,OAAO,SAAS,OAAO,MAChC,OAAM,IAAI,MACR,kDAAkD,OAAO,KAAK,UAAU,OAAO,QAChF;UACQ,OAAO,SAAS,YAAY,OAAO,UAAU,SACtD,QAAQ,OAAO;UACN,MAAM,QAAQ,KAAK,IAAI,MAAM,QAAQ,MAAM,CACpD,QAAO,YAAY,MAAM,OAAO,QAAQ;UAC/B,OAAO,SAAS,YAAY,OAAO,UAAU,SACtD,QAAO,YACL,MACA,OACA,QACD;UACQ,SAAS,MAClB,QAAO;KAEP,OAAM,IAAI,MACR,mDAAmD,KAAK,UAAU,QACnE;;;;;;;;;AAWL,IAAsB,mBAAtB,MAAsB,yBAGZ,YAA+B;CAGvC,OAAO,WAAW,KAAuC;AACvD,MAAI,CAAC,MAAM,WAAW,IAAI,CACxB,QAAO;EAGT,IAAI,QAAQ,OAAO,eAAe,IAAI;AACtC,SAAO,UAAU,MAAM;AACrB,OAAI,UAAU,iBAAiB,UAC7B,QAAO;AAET,WAAQ,OAAO,eAAe,MAAM;;AAEtC,SAAO;;;AAUX,SAAgB,wBACd,GAC2B;AAC3B,QAAO,OAAQ,EAA2B,SAAS;;;;;AAoBrD,SAAgB,cACd,aAC4B;AAC5B,QAAO,OAAQ,aAA6B,aAAa;;;;;AAM3D,SAAgB,mBACd,aACiC;AACjC,QAAO,iBAAiB,WAAW,YAAY"}
@@ -25,21 +25,23 @@ var FakeBuiltModel = class FakeBuiltModel extends require_language_models_chat_m
25
25
  _alwaysThrowError;
26
26
  _structuredResponseValue;
27
27
  _tools = [];
28
- _callIndex = 0;
29
- _calls = [];
28
+ _state = {
29
+ callIndex: 0,
30
+ calls: []
31
+ };
30
32
  /**
31
33
  * All invocations recorded by this model, in order.
32
34
  * Each entry contains the `messages` array and `options` that were
33
35
  * passed to `invoke()`.
34
36
  */
35
37
  get calls() {
36
- return this._calls;
38
+ return this._state.calls;
37
39
  }
38
40
  /**
39
41
  * The number of times this model has been invoked.
40
42
  */
41
43
  get callCount() {
42
- return this._calls.length;
44
+ return this._state.calls.length;
43
45
  }
44
46
  constructor() {
45
47
  super({});
@@ -122,8 +124,7 @@ var FakeBuiltModel = class FakeBuiltModel extends require_language_models_chat_m
122
124
  next._alwaysThrowError = this._alwaysThrowError;
123
125
  next._structuredResponseValue = this._structuredResponseValue;
124
126
  next._tools = merged;
125
- next._calls = this._calls;
126
- next._callIndex = this._callIndex;
127
+ next._state = this._state;
127
128
  return next.withConfig({});
128
129
  }
129
130
  /**
@@ -140,12 +141,12 @@ var FakeBuiltModel = class FakeBuiltModel extends require_language_models_chat_m
140
141
  });
141
142
  }
142
143
  async _generate(messages, options, _runManager) {
143
- this._calls.push({
144
+ this._state.calls.push({
144
145
  messages: [...messages],
145
146
  options
146
147
  });
147
- const currentCallIndex = this._callIndex;
148
- this._callIndex += 1;
148
+ const currentCallIndex = this._state.callIndex;
149
+ this._state.callIndex += 1;
149
150
  if (this._alwaysThrowError) throw this._alwaysThrowError;
150
151
  const entry = this.queue[currentCallIndex];
151
152
  if (!entry) throw new Error(`FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`);
@@ -1 +1 @@
1
- {"version":3,"file":"fake_model_builder.cjs","names":["BaseChatModel","BaseMessage","RunnableLambda","AIMessage"],"sources":["../../src/testing/fake_model_builder.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport { CallbackManagerForLLMRun } from \"../callbacks/manager.js\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"../language_models/chat_models.js\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n StructuredOutputMethodParams,\n} from \"../language_models/base.js\";\nimport { BaseMessage, AIMessage } from \"../messages/index.js\";\nimport type { ToolCall } from \"../messages/tool.js\";\nimport type { ChatResult } from \"../outputs.js\";\nimport { Runnable, RunnableLambda } from \"../runnables/base.js\";\nimport { StructuredTool } from \"../tools/index.js\";\nimport type { InteropZodType } from \"../utils/types/zod.js\";\nimport type { ToolSpec } from \"../utils/testing/chat_models.js\";\n\ntype ResponseFactory = (messages: BaseMessage[]) => BaseMessage | Error;\n\ntype QueueEntry =\n | { kind: \"message\"; message: BaseMessage }\n | { kind: \"toolCalls\"; toolCalls: ToolCall[] }\n | { kind: \"error\"; error: Error }\n | { kind: \"factory\"; factory: ResponseFactory };\n\ninterface FakeModelCall {\n messages: BaseMessage[];\n options: any;\n}\n\nfunction deriveContent(messages: BaseMessage[]): string {\n return messages\n .map((m) => m.text)\n .filter(Boolean)\n .join(\"-\");\n}\n\nlet idCounter = 0;\nfunction nextToolCallId(): string {\n idCounter += 1;\n return `fake_tc_${idCounter}`;\n}\n\n/**\n * A fake chat model for testing, created via {@link fakeModel}.\n *\n * Queue responses with `.respond()` and `.respondWithTools()`, then\n * pass the instance directly wherever a chat model is expected.\n * Responses are consumed in first-in-first-out order — one per `invoke()` call.\n * When all queued responses are consumed, further invocations throw.\n */\nexport class FakeBuiltModel extends BaseChatModel {\n private queue: QueueEntry[] = [];\n\n private _alwaysThrowError: Error | undefined;\n\n private _structuredResponseValue: any;\n\n private _tools: (StructuredTool | ToolSpec)[] = [];\n\n private _callIndex = 0;\n\n private _calls: FakeModelCall[] = [];\n\n /**\n * All invocations recorded by this model, in order.\n * Each entry contains the `messages` array and `options` that were\n * passed to `invoke()`.\n */\n get calls(): FakeModelCall[] {\n return this._calls;\n }\n\n /**\n * The number of times this model has been invoked.\n */\n get callCount(): number {\n return this._calls.length;\n }\n\n constructor() {\n super({});\n }\n\n _llmType(): string {\n return \"fake-model-builder\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n /**\n * Enqueue a response that the model will return on its next invocation.\n * @param entry A {@link BaseMessage} to return, an `Error` to throw, or\n * a factory `(messages) => BaseMessage | Error` for dynamic responses.\n * @returns `this`, for chaining.\n */\n respond(entry: BaseMessage | Error | ResponseFactory): this {\n if (typeof entry === \"function\") {\n this.queue.push({ kind: \"factory\", factory: entry });\n } else if (BaseMessage.isInstance(entry)) {\n this.queue.push({ kind: \"message\", message: entry });\n } else {\n this.queue.push({ kind: \"error\", error: entry });\n }\n return this;\n }\n\n /**\n * Enqueue an {@link AIMessage} that carries the given tool calls.\n * Content is derived from the input messages at invocation time.\n * @param toolCalls Array of tool calls. Each entry needs `name` and\n * `args`; `id` is optional and auto-generated when omitted.\n * @returns `this`, for chaining.\n */\n respondWithTools(\n toolCalls: Array<{ name: string; args: Record<string, any>; id?: string }>\n ): this {\n this.queue.push({\n kind: \"toolCalls\",\n toolCalls: toolCalls.map((tc) => ({\n name: tc.name,\n args: tc.args,\n id: tc.id ?? nextToolCallId(),\n type: \"tool_call\" as const,\n })),\n });\n return this;\n }\n\n /**\n * Make every invocation throw the given error, regardless of the queue.\n * @param error The error to throw.\n * @returns `this`, for chaining.\n */\n alwaysThrow(error: Error): this {\n this._alwaysThrowError = error;\n return this;\n }\n\n /**\n * Set the value that {@link withStructuredOutput} will resolve to.\n * @param value The structured object to return.\n * @returns `this`, for chaining.\n */\n structuredResponse(value: Record<string, any>): this {\n this._structuredResponseValue = value;\n return this;\n }\n\n /**\n * Bind tools to the model. Returns a new model that shares the same\n * response queue and call history.\n * @param tools The tools to bind, as {@link StructuredTool} instances or\n * plain {@link ToolSpec} objects.\n * @returns A new RunnableBinding with the tools bound.\n */\n bindTools(tools: (StructuredTool | ToolSpec)[]) {\n const merged = [...this._tools, ...tools];\n const next = new FakeBuiltModel();\n next.queue = this.queue;\n next._alwaysThrowError = this._alwaysThrowError;\n next._structuredResponseValue = this._structuredResponseValue;\n next._tools = merged;\n next._calls = this._calls;\n next._callIndex = this._callIndex;\n\n return next.withConfig({} as BaseChatModelCallOptions);\n }\n\n /**\n * Returns a {@link Runnable} that produces the {@link structuredResponse}\n * value. The schema argument is accepted for compatibility but ignored.\n * @param _params Schema or params (ignored).\n * @param _config Options (ignored).\n * @returns A Runnable that resolves to the structured response value.\n */\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n | Record<string, any>,\n _config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n const { _structuredResponseValue } = this;\n return RunnableLambda.from(async () => {\n return _structuredResponseValue as RunOutput;\n }) as Runnable;\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n this._calls.push({ messages: [...messages], options });\n\n const currentCallIndex = this._callIndex;\n this._callIndex += 1;\n\n if (this._alwaysThrowError) {\n throw this._alwaysThrowError;\n }\n\n const entry = this.queue[currentCallIndex];\n if (!entry) {\n throw new Error(\n `FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`\n );\n }\n\n if (entry.kind === \"error\") {\n throw entry.error;\n }\n\n if (entry.kind === \"factory\") {\n const result = entry.factory(messages);\n if (!BaseMessage.isInstance(result)) {\n throw result;\n }\n return {\n generations: [{ text: \"\", message: result }],\n };\n }\n\n if (entry.kind === \"message\") {\n return {\n generations: [{ text: \"\", message: entry.message }],\n };\n }\n\n const content = deriveContent(messages);\n const message = new AIMessage({\n content,\n id: currentCallIndex.toString(),\n tool_calls:\n entry.toolCalls.length > 0\n ? entry.toolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [{ text: content, message }],\n llmOutput: {},\n };\n }\n}\n\n/**\n * Creates a new {@link FakeBuiltModel} for testing.\n *\n * Returns a chainable builder — queue responses, then pass the model\n * anywhere a chat model is expected. Responses are consumed in FIFO\n * order, one per `invoke()` call.\n *\n * ## API summary\n *\n * | Method | Description |\n * | --- | --- |\n * | `fakeModel()` | Creates a new fake chat model. Returns a chainable builder. |\n * | `.respond(message)` | Queue an `AIMessage` (or any `BaseMessage`) to return on the next invocation. |\n * | `.respond(error)` | Queue an `Error` to throw on the next invocation. |\n * | `.respond(factory)` | Queue a function `(messages) => BaseMessage \\| Error` for dynamic responses. |\n * | `.respondWithTools(toolCalls)` | Shorthand for `.respond()` with tool calls. Each entry needs `name` and `args`; `id` is optional. |\n * | `.alwaysThrow(error)` | Make every invocation throw this error, regardless of the queue. |\n * | `.structuredResponse(value)` | Set the value returned by `.withStructuredOutput()`. |\n * | `.bindTools(tools)` | Bind tools to the model. Returns a `RunnableBinding` that shares the response queue and call recording. |\n * | `.withStructuredOutput(schema)` | Returns a runnable that produces the `.structuredResponse()` value. |\n * | `.calls` | Array of `{ messages, options }` for every invocation (read-only). |\n * | `.callCount` | Number of times the model has been invoked. |\n *\n * @example\n * ```typescript\n * const model = fakeModel()\n * .respondWithTools([{ name: \"search\", args: { query: \"weather\" } }])\n * .respond(new AIMessage(\"Sunny and warm.\"));\n *\n * const r1 = await model.invoke([new HumanMessage(\"What's the weather?\")]);\n * // r1.tool_calls[0].name === \"search\"\n *\n * const r2 = await model.invoke([new HumanMessage(\"Thanks\")]);\n * // r2.content === \"Sunny and warm.\"\n * ```\n */\nexport function fakeModel(): FakeBuiltModel {\n return new FakeBuiltModel();\n}\n"],"mappings":";;;;;;AAgCA,SAAS,cAAc,UAAiC;AACtD,QAAO,SACJ,KAAK,MAAM,EAAE,KAAK,CAClB,OAAO,QAAQ,CACf,KAAK,IAAI;;AAGd,IAAI,YAAY;AAChB,SAAS,iBAAyB;AAChC,cAAa;AACb,QAAO,WAAW;;;;;;;;;;AAWpB,IAAa,iBAAb,MAAa,uBAAuBA,oCAAAA,cAAc;CAChD,QAA8B,EAAE;CAEhC;CAEA;CAEA,SAAgD,EAAE;CAElD,aAAqB;CAErB,SAAkC,EAAE;;;;;;CAOpC,IAAI,QAAyB;AAC3B,SAAO,KAAK;;;;;CAMd,IAAI,YAAoB;AACtB,SAAO,KAAK,OAAO;;CAGrB,cAAc;AACZ,QAAM,EAAE,CAAC;;CAGX,WAAmB;AACjB,SAAO;;CAGT,oBAAoB;AA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EAGb,MAAM,QAAQ,KAAK,MAAM;AACzB,MAAI,CAAC,MACH,OAAM,IAAI,MACR,gDAAgD,iBAAiB,IAAI,KAAK,MAAM,OAAO,iBACxF;AAGH,MAAI,MAAM,SAAS,QACjB,OAAM,MAAM;AAGd,MAAI,MAAM,SAAS,WAAW;GAC5B,MAAM,SAAS,MAAM,QAAQ,SAAS;AACtC,OAAI,CAACD,aAAAA,YAAY,WAAW,OAAO,CACjC,OAAM;AAER,UAAO,EACL,aAAa,CAAC;IAAE,MAAM;IAAI,SAAS;IAAQ,CAAC,EAC7C;;AAGH,MAAI,MAAM,SAAS,UACjB,QAAO,EACL,aAAa,CAAC;GAAE,MAAM;GAAI,SAAS,MAAM;GAAS,CAAC,EACpD;EAGH,MAAM,UAAU,cAAc,SAAS;AAavC,SAAO;GACL,aAAa,CAAC;IAAE,MAAM;IAAS,SAbjB,IAAIE,WAAAA,UAAU;KAC5B;KACA,IAAI,iBAAiB,UAAU;KAC/B,YACE,MAAM,UAAU,SAAS,IACrB,MAAM,UAAU,KAAK,QAAQ;MAC3B,GAAG;MACH,MAAM;MACP,EAAE,GACH,KAAA;KACP,CAAC;IAGwC,CAAC;GACzC,WAAW,EAAE;GACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCL,SAAgB,YAA4B;AAC1C,QAAO,IAAI,gBAAgB"}
1
+ {"version":3,"file":"fake_model_builder.cjs","names":["BaseChatModel","BaseMessage","RunnableLambda","AIMessage"],"sources":["../../src/testing/fake_model_builder.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport { CallbackManagerForLLMRun } from \"../callbacks/manager.js\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"../language_models/chat_models.js\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n StructuredOutputMethodParams,\n} from \"../language_models/base.js\";\nimport { BaseMessage, AIMessage } from \"../messages/index.js\";\nimport type { ToolCall } from \"../messages/tool.js\";\nimport type { ChatResult } from \"../outputs.js\";\nimport { Runnable, RunnableLambda } from \"../runnables/base.js\";\nimport { StructuredTool } from \"../tools/index.js\";\nimport type { InteropZodType } from \"../utils/types/zod.js\";\nimport type { ToolSpec } from \"../utils/testing/chat_models.js\";\n\ntype ResponseFactory = (messages: BaseMessage[]) => BaseMessage | Error;\n\ntype QueueEntry =\n | { kind: \"message\"; message: BaseMessage }\n | { kind: \"toolCalls\"; toolCalls: ToolCall[] }\n | { kind: \"error\"; error: Error }\n | { kind: \"factory\"; factory: ResponseFactory };\n\ninterface FakeModelCall {\n messages: BaseMessage[];\n options: any;\n}\n\ninterface FakeModelState {\n callIndex: number;\n calls: FakeModelCall[];\n}\n\nfunction deriveContent(messages: BaseMessage[]): string {\n return messages\n .map((m) => m.text)\n .filter(Boolean)\n .join(\"-\");\n}\n\nlet idCounter = 0;\nfunction nextToolCallId(): string {\n idCounter += 1;\n return `fake_tc_${idCounter}`;\n}\n\n/**\n * A fake chat model for testing, created via {@link fakeModel}.\n *\n * Queue responses with `.respond()` and `.respondWithTools()`, then\n * pass the instance directly wherever a chat model is expected.\n * Responses are consumed in first-in-first-out order — one per `invoke()` call.\n * When all queued responses are consumed, further invocations throw.\n */\nexport class FakeBuiltModel extends BaseChatModel {\n private queue: QueueEntry[] = [];\n\n private _alwaysThrowError: Error | undefined;\n\n private _structuredResponseValue: any;\n\n private _tools: (StructuredTool | ToolSpec)[] = [];\n\n private _state: FakeModelState = { callIndex: 0, calls: [] };\n\n /**\n * All invocations recorded by this model, in order.\n * Each entry contains the `messages` array and `options` that were\n * passed to `invoke()`.\n */\n get calls(): FakeModelCall[] {\n return this._state.calls;\n }\n\n /**\n * The number of times this model has been invoked.\n */\n get callCount(): number {\n return this._state.calls.length;\n }\n\n constructor() {\n super({});\n }\n\n _llmType(): string {\n return \"fake-model-builder\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n /**\n * Enqueue a response that the model will return on its next invocation.\n * @param entry A {@link BaseMessage} to return, an `Error` to throw, or\n * a factory `(messages) => BaseMessage | Error` for dynamic responses.\n * @returns `this`, for chaining.\n */\n respond(entry: BaseMessage | Error | ResponseFactory): this {\n if (typeof entry === \"function\") {\n this.queue.push({ kind: \"factory\", factory: entry });\n } else if (BaseMessage.isInstance(entry)) {\n this.queue.push({ kind: \"message\", message: entry });\n } else {\n this.queue.push({ kind: \"error\", error: entry });\n }\n return this;\n }\n\n /**\n * Enqueue an {@link AIMessage} that carries the given tool calls.\n * Content is derived from the input messages at invocation time.\n * @param toolCalls Array of tool calls. Each entry needs `name` and\n * `args`; `id` is optional and auto-generated when omitted.\n * @returns `this`, for chaining.\n */\n respondWithTools(\n toolCalls: Array<{ name: string; args: Record<string, any>; id?: string }>\n ): this {\n this.queue.push({\n kind: \"toolCalls\",\n toolCalls: toolCalls.map((tc) => ({\n name: tc.name,\n args: tc.args,\n id: tc.id ?? nextToolCallId(),\n type: \"tool_call\" as const,\n })),\n });\n return this;\n }\n\n /**\n * Make every invocation throw the given error, regardless of the queue.\n * @param error The error to throw.\n * @returns `this`, for chaining.\n */\n alwaysThrow(error: Error): this {\n this._alwaysThrowError = error;\n return this;\n }\n\n /**\n * Set the value that {@link withStructuredOutput} will resolve to.\n * @param value The structured object to return.\n * @returns `this`, for chaining.\n */\n structuredResponse(value: Record<string, any>): this {\n this._structuredResponseValue = value;\n return this;\n }\n\n /**\n * Bind tools to the model. Returns a new model that shares the same\n * response queue and call history.\n * @param tools The tools to bind, as {@link StructuredTool} instances or\n * plain {@link ToolSpec} objects.\n * @returns A new RunnableBinding with the tools bound.\n */\n bindTools(tools: (StructuredTool | ToolSpec)[]) {\n const merged = [...this._tools, ...tools];\n const next = new FakeBuiltModel();\n next.queue = this.queue;\n next._alwaysThrowError = this._alwaysThrowError;\n next._structuredResponseValue = this._structuredResponseValue;\n next._tools = merged;\n next._state = this._state;\n\n return next.withConfig({} as BaseChatModelCallOptions);\n }\n\n /**\n * Returns a {@link Runnable} that produces the {@link structuredResponse}\n * value. The schema argument is accepted for compatibility but ignored.\n * @param _params Schema or params (ignored).\n * @param _config Options (ignored).\n * @returns A Runnable that resolves to the structured response value.\n */\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n | Record<string, any>,\n _config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n const { _structuredResponseValue } = this;\n return RunnableLambda.from(async () => {\n return _structuredResponseValue as RunOutput;\n }) as Runnable;\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n this._state.calls.push({ messages: [...messages], options });\n\n const currentCallIndex = this._state.callIndex;\n this._state.callIndex += 1;\n\n if (this._alwaysThrowError) {\n throw this._alwaysThrowError;\n }\n\n const entry = this.queue[currentCallIndex];\n if (!entry) {\n throw new Error(\n `FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`\n );\n }\n\n if (entry.kind === \"error\") {\n throw entry.error;\n }\n\n if (entry.kind === \"factory\") {\n const result = entry.factory(messages);\n if (!BaseMessage.isInstance(result)) {\n throw result;\n }\n return {\n generations: [{ text: \"\", message: result }],\n };\n }\n\n if (entry.kind === \"message\") {\n return {\n generations: [{ text: \"\", message: entry.message }],\n };\n }\n\n const content = deriveContent(messages);\n const message = new AIMessage({\n content,\n id: currentCallIndex.toString(),\n tool_calls:\n entry.toolCalls.length > 0\n ? entry.toolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [{ text: content, message }],\n llmOutput: {},\n };\n }\n}\n\n/**\n * Creates a new {@link FakeBuiltModel} for testing.\n *\n * Returns a chainable builder — queue responses, then pass the model\n * anywhere a chat model is expected. Responses are consumed in FIFO\n * order, one per `invoke()` call.\n *\n * ## API summary\n *\n * | Method | Description |\n * | --- | --- |\n * | `fakeModel()` | Creates a new fake chat model. Returns a chainable builder. |\n * | `.respond(message)` | Queue an `AIMessage` (or any `BaseMessage`) to return on the next invocation. |\n * | `.respond(error)` | Queue an `Error` to throw on the next invocation. |\n * | `.respond(factory)` | Queue a function `(messages) => BaseMessage \\| Error` for dynamic responses. |\n * | `.respondWithTools(toolCalls)` | Shorthand for `.respond()` with tool calls. Each entry needs `name` and `args`; `id` is optional. |\n * | `.alwaysThrow(error)` | Make every invocation throw this error, regardless of the queue. |\n * | `.structuredResponse(value)` | Set the value returned by `.withStructuredOutput()`. |\n * | `.bindTools(tools)` | Bind tools to the model. Returns a `RunnableBinding` that shares the response queue and call recording. |\n * | `.withStructuredOutput(schema)` | Returns a runnable that produces the `.structuredResponse()` value. |\n * | `.calls` | Array of `{ messages, options }` for every invocation (read-only). |\n * | `.callCount` | Number of times the model has been invoked. |\n *\n * @example\n * ```typescript\n * const model = fakeModel()\n * .respondWithTools([{ name: \"search\", args: { query: \"weather\" } }])\n * .respond(new AIMessage(\"Sunny and warm.\"));\n *\n * const r1 = await model.invoke([new HumanMessage(\"What's the weather?\")]);\n * // r1.tool_calls[0].name === \"search\"\n *\n * const r2 = await model.invoke([new HumanMessage(\"Thanks\")]);\n * // r2.content === \"Sunny and warm.\"\n * ```\n */\nexport function fakeModel(): FakeBuiltModel {\n return new FakeBuiltModel();\n}\n"],"mappings":";;;;;;AAqCA,SAAS,cAAc,UAAiC;AACtD,QAAO,SACJ,KAAK,MAAM,EAAE,KAAK,CAClB,OAAO,QAAQ,CACf,KAAK,IAAI;;AAGd,IAAI,YAAY;AAChB,SAAS,iBAAyB;AAChC,cAAa;AACb,QAAO,WAAW;;;;;;;;;;AAWpB,IAAa,iBAAb,MAAa,uBAAuBA,oCAAAA,cAAc;CAChD,QAA8B,EAAE;CAEhC;CAEA;CAEA,SAAgD,EAAE;CAElD,SAAiC;EAAE,WA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;;CAGJ,MAAM,UACJ,UACA,SACA,aACqB;AACrB,OAAK,OAAO,MAAM,KAAK;GAAE,UAAU,CAAC,GAAG,SAAS;GAAE;GAAS,CAAC;EAE5D,MAAM,mBAAmB,KAAK,OAAO;AACrC,OAAK,OAAO,aAAa;AAEzB,MAAI,KAAK,kBACP,OAAM,KAAK;EAGb,MAAM,QAAQ,KAAK,MAAM;AACzB,MAAI,CAAC,MACH,OAAM,IAAI,MACR,gDAAgD,iBAAiB,IAAI,KAAK,MAAM,OAAO,iBACxF;AAGH,MAAI,MAAM,SAAS,QACjB,OAAM,MAAM;AAGd,MAAI,MAAM,SAAS,WAAW;GAC5B,MAAM,SAAS,MAAM,QAAQ,SAAS;AACtC,OAAI,CAACD,aAAAA,YAAY,WAAW,OAAO,CACjC,OAAM;AAER,UAAO,EACL,aAAa,CAAC;IAAE,MAAM;IAAI,SAAS;IAAQ,CAAC,EAC7C;;AAGH,MAAI,MAAM,SAAS,UACjB,QAAO,EACL,aAAa,CAAC;GAAE,MAAM;GAAI,SAAS,MAAM;GAAS,CAAC,EACpD;EAGH,MAAM,UAAU,cAAc,SAAS;AAavC,SAAO;GACL,aAAa,CAAC;IAAE,MAAM;IAAS,SAbjB,IAAIE,WAAAA,UAAU;KAC5B;KACA,IAAI,iBAAiB,UAAU;KAC/B,YACE,MAAM,UAAU,SAAS,IACrB,MAAM,UAAU,KAAK,QAAQ;MAC3B,GAAG;MACH,MAAM;MACP,EAAE,GACH,KAAA;KACP,CAAC;IAGwC,CAAC;GACzC,WAAW,EAAE;GACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCL,SAAgB,YAA4B;AAC1C,QAAO,IAAI,gBAAgB"}
@@ -29,8 +29,7 @@ declare class FakeBuiltModel extends BaseChatModel {
29
29
  private _alwaysThrowError;
30
30
  private _structuredResponseValue;
31
31
  private _tools;
32
- private _callIndex;
33
- private _calls;
32
+ private _state;
34
33
  /**
35
34
  * All invocations recorded by this model, in order.
36
35
  * Each entry contains the `messages` array and `options` that were
@@ -1 +1 @@
1
- {"version":3,"file":"fake_model_builder.d.cts","names":[],"sources":["../../src/testing/fake_model_builder.ts"],"mappings":";;;;;;;;;;;;;KAmBK,eAAA,IAAmB,QAAA,EAAU,WAAA,OAAkB,WAAA,GAAc,KAAA;AAAA,UAQxD,aAAA;EACR,QAAA,EAAU,WAAA;EACV,OAAA;AAAA;AAZ8D;;;;;;;;AAAA,cAoCnD,cAAA,SAAuB,aAAA;EAAA,QAC1B,KAAA;EAAA,QAEA,iBAAA;EAAA,QAEA,wBAAA;EAAA,QAEA,MAAA;EAAA,QAEA,UAAA;EAAA,QAEA,MAAA;EArCa;;;;;EAAA,IA4CjB,KAAA,CAAA,GAAS,aAAA;EA1CN;;AAwBT;EAxBS,IAiDH,SAAA,CAAA;EAIJ,WAAA,CAAA;EAIA,QAAA,CAAA;EAIA,iBAAA,CAAA;EAU6B;;;;;;EAA7B,OAAA,CAAQ,KAAA,EAAO,WAAA,GAAc,KAAA,GAAQ,eAAA;EA4DF;;;;;;;EA1CnC,gBAAA,CACE,SAAA,EAAW,KAAA;IAAQ,IAAA;IAAc,IAAA,EAAM,MAAA;IAAqB,EAAA;EAAA;EAkExD;;;;;EA/CN,WAAA,CAAY,KAAA,EAAO,KAAA;EAqDb;;;;;EA3CN,kBAAA,CAAmB,KAAA,EAAO,MAAA;EAwDf;;;;;;;EA5CX,SAAA,CAAU,KAAA,GAAQ,cAAA,GAAiB,QAAA,MAAW,QAAA,CAAA,sBAAA,EAAA,cAAA,CAAA,gBAAA,CAAA,cAAA,IAAA,wBAAA;EAtGtC;;;;;;;EA0HR,oBAAA,mBACoB,MAAA,gBAAsB,MAAA,cAAA,CAExC,OAAA,EACI,4BAAA,CAA6B,SAAA,aAC7B,cAAA,CAAe,SAAA,IACf,MAAA,eACJ,OAAA,GAAU,6BAAA,YAER,QAAA,CAAS,sBAAA,EAAwB,SAAA,IACjC,QAAA,CACE,sBAAA;IACE,GAAA,EAAK,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4BAAA,CAA6B,SAAA,aAC7B,cAAA,CAAe,SAAA,IACf,MAAA,eACJ,OAAA,GAAU,6BAAA,YAER,QAAA,CAAS,sBAAA,EAAwB,SAAA,IACjC,QAAA,CACE,sBAAA;IACE,GAAA,EAAK,WAAA;IAAa,MAAA,EAAQ,SAAA;EAAA;EAQ5B,SAAA,CACJ,QAAA,EAAU,WAAA,IACV,OAAA,8BACA,WAAA,GAAc,wBAAA,GACb,OAAA,CAAQ,UAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6FG,SAAA,CAAA,GAAa,cAAA"}
@@ -29,8 +29,7 @@ declare class FakeBuiltModel extends BaseChatModel {
29
29
  private _alwaysThrowError;
30
30
  private _structuredResponseValue;
31
31
  private _tools;
32
- private _callIndex;
33
- private _calls;
32
+ private _state;
34
33
  /**
35
34
  * All invocations recorded by this model, in order.
36
35
  * Each entry contains the `messages` array and `options` that were
@@ -1 +1 @@
1
- {"version":3,"file":"fake_model_builder.d.ts","names":[],"sources":["../../src/testing/fake_model_builder.ts"],"mappings":";;;;;;;;;;;;;KAmBK,eAAA,IAAmB,QAAA,EAAU,WAAA,OAAkB,WAAA,GAAc,KAAA;AAAA,UAQxD,aAAA;EACR,QAAA,EAAU,WAAA;EACV,OAAA;AAAA;AAZ8D;;;;;;;;AAAA,cAoCnD,cAAA,SAAuB,aAAA;EAAA,QAC1B,KAAA;EAAA,QAEA,iBAAA;EAAA,QAEA,wBAAA;EAAA,QAEA,MAAA;EAAA,QAEA,UAAA;EAAA,QAEA,MAAA;EArCa;;;;;EAAA,IA4CjB,KAAA,CAAA,GAAS,aAAA;EA1CN;;AAwBT;EAxBS,IAiDH,SAAA,CAAA;EAIJ,WAAA,CAAA;EAIA,QAAA,CAAA;EAIA,iBAAA,CAAA;EAU6B;;;;;;EAA7B,OAAA,CAAQ,KAAA,EAAO,WAAA,GAAc,KAAA,GAAQ,eAAA;EA4DF;;;;;;;EA1CnC,gBAAA,CACE,SAAA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A;EAIA,QAAA,CAAA;EAIA,iBAAA,CAAA;EAUe;;;;;;EAAf,OAAA,CAAQ,KAAA,EAAO,WAAA,GAAc,KAAA,GAAQ,eAAA;EA4DnB;;;;;;;EA1ClB,gBAAA,CACE,SAAA,EAAW,KAAA;IAAQ,IAAA;IAAc,IAAA,EAAM,MAAA;IAAqB,EAAA;EAAA;EAiEzC;;;;;EA9CrB,WAAA,CAAY,KAAA,EAAO,KAAA;EAkDf;;;;;EAxCJ,kBAAA,CAAmB,KAAA,EAAO,MAAA;EAsDV;;;;;;;EA1ChB,SAAA,CAAU,KAAA,GAAQ,cAAA,GAAiB,QAAA,MAAW,QAAA,CAAA,sBAAA,EAAA,cAAA,CAAA,gBAAA,CAAA,cAAA,IAAA,wBAAA;EAtGtC;;;;;;;EAyHR,oBAAA,mBACoB,MAAA,gBAAsB,MAAA,cAAA,CAExC,OAAA,EACI,4BAAA,CAA6B,SAAA,aAC7B,cAAA,CAAe,SAAA,IACf,MAAA,eACJ,OAAA,GAAU,6BAAA,YAER,QAAA,CAAS,sBAAA,EAAwB,SAAA,IACjC,QAAA,CACE,sBAAA;IACE,GAAA,EAAK,WAAA;IAAa,MAAA,EAAQ,SAAA;EAAA;EAQ5B,SAAA,CACJ,QAAA,EAAU,WAAA,IACV,OAAA,8BACA,WAAA,GAAc,wBAAA,GACb,OAAA,CAAQ,UAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6FG,SAAA,CAAA,GAAa,cAAA"}
@@ -25,21 +25,23 @@ var FakeBuiltModel = class FakeBuiltModel extends BaseChatModel {
25
25
  _alwaysThrowError;
26
26
  _structuredResponseValue;
27
27
  _tools = [];
28
- _callIndex = 0;
29
- _calls = [];
28
+ _state = {
29
+ callIndex: 0,
30
+ calls: []
31
+ };
30
32
  /**
31
33
  * All invocations recorded by this model, in order.
32
34
  * Each entry contains the `messages` array and `options` that were
33
35
  * passed to `invoke()`.
34
36
  */
35
37
  get calls() {
36
- return this._calls;
38
+ return this._state.calls;
37
39
  }
38
40
  /**
39
41
  * The number of times this model has been invoked.
40
42
  */
41
43
  get callCount() {
42
- return this._calls.length;
44
+ return this._state.calls.length;
43
45
  }
44
46
  constructor() {
45
47
  super({});
@@ -122,8 +124,7 @@ var FakeBuiltModel = class FakeBuiltModel extends BaseChatModel {
122
124
  next._alwaysThrowError = this._alwaysThrowError;
123
125
  next._structuredResponseValue = this._structuredResponseValue;
124
126
  next._tools = merged;
125
- next._calls = this._calls;
126
- next._callIndex = this._callIndex;
127
+ next._state = this._state;
127
128
  return next.withConfig({});
128
129
  }
129
130
  /**
@@ -140,12 +141,12 @@ var FakeBuiltModel = class FakeBuiltModel extends BaseChatModel {
140
141
  });
141
142
  }
142
143
  async _generate(messages, options, _runManager) {
143
- this._calls.push({
144
+ this._state.calls.push({
144
145
  messages: [...messages],
145
146
  options
146
147
  });
147
- const currentCallIndex = this._callIndex;
148
- this._callIndex += 1;
148
+ const currentCallIndex = this._state.callIndex;
149
+ this._state.callIndex += 1;
149
150
  if (this._alwaysThrowError) throw this._alwaysThrowError;
150
151
  const entry = this.queue[currentCallIndex];
151
152
  if (!entry) throw new Error(`FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`);
@@ -1 +1 @@
1
- {"version":3,"file":"fake_model_builder.js","names":[],"sources":["../../src/testing/fake_model_builder.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport { CallbackManagerForLLMRun } from \"../callbacks/manager.js\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"../language_models/chat_models.js\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n StructuredOutputMethodParams,\n} from \"../language_models/base.js\";\nimport { BaseMessage, AIMessage } from \"../messages/index.js\";\nimport type { ToolCall } from \"../messages/tool.js\";\nimport type { ChatResult } from \"../outputs.js\";\nimport { Runnable, RunnableLambda } from \"../runnables/base.js\";\nimport { StructuredTool } from \"../tools/index.js\";\nimport type { InteropZodType } from \"../utils/types/zod.js\";\nimport type { ToolSpec } from \"../utils/testing/chat_models.js\";\n\ntype ResponseFactory = (messages: BaseMessage[]) => BaseMessage | Error;\n\ntype QueueEntry =\n | { kind: \"message\"; message: BaseMessage }\n | { kind: \"toolCalls\"; toolCalls: ToolCall[] }\n | { kind: \"error\"; error: Error }\n | { kind: \"factory\"; factory: ResponseFactory };\n\ninterface FakeModelCall {\n messages: BaseMessage[];\n options: any;\n}\n\nfunction deriveContent(messages: BaseMessage[]): string {\n return messages\n .map((m) => m.text)\n .filter(Boolean)\n .join(\"-\");\n}\n\nlet idCounter = 0;\nfunction nextToolCallId(): string {\n idCounter += 1;\n return `fake_tc_${idCounter}`;\n}\n\n/**\n * A fake chat model for testing, created via {@link fakeModel}.\n *\n * Queue responses with `.respond()` and `.respondWithTools()`, then\n * pass the instance directly wherever a chat model is expected.\n * Responses are consumed in first-in-first-out order — one per `invoke()` call.\n * When all queued responses are consumed, further invocations throw.\n */\nexport class FakeBuiltModel extends BaseChatModel {\n private queue: QueueEntry[] = [];\n\n private _alwaysThrowError: Error | undefined;\n\n private _structuredResponseValue: any;\n\n private _tools: (StructuredTool | ToolSpec)[] = [];\n\n private _callIndex = 0;\n\n private _calls: FakeModelCall[] = [];\n\n /**\n * All invocations recorded by this model, in order.\n * Each entry contains the `messages` array and `options` that were\n * passed to `invoke()`.\n */\n get calls(): FakeModelCall[] {\n return this._calls;\n }\n\n /**\n * The number of times this model has been invoked.\n */\n get callCount(): number {\n return this._calls.length;\n }\n\n constructor() {\n super({});\n }\n\n _llmType(): string {\n return \"fake-model-builder\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n /**\n * Enqueue a response that the model will return on its next invocation.\n * @param entry A {@link BaseMessage} to return, an `Error` to throw, or\n * a factory `(messages) => BaseMessage | Error` for dynamic responses.\n * @returns `this`, for chaining.\n */\n respond(entry: BaseMessage | Error | ResponseFactory): this {\n if (typeof entry === \"function\") {\n this.queue.push({ kind: \"factory\", factory: entry });\n } else if (BaseMessage.isInstance(entry)) {\n this.queue.push({ kind: \"message\", message: entry });\n } else {\n this.queue.push({ kind: \"error\", error: entry });\n }\n return this;\n }\n\n /**\n * Enqueue an {@link AIMessage} that carries the given tool calls.\n * Content is derived from the input messages at invocation time.\n * @param toolCalls Array of tool calls. Each entry needs `name` and\n * `args`; `id` is optional and auto-generated when omitted.\n * @returns `this`, for chaining.\n */\n respondWithTools(\n toolCalls: Array<{ name: string; args: Record<string, any>; id?: string }>\n ): this {\n this.queue.push({\n kind: \"toolCalls\",\n toolCalls: toolCalls.map((tc) => ({\n name: tc.name,\n args: tc.args,\n id: tc.id ?? nextToolCallId(),\n type: \"tool_call\" as const,\n })),\n });\n return this;\n }\n\n /**\n * Make every invocation throw the given error, regardless of the queue.\n * @param error The error to throw.\n * @returns `this`, for chaining.\n */\n alwaysThrow(error: Error): this {\n this._alwaysThrowError = error;\n return this;\n }\n\n /**\n * Set the value that {@link withStructuredOutput} will resolve to.\n * @param value The structured object to return.\n * @returns `this`, for chaining.\n */\n structuredResponse(value: Record<string, any>): this {\n this._structuredResponseValue = value;\n return this;\n }\n\n /**\n * Bind tools to the model. Returns a new model that shares the same\n * response queue and call history.\n * @param tools The tools to bind, as {@link StructuredTool} instances or\n * plain {@link ToolSpec} objects.\n * @returns A new RunnableBinding with the tools bound.\n */\n bindTools(tools: (StructuredTool | ToolSpec)[]) {\n const merged = [...this._tools, ...tools];\n const next = new FakeBuiltModel();\n next.queue = this.queue;\n next._alwaysThrowError = this._alwaysThrowError;\n next._structuredResponseValue = this._structuredResponseValue;\n next._tools = merged;\n next._calls = this._calls;\n next._callIndex = this._callIndex;\n\n return next.withConfig({} as BaseChatModelCallOptions);\n }\n\n /**\n * Returns a {@link Runnable} that produces the {@link structuredResponse}\n * value. The schema argument is accepted for compatibility but ignored.\n * @param _params Schema or params (ignored).\n * @param _config Options (ignored).\n * @returns A Runnable that resolves to the structured response value.\n */\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n | Record<string, any>,\n _config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n const { _structuredResponseValue } = this;\n return RunnableLambda.from(async () => {\n return _structuredResponseValue as RunOutput;\n }) as Runnable;\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n this._calls.push({ messages: [...messages], options });\n\n const currentCallIndex = this._callIndex;\n this._callIndex += 1;\n\n if (this._alwaysThrowError) {\n throw this._alwaysThrowError;\n }\n\n const entry = this.queue[currentCallIndex];\n if (!entry) {\n throw new Error(\n `FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`\n );\n }\n\n if (entry.kind === \"error\") {\n throw entry.error;\n }\n\n if (entry.kind === \"factory\") {\n const result = entry.factory(messages);\n if (!BaseMessage.isInstance(result)) {\n throw result;\n }\n return {\n generations: [{ text: \"\", message: result }],\n };\n }\n\n if (entry.kind === \"message\") {\n return {\n generations: [{ text: \"\", message: entry.message }],\n };\n }\n\n const content = deriveContent(messages);\n const message = new AIMessage({\n content,\n id: currentCallIndex.toString(),\n tool_calls:\n entry.toolCalls.length > 0\n ? entry.toolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [{ text: content, message }],\n llmOutput: {},\n };\n }\n}\n\n/**\n * Creates a new {@link FakeBuiltModel} for testing.\n *\n * Returns a chainable builder — queue responses, then pass the model\n * anywhere a chat model is expected. Responses are consumed in FIFO\n * order, one per `invoke()` call.\n *\n * ## API summary\n *\n * | Method | Description |\n * | --- | --- |\n * | `fakeModel()` | Creates a new fake chat model. Returns a chainable builder. |\n * | `.respond(message)` | Queue an `AIMessage` (or any `BaseMessage`) to return on the next invocation. |\n * | `.respond(error)` | Queue an `Error` to throw on the next invocation. |\n * | `.respond(factory)` | Queue a function `(messages) => BaseMessage \\| Error` for dynamic responses. |\n * | `.respondWithTools(toolCalls)` | Shorthand for `.respond()` with tool calls. Each entry needs `name` and `args`; `id` is optional. |\n * | `.alwaysThrow(error)` | Make every invocation throw this error, regardless of the queue. |\n * | `.structuredResponse(value)` | Set the value returned by `.withStructuredOutput()`. |\n * | `.bindTools(tools)` | Bind tools to the model. Returns a `RunnableBinding` that shares the response queue and call recording. |\n * | `.withStructuredOutput(schema)` | Returns a runnable that produces the `.structuredResponse()` value. |\n * | `.calls` | Array of `{ messages, options }` for every invocation (read-only). |\n * | `.callCount` | Number of times the model has been invoked. |\n *\n * @example\n * ```typescript\n * const model = fakeModel()\n * .respondWithTools([{ name: \"search\", args: { query: \"weather\" } }])\n * .respond(new AIMessage(\"Sunny and warm.\"));\n *\n * const r1 = await model.invoke([new HumanMessage(\"What's the weather?\")]);\n * // r1.tool_calls[0].name === \"search\"\n *\n * const r2 = await model.invoke([new HumanMessage(\"Thanks\")]);\n * // r2.content === \"Sunny and warm.\"\n * ```\n */\nexport function fakeModel(): FakeBuiltModel {\n return new FakeBuiltModel();\n}\n"],"mappings":";;;;;;AAgCA,SAAS,cAAc,UAAiC;AACtD,QAAO,SACJ,KAAK,MAAM,EAAE,KAAK,CAClB,OAAO,QAAQ,CACf,KAAK,IAAI;;AAGd,IAAI,YAAY;AAChB,SAAS,iBAAyB;AAChC,cAAa;AACb,QAAO,WAAW;;;;;;;;;;AAWpB,IAAa,iBAAb,MAAa,uBAAuB,cAAc;CAChD,QAA8B,EAAE;CAEhC;CAEA;CAEA,SAAgD,EAAE;CAElD,aAAqB;CAErB,SAAkC,EAAE;;;;;;CAOpC,IAAI,QAAyB;AAC3B,SAAO,KAAK;;;;;CAMd,IAAI,YAAoB;AACtB,SAAO,KAAK,OAAO;;CAGrB,cAAc;AACZ,QAAM,EAAE,CAAC;;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I,KAAK,kBACP,OAAM,KAAK;EAGb,MAAM,QAAQ,KAAK,MAAM;AACzB,MAAI,CAAC,MACH,OAAM,IAAI,MACR,gDAAgD,iBAAiB,IAAI,KAAK,MAAM,OAAO,iBACxF;AAGH,MAAI,MAAM,SAAS,QACjB,OAAM,MAAM;AAGd,MAAI,MAAM,SAAS,WAAW;GAC5B,MAAM,SAAS,MAAM,QAAQ,SAAS;AACtC,OAAI,CAAC,YAAY,WAAW,OAAO,CACjC,OAAM;AAER,UAAO,EACL,aAAa,CAAC;IAAE,MAAM;IAAI,SAAS;IAAQ,CAAC,EAC7C;;AAGH,MAAI,MAAM,SAAS,UACjB,QAAO,EACL,aAAa,CAAC;GAAE,MAAM;GAAI,SAAS,MAAM;GAAS,CAAC,EACpD;EAGH,MAAM,UAAU,cAAc,SAAS;AAavC,SAAO;GACL,aAAa,CAAC;IAAE,MAAM;IAAS,SAbjB,IAAI,UAAU;KAC5B;KACA,IAAI,iBAAiB,UAAU;KAC/B,YACE,MAAM,UAAU,SAAS,IACrB,MAAM,UAAU,KAAK,QAAQ;MAC3B,GAAG;MACH,MAAM;MACP,EAAE,GACH,KAAA;KACP,CAAC;IAGwC,CAAC;GACzC,WAAW,EAAE;GACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCL,SAAgB,YAA4B;AAC1C,QAAO,IAAI,gBAAgB"}
1
+ {"version":3,"file":"fake_model_builder.js","names":[],"sources":["../../src/testing/fake_model_builder.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-explicit-any */\nimport { CallbackManagerForLLMRun } from \"../callbacks/manager.js\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"../language_models/chat_models.js\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n StructuredOutputMethodParams,\n} from \"../language_models/base.js\";\nimport { BaseMessage, AIMessage } from \"../messages/index.js\";\nimport type { ToolCall } from \"../messages/tool.js\";\nimport type { ChatResult } from \"../outputs.js\";\nimport { Runnable, RunnableLambda } from \"../runnables/base.js\";\nimport { StructuredTool } from \"../tools/index.js\";\nimport type { InteropZodType } from \"../utils/types/zod.js\";\nimport type { ToolSpec } from \"../utils/testing/chat_models.js\";\n\ntype ResponseFactory = (messages: BaseMessage[]) => BaseMessage | Error;\n\ntype QueueEntry =\n | { kind: \"message\"; message: BaseMessage }\n | { kind: \"toolCalls\"; toolCalls: ToolCall[] }\n | { kind: \"error\"; error: Error }\n | { kind: \"factory\"; factory: ResponseFactory };\n\ninterface FakeModelCall {\n messages: BaseMessage[];\n options: any;\n}\n\ninterface FakeModelState {\n callIndex: number;\n calls: FakeModelCall[];\n}\n\nfunction deriveContent(messages: BaseMessage[]): string {\n return messages\n .map((m) => m.text)\n .filter(Boolean)\n .join(\"-\");\n}\n\nlet idCounter = 0;\nfunction nextToolCallId(): string {\n idCounter += 1;\n return `fake_tc_${idCounter}`;\n}\n\n/**\n * A fake chat model for testing, created via {@link fakeModel}.\n *\n * Queue responses with `.respond()` and `.respondWithTools()`, then\n * pass the instance directly wherever a chat model is expected.\n * Responses are consumed in first-in-first-out order — one per `invoke()` call.\n * When all queued responses are consumed, further invocations throw.\n */\nexport class FakeBuiltModel extends BaseChatModel {\n private queue: QueueEntry[] = [];\n\n private _alwaysThrowError: Error | undefined;\n\n private _structuredResponseValue: any;\n\n private _tools: (StructuredTool | ToolSpec)[] = [];\n\n private _state: FakeModelState = { callIndex: 0, calls: [] };\n\n /**\n * All invocations recorded by this model, in order.\n * Each entry contains the `messages` array and `options` that were\n * passed to `invoke()`.\n */\n get calls(): FakeModelCall[] {\n return this._state.calls;\n }\n\n /**\n * The number of times this model has been invoked.\n */\n get callCount(): number {\n return this._state.calls.length;\n }\n\n constructor() {\n super({});\n }\n\n _llmType(): string {\n return \"fake-model-builder\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n /**\n * Enqueue a response that the model will return on its next invocation.\n * @param entry A {@link BaseMessage} to return, an `Error` to throw, or\n * a factory `(messages) => BaseMessage | Error` for dynamic responses.\n * @returns `this`, for chaining.\n */\n respond(entry: BaseMessage | Error | ResponseFactory): this {\n if (typeof entry === \"function\") {\n this.queue.push({ kind: \"factory\", factory: entry });\n } else if (BaseMessage.isInstance(entry)) {\n this.queue.push({ kind: \"message\", message: entry });\n } else {\n this.queue.push({ kind: \"error\", error: entry });\n }\n return this;\n }\n\n /**\n * Enqueue an {@link AIMessage} that carries the given tool calls.\n * Content is derived from the input messages at invocation time.\n * @param toolCalls Array of tool calls. Each entry needs `name` and\n * `args`; `id` is optional and auto-generated when omitted.\n * @returns `this`, for chaining.\n */\n respondWithTools(\n toolCalls: Array<{ name: string; args: Record<string, any>; id?: string }>\n ): this {\n this.queue.push({\n kind: \"toolCalls\",\n toolCalls: toolCalls.map((tc) => ({\n name: tc.name,\n args: tc.args,\n id: tc.id ?? nextToolCallId(),\n type: \"tool_call\" as const,\n })),\n });\n return this;\n }\n\n /**\n * Make every invocation throw the given error, regardless of the queue.\n * @param error The error to throw.\n * @returns `this`, for chaining.\n */\n alwaysThrow(error: Error): this {\n this._alwaysThrowError = error;\n return this;\n }\n\n /**\n * Set the value that {@link withStructuredOutput} will resolve to.\n * @param value The structured object to return.\n * @returns `this`, for chaining.\n */\n structuredResponse(value: Record<string, any>): this {\n this._structuredResponseValue = value;\n return this;\n }\n\n /**\n * Bind tools to the model. Returns a new model that shares the same\n * response queue and call history.\n * @param tools The tools to bind, as {@link StructuredTool} instances or\n * plain {@link ToolSpec} objects.\n * @returns A new RunnableBinding with the tools bound.\n */\n bindTools(tools: (StructuredTool | ToolSpec)[]) {\n const merged = [...this._tools, ...tools];\n const next = new FakeBuiltModel();\n next.queue = this.queue;\n next._alwaysThrowError = this._alwaysThrowError;\n next._structuredResponseValue = this._structuredResponseValue;\n next._tools = merged;\n next._state = this._state;\n\n return next.withConfig({} as BaseChatModelCallOptions);\n }\n\n /**\n * Returns a {@link Runnable} that produces the {@link structuredResponse}\n * value. The schema argument is accepted for compatibility but ignored.\n * @param _params Schema or params (ignored).\n * @param _config Options (ignored).\n * @returns A Runnable that resolves to the structured response value.\n */\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n | Record<string, any>,\n _config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n const { _structuredResponseValue } = this;\n return RunnableLambda.from(async () => {\n return _structuredResponseValue as RunOutput;\n }) as Runnable;\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n this._state.calls.push({ messages: [...messages], options });\n\n const currentCallIndex = this._state.callIndex;\n this._state.callIndex += 1;\n\n if (this._alwaysThrowError) {\n throw this._alwaysThrowError;\n }\n\n const entry = this.queue[currentCallIndex];\n if (!entry) {\n throw new Error(\n `FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`\n );\n }\n\n if (entry.kind === \"error\") {\n throw entry.error;\n }\n\n if (entry.kind === \"factory\") {\n const result = entry.factory(messages);\n if (!BaseMessage.isInstance(result)) {\n throw result;\n }\n return {\n generations: [{ text: \"\", message: result }],\n };\n }\n\n if (entry.kind === \"message\") {\n return {\n generations: [{ text: \"\", message: entry.message }],\n };\n }\n\n const content = deriveContent(messages);\n const message = new AIMessage({\n content,\n id: currentCallIndex.toString(),\n tool_calls:\n entry.toolCalls.length > 0\n ? entry.toolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [{ text: content, message }],\n llmOutput: {},\n };\n }\n}\n\n/**\n * Creates a new {@link FakeBuiltModel} for testing.\n *\n * Returns a chainable builder — queue responses, then pass the model\n * anywhere a chat model is expected. Responses are consumed in FIFO\n * order, one per `invoke()` call.\n *\n * ## API summary\n *\n * | Method | Description |\n * | --- | --- |\n * | `fakeModel()` | Creates a new fake chat model. Returns a chainable builder. |\n * | `.respond(message)` | Queue an `AIMessage` (or any `BaseMessage`) to return on the next invocation. |\n * | `.respond(error)` | Queue an `Error` to throw on the next invocation. |\n * | `.respond(factory)` | Queue a function `(messages) => BaseMessage \\| Error` for dynamic responses. |\n * | `.respondWithTools(toolCalls)` | Shorthand for `.respond()` with tool calls. Each entry needs `name` and `args`; `id` is optional. |\n * | `.alwaysThrow(error)` | Make every invocation throw this error, regardless of the queue. |\n * | `.structuredResponse(value)` | Set the value returned by `.withStructuredOutput()`. |\n * | `.bindTools(tools)` | Bind tools to the model. Returns a `RunnableBinding` that shares the response queue and call recording. |\n * | `.withStructuredOutput(schema)` | Returns a runnable that produces the `.structuredResponse()` value. |\n * | `.calls` | Array of `{ messages, options }` for every invocation (read-only). |\n * | `.callCount` | Number of times the model has been invoked. |\n *\n * @example\n * ```typescript\n * const model = fakeModel()\n * .respondWithTools([{ name: \"search\", args: { query: \"weather\" } }])\n * .respond(new AIMessage(\"Sunny and warm.\"));\n *\n * const r1 = await model.invoke([new HumanMessage(\"What's the weather?\")]);\n * // r1.tool_calls[0].name === \"search\"\n *\n * const r2 = await model.invoke([new HumanMessage(\"Thanks\")]);\n * // r2.content === \"Sunny and warm.\"\n * ```\n */\nexport function fakeModel(): FakeBuiltModel {\n return new FakeBuiltModel();\n}\n"],"mappings":";;;;;;AAqCA,SAAS,cAAc,UAAiC;AACtD,QAAO,SACJ,KAAK,MAAM,EAAE,KAAK,CAClB,OAAO,QAAQ,CACf,KAAK,IAAI;;AAGd,IAAI,YAAY;AAChB,SAAS,iBAAyB;AAChC,cAAa;AACb,QAAO,WAAW;;;;;;;;;;AAWpB,IAAa,iBAAb,MAAa,uBAAuB,cAAc;CAChD,QAA8B,EAAE;CAEhC;CAEA;CAEA,SAAgD,EAAE;CAElD,SAAiC;EAAE,WAAW;EAAG,OAAO,EAAE;EAAE;;;;;;CA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O,MAAM,KAAK;GAAE,UAAU,CAAC,GAAG,SAAS;GAAE;GAAS,CAAC;EAE5D,MAAM,mBAAmB,KAAK,OAAO;AACrC,OAAK,OAAO,aAAa;AAEzB,MAAI,KAAK,kBACP,OAAM,KAAK;EAGb,MAAM,QAAQ,KAAK,MAAM;AACzB,MAAI,CAAC,MACH,OAAM,IAAI,MACR,gDAAgD,iBAAiB,IAAI,KAAK,MAAM,OAAO,iBACxF;AAGH,MAAI,MAAM,SAAS,QACjB,OAAM,MAAM;AAGd,MAAI,MAAM,SAAS,WAAW;GAC5B,MAAM,SAAS,MAAM,QAAQ,SAAS;AACtC,OAAI,CAAC,YAAY,WAAW,OAAO,CACjC,OAAM;AAER,UAAO,EACL,aAAa,CAAC;IAAE,MAAM;IAAI,SAAS;IAAQ,CAAC,EAC7C;;AAGH,MAAI,MAAM,SAAS,UACjB,QAAO,EACL,aAAa,CAAC;GAAE,MAAM;GAAI,SAAS,MAAM;GAAS,CAAC,EACpD;EAGH,MAAM,UAAU,cAAc,SAAS;AAavC,SAAO;GACL,aAAa,CAAC;IAAE,MAAM;IAAS,SAbjB,IAAI,UAAU;KAC5B;KACA,IAAI,iBAAiB,UAAU;KAC/B,YACE,MAAM,UAAU,SAAS,IACrB,MAAM,UAAU,KAAK,QAAQ;MAC3B,GAAG;MACH,MAAM;MACP,EAAE,GACH,KAAA;KACP,CAAC;IAGwC,CAAC;GACzC,WAAW,EAAE;GACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCL,SAAgB,YAA4B;AAC1C,QAAO,IAAI,gBAAgB"}
@@ -1,10 +1,36 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
3
3
  const require_tracers_base = require("./base.cjs");
4
- let ansi_styles = require("ansi-styles");
5
- ansi_styles = require_runtime.__toESM(ansi_styles, 1);
6
4
  //#region src/tracers/console.ts
7
5
  var console_exports = /* @__PURE__ */ require_runtime.__exportAll({ ConsoleCallbackHandler: () => ConsoleCallbackHandler });
6
+ const styles = {
7
+ bold: {
8
+ open: "\x1B[1m",
9
+ close: "\x1B[22m"
10
+ },
11
+ color: {
12
+ grey: {
13
+ open: "\x1B[90m",
14
+ close: "\x1B[39m"
15
+ },
16
+ green: {
17
+ open: "\x1B[32m",
18
+ close: "\x1B[39m"
19
+ },
20
+ cyan: {
21
+ open: "\x1B[36m",
22
+ close: "\x1B[39m"
23
+ },
24
+ red: {
25
+ open: "\x1B[31m",
26
+ close: "\x1B[39m"
27
+ },
28
+ blue: {
29
+ open: "\x1B[34m",
30
+ close: "\x1B[39m"
31
+ }
32
+ }
33
+ };
8
34
  function wrap(style, text) {
9
35
  return `${style.open}${text}${style.close}`;
10
36
  }
@@ -26,7 +52,7 @@ function elapsed(run) {
26
52
  if (elapsed < 1e3) return `${elapsed}ms`;
27
53
  return `${(elapsed / 1e3).toFixed(2)}s`;
28
54
  }
29
- const { color } = ansi_styles.default;
55
+ const { color } = styles;
30
56
  /**
31
57
  * A tracer that logs all events to the console. It extends from the
32
58
  * `BaseTracer` class and overrides its methods to provide custom logging
@@ -79,7 +105,7 @@ var ConsoleCallbackHandler = class extends require_tracers_base.BaseTracer {
79
105
  getBreadcrumbs(run) {
80
106
  const string = [...this.getParents(run).reverse(), run].map((parent, i, arr) => {
81
107
  const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`;
82
- return i === arr.length - 1 ? wrap(ansi_styles.default.bold, name) : name;
108
+ return i === arr.length - 1 ? wrap(styles.bold, name) : name;
83
109
  }).join(" > ");
84
110
  return wrap(color.grey, string);
85
111
  }
@@ -1 +1 @@
1
- {"version":3,"file":"console.cjs","names":["styles","BaseTracer"],"sources":["../../src/tracers/console.ts"],"sourcesContent":["import type { CSPair } from \"ansi-styles\";\nimport styles from \"ansi-styles\";\nimport { BaseTracer, type AgentRun, type Run } from \"./base.js\";\n\nfunction wrap(style: CSPair, text: string) {\n return `${style.open}${text}${style.close}`;\n}\n\nfunction tryJsonStringify(obj: unknown, fallback: string) {\n try {\n return JSON.stringify(obj, null, 2);\n } catch {\n return fallback;\n }\n}\n\nfunction formatKVMapItem(value: unknown) {\n if (typeof value === \"string\") {\n return value.trim();\n }\n\n if (value === null || value === undefined) {\n return value;\n }\n\n return tryJsonStringify(value, value.toString());\n}\n\nfunction elapsed(run: Run): string {\n if (!run.end_time) return \"\";\n const elapsed = run.end_time - run.start_time;\n if (elapsed < 1000) {\n return `${elapsed}ms`;\n }\n return `${(elapsed / 1000).toFixed(2)}s`;\n}\n\nconst { color } = styles;\n\n/**\n * A tracer that logs all events to the console. It extends from the\n * `BaseTracer` class and overrides its methods to provide custom logging\n * functionality.\n * @example\n * ```typescript\n *\n * const llm = new ChatAnthropic({\n * temperature: 0,\n * tags: [\"example\", \"callbacks\", \"constructor\"],\n * callbacks: [new ConsoleCallbackHandler()],\n * });\n *\n * ```\n */\nexport class ConsoleCallbackHandler extends BaseTracer {\n name = \"console_callback_handler\" as const;\n\n /**\n * Method used to persist the run. In this case, it simply returns a\n * resolved promise as there's no persistence logic.\n * @param _run The run to persist.\n * @returns A resolved promise.\n */\n protected persistRun(_run: Run) {\n return Promise.resolve();\n }\n\n // utility methods\n\n /**\n * Method used to get all the parent runs of a given run.\n * @param run The run whose parents are to be retrieved.\n * @returns An array of parent runs.\n */\n getParents(run: Run) {\n const parents: Run[] = [];\n let currentRun = run;\n while (currentRun.parent_run_id) {\n const parent = this.runMap.get(currentRun.parent_run_id);\n if (parent) {\n parents.push(parent);\n currentRun = parent;\n } else {\n break;\n }\n }\n return parents;\n }\n\n /**\n * Method used to get a string representation of the run's lineage, which\n * is used in logging.\n * @param run The run whose lineage is to be retrieved.\n * @returns A string representation of the run's lineage.\n */\n getBreadcrumbs(run: Run) {\n const parents = this.getParents(run).reverse();\n const string = [...parents, run]\n .map((parent, i, arr) => {\n const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`;\n return i === arr.length - 1 ? wrap(styles.bold, name) : name;\n })\n .join(\" > \");\n return wrap(color.grey, string);\n }\n\n // logging methods\n\n /**\n * Method used to log the start of a chain run.\n * @param run The chain run that has started.\n * @returns void\n */\n onChainStart(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(\n color.green,\n \"[chain/start]\"\n )} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(\n run.inputs,\n \"[inputs]\"\n )}`\n );\n }\n\n /**\n * Method used to log the end of a chain run.\n * @param run The chain run that has ended.\n * @returns void\n */\n onChainEnd(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.cyan, \"[chain/end]\")} [${crumbs}] [${elapsed(\n run\n )}] Exiting Chain run with output: ${tryJsonStringify(\n run.outputs,\n \"[outputs]\"\n )}`\n );\n }\n\n /**\n * Method used to log any errors of a chain run.\n * @param run The chain run that has errored.\n * @returns void\n */\n onChainError(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.red, \"[chain/error]\")} [${crumbs}] [${elapsed(\n run\n )}] Chain run errored with error: ${tryJsonStringify(\n run.error,\n \"[error]\"\n )}`\n );\n }\n\n /**\n * Method used to log the start of an LLM run.\n * @param run The LLM run that has started.\n * @returns void\n */\n onLLMStart(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n const inputs =\n \"prompts\" in run.inputs\n ? { prompts: (run.inputs.prompts as string[]).map((p) => p.trim()) }\n : run.inputs;\n console.log(\n `${wrap(\n color.green,\n \"[llm/start]\"\n )} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(\n inputs,\n \"[inputs]\"\n )}`\n );\n }\n\n /**\n * Method used to log the end of an LLM run.\n * @param run The LLM run that has ended.\n * @returns void\n */\n onLLMEnd(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.cyan, \"[llm/end]\")} [${crumbs}] [${elapsed(\n run\n )}] Exiting LLM run with output: ${tryJsonStringify(\n run.outputs,\n \"[response]\"\n )}`\n );\n }\n\n /**\n * Method used to log any errors of an LLM run.\n * @param run The LLM run that has errored.\n * @returns void\n */\n onLLMError(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.red, \"[llm/error]\")} [${crumbs}] [${elapsed(\n run\n )}] LLM run errored with error: ${tryJsonStringify(run.error, \"[error]\")}`\n );\n }\n\n /**\n * Method used to log the start of a tool run.\n * @param run The tool run that has started.\n * @returns void\n */\n onToolStart(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(\n color.green,\n \"[tool/start]\"\n )} [${crumbs}] Entering Tool run with input: \"${formatKVMapItem(\n run.inputs.input\n )}\"`\n );\n }\n\n /**\n * Method used to log the end of a tool run.\n * @param run The tool run that has ended.\n * @returns void\n */\n onToolEnd(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n\n console.log(\n `${wrap(color.cyan, \"[tool/end]\")} [${crumbs}] [${elapsed(\n run\n )}] Exiting Tool run with output: \"${formatKVMapItem(\n run.outputs?.output\n )}\"`\n );\n }\n\n /**\n * Method used to log any errors of a tool run.\n * @param run The tool run that has errored.\n * @returns void\n */\n onToolError(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.red, \"[tool/error]\")} [${crumbs}] [${elapsed(\n run\n )}] Tool run errored with error: ${tryJsonStringify(\n run.error,\n \"[error]\"\n )}`\n );\n }\n\n /**\n * Method used to log the start of a retriever run.\n * @param run The retriever run that has started.\n * @returns void\n */\n onRetrieverStart(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(\n color.green,\n \"[retriever/start]\"\n )} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(\n run.inputs,\n \"[inputs]\"\n )}`\n );\n }\n\n /**\n * Method used to log the end of a retriever run.\n * @param run The retriever run that has ended.\n * @returns void\n */\n onRetrieverEnd(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.cyan, \"[retriever/end]\")} [${crumbs}] [${elapsed(\n run\n )}] Exiting Retriever run with output: ${tryJsonStringify(\n run.outputs,\n \"[outputs]\"\n )}`\n );\n }\n\n /**\n * Method used to log any errors of a retriever run.\n * @param run The retriever run that has errored.\n * @returns void\n */\n onRetrieverError(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.red, \"[retriever/error]\")} [${crumbs}] [${elapsed(\n run\n )}] Retriever run errored with error: ${tryJsonStringify(\n run.error,\n \"[error]\"\n )}`\n );\n }\n\n /**\n * Method used to log the action selected by the agent.\n * @param run The run in which the agent action occurred.\n * @returns void\n */\n onAgentAction(run: Run) {\n const agentRun = run as AgentRun;\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(\n color.blue,\n \"[agent/action]\"\n )} [${crumbs}] Agent selected action: ${tryJsonStringify(\n agentRun.actions[agentRun.actions.length - 1],\n \"[action]\"\n )}`\n );\n }\n}\n"],"mappings":";;;;;;;AAIA,SAAS,KAAK,OAAe,MAAc;AACzC,QAAO,GAAG,MAAM,OAAO,OAAO,MAAM;;AAGtC,SAAS,iBAAiB,KAAc,UAAkB;AACxD,KAAI;AACF,SAAO,KAAK,UAAU,KAAK,MAAM,EAAE;SAC7B;AACN,SAAO;;;AAIX,SAAS,gBAAgB,OAAgB;AACvC,KAAI,OAAO,UAAU,SACnB,QAAO,MAAM,MAAM;AAGrB,KAAI,UAAU,QAAQ,UAAU,KAAA,EAC9B,QAAO;AAGT,QAAO,iBAAiB,OAAO,MAAM,UAAU,CAAC;;AAGlD,SAAS,QAAQ,KAAkB;AACjC,KAAI,CAAC,IAAI,SAAU,QAAO;CAC1B,MAAM,UAAU,IAAI,WAAW,IAAI;AACnC,KAAI,UAAU,IACZ,QAAO,GAAG,QAAQ;AAEpB,QAAO,IAAI,UAAU,KAAM,QAAQ,EAAE,CAAC;;AAGxC,MAAM,EAAE,UAAUA,YAAAA;;;;;;;;;;;;;;;;AAiBlB,IAAa,yBAAb,cAA4CC,qBAAAA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M,OACN,oBACD,CAAC,IAAI,OAAO,uCAAuC,iBAClD,IAAI,QACJ,WACD,GACF;;;;;;;CAQH,eAAe,KAAU;EACvB,MAAM,SAAS,KAAK,eAAe,IAAI;AACvC,UAAQ,IACN,GAAG,KAAK,MAAM,MAAM,kBAAkB,CAAC,IAAI,OAAO,KAAK,QACrD,IACD,CAAC,uCAAuC,iBACvC,IAAI,SACJ,YACD,GACF;;;;;;;CAQH,iBAAiB,KAAU;EACzB,MAAM,SAAS,KAAK,eAAe,IAAI;AACvC,UAAQ,IACN,GAAG,KAAK,MAAM,KAAK,oBAAoB,CAAC,IAAI,OAAO,KAAK,QACtD,IACD,CAAC,sCAAsC,iBACtC,IAAI,OACJ,UACD,GACF;;;;;;;CAQH,cAAc,KAAU;EACtB,MAAM,WAAW;EACjB,MAAM,SAAS,KAAK,eAAe,IAAI;AACvC,UAAQ,IACN,GAAG,KACD,MAAM,MACN,iBACD,CAAC,IAAI,OAAO,2BAA2B,iBACtC,SAAS,QAAQ,SAAS,QAAQ,SAAS,IAC3C,WACD,GACF"}
1
+ {"version":3,"file":"console.cjs","names":["BaseTracer"],"sources":["../../src/tracers/console.ts"],"sourcesContent":["import { BaseTracer, type AgentRun, type Run } from \"./base.js\";\n\ninterface CSPair {\n open: string;\n close: string;\n}\n\nconst styles: {\n bold: CSPair;\n color: Record<\"grey\" | \"green\" | \"cyan\" | \"red\" | \"blue\", CSPair>;\n} = {\n bold: { open: \"\\u001b[1m\", close: \"\\u001b[22m\" },\n color: {\n grey: { open: \"\\u001b[90m\", close: \"\\u001b[39m\" },\n green: { open: \"\\u001b[32m\", close: \"\\u001b[39m\" },\n cyan: { open: \"\\u001b[36m\", close: \"\\u001b[39m\" },\n red: { open: \"\\u001b[31m\", close: \"\\u001b[39m\" },\n blue: { open: \"\\u001b[34m\", close: \"\\u001b[39m\" },\n },\n};\n\nfunction wrap(style: CSPair, text: string) {\n return `${style.open}${text}${style.close}`;\n}\n\nfunction tryJsonStringify(obj: unknown, fallback: string) {\n try {\n return JSON.stringify(obj, null, 2);\n } catch {\n return fallback;\n }\n}\n\nfunction formatKVMapItem(value: unknown) {\n if (typeof value === \"string\") {\n return value.trim();\n }\n\n if (value === null || value === undefined) {\n return value;\n }\n\n return tryJsonStringify(value, value.toString());\n}\n\nfunction elapsed(run: Run): string {\n if (!run.end_time) return \"\";\n const elapsed = run.end_time - run.start_time;\n if (elapsed < 1000) {\n return `${elapsed}ms`;\n }\n return `${(elapsed / 1000).toFixed(2)}s`;\n}\n\nconst { color } = styles;\n\n/**\n * A tracer that logs all events to the console. It extends from the\n * `BaseTracer` class and overrides its methods to provide custom logging\n * functionality.\n * @example\n * ```typescript\n *\n * const llm = new ChatAnthropic({\n * temperature: 0,\n * tags: [\"example\", \"callbacks\", \"constructor\"],\n * callbacks: [new ConsoleCallbackHandler()],\n * });\n *\n * ```\n */\nexport class ConsoleCallbackHandler extends BaseTracer {\n name = \"console_callback_handler\" as const;\n\n /**\n * Method used to persist the run. In this case, it simply returns a\n * resolved promise as there's no persistence logic.\n * @param _run The run to persist.\n * @returns A resolved promise.\n */\n protected persistRun(_run: Run) {\n return Promise.resolve();\n }\n\n // utility methods\n\n /**\n * Method used to get all the parent runs of a given run.\n * @param run The run whose parents are to be retrieved.\n * @returns An array of parent runs.\n */\n getParents(run: Run) {\n const parents: Run[] = [];\n let currentRun = run;\n while (currentRun.parent_run_id) {\n const parent = this.runMap.get(currentRun.parent_run_id);\n if (parent) {\n parents.push(parent);\n currentRun = parent;\n } else {\n break;\n }\n }\n return parents;\n }\n\n /**\n * Method used to get a string representation of the run's lineage, which\n * is used in logging.\n * @param run The run whose lineage is to be retrieved.\n * @returns A string representation of the run's lineage.\n */\n getBreadcrumbs(run: Run) {\n const parents = this.getParents(run).reverse();\n const string = [...parents, run]\n .map((parent, i, arr) => {\n const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`;\n return i === arr.length - 1 ? wrap(styles.bold, name) : name;\n })\n .join(\" > \");\n return wrap(color.grey, string);\n }\n\n // logging methods\n\n /**\n * Method used to log the start of a chain run.\n * @param run The chain run that has started.\n * @returns void\n */\n onChainStart(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(\n color.green,\n \"[chain/start]\"\n )} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(\n run.inputs,\n \"[inputs]\"\n )}`\n );\n }\n\n /**\n * Method used to log the end of a chain run.\n * @param run The chain run that has ended.\n * @returns void\n */\n onChainEnd(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.cyan, \"[chain/end]\")} [${crumbs}] [${elapsed(\n run\n )}] Exiting Chain run with output: ${tryJsonStringify(\n run.outputs,\n \"[outputs]\"\n )}`\n );\n }\n\n /**\n * Method used to log any errors of a chain run.\n * @param run The chain run that has errored.\n * @returns void\n */\n onChainError(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.red, \"[chain/error]\")} [${crumbs}] [${elapsed(\n run\n )}] Chain run errored with error: ${tryJsonStringify(\n run.error,\n \"[error]\"\n )}`\n );\n }\n\n /**\n * Method used to log the start of an LLM run.\n * @param run The LLM run that has started.\n * @returns void\n */\n onLLMStart(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n const inputs =\n \"prompts\" in run.inputs\n ? { prompts: (run.inputs.prompts as string[]).map((p) => p.trim()) }\n : run.inputs;\n console.log(\n `${wrap(\n color.green,\n \"[llm/start]\"\n )} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(\n inputs,\n \"[inputs]\"\n )}`\n );\n }\n\n /**\n * Method used to log the end of an LLM run.\n * @param run The LLM run that has ended.\n * @returns void\n */\n onLLMEnd(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.cyan, \"[llm/end]\")} [${crumbs}] [${elapsed(\n run\n )}] Exiting LLM run with output: ${tryJsonStringify(\n run.outputs,\n \"[response]\"\n )}`\n );\n }\n\n /**\n * Method used to log any errors of an LLM run.\n * @param run The LLM run that has errored.\n * @returns void\n */\n onLLMError(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.red, \"[llm/error]\")} [${crumbs}] [${elapsed(\n run\n )}] LLM run errored with error: ${tryJsonStringify(run.error, \"[error]\")}`\n );\n }\n\n /**\n * Method used to log the start of a tool run.\n * @param run The tool run that has started.\n * @returns void\n */\n onToolStart(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(\n color.green,\n \"[tool/start]\"\n )} [${crumbs}] Entering Tool run with input: \"${formatKVMapItem(\n run.inputs.input\n )}\"`\n );\n }\n\n /**\n * Method used to log the end of a tool run.\n * @param run The tool run that has ended.\n * @returns void\n */\n onToolEnd(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n\n console.log(\n `${wrap(color.cyan, \"[tool/end]\")} [${crumbs}] [${elapsed(\n run\n )}] Exiting Tool run with output: \"${formatKVMapItem(\n run.outputs?.output\n )}\"`\n );\n }\n\n /**\n * Method used to log any errors of a tool run.\n * @param run The tool run that has errored.\n * @returns void\n */\n onToolError(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.red, \"[tool/error]\")} [${crumbs}] [${elapsed(\n run\n )}] Tool run errored with error: ${tryJsonStringify(\n run.error,\n \"[error]\"\n )}`\n );\n }\n\n /**\n * Method used to log the start of a retriever run.\n * @param run The retriever run that has started.\n * @returns void\n */\n onRetrieverStart(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(\n color.green,\n \"[retriever/start]\"\n )} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(\n run.inputs,\n \"[inputs]\"\n )}`\n );\n }\n\n /**\n * Method used to log the end of a retriever run.\n * @param run The retriever run that has ended.\n * @returns void\n */\n onRetrieverEnd(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.cyan, \"[retriever/end]\")} [${crumbs}] [${elapsed(\n run\n )}] Exiting Retriever run with output: ${tryJsonStringify(\n run.outputs,\n \"[outputs]\"\n )}`\n );\n }\n\n /**\n * Method used to log any errors of a retriever run.\n * @param run The retriever run that has errored.\n * @returns void\n */\n onRetrieverError(run: Run) {\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(color.red, \"[retriever/error]\")} [${crumbs}] [${elapsed(\n run\n )}] Retriever run errored with error: ${tryJsonStringify(\n run.error,\n \"[error]\"\n )}`\n );\n }\n\n /**\n * Method used to log the action selected by the agent.\n * @param run The run in which the agent action occurred.\n * @returns void\n */\n onAgentAction(run: Run) {\n const agentRun = run as AgentRun;\n const crumbs = this.getBreadcrumbs(run);\n console.log(\n `${wrap(\n color.blue,\n \"[agent/action]\"\n )} [${crumbs}] Agent selected action: ${tryJsonStringify(\n agentRun.actions[agentRun.actions.length - 1],\n \"[action]\"\n )}`\n );\n }\n}\n"],"mappings":";;;;;AAOA,MAAM,SAGF;CACF,MAAM;EAAE,MAAM;EAAa,OAAO;EAAc;CAChD,OAAO;EACL,MAAM;GAAE,MAAM;GAAc,OAAO;GAAc;EACjD,OAAO;GAAE,MAAM;GAAc,OAAO;GAAc;EAClD,MAAM;GAAE,MAAM;GAAc,OAAO;GAAc;EACjD,KAAK;GAAE,MAAM;GAAc,OAAO;GAAc;EAChD,MAAM;GAAE,MAAM;GAAc,OAAO;GAAc;EAClD;CACF;AAED,SAAS,KAAK,OAAe,MAAc;AACzC,QAAO,GAAG,MAAM,OAAO,OAAO,MAAM;;AAGtC,SAAS,iBAAiB,KAAc,UAAkB;AACxD,KAAI;AACF,SAAO,KAAK,UAAU,KAAK,MAAM,EAAE;SAC7B;AACN,SAAO;;;AAIX,SAAS,gBAAgB,OAAgB;AACvC,KAAI,OAAO,UAAU,SACnB,QAAO,MAAM,MAAM;AAGrB,KAAI,UAAU,QAAQ,UAAU,KAAA,EAC9B,QAAO;AAGT,QAAO,iBAAiB,OAAO,MAAM,UAAU,CAAC;;AAGlD,SAAS,QAAQ,KAAkB;AACjC,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;;EAiBtB,aAAA,CAAc,GAAA,EAAK,GAAA;AAAA"}
1
+ {"version":3,"file":"console.d.ts","names":[],"sources":["../../src/tracers/console.ts"],"mappings":";;;;;AAuEA;;;;;;;;;;;;;cAAa,sBAAA,SAA+B,UAAA;EAC1C,IAAA;EAoLe;;;;;;EAAA,UA5KL,UAAA,CAAW,IAAA,EAAM,GAAA,GAAG,OAAA;EATsB;;;;;EAoBpD,UAAA,CAAW,GAAA,EAAK,GAAA,GAAG,GAAA;EAXE;;;;;;EAgCrB,cAAA,CAAe,GAAA,EAAK,GAAA;EAAA;;;;;EAkBpB,YAAA,CAAa,GAAA,EAAK,GAAA;EAkBF;;;;;EAAhB,UAAA,CAAW,GAAA,EAAK,GAAA;EAkCA;;;;;EAjBhB,YAAA,CAAa,GAAA,EAAK,GAAA;EAwDF;;;;;EAvChB,UAAA,CAAW,GAAA,EAAK,GAAA;EAsED;;;;;EAhDf,QAAA,CAAS,GAAA,EAAK,GAAA;EAkFQ;;;;;EAjEtB,UAAA,CAAW,GAAA,EAAK,GAAA;EAoGM;;;;;EAtFtB,WAAA,CAAY,GAAA,EAAK,GAAA;EAuGK;;;;;EAtFtB,SAAA,CAAU,GAAA,EAAK,GAAA;;;;;;EAiBf,WAAA,CAAY,GAAA,EAAK,GAAA;;;;;;EAiBjB,gBAAA,CAAiB,GAAA,EAAK,GAAA;;;;;;EAkBtB,cAAA,CAAe,GAAA,EAAK,GAAA;;;;;;EAiBpB,gBAAA,CAAiB,GAAA,EAAK,GAAA;;;;;;EAiBtB,aAAA,CAAc,GAAA,EAAK,GAAA;AAAA"}
@@ -1,8 +1,35 @@
1
1
  import { __exportAll } from "../_virtual/_rolldown/runtime.js";
2
2
  import { BaseTracer } from "./base.js";
3
- import styles from "ansi-styles";
4
3
  //#region src/tracers/console.ts
5
4
  var console_exports = /* @__PURE__ */ __exportAll({ ConsoleCallbackHandler: () => ConsoleCallbackHandler });
5
+ const styles = {
6
+ bold: {
7
+ open: "\x1B[1m",
8
+ close: "\x1B[22m"
9
+ },
10
+ color: {
11
+ grey: {
12
+ open: "\x1B[90m",
13
+ close: "\x1B[39m"
14
+ },
15
+ green: {
16
+ open: "\x1B[32m",
17
+ close: "\x1B[39m"
18
+ },
19
+ cyan: {
20
+ open: "\x1B[36m",
21
+ close: "\x1B[39m"
22
+ },
23
+ red: {
24
+ open: "\x1B[31m",
25
+ close: "\x1B[39m"
26
+ },
27
+ blue: {
28
+ open: "\x1B[34m",
29
+ close: "\x1B[39m"
30
+ }
31
+ }
32
+ };
6
33
  function wrap(style, text) {
7
34
  return `${style.open}${text}${style.close}`;
8
35
  }