@langchain/core 1.2.9 → 1.2.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/_virtual/_rolldown/runtime.cjs +1 -1
- package/dist/callbacks/dispatch/index.cjs +2 -1
- package/dist/callbacks/dispatch/index.cjs.map +1 -1
- package/dist/callbacks/dispatch/index.js +2 -1
- package/dist/callbacks/dispatch/index.js.map +1 -1
- package/dist/indexing/base.cjs +10 -6
- package/dist/indexing/base.cjs.map +1 -1
- package/dist/indexing/base.js +10 -6
- package/dist/indexing/base.js.map +1 -1
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.js +1 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/language_models/chat_models.cjs +10 -5
- package/dist/language_models/chat_models.cjs.map +1 -1
- package/dist/language_models/chat_models.js +10 -5
- package/dist/language_models/chat_models.js.map +1 -1
- package/dist/language_models/stream.cjs +0 -2
- package/dist/language_models/stream.cjs.map +1 -1
- package/dist/language_models/stream.js +0 -2
- package/dist/language_models/stream.js.map +1 -1
- package/dist/load/index.cjs +7 -5
- package/dist/load/index.cjs.map +1 -1
- package/dist/load/index.js +7 -5
- package/dist/load/index.js.map +1 -1
- package/dist/load/serializable.cjs +2 -1
- package/dist/load/serializable.cjs.map +1 -1
- package/dist/load/serializable.js +2 -1
- package/dist/load/serializable.js.map +1 -1
- package/dist/load/validation.cjs +4 -3
- package/dist/load/validation.cjs.map +1 -1
- package/dist/load/validation.js +4 -3
- package/dist/load/validation.js.map +1 -1
- package/dist/messages/base.cjs +13 -18
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.d.cts.map +1 -1
- package/dist/messages/base.d.ts.map +1 -1
- package/dist/messages/base.js +13 -18
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/block_translators/anthropic.cjs.map +1 -1
- package/dist/messages/block_translators/anthropic.js.map +1 -1
- package/dist/messages/block_translators/google.cjs +10 -9
- package/dist/messages/block_translators/google.cjs.map +1 -1
- package/dist/messages/block_translators/google.js +10 -9
- package/dist/messages/block_translators/google.js.map +1 -1
- package/dist/messages/block_translators/google_vertexai.cjs +14 -12
- package/dist/messages/block_translators/google_vertexai.cjs.map +1 -1
- package/dist/messages/block_translators/google_vertexai.js +14 -12
- package/dist/messages/block_translators/google_vertexai.js.map +1 -1
- package/dist/messages/message.cjs.map +1 -1
- package/dist/messages/message.d.cts.map +1 -1
- package/dist/messages/message.d.ts.map +1 -1
- package/dist/messages/message.js.map +1 -1
- package/dist/messages/transformers.cjs +12 -8
- package/dist/messages/transformers.cjs.map +1 -1
- package/dist/messages/transformers.js +12 -8
- package/dist/messages/transformers.js.map +1 -1
- package/dist/output_parsers/transform.cjs.map +1 -1
- package/dist/prompts/chat.cjs +2 -1
- package/dist/prompts/chat.cjs.map +1 -1
- package/dist/prompts/chat.js +2 -1
- package/dist/prompts/chat.js.map +1 -1
- package/dist/prompts/few_shot.cjs +6 -4
- package/dist/prompts/few_shot.cjs.map +1 -1
- package/dist/prompts/few_shot.js +6 -4
- package/dist/prompts/few_shot.js.map +1 -1
- package/dist/prompts/image.cjs +2 -1
- package/dist/prompts/image.cjs.map +1 -1
- package/dist/prompts/image.js +2 -1
- package/dist/prompts/image.js.map +1 -1
- package/dist/prompts/prompt.cjs.map +1 -1
- package/dist/prompts/prompt.d.cts.map +1 -1
- package/dist/prompts/prompt.d.ts.map +1 -1
- package/dist/prompts/prompt.js.map +1 -1
- package/dist/prompts/string.cjs +2 -1
- package/dist/prompts/string.cjs.map +1 -1
- package/dist/prompts/string.js +2 -1
- package/dist/prompts/string.js.map +1 -1
- package/dist/prompts/template.cjs.map +1 -1
- package/dist/prompts/template.js.map +1 -1
- package/dist/runnables/base.cjs +60 -40
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.js +60 -40
- package/dist/runnables/base.js.map +1 -1
- package/dist/runnables/branch.cjs +16 -12
- package/dist/runnables/branch.cjs.map +1 -1
- package/dist/runnables/branch.js +16 -12
- package/dist/runnables/branch.js.map +1 -1
- package/dist/runnables/config.cjs +28 -23
- package/dist/runnables/config.cjs.map +1 -1
- package/dist/runnables/config.js +28 -23
- package/dist/runnables/config.js.map +1 -1
- package/dist/runnables/graph.cjs +2 -1
- package/dist/runnables/graph.cjs.map +1 -1
- package/dist/runnables/graph.js +2 -1
- package/dist/runnables/graph.js.map +1 -1
- package/dist/runnables/passthrough.cjs +8 -6
- package/dist/runnables/passthrough.cjs.map +1 -1
- package/dist/runnables/passthrough.js +8 -6
- package/dist/runnables/passthrough.js.map +1 -1
- package/dist/singletons/async_local_storage/context.cjs.map +1 -1
- package/dist/singletons/tracer.cjs +4 -1
- package/dist/singletons/tracer.cjs.map +1 -1
- package/dist/singletons/tracer.js +4 -1
- package/dist/singletons/tracer.js.map +1 -1
- package/dist/tools/index.cjs +22 -20
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.js +22 -20
- package/dist/tools/index.js.map +1 -1
- package/dist/tracers/base.cjs +11 -10
- package/dist/tracers/base.cjs.map +1 -1
- package/dist/tracers/base.js +11 -10
- package/dist/tracers/base.js.map +1 -1
- package/dist/tracers/log_stream.cjs +7 -6
- package/dist/tracers/log_stream.cjs.map +1 -1
- package/dist/tracers/log_stream.js +7 -6
- package/dist/tracers/log_stream.js.map +1 -1
- package/dist/tracers/tracer_langchain.cjs.map +1 -1
- package/dist/utils/env.cjs.map +1 -1
- package/dist/utils/env.d.cts.map +1 -1
- package/dist/utils/env.d.ts.map +1 -1
- package/dist/utils/env.js.map +1 -1
- package/dist/utils/event_source_parse.cjs +1 -3
- package/dist/utils/event_source_parse.cjs.map +1 -1
- package/dist/utils/event_source_parse.js +1 -3
- package/dist/utils/event_source_parse.js.map +1 -1
- package/dist/utils/fast-json-patch/src/core.cjs +4 -2
- package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
- package/dist/utils/fast-json-patch/src/core.js +4 -2
- package/dist/utils/fast-json-patch/src/core.js.map +1 -1
- package/dist/utils/fast-json-patch/src/helpers.cjs.map +1 -1
- package/dist/utils/fast-json-patch/src/helpers.js.map +1 -1
- package/dist/utils/js-sha256/hash.cjs.map +1 -1
- package/dist/utils/js-sha256/hash.js.map +1 -1
- package/dist/utils/json_schema.cjs +4 -2
- package/dist/utils/json_schema.cjs.map +1 -1
- package/dist/utils/json_schema.js +4 -2
- package/dist/utils/json_schema.js.map +1 -1
- package/dist/utils/sax-js/sax.cjs +41 -35
- package/dist/utils/sax-js/sax.cjs.map +1 -1
- package/dist/utils/sax-js/sax.js +41 -35
- package/dist/utils/sax-js/sax.js.map +1 -1
- package/dist/utils/testing/chat_models.cjs +2 -1
- package/dist/utils/testing/chat_models.cjs.map +1 -1
- package/dist/utils/testing/chat_models.js +2 -1
- package/dist/utils/testing/chat_models.js.map +1 -1
- package/dist/utils/tiktoken.cjs.map +1 -1
- package/dist/utils/types/zod.cjs.map +1 -1
- package/dist/utils/types/zod.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/bigint.cjs +9 -9
- package/dist/utils/zod-to-json-schema/parsers/bigint.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/bigint.js +9 -9
- package/dist/utils/zod-to-json-schema/parsers/bigint.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/date.cjs +1 -3
- package/dist/utils/zod-to-json-schema/parsers/date.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/date.js +1 -3
- package/dist/utils/zod-to-json-schema/parsers/date.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/number.cjs +9 -9
- package/dist/utils/zod-to-json-schema/parsers/number.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/number.js +9 -9
- package/dist/utils/zod-to-json-schema/parsers/number.js.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/string.cjs +3 -13
- package/dist/utils/zod-to-json-schema/parsers/string.cjs.map +1 -1
- package/dist/utils/zod-to-json-schema/parsers/string.js +3 -13
- package/dist/utils/zod-to-json-schema/parsers/string.js.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.js","names":["isUuid","uuidv4"],"sources":["../../src/runnables/graph.ts"],"sourcesContent":["import { v4 as uuidv4, validate as isUuid } from \"../utils/uuid/index.js\";\nimport type {\n RunnableInterface,\n RunnableIOSchema,\n Node,\n Edge,\n} from \"./types.js\";\nimport { isRunnableInterface } from \"./utils.js\";\nimport { drawMermaid, drawMermaidImage } from \"./graph_mermaid.js\";\nimport { toJsonSchema } from \"../utils/json_schema.js\";\n\nexport { Node, Edge };\n\nfunction nodeDataStr(\n id: string | undefined,\n data: RunnableInterface | RunnableIOSchema\n): string {\n if (id !== undefined && !isUuid(id)) {\n return id;\n } else if (isRunnableInterface(data)) {\n try {\n let dataStr = data.getName();\n dataStr = dataStr.startsWith(\"Runnable\")\n ? dataStr.slice(\"Runnable\".length)\n : dataStr;\n return dataStr;\n } catch {\n return data.getName();\n }\n } else {\n return data.name ?? \"UnknownSchema\";\n }\n}\n\nfunction nodeDataJson(node: Node) {\n // if node.data implements Runnable\n if (isRunnableInterface(node.data)) {\n return {\n type: \"runnable\",\n data: {\n id: node.data.lc_id,\n name: node.data.getName(),\n },\n };\n } else {\n return {\n type: \"schema\",\n data: { ...toJsonSchema(node.data.schema), title: node.data.name },\n };\n }\n}\n\nexport class Graph {\n nodes: Record<string, Node> = {};\n\n edges: Edge[] = [];\n\n constructor(params?: { nodes: Record<string, Node>; edges: Edge[] }) {\n this.nodes = params?.nodes ?? this.nodes;\n this.edges = params?.edges ?? this.edges;\n }\n\n // Convert the graph to a JSON-serializable format.\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(): Record<string, any> {\n const stableNodeIds: Record<string, string | number> = {};\n Object.values(this.nodes).forEach((node, i) => {\n stableNodeIds[node.id] = isUuid(node.id) ? i : node.id;\n });\n\n return {\n nodes: Object.values(this.nodes).map((node) => ({\n id: stableNodeIds[node.id],\n ...nodeDataJson(node),\n })),\n edges: this.edges.map((edge) => {\n const item: Record<string, unknown> = {\n source: stableNodeIds[edge.source],\n target: stableNodeIds[edge.target],\n };\n\n if (typeof edge.data !== \"undefined\") {\n item.data = edge.data;\n }\n\n if (typeof edge.conditional !== \"undefined\") {\n item.conditional = edge.conditional;\n }\n return item;\n }),\n };\n }\n\n addNode(\n data: RunnableInterface | RunnableIOSchema,\n id?: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>\n ): Node {\n if (id !== undefined && this.nodes[id] !== undefined) {\n throw new Error(`Node with id ${id} already exists`);\n }\n const nodeId = id ?? uuidv4();\n const node: Node = {\n id: nodeId,\n data,\n name: nodeDataStr(id, data),\n metadata,\n };\n this.nodes[nodeId] = node;\n return node;\n }\n\n removeNode(node: Node): void {\n // Remove the node from the nodes map\n delete this.nodes[node.id];\n\n // Filter out edges connected to the node\n this.edges = this.edges.filter(\n (edge) => edge.source !== node.id && edge.target !== node.id\n );\n }\n\n addEdge(\n source: Node,\n target: Node,\n data?: string,\n conditional?: boolean\n ): Edge {\n if (this.nodes[source.id] === undefined) {\n throw new Error(`Source node ${source.id} not in graph`);\n }\n if (this.nodes[target.id] === undefined) {\n throw new Error(`Target node ${target.id} not in graph`);\n }\n const edge: Edge = {\n source: source.id,\n target: target.id,\n data,\n conditional,\n };\n this.edges.push(edge);\n return edge;\n }\n\n firstNode(): Node | undefined {\n return _firstNode(this);\n }\n\n lastNode(): Node | undefined {\n return _lastNode(this);\n }\n\n /**\n * Add all nodes and edges from another graph.\n * Note this doesn't check for duplicates, nor does it connect the graphs.\n */\n extend(graph: Graph, prefix = \"\") {\n let finalPrefix = prefix;\n const nodeIds = Object.values(graph.nodes).map((node) => node.id);\n if (nodeIds.every(isUuid)) {\n finalPrefix = \"\";\n }\n\n const prefixed = (id: string) => {\n return finalPrefix ? `${finalPrefix}:${id}` : id;\n };\n\n Object.entries(graph.nodes).forEach(([key, value]) => {\n this.nodes[prefixed(key)] = { ...value, id: prefixed(key) };\n });\n\n const newEdges = graph.edges.map((edge) => {\n return {\n ...edge,\n source: prefixed(edge.source),\n target: prefixed(edge.target),\n };\n });\n // Add all edges from the other graph\n this.edges = [...this.edges, ...newEdges];\n const first = graph.firstNode();\n const last = graph.lastNode();\n return [\n first ? { id: prefixed(first.id), data: first.data } : undefined,\n last ? { id: prefixed(last.id), data: last.data } : undefined,\n ];\n }\n\n trimFirstNode(): void {\n const firstNode = this.firstNode();\n if (firstNode && _firstNode(this, [firstNode.id])) {\n this.removeNode(firstNode);\n }\n }\n\n trimLastNode(): void {\n const lastNode = this.lastNode();\n if (lastNode && _lastNode(this, [lastNode.id])) {\n this.removeNode(lastNode);\n }\n }\n\n /**\n * Return a new graph with all nodes re-identified,\n * using their unique, readable names where possible.\n */\n reid(): Graph {\n const nodeLabels: Record<string, string> = Object.fromEntries(\n Object.values(this.nodes).map((node) => [node.id, node.name])\n );\n const nodeLabelCounts = new Map<string, number>();\n Object.values(nodeLabels).forEach((label) => {\n nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1);\n });\n\n const getNodeId = (nodeId: string): string => {\n const label = nodeLabels[nodeId];\n if (isUuid(nodeId) && nodeLabelCounts.get(label) === 1) {\n return label;\n } else {\n return nodeId;\n }\n };\n\n return new Graph({\n nodes: Object.fromEntries(\n Object.entries(this.nodes).map(([id, node]) => [\n getNodeId(id),\n { ...node, id: getNodeId(id) },\n ])\n ),\n edges: this.edges.map((edge) => ({\n ...edge,\n source: getNodeId(edge.source),\n target: getNodeId(edge.target),\n })),\n });\n }\n\n drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }): string {\n const {\n withStyles,\n curveStyle,\n nodeColors = {\n default: \"fill:#f2f0ff,line-height:1.2\",\n first: \"fill-opacity:0\",\n last: \"fill:#bfb6fc\",\n },\n wrapLabelNWords,\n } = params ?? {};\n const graph = this.reid();\n const firstNode = graph.firstNode();\n\n const lastNode = graph.lastNode();\n\n return drawMermaid(graph.nodes, graph.edges, {\n firstNode: firstNode?.id,\n lastNode: lastNode?.id,\n withStyles,\n curveStyle,\n nodeColors,\n wrapLabelNWords,\n });\n }\n\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<Blob> {\n const mermaidSyntax = this.drawMermaid(params);\n return drawMermaidImage(mermaidSyntax, {\n backgroundColor: params?.backgroundColor,\n });\n }\n}\n/**\n * Find the single node that is not a target of any edge.\n * Exclude nodes/sources with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the origin.\n */\nfunction _firstNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const targets = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.source))\n .map((edge) => edge.target)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !targets.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\n\n/**\n * Find the single node that is not a source of any edge.\n * Exclude nodes/targets with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the destination.\n */\nfunction _lastNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const sources = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.target))\n .map((edge) => edge.source)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !sources.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\n"],"mappings":";;;;;;;AAaA,SAAS,YACP,IACA,MACQ;CACR,IAAI,OAAO,KAAA,KAAa,CAACA,SAAO,EAAE,GAChC,OAAO;MACF,IAAI,oBAAoB,IAAI,GACjC,IAAI;EACF,IAAI,UAAU,KAAK,QAAQ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AEA,MAAM,QAAgB,CAAC;CACvB,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,KAAK,GAC1C,IAAI,CAAC,QAAQ,SAAS,KAAK,EAAE,KAAK,CAAC,QAAQ,IAAI,KAAK,EAAE,GACpD,MAAM,KAAK,IAAI;CAGnB,OAAO,MAAM,WAAW,IAAI,MAAM,KAAK,KAAA;AACzC"}
|
|
1
|
+
{"version":3,"file":"graph.js","names":["isUuid","uuidv4"],"sources":["../../src/runnables/graph.ts"],"sourcesContent":["import { v4 as uuidv4, validate as isUuid } from \"../utils/uuid/index.js\";\nimport type {\n RunnableInterface,\n RunnableIOSchema,\n Node,\n Edge,\n} from \"./types.js\";\nimport { isRunnableInterface } from \"./utils.js\";\nimport { drawMermaid, drawMermaidImage } from \"./graph_mermaid.js\";\nimport { toJsonSchema } from \"../utils/json_schema.js\";\n\nexport { Node, Edge };\n\nfunction nodeDataStr(\n id: string | undefined,\n data: RunnableInterface | RunnableIOSchema\n): string {\n if (id !== undefined && !isUuid(id)) {\n return id;\n } else if (isRunnableInterface(data)) {\n try {\n let dataStr = data.getName();\n dataStr = dataStr.startsWith(\"Runnable\")\n ? dataStr.slice(\"Runnable\".length)\n : dataStr;\n return dataStr;\n } catch {\n return data.getName();\n }\n } else {\n return data.name ?? \"UnknownSchema\";\n }\n}\n\nfunction nodeDataJson(node: Node) {\n // if node.data implements Runnable\n if (isRunnableInterface(node.data)) {\n return {\n type: \"runnable\",\n data: {\n id: node.data.lc_id,\n name: node.data.getName(),\n },\n };\n } else {\n return {\n type: \"schema\",\n data: { ...toJsonSchema(node.data.schema), title: node.data.name },\n };\n }\n}\n\nexport class Graph {\n nodes: Record<string, Node> = {};\n\n edges: Edge[] = [];\n\n constructor(params?: { nodes: Record<string, Node>; edges: Edge[] }) {\n this.nodes = params?.nodes ?? this.nodes;\n this.edges = params?.edges ?? this.edges;\n }\n\n // Convert the graph to a JSON-serializable format.\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n toJSON(): Record<string, any> {\n const stableNodeIds: Record<string, string | number> = {};\n Object.values(this.nodes).forEach((node, i) => {\n stableNodeIds[node.id] = isUuid(node.id) ? i : node.id;\n });\n\n return {\n nodes: Object.values(this.nodes).map((node) => ({\n id: stableNodeIds[node.id],\n ...nodeDataJson(node),\n })),\n edges: this.edges.map((edge) => {\n const item: Record<string, unknown> = {\n source: stableNodeIds[edge.source],\n target: stableNodeIds[edge.target],\n };\n\n if (typeof edge.data !== \"undefined\") {\n item.data = edge.data;\n }\n\n if (typeof edge.conditional !== \"undefined\") {\n item.conditional = edge.conditional;\n }\n return item;\n }),\n };\n }\n\n addNode(\n data: RunnableInterface | RunnableIOSchema,\n id?: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n metadata?: Record<string, any>\n ): Node {\n if (id !== undefined && this.nodes[id] !== undefined) {\n throw new Error(`Node with id ${id} already exists`);\n }\n const nodeId = id ?? uuidv4();\n const node: Node = {\n id: nodeId,\n data,\n name: nodeDataStr(id, data),\n metadata,\n };\n this.nodes[nodeId] = node;\n return node;\n }\n\n removeNode(node: Node): void {\n // Remove the node from the nodes map\n delete this.nodes[node.id];\n\n // Filter out edges connected to the node\n this.edges = this.edges.filter(\n (edge) => edge.source !== node.id && edge.target !== node.id\n );\n }\n\n addEdge(\n source: Node,\n target: Node,\n data?: string,\n conditional?: boolean\n ): Edge {\n if (this.nodes[source.id] === undefined) {\n throw new Error(`Source node ${source.id} not in graph`);\n }\n if (this.nodes[target.id] === undefined) {\n throw new Error(`Target node ${target.id} not in graph`);\n }\n const edge: Edge = {\n source: source.id,\n target: target.id,\n data,\n conditional,\n };\n this.edges.push(edge);\n return edge;\n }\n\n firstNode(): Node | undefined {\n return _firstNode(this);\n }\n\n lastNode(): Node | undefined {\n return _lastNode(this);\n }\n\n /**\n * Add all nodes and edges from another graph.\n * Note this doesn't check for duplicates, nor does it connect the graphs.\n */\n extend(graph: Graph, prefix = \"\") {\n let finalPrefix = prefix;\n const nodeIds = Object.values(graph.nodes).map((node) => node.id);\n if (nodeIds.every(isUuid)) {\n finalPrefix = \"\";\n }\n\n const prefixed = (id: string) => {\n return finalPrefix ? `${finalPrefix}:${id}` : id;\n };\n\n Object.entries(graph.nodes).forEach(([key, value]) => {\n this.nodes[prefixed(key)] = { ...value, id: prefixed(key) };\n });\n\n const newEdges = graph.edges.map((edge) => {\n return {\n ...edge,\n source: prefixed(edge.source),\n target: prefixed(edge.target),\n };\n });\n // Add all edges from the other graph\n this.edges = [...this.edges, ...newEdges];\n const first = graph.firstNode();\n const last = graph.lastNode();\n return [\n first ? { id: prefixed(first.id), data: first.data } : undefined,\n last ? { id: prefixed(last.id), data: last.data } : undefined,\n ];\n }\n\n trimFirstNode(): void {\n const firstNode = this.firstNode();\n if (firstNode && _firstNode(this, [firstNode.id])) {\n this.removeNode(firstNode);\n }\n }\n\n trimLastNode(): void {\n const lastNode = this.lastNode();\n if (lastNode && _lastNode(this, [lastNode.id])) {\n this.removeNode(lastNode);\n }\n }\n\n /**\n * Return a new graph with all nodes re-identified,\n * using their unique, readable names where possible.\n */\n reid(): Graph {\n const nodeLabels: Record<string, string> = Object.fromEntries(\n Object.values(this.nodes).map((node) => [node.id, node.name])\n );\n const nodeLabelCounts = new Map<string, number>();\n Object.values(nodeLabels).forEach((label) => {\n nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1);\n });\n\n const getNodeId = (nodeId: string): string => {\n const label = nodeLabels[nodeId];\n if (isUuid(nodeId) && nodeLabelCounts.get(label) === 1) {\n return label;\n } else {\n return nodeId;\n }\n };\n\n return new Graph({\n nodes: Object.fromEntries(\n Object.entries(this.nodes).map(([id, node]) => [\n getNodeId(id),\n { ...node, id: getNodeId(id) },\n ])\n ),\n edges: this.edges.map((edge) => ({\n ...edge,\n source: getNodeId(edge.source),\n target: getNodeId(edge.target),\n })),\n });\n }\n\n drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n }): string {\n const {\n withStyles,\n curveStyle,\n nodeColors = {\n default: \"fill:#f2f0ff,line-height:1.2\",\n first: \"fill-opacity:0\",\n last: \"fill:#bfb6fc\",\n },\n wrapLabelNWords,\n } = params ?? {};\n const graph = this.reid();\n const firstNode = graph.firstNode();\n\n const lastNode = graph.lastNode();\n\n return drawMermaid(graph.nodes, graph.edges, {\n firstNode: firstNode?.id,\n lastNode: lastNode?.id,\n withStyles,\n curveStyle,\n nodeColors,\n wrapLabelNWords,\n });\n }\n\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<Blob> {\n const mermaidSyntax = this.drawMermaid(params);\n return drawMermaidImage(mermaidSyntax, {\n backgroundColor: params?.backgroundColor,\n });\n }\n}\n/**\n * Find the single node that is not a target of any edge.\n * Exclude nodes/sources with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the origin.\n */\nfunction _firstNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const targets = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.source))\n .map((edge) => edge.target)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !targets.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\n\n/**\n * Find the single node that is not a source of any edge.\n * Exclude nodes/targets with ids in the exclude list.\n * If there is no such node, or there are multiple, return undefined.\n * When drawing the graph, this node would be the destination.\n */\nfunction _lastNode(graph: Graph, exclude: string[] = []): Node | undefined {\n const sources = new Set(\n graph.edges\n .filter((edge) => !exclude.includes(edge.target))\n .map((edge) => edge.source)\n );\n\n const found: Node[] = [];\n for (const node of Object.values(graph.nodes)) {\n if (!exclude.includes(node.id) && !sources.has(node.id)) {\n found.push(node);\n }\n }\n return found.length === 1 ? found[0] : undefined;\n}\n"],"mappings":";;;;;;;AAaA,SAAS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AU,OAAc,UAAoB,CAAC,GAAqB;CACzE,MAAM,UAAU,IAAI,IAClB,MAAM,MACH,QAAQ,SAAS,CAAC,QAAQ,SAAS,KAAK,MAAM,CAAC,CAAC,CAChD,KAAK,SAAS,KAAK,MAAM,CAC9B;CAEA,MAAM,QAAgB,CAAC;CACvB,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,KAAK,GAC1C,IAAI,CAAC,QAAQ,SAAS,KAAK,EAAE,KAAK,CAAC,QAAQ,IAAI,KAAK,EAAE,GACpD,MAAM,KAAK,IAAI;CAGnB,OAAO,MAAM,WAAW,IAAI,MAAM,KAAK,KAAA;AACzC"}
|
|
@@ -50,12 +50,14 @@ var RunnablePassthrough = class extends require_base.Runnable {
|
|
|
50
50
|
let finalOutputSupported = true;
|
|
51
51
|
for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) {
|
|
52
52
|
yield chunk;
|
|
53
|
-
if (finalOutputSupported)
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
53
|
+
if (finalOutputSupported) {
|
|
54
|
+
if (finalOutput === void 0) finalOutput = chunk;
|
|
55
|
+
else try {
|
|
56
|
+
finalOutput = require_utils_stream.concat(finalOutput, chunk);
|
|
57
|
+
} catch {
|
|
58
|
+
finalOutput = void 0;
|
|
59
|
+
finalOutputSupported = false;
|
|
60
|
+
}
|
|
59
61
|
}
|
|
60
62
|
}
|
|
61
63
|
if (this.func && finalOutput !== void 0) await this.func(finalOutput, config);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"passthrough.cjs","names":["Runnable","ensureConfig","concat","RunnableAssign","RunnableMap"],"sources":["../../src/runnables/passthrough.ts"],"sourcesContent":["import { concat } from \"../utils/stream.js\";\nimport {\n Runnable,\n RunnableAssign,\n RunnableMap,\n RunnableMapLike,\n} from \"./base.js\";\nimport { ensureConfig, type RunnableConfig } from \"./config.js\";\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype RunnablePassthroughFunc<RunInput = any> =\n | ((input: RunInput) => void)\n | ((input: RunInput, config?: RunnableConfig) => void)\n | ((input: RunInput) => Promise<void>)\n | ((input: RunInput, config?: RunnableConfig) => Promise<void>);\n\n/**\n * A runnable to passthrough inputs unchanged or with additional keys.\n *\n * This runnable behaves almost like the identity function, except that it\n * can be configured to add additional keys to the output, if the input is\n * an object.\n *\n * The example below demonstrates how to use `RunnablePassthrough to\n * passthrough the input from the `.invoke()`\n *\n * @example\n * ```typescript\n * const chain = RunnableSequence.from([\n * {\n * question: new RunnablePassthrough(),\n * context: async () => loadContextFromStore(),\n * },\n * prompt,\n * llm,\n * outputParser,\n * ]);\n * const response = await chain.invoke(\n * \"I can pass a single string instead of an object since I'm using `RunnablePassthrough`.\"\n * );\n * ```\n */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport class RunnablePassthrough<RunInput = any> extends Runnable<\n RunInput,\n RunInput\n> {\n static lc_name() {\n return \"RunnablePassthrough\";\n }\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n lc_serializable = true;\n\n func?: RunnablePassthroughFunc<RunInput>;\n\n constructor(fields?: { func?: RunnablePassthroughFunc<RunInput> }) {\n super(fields);\n if (fields) {\n this.func = fields.func;\n }\n }\n\n async invoke(\n input: RunInput,\n options?: Partial<RunnableConfig>\n ): Promise<RunInput> {\n const config = ensureConfig(options);\n if (this.func) {\n await this.func(input, config);\n }\n\n return this._callWithConfig(\n (input: RunInput) => Promise.resolve(input),\n input,\n config\n );\n }\n\n async *transform(\n generator: AsyncGenerator<RunInput>,\n options: Partial<RunnableConfig>\n ): AsyncGenerator<RunInput> {\n const config = ensureConfig(options);\n let finalOutput: RunInput | undefined;\n let finalOutputSupported = true;\n\n for await (const chunk of this._transformStreamWithConfig(\n generator,\n (input: AsyncGenerator<RunInput>) => input,\n config\n )) {\n yield chunk;\n if (finalOutputSupported) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n } else {\n try {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n finalOutput = concat(finalOutput, chunk as any);\n } catch {\n finalOutput = undefined;\n finalOutputSupported = false;\n }\n }\n }\n }\n\n if (this.func && finalOutput !== undefined) {\n await this.func(finalOutput, config);\n }\n }\n\n /**\n * A runnable that assigns key-value pairs to the input.\n *\n * The example below shows how you could use it with an inline function.\n *\n * @example\n * ```typescript\n * const prompt =\n * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema}\n * Question: {question}\n * SQL Query:`);\n *\n * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()`\n * // call (in this example it's the question), along with any inputs passed to the `.assign()` method.\n * // In this case, we're passing the schema.\n * const sqlQueryGeneratorChain = RunnableSequence.from([\n * RunnablePassthrough.assign({\n * schema: async () => db.getTableInfo(),\n * }),\n * prompt,\n * new ChatOpenAI({ model: \"gpt-4o-mini\" }).withConfig({ stop: [\"\\nSQLResult:\"] }),\n * new StringOutputParser(),\n * ]);\n * const result = await sqlQueryGeneratorChain.invoke({\n * question: \"How many employees are there?\",\n * });\n * ```\n */\n static assign<\n RunInput extends Record<string, unknown> = Record<string, unknown>,\n RunOutput extends Record<string, unknown> = Record<string, unknown>,\n >(\n mapping: RunnableMapLike<RunInput, RunOutput>\n ): RunnableAssign<RunInput, RunInput & RunOutput> {\n return new RunnableAssign(new RunnableMap({ steps: mapping }));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,sBAAb,cAAyDA,aAAAA,SAGvD;CACA,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe,CAAC,kBAAkB,WAAW;CAE7C,kBAAkB;CAElB;CAEA,YAAY,QAAuD;EACjE,MAAM,MAAM;EACZ,IAAI,QACF,KAAK,OAAO,OAAO;CAEvB;CAEA,MAAM,OACJ,OACA,SACmB;EACnB,MAAM,SAASC,eAAAA,aAAa,OAAO;EACnC,IAAI,KAAK,MACP,MAAM,KAAK,KAAK,OAAO,MAAM;EAG/B,OAAO,KAAK,iBACT,UAAoB,QAAQ,QAAQ,KAAK,GAC1C,OACA,MACF;CACF;CAEA,OAAO,UACL,WACA,SAC0B;EAC1B,MAAM,SAASA,eAAAA,aAAa,OAAO;EACnC,IAAI;EACJ,IAAI,uBAAuB;EAE3B,WAAW,MAAM,SAAS,KAAK,2BAC7B,YACC,UAAoC,OACrC,MACF,GAAG;GACD,MAAM;GACN,IAAI,
|
|
1
|
+
{"version":3,"file":"passthrough.cjs","names":["Runnable","ensureConfig","concat","RunnableAssign","RunnableMap"],"sources":["../../src/runnables/passthrough.ts"],"sourcesContent":["import { concat } from \"../utils/stream.js\";\nimport {\n Runnable,\n RunnableAssign,\n RunnableMap,\n RunnableMapLike,\n} from \"./base.js\";\nimport { ensureConfig, type RunnableConfig } from \"./config.js\";\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype RunnablePassthroughFunc<RunInput = any> =\n | ((input: RunInput) => void)\n | ((input: RunInput, config?: RunnableConfig) => void)\n | ((input: RunInput) => Promise<void>)\n | ((input: RunInput, config?: RunnableConfig) => Promise<void>);\n\n/**\n * A runnable to passthrough inputs unchanged or with additional keys.\n *\n * This runnable behaves almost like the identity function, except that it\n * can be configured to add additional keys to the output, if the input is\n * an object.\n *\n * The example below demonstrates how to use `RunnablePassthrough to\n * passthrough the input from the `.invoke()`\n *\n * @example\n * ```typescript\n * const chain = RunnableSequence.from([\n * {\n * question: new RunnablePassthrough(),\n * context: async () => loadContextFromStore(),\n * },\n * prompt,\n * llm,\n * outputParser,\n * ]);\n * const response = await chain.invoke(\n * \"I can pass a single string instead of an object since I'm using `RunnablePassthrough`.\"\n * );\n * ```\n */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport class RunnablePassthrough<RunInput = any> extends Runnable<\n RunInput,\n RunInput\n> {\n static lc_name() {\n return \"RunnablePassthrough\";\n }\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n lc_serializable = true;\n\n func?: RunnablePassthroughFunc<RunInput>;\n\n constructor(fields?: { func?: RunnablePassthroughFunc<RunInput> }) {\n super(fields);\n if (fields) {\n this.func = fields.func;\n }\n }\n\n async invoke(\n input: RunInput,\n options?: Partial<RunnableConfig>\n ): Promise<RunInput> {\n const config = ensureConfig(options);\n if (this.func) {\n await this.func(input, config);\n }\n\n return this._callWithConfig(\n (input: RunInput) => Promise.resolve(input),\n input,\n config\n );\n }\n\n async *transform(\n generator: AsyncGenerator<RunInput>,\n options: Partial<RunnableConfig>\n ): AsyncGenerator<RunInput> {\n const config = ensureConfig(options);\n let finalOutput: RunInput | undefined;\n let finalOutputSupported = true;\n\n for await (const chunk of this._transformStreamWithConfig(\n generator,\n (input: AsyncGenerator<RunInput>) => input,\n config\n )) {\n yield chunk;\n if (finalOutputSupported) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n } else {\n try {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n finalOutput = concat(finalOutput, chunk as any);\n } catch {\n finalOutput = undefined;\n finalOutputSupported = false;\n }\n }\n }\n }\n\n if (this.func && finalOutput !== undefined) {\n await this.func(finalOutput, config);\n }\n }\n\n /**\n * A runnable that assigns key-value pairs to the input.\n *\n * The example below shows how you could use it with an inline function.\n *\n * @example\n * ```typescript\n * const prompt =\n * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema}\n * Question: {question}\n * SQL Query:`);\n *\n * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()`\n * // call (in this example it's the question), along with any inputs passed to the `.assign()` method.\n * // In this case, we're passing the schema.\n * const sqlQueryGeneratorChain = RunnableSequence.from([\n * RunnablePassthrough.assign({\n * schema: async () => db.getTableInfo(),\n * }),\n * prompt,\n * new ChatOpenAI({ model: \"gpt-4o-mini\" }).withConfig({ stop: [\"\\nSQLResult:\"] }),\n * new StringOutputParser(),\n * ]);\n * const result = await sqlQueryGeneratorChain.invoke({\n * question: \"How many employees are there?\",\n * });\n * ```\n */\n static assign<\n RunInput extends Record<string, unknown> = Record<string, unknown>,\n RunOutput extends Record<string, unknown> = Record<string, unknown>,\n >(\n mapping: RunnableMapLike<RunInput, RunOutput>\n ): RunnableAssign<RunInput, RunInput & RunOutput> {\n return new RunnableAssign(new RunnableMap({ steps: mapping }));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,sBAAb,cAAyDA,aAAAA,SAGvD;CACA,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe,CAAC,kBAAkB,WAAW;CAE7C,kBAAkB;CAElB;CAEA,YAAY,QAAuD;EACjE,MAAM,MAAM;EACZ,IAAI,QACF,KAAK,OAAO,OAAO;CAEvB;CAEA,MAAM,OACJ,OACA,SACmB;EACnB,MAAM,SAASC,eAAAA,aAAa,OAAO;EACnC,IAAI,KAAK,MACP,MAAM,KAAK,KAAK,OAAO,MAAM;EAG/B,OAAO,KAAK,iBACT,UAAoB,QAAQ,QAAQ,KAAK,GAC1C,OACA,MACF;CACF;CAEA,OAAO,UACL,WACA,SAC0B;EAC1B,MAAM,SAASA,eAAAA,aAAa,OAAO;EACnC,IAAI;EACJ,IAAI,uBAAuB;EAE3B,WAAW,MAAM,SAAS,KAAK,2BAC7B,YACC,UAAoC,OACrC,MACF,GAAG;GACD,MAAM;GACN,IAAI,sBAAsB;IACxB,IAAI,gBAAgB,KAAA,GAClB,cAAc;SAEd,IAAI;KAEF,cAAcC,qBAAAA,OAAO,aAAa,KAAY;IAChD,QAAQ;KACN,cAAc,KAAA;KACd,uBAAuB;IACzB;GAEJ;EACF;EAEA,IAAI,KAAK,QAAQ,gBAAgB,KAAA,GAC/B,MAAM,KAAK,KAAK,aAAa,MAAM;CAEvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BA,OAAO,OAIL,SACgD;EAChD,OAAO,IAAIC,aAAAA,eAAe,IAAIC,aAAAA,YAAY,EAAE,OAAO,QAAQ,CAAC,CAAC;CAC/D;AACF"}
|
|
@@ -50,12 +50,14 @@ var RunnablePassthrough = class extends Runnable {
|
|
|
50
50
|
let finalOutputSupported = true;
|
|
51
51
|
for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) {
|
|
52
52
|
yield chunk;
|
|
53
|
-
if (finalOutputSupported)
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
53
|
+
if (finalOutputSupported) {
|
|
54
|
+
if (finalOutput === void 0) finalOutput = chunk;
|
|
55
|
+
else try {
|
|
56
|
+
finalOutput = concat(finalOutput, chunk);
|
|
57
|
+
} catch {
|
|
58
|
+
finalOutput = void 0;
|
|
59
|
+
finalOutputSupported = false;
|
|
60
|
+
}
|
|
59
61
|
}
|
|
60
62
|
}
|
|
61
63
|
if (this.func && finalOutput !== void 0) await this.func(finalOutput, config);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"passthrough.js","names":[],"sources":["../../src/runnables/passthrough.ts"],"sourcesContent":["import { concat } from \"../utils/stream.js\";\nimport {\n Runnable,\n RunnableAssign,\n RunnableMap,\n RunnableMapLike,\n} from \"./base.js\";\nimport { ensureConfig, type RunnableConfig } from \"./config.js\";\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype RunnablePassthroughFunc<RunInput = any> =\n | ((input: RunInput) => void)\n | ((input: RunInput, config?: RunnableConfig) => void)\n | ((input: RunInput) => Promise<void>)\n | ((input: RunInput, config?: RunnableConfig) => Promise<void>);\n\n/**\n * A runnable to passthrough inputs unchanged or with additional keys.\n *\n * This runnable behaves almost like the identity function, except that it\n * can be configured to add additional keys to the output, if the input is\n * an object.\n *\n * The example below demonstrates how to use `RunnablePassthrough to\n * passthrough the input from the `.invoke()`\n *\n * @example\n * ```typescript\n * const chain = RunnableSequence.from([\n * {\n * question: new RunnablePassthrough(),\n * context: async () => loadContextFromStore(),\n * },\n * prompt,\n * llm,\n * outputParser,\n * ]);\n * const response = await chain.invoke(\n * \"I can pass a single string instead of an object since I'm using `RunnablePassthrough`.\"\n * );\n * ```\n */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport class RunnablePassthrough<RunInput = any> extends Runnable<\n RunInput,\n RunInput\n> {\n static lc_name() {\n return \"RunnablePassthrough\";\n }\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n lc_serializable = true;\n\n func?: RunnablePassthroughFunc<RunInput>;\n\n constructor(fields?: { func?: RunnablePassthroughFunc<RunInput> }) {\n super(fields);\n if (fields) {\n this.func = fields.func;\n }\n }\n\n async invoke(\n input: RunInput,\n options?: Partial<RunnableConfig>\n ): Promise<RunInput> {\n const config = ensureConfig(options);\n if (this.func) {\n await this.func(input, config);\n }\n\n return this._callWithConfig(\n (input: RunInput) => Promise.resolve(input),\n input,\n config\n );\n }\n\n async *transform(\n generator: AsyncGenerator<RunInput>,\n options: Partial<RunnableConfig>\n ): AsyncGenerator<RunInput> {\n const config = ensureConfig(options);\n let finalOutput: RunInput | undefined;\n let finalOutputSupported = true;\n\n for await (const chunk of this._transformStreamWithConfig(\n generator,\n (input: AsyncGenerator<RunInput>) => input,\n config\n )) {\n yield chunk;\n if (finalOutputSupported) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n } else {\n try {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n finalOutput = concat(finalOutput, chunk as any);\n } catch {\n finalOutput = undefined;\n finalOutputSupported = false;\n }\n }\n }\n }\n\n if (this.func && finalOutput !== undefined) {\n await this.func(finalOutput, config);\n }\n }\n\n /**\n * A runnable that assigns key-value pairs to the input.\n *\n * The example below shows how you could use it with an inline function.\n *\n * @example\n * ```typescript\n * const prompt =\n * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema}\n * Question: {question}\n * SQL Query:`);\n *\n * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()`\n * // call (in this example it's the question), along with any inputs passed to the `.assign()` method.\n * // In this case, we're passing the schema.\n * const sqlQueryGeneratorChain = RunnableSequence.from([\n * RunnablePassthrough.assign({\n * schema: async () => db.getTableInfo(),\n * }),\n * prompt,\n * new ChatOpenAI({ model: \"gpt-4o-mini\" }).withConfig({ stop: [\"\\nSQLResult:\"] }),\n * new StringOutputParser(),\n * ]);\n * const result = await sqlQueryGeneratorChain.invoke({\n * question: \"How many employees are there?\",\n * });\n * ```\n */\n static assign<\n RunInput extends Record<string, unknown> = Record<string, unknown>,\n RunOutput extends Record<string, unknown> = Record<string, unknown>,\n >(\n mapping: RunnableMapLike<RunInput, RunOutput>\n ): RunnableAssign<RunInput, RunInput & RunOutput> {\n return new RunnableAssign(new RunnableMap({ steps: mapping }));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,sBAAb,cAAyD,SAGvD;CACA,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe,CAAC,kBAAkB,WAAW;CAE7C,kBAAkB;CAElB;CAEA,YAAY,QAAuD;EACjE,MAAM,MAAM;EACZ,IAAI,QACF,KAAK,OAAO,OAAO;CAEvB;CAEA,MAAM,OACJ,OACA,SACmB;EACnB,MAAM,SAAS,aAAa,OAAO;EACnC,IAAI,KAAK,MACP,MAAM,KAAK,KAAK,OAAO,MAAM;EAG/B,OAAO,KAAK,iBACT,UAAoB,QAAQ,QAAQ,KAAK,GAC1C,OACA,MACF;CACF;CAEA,OAAO,UACL,WACA,SAC0B;EAC1B,MAAM,SAAS,aAAa,OAAO;EACnC,IAAI;EACJ,IAAI,uBAAuB;EAE3B,WAAW,MAAM,SAAS,KAAK,2BAC7B,YACC,UAAoC,OACrC,MACF,GAAG;GACD,MAAM;GACN,IAAI,
|
|
1
|
+
{"version":3,"file":"passthrough.js","names":[],"sources":["../../src/runnables/passthrough.ts"],"sourcesContent":["import { concat } from \"../utils/stream.js\";\nimport {\n Runnable,\n RunnableAssign,\n RunnableMap,\n RunnableMapLike,\n} from \"./base.js\";\nimport { ensureConfig, type RunnableConfig } from \"./config.js\";\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype RunnablePassthroughFunc<RunInput = any> =\n | ((input: RunInput) => void)\n | ((input: RunInput, config?: RunnableConfig) => void)\n | ((input: RunInput) => Promise<void>)\n | ((input: RunInput, config?: RunnableConfig) => Promise<void>);\n\n/**\n * A runnable to passthrough inputs unchanged or with additional keys.\n *\n * This runnable behaves almost like the identity function, except that it\n * can be configured to add additional keys to the output, if the input is\n * an object.\n *\n * The example below demonstrates how to use `RunnablePassthrough to\n * passthrough the input from the `.invoke()`\n *\n * @example\n * ```typescript\n * const chain = RunnableSequence.from([\n * {\n * question: new RunnablePassthrough(),\n * context: async () => loadContextFromStore(),\n * },\n * prompt,\n * llm,\n * outputParser,\n * ]);\n * const response = await chain.invoke(\n * \"I can pass a single string instead of an object since I'm using `RunnablePassthrough`.\"\n * );\n * ```\n */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport class RunnablePassthrough<RunInput = any> extends Runnable<\n RunInput,\n RunInput\n> {\n static lc_name() {\n return \"RunnablePassthrough\";\n }\n\n lc_namespace = [\"langchain_core\", \"runnables\"];\n\n lc_serializable = true;\n\n func?: RunnablePassthroughFunc<RunInput>;\n\n constructor(fields?: { func?: RunnablePassthroughFunc<RunInput> }) {\n super(fields);\n if (fields) {\n this.func = fields.func;\n }\n }\n\n async invoke(\n input: RunInput,\n options?: Partial<RunnableConfig>\n ): Promise<RunInput> {\n const config = ensureConfig(options);\n if (this.func) {\n await this.func(input, config);\n }\n\n return this._callWithConfig(\n (input: RunInput) => Promise.resolve(input),\n input,\n config\n );\n }\n\n async *transform(\n generator: AsyncGenerator<RunInput>,\n options: Partial<RunnableConfig>\n ): AsyncGenerator<RunInput> {\n const config = ensureConfig(options);\n let finalOutput: RunInput | undefined;\n let finalOutputSupported = true;\n\n for await (const chunk of this._transformStreamWithConfig(\n generator,\n (input: AsyncGenerator<RunInput>) => input,\n config\n )) {\n yield chunk;\n if (finalOutputSupported) {\n if (finalOutput === undefined) {\n finalOutput = chunk;\n } else {\n try {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n finalOutput = concat(finalOutput, chunk as any);\n } catch {\n finalOutput = undefined;\n finalOutputSupported = false;\n }\n }\n }\n }\n\n if (this.func && finalOutput !== undefined) {\n await this.func(finalOutput, config);\n }\n }\n\n /**\n * A runnable that assigns key-value pairs to the input.\n *\n * The example below shows how you could use it with an inline function.\n *\n * @example\n * ```typescript\n * const prompt =\n * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema}\n * Question: {question}\n * SQL Query:`);\n *\n * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()`\n * // call (in this example it's the question), along with any inputs passed to the `.assign()` method.\n * // In this case, we're passing the schema.\n * const sqlQueryGeneratorChain = RunnableSequence.from([\n * RunnablePassthrough.assign({\n * schema: async () => db.getTableInfo(),\n * }),\n * prompt,\n * new ChatOpenAI({ model: \"gpt-4o-mini\" }).withConfig({ stop: [\"\\nSQLResult:\"] }),\n * new StringOutputParser(),\n * ]);\n * const result = await sqlQueryGeneratorChain.invoke({\n * question: \"How many employees are there?\",\n * });\n * ```\n */\n static assign<\n RunInput extends Record<string, unknown> = Record<string, unknown>,\n RunOutput extends Record<string, unknown> = Record<string, unknown>,\n >(\n mapping: RunnableMapLike<RunInput, RunOutput>\n ): RunnableAssign<RunInput, RunInput & RunOutput> {\n return new RunnableAssign(new RunnableMap({ steps: mapping }));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,sBAAb,cAAyD,SAGvD;CACA,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe,CAAC,kBAAkB,WAAW;CAE7C,kBAAkB;CAElB;CAEA,YAAY,QAAuD;EACjE,MAAM,MAAM;EACZ,IAAI,QACF,KAAK,OAAO,OAAO;CAEvB;CAEA,MAAM,OACJ,OACA,SACmB;EACnB,MAAM,SAAS,aAAa,OAAO;EACnC,IAAI,KAAK,MACP,MAAM,KAAK,KAAK,OAAO,MAAM;EAG/B,OAAO,KAAK,iBACT,UAAoB,QAAQ,QAAQ,KAAK,GAC1C,OACA,MACF;CACF;CAEA,OAAO,UACL,WACA,SAC0B;EAC1B,MAAM,SAAS,aAAa,OAAO;EACnC,IAAI;EACJ,IAAI,uBAAuB;EAE3B,WAAW,MAAM,SAAS,KAAK,2BAC7B,YACC,UAAoC,OACrC,MACF,GAAG;GACD,MAAM;GACN,IAAI,sBAAsB;IACxB,IAAI,gBAAgB,KAAA,GAClB,cAAc;SAEd,IAAI;KAEF,cAAc,OAAO,aAAa,KAAY;IAChD,QAAQ;KACN,cAAc,KAAA;KACd,uBAAuB;IACzB;GAEJ;EACF;EAEA,IAAI,KAAK,QAAQ,gBAAgB,KAAA,GAC/B,MAAM,KAAK,KAAK,aAAa,MAAM;CAEvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BA,OAAO,OAIL,SACgD;EAChD,OAAO,IAAI,eAAe,IAAI,YAAY,EAAE,OAAO,QAAQ,CAAC,CAAC;CAC/D;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.cjs","names":["getGlobalAsyncLocalStorageInstance","_CONTEXT_VARIABLES_KEY","RunTree"],"sources":["../../../src/singletons/async_local_storage/context.ts"],"sourcesContent":["import { isRunTree, RunTree } from \"langsmith/run_trees\";\nimport { BaseCallbackHandler } from \"../../callbacks/base.js\";\nimport {\n _CONTEXT_VARIABLES_KEY,\n getGlobalAsyncLocalStorageInstance,\n} from \"./globals.js\";\n\n/**\n * Set a context variable. Context variables are scoped to any\n * child runnables called by the current runnable, or globally if set outside\n * of any runnable.\n *\n * @remarks\n * This function is only supported in environments that support AsyncLocalStorage,\n * including Node.js, Deno, and Cloudflare Workers.\n *\n * @example\n * ```ts\n * import { RunnableLambda } from \"@langchain/core/runnables\";\n * import {\n * getContextVariable,\n * setContextVariable\n * } from \"@langchain/core/context\";\n *\n * const nested = RunnableLambda.from(() => {\n * // \"bar\" because it was set by a parent\n * console.log(getContextVariable(\"foo\"));\n *\n * // Override to \"baz\", but only for child runnables\n * setContextVariable(\"foo\", \"baz\");\n *\n * // Now \"baz\", but only for child runnables\n * return getContextVariable(\"foo\");\n * });\n *\n * const runnable = RunnableLambda.from(async () => {\n * // Set a context variable named \"foo\"\n * setContextVariable(\"foo\", \"bar\");\n *\n * const res = await nested.invoke({});\n *\n * // Still \"bar\" since child changes do not affect parents\n * console.log(getContextVariable(\"foo\"));\n *\n * return res;\n * });\n *\n * // undefined, because context variable has not been set yet\n * console.log(getContextVariable(\"foo\"));\n *\n * // Final return value is \"baz\"\n * const result = await runnable.invoke({});\n * ```\n *\n * @param name The name of the context variable.\n * @param value The value to set.\n */\nexport function setContextVariable<T>(name: PropertyKey, value: T): void {\n // Avoid using global singleton due to circuluar dependency issues\n const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();\n if (asyncLocalStorageInstance === undefined) {\n throw new Error(\n `Internal error: Global shared async local storage instance has not been initialized.`\n );\n }\n const runTree = asyncLocalStorageInstance.getStore();\n const contextVars = { ...runTree?.[_CONTEXT_VARIABLES_KEY] };\n contextVars[name] = value;\n let newValue = {};\n if (isRunTree(runTree)) {\n newValue = new RunTree(runTree);\n }\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n (newValue as any)[_CONTEXT_VARIABLES_KEY] = contextVars;\n asyncLocalStorageInstance.enterWith(newValue);\n}\n\n/**\n * Get the value of a previously set context variable. Context variables\n * are scoped to any child runnables called by the current runnable,\n * or globally if set outside of any runnable.\n *\n * @remarks\n * This function is only supported in environments that support AsyncLocalStorage,\n * including Node.js, Deno, and Cloudflare Workers.\n *\n * @example\n * ```ts\n * import { RunnableLambda } from \"@langchain/core/runnables\";\n * import {\n * getContextVariable,\n * setContextVariable\n * } from \"@langchain/core/context\";\n *\n * const nested = RunnableLambda.from(() => {\n * // \"bar\" because it was set by a parent\n * console.log(getContextVariable(\"foo\"));\n *\n * // Override to \"baz\", but only for child runnables\n * setContextVariable(\"foo\", \"baz\");\n *\n * // Now \"baz\", but only for child runnables\n * return getContextVariable(\"foo\");\n * });\n *\n * const runnable = RunnableLambda.from(async () => {\n * // Set a context variable named \"foo\"\n * setContextVariable(\"foo\", \"bar\");\n *\n * const res = await nested.invoke({});\n *\n * // Still \"bar\" since child changes do not affect parents\n * console.log(getContextVariable(\"foo\"));\n *\n * return res;\n * });\n *\n * // undefined, because context variable has not been set yet\n * console.log(getContextVariable(\"foo\"));\n *\n * // Final return value is \"baz\"\n * const result = await runnable.invoke({});\n * ```\n *\n * @param name The name of the context variable.\n */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getContextVariable<T = any>(name: PropertyKey): T | undefined {\n // Avoid using global singleton due to circuluar dependency issues\n const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();\n if (asyncLocalStorageInstance === undefined) {\n return undefined;\n }\n const runTree = asyncLocalStorageInstance.getStore();\n return runTree?.[_CONTEXT_VARIABLES_KEY]?.[name];\n}\n\nconst LC_CONFIGURE_HOOKS_KEY = Symbol(\"lc:configure_hooks\");\n\nexport const _getConfigureHooks = () =>\n getContextVariable<ConfigureHook[]>(LC_CONFIGURE_HOOKS_KEY) || [];\n\n/**\n * Register a callback configure hook to automatically add callback handlers to all runs.\n *\n * There are two ways to use this:\n *\n * 1. Using a context variable:\n * - Set `contextVar` to specify the variable name\n * - Use `setContextVariable()` to store your handler instance\n *\n * 2. Using an environment variable:\n * - Set both `envVar` and `handlerClass`\n * - The handler will be instantiated when the env var is set to \"true\".\n *\n * @example\n * ```typescript\n * // Method 1: Using context variable\n * import {\n * registerConfigureHook,\n * setContextVariable\n * } from \"@langchain/core/context\";\n *\n * const tracer = new MyCallbackHandler();\n * registerConfigureHook({\n * contextVar: \"my_tracer\",\n * });\n * setContextVariable(\"my_tracer\", tracer);\n *\n * // ...run code here\n *\n * // Method 2: Using environment variable\n * registerConfigureHook({\n * handlerClass: MyCallbackHandler,\n * envVar: \"MY_TRACER_ENABLED\",\n * });\n * process.env.MY_TRACER_ENABLED = \"true\";\n *\n * // ...run code here\n * ```\n *\n * @param config Configuration object for the hook\n * @param config.contextVar Name of the context variable containing the handler instance\n * @param config.inheritable Whether child runs should inherit this handler\n * @param config.handlerClass Optional callback handler class (required if using envVar)\n * @param config.envVar Optional environment variable name to control handler activation\n */\nexport const registerConfigureHook = (config: ConfigureHook) => {\n if (config.envVar && !config.handlerClass) {\n throw new Error(\n \"If envVar is set, handlerClass must also be set to a non-None value.\"\n );\n }\n setContextVariable(LC_CONFIGURE_HOOKS_KEY, [..._getConfigureHooks(), config]);\n};\n\nexport type ConfigureHook = {\n contextVar?: string;\n inheritable?: boolean;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n handlerClass?: new (...args: any[]) => BaseCallbackHandler;\n envVar?: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAgB,mBAAsB,MAAmB,OAAgB;CAEvE,MAAM,4BAA4BA,gBAAAA,mCAAmC;CACrE,IAAI,8BAA8B,KAAA,GAChC,MAAM,IAAI,MACR,sFACF;CAEF,MAAM,UAAU,0BAA0B,SAAS;CACnD,MAAM,cAAc,EAAE,GAAG,UAAUC,gBAAAA,wBAAwB;CAC3D,YAAY,QAAQ;CACpB,IAAI,WAAW,CAAC;CAChB,KAAA,
|
|
1
|
+
{"version":3,"file":"context.cjs","names":["getGlobalAsyncLocalStorageInstance","_CONTEXT_VARIABLES_KEY","isRunTree","RunTree"],"sources":["../../../src/singletons/async_local_storage/context.ts"],"sourcesContent":["import { isRunTree, RunTree } from \"langsmith/run_trees\";\nimport { BaseCallbackHandler } from \"../../callbacks/base.js\";\nimport {\n _CONTEXT_VARIABLES_KEY,\n getGlobalAsyncLocalStorageInstance,\n} from \"./globals.js\";\n\n/**\n * Set a context variable. Context variables are scoped to any\n * child runnables called by the current runnable, or globally if set outside\n * of any runnable.\n *\n * @remarks\n * This function is only supported in environments that support AsyncLocalStorage,\n * including Node.js, Deno, and Cloudflare Workers.\n *\n * @example\n * ```ts\n * import { RunnableLambda } from \"@langchain/core/runnables\";\n * import {\n * getContextVariable,\n * setContextVariable\n * } from \"@langchain/core/context\";\n *\n * const nested = RunnableLambda.from(() => {\n * // \"bar\" because it was set by a parent\n * console.log(getContextVariable(\"foo\"));\n *\n * // Override to \"baz\", but only for child runnables\n * setContextVariable(\"foo\", \"baz\");\n *\n * // Now \"baz\", but only for child runnables\n * return getContextVariable(\"foo\");\n * });\n *\n * const runnable = RunnableLambda.from(async () => {\n * // Set a context variable named \"foo\"\n * setContextVariable(\"foo\", \"bar\");\n *\n * const res = await nested.invoke({});\n *\n * // Still \"bar\" since child changes do not affect parents\n * console.log(getContextVariable(\"foo\"));\n *\n * return res;\n * });\n *\n * // undefined, because context variable has not been set yet\n * console.log(getContextVariable(\"foo\"));\n *\n * // Final return value is \"baz\"\n * const result = await runnable.invoke({});\n * ```\n *\n * @param name The name of the context variable.\n * @param value The value to set.\n */\nexport function setContextVariable<T>(name: PropertyKey, value: T): void {\n // Avoid using global singleton due to circuluar dependency issues\n const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();\n if (asyncLocalStorageInstance === undefined) {\n throw new Error(\n `Internal error: Global shared async local storage instance has not been initialized.`\n );\n }\n const runTree = asyncLocalStorageInstance.getStore();\n const contextVars = { ...runTree?.[_CONTEXT_VARIABLES_KEY] };\n contextVars[name] = value;\n let newValue = {};\n if (isRunTree(runTree)) {\n newValue = new RunTree(runTree);\n }\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n (newValue as any)[_CONTEXT_VARIABLES_KEY] = contextVars;\n asyncLocalStorageInstance.enterWith(newValue);\n}\n\n/**\n * Get the value of a previously set context variable. Context variables\n * are scoped to any child runnables called by the current runnable,\n * or globally if set outside of any runnable.\n *\n * @remarks\n * This function is only supported in environments that support AsyncLocalStorage,\n * including Node.js, Deno, and Cloudflare Workers.\n *\n * @example\n * ```ts\n * import { RunnableLambda } from \"@langchain/core/runnables\";\n * import {\n * getContextVariable,\n * setContextVariable\n * } from \"@langchain/core/context\";\n *\n * const nested = RunnableLambda.from(() => {\n * // \"bar\" because it was set by a parent\n * console.log(getContextVariable(\"foo\"));\n *\n * // Override to \"baz\", but only for child runnables\n * setContextVariable(\"foo\", \"baz\");\n *\n * // Now \"baz\", but only for child runnables\n * return getContextVariable(\"foo\");\n * });\n *\n * const runnable = RunnableLambda.from(async () => {\n * // Set a context variable named \"foo\"\n * setContextVariable(\"foo\", \"bar\");\n *\n * const res = await nested.invoke({});\n *\n * // Still \"bar\" since child changes do not affect parents\n * console.log(getContextVariable(\"foo\"));\n *\n * return res;\n * });\n *\n * // undefined, because context variable has not been set yet\n * console.log(getContextVariable(\"foo\"));\n *\n * // Final return value is \"baz\"\n * const result = await runnable.invoke({});\n * ```\n *\n * @param name The name of the context variable.\n */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getContextVariable<T = any>(name: PropertyKey): T | undefined {\n // Avoid using global singleton due to circuluar dependency issues\n const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance();\n if (asyncLocalStorageInstance === undefined) {\n return undefined;\n }\n const runTree = asyncLocalStorageInstance.getStore();\n return runTree?.[_CONTEXT_VARIABLES_KEY]?.[name];\n}\n\nconst LC_CONFIGURE_HOOKS_KEY = Symbol(\"lc:configure_hooks\");\n\nexport const _getConfigureHooks = () =>\n getContextVariable<ConfigureHook[]>(LC_CONFIGURE_HOOKS_KEY) || [];\n\n/**\n * Register a callback configure hook to automatically add callback handlers to all runs.\n *\n * There are two ways to use this:\n *\n * 1. Using a context variable:\n * - Set `contextVar` to specify the variable name\n * - Use `setContextVariable()` to store your handler instance\n *\n * 2. Using an environment variable:\n * - Set both `envVar` and `handlerClass`\n * - The handler will be instantiated when the env var is set to \"true\".\n *\n * @example\n * ```typescript\n * // Method 1: Using context variable\n * import {\n * registerConfigureHook,\n * setContextVariable\n * } from \"@langchain/core/context\";\n *\n * const tracer = new MyCallbackHandler();\n * registerConfigureHook({\n * contextVar: \"my_tracer\",\n * });\n * setContextVariable(\"my_tracer\", tracer);\n *\n * // ...run code here\n *\n * // Method 2: Using environment variable\n * registerConfigureHook({\n * handlerClass: MyCallbackHandler,\n * envVar: \"MY_TRACER_ENABLED\",\n * });\n * process.env.MY_TRACER_ENABLED = \"true\";\n *\n * // ...run code here\n * ```\n *\n * @param config Configuration object for the hook\n * @param config.contextVar Name of the context variable containing the handler instance\n * @param config.inheritable Whether child runs should inherit this handler\n * @param config.handlerClass Optional callback handler class (required if using envVar)\n * @param config.envVar Optional environment variable name to control handler activation\n */\nexport const registerConfigureHook = (config: ConfigureHook) => {\n if (config.envVar && !config.handlerClass) {\n throw new Error(\n \"If envVar is set, handlerClass must also be set to a non-None value.\"\n );\n }\n setContextVariable(LC_CONFIGURE_HOOKS_KEY, [..._getConfigureHooks(), config]);\n};\n\nexport type ConfigureHook = {\n contextVar?: string;\n inheritable?: boolean;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n handlerClass?: new (...args: any[]) => BaseCallbackHandler;\n envVar?: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAgB,mBAAsB,MAAmB,OAAgB;CAEvE,MAAM,4BAA4BA,gBAAAA,mCAAmC;CACrE,IAAI,8BAA8B,KAAA,GAChC,MAAM,IAAI,MACR,sFACF;CAEF,MAAM,UAAU,0BAA0B,SAAS;CACnD,MAAM,cAAc,EAAE,GAAG,UAAUC,gBAAAA,wBAAwB;CAC3D,YAAY,QAAQ;CACpB,IAAI,WAAW,CAAC;CAChB,KAAA,GAAIC,oBAAAA,UAAAA,CAAU,OAAO,GACnB,WAAW,IAAIC,oBAAAA,QAAQ,OAAO;CAGhC,SAAkBF,gBAAAA,0BAA0B;CAC5C,0BAA0B,UAAU,QAAQ;AAC9C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,mBAA4B,MAAkC;CAE5E,MAAM,4BAA4BD,gBAAAA,mCAAmC;CACrE,IAAI,8BAA8B,KAAA,GAChC;CAGF,OADgB,0BAA0B,SAC7B,CAAC,GAAGC,gBAAAA,uBAAuB,GAAG;AAC7C;AAEA,MAAM,yBAAyB,OAAO,oBAAoB;AAE1D,MAAa,2BACX,mBAAoC,sBAAsB,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+ClE,MAAa,yBAAyB,WAA0B;CAC9D,IAAI,OAAO,UAAU,CAAC,OAAO,cAC3B,MAAM,IAAI,MACR,sEACF;CAEF,mBAAmB,wBAAwB,CAAC,GAAG,mBAAmB,GAAG,MAAM,CAAC;AAC9E"}
|
|
@@ -3,7 +3,10 @@ let langsmith = require("langsmith");
|
|
|
3
3
|
//#region src/singletons/tracer.ts
|
|
4
4
|
let client;
|
|
5
5
|
const getDefaultLangChainClientSingleton = () => {
|
|
6
|
-
if (client === void 0)
|
|
6
|
+
if (client === void 0) {
|
|
7
|
+
const clientParams = require_utils_env.getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? { blockOnRootRunFinalization: true } : {};
|
|
8
|
+
client = new langsmith.Client(clientParams);
|
|
9
|
+
}
|
|
7
10
|
return client;
|
|
8
11
|
};
|
|
9
12
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracer.cjs","names":["
|
|
1
|
+
{"version":3,"file":"tracer.cjs","names":["getEnvironmentVariable","Client"],"sources":["../../src/singletons/tracer.ts"],"sourcesContent":["import { Client } from \"langsmith\";\nimport { getEnvironmentVariable } from \"../utils/env.js\";\n\nlet client: Client;\n\nexport const getDefaultLangChainClientSingleton = () => {\n if (client === undefined) {\n const clientParams =\n getEnvironmentVariable(\"LANGCHAIN_CALLBACKS_BACKGROUND\") === \"false\"\n ? {\n // LangSmith has its own backgrounding system\n blockOnRootRunFinalization: true,\n }\n : {};\n client = new Client(clientParams);\n }\n return client;\n};\n\nexport const setDefaultLangChainClientSingleton = (newClient: Client) => {\n client = newClient;\n};\n"],"mappings":";;;AAGA,IAAI;AAEJ,MAAa,2CAA2C;CACtD,IAAI,WAAW,KAAA,GAAW;EACxB,MAAM,eACJA,kBAAAA,uBAAuB,gCAAgC,MAAM,UACzD,EAEE,4BAA4B,KAC9B,IACA,CAAC;EACP,SAAS,IAAIC,UAAAA,OAAO,YAAY;CAClC;CACA,OAAO;AACT"}
|
|
@@ -3,7 +3,10 @@ import { Client } from "langsmith";
|
|
|
3
3
|
//#region src/singletons/tracer.ts
|
|
4
4
|
let client;
|
|
5
5
|
const getDefaultLangChainClientSingleton = () => {
|
|
6
|
-
if (client === void 0)
|
|
6
|
+
if (client === void 0) {
|
|
7
|
+
const clientParams = getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? { blockOnRootRunFinalization: true } : {};
|
|
8
|
+
client = new Client(clientParams);
|
|
9
|
+
}
|
|
7
10
|
return client;
|
|
8
11
|
};
|
|
9
12
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracer.js","names":[],"sources":["../../src/singletons/tracer.ts"],"sourcesContent":["import { Client } from \"langsmith\";\nimport { getEnvironmentVariable } from \"../utils/env.js\";\n\nlet client: Client;\n\nexport const getDefaultLangChainClientSingleton = () => {\n if (client === undefined) {\n const clientParams =\n getEnvironmentVariable(\"LANGCHAIN_CALLBACKS_BACKGROUND\") === \"false\"\n ? {\n // LangSmith has its own backgrounding system\n blockOnRootRunFinalization: true,\n }\n : {};\n client = new Client(clientParams);\n }\n return client;\n};\n\nexport const setDefaultLangChainClientSingleton = (newClient: Client) => {\n client = newClient;\n};\n"],"mappings":";;;AAGA,IAAI;AAEJ,MAAa,2CAA2C;CACtD,IAAI,WAAW,KAAA,
|
|
1
|
+
{"version":3,"file":"tracer.js","names":[],"sources":["../../src/singletons/tracer.ts"],"sourcesContent":["import { Client } from \"langsmith\";\nimport { getEnvironmentVariable } from \"../utils/env.js\";\n\nlet client: Client;\n\nexport const getDefaultLangChainClientSingleton = () => {\n if (client === undefined) {\n const clientParams =\n getEnvironmentVariable(\"LANGCHAIN_CALLBACKS_BACKGROUND\") === \"false\"\n ? {\n // LangSmith has its own backgrounding system\n blockOnRootRunFinalization: true,\n }\n : {};\n client = new Client(clientParams);\n }\n return client;\n};\n\nexport const setDefaultLangChainClientSingleton = (newClient: Client) => {\n client = newClient;\n};\n"],"mappings":";;;AAGA,IAAI;AAEJ,MAAa,2CAA2C;CACtD,IAAI,WAAW,KAAA,GAAW;EACxB,MAAM,eACJ,uBAAuB,gCAAgC,MAAM,UACzD,EAEE,4BAA4B,KAC9B,IACA,CAAC;EACP,SAAS,IAAI,OAAO,YAAY;CAClC;CACA,OAAO;AACT"}
|
package/dist/tools/index.cjs
CHANGED
|
@@ -145,9 +145,10 @@ var StructuredTool = class extends require_language_models_base.BaseLangChain {
|
|
|
145
145
|
}
|
|
146
146
|
let content;
|
|
147
147
|
let artifact;
|
|
148
|
-
if (this.responseFormat === "content_and_artifact")
|
|
149
|
-
|
|
150
|
-
|
|
148
|
+
if (this.responseFormat === "content_and_artifact") {
|
|
149
|
+
if (Array.isArray(result) && result.length === 2) [content, artifact] = result;
|
|
150
|
+
else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(result)}`);
|
|
151
|
+
} else content = result;
|
|
151
152
|
const formattedOutput = _formatToolOutput({
|
|
152
153
|
content,
|
|
153
154
|
artifact,
|
|
@@ -333,23 +334,24 @@ function _isMessageContentBlockShaped(item) {
|
|
|
333
334
|
}
|
|
334
335
|
function _formatToolOutput(params) {
|
|
335
336
|
const { content, artifact, toolCallId, metadata } = params;
|
|
336
|
-
if (toolCallId && !require_messages_tool.isDirectToolOutput(content))
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
337
|
+
if (toolCallId && !require_messages_tool.isDirectToolOutput(content)) {
|
|
338
|
+
if (typeof content === "string" || Array.isArray(content) && content.every(_isMessageContentBlockShaped)) return new require_messages_tool.ToolMessage({
|
|
339
|
+
status: "success",
|
|
340
|
+
content,
|
|
341
|
+
artifact,
|
|
342
|
+
tool_call_id: toolCallId,
|
|
343
|
+
name: params.name,
|
|
344
|
+
metadata
|
|
345
|
+
});
|
|
346
|
+
else return new require_messages_tool.ToolMessage({
|
|
347
|
+
status: "success",
|
|
348
|
+
content: _stringify(content),
|
|
349
|
+
artifact,
|
|
350
|
+
tool_call_id: toolCallId,
|
|
351
|
+
name: params.name,
|
|
352
|
+
metadata
|
|
353
|
+
});
|
|
354
|
+
} else return content;
|
|
353
355
|
}
|
|
354
356
|
function _stringify(content) {
|
|
355
357
|
try {
|
package/dist/tools/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["BaseLangChain","ensureConfig","mergeConfigs","_isToolCall","isInteropZodSchema","interopParseAsync","isInteropZodError","z4","ToolInputParsingException","parseCallbackConfigArg","CallbackManager","_configHasToolCallId","isAsyncGenerator","consumeAsyncGenerator","z","isSimpleStringZodSchema","validatesOnlyStrings","patchConfig","AsyncLocalStorageProviderSingleton","pickRunnableConfigKeys","getAbortSignalError","isDirectToolOutput","ToolMessage"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodError,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n ToolEventType,\n InferToolEventFromFunc,\n InferToolOutputFromFunc,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\nimport { consumeAsyncGenerator, isAsyncGenerator } from \"../runnables/iter.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n>\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Optional provider-specific extra fields for the tool.\n *\n * This is used to pass provider-specific configuration that doesn't fit into\n * standard tool fields.\n */\n extras?: Record<string, unknown>;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n this.extras = fields?.extras ?? this.extras;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n if (isInteropZodError(e)) {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName,\n toolCallId\n );\n delete config.runId;\n\n let result;\n try {\n const raw = await this._call(parsed, runManager, config);\n result = isAsyncGenerator(raw)\n ? await consumeAsyncGenerator(raw, async (chunk) => {\n try {\n await runManager?.handleToolEvent(chunk);\n } catch (streamError) {\n await runManager?.handleToolError(streamError);\n }\n })\n : raw;\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT,\n ToolEventT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n> extends Tool<ToolOutputT, ToolEventT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT, ToolEventT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT, ToolEventT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n *\n * @template SchemaT The input schema type for the tool (Zod schema or JSON schema). Defaults to `ToolInputSchemaBase`.\n * @template SchemaOutputT The output type derived from the schema after parsing/validation. Defaults to `ToolInputSchemaOutputType<SchemaT>`.\n * @template SchemaInputT The input type derived from the schema before parsing. Defaults to `ToolInputSchemaInputType<SchemaT>`.\n * @template ToolOutputT The return type of the tool's function. Defaults to `ToolOutputType`.\n * @template NameT The literal type of the tool name (for discriminated union support). Defaults to `string`.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n NameT extends string = string,\n> extends StructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT\n> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n declare name: NameT;\n\n description: string;\n\n func: DynamicStructuredToolInput<\n SchemaT,\n SchemaOutputT,\n ToolOutputT,\n ToolEventT\n >[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<\n SchemaT,\n SchemaOutputT,\n ToolOutputT,\n ToolEventT\n > & {\n name: NameT;\n }\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<\n SchemaT,\n SchemaOutputT,\n ToolOutputT,\n ToolEventT\n >[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n * @template {string} NameT The literal name type for discriminated union support.\n */\nexport interface ToolWrapperParams<\n RunInput = ToolInputSchemaBase | undefined,\n NameT extends string = string,\n> extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: NameT;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n > = RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n > = RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> =\n RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> =\n RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n > = RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> =\n RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n >\n | DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n >\n | DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT,\n NameT\n >\n | DynamicTool<ToolOutputT, ToolEventT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT, ToolEventT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // oxlint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT,\n NameT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener, { once: true });\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // oxlint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n if (isAsyncGenerator(result)) {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(result as any);\n return;\n }\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT,\n NameT\n >;\n}\n\nfunction _isMessageContentBlockShaped(item: unknown) {\n return typeof item === \"object\" && item !== null && \"type\" in item;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) && content.every(_isMessageContentBlockShaped))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,IAAsB,iBAAtB,cAOUA,6BAAAA,cAKV;;;;;;;CAaE;;;;;;;CAQA,eAAe;CAEf,uBAAuB;CAEvB,IAAI,eAAe;EACjB,OAAO,CAAC,aAAa,OAAO;CAC9B;;;;;;;;;;CAWA,iBAAkC;;;;CAKlC;CAEA,YAAY,QAAqB;EAC/B,MAAM,UAAU,CAAC,CAAC;EAElB,KAAK,uBACH,QAAQ,wBAAwB,K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names":["BaseLangChain","ensureConfig","mergeConfigs","_isToolCall","isInteropZodSchema","interopParseAsync","isInteropZodError","z4","ToolInputParsingException","validate","parseCallbackConfigArg","CallbackManager","_configHasToolCallId","isAsyncGenerator","consumeAsyncGenerator","z","isSimpleStringZodSchema","validatesOnlyStrings","patchConfig","AsyncLocalStorageProviderSingleton","pickRunnableConfigKeys","getAbortSignalError","isDirectToolOutput","ToolMessage"],"sources":["../../src/tools/index.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4, ZodError } from \"zod/v4\";\nimport {\n validate,\n type Schema as ValidationSchema,\n} from \"@cfworker/json-schema\";\nimport {\n CallbackManager,\n CallbackManagerForToolRun,\n parseCallbackConfigArg,\n} from \"../callbacks/manager.js\";\nimport { BaseLangChain } from \"../language_models/base.js\";\nimport {\n mergeConfigs,\n ensureConfig,\n patchConfig,\n pickRunnableConfigKeys,\n type RunnableConfig,\n} from \"../runnables/config.js\";\nimport type { RunnableFunc } from \"../runnables/base.js\";\nimport { isDirectToolOutput, ToolCall, ToolMessage } from \"../messages/tool.js\";\nimport { AsyncLocalStorageProviderSingleton } from \"../singletons/index.js\";\nimport type { RunnableToolLike } from \"../runnables/base.js\";\nimport {\n _configHasToolCallId,\n _isToolCall,\n ToolInputParsingException,\n} from \"./utils.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodObject,\n type InteropZodType,\n interopParseAsync,\n isSimpleStringZodSchema,\n isInteropZodError,\n isInteropZodSchema,\n type ZodStringV3,\n type ZodStringV4,\n type ZodObjectV3,\n type ZodObjectV4,\n} from \"../utils/types/zod.js\";\nimport { getAbortSignalError } from \"../utils/signal.js\";\nimport type {\n StructuredToolCallInput,\n ToolInputSchemaBase,\n ToolReturnType,\n ResponseFormat,\n ToolInputSchemaInputType,\n ToolInputSchemaOutputType,\n ToolParams,\n ToolRunnableConfig,\n StructuredToolInterface,\n DynamicToolInput,\n DynamicStructuredToolInput,\n StringInputToolSchema,\n ToolInterface,\n ToolOutputType,\n ToolRuntime,\n ToolEventType,\n InferToolEventFromFunc,\n InferToolOutputFromFunc,\n} from \"./types.js\";\nimport { type JSONSchema, validatesOnlyStrings } from \"../utils/json_schema.js\";\nimport { consumeAsyncGenerator, isAsyncGenerator } from \"../runnables/iter.js\";\n\nexport type {\n BaseDynamicToolInput,\n ContentAndArtifact,\n DynamicToolInput,\n DynamicStructuredToolInput,\n ResponseFormat,\n StructuredToolCallInput,\n StructuredToolInterface,\n StructuredToolParams,\n ToolInterface,\n ToolParams,\n ToolReturnType,\n ToolRunnableConfig,\n ToolInputSchemaBase as ToolSchemaBase,\n} from \"./types.js\";\n\nexport {\n isLangChainTool,\n isRunnableToolLike,\n isStructuredTool,\n isStructuredToolParams,\n type ToolRuntime,\n} from \"./types.js\";\n\nexport { ToolInputParsingException };\n/**\n * Base class for Tools that accept input of any shape defined by a Zod schema.\n */\nexport abstract class StructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n>\n extends BaseLangChain<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n >\n implements StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT>\n{\n abstract name: string;\n\n abstract description: string;\n\n abstract schema: SchemaT;\n\n /**\n * Optional provider-specific extra fields for the tool.\n *\n * This is used to pass provider-specific configuration that doesn't fit into\n * standard tool fields.\n */\n extras?: Record<string, unknown>;\n\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect = false;\n\n verboseParsingErrors = false;\n\n get lc_namespace() {\n return [\"langchain\", \"tools\"];\n }\n\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat = \"content\";\n\n /**\n * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n\n constructor(fields?: ToolParams) {\n super(fields ?? {});\n\n this.verboseParsingErrors =\n fields?.verboseParsingErrors ?? this.verboseParsingErrors;\n this.responseFormat = fields?.responseFormat ?? this.responseFormat;\n this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig;\n this.metadata = fields?.metadata ?? this.metadata;\n this.extras = fields?.extras ?? this.extras;\n }\n\n protected abstract _call(\n arg: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT>;\n\n /**\n * Invokes the tool with the provided input and configuration.\n * @param input The input for the tool.\n * @param config Optional configuration for the tool.\n * @returns A Promise that resolves with the tool's output.\n */\n async invoke<\n TInput extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n input: TInput,\n config?: TConfig\n ): Promise<ToolReturnType<TInput, TConfig, ToolOutputT>> {\n let toolInput: Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n\n let enrichedConfig: ToolRunnableConfig = ensureConfig(\n mergeConfigs(this.defaultConfig, config)\n );\n if (_isToolCall(input)) {\n toolInput = input.args as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n enrichedConfig = {\n ...enrichedConfig,\n toolCall: input,\n };\n } else {\n toolInput = input as Exclude<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolCall\n >;\n }\n\n return this.call(toolInput, enrichedConfig) as Promise<\n ToolReturnType<TInput, TConfig, ToolOutputT>\n >;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument, configuration, and tags. It\n * parses the input according to the schema, handles any errors, and\n * manages callbacks.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration or callbacks for the tool.\n * @param tags Optional tags for the tool.\n * @returns A Promise that resolves with a string.\n */\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>> {\n // Determine the actual input that needs parsing/validation.\n // If arg is a ToolCall, use its args; otherwise, use arg directly.\n const inputForValidation = _isToolCall(arg) ? arg.args : arg;\n\n let parsed: SchemaOutputT; // This will hold the successfully parsed input of the expected output type.\n if (isInteropZodSchema(this.schema)) {\n try {\n // Validate the inputForValidation - TS needs help here as it can't exclude ToolCall based on the check\n parsed = await interopParseAsync(\n this.schema as InteropZodType,\n inputForValidation as Exclude<TArg, ToolCall>\n );\n } catch (e) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${(e as Error).message}`;\n }\n if (isInteropZodError(e)) {\n message = `${message}\\n\\n${z4.prettifyError(e as ZodError)}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n } else {\n const result = validate(\n inputForValidation,\n this.schema as ValidationSchema\n );\n if (!result.valid) {\n let message = `Received tool input did not match expected schema`;\n if (this.verboseParsingErrors) {\n message = `${message}\\nDetails: ${result.errors\n .map((e) => `${e.keywordLocation}: ${e.error}`)\n .join(\"\\n\")}`;\n }\n // Pass the original raw input arg to the exception\n throw new ToolInputParsingException(message, JSON.stringify(arg));\n }\n // Assign the validated input to parsed\n // We cast here because validate() doesn't narrow the type sufficiently for TS, but we know it's valid.\n parsed = inputForValidation as SchemaOutputT;\n }\n\n const config = parseCallbackConfigArg(configArg);\n const callbackManager_ = CallbackManager.configure(\n config.callbacks,\n this.callbacks,\n config.tags || tags,\n this.tags,\n config.metadata,\n this.metadata,\n { verbose: this.verbose }\n );\n\n let toolCallId: string | undefined;\n // Extract toolCallId ONLY if the original arg was a ToolCall\n if (_isToolCall(arg)) {\n toolCallId = arg.id;\n }\n // Or if it was provided in the config's toolCall property\n if (!toolCallId && _configHasToolCallId(config)) {\n toolCallId = config.toolCall.id;\n }\n\n const runManager = await callbackManager_?.handleToolStart(\n this.toJSON(),\n // Log the original raw input arg\n typeof arg === \"string\" ? arg : JSON.stringify(arg),\n config.runId,\n undefined,\n undefined,\n undefined,\n config.runName,\n toolCallId\n );\n delete config.runId;\n\n let result;\n try {\n const raw = await this._call(parsed, runManager, config);\n result = isAsyncGenerator(raw)\n ? await consumeAsyncGenerator(raw, async (chunk) => {\n try {\n await runManager?.handleToolEvent(chunk);\n } catch (streamError) {\n await runManager?.handleToolError(streamError);\n }\n })\n : raw;\n } catch (e) {\n await runManager?.handleToolError(e);\n throw e;\n }\n\n let content;\n let artifact;\n if (this.responseFormat === \"content_and_artifact\") {\n if (Array.isArray(result) && result.length === 2) {\n [content, artifact] = result;\n } else {\n throw new Error(\n `Tool response format is \"content_and_artifact\" but the output was not a two-tuple.\\nResult: ${JSON.stringify(\n result\n )}`\n );\n }\n } else {\n content = result;\n }\n\n const formattedOutput = _formatToolOutput<ToolOutputT>({\n content,\n artifact,\n toolCallId,\n name: this.name,\n metadata: this.metadata,\n });\n await runManager?.handleToolEnd(formattedOutput);\n return formattedOutput as ToolReturnType<TArg, TConfig, ToolOutputT>;\n }\n}\n\n/**\n * Base class for Tools that accept input as a string.\n */\nexport abstract class Tool<\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n>\n extends StructuredTool<\n StringInputToolSchema,\n ToolInputSchemaOutputType<StringInputToolSchema>,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT,\n ToolEventT\n >\n implements\n ToolInterface<\n StringInputToolSchema,\n ToolInputSchemaInputType<StringInputToolSchema>,\n ToolOutputT\n >\n{\n schema = z\n .object({ input: z.string().optional() })\n .transform((obj) => obj.input);\n\n constructor(fields?: ToolParams) {\n super(fields);\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n *\n * Calls the tool with the provided argument and callbacks. It handles\n * string inputs specifically.\n * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema.\n * @param callbacks Optional callbacks for the tool.\n * @returns A Promise that resolves with a string.\n */\n // Match the base class signature including the generics and conditional return type\n call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n // Prepare the input for the base class call method.\n // If arg is string or undefined, wrap it; otherwise, pass ToolCall or { input: ... } directly.\n const structuredArg =\n typeof arg === \"string\" || arg == null ? { input: arg } : arg;\n\n // Ensure TConfig is passed to super.call\n return super.call(structuredArg, callbacks);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and description.\n */\nexport class DynamicTool<\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n> extends Tool<ToolOutputT, ToolEventT> {\n static lc_name() {\n return \"DynamicTool\";\n }\n\n name: string;\n\n description: string;\n\n func: DynamicToolInput<ToolOutputT, ToolEventT>[\"func\"];\n\n constructor(fields: DynamicToolInput<ToolOutputT, ToolEventT>) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n async call<\n TArg extends string | undefined | z.input<this[\"schema\"]> | ToolCall,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n // Call the Tool class's call method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig);\n }\n\n /** @ignore */\n _call(\n input: string, // DynamicTool's _call specifically expects a string after schema transformation\n runManager?: CallbackManagerForToolRun,\n parentConfig?: ToolRunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT> {\n return this.func(input, runManager, parentConfig);\n }\n}\n\n/**\n * A tool that can be created dynamically from a function, name, and\n * description, designed to work with structured data. It extends the\n * StructuredTool class and overrides the _call method to execute the\n * provided function when the tool is called.\n *\n * Schema can be passed as Zod or JSON schema. The tool will not validate\n * input if JSON schema is passed.\n *\n * @template SchemaT The input schema type for the tool (Zod schema or JSON schema). Defaults to `ToolInputSchemaBase`.\n * @template SchemaOutputT The output type derived from the schema after parsing/validation. Defaults to `ToolInputSchemaOutputType<SchemaT>`.\n * @template SchemaInputT The input type derived from the schema before parsing. Defaults to `ToolInputSchemaInputType<SchemaT>`.\n * @template ToolOutputT The return type of the tool's function. Defaults to `ToolOutputType`.\n * @template NameT The literal type of the tool name (for discriminated union support). Defaults to `string`.\n */\nexport class DynamicStructuredTool<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n NameT extends string = string,\n> extends StructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT\n> {\n static lc_name() {\n return \"DynamicStructuredTool\";\n }\n\n declare name: NameT;\n\n description: string;\n\n func: DynamicStructuredToolInput<\n SchemaT,\n SchemaOutputT,\n ToolOutputT,\n ToolEventT\n >[\"func\"];\n\n schema: SchemaT;\n\n constructor(\n fields: DynamicStructuredToolInput<\n SchemaT,\n SchemaOutputT,\n ToolOutputT,\n ToolEventT\n > & {\n name: NameT;\n }\n ) {\n super(fields);\n this.name = fields.name;\n this.description = fields.description;\n this.func = fields.func;\n this.returnDirect = fields.returnDirect ?? this.returnDirect;\n this.schema = fields.schema;\n }\n\n /**\n * @deprecated Use .invoke() instead. Will be removed in 0.3.0.\n */\n // Match the base class signature\n async call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig,\n /** @deprecated */\n tags?: string[]\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>> {\n const config = parseCallbackConfigArg(configArg);\n if (config.runName === undefined) {\n config.runName = this.name;\n }\n\n // Call the base class method, passing generics through\n // Cast config to TConfig to satisfy the super.call signature\n return super.call<TArg, TConfig>(arg, config as TConfig, tags);\n }\n\n protected _call(\n arg: Parameters<\n DynamicStructuredToolInput<\n SchemaT,\n SchemaOutputT,\n ToolOutputT,\n ToolEventT\n >[\"func\"]\n >[0],\n runManager?: CallbackManagerForToolRun,\n parentConfig?: RunnableConfig\n ): Promise<ToolOutputT> | AsyncGenerator<ToolEventT, ToolOutputT> {\n return this.func(arg, runManager, parentConfig);\n }\n}\n\n/**\n * Abstract base class for toolkits in LangChain. Toolkits are collections\n * of tools that agents can use. Subclasses must implement the `tools`\n * property to provide the specific tools for the toolkit.\n */\nexport abstract class BaseToolkit {\n abstract tools: StructuredToolInterface[];\n\n getTools(): StructuredToolInterface[] {\n return this.tools;\n }\n}\n\n/**\n * Parameters for the tool function.\n * Schema can be provided as Zod or JSON schema.\n * Both schema types will be validated.\n * @template {ToolInputSchemaBase} RunInput The input schema for the tool.\n * @template {string} NameT The literal name type for discriminated union support.\n */\nexport interface ToolWrapperParams<\n RunInput = ToolInputSchemaBase | undefined,\n NameT extends string = string,\n> extends ToolParams {\n /**\n * The name of the tool. If using with an LLM, this\n * will be passed as the tool name.\n */\n name: NameT;\n /**\n * The description of the tool.\n * @default `${fields.name} tool`\n */\n description?: string;\n /**\n * The input schema for the tool. If using an LLM, this\n * will be passed as the tool schema to generate arguments\n * for.\n */\n schema?: RunInput;\n /**\n * The tool response format.\n *\n * If \"content\" then the output of the tool is interpreted as the contents of a\n * ToolMessage. If \"content_and_artifact\" then the output is expected to be a\n * two-tuple corresponding to the (content, artifact) of a ToolMessage.\n *\n * @default \"content\"\n */\n responseFormat?: ResponseFormat;\n /**\n * Whether to return the tool's output directly.\n *\n * Setting this to true means that after the tool is called,\n * an agent should stop looping.\n */\n returnDirect?: boolean;\n}\n\n/**\n * Creates a new StructuredTool instance with the provided function, name, description, and schema.\n *\n * Schema can be provided as Zod or JSON schema, and both will be validated.\n *\n * @function\n * @template {ToolInputSchemaBase} SchemaT The input schema for the tool.\n * @template {ToolReturnType} ToolOutputT The output type of the tool.\n *\n * @param {RunnableFunc<z.output<SchemaT>, ToolOutputT>} func - The function to invoke when the tool is called.\n * @param {ToolWrapperParams<SchemaT>} fields - An object containing the following properties:\n * @param {string} fields.name The name of the tool.\n * @param {string | undefined} fields.description The description of the tool. Defaults to either the description on the Zod schema, or `${fields.name} tool`.\n * @param {z.AnyZodObject | z.ZodString | undefined} fields.schema The Zod schema defining the input for the tool. If undefined, it will default to a Zod string schema.\n *\n * @returns {DynamicStructuredTool<SchemaT>} A new StructuredTool instance.\n */\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n > = RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n > = RunnableFunc<\n InferInteropZodOutput<SchemaT>,\n ToolOutputT,\n ToolRunnableConfig\n >,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> =\n RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> =\n RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n > = RunnableFunc<\n Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n ToolOutputT,\n ToolRunnableConfig\n >,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n FuncT extends RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig> =\n RunnableFunc<SchemaOutputT, ToolOutputT, ToolRunnableConfig>,\n>(\n func: FuncT,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n InferToolOutputFromFunc<FuncT>,\n InferToolEventFromFunc<FuncT>,\n NameT\n >\n | DynamicTool<InferToolOutputFromFunc<FuncT>, InferToolEventFromFunc<FuncT>>;\n\n// Overloads with ToolRuntime as CallOptions\nexport function tool<\n SchemaT extends ZodStringV3,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodStringV4,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: InferInteropZodOutput<SchemaT>,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT>\n): DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends ZodObjectV3,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n>;\n\nexport function tool<\n SchemaT extends ZodObjectV4,\n NameT extends string,\n SchemaOutputT = InferInteropZodOutput<SchemaT>,\n SchemaInputT = InferInteropZodInput<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n>;\n\nexport function tool<\n SchemaT extends JSONSchema,\n NameT extends string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: Parameters<DynamicStructuredToolInput<SchemaT>[\"func\"]>[0],\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n): DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventType,\n NameT\n >\n | DynamicTool<ToolOutputT>;\n\nexport function tool<\n SchemaT extends InteropZodObject | InteropZodType<string> | JSONSchema =\n InteropZodObject,\n NameT extends string = string,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n TState = unknown,\n TContext = unknown,\n>(\n func: (\n input: SchemaOutputT,\n runtime: ToolRuntime<TState, TContext>\n ) => ToolOutputT | Promise<ToolOutputT>,\n fields: ToolWrapperParams<SchemaT, NameT>\n):\n | DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT,\n NameT\n >\n | DynamicTool<ToolOutputT, ToolEventT> {\n const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema);\n const isStringJSONSchema = validatesOnlyStrings(fields.schema);\n\n // If the schema is not provided, or it's a simple string schema, create a DynamicTool\n if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) {\n return new DynamicTool<ToolOutputT, ToolEventT>({\n ...fields,\n description:\n fields.description ??\n (fields.schema as { description?: string } | undefined)?.description ??\n `${fields.name} tool`,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // oxlint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(func(input as any, childConfig as any));\n } catch (e) {\n reject(e);\n }\n }\n );\n });\n },\n });\n }\n\n const schema = fields.schema as InteropZodObject | JSONSchema;\n\n const description =\n fields.description ??\n (fields.schema as { description?: string }).description ??\n `${fields.name} tool`;\n\n return new DynamicStructuredTool<\n typeof schema,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT,\n NameT\n >({\n ...fields,\n description,\n schema,\n func: async (input, runManager, config) => {\n return new Promise<ToolOutputT>((resolve, reject) => {\n let listener: (() => void) | undefined;\n const cleanup = () => {\n if (config?.signal && listener) {\n config.signal.removeEventListener(\"abort\", listener);\n }\n };\n\n if (config?.signal) {\n listener = () => {\n cleanup();\n reject(getAbortSignalError(config.signal));\n };\n config.signal.addEventListener(\"abort\", listener, { once: true });\n }\n\n const childConfig = patchConfig(config, {\n callbacks: runManager?.getChild(),\n });\n // oxlint-disable-next-line no-void\n void AsyncLocalStorageProviderSingleton.runWithConfig(\n pickRunnableConfigKeys(childConfig),\n async () => {\n try {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await func(input as any, childConfig as any);\n if (isAsyncGenerator(result)) {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n resolve(result as any);\n return;\n }\n\n /**\n * If the signal is aborted, we don't want to resolve the promise\n * as the promise is already rejected.\n */\n if (config?.signal?.aborted) {\n cleanup();\n return;\n }\n\n cleanup();\n resolve(result);\n } catch (e) {\n cleanup();\n reject(e);\n }\n }\n );\n });\n },\n }) as DynamicStructuredTool<\n SchemaT,\n SchemaOutputT,\n SchemaInputT,\n ToolOutputT,\n ToolEventT,\n NameT\n >;\n}\n\nfunction _isMessageContentBlockShaped(item: unknown) {\n return typeof item === \"object\" && item !== null && \"type\" in item;\n}\n\nfunction _formatToolOutput<TOutput extends ToolOutputType>(params: {\n content: TOutput;\n name: string;\n artifact?: unknown;\n toolCallId?: string;\n metadata?: Record<string, unknown>;\n}): ToolMessage | TOutput {\n const { content, artifact, toolCallId, metadata } = params;\n if (toolCallId && !isDirectToolOutput(content)) {\n if (\n typeof content === \"string\" ||\n (Array.isArray(content) && content.every(_isMessageContentBlockShaped))\n ) {\n return new ToolMessage({\n status: \"success\",\n content,\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n } else {\n return new ToolMessage({\n status: \"success\",\n content: _stringify(content),\n artifact,\n tool_call_id: toolCallId,\n name: params.name,\n metadata,\n });\n }\n } else {\n return content;\n }\n}\n\nfunction _stringify(content: unknown): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch (_noOp) {\n return `${content}`;\n }\n}\n\nexport type ServerTool = Record<string, unknown>;\nexport type ClientTool =\n | StructuredToolInterface\n | DynamicTool\n | RunnableToolLike;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,IAAsB,iBAAtB,cAOUA,6BAAAA,cAKV;;;;;;;CAaE;;;;;;;CAQA,eAAe;CAEf,uBAAuB;CAEvB,IAAI,eAAe;EACjB,OAAO,CAAC,aAAa,OAAO;CAC9B;;;;;;;;;;CAWA,iBAAkC;;;;CAKlC;CAEA,YAAY,QAAqB;EAC/B,MAAM,UAAU,CAAC,CAAC;EAElB,KAAK,uBACH,QAAQ,wBAAwB,KAAK;EACvC,KAAK,iBAAiB,QAAQ,kBAAkB,KAAK;EACrD,KAAK,gBAAgB,QAAQ,iBAAiB,KAAK;EACnD,KAAK,WAAW,QAAQ,YAAY,KAAK;EACzC,KAAK,SAAS,QAAQ,UAAU,KAAK;CACvC;;;;;;;CAcA,MAAM,OAIJ,OACA,QACuD;EACvD,IAAI;EAKJ,IAAI,iBAAqCC,eAAAA,aACvCC,eAAAA,aAAa,KAAK,eAAe,MAAM,CACzC;EACA,IAAIC,cAAAA,YAAY,KAAK,GAAG;GACtB,YAAY,MAAM;GAIlB,iBAAiB;IACf,GAAG;IACH,UAAU;GACZ;EACF,OACE,YAAY;EAMd,OAAO,KAAK,KAAK,WAAW,cAAc;CAG5C;;;;;;;;;;;;CAaA,MAAM,KAIJ,KACA,WAEA,MACqD;EAGrD,MAAM,qBAAqBA,cAAAA,YAAY,GAAG,IAAI,IAAI,OAAO;EAEzD,IAAI;EACJ,IAAIC,YAAAA,mBAAmB,KAAK,MAAM,GAChC,IAAI;GAEF,SAAS,MAAMC,YAAAA,kBACb,KAAK,QACL,kBACF;EACF,SAAS,GAA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B,MAAM,EAAE,SAAS,UAAU,YAAY,aAAa;CACpD,IAAI,cAAc,CAACS,sBAAAA,mBAAmB,OAAO,GAAG;EAC9C,IACE,OAAO,YAAY,YAClB,MAAM,QAAQ,OAAO,KAAK,QAAQ,MAAM,4BAA4B,GAErE,OAAO,IAAIC,sBAAAA,YAAY;GACrB,QAAQ;GACR;GACA;GACA,cAAc;GACd,MAAM,OAAO;GACb;EACF,CAAC;OAED,OAAO,IAAIA,sBAAAA,YAAY;GACrB,QAAQ;GACR,SAAS,WAAW,OAAO;GAC3B;GACA,cAAc;GACd,MAAM,OAAO;GACb;EACF,CAAC;CAEL,OACE,OAAO;AAEX;AAEA,SAAS,WAAW,SAA0B;CAC5C,IAAI;EACF,OAAO,KAAK,UAAU,OAAO,KAAK;CACpC,SAAS,OAAO;EACd,OAAO,GAAG;CACZ;AACF"}
|
package/dist/tools/index.js
CHANGED
|
@@ -144,9 +144,10 @@ var StructuredTool = class extends BaseLangChain {
|
|
|
144
144
|
}
|
|
145
145
|
let content;
|
|
146
146
|
let artifact;
|
|
147
|
-
if (this.responseFormat === "content_and_artifact")
|
|
148
|
-
|
|
149
|
-
|
|
147
|
+
if (this.responseFormat === "content_and_artifact") {
|
|
148
|
+
if (Array.isArray(result) && result.length === 2) [content, artifact] = result;
|
|
149
|
+
else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(result)}`);
|
|
150
|
+
} else content = result;
|
|
150
151
|
const formattedOutput = _formatToolOutput({
|
|
151
152
|
content,
|
|
152
153
|
artifact,
|
|
@@ -332,23 +333,24 @@ function _isMessageContentBlockShaped(item) {
|
|
|
332
333
|
}
|
|
333
334
|
function _formatToolOutput(params) {
|
|
334
335
|
const { content, artifact, toolCallId, metadata } = params;
|
|
335
|
-
if (toolCallId && !isDirectToolOutput(content))
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
336
|
+
if (toolCallId && !isDirectToolOutput(content)) {
|
|
337
|
+
if (typeof content === "string" || Array.isArray(content) && content.every(_isMessageContentBlockShaped)) return new ToolMessage({
|
|
338
|
+
status: "success",
|
|
339
|
+
content,
|
|
340
|
+
artifact,
|
|
341
|
+
tool_call_id: toolCallId,
|
|
342
|
+
name: params.name,
|
|
343
|
+
metadata
|
|
344
|
+
});
|
|
345
|
+
else return new ToolMessage({
|
|
346
|
+
status: "success",
|
|
347
|
+
content: _stringify(content),
|
|
348
|
+
artifact,
|
|
349
|
+
tool_call_id: toolCallId,
|
|
350
|
+
name: params.name,
|
|
351
|
+
metadata
|
|
352
|
+
});
|
|
353
|
+
} else return content;
|
|
352
354
|
}
|
|
353
355
|
function _stringify(content) {
|
|
354
356
|
try {
|