@langchain/core 1.1.19 → 1.1.21
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 +14 -0
- package/dist/agents.d.cts.map +1 -1
- package/dist/callbacks/base.cjs.map +1 -1
- package/dist/callbacks/base.js.map +1 -1
- package/dist/documents/document.cjs.map +1 -1
- package/dist/documents/document.js.map +1 -1
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.js.map +1 -1
- package/dist/language_models/base.cjs.map +1 -1
- package/dist/language_models/base.js.map +1 -1
- package/dist/load/import_map.cjs +2 -0
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +2 -0
- package/dist/load/import_map.js.map +1 -1
- package/dist/load/serializable.cjs.map +1 -1
- package/dist/load/serializable.js.map +1 -1
- package/dist/memory.d.cts.map +1 -1
- package/dist/messages/ai.cjs.map +1 -1
- package/dist/messages/ai.js.map +1 -1
- package/dist/messages/base.cjs.map +1 -1
- package/dist/messages/base.js.map +1 -1
- package/dist/messages/content/tools.cjs.map +1 -1
- package/dist/messages/content/tools.js.map +1 -1
- package/dist/messages/function.cjs.map +1 -1
- package/dist/messages/function.js.map +1 -1
- package/dist/messages/message.cjs.map +1 -1
- package/dist/messages/message.js.map +1 -1
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/output_parsers/xml.cjs.map +1 -1
- package/dist/output_parsers/xml.js.map +1 -1
- package/dist/prompts/base.cjs.map +1 -1
- package/dist/prompts/base.js.map +1 -1
- package/dist/prompts/chat.cjs.map +1 -1
- package/dist/prompts/chat.js.map +1 -1
- package/dist/prompts/few_shot.cjs.map +1 -1
- package/dist/prompts/few_shot.js.map +1 -1
- package/dist/prompts/prompt.cjs.map +1 -1
- package/dist/prompts/prompt.js.map +1 -1
- package/dist/prompts/structured.cjs.map +1 -1
- package/dist/prompts/structured.js.map +1 -1
- package/dist/retrievers/index.cjs.map +1 -1
- package/dist/retrievers/index.js.map +1 -1
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.js.map +1 -1
- package/dist/runnables/history.cjs.map +1 -1
- package/dist/runnables/history.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js.map +1 -1
- package/dist/tracers/event_stream.cjs.map +1 -1
- package/dist/tracers/event_stream.js.map +1 -1
- package/dist/tracers/log_stream.cjs.map +1 -1
- package/dist/tracers/log_stream.js.map +1 -1
- package/dist/utils/fast-json-patch/src/core.cjs +3 -10
- package/dist/utils/fast-json-patch/src/core.cjs.map +1 -1
- package/dist/utils/fast-json-patch/src/core.js +3 -10
- package/dist/utils/fast-json-patch/src/core.js.map +1 -1
- package/dist/utils/ssrf.cjs +271 -0
- package/dist/utils/ssrf.cjs.map +1 -0
- package/dist/utils/ssrf.d.cts +52 -0
- package/dist/utils/ssrf.d.cts.map +1 -0
- package/dist/utils/ssrf.d.ts +52 -0
- package/dist/utils/ssrf.d.ts.map +1 -0
- package/dist/utils/ssrf.js +260 -0
- package/dist/utils/ssrf.js.map +1 -0
- package/dist/utils/stream.cjs.map +1 -1
- package/dist/utils/stream.js.map +1 -1
- package/dist/utils/testing/chat_models.cjs.map +1 -1
- package/dist/utils/testing/chat_models.js.map +1 -1
- package/dist/utils/testing/tools.cjs.map +1 -1
- package/dist/utils/testing/tools.js.map +1 -1
- package/dist/vectorstores.cjs.map +1 -1
- package/dist/vectorstores.js.map +1 -1
- package/package.json +14 -3
- package/utils/ssrf.cjs +1 -0
- package/utils/ssrf.d.cts +1 -0
- package/utils/ssrf.d.ts +1 -0
- package/utils/ssrf.js +1 -0
package/dist/tools/types.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","names":["tool?: StructuredToolInterface | ToolDefinition | JSONSchema","tool?: unknown","Runnable","isInteropZodSchema"],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type { z as z3 } from \"zod/v3\";\nimport { CallbackManagerForToolRun } from \"../callbacks/manager.js\";\nimport type {\n BaseLangChainParams,\n ToolDefinition,\n} from \"../language_models/base.js\";\nimport type { RunnableConfig } from \"../runnables/config.js\";\nimport {\n Runnable,\n RunnableToolLike,\n type RunnableInterface,\n} from \"../runnables/base.js\";\nimport {\n type DirectToolOutput,\n type ToolCall,\n type ToolMessage,\n} from \"../messages/tool.js\";\nimport type { MessageContent } from \"../messages/base.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodType,\n isInteropZodSchema,\n type InteropZodObject,\n} from \"../utils/types/zod.js\";\n\nimport { JSONSchema } from \"../utils/json_schema.js\";\nimport type { BaseStore } from \"../stores.js\";\n\nexport type ResponseFormat = \"content\" | \"content_and_artifact\" | string;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ToolOutputType = any;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContentAndArtifact = [MessageContent, any];\n\n/**\n * Conditional type that determines the return type of the {@link StructuredTool.invoke} method.\n * - If the input is a ToolCall, it returns a ToolMessage\n * - If the config is a runnable config and contains a toolCall property, it returns a ToolMessage\n * - Otherwise, it returns the original output type\n */\nexport type ToolReturnType<TInput, TConfig, TOutput> =\n TOutput extends DirectToolOutput\n ? TOutput\n : TConfig extends { toolCall: { id: string } }\n ? ToolMessage\n : TConfig extends { toolCall: { id: undefined } }\n ? TOutput\n : TConfig extends { toolCall: { id?: string } }\n ? TOutput | ToolMessage\n : TInput extends ToolCall\n ? ToolMessage\n : TOutput;\n\n/**\n * Base type that establishes the types of input schemas that can be used for LangChain tool\n * definitions.\n */\nexport type ToolInputSchemaBase = z3.ZodTypeAny | JSONSchema;\n\n/**\n * Parameters for the Tool classes.\n */\nexport interface ToolParams extends BaseLangChainParams {\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 * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n /**\n * Whether to show full details in the thrown parsing errors.\n *\n * @default false\n */\n verboseParsingErrors?: boolean;\n /**\n * Metadata for the tool.\n */\n metadata?: Record<string, unknown>;\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\nexport type ToolRunnableConfig<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ConfigurableFieldType extends Record<string, any> = Record<string, any>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ContextSchema = any,\n> = RunnableConfig<ConfigurableFieldType> & {\n toolCall?: ToolCall;\n context?: ContextSchema;\n};\n\n/**\n * Schema for defining tools.\n *\n * @version 0.2.19\n */\nexport interface StructuredToolParams\n extends Pick<StructuredToolInterface, \"name\" | \"schema\" | \"extras\"> {\n /**\n * An optional description of the tool to pass to the model.\n */\n description?: string;\n}\n\n/**\n * Utility type that resolves the output type of a tool input schema.\n *\n * Input & Output types are a concept used with Zod schema, as Zod allows for transforms to occur\n * during parsing. When using JSONSchema, input and output types are the same.\n *\n * The input type for a given schema should match the structure of the arguments that the LLM\n * generates as part of its {@link ToolCall}. The output type will be the type that results from\n * applying any transforms defined in your schema. If there are no transforms, the input and output\n * types will be the same.\n */\nexport type ToolInputSchemaOutputType<T> = T extends InteropZodType\n ? InferInteropZodOutput<T>\n : T extends JSONSchema\n ? unknown\n : never;\n\n/**\n * Utility type that resolves the input type of a tool input schema.\n *\n * Input & Output types are a concept used with Zod schema, as Zod allows for transforms to occur\n * during parsing. When using JSONSchema, input and output types are the same.\n *\n * The input type for a given schema should match the structure of the arguments that the LLM\n * generates as part of its {@link ToolCall}. The output type will be the type that results from\n * applying any transforms defined in your schema. If there are no transforms, the input and output\n * types will be the same.\n */\nexport type ToolInputSchemaInputType<T> = T extends InteropZodType\n ? InferInteropZodInput<T>\n : T extends JSONSchema\n ? unknown\n : never;\n\n/**\n * Defines the type that will be passed into a tool handler function as a result of a tool call.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport type StructuredToolCallInput<\n SchemaT = ToolInputSchemaBase,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n> =\n | (ToolInputSchemaOutputType<SchemaT> extends string ? string : never)\n | SchemaInputT\n | ToolCall;\n\n/**\n * An input schema type for tools that accept a single string input.\n *\n * This schema defines a tool that takes an optional string parameter named \"input\".\n * It uses Zod's effects to transform the input and strip any extra properties.\n *\n * This is primarily used for creating simple string-based tools where the LLM\n * only needs to provide a single text value as input to the tool.\n */\nexport type StringInputToolSchema = z3.ZodType<\n string | undefined,\n z3.ZodTypeDef,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\n/**\n * Defines the type for input to a tool's call method.\n *\n * This type is a convenience alias for StructuredToolCallInput with the input type\n * derived from the schema. It represents the possible inputs that can be passed to a tool,\n * which can be either:\n * - A string (if the tool accepts string input)\n * - A structured input matching the tool's schema\n * - A ToolCall object (typically from an LLM)\n *\n * @param SchemaT - The schema type for the tool input, defaults to StringInputToolSchema\n */\nexport type ToolCallInput<SchemaT = StringInputToolSchema> =\n StructuredToolCallInput<SchemaT, ToolInputSchemaInputType<SchemaT>>;\n\n/**\n * Interface that defines the shape of a LangChain structured tool.\n *\n * A structured tool is a tool that uses a schema to define the structure of the arguments that the\n * LLM generates as part of its {@link ToolCall}.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface StructuredToolInterface<\n SchemaT = ToolInputSchemaBase,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends RunnableInterface<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n > {\n lc_namespace: string[];\n\n /**\n * A Zod schema representing the parameters of the tool.\n */\n schema: SchemaT;\n\n /**\n * Invokes the tool with the provided argument and configuration.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration for the tool call.\n * @returns A Promise that resolves with the tool's output.\n */\n invoke<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>>;\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 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\n /**\n * The name of the tool.\n */\n name: string;\n\n /**\n * A description of the tool.\n */\n description: string;\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: boolean;\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/**\n * A special interface for tools that accept a string input, usually defined with the {@link Tool} class.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface ToolInterface<\n SchemaT = StringInputToolSchema,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT> {\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 call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n // TODO: shouldn't this be narrowed based on SchemaT?\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>>;\n}\n\n/**\n * Base interface for the input parameters of the {@link DynamicTool} and\n * {@link DynamicStructuredTool} classes.\n */\nexport interface BaseDynamicToolInput extends ToolParams {\n name: string;\n description: string;\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 * Interface for the input parameters of the DynamicTool class.\n */\nexport interface DynamicToolInput<ToolOutputT = ToolOutputType>\n extends BaseDynamicToolInput {\n func: (\n input: string,\n runManager?: CallbackManagerForToolRun,\n config?: ToolRunnableConfig\n ) => Promise<ToolOutputT>;\n}\n\n/**\n * Interface for the input parameters of the DynamicStructuredTool class.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaOutputT - The TypeScript type representing the result of applying the schema to the tool arguments. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface DynamicStructuredToolInput<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends BaseDynamicToolInput {\n /**\n * Tool handler function - the function that will be called when the tool is invoked.\n *\n * @param input - The input to the tool.\n * @param runManager - The run manager for the tool.\n * @param config - The configuration for the tool.\n * @returns The result of the tool.\n */\n func: (\n input: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n config?: RunnableConfig\n ) => Promise<ToolOutputT>;\n schema: SchemaT;\n}\n\n/**\n * Confirm whether the inputted tool is an instance of `StructuredToolInterface`.\n *\n * @param {StructuredToolInterface | JSONSchema | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`.\n * @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`.\n */\nexport function isStructuredTool(\n tool?: StructuredToolInterface | ToolDefinition | JSONSchema\n): tool is StructuredToolInterface {\n return (\n tool !== undefined &&\n Array.isArray((tool as StructuredToolInterface).lc_namespace)\n );\n}\n\n/**\n * Confirm whether the inputted tool is an instance of `RunnableToolLike`.\n *\n * @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`.\n * @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`.\n */\nexport function isRunnableToolLike(tool?: unknown): tool is RunnableToolLike {\n return (\n tool !== undefined &&\n Runnable.isRunnable(tool) &&\n \"lc_name\" in tool.constructor &&\n typeof tool.constructor.lc_name === \"function\" &&\n tool.constructor.lc_name() === \"RunnableToolLike\"\n );\n}\n\n/**\n * Confirm whether or not the tool contains the necessary properties to be considered a `StructuredToolParams`.\n *\n * @param {unknown | undefined} tool The object to check if it is a `StructuredToolParams`.\n * @returns {tool is StructuredToolParams} Whether the inputted object is a `StructuredToolParams`.\n */\nexport function isStructuredToolParams(\n tool?: unknown\n): tool is StructuredToolParams {\n return (\n !!tool &&\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"schema\" in tool &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (isInteropZodSchema(tool.schema as Record<string, any>) ||\n (tool.schema != null &&\n typeof tool.schema === \"object\" &&\n \"type\" in tool.schema &&\n typeof tool.schema.type === \"string\" &&\n [\"null\", \"boolean\", \"object\", \"array\", \"number\", \"string\"].includes(\n tool.schema.type\n )))\n );\n}\n\n/**\n * Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams.\n * It returns `is StructuredToolParams` since that is the most minimal interface of the three,\n * while still containing the necessary properties to be passed to a LLM for tool calling.\n *\n * @param {unknown | undefined} tool The tool to check if it is a LangChain tool.\n * @returns {tool is StructuredToolParams} Whether the inputted tool is a LangChain tool.\n */\nexport function isLangChainTool(tool?: unknown): tool is StructuredToolParams {\n return (\n isStructuredToolParams(tool) ||\n isRunnableToolLike(tool) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n isStructuredTool(tool as any)\n );\n}\n\n/**\n * Runtime context automatically injected into tools.\n *\n * When a tool function has a parameter named `tool_runtime` with type hint\n * `ToolRuntime`, the tool execution system will automatically inject an instance\n * containing:\n *\n * - `state`: The current graph state\n * - `toolCallId`: The ID of the current tool call\n * - `config`: `RunnableConfig` for the current execution\n * - `context`: Runtime context\n * - `store`: `BaseStore` instance for persistent storage\n * - `writer`: Stream writer for streaming output\n *\n * No `Annotated` wrapper is needed - just use `runtime: ToolRuntime`\n * as a parameter.\n *\n * @example\n * ```typescript\n * import { tool, type ToolRuntime } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const stateSchema = z.object({\n * messages: z.array(z.any()),\n * userId: z.string().optional(),\n * });\n *\n * const greet = tool(\n * async ({ name }, runtime: ToolRuntime<typeof stateSchema>) => {\n * // Access state\n * const messages = runtime.state.messages;\n *\n * // Access tool_call_id\n * console.log(`Tool call ID: ${runtime.toolCallId}`);\n *\n * // Access config\n * console.log(`Run ID: ${runtime.config.runId}`);\n *\n * // Access runtime context\n * const userId = runtime.context?.userId;\n *\n * // Access store\n * await runtime.store?.mset([[\"key\", \"value\"]]);\n *\n * // Stream output\n * runtime.writer?.(\"Processing...\");\n *\n * return `Hello! User ID: ${runtime.state.userId || \"unknown\"} ${name}`;\n * },\n * {\n * name: \"greet\",\n * description: \"Use this to greet the user once you found their info.\",\n * schema: z.object({ name: z.string() }),\n * stateSchema,\n * }\n * );\n *\n * const agent = createAgent({\n * model,\n * tools: [greet],\n * stateSchema,\n * contextSchema,\n * });\n * ```\n *\n * @template StateT - The type of the state schema (inferred from stateSchema)\n * @template ContextT - The type of the context schema (inferred from contextSchema)\n */\nexport type ToolRuntime<\n TState = unknown,\n TContext = unknown,\n> = RunnableConfig & {\n /**\n * The current graph state.\n */\n state: TState extends InteropZodObject\n ? InferInteropZodOutput<TState>\n : TState extends Record<string, unknown>\n ? TState\n : unknown;\n /**\n * The ID of the current tool call.\n */\n toolCallId: string;\n /**\n * The current tool call.\n */\n toolCall?: ToolCall;\n /**\n * RunnableConfig for the current execution.\n */\n config: ToolRunnableConfig;\n /**\n * Runtime context (from langgraph `Runtime`).\n */\n context: TContext extends InteropZodObject\n ? InferInteropZodOutput<TContext>\n : TContext extends Record<string, unknown>\n ? TContext\n : unknown;\n /**\n * BaseStore instance for persistent storage (from langgraph `Runtime`).\n */\n store: BaseStore<string, unknown> | null;\n /**\n * Stream writer for streaming output (from langgraph `Runtime`).\n */\n writer: ((chunk: unknown) => void) | null;\n};\n"],"mappings":";;;;;;;;;;AA0XA,SAAgB,iBACdA,MACiC;AACjC,QACE,SAAS,UACT,MAAM,QAAS,KAAiC,aAAa;AAEhE;;;;;;;AAQD,SAAgB,mBAAmBC,MAA0C;AAC3E,QACE,SAAS,UACTC,sBAAS,WAAW,KAAK,IACzB,aAAa,KAAK,eAClB,OAAO,KAAK,YAAY,YAAY,cACpC,KAAK,YAAY,SAAS,KAAK;AAElC;;;;;;;AAQD,SAAgB,uBACdD,MAC8B;AAC9B,QACE,CAAC,CAAC,QACF,OAAO,SAAS,YAChB,UAAU,QACV,YAAY,SAEXE,+BAAmB,KAAK,OAA8B,IACpD,KAAK,UAAU,QACd,OAAO,KAAK,WAAW,YACvB,UAAU,KAAK,UACf,OAAO,KAAK,OAAO,SAAS,YAC5B;EAAC;EAAQ;EAAW;EAAU;EAAS;EAAU;CAAS,EAAC,SACzD,KAAK,OAAO,KACb;AAER;;;;;;;;;AAUD,SAAgB,gBAAgBF,MAA8C;AAC5E,QACE,uBAAuB,KAAK,IAC5B,mBAAmB,KAAK,IAExB,iBAAiB,KAAY;AAEhC"}
|
|
1
|
+
{"version":3,"file":"types.cjs","names":["tool?: StructuredToolInterface | ToolDefinition | JSONSchema","tool?: unknown","Runnable","isInteropZodSchema"],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type { z as z3 } from \"zod/v3\";\nimport { CallbackManagerForToolRun } from \"../callbacks/manager.js\";\nimport type {\n BaseLangChainParams,\n ToolDefinition,\n} from \"../language_models/base.js\";\nimport type { RunnableConfig } from \"../runnables/config.js\";\nimport {\n Runnable,\n RunnableToolLike,\n type RunnableInterface,\n} from \"../runnables/base.js\";\nimport {\n type DirectToolOutput,\n type ToolCall,\n type ToolMessage,\n} from \"../messages/tool.js\";\nimport type { MessageContent } from \"../messages/base.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodType,\n isInteropZodSchema,\n type InteropZodObject,\n} from \"../utils/types/zod.js\";\n\nimport { JSONSchema } from \"../utils/json_schema.js\";\nimport type { BaseStore } from \"../stores.js\";\n\nexport type ResponseFormat = \"content\" | \"content_and_artifact\" | string;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ToolOutputType = any;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContentAndArtifact = [MessageContent, any];\n\n/**\n * Conditional type that determines the return type of the {@link StructuredTool.invoke} method.\n * - If the input is a ToolCall, it returns a ToolMessage\n * - If the config is a runnable config and contains a toolCall property, it returns a ToolMessage\n * - Otherwise, it returns the original output type\n */\nexport type ToolReturnType<TInput, TConfig, TOutput> =\n TOutput extends DirectToolOutput\n ? TOutput\n : TConfig extends { toolCall: { id: string } }\n ? ToolMessage\n : TConfig extends { toolCall: { id: undefined } }\n ? TOutput\n : TConfig extends { toolCall: { id?: string } }\n ? TOutput | ToolMessage\n : TInput extends ToolCall\n ? ToolMessage\n : TOutput;\n\n/**\n * Base type that establishes the types of input schemas that can be used for LangChain tool\n * definitions.\n */\nexport type ToolInputSchemaBase = z3.ZodTypeAny | JSONSchema;\n\n/**\n * Parameters for the Tool classes.\n */\nexport interface ToolParams extends BaseLangChainParams {\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 * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n /**\n * Whether to show full details in the thrown parsing errors.\n *\n * @default false\n */\n verboseParsingErrors?: boolean;\n /**\n * Metadata for the tool.\n */\n metadata?: Record<string, unknown>;\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\nexport type ToolRunnableConfig<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ConfigurableFieldType extends Record<string, any> = Record<string, any>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ContextSchema = any,\n> = RunnableConfig<ConfigurableFieldType> & {\n toolCall?: ToolCall;\n context?: ContextSchema;\n};\n\n/**\n * Schema for defining tools.\n *\n * @version 0.2.19\n */\nexport interface StructuredToolParams extends Pick<\n StructuredToolInterface,\n \"name\" | \"schema\" | \"extras\"\n> {\n /**\n * An optional description of the tool to pass to the model.\n */\n description?: string;\n}\n\n/**\n * Utility type that resolves the output type of a tool input schema.\n *\n * Input & Output types are a concept used with Zod schema, as Zod allows for transforms to occur\n * during parsing. When using JSONSchema, input and output types are the same.\n *\n * The input type for a given schema should match the structure of the arguments that the LLM\n * generates as part of its {@link ToolCall}. The output type will be the type that results from\n * applying any transforms defined in your schema. If there are no transforms, the input and output\n * types will be the same.\n */\nexport type ToolInputSchemaOutputType<T> = T extends InteropZodType\n ? InferInteropZodOutput<T>\n : T extends JSONSchema\n ? unknown\n : never;\n\n/**\n * Utility type that resolves the input type of a tool input schema.\n *\n * Input & Output types are a concept used with Zod schema, as Zod allows for transforms to occur\n * during parsing. When using JSONSchema, input and output types are the same.\n *\n * The input type for a given schema should match the structure of the arguments that the LLM\n * generates as part of its {@link ToolCall}. The output type will be the type that results from\n * applying any transforms defined in your schema. If there are no transforms, the input and output\n * types will be the same.\n */\nexport type ToolInputSchemaInputType<T> = T extends InteropZodType\n ? InferInteropZodInput<T>\n : T extends JSONSchema\n ? unknown\n : never;\n\n/**\n * Defines the type that will be passed into a tool handler function as a result of a tool call.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport type StructuredToolCallInput<\n SchemaT = ToolInputSchemaBase,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n> =\n | (ToolInputSchemaOutputType<SchemaT> extends string ? string : never)\n | SchemaInputT\n | ToolCall;\n\n/**\n * An input schema type for tools that accept a single string input.\n *\n * This schema defines a tool that takes an optional string parameter named \"input\".\n * It uses Zod's effects to transform the input and strip any extra properties.\n *\n * This is primarily used for creating simple string-based tools where the LLM\n * only needs to provide a single text value as input to the tool.\n */\nexport type StringInputToolSchema = z3.ZodType<\n string | undefined,\n z3.ZodTypeDef,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\n/**\n * Defines the type for input to a tool's call method.\n *\n * This type is a convenience alias for StructuredToolCallInput with the input type\n * derived from the schema. It represents the possible inputs that can be passed to a tool,\n * which can be either:\n * - A string (if the tool accepts string input)\n * - A structured input matching the tool's schema\n * - A ToolCall object (typically from an LLM)\n *\n * @param SchemaT - The schema type for the tool input, defaults to StringInputToolSchema\n */\nexport type ToolCallInput<SchemaT = StringInputToolSchema> =\n StructuredToolCallInput<SchemaT, ToolInputSchemaInputType<SchemaT>>;\n\n/**\n * Interface that defines the shape of a LangChain structured tool.\n *\n * A structured tool is a tool that uses a schema to define the structure of the arguments that the\n * LLM generates as part of its {@link ToolCall}.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface StructuredToolInterface<\n SchemaT = ToolInputSchemaBase,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends RunnableInterface<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n> {\n lc_namespace: string[];\n\n /**\n * A Zod schema representing the parameters of the tool.\n */\n schema: SchemaT;\n\n /**\n * Invokes the tool with the provided argument and configuration.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration for the tool call.\n * @returns A Promise that resolves with the tool's output.\n */\n invoke<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>>;\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 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\n /**\n * The name of the tool.\n */\n name: string;\n\n /**\n * A description of the tool.\n */\n description: string;\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: boolean;\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/**\n * A special interface for tools that accept a string input, usually defined with the {@link Tool} class.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface ToolInterface<\n SchemaT = StringInputToolSchema,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT> {\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 call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n // TODO: shouldn't this be narrowed based on SchemaT?\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>>;\n}\n\n/**\n * Base interface for the input parameters of the {@link DynamicTool} and\n * {@link DynamicStructuredTool} classes.\n */\nexport interface BaseDynamicToolInput extends ToolParams {\n name: string;\n description: string;\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 * Interface for the input parameters of the DynamicTool class.\n */\nexport interface DynamicToolInput<\n ToolOutputT = ToolOutputType,\n> extends BaseDynamicToolInput {\n func: (\n input: string,\n runManager?: CallbackManagerForToolRun,\n config?: ToolRunnableConfig\n ) => Promise<ToolOutputT>;\n}\n\n/**\n * Interface for the input parameters of the DynamicStructuredTool class.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaOutputT - The TypeScript type representing the result of applying the schema to the tool arguments. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface DynamicStructuredToolInput<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends BaseDynamicToolInput {\n /**\n * Tool handler function - the function that will be called when the tool is invoked.\n *\n * @param input - The input to the tool.\n * @param runManager - The run manager for the tool.\n * @param config - The configuration for the tool.\n * @returns The result of the tool.\n */\n func: (\n input: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n config?: RunnableConfig\n ) => Promise<ToolOutputT>;\n schema: SchemaT;\n}\n\n/**\n * Confirm whether the inputted tool is an instance of `StructuredToolInterface`.\n *\n * @param {StructuredToolInterface | JSONSchema | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`.\n * @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`.\n */\nexport function isStructuredTool(\n tool?: StructuredToolInterface | ToolDefinition | JSONSchema\n): tool is StructuredToolInterface {\n return (\n tool !== undefined &&\n Array.isArray((tool as StructuredToolInterface).lc_namespace)\n );\n}\n\n/**\n * Confirm whether the inputted tool is an instance of `RunnableToolLike`.\n *\n * @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`.\n * @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`.\n */\nexport function isRunnableToolLike(tool?: unknown): tool is RunnableToolLike {\n return (\n tool !== undefined &&\n Runnable.isRunnable(tool) &&\n \"lc_name\" in tool.constructor &&\n typeof tool.constructor.lc_name === \"function\" &&\n tool.constructor.lc_name() === \"RunnableToolLike\"\n );\n}\n\n/**\n * Confirm whether or not the tool contains the necessary properties to be considered a `StructuredToolParams`.\n *\n * @param {unknown | undefined} tool The object to check if it is a `StructuredToolParams`.\n * @returns {tool is StructuredToolParams} Whether the inputted object is a `StructuredToolParams`.\n */\nexport function isStructuredToolParams(\n tool?: unknown\n): tool is StructuredToolParams {\n return (\n !!tool &&\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"schema\" in tool &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (isInteropZodSchema(tool.schema as Record<string, any>) ||\n (tool.schema != null &&\n typeof tool.schema === \"object\" &&\n \"type\" in tool.schema &&\n typeof tool.schema.type === \"string\" &&\n [\"null\", \"boolean\", \"object\", \"array\", \"number\", \"string\"].includes(\n tool.schema.type\n )))\n );\n}\n\n/**\n * Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams.\n * It returns `is StructuredToolParams` since that is the most minimal interface of the three,\n * while still containing the necessary properties to be passed to a LLM for tool calling.\n *\n * @param {unknown | undefined} tool The tool to check if it is a LangChain tool.\n * @returns {tool is StructuredToolParams} Whether the inputted tool is a LangChain tool.\n */\nexport function isLangChainTool(tool?: unknown): tool is StructuredToolParams {\n return (\n isStructuredToolParams(tool) ||\n isRunnableToolLike(tool) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n isStructuredTool(tool as any)\n );\n}\n\n/**\n * Runtime context automatically injected into tools.\n *\n * When a tool function has a parameter named `tool_runtime` with type hint\n * `ToolRuntime`, the tool execution system will automatically inject an instance\n * containing:\n *\n * - `state`: The current graph state\n * - `toolCallId`: The ID of the current tool call\n * - `config`: `RunnableConfig` for the current execution\n * - `context`: Runtime context\n * - `store`: `BaseStore` instance for persistent storage\n * - `writer`: Stream writer for streaming output\n *\n * No `Annotated` wrapper is needed - just use `runtime: ToolRuntime`\n * as a parameter.\n *\n * @example\n * ```typescript\n * import { tool, type ToolRuntime } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const stateSchema = z.object({\n * messages: z.array(z.any()),\n * userId: z.string().optional(),\n * });\n *\n * const greet = tool(\n * async ({ name }, runtime: ToolRuntime<typeof stateSchema>) => {\n * // Access state\n * const messages = runtime.state.messages;\n *\n * // Access tool_call_id\n * console.log(`Tool call ID: ${runtime.toolCallId}`);\n *\n * // Access config\n * console.log(`Run ID: ${runtime.config.runId}`);\n *\n * // Access runtime context\n * const userId = runtime.context?.userId;\n *\n * // Access store\n * await runtime.store?.mset([[\"key\", \"value\"]]);\n *\n * // Stream output\n * runtime.writer?.(\"Processing...\");\n *\n * return `Hello! User ID: ${runtime.state.userId || \"unknown\"} ${name}`;\n * },\n * {\n * name: \"greet\",\n * description: \"Use this to greet the user once you found their info.\",\n * schema: z.object({ name: z.string() }),\n * stateSchema,\n * }\n * );\n *\n * const agent = createAgent({\n * model,\n * tools: [greet],\n * stateSchema,\n * contextSchema,\n * });\n * ```\n *\n * @template StateT - The type of the state schema (inferred from stateSchema)\n * @template ContextT - The type of the context schema (inferred from contextSchema)\n */\nexport type ToolRuntime<\n TState = unknown,\n TContext = unknown,\n> = RunnableConfig & {\n /**\n * The current graph state.\n */\n state: TState extends InteropZodObject\n ? InferInteropZodOutput<TState>\n : TState extends Record<string, unknown>\n ? TState\n : unknown;\n /**\n * The ID of the current tool call.\n */\n toolCallId: string;\n /**\n * The current tool call.\n */\n toolCall?: ToolCall;\n /**\n * RunnableConfig for the current execution.\n */\n config: ToolRunnableConfig;\n /**\n * Runtime context (from langgraph `Runtime`).\n */\n context: TContext extends InteropZodObject\n ? InferInteropZodOutput<TContext>\n : TContext extends Record<string, unknown>\n ? TContext\n : unknown;\n /**\n * BaseStore instance for persistent storage (from langgraph `Runtime`).\n */\n store: BaseStore<string, unknown> | null;\n /**\n * Stream writer for streaming output (from langgraph `Runtime`).\n */\n writer: ((chunk: unknown) => void) | null;\n};\n"],"mappings":";;;;;;;;;;AA6XA,SAAgB,iBACdA,MACiC;AACjC,QACE,SAAS,UACT,MAAM,QAAS,KAAiC,aAAa;AAEhE;;;;;;;AAQD,SAAgB,mBAAmBC,MAA0C;AAC3E,QACE,SAAS,UACTC,sBAAS,WAAW,KAAK,IACzB,aAAa,KAAK,eAClB,OAAO,KAAK,YAAY,YAAY,cACpC,KAAK,YAAY,SAAS,KAAK;AAElC;;;;;;;AAQD,SAAgB,uBACdD,MAC8B;AAC9B,QACE,CAAC,CAAC,QACF,OAAO,SAAS,YAChB,UAAU,QACV,YAAY,SAEXE,+BAAmB,KAAK,OAA8B,IACpD,KAAK,UAAU,QACd,OAAO,KAAK,WAAW,YACvB,UAAU,KAAK,UACf,OAAO,KAAK,OAAO,SAAS,YAC5B;EAAC;EAAQ;EAAW;EAAU;EAAS;EAAU;CAAS,EAAC,SACzD,KAAK,OAAO,KACb;AAER;;;;;;;;;AAUD,SAAgB,gBAAgBF,MAA8C;AAC5E,QACE,uBAAuB,KAAK,IAC5B,mBAAmB,KAAK,IAExB,iBAAiB,KAAY;AAEhC"}
|
package/dist/tools/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":["tool?: StructuredToolInterface | ToolDefinition | JSONSchema","tool?: unknown"],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type { z as z3 } from \"zod/v3\";\nimport { CallbackManagerForToolRun } from \"../callbacks/manager.js\";\nimport type {\n BaseLangChainParams,\n ToolDefinition,\n} from \"../language_models/base.js\";\nimport type { RunnableConfig } from \"../runnables/config.js\";\nimport {\n Runnable,\n RunnableToolLike,\n type RunnableInterface,\n} from \"../runnables/base.js\";\nimport {\n type DirectToolOutput,\n type ToolCall,\n type ToolMessage,\n} from \"../messages/tool.js\";\nimport type { MessageContent } from \"../messages/base.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodType,\n isInteropZodSchema,\n type InteropZodObject,\n} from \"../utils/types/zod.js\";\n\nimport { JSONSchema } from \"../utils/json_schema.js\";\nimport type { BaseStore } from \"../stores.js\";\n\nexport type ResponseFormat = \"content\" | \"content_and_artifact\" | string;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ToolOutputType = any;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContentAndArtifact = [MessageContent, any];\n\n/**\n * Conditional type that determines the return type of the {@link StructuredTool.invoke} method.\n * - If the input is a ToolCall, it returns a ToolMessage\n * - If the config is a runnable config and contains a toolCall property, it returns a ToolMessage\n * - Otherwise, it returns the original output type\n */\nexport type ToolReturnType<TInput, TConfig, TOutput> =\n TOutput extends DirectToolOutput\n ? TOutput\n : TConfig extends { toolCall: { id: string } }\n ? ToolMessage\n : TConfig extends { toolCall: { id: undefined } }\n ? TOutput\n : TConfig extends { toolCall: { id?: string } }\n ? TOutput | ToolMessage\n : TInput extends ToolCall\n ? ToolMessage\n : TOutput;\n\n/**\n * Base type that establishes the types of input schemas that can be used for LangChain tool\n * definitions.\n */\nexport type ToolInputSchemaBase = z3.ZodTypeAny | JSONSchema;\n\n/**\n * Parameters for the Tool classes.\n */\nexport interface ToolParams extends BaseLangChainParams {\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 * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n /**\n * Whether to show full details in the thrown parsing errors.\n *\n * @default false\n */\n verboseParsingErrors?: boolean;\n /**\n * Metadata for the tool.\n */\n metadata?: Record<string, unknown>;\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\nexport type ToolRunnableConfig<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ConfigurableFieldType extends Record<string, any> = Record<string, any>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ContextSchema = any,\n> = RunnableConfig<ConfigurableFieldType> & {\n toolCall?: ToolCall;\n context?: ContextSchema;\n};\n\n/**\n * Schema for defining tools.\n *\n * @version 0.2.19\n */\nexport interface StructuredToolParams\n extends Pick<StructuredToolInterface, \"name\" | \"schema\" | \"extras\"> {\n /**\n * An optional description of the tool to pass to the model.\n */\n description?: string;\n}\n\n/**\n * Utility type that resolves the output type of a tool input schema.\n *\n * Input & Output types are a concept used with Zod schema, as Zod allows for transforms to occur\n * during parsing. When using JSONSchema, input and output types are the same.\n *\n * The input type for a given schema should match the structure of the arguments that the LLM\n * generates as part of its {@link ToolCall}. The output type will be the type that results from\n * applying any transforms defined in your schema. If there are no transforms, the input and output\n * types will be the same.\n */\nexport type ToolInputSchemaOutputType<T> = T extends InteropZodType\n ? InferInteropZodOutput<T>\n : T extends JSONSchema\n ? unknown\n : never;\n\n/**\n * Utility type that resolves the input type of a tool input schema.\n *\n * Input & Output types are a concept used with Zod schema, as Zod allows for transforms to occur\n * during parsing. When using JSONSchema, input and output types are the same.\n *\n * The input type for a given schema should match the structure of the arguments that the LLM\n * generates as part of its {@link ToolCall}. The output type will be the type that results from\n * applying any transforms defined in your schema. If there are no transforms, the input and output\n * types will be the same.\n */\nexport type ToolInputSchemaInputType<T> = T extends InteropZodType\n ? InferInteropZodInput<T>\n : T extends JSONSchema\n ? unknown\n : never;\n\n/**\n * Defines the type that will be passed into a tool handler function as a result of a tool call.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport type StructuredToolCallInput<\n SchemaT = ToolInputSchemaBase,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n> =\n | (ToolInputSchemaOutputType<SchemaT> extends string ? string : never)\n | SchemaInputT\n | ToolCall;\n\n/**\n * An input schema type for tools that accept a single string input.\n *\n * This schema defines a tool that takes an optional string parameter named \"input\".\n * It uses Zod's effects to transform the input and strip any extra properties.\n *\n * This is primarily used for creating simple string-based tools where the LLM\n * only needs to provide a single text value as input to the tool.\n */\nexport type StringInputToolSchema = z3.ZodType<\n string | undefined,\n z3.ZodTypeDef,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\n/**\n * Defines the type for input to a tool's call method.\n *\n * This type is a convenience alias for StructuredToolCallInput with the input type\n * derived from the schema. It represents the possible inputs that can be passed to a tool,\n * which can be either:\n * - A string (if the tool accepts string input)\n * - A structured input matching the tool's schema\n * - A ToolCall object (typically from an LLM)\n *\n * @param SchemaT - The schema type for the tool input, defaults to StringInputToolSchema\n */\nexport type ToolCallInput<SchemaT = StringInputToolSchema> =\n StructuredToolCallInput<SchemaT, ToolInputSchemaInputType<SchemaT>>;\n\n/**\n * Interface that defines the shape of a LangChain structured tool.\n *\n * A structured tool is a tool that uses a schema to define the structure of the arguments that the\n * LLM generates as part of its {@link ToolCall}.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface StructuredToolInterface<\n SchemaT = ToolInputSchemaBase,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends RunnableInterface<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n > {\n lc_namespace: string[];\n\n /**\n * A Zod schema representing the parameters of the tool.\n */\n schema: SchemaT;\n\n /**\n * Invokes the tool with the provided argument and configuration.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration for the tool call.\n * @returns A Promise that resolves with the tool's output.\n */\n invoke<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>>;\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 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\n /**\n * The name of the tool.\n */\n name: string;\n\n /**\n * A description of the tool.\n */\n description: string;\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: boolean;\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/**\n * A special interface for tools that accept a string input, usually defined with the {@link Tool} class.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface ToolInterface<\n SchemaT = StringInputToolSchema,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT> {\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 call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n // TODO: shouldn't this be narrowed based on SchemaT?\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>>;\n}\n\n/**\n * Base interface for the input parameters of the {@link DynamicTool} and\n * {@link DynamicStructuredTool} classes.\n */\nexport interface BaseDynamicToolInput extends ToolParams {\n name: string;\n description: string;\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 * Interface for the input parameters of the DynamicTool class.\n */\nexport interface DynamicToolInput<ToolOutputT = ToolOutputType>\n extends BaseDynamicToolInput {\n func: (\n input: string,\n runManager?: CallbackManagerForToolRun,\n config?: ToolRunnableConfig\n ) => Promise<ToolOutputT>;\n}\n\n/**\n * Interface for the input parameters of the DynamicStructuredTool class.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaOutputT - The TypeScript type representing the result of applying the schema to the tool arguments. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface DynamicStructuredToolInput<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends BaseDynamicToolInput {\n /**\n * Tool handler function - the function that will be called when the tool is invoked.\n *\n * @param input - The input to the tool.\n * @param runManager - The run manager for the tool.\n * @param config - The configuration for the tool.\n * @returns The result of the tool.\n */\n func: (\n input: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n config?: RunnableConfig\n ) => Promise<ToolOutputT>;\n schema: SchemaT;\n}\n\n/**\n * Confirm whether the inputted tool is an instance of `StructuredToolInterface`.\n *\n * @param {StructuredToolInterface | JSONSchema | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`.\n * @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`.\n */\nexport function isStructuredTool(\n tool?: StructuredToolInterface | ToolDefinition | JSONSchema\n): tool is StructuredToolInterface {\n return (\n tool !== undefined &&\n Array.isArray((tool as StructuredToolInterface).lc_namespace)\n );\n}\n\n/**\n * Confirm whether the inputted tool is an instance of `RunnableToolLike`.\n *\n * @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`.\n * @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`.\n */\nexport function isRunnableToolLike(tool?: unknown): tool is RunnableToolLike {\n return (\n tool !== undefined &&\n Runnable.isRunnable(tool) &&\n \"lc_name\" in tool.constructor &&\n typeof tool.constructor.lc_name === \"function\" &&\n tool.constructor.lc_name() === \"RunnableToolLike\"\n );\n}\n\n/**\n * Confirm whether or not the tool contains the necessary properties to be considered a `StructuredToolParams`.\n *\n * @param {unknown | undefined} tool The object to check if it is a `StructuredToolParams`.\n * @returns {tool is StructuredToolParams} Whether the inputted object is a `StructuredToolParams`.\n */\nexport function isStructuredToolParams(\n tool?: unknown\n): tool is StructuredToolParams {\n return (\n !!tool &&\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"schema\" in tool &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (isInteropZodSchema(tool.schema as Record<string, any>) ||\n (tool.schema != null &&\n typeof tool.schema === \"object\" &&\n \"type\" in tool.schema &&\n typeof tool.schema.type === \"string\" &&\n [\"null\", \"boolean\", \"object\", \"array\", \"number\", \"string\"].includes(\n tool.schema.type\n )))\n );\n}\n\n/**\n * Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams.\n * It returns `is StructuredToolParams` since that is the most minimal interface of the three,\n * while still containing the necessary properties to be passed to a LLM for tool calling.\n *\n * @param {unknown | undefined} tool The tool to check if it is a LangChain tool.\n * @returns {tool is StructuredToolParams} Whether the inputted tool is a LangChain tool.\n */\nexport function isLangChainTool(tool?: unknown): tool is StructuredToolParams {\n return (\n isStructuredToolParams(tool) ||\n isRunnableToolLike(tool) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n isStructuredTool(tool as any)\n );\n}\n\n/**\n * Runtime context automatically injected into tools.\n *\n * When a tool function has a parameter named `tool_runtime` with type hint\n * `ToolRuntime`, the tool execution system will automatically inject an instance\n * containing:\n *\n * - `state`: The current graph state\n * - `toolCallId`: The ID of the current tool call\n * - `config`: `RunnableConfig` for the current execution\n * - `context`: Runtime context\n * - `store`: `BaseStore` instance for persistent storage\n * - `writer`: Stream writer for streaming output\n *\n * No `Annotated` wrapper is needed - just use `runtime: ToolRuntime`\n * as a parameter.\n *\n * @example\n * ```typescript\n * import { tool, type ToolRuntime } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const stateSchema = z.object({\n * messages: z.array(z.any()),\n * userId: z.string().optional(),\n * });\n *\n * const greet = tool(\n * async ({ name }, runtime: ToolRuntime<typeof stateSchema>) => {\n * // Access state\n * const messages = runtime.state.messages;\n *\n * // Access tool_call_id\n * console.log(`Tool call ID: ${runtime.toolCallId}`);\n *\n * // Access config\n * console.log(`Run ID: ${runtime.config.runId}`);\n *\n * // Access runtime context\n * const userId = runtime.context?.userId;\n *\n * // Access store\n * await runtime.store?.mset([[\"key\", \"value\"]]);\n *\n * // Stream output\n * runtime.writer?.(\"Processing...\");\n *\n * return `Hello! User ID: ${runtime.state.userId || \"unknown\"} ${name}`;\n * },\n * {\n * name: \"greet\",\n * description: \"Use this to greet the user once you found their info.\",\n * schema: z.object({ name: z.string() }),\n * stateSchema,\n * }\n * );\n *\n * const agent = createAgent({\n * model,\n * tools: [greet],\n * stateSchema,\n * contextSchema,\n * });\n * ```\n *\n * @template StateT - The type of the state schema (inferred from stateSchema)\n * @template ContextT - The type of the context schema (inferred from contextSchema)\n */\nexport type ToolRuntime<\n TState = unknown,\n TContext = unknown,\n> = RunnableConfig & {\n /**\n * The current graph state.\n */\n state: TState extends InteropZodObject\n ? InferInteropZodOutput<TState>\n : TState extends Record<string, unknown>\n ? TState\n : unknown;\n /**\n * The ID of the current tool call.\n */\n toolCallId: string;\n /**\n * The current tool call.\n */\n toolCall?: ToolCall;\n /**\n * RunnableConfig for the current execution.\n */\n config: ToolRunnableConfig;\n /**\n * Runtime context (from langgraph `Runtime`).\n */\n context: TContext extends InteropZodObject\n ? InferInteropZodOutput<TContext>\n : TContext extends Record<string, unknown>\n ? TContext\n : unknown;\n /**\n * BaseStore instance for persistent storage (from langgraph `Runtime`).\n */\n store: BaseStore<string, unknown> | null;\n /**\n * Stream writer for streaming output (from langgraph `Runtime`).\n */\n writer: ((chunk: unknown) => void) | null;\n};\n"],"mappings":";;;;;;;;;;AA0XA,SAAgB,iBACdA,MACiC;AACjC,QACE,SAAS,UACT,MAAM,QAAS,KAAiC,aAAa;AAEhE;;;;;;;AAQD,SAAgB,mBAAmBC,MAA0C;AAC3E,QACE,SAAS,UACT,SAAS,WAAW,KAAK,IACzB,aAAa,KAAK,eAClB,OAAO,KAAK,YAAY,YAAY,cACpC,KAAK,YAAY,SAAS,KAAK;AAElC;;;;;;;AAQD,SAAgB,uBACdA,MAC8B;AAC9B,QACE,CAAC,CAAC,QACF,OAAO,SAAS,YAChB,UAAU,QACV,YAAY,SAEX,mBAAmB,KAAK,OAA8B,IACpD,KAAK,UAAU,QACd,OAAO,KAAK,WAAW,YACvB,UAAU,KAAK,UACf,OAAO,KAAK,OAAO,SAAS,YAC5B;EAAC;EAAQ;EAAW;EAAU;EAAS;EAAU;CAAS,EAAC,SACzD,KAAK,OAAO,KACb;AAER;;;;;;;;;AAUD,SAAgB,gBAAgBA,MAA8C;AAC5E,QACE,uBAAuB,KAAK,IAC5B,mBAAmB,KAAK,IAExB,iBAAiB,KAAY;AAEhC"}
|
|
1
|
+
{"version":3,"file":"types.js","names":["tool?: StructuredToolInterface | ToolDefinition | JSONSchema","tool?: unknown"],"sources":["../../src/tools/types.ts"],"sourcesContent":["import type { z as z3 } from \"zod/v3\";\nimport { CallbackManagerForToolRun } from \"../callbacks/manager.js\";\nimport type {\n BaseLangChainParams,\n ToolDefinition,\n} from \"../language_models/base.js\";\nimport type { RunnableConfig } from \"../runnables/config.js\";\nimport {\n Runnable,\n RunnableToolLike,\n type RunnableInterface,\n} from \"../runnables/base.js\";\nimport {\n type DirectToolOutput,\n type ToolCall,\n type ToolMessage,\n} from \"../messages/tool.js\";\nimport type { MessageContent } from \"../messages/base.js\";\nimport {\n type InferInteropZodInput,\n type InferInteropZodOutput,\n type InteropZodType,\n isInteropZodSchema,\n type InteropZodObject,\n} from \"../utils/types/zod.js\";\n\nimport { JSONSchema } from \"../utils/json_schema.js\";\nimport type { BaseStore } from \"../stores.js\";\n\nexport type ResponseFormat = \"content\" | \"content_and_artifact\" | string;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ToolOutputType = any;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ContentAndArtifact = [MessageContent, any];\n\n/**\n * Conditional type that determines the return type of the {@link StructuredTool.invoke} method.\n * - If the input is a ToolCall, it returns a ToolMessage\n * - If the config is a runnable config and contains a toolCall property, it returns a ToolMessage\n * - Otherwise, it returns the original output type\n */\nexport type ToolReturnType<TInput, TConfig, TOutput> =\n TOutput extends DirectToolOutput\n ? TOutput\n : TConfig extends { toolCall: { id: string } }\n ? ToolMessage\n : TConfig extends { toolCall: { id: undefined } }\n ? TOutput\n : TConfig extends { toolCall: { id?: string } }\n ? TOutput | ToolMessage\n : TInput extends ToolCall\n ? ToolMessage\n : TOutput;\n\n/**\n * Base type that establishes the types of input schemas that can be used for LangChain tool\n * definitions.\n */\nexport type ToolInputSchemaBase = z3.ZodTypeAny | JSONSchema;\n\n/**\n * Parameters for the Tool classes.\n */\nexport interface ToolParams extends BaseLangChainParams {\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 * Default config object for the tool runnable.\n */\n defaultConfig?: ToolRunnableConfig;\n /**\n * Whether to show full details in the thrown parsing errors.\n *\n * @default false\n */\n verboseParsingErrors?: boolean;\n /**\n * Metadata for the tool.\n */\n metadata?: Record<string, unknown>;\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\nexport type ToolRunnableConfig<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ConfigurableFieldType extends Record<string, any> = Record<string, any>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ContextSchema = any,\n> = RunnableConfig<ConfigurableFieldType> & {\n toolCall?: ToolCall;\n context?: ContextSchema;\n};\n\n/**\n * Schema for defining tools.\n *\n * @version 0.2.19\n */\nexport interface StructuredToolParams extends Pick<\n StructuredToolInterface,\n \"name\" | \"schema\" | \"extras\"\n> {\n /**\n * An optional description of the tool to pass to the model.\n */\n description?: string;\n}\n\n/**\n * Utility type that resolves the output type of a tool input schema.\n *\n * Input & Output types are a concept used with Zod schema, as Zod allows for transforms to occur\n * during parsing. When using JSONSchema, input and output types are the same.\n *\n * The input type for a given schema should match the structure of the arguments that the LLM\n * generates as part of its {@link ToolCall}. The output type will be the type that results from\n * applying any transforms defined in your schema. If there are no transforms, the input and output\n * types will be the same.\n */\nexport type ToolInputSchemaOutputType<T> = T extends InteropZodType\n ? InferInteropZodOutput<T>\n : T extends JSONSchema\n ? unknown\n : never;\n\n/**\n * Utility type that resolves the input type of a tool input schema.\n *\n * Input & Output types are a concept used with Zod schema, as Zod allows for transforms to occur\n * during parsing. When using JSONSchema, input and output types are the same.\n *\n * The input type for a given schema should match the structure of the arguments that the LLM\n * generates as part of its {@link ToolCall}. The output type will be the type that results from\n * applying any transforms defined in your schema. If there are no transforms, the input and output\n * types will be the same.\n */\nexport type ToolInputSchemaInputType<T> = T extends InteropZodType\n ? InferInteropZodInput<T>\n : T extends JSONSchema\n ? unknown\n : never;\n\n/**\n * Defines the type that will be passed into a tool handler function as a result of a tool call.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport type StructuredToolCallInput<\n SchemaT = ToolInputSchemaBase,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n> =\n | (ToolInputSchemaOutputType<SchemaT> extends string ? string : never)\n | SchemaInputT\n | ToolCall;\n\n/**\n * An input schema type for tools that accept a single string input.\n *\n * This schema defines a tool that takes an optional string parameter named \"input\".\n * It uses Zod's effects to transform the input and strip any extra properties.\n *\n * This is primarily used for creating simple string-based tools where the LLM\n * only needs to provide a single text value as input to the tool.\n */\nexport type StringInputToolSchema = z3.ZodType<\n string | undefined,\n z3.ZodTypeDef,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\n/**\n * Defines the type for input to a tool's call method.\n *\n * This type is a convenience alias for StructuredToolCallInput with the input type\n * derived from the schema. It represents the possible inputs that can be passed to a tool,\n * which can be either:\n * - A string (if the tool accepts string input)\n * - A structured input matching the tool's schema\n * - A ToolCall object (typically from an LLM)\n *\n * @param SchemaT - The schema type for the tool input, defaults to StringInputToolSchema\n */\nexport type ToolCallInput<SchemaT = StringInputToolSchema> =\n StructuredToolCallInput<SchemaT, ToolInputSchemaInputType<SchemaT>>;\n\n/**\n * Interface that defines the shape of a LangChain structured tool.\n *\n * A structured tool is a tool that uses a schema to define the structure of the arguments that the\n * LLM generates as part of its {@link ToolCall}.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface StructuredToolInterface<\n SchemaT = ToolInputSchemaBase,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends RunnableInterface<\n StructuredToolCallInput<SchemaT, SchemaInputT>,\n ToolOutputT | ToolMessage\n> {\n lc_namespace: string[];\n\n /**\n * A Zod schema representing the parameters of the tool.\n */\n schema: SchemaT;\n\n /**\n * Invokes the tool with the provided argument and configuration.\n * @param arg The input argument for the tool.\n * @param configArg Optional configuration for the tool call.\n * @returns A Promise that resolves with the tool's output.\n */\n invoke<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n arg: TArg,\n configArg?: TConfig\n ): Promise<ToolReturnType<TArg, TConfig, ToolOutputT>>;\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 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\n /**\n * The name of the tool.\n */\n name: string;\n\n /**\n * A description of the tool.\n */\n description: string;\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: boolean;\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/**\n * A special interface for tools that accept a string input, usually defined with the {@link Tool} class.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaInputT - The TypeScript type representing the structure of the tool arguments generated by the LLM. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface ToolInterface<\n SchemaT = StringInputToolSchema,\n SchemaInputT = ToolInputSchemaInputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT> {\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 call<\n TArg extends StructuredToolCallInput<SchemaT, SchemaInputT>,\n TConfig extends ToolRunnableConfig | undefined,\n >(\n // TODO: shouldn't this be narrowed based on SchemaT?\n arg: TArg,\n callbacks?: TConfig\n ): Promise<ToolReturnType<NonNullable<TArg>, TConfig, ToolOutputT>>;\n}\n\n/**\n * Base interface for the input parameters of the {@link DynamicTool} and\n * {@link DynamicStructuredTool} classes.\n */\nexport interface BaseDynamicToolInput extends ToolParams {\n name: string;\n description: string;\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 * Interface for the input parameters of the DynamicTool class.\n */\nexport interface DynamicToolInput<\n ToolOutputT = ToolOutputType,\n> extends BaseDynamicToolInput {\n func: (\n input: string,\n runManager?: CallbackManagerForToolRun,\n config?: ToolRunnableConfig\n ) => Promise<ToolOutputT>;\n}\n\n/**\n * Interface for the input parameters of the DynamicStructuredTool class.\n *\n * @param SchemaT - The type of the tool input schema. Usually you don't need to specify this.\n * @param SchemaOutputT - The TypeScript type representing the result of applying the schema to the tool arguments. Useful for type checking tool handler functions when using JSONSchema.\n */\nexport interface DynamicStructuredToolInput<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n> extends BaseDynamicToolInput {\n /**\n * Tool handler function - the function that will be called when the tool is invoked.\n *\n * @param input - The input to the tool.\n * @param runManager - The run manager for the tool.\n * @param config - The configuration for the tool.\n * @returns The result of the tool.\n */\n func: (\n input: SchemaOutputT,\n runManager?: CallbackManagerForToolRun,\n config?: RunnableConfig\n ) => Promise<ToolOutputT>;\n schema: SchemaT;\n}\n\n/**\n * Confirm whether the inputted tool is an instance of `StructuredToolInterface`.\n *\n * @param {StructuredToolInterface | JSONSchema | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`.\n * @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`.\n */\nexport function isStructuredTool(\n tool?: StructuredToolInterface | ToolDefinition | JSONSchema\n): tool is StructuredToolInterface {\n return (\n tool !== undefined &&\n Array.isArray((tool as StructuredToolInterface).lc_namespace)\n );\n}\n\n/**\n * Confirm whether the inputted tool is an instance of `RunnableToolLike`.\n *\n * @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`.\n * @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`.\n */\nexport function isRunnableToolLike(tool?: unknown): tool is RunnableToolLike {\n return (\n tool !== undefined &&\n Runnable.isRunnable(tool) &&\n \"lc_name\" in tool.constructor &&\n typeof tool.constructor.lc_name === \"function\" &&\n tool.constructor.lc_name() === \"RunnableToolLike\"\n );\n}\n\n/**\n * Confirm whether or not the tool contains the necessary properties to be considered a `StructuredToolParams`.\n *\n * @param {unknown | undefined} tool The object to check if it is a `StructuredToolParams`.\n * @returns {tool is StructuredToolParams} Whether the inputted object is a `StructuredToolParams`.\n */\nexport function isStructuredToolParams(\n tool?: unknown\n): tool is StructuredToolParams {\n return (\n !!tool &&\n typeof tool === \"object\" &&\n \"name\" in tool &&\n \"schema\" in tool &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (isInteropZodSchema(tool.schema as Record<string, any>) ||\n (tool.schema != null &&\n typeof tool.schema === \"object\" &&\n \"type\" in tool.schema &&\n typeof tool.schema.type === \"string\" &&\n [\"null\", \"boolean\", \"object\", \"array\", \"number\", \"string\"].includes(\n tool.schema.type\n )))\n );\n}\n\n/**\n * Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams.\n * It returns `is StructuredToolParams` since that is the most minimal interface of the three,\n * while still containing the necessary properties to be passed to a LLM for tool calling.\n *\n * @param {unknown | undefined} tool The tool to check if it is a LangChain tool.\n * @returns {tool is StructuredToolParams} Whether the inputted tool is a LangChain tool.\n */\nexport function isLangChainTool(tool?: unknown): tool is StructuredToolParams {\n return (\n isStructuredToolParams(tool) ||\n isRunnableToolLike(tool) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n isStructuredTool(tool as any)\n );\n}\n\n/**\n * Runtime context automatically injected into tools.\n *\n * When a tool function has a parameter named `tool_runtime` with type hint\n * `ToolRuntime`, the tool execution system will automatically inject an instance\n * containing:\n *\n * - `state`: The current graph state\n * - `toolCallId`: The ID of the current tool call\n * - `config`: `RunnableConfig` for the current execution\n * - `context`: Runtime context\n * - `store`: `BaseStore` instance for persistent storage\n * - `writer`: Stream writer for streaming output\n *\n * No `Annotated` wrapper is needed - just use `runtime: ToolRuntime`\n * as a parameter.\n *\n * @example\n * ```typescript\n * import { tool, type ToolRuntime } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const stateSchema = z.object({\n * messages: z.array(z.any()),\n * userId: z.string().optional(),\n * });\n *\n * const greet = tool(\n * async ({ name }, runtime: ToolRuntime<typeof stateSchema>) => {\n * // Access state\n * const messages = runtime.state.messages;\n *\n * // Access tool_call_id\n * console.log(`Tool call ID: ${runtime.toolCallId}`);\n *\n * // Access config\n * console.log(`Run ID: ${runtime.config.runId}`);\n *\n * // Access runtime context\n * const userId = runtime.context?.userId;\n *\n * // Access store\n * await runtime.store?.mset([[\"key\", \"value\"]]);\n *\n * // Stream output\n * runtime.writer?.(\"Processing...\");\n *\n * return `Hello! User ID: ${runtime.state.userId || \"unknown\"} ${name}`;\n * },\n * {\n * name: \"greet\",\n * description: \"Use this to greet the user once you found their info.\",\n * schema: z.object({ name: z.string() }),\n * stateSchema,\n * }\n * );\n *\n * const agent = createAgent({\n * model,\n * tools: [greet],\n * stateSchema,\n * contextSchema,\n * });\n * ```\n *\n * @template StateT - The type of the state schema (inferred from stateSchema)\n * @template ContextT - The type of the context schema (inferred from contextSchema)\n */\nexport type ToolRuntime<\n TState = unknown,\n TContext = unknown,\n> = RunnableConfig & {\n /**\n * The current graph state.\n */\n state: TState extends InteropZodObject\n ? InferInteropZodOutput<TState>\n : TState extends Record<string, unknown>\n ? TState\n : unknown;\n /**\n * The ID of the current tool call.\n */\n toolCallId: string;\n /**\n * The current tool call.\n */\n toolCall?: ToolCall;\n /**\n * RunnableConfig for the current execution.\n */\n config: ToolRunnableConfig;\n /**\n * Runtime context (from langgraph `Runtime`).\n */\n context: TContext extends InteropZodObject\n ? InferInteropZodOutput<TContext>\n : TContext extends Record<string, unknown>\n ? TContext\n : unknown;\n /**\n * BaseStore instance for persistent storage (from langgraph `Runtime`).\n */\n store: BaseStore<string, unknown> | null;\n /**\n * Stream writer for streaming output (from langgraph `Runtime`).\n */\n writer: ((chunk: unknown) => void) | null;\n};\n"],"mappings":";;;;;;;;;;AA6XA,SAAgB,iBACdA,MACiC;AACjC,QACE,SAAS,UACT,MAAM,QAAS,KAAiC,aAAa;AAEhE;;;;;;;AAQD,SAAgB,mBAAmBC,MAA0C;AAC3E,QACE,SAAS,UACT,SAAS,WAAW,KAAK,IACzB,aAAa,KAAK,eAClB,OAAO,KAAK,YAAY,YAAY,cACpC,KAAK,YAAY,SAAS,KAAK;AAElC;;;;;;;AAQD,SAAgB,uBACdA,MAC8B;AAC9B,QACE,CAAC,CAAC,QACF,OAAO,SAAS,YAChB,UAAU,QACV,YAAY,SAEX,mBAAmB,KAAK,OAA8B,IACpD,KAAK,UAAU,QACd,OAAO,KAAK,WAAW,YACvB,UAAU,KAAK,UACf,OAAO,KAAK,OAAO,SAAS,YAC5B;EAAC;EAAQ;EAAW;EAAU;EAAS;EAAU;CAAS,EAAC,SACzD,KAAK,OAAO,KACb;AAER;;;;;;;;;AAUD,SAAgB,gBAAgBA,MAA8C;AAC5E,QACE,uBAAuB,KAAK,IAC5B,mBAAmB,KAAK,IAExB,iBAAiB,KAAY;AAEhC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event_stream.cjs","names":["handler: BaseCallbackHandler","BaseTracer","fields?: EventStreamCallbackHandlerInput","IterableReadableStream","_run: Run","run: RunInfo","runId: string","outputStream: AsyncGenerator<T>","eventType: string","data: unknown","GenerationChunk","tappedPromiseResolver: (() => void) | undefined","event: StreamEvent","payload: StreamEvent","run: Run","token: string","kwargs?: { chunk: any }","AIMessageChunk","eventName: string","generations: ChatGeneration[][] | Generation[][] | undefined","output: BaseMessage | Record<string, any> | undefined","runInfo: RunInfo","eventData: StreamEventData","data: StreamEventData","data: any"],"sources":["../../src/tracers/event_stream.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport { ChatGeneration, Generation, GenerationChunk } from \"../outputs.js\";\nimport { BaseMessage } from \"../messages/base.js\";\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input?: any;\n\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n output?: any;\n\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunk?: any;\n\n /**\n * Error message if the runnable that generated the event failed.\n * This field will only be present if the runnable failed.\n */\n error?: string;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\ntype RunInfo = {\n name: string;\n tags: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n runType: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: Record<string, any>;\n};\n\nexport interface EventStreamCallbackHandlerInput\n extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\n\nfunction assignName({\n name,\n serialized,\n}: {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialized?: Record<string, any>;\n}): string {\n if (name !== undefined) {\n return name;\n }\n if (serialized?.name !== undefined) {\n return serialized.name;\n } else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {\n return serialized.id[serialized.id.length - 1];\n }\n return \"Unnamed\";\n}\n\nexport const isStreamEventsHandler = (\n handler: BaseCallbackHandler\n): handler is EventStreamCallbackHandler =>\n handler.name === \"event_stream_tracer\";\n\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport class EventStreamCallbackHandler\n extends BaseTracer\n implements CallbackHandlerPrefersStreaming\n{\n protected autoClose = true;\n\n protected includeNames?: string[];\n\n protected includeTypes?: string[];\n\n protected includeTags?: string[];\n\n protected excludeNames?: string[];\n\n protected excludeTypes?: string[];\n\n protected excludeTags?: string[];\n\n private runInfoMap: Map<string, RunInfo> = new Map();\n\n private tappedPromises: Map<string, Promise<void>> = new Map();\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<StreamEvent>;\n\n private readableStreamClosed = false;\n\n name = \"event_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: EventStreamCallbackHandlerInput) {\n super({ _awaitHandler: true, ...fields });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this.transformStream = new TransformStream({\n flush: () => {\n this.readableStreamClosed = true;\n },\n });\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = IterableReadableStream.fromReadableStream(\n this.transformStream.readable\n );\n }\n\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n\n protected async persistRun(_run: Run): Promise<void> {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n\n _includeRun(run: RunInfo): boolean {\n const runTags = run.tags ?? [];\n let include =\n this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.runType);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.runType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n\n async *tapOutputIterable<T>(\n runId: string,\n outputStream: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n const firstChunk = await outputStream.next();\n if (firstChunk.done) {\n return;\n }\n const runInfo = this.runInfoMap.get(runId);\n // Run has finished, don't issue any stream events.\n // An example of this is for runnables that use the default\n // implementation of .stream(), which delegates to .invoke()\n // and calls .onChainEnd() before passing it to the iterator.\n if (runInfo === undefined) {\n yield firstChunk.value;\n return;\n }\n // Match format from handlers below\n function _formatOutputChunk(eventType: string, data: unknown) {\n if (eventType === \"llm\" && typeof data === \"string\") {\n return new GenerationChunk({ text: data });\n }\n return data;\n }\n let tappedPromise = this.tappedPromises.get(runId);\n // if we are the first to tap, issue stream events\n if (tappedPromise === undefined) {\n let tappedPromiseResolver: (() => void) | undefined;\n tappedPromise = new Promise((resolve) => {\n tappedPromiseResolver = resolve;\n });\n this.tappedPromises.set(runId, tappedPromise);\n try {\n const event: StreamEvent = {\n event: `on_${runInfo.runType}_stream`,\n run_id: runId,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data: {},\n };\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, firstChunk.value),\n },\n },\n runInfo\n );\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n // Don't yield tool and retriever stream events\n if (runInfo.runType !== \"tool\" && runInfo.runType !== \"retriever\") {\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, chunk),\n },\n },\n runInfo\n );\n }\n yield chunk;\n }\n } finally {\n tappedPromiseResolver?.();\n // Don't delete from the promises map to keep track of which runs have been tapped.\n }\n } else {\n // otherwise just pass through\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n yield chunk;\n }\n }\n }\n\n async send(payload: StreamEvent, run: RunInfo) {\n if (this.readableStreamClosed) return;\n if (this._includeRun(run)) {\n await this.writer.write(payload);\n }\n }\n\n async sendEndEvent(payload: StreamEvent, run: RunInfo) {\n const tappedPromise = this.tappedPromises.get(payload.run_id);\n if (tappedPromise !== undefined) {\n // eslint-disable-next-line no-void\n void tappedPromise.then(() => {\n // eslint-disable-next-line no-void\n void this.send(payload, run);\n });\n } else {\n await this.send(payload, run);\n }\n }\n\n async onLLMStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.inputs.messages !== undefined ? \"chat_model\" : \"llm\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: run.inputs,\n };\n this.runInfoMap.set(run.id, runInfo);\n const eventName = `on_${runType}_start`;\n await this.send(\n {\n event: eventName,\n data: {\n input: run.inputs,\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kwargs?: { chunk: any }\n ): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n let chunk;\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n }\n // Top-level streaming events are covered by tapOutputIterable\n if (this.runInfoMap.size === 1) {\n return;\n }\n if (runInfo.runType === \"chat_model\") {\n eventName = \"on_chat_model_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` });\n } else {\n chunk = kwargs.chunk.message;\n }\n } else if (runInfo.runType === \"llm\") {\n eventName = \"on_llm_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new GenerationChunk({ text: token });\n } else {\n chunk = kwargs.chunk;\n }\n } else {\n throw new Error(`Unexpected run type ${runInfo.runType}`);\n }\n await this.send(\n {\n event: eventName,\n data: {\n chunk,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onLLMEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n let eventName: string;\n if (runInfo === undefined) {\n throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n }\n const generations: ChatGeneration[][] | Generation[][] | undefined =\n run.outputs?.generations;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let output: BaseMessage | Record<string, any> | undefined;\n if (runInfo.runType === \"chat_model\") {\n for (const generation of generations ?? []) {\n if (output !== undefined) {\n break;\n }\n output = (generation[0] as ChatGeneration | undefined)?.message;\n }\n eventName = \"on_chat_model_end\";\n } else if (runInfo.runType === \"llm\") {\n output = {\n generations: generations?.map((generation) => {\n return generation.map((chunk) => {\n return {\n text: chunk.text,\n generationInfo: chunk.generationInfo,\n };\n });\n }),\n llmOutput: run.outputs?.llmOutput ?? {},\n };\n eventName = \"on_llm_end\";\n } else {\n throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onChainStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.run_type ?? \"chain\";\n const runInfo: RunInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: run.run_type,\n };\n let eventData: StreamEventData = {};\n // Workaround Runnable core code not sending input when transform streaming.\n if (run.inputs.input === \"\" && Object.keys(run.inputs).length === 1) {\n eventData = {};\n runInfo.inputs = {};\n } else if (run.inputs.input !== undefined) {\n eventData.input = run.inputs.input;\n runInfo.inputs = run.inputs.input;\n } else {\n eventData.input = run.inputs;\n runInfo.inputs = run.inputs;\n }\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: `on_${runType}_start`,\n data: eventData,\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onChainEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n }\n const eventName = `on_${run.run_type}_end`;\n const inputs = run.inputs ?? runInfo.inputs ?? {};\n const outputs = run.outputs?.output ?? run.outputs;\n const data: StreamEventData = {\n output: outputs,\n input: inputs,\n };\n if (inputs.input && Object.keys(inputs).length === 1) {\n data.input = inputs.input;\n runInfo.inputs = inputs.input;\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data,\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: \"tool\",\n inputs: run.inputs ?? {},\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_tool_start\",\n data: {\n input: run.inputs ?? {},\n },\n name: runName,\n run_id: run.id,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n const output =\n run.outputs?.output === undefined ? run.outputs : run.outputs.output;\n await this.sendEndEvent(\n {\n event: \"on_tool_end\",\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onToolError(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n\n await this.sendEndEvent(\n {\n event: \"on_tool_error\",\n data: {\n input: runInfo.inputs,\n error: run.error,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onRetrieverStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = \"retriever\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: {\n query: run.inputs.query,\n },\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_retriever_start\",\n data: {\n input: {\n query: run.inputs.query,\n },\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onRetrieverEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n }\n await this.sendEndEvent(\n {\n event: \"on_retriever_end\",\n data: {\n output: run.outputs?.documents ?? run.outputs,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async handleCustomEvent(eventName: string, data: any, runId: string) {\n const runInfo = this.runInfoMap.get(runId);\n if (runInfo === undefined) {\n throw new Error(\n `handleCustomEvent: Run ID ${runId} not found in run map.`\n );\n }\n await this.send(\n {\n event: \"on_custom_event\",\n run_id: runId,\n name: eventName,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data,\n },\n runInfo\n );\n }\n\n async finish() {\n const pendingPromises = [...this.tappedPromises.values()];\n // eslint-disable-next-line no-void\n void Promise.all(pendingPromises).finally(() => {\n // eslint-disable-next-line no-void\n void this.writer.close();\n });\n }\n}\n"],"mappings":";;;;;;AA2HA,SAAS,WAAW,EAClB,MACA,YAKD,EAAU;AACT,KAAI,SAAS,OACX,QAAO;AAET,KAAI,YAAY,SAAS,OACvB,QAAO,WAAW;UACT,YAAY,OAAO,UAAa,MAAM,QAAQ,YAAY,GAAG,CACtE,QAAO,WAAW,GAAG,WAAW,GAAG,SAAS;AAE9C,QAAO;AACR;AAED,MAAa,wBAAwB,CACnCA,YAEA,QAAQ,SAAS;;;;;;;AAQnB,IAAa,6BAAb,cACUC,gCAEV;CACE,AAAU,YAAY;CAEtB,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAQ,6BAAmC,IAAI;CAE/C,AAAQ,iCAA6C,IAAI;CAEzD,AAAU;CAEV,AAAO;CAEP,AAAO;CAEP,AAAQ,uBAAuB;CAE/B,OAAO;CAEP,sBAAsB;CAEtB,YAAYC,QAA0C;EACpD,MAAM;GAAE,eAAe;GAAM,GAAG;EAAQ,EAAC;EACzC,KAAK,YAAY,QAAQ,aAAa;EACtC,KAAK,eAAe,QAAQ;EAC5B,KAAK,eAAe,QAAQ;EAC5B,KAAK,cAAc,QAAQ;EAC3B,KAAK,eAAe,QAAQ;EAC5B,KAAK,eAAe,QAAQ;EAC5B,KAAK,cAAc,QAAQ;EAC3B,KAAK,kBAAkB,IAAI,gBAAgB,EACzC,OAAO,MAAM;GACX,KAAK,uBAAuB;EAC7B,EACF;EACD,KAAK,SAAS,KAAK,gBAAgB,SAAS,WAAW;EACvD,KAAK,gBAAgBC,4CAAuB,mBAC1C,KAAK,gBAAgB,SACtB;CACF;CAED,CAAC,OAAO,iBAAiB;AACvB,SAAO,KAAK;CACb;CAED,MAAgB,WAAWC,MAA0B,CAGpD;CAED,YAAYC,KAAuB;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AAI,IAAI,IAAI,QAAQ;EACpC,MAAM,KAAK,KACT;GACE,OAAO;GACP,MAAM,EACJ,OAAO,EACL,OAAO,IAAI,OAAO,MACnB,EACF;GACD,MAAM;GACN,MAAM,IAAI,QAAQ,CAAE;GACpB,QAAQ,IAAI;GACZ,UAAU,IAAI,OAAO,YAAY,CAAE;EACpC,GACD,QACD;CACF;CAED,MAAM,eAAeA,KAAyB;EAC5C,MAAM,UAAU,KAAK,WAAW,IAAI,IAAI,GAAG;EAC3C,KAAK,WAAW,OAAO,IAAI,GAAG;AAC9B,MAAI,YAAY,OACd,OAAM,IAAI,MAAM,CAAC,uBAAuB,EAAE,IAAI,GAAG,sBAAsB,CAAC;EAE1E,MAAM,KAAK,aACT;GACE,OAAO;GACP,MAAM;IACJ,QAAQ,IAAI,SAAS,aAAa,IAAI;IACtC,OAAO,QAAQ;GAChB;GACD,QAAQ,IAAI;GACZ,MAAM,QAAQ;GACd,MAAM,QAAQ;GACd,UAAU,QAAQ;EACnB,GACD,QACD;CACF;CAGD,MAAM,kBAAkBI,WAAmBM,MAAWlB,OAAe;EACnE,MAAM,UAAU,KAAK,WAAW,IAAI,MAAM;AAC1C,MAAI,YAAY,OACd,OAAM,IAAI,MACR,CAAC,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;EAG9D,MAAM,KAAK,KACT;GACE,OAAO;GACP,QAAQ;GACR,MAAM;GACN,MAAM,QAAQ;GACd,UAAU,QAAQ;GAClB;EACD,GACD,QACD;CACF;CAED,MAAM,SAAS;EACb,MAAM,kBAAkB,CAAC,GAAG,KAAK,eAAe,QAAQ,AAAC;EAEpD,QAAQ,IAAI,gBAAgB,CAAC,QAAQ,MAAM;GAEzC,KAAK,OAAO,OAAO;EACzB,EAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"event_stream.cjs","names":["handler: BaseCallbackHandler","BaseTracer","fields?: EventStreamCallbackHandlerInput","IterableReadableStream","_run: Run","run: RunInfo","runId: string","outputStream: AsyncGenerator<T>","eventType: string","data: unknown","GenerationChunk","tappedPromiseResolver: (() => void) | undefined","event: StreamEvent","payload: StreamEvent","run: Run","token: string","kwargs?: { chunk: any }","AIMessageChunk","eventName: string","generations: ChatGeneration[][] | Generation[][] | undefined","output: BaseMessage | Record<string, any> | undefined","runInfo: RunInfo","eventData: StreamEventData","data: StreamEventData","data: any"],"sources":["../../src/tracers/event_stream.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport { ChatGeneration, Generation, GenerationChunk } from \"../outputs.js\";\nimport { BaseMessage } from \"../messages/base.js\";\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input?: any;\n\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n output?: any;\n\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunk?: any;\n\n /**\n * Error message if the runnable that generated the event failed.\n * This field will only be present if the runnable failed.\n */\n error?: string;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\ntype RunInfo = {\n name: string;\n tags: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n runType: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: Record<string, any>;\n};\n\nexport interface EventStreamCallbackHandlerInput extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\n\nfunction assignName({\n name,\n serialized,\n}: {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialized?: Record<string, any>;\n}): string {\n if (name !== undefined) {\n return name;\n }\n if (serialized?.name !== undefined) {\n return serialized.name;\n } else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {\n return serialized.id[serialized.id.length - 1];\n }\n return \"Unnamed\";\n}\n\nexport const isStreamEventsHandler = (\n handler: BaseCallbackHandler\n): handler is EventStreamCallbackHandler =>\n handler.name === \"event_stream_tracer\";\n\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport class EventStreamCallbackHandler\n extends BaseTracer\n implements CallbackHandlerPrefersStreaming\n{\n protected autoClose = true;\n\n protected includeNames?: string[];\n\n protected includeTypes?: string[];\n\n protected includeTags?: string[];\n\n protected excludeNames?: string[];\n\n protected excludeTypes?: string[];\n\n protected excludeTags?: string[];\n\n private runInfoMap: Map<string, RunInfo> = new Map();\n\n private tappedPromises: Map<string, Promise<void>> = new Map();\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<StreamEvent>;\n\n private readableStreamClosed = false;\n\n name = \"event_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: EventStreamCallbackHandlerInput) {\n super({ _awaitHandler: true, ...fields });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this.transformStream = new TransformStream({\n flush: () => {\n this.readableStreamClosed = true;\n },\n });\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = IterableReadableStream.fromReadableStream(\n this.transformStream.readable\n );\n }\n\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n\n protected async persistRun(_run: Run): Promise<void> {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n\n _includeRun(run: RunInfo): boolean {\n const runTags = run.tags ?? [];\n let include =\n this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.runType);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.runType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n\n async *tapOutputIterable<T>(\n runId: string,\n outputStream: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n const firstChunk = await outputStream.next();\n if (firstChunk.done) {\n return;\n }\n const runInfo = this.runInfoMap.get(runId);\n // Run has finished, don't issue any stream events.\n // An example of this is for runnables that use the default\n // implementation of .stream(), which delegates to .invoke()\n // and calls .onChainEnd() before passing it to the iterator.\n if (runInfo === undefined) {\n yield firstChunk.value;\n return;\n }\n // Match format from handlers below\n function _formatOutputChunk(eventType: string, data: unknown) {\n if (eventType === \"llm\" && typeof data === \"string\") {\n return new GenerationChunk({ text: data });\n }\n return data;\n }\n let tappedPromise = this.tappedPromises.get(runId);\n // if we are the first to tap, issue stream events\n if (tappedPromise === undefined) {\n let tappedPromiseResolver: (() => void) | undefined;\n tappedPromise = new Promise((resolve) => {\n tappedPromiseResolver = resolve;\n });\n this.tappedPromises.set(runId, tappedPromise);\n try {\n const event: StreamEvent = {\n event: `on_${runInfo.runType}_stream`,\n run_id: runId,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data: {},\n };\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, firstChunk.value),\n },\n },\n runInfo\n );\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n // Don't yield tool and retriever stream events\n if (runInfo.runType !== \"tool\" && runInfo.runType !== \"retriever\") {\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, chunk),\n },\n },\n runInfo\n );\n }\n yield chunk;\n }\n } finally {\n tappedPromiseResolver?.();\n // Don't delete from the promises map to keep track of which runs have been tapped.\n }\n } else {\n // otherwise just pass through\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n yield chunk;\n }\n }\n }\n\n async send(payload: StreamEvent, run: RunInfo) {\n if (this.readableStreamClosed) return;\n if (this._includeRun(run)) {\n await this.writer.write(payload);\n }\n }\n\n async sendEndEvent(payload: StreamEvent, run: RunInfo) {\n const tappedPromise = this.tappedPromises.get(payload.run_id);\n if (tappedPromise !== undefined) {\n // eslint-disable-next-line no-void\n void tappedPromise.then(() => {\n // eslint-disable-next-line no-void\n void this.send(payload, run);\n });\n } else {\n await this.send(payload, run);\n }\n }\n\n async onLLMStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.inputs.messages !== undefined ? \"chat_model\" : \"llm\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: run.inputs,\n };\n this.runInfoMap.set(run.id, runInfo);\n const eventName = `on_${runType}_start`;\n await this.send(\n {\n event: eventName,\n data: {\n input: run.inputs,\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kwargs?: { chunk: any }\n ): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n let chunk;\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n }\n // Top-level streaming events are covered by tapOutputIterable\n if (this.runInfoMap.size === 1) {\n return;\n }\n if (runInfo.runType === \"chat_model\") {\n eventName = \"on_chat_model_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` });\n } else {\n chunk = kwargs.chunk.message;\n }\n } else if (runInfo.runType === \"llm\") {\n eventName = \"on_llm_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new GenerationChunk({ text: token });\n } else {\n chunk = kwargs.chunk;\n }\n } else {\n throw new Error(`Unexpected run type ${runInfo.runType}`);\n }\n await this.send(\n {\n event: eventName,\n data: {\n chunk,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onLLMEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n let eventName: string;\n if (runInfo === undefined) {\n throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n }\n const generations: ChatGeneration[][] | Generation[][] | undefined =\n run.outputs?.generations;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let output: BaseMessage | Record<string, any> | undefined;\n if (runInfo.runType === \"chat_model\") {\n for (const generation of generations ?? []) {\n if (output !== undefined) {\n break;\n }\n output = (generation[0] as ChatGeneration | undefined)?.message;\n }\n eventName = \"on_chat_model_end\";\n } else if (runInfo.runType === \"llm\") {\n output = {\n generations: generations?.map((generation) => {\n return generation.map((chunk) => {\n return {\n text: chunk.text,\n generationInfo: chunk.generationInfo,\n };\n });\n }),\n llmOutput: run.outputs?.llmOutput ?? {},\n };\n eventName = \"on_llm_end\";\n } else {\n throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onChainStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.run_type ?? \"chain\";\n const runInfo: RunInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: run.run_type,\n };\n let eventData: StreamEventData = {};\n // Workaround Runnable core code not sending input when transform streaming.\n if (run.inputs.input === \"\" && Object.keys(run.inputs).length === 1) {\n eventData = {};\n runInfo.inputs = {};\n } else if (run.inputs.input !== undefined) {\n eventData.input = run.inputs.input;\n runInfo.inputs = run.inputs.input;\n } else {\n eventData.input = run.inputs;\n runInfo.inputs = run.inputs;\n }\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: `on_${runType}_start`,\n data: eventData,\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onChainEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n }\n const eventName = `on_${run.run_type}_end`;\n const inputs = run.inputs ?? runInfo.inputs ?? {};\n const outputs = run.outputs?.output ?? run.outputs;\n const data: StreamEventData = {\n output: outputs,\n input: inputs,\n };\n if (inputs.input && Object.keys(inputs).length === 1) {\n data.input = inputs.input;\n runInfo.inputs = inputs.input;\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data,\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: \"tool\",\n inputs: run.inputs ?? {},\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_tool_start\",\n data: {\n input: run.inputs ?? {},\n },\n name: runName,\n run_id: run.id,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n const output =\n run.outputs?.output === undefined ? run.outputs : run.outputs.output;\n await this.sendEndEvent(\n {\n event: \"on_tool_end\",\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onToolError(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n\n await this.sendEndEvent(\n {\n event: \"on_tool_error\",\n data: {\n input: runInfo.inputs,\n error: run.error,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onRetrieverStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = \"retriever\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: {\n query: run.inputs.query,\n },\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_retriever_start\",\n data: {\n input: {\n query: run.inputs.query,\n },\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onRetrieverEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n }\n await this.sendEndEvent(\n {\n event: \"on_retriever_end\",\n data: {\n output: run.outputs?.documents ?? run.outputs,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async handleCustomEvent(eventName: string, data: any, runId: string) {\n const runInfo = this.runInfoMap.get(runId);\n if (runInfo === undefined) {\n throw new Error(\n `handleCustomEvent: Run ID ${runId} not found in run map.`\n );\n }\n await this.send(\n {\n event: \"on_custom_event\",\n run_id: runId,\n name: eventName,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data,\n },\n runInfo\n );\n }\n\n async finish() {\n const pendingPromises = [...this.tappedPromises.values()];\n // eslint-disable-next-line no-void\n void Promise.all(pendingPromises).finally(() => {\n // eslint-disable-next-line no-void\n void this.writer.close();\n });\n }\n}\n"],"mappings":";;;;;;AA0HA,SAAS,WAAW,EAClB,MACA,YAKD,EAAU;AACT,KAAI,SAAS,OACX,QAAO;AAET,KAAI,YAAY,SAAS,OACvB,QAAO,WAAW;UACT,YAAY,OAAO,UAAa,MAAM,QAAQ,YAAY,GAAG,CACtE,QAAO,WAAW,GAAG,WAAW,GAAG,SAAS;AAE9C,QAAO;AACR;AAED,MAAa,wBAAwB,CACnCA,YAEA,QAAQ,SAAS;;;;;;;AAQnB,IAAa,6BAAb,cACUC,gCAEV;CACE,AAAU,YAAY;CAEtB,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAQ,6BAAmC,IAAI;CAE/C,AAAQ,iCAA6C,IAAI;CAEzD,AAAU;CAEV,AAAO;CAEP,AAAO;CAEP,AAAQ,uBAAuB;CAE/B,OAAO;CAEP,sBAAsB;CAEtB,YAAYC,QAA0C;EACpD,MAAM;GAAE,eAAe;GAAM,GAAG;EAAQ,EAAC;EACzC,KAAK,YAAY,QAAQ,aAAa;EACtC,KAAK,eAAe,QAAQ;EAC5B,KAAK,eAAe,QAAQ;EAC5B,KAAK,cAAc,QAAQ;EAC3B,KAAK,eAAe,QAAQ;EAC5B,KAAK,eAAe,QAAQ;EAC5B,KAAK,cAAc,QAAQ;EAC3B,KAAK,kBAAkB,IAAI,gBAAgB,EACzC,OAAO,MAAM;GACX,KAAK,uBAAuB;EAC7B,EACF;EACD,KAAK,SAAS,KAAK,gBAAgB,SAAS,WAAW;EACvD,KAAK,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;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event_stream.js","names":["handler: BaseCallbackHandler","fields?: EventStreamCallbackHandlerInput","_run: Run","run: RunInfo","runId: string","outputStream: AsyncGenerator<T>","eventType: string","data: unknown","tappedPromiseResolver: (() => void) | undefined","event: StreamEvent","payload: StreamEvent","run: Run","token: string","kwargs?: { chunk: any }","eventName: string","generations: ChatGeneration[][] | Generation[][] | undefined","output: BaseMessage | Record<string, any> | undefined","runInfo: RunInfo","eventData: StreamEventData","data: StreamEventData","data: any"],"sources":["../../src/tracers/event_stream.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport { ChatGeneration, Generation, GenerationChunk } from \"../outputs.js\";\nimport { BaseMessage } from \"../messages/base.js\";\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input?: any;\n\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n output?: any;\n\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunk?: any;\n\n /**\n * Error message if the runnable that generated the event failed.\n * This field will only be present if the runnable failed.\n */\n error?: string;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\ntype RunInfo = {\n name: string;\n tags: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n runType: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: Record<string, any>;\n};\n\nexport interface EventStreamCallbackHandlerInput\n extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\n\nfunction assignName({\n name,\n serialized,\n}: {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialized?: Record<string, any>;\n}): string {\n if (name !== undefined) {\n return name;\n }\n if (serialized?.name !== undefined) {\n return serialized.name;\n } else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {\n return serialized.id[serialized.id.length - 1];\n }\n return \"Unnamed\";\n}\n\nexport const isStreamEventsHandler = (\n handler: BaseCallbackHandler\n): handler is EventStreamCallbackHandler =>\n handler.name === \"event_stream_tracer\";\n\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport class EventStreamCallbackHandler\n extends BaseTracer\n implements CallbackHandlerPrefersStreaming\n{\n protected autoClose = true;\n\n protected includeNames?: string[];\n\n protected includeTypes?: string[];\n\n protected includeTags?: string[];\n\n protected excludeNames?: string[];\n\n protected excludeTypes?: string[];\n\n protected excludeTags?: string[];\n\n private runInfoMap: Map<string, RunInfo> = new Map();\n\n private tappedPromises: Map<string, Promise<void>> = new Map();\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<StreamEvent>;\n\n private readableStreamClosed = false;\n\n name = \"event_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: EventStreamCallbackHandlerInput) {\n super({ _awaitHandler: true, ...fields });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this.transformStream = new TransformStream({\n flush: () => {\n this.readableStreamClosed = true;\n },\n });\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = IterableReadableStream.fromReadableStream(\n this.transformStream.readable\n );\n }\n\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n\n protected async persistRun(_run: Run): Promise<void> {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n\n _includeRun(run: RunInfo): boolean {\n const runTags = run.tags ?? [];\n let include =\n this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.runType);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.runType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n\n async *tapOutputIterable<T>(\n runId: string,\n outputStream: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n const firstChunk = await outputStream.next();\n if (firstChunk.done) {\n return;\n }\n const runInfo = this.runInfoMap.get(runId);\n // Run has finished, don't issue any stream events.\n // An example of this is for runnables that use the default\n // implementation of .stream(), which delegates to .invoke()\n // and calls .onChainEnd() before passing it to the iterator.\n if (runInfo === undefined) {\n yield firstChunk.value;\n return;\n }\n // Match format from handlers below\n function _formatOutputChunk(eventType: string, data: unknown) {\n if (eventType === \"llm\" && typeof data === \"string\") {\n return new GenerationChunk({ text: data });\n }\n return data;\n }\n let tappedPromise = this.tappedPromises.get(runId);\n // if we are the first to tap, issue stream events\n if (tappedPromise === undefined) {\n let tappedPromiseResolver: (() => void) | undefined;\n tappedPromise = new Promise((resolve) => {\n tappedPromiseResolver = resolve;\n });\n this.tappedPromises.set(runId, tappedPromise);\n try {\n const event: StreamEvent = {\n event: `on_${runInfo.runType}_stream`,\n run_id: runId,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data: {},\n };\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, firstChunk.value),\n },\n },\n runInfo\n );\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n // Don't yield tool and retriever stream events\n if (runInfo.runType !== \"tool\" && runInfo.runType !== \"retriever\") {\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, chunk),\n },\n },\n runInfo\n );\n }\n yield chunk;\n }\n } finally {\n tappedPromiseResolver?.();\n // Don't delete from the promises map to keep track of which runs have been tapped.\n }\n } else {\n // otherwise just pass through\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n yield chunk;\n }\n }\n }\n\n async send(payload: StreamEvent, run: RunInfo) {\n if (this.readableStreamClosed) return;\n if (this._includeRun(run)) {\n await this.writer.write(payload);\n }\n }\n\n async sendEndEvent(payload: StreamEvent, run: RunInfo) {\n const tappedPromise = this.tappedPromises.get(payload.run_id);\n if (tappedPromise !== undefined) {\n // eslint-disable-next-line no-void\n void tappedPromise.then(() => {\n // eslint-disable-next-line no-void\n void this.send(payload, run);\n });\n } else {\n await this.send(payload, run);\n }\n }\n\n async onLLMStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.inputs.messages !== undefined ? \"chat_model\" : \"llm\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: run.inputs,\n };\n this.runInfoMap.set(run.id, runInfo);\n const eventName = `on_${runType}_start`;\n await this.send(\n {\n event: eventName,\n data: {\n input: run.inputs,\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kwargs?: { chunk: any }\n ): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n let chunk;\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n }\n // Top-level streaming events are covered by tapOutputIterable\n if (this.runInfoMap.size === 1) {\n return;\n }\n if (runInfo.runType === \"chat_model\") {\n eventName = \"on_chat_model_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` });\n } else {\n chunk = kwargs.chunk.message;\n }\n } else if (runInfo.runType === \"llm\") {\n eventName = \"on_llm_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new GenerationChunk({ text: token });\n } else {\n chunk = kwargs.chunk;\n }\n } else {\n throw new Error(`Unexpected run type ${runInfo.runType}`);\n }\n await this.send(\n {\n event: eventName,\n data: {\n chunk,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onLLMEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n let eventName: string;\n if (runInfo === undefined) {\n throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n }\n const generations: ChatGeneration[][] | Generation[][] | undefined =\n run.outputs?.generations;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let output: BaseMessage | Record<string, any> | undefined;\n if (runInfo.runType === \"chat_model\") {\n for (const generation of generations ?? []) {\n if (output !== undefined) {\n break;\n }\n output = (generation[0] as ChatGeneration | undefined)?.message;\n }\n eventName = \"on_chat_model_end\";\n } else if (runInfo.runType === \"llm\") {\n output = {\n generations: generations?.map((generation) => {\n return generation.map((chunk) => {\n return {\n text: chunk.text,\n generationInfo: chunk.generationInfo,\n };\n });\n }),\n llmOutput: run.outputs?.llmOutput ?? {},\n };\n eventName = \"on_llm_end\";\n } else {\n throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onChainStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.run_type ?? \"chain\";\n const runInfo: RunInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: run.run_type,\n };\n let eventData: StreamEventData = {};\n // Workaround Runnable core code not sending input when transform streaming.\n if (run.inputs.input === \"\" && Object.keys(run.inputs).length === 1) {\n eventData = {};\n runInfo.inputs = {};\n } else if (run.inputs.input !== undefined) {\n eventData.input = run.inputs.input;\n runInfo.inputs = run.inputs.input;\n } else {\n eventData.input = run.inputs;\n runInfo.inputs = run.inputs;\n }\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: `on_${runType}_start`,\n data: eventData,\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onChainEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n }\n const eventName = `on_${run.run_type}_end`;\n const inputs = run.inputs ?? runInfo.inputs ?? {};\n const outputs = run.outputs?.output ?? run.outputs;\n const data: StreamEventData = {\n output: outputs,\n input: inputs,\n };\n if (inputs.input && Object.keys(inputs).length === 1) {\n data.input = inputs.input;\n runInfo.inputs = inputs.input;\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data,\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: \"tool\",\n inputs: run.inputs ?? {},\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_tool_start\",\n data: {\n input: run.inputs ?? {},\n },\n name: runName,\n run_id: run.id,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n const output =\n run.outputs?.output === undefined ? run.outputs : run.outputs.output;\n await this.sendEndEvent(\n {\n event: \"on_tool_end\",\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onToolError(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n\n await this.sendEndEvent(\n {\n event: \"on_tool_error\",\n data: {\n input: runInfo.inputs,\n error: run.error,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onRetrieverStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = \"retriever\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: {\n query: run.inputs.query,\n },\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_retriever_start\",\n data: {\n input: {\n query: run.inputs.query,\n },\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onRetrieverEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n }\n await this.sendEndEvent(\n {\n event: \"on_retriever_end\",\n data: {\n output: run.outputs?.documents ?? run.outputs,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async handleCustomEvent(eventName: string, data: any, runId: string) {\n const runInfo = this.runInfoMap.get(runId);\n if (runInfo === undefined) {\n throw new Error(\n `handleCustomEvent: Run ID ${runId} not found in run map.`\n );\n }\n await this.send(\n {\n event: \"on_custom_event\",\n run_id: runId,\n name: eventName,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data,\n },\n runInfo\n );\n }\n\n async finish() {\n const pendingPromises = [...this.tappedPromises.values()];\n // eslint-disable-next-line no-void\n void Promise.all(pendingPromises).finally(() => {\n // eslint-disable-next-line no-void\n void this.writer.close();\n });\n }\n}\n"],"mappings":";;;;;;AA2HA,SAAS,WAAW,EAClB,MACA,YAKD,EAAU;AACT,KAAI,SAAS,OACX,QAAO;AAET,KAAI,YAAY,SAAS,OACvB,QAAO,WAAW;UACT,YAAY,OAAO,UAAa,MAAM,QAAQ,YAAY,GAAG,CACtE,QAAO,WAAW,GAAG,WAAW,GAAG,SAAS;AAE9C,QAAO;AACR;AAED,MAAa,wBAAwB,CACnCA,YAEA,QAAQ,SAAS;;;;;;;AAQnB,IAAa,6BAAb,cACU,WAEV;CACE,AAAU,YAAY;CAEtB,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAQ,6BAAmC,IAAI;CAE/C,AAAQ,iCAA6C,IAAI;CAEzD,AAAU;CAEV,AAAO;CAEP,AAAO;CAEP,AAAQ,uBAAuB;CAE/B,OAAO;CAEP,sBAAsB;CAEtB,YAAYC,QAA0C;EACpD,MAAM;GAAE,eAAe;GAAM,GAAG;EAAQ,EAAC;EACzC,KAAK,YAAY,QAAQ,aAAa;EACtC,KAAK,eAAe,QAAQ;EAC5B,KAAK,eAAe,QAAQ;EAC5B,KAAK,cAAc,QAAQ;EAC3B,KAAK,eAAe,QAAQ;EAC5B,KAAK,eAAe,QAAQ;EAC5B,KAAK,cAAc,QAAQ;EAC3B,K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BAAkB,CAAC,GAAG,KAAK,eAAe,QAAQ,AAAC;EAEpD,QAAQ,IAAI,gBAAgB,CAAC,QAAQ,MAAM;GAEzC,KAAK,OAAO,OAAO;EACzB,EAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"event_stream.js","names":["handler: BaseCallbackHandler","fields?: EventStreamCallbackHandlerInput","_run: Run","run: RunInfo","runId: string","outputStream: AsyncGenerator<T>","eventType: string","data: unknown","tappedPromiseResolver: (() => void) | undefined","event: StreamEvent","payload: StreamEvent","run: Run","token: string","kwargs?: { chunk: any }","eventName: string","generations: ChatGeneration[][] | Generation[][] | undefined","output: BaseMessage | Record<string, any> | undefined","runInfo: RunInfo","eventData: StreamEventData","data: StreamEventData","data: any"],"sources":["../../src/tracers/event_stream.ts"],"sourcesContent":["import { BaseTracer, type Run } from \"./base.js\";\nimport {\n BaseCallbackHandler,\n BaseCallbackHandlerInput,\n CallbackHandlerPrefersStreaming,\n} from \"../callbacks/base.js\";\nimport { IterableReadableStream } from \"../utils/stream.js\";\nimport { AIMessageChunk } from \"../messages/ai.js\";\nimport { ChatGeneration, Generation, GenerationChunk } from \"../outputs.js\";\nimport { BaseMessage } from \"../messages/base.js\";\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input?: any;\n\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n output?: any;\n\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n chunk?: any;\n\n /**\n * Error message if the runnable that generated the event failed.\n * This field will only be present if the runnable failed.\n */\n error?: string;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\ntype RunInfo = {\n name: string;\n tags: string[];\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n metadata: Record<string, any>;\n runType: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inputs?: Record<string, any>;\n};\n\nexport interface EventStreamCallbackHandlerInput extends BaseCallbackHandlerInput {\n autoClose?: boolean;\n includeNames?: string[];\n includeTypes?: string[];\n includeTags?: string[];\n excludeNames?: string[];\n excludeTypes?: string[];\n excludeTags?: string[];\n}\n\nfunction assignName({\n name,\n serialized,\n}: {\n name?: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serialized?: Record<string, any>;\n}): string {\n if (name !== undefined) {\n return name;\n }\n if (serialized?.name !== undefined) {\n return serialized.name;\n } else if (serialized?.id !== undefined && Array.isArray(serialized?.id)) {\n return serialized.id[serialized.id.length - 1];\n }\n return \"Unnamed\";\n}\n\nexport const isStreamEventsHandler = (\n handler: BaseCallbackHandler\n): handler is EventStreamCallbackHandler =>\n handler.name === \"event_stream_tracer\";\n\n/**\n * Class that extends the `BaseTracer` class from the\n * `langchain.callbacks.tracers.base` module. It represents a callback\n * handler that logs the execution of runs and emits `RunLog` instances to a\n * `RunLogStream`.\n */\nexport class EventStreamCallbackHandler\n extends BaseTracer\n implements CallbackHandlerPrefersStreaming\n{\n protected autoClose = true;\n\n protected includeNames?: string[];\n\n protected includeTypes?: string[];\n\n protected includeTags?: string[];\n\n protected excludeNames?: string[];\n\n protected excludeTypes?: string[];\n\n protected excludeTags?: string[];\n\n private runInfoMap: Map<string, RunInfo> = new Map();\n\n private tappedPromises: Map<string, Promise<void>> = new Map();\n\n protected transformStream: TransformStream;\n\n public writer: WritableStreamDefaultWriter;\n\n public receiveStream: IterableReadableStream<StreamEvent>;\n\n private readableStreamClosed = false;\n\n name = \"event_stream_tracer\";\n\n lc_prefer_streaming = true;\n\n constructor(fields?: EventStreamCallbackHandlerInput) {\n super({ _awaitHandler: true, ...fields });\n this.autoClose = fields?.autoClose ?? true;\n this.includeNames = fields?.includeNames;\n this.includeTypes = fields?.includeTypes;\n this.includeTags = fields?.includeTags;\n this.excludeNames = fields?.excludeNames;\n this.excludeTypes = fields?.excludeTypes;\n this.excludeTags = fields?.excludeTags;\n this.transformStream = new TransformStream({\n flush: () => {\n this.readableStreamClosed = true;\n },\n });\n this.writer = this.transformStream.writable.getWriter();\n this.receiveStream = IterableReadableStream.fromReadableStream(\n this.transformStream.readable\n );\n }\n\n [Symbol.asyncIterator]() {\n return this.receiveStream;\n }\n\n protected async persistRun(_run: Run): Promise<void> {\n // This is a legacy method only called once for an entire run tree\n // and is therefore not useful here\n }\n\n _includeRun(run: RunInfo): boolean {\n const runTags = run.tags ?? [];\n let include =\n this.includeNames === undefined &&\n this.includeTags === undefined &&\n this.includeTypes === undefined;\n if (this.includeNames !== undefined) {\n include = include || this.includeNames.includes(run.name);\n }\n if (this.includeTypes !== undefined) {\n include = include || this.includeTypes.includes(run.runType);\n }\n if (this.includeTags !== undefined) {\n include =\n include ||\n runTags.find((tag) => this.includeTags?.includes(tag)) !== undefined;\n }\n if (this.excludeNames !== undefined) {\n include = include && !this.excludeNames.includes(run.name);\n }\n if (this.excludeTypes !== undefined) {\n include = include && !this.excludeTypes.includes(run.runType);\n }\n if (this.excludeTags !== undefined) {\n include =\n include && runTags.every((tag) => !this.excludeTags?.includes(tag));\n }\n return include;\n }\n\n async *tapOutputIterable<T>(\n runId: string,\n outputStream: AsyncGenerator<T>\n ): AsyncGenerator<T> {\n const firstChunk = await outputStream.next();\n if (firstChunk.done) {\n return;\n }\n const runInfo = this.runInfoMap.get(runId);\n // Run has finished, don't issue any stream events.\n // An example of this is for runnables that use the default\n // implementation of .stream(), which delegates to .invoke()\n // and calls .onChainEnd() before passing it to the iterator.\n if (runInfo === undefined) {\n yield firstChunk.value;\n return;\n }\n // Match format from handlers below\n function _formatOutputChunk(eventType: string, data: unknown) {\n if (eventType === \"llm\" && typeof data === \"string\") {\n return new GenerationChunk({ text: data });\n }\n return data;\n }\n let tappedPromise = this.tappedPromises.get(runId);\n // if we are the first to tap, issue stream events\n if (tappedPromise === undefined) {\n let tappedPromiseResolver: (() => void) | undefined;\n tappedPromise = new Promise((resolve) => {\n tappedPromiseResolver = resolve;\n });\n this.tappedPromises.set(runId, tappedPromise);\n try {\n const event: StreamEvent = {\n event: `on_${runInfo.runType}_stream`,\n run_id: runId,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data: {},\n };\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, firstChunk.value),\n },\n },\n runInfo\n );\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n // Don't yield tool and retriever stream events\n if (runInfo.runType !== \"tool\" && runInfo.runType !== \"retriever\") {\n await this.send(\n {\n ...event,\n data: {\n chunk: _formatOutputChunk(runInfo.runType, chunk),\n },\n },\n runInfo\n );\n }\n yield chunk;\n }\n } finally {\n tappedPromiseResolver?.();\n // Don't delete from the promises map to keep track of which runs have been tapped.\n }\n } else {\n // otherwise just pass through\n yield firstChunk.value;\n for await (const chunk of outputStream) {\n yield chunk;\n }\n }\n }\n\n async send(payload: StreamEvent, run: RunInfo) {\n if (this.readableStreamClosed) return;\n if (this._includeRun(run)) {\n await this.writer.write(payload);\n }\n }\n\n async sendEndEvent(payload: StreamEvent, run: RunInfo) {\n const tappedPromise = this.tappedPromises.get(payload.run_id);\n if (tappedPromise !== undefined) {\n // eslint-disable-next-line no-void\n void tappedPromise.then(() => {\n // eslint-disable-next-line no-void\n void this.send(payload, run);\n });\n } else {\n await this.send(payload, run);\n }\n }\n\n async onLLMStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.inputs.messages !== undefined ? \"chat_model\" : \"llm\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: run.inputs,\n };\n this.runInfoMap.set(run.id, runInfo);\n const eventName = `on_${runType}_start`;\n await this.send(\n {\n event: eventName,\n data: {\n input: run.inputs,\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onLLMNewToken(\n run: Run,\n token: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n kwargs?: { chunk: any }\n ): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n let chunk;\n let eventName;\n if (runInfo === undefined) {\n throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`);\n }\n // Top-level streaming events are covered by tapOutputIterable\n if (this.runInfoMap.size === 1) {\n return;\n }\n if (runInfo.runType === \"chat_model\") {\n eventName = \"on_chat_model_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new AIMessageChunk({ content: token, id: `run-${run.id}` });\n } else {\n chunk = kwargs.chunk.message;\n }\n } else if (runInfo.runType === \"llm\") {\n eventName = \"on_llm_stream\";\n if (kwargs?.chunk === undefined) {\n chunk = new GenerationChunk({ text: token });\n } else {\n chunk = kwargs.chunk;\n }\n } else {\n throw new Error(`Unexpected run type ${runInfo.runType}`);\n }\n await this.send(\n {\n event: eventName,\n data: {\n chunk,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onLLMEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n let eventName: string;\n if (runInfo === undefined) {\n throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`);\n }\n const generations: ChatGeneration[][] | Generation[][] | undefined =\n run.outputs?.generations;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let output: BaseMessage | Record<string, any> | undefined;\n if (runInfo.runType === \"chat_model\") {\n for (const generation of generations ?? []) {\n if (output !== undefined) {\n break;\n }\n output = (generation[0] as ChatGeneration | undefined)?.message;\n }\n eventName = \"on_chat_model_end\";\n } else if (runInfo.runType === \"llm\") {\n output = {\n generations: generations?.map((generation) => {\n return generation.map((chunk) => {\n return {\n text: chunk.text,\n generationInfo: chunk.generationInfo,\n };\n });\n }),\n llmOutput: run.outputs?.llmOutput ?? {},\n };\n eventName = \"on_llm_end\";\n } else {\n throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`);\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onChainStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = run.run_type ?? \"chain\";\n const runInfo: RunInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: run.run_type,\n };\n let eventData: StreamEventData = {};\n // Workaround Runnable core code not sending input when transform streaming.\n if (run.inputs.input === \"\" && Object.keys(run.inputs).length === 1) {\n eventData = {};\n runInfo.inputs = {};\n } else if (run.inputs.input !== undefined) {\n eventData.input = run.inputs.input;\n runInfo.inputs = run.inputs.input;\n } else {\n eventData.input = run.inputs;\n runInfo.inputs = run.inputs;\n }\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: `on_${runType}_start`,\n data: eventData,\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onChainEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`);\n }\n const eventName = `on_${run.run_type}_end`;\n const inputs = run.inputs ?? runInfo.inputs ?? {};\n const outputs = run.outputs?.output ?? run.outputs;\n const data: StreamEventData = {\n output: outputs,\n input: inputs,\n };\n if (inputs.input && Object.keys(inputs).length === 1) {\n data.input = inputs.input;\n runInfo.inputs = inputs.input;\n }\n await this.sendEndEvent(\n {\n event: eventName,\n data,\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType: \"tool\",\n inputs: run.inputs ?? {},\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_tool_start\",\n data: {\n input: run.inputs ?? {},\n },\n name: runName,\n run_id: run.id,\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onToolEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n const output =\n run.outputs?.output === undefined ? run.outputs : run.outputs.output;\n await this.sendEndEvent(\n {\n event: \"on_tool_end\",\n data: {\n output,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onToolError(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`);\n }\n if (runInfo.inputs === undefined) {\n throw new Error(\n `onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`\n );\n }\n\n await this.sendEndEvent(\n {\n event: \"on_tool_error\",\n data: {\n input: runInfo.inputs,\n error: run.error,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n async onRetrieverStart(run: Run): Promise<void> {\n const runName = assignName(run);\n const runType = \"retriever\";\n const runInfo = {\n tags: run.tags ?? [],\n metadata: run.extra?.metadata ?? {},\n name: runName,\n runType,\n inputs: {\n query: run.inputs.query,\n },\n };\n this.runInfoMap.set(run.id, runInfo);\n await this.send(\n {\n event: \"on_retriever_start\",\n data: {\n input: {\n query: run.inputs.query,\n },\n },\n name: runName,\n tags: run.tags ?? [],\n run_id: run.id,\n metadata: run.extra?.metadata ?? {},\n },\n runInfo\n );\n }\n\n async onRetrieverEnd(run: Run): Promise<void> {\n const runInfo = this.runInfoMap.get(run.id);\n this.runInfoMap.delete(run.id);\n if (runInfo === undefined) {\n throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`);\n }\n await this.sendEndEvent(\n {\n event: \"on_retriever_end\",\n data: {\n output: run.outputs?.documents ?? run.outputs,\n input: runInfo.inputs,\n },\n run_id: run.id,\n name: runInfo.name,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n },\n runInfo\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async handleCustomEvent(eventName: string, data: any, runId: string) {\n const runInfo = this.runInfoMap.get(runId);\n if (runInfo === undefined) {\n throw new Error(\n `handleCustomEvent: Run ID ${runId} not found in run map.`\n );\n }\n await this.send(\n {\n event: \"on_custom_event\",\n run_id: runId,\n name: eventName,\n tags: runInfo.tags,\n metadata: runInfo.metadata,\n data,\n },\n runInfo\n );\n }\n\n async finish() {\n const pendingPromises = [...this.tappedPromises.values()];\n // eslint-disable-next-line no-void\n void Promise.all(pendingPromises).finally(() => {\n // eslint-disable-next-line no-void\n void this.writer.close();\n });\n }\n}\n"],"mappings":";;;;;;AA0HA,SAAS,WAAW,EAClB,MACA,YAKD,EAAU;AACT,KAAI,SAAS,OACX,QAAO;AAET,KAAI,YAAY,SAAS,OACvB,QAAO,WAAW;UACT,YAAY,OAAO,UAAa,MAAM,QAAQ,YAAY,GAAG,CACtE,QAAO,WAAW,GAAG,WAAW,GAAG,SAAS;AAE9C,QAAO;AACR;AAED,MAAa,wBAAwB,CACnCA,YAEA,QAAQ,SAAS;;;;;;;AAQnB,IAAa,6BAAb,cACU,WAEV;CACE,AAAU,YAAY;CAEtB,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAU;CAEV,AAAQ,6BAAmC,IAAI;CAE/C,AAAQ,iCAA6C,IAAI;CAEzD,AAAU;CAEV,AAAO;CAEP,AAAO;CAEP,AAAQ,uBAAuB;CAE/B,OAAO;CAEP,sBAAsB;CAEtB,YAAYC,QAA0C;EACpD,MAAM;GAAE,eAAe;GAAM,GAAG;EAAQ,EAAC;EACzC,KAAK,YAAY,QAAQ,aAAa;EACtC,KAAK,eAAe,QAAQ;EAC5B,KAAK,eAAe,QAAQ;EAC5B,KA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