@langchain/core 1.1.30 → 1.1.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/language_models/base.cjs +1 -1
  3. package/dist/language_models/base.js +1 -1
  4. package/dist/load/import_map.cjs +2 -0
  5. package/dist/load/import_map.cjs.map +1 -1
  6. package/dist/load/import_map.js +4 -2
  7. package/dist/load/import_map.js.map +1 -1
  8. package/dist/messages/ai.cjs.map +1 -1
  9. package/dist/messages/ai.js.map +1 -1
  10. package/dist/messages/base.cjs +4 -3
  11. package/dist/messages/base.cjs.map +1 -1
  12. package/dist/messages/base.d.cts.map +1 -1
  13. package/dist/messages/base.d.ts.map +1 -1
  14. package/dist/messages/base.js +4 -3
  15. package/dist/messages/base.js.map +1 -1
  16. package/dist/messages/block_translators/google.cjs +16 -1
  17. package/dist/messages/block_translators/google.cjs.map +1 -1
  18. package/dist/messages/block_translators/google.js +16 -1
  19. package/dist/messages/block_translators/google.js.map +1 -1
  20. package/dist/runnables/base.cjs +1 -1
  21. package/dist/runnables/base.cjs.map +1 -1
  22. package/dist/runnables/base.js +2 -2
  23. package/dist/runnables/base.js.map +1 -1
  24. package/dist/{utils/testing → testing}/fake_model_builder.cjs +75 -23
  25. package/dist/testing/fake_model_builder.cjs.map +1 -0
  26. package/dist/testing/fake_model_builder.d.cts +138 -0
  27. package/dist/testing/fake_model_builder.d.cts.map +1 -0
  28. package/dist/testing/fake_model_builder.d.ts +139 -0
  29. package/dist/testing/fake_model_builder.d.ts.map +1 -0
  30. package/dist/{utils/testing → testing}/fake_model_builder.js +75 -24
  31. package/dist/testing/fake_model_builder.js.map +1 -0
  32. package/dist/testing/index.cjs +43 -0
  33. package/dist/testing/index.cjs.map +1 -0
  34. package/dist/testing/index.d.cts +3 -0
  35. package/dist/testing/index.d.ts +3 -0
  36. package/dist/testing/index.js +24 -0
  37. package/dist/testing/index.js.map +1 -0
  38. package/dist/testing/matchers.cjs +213 -0
  39. package/dist/testing/matchers.cjs.map +1 -0
  40. package/dist/testing/matchers.d.cts +94 -0
  41. package/dist/testing/matchers.d.cts.map +1 -0
  42. package/dist/testing/matchers.d.ts +94 -0
  43. package/dist/testing/matchers.d.ts.map +1 -0
  44. package/dist/testing/matchers.js +203 -0
  45. package/dist/testing/matchers.js.map +1 -0
  46. package/dist/tools/index.cjs +4 -0
  47. package/dist/tools/index.cjs.map +1 -1
  48. package/dist/tools/index.d.cts +22 -21
  49. package/dist/tools/index.d.cts.map +1 -1
  50. package/dist/tools/index.d.ts +22 -21
  51. package/dist/tools/index.d.ts.map +1 -1
  52. package/dist/tools/index.js +4 -0
  53. package/dist/tools/index.js.map +1 -1
  54. package/dist/tools/types.cjs.map +1 -1
  55. package/dist/tools/types.d.cts +13 -5
  56. package/dist/tools/types.d.cts.map +1 -1
  57. package/dist/tools/types.d.ts +13 -5
  58. package/dist/tools/types.d.ts.map +1 -1
  59. package/dist/tools/types.js.map +1 -1
  60. package/dist/utils/testing/index.cjs +1 -4
  61. package/dist/utils/testing/index.cjs.map +1 -1
  62. package/dist/utils/testing/index.d.cts +1 -2
  63. package/dist/utils/testing/index.d.ts +1 -2
  64. package/dist/utils/testing/index.js +2 -4
  65. package/dist/utils/testing/index.js.map +1 -1
  66. package/package.json +16 -4
  67. package/dist/utils/testing/fake_model_builder.cjs.map +0 -1
  68. package/dist/utils/testing/fake_model_builder.d.cts +0 -87
  69. package/dist/utils/testing/fake_model_builder.d.cts.map +0 -1
  70. package/dist/utils/testing/fake_model_builder.d.ts +0 -88
  71. package/dist/utils/testing/fake_model_builder.d.ts.map +0 -1
  72. package/dist/utils/testing/fake_model_builder.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../../src/tools/types.ts"],"mappings":";;;;;;;;;;;;;;KA6BY,cAAA;AAAA,KAGA,cAAA;AAAA,KAGA,kBAAA,IAAsB,cAAA;;AANlC;;;;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7C,QAAA,GAAW,QAAA;EApPH;;;EAwPR,MAAA,EAAQ,kBAAA;EA3PE;;;EA+PV,OAAA,EAAS,QAAA,SAAiB,gBAAA,GACtB,qBAAA,CAAsB,QAAA,IACtB,QAAA,SAAiB,MAAA,oBACf,QAAA;EAhQN;;;EAqQA,KAAA,EAAO,SAAA;EApQkC;;;EAwQzC,MAAA,IAAU,KAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"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> | AsyncGenerator<unknown, 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> | AsyncGenerator<unknown, 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,iBACd,MACiC;AACjC,QACE,SAAS,UACT,MAAM,QAAS,KAAiC,aAAa;;;;;;;;AAUjE,SAAgB,mBAAmB,MAA0C;AAC3E,QACE,SAAS,UACT,SAAS,WAAW,KAAK,IACzB,aAAa,KAAK,eAClB,OAAO,KAAK,YAAY,YAAY,cACpC,KAAK,YAAY,SAAS,KAAK;;;;;;;;AAUnC,SAAgB,uBACd,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;EAAS,CAAC,SACzD,KAAK,OAAO,KACb;;;;;;;;;;AAYT,SAAgB,gBAAgB,MAA8C;AAC5E,QACE,uBAAuB,KAAK,IAC5B,mBAAmB,KAAK,IAExB,iBAAiB,KAAY"}
1
+ {"version":3,"file":"types.js","names":[],"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\nexport type ToolEventType = unknown;\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type InferToolEventFromFunc<F> = F extends (\n ...args: any[]\n) => AsyncGenerator<infer Y, any, any>\n ? Y\n : ToolEventType;\n\nexport type InferToolOutputFromFunc<F> = F extends (\n ...args: any[]\n) => AsyncGenerator<any, infer R, any>\n ? R\n : F extends (...args: any[]) => Promise<infer R>\n ? R\n : F extends (...args: any[]) => infer R\n ? R\n : ToolOutputType;\n/* eslint-enable @typescript-eslint/no-explicit-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 *\n * @param ToolOutputT - The return type of the tool.\n * @param ToolEventT - The type of values yielded by the tool when using an async generator.\n */\nexport interface DynamicToolInput<\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\n> extends BaseDynamicToolInput {\n func: (\n input: string,\n runManager?: CallbackManagerForToolRun,\n config?: ToolRunnableConfig\n ) => Promise<ToolOutputT> | AsyncGenerator<ToolEventT, 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 * @param ToolOutputT - The return type of the tool.\n * @param ToolEventT - The type of values yielded by the tool when using an async generator.\n */\nexport interface DynamicStructuredToolInput<\n SchemaT = ToolInputSchemaBase,\n SchemaOutputT = ToolInputSchemaOutputType<SchemaT>,\n ToolOutputT = ToolOutputType,\n ToolEventT = ToolEventType,\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> | AsyncGenerator<ToolEventT, 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":";;;;;;;;;;AAwZA,SAAgB,iBACd,MACiC;AACjC,QACE,SAAS,UACT,MAAM,QAAS,KAAiC,aAAa;;;;;;;;AAUjE,SAAgB,mBAAmB,MAA0C;AAC3E,QACE,SAAS,UACT,SAAS,WAAW,KAAK,IACzB,aAAa,KAAK,eAClB,OAAO,KAAK,YAAY,YAAY,cACpC,KAAK,YAAY,SAAS,KAAK;;;;;;;;AAUnC,SAAgB,uBACd,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;EAAS,CAAC,SACzD,KAAK,OAAO,KACb;;;;;;;;;;AAYT,SAAgB,gBAAgB,MAA8C;AAC5E,QACE,uBAAuB,KAAK,IAC5B,mBAAmB,KAAK,IAExB,iBAAiB,KAAY"}
@@ -10,7 +10,6 @@ const require_runnables = require('./runnables.cjs');
10
10
  const require_tools = require('./tools.cjs');
11
11
  const require_tracers = require('./tracers.cjs');
12
12
  const require_vectorstores = require('./vectorstores.cjs');
13
- const require_fake_model_builder = require('./fake_model_builder.cjs');
14
13
 
15
14
  //#region src/utils/testing/index.ts
16
15
  var testing_exports = /* @__PURE__ */ require_runtime.__exportAll({
@@ -29,8 +28,7 @@ var testing_exports = /* @__PURE__ */ require_runtime.__exportAll({
29
28
  FakeTracer: () => require_message_history.FakeTracer,
30
29
  FakeVectorStore: () => require_vectorstores.FakeVectorStore,
31
30
  SingleRunExtractor: () => require_tracers.SingleRunExtractor,
32
- SyntheticEmbeddings: () => require_embeddings.SyntheticEmbeddings,
33
- fakeModel: () => require_fake_model_builder.fakeModel
31
+ SyntheticEmbeddings: () => require_embeddings.SyntheticEmbeddings
34
32
  });
35
33
 
36
34
  //#endregion
@@ -50,7 +48,6 @@ exports.FakeTracer = require_message_history.FakeTracer;
50
48
  exports.FakeVectorStore = require_vectorstores.FakeVectorStore;
51
49
  exports.SingleRunExtractor = require_tracers.SingleRunExtractor;
52
50
  exports.SyntheticEmbeddings = require_embeddings.SyntheticEmbeddings;
53
- exports.fakeModel = require_fake_model_builder.fakeModel;
54
51
  Object.defineProperty(exports, 'testing_exports', {
55
52
  enumerable: true,
56
53
  get: function () {
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../../../src/utils/testing/index.ts"],"sourcesContent":["export * from \"./chat_models.js\";\nexport * from \"./embeddings.js\";\nexport * from \"./llms.js\";\nexport * from \"./message_history.js\";\nexport * from \"./output_parsers.js\";\nexport * from \"./retrievers.js\";\nexport * from \"./runnables.js\";\nexport * from \"./tools.js\";\nexport * from \"./tracers.js\";\nexport * from \"./vectorstores.js\";\nexport { fakeModel } from \"./fake_model_builder.js\";\n"],"mappings":""}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../../src/utils/testing/index.ts"],"sourcesContent":["export * from \"./chat_models.js\";\nexport * from \"./embeddings.js\";\nexport * from \"./llms.js\";\nexport * from \"./message_history.js\";\nexport * from \"./output_parsers.js\";\nexport * from \"./retrievers.js\";\nexport * from \"./runnables.js\";\nexport * from \"./tools.js\";\nexport * from \"./tracers.js\";\nexport * from \"./vectorstores.js\";\n"],"mappings":""}
@@ -8,5 +8,4 @@ import { FakeRunnable } from "./runnables.cjs";
8
8
  import { FakeTool, FakeToolParams } from "./tools.cjs";
9
9
  import { SingleRunExtractor } from "./tracers.cjs";
10
10
  import { FakeVectorStore, FakeVectorStoreArgs } from "./vectorstores.cjs";
11
- import { fakeModel } from "./fake_model_builder.cjs";
12
- export { FakeChatInput, FakeChatMessageHistory, FakeChatModel, FakeEmbeddings, FakeLLM, FakeListChatMessageHistory, FakeListChatModel, FakeListChatModelCallOptions, FakeRetriever, FakeRunnable, FakeSplitIntoListParser, FakeStreamingChatModel, FakeStreamingChatModelCallOptions, FakeStreamingChatModelFields, FakeStreamingLLM, FakeTool, FakeToolParams, FakeTracer, FakeVectorStore, FakeVectorStoreArgs, SingleRunExtractor, SyntheticEmbeddings, ToolSpec, fakeModel };
11
+ export { FakeChatInput, FakeChatMessageHistory, FakeChatModel, FakeEmbeddings, FakeLLM, FakeListChatMessageHistory, FakeListChatModel, FakeListChatModelCallOptions, FakeRetriever, FakeRunnable, FakeSplitIntoListParser, FakeStreamingChatModel, FakeStreamingChatModelCallOptions, FakeStreamingChatModelFields, FakeStreamingLLM, FakeTool, FakeToolParams, FakeTracer, FakeVectorStore, FakeVectorStoreArgs, SingleRunExtractor, SyntheticEmbeddings, ToolSpec };
@@ -8,5 +8,4 @@ import { FakeRunnable } from "./runnables.js";
8
8
  import { FakeTool, FakeToolParams } from "./tools.js";
9
9
  import { SingleRunExtractor } from "./tracers.js";
10
10
  import { FakeVectorStore, FakeVectorStoreArgs } from "./vectorstores.js";
11
- import { fakeModel } from "./fake_model_builder.js";
12
- export { FakeChatInput, FakeChatMessageHistory, FakeChatModel, FakeEmbeddings, FakeLLM, FakeListChatMessageHistory, FakeListChatModel, FakeListChatModelCallOptions, FakeRetriever, FakeRunnable, FakeSplitIntoListParser, FakeStreamingChatModel, FakeStreamingChatModelCallOptions, FakeStreamingChatModelFields, FakeStreamingLLM, FakeTool, FakeToolParams, FakeTracer, FakeVectorStore, FakeVectorStoreArgs, SingleRunExtractor, SyntheticEmbeddings, ToolSpec, fakeModel };
11
+ export { FakeChatInput, FakeChatMessageHistory, FakeChatModel, FakeEmbeddings, FakeLLM, FakeListChatMessageHistory, FakeListChatModel, FakeListChatModelCallOptions, FakeRetriever, FakeRunnable, FakeSplitIntoListParser, FakeStreamingChatModel, FakeStreamingChatModelCallOptions, FakeStreamingChatModelFields, FakeStreamingLLM, FakeTool, FakeToolParams, FakeTracer, FakeVectorStore, FakeVectorStoreArgs, SingleRunExtractor, SyntheticEmbeddings, ToolSpec };
@@ -9,7 +9,6 @@ import { FakeRunnable } from "./runnables.js";
9
9
  import { FakeTool } from "./tools.js";
10
10
  import { SingleRunExtractor } from "./tracers.js";
11
11
  import { FakeVectorStore } from "./vectorstores.js";
12
- import { fakeModel } from "./fake_model_builder.js";
13
12
 
14
13
  //#region src/utils/testing/index.ts
15
14
  var testing_exports = /* @__PURE__ */ __exportAll({
@@ -28,10 +27,9 @@ var testing_exports = /* @__PURE__ */ __exportAll({
28
27
  FakeTracer: () => FakeTracer,
29
28
  FakeVectorStore: () => FakeVectorStore,
30
29
  SingleRunExtractor: () => SingleRunExtractor,
31
- SyntheticEmbeddings: () => SyntheticEmbeddings,
32
- fakeModel: () => fakeModel
30
+ SyntheticEmbeddings: () => SyntheticEmbeddings
33
31
  });
34
32
 
35
33
  //#endregion
36
- export { FakeChatMessageHistory, FakeChatModel, FakeEmbeddings, FakeLLM, FakeListChatMessageHistory, FakeListChatModel, FakeRetriever, FakeRunnable, FakeSplitIntoListParser, FakeStreamingChatModel, FakeStreamingLLM, FakeTool, FakeTracer, FakeVectorStore, SingleRunExtractor, SyntheticEmbeddings, fakeModel, testing_exports };
34
+ export { FakeChatMessageHistory, FakeChatModel, FakeEmbeddings, FakeLLM, FakeListChatMessageHistory, FakeListChatModel, FakeRetriever, FakeRunnable, FakeSplitIntoListParser, FakeStreamingChatModel, FakeStreamingLLM, FakeTool, FakeTracer, FakeVectorStore, SingleRunExtractor, SyntheticEmbeddings, testing_exports };
37
35
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/utils/testing/index.ts"],"sourcesContent":["export * from \"./chat_models.js\";\nexport * from \"./embeddings.js\";\nexport * from \"./llms.js\";\nexport * from \"./message_history.js\";\nexport * from \"./output_parsers.js\";\nexport * from \"./retrievers.js\";\nexport * from \"./runnables.js\";\nexport * from \"./tools.js\";\nexport * from \"./tracers.js\";\nexport * from \"./vectorstores.js\";\nexport { fakeModel } from \"./fake_model_builder.js\";\n"],"mappings":""}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/utils/testing/index.ts"],"sourcesContent":["export * from \"./chat_models.js\";\nexport * from \"./embeddings.js\";\nexport * from \"./llms.js\";\nexport * from \"./message_history.js\";\nexport * from \"./output_parsers.js\";\nexport * from \"./retrievers.js\";\nexport * from \"./runnables.js\";\nexport * from \"./tools.js\";\nexport * from \"./tracers.js\";\nexport * from \"./vectorstores.js\";\n"],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/core",
3
- "version": "1.1.30",
3
+ "version": "1.1.32",
4
4
  "description": "Core LangChain.js abstractions and schemas",
5
5
  "type": "module",
6
6
  "engines": {
@@ -37,12 +37,12 @@
37
37
  "eslint": "^9.34.0",
38
38
  "ml-matrix": "^6.10.4",
39
39
  "prettier": "^3.5.0",
40
- "rimraf": "^5.0.1",
40
+ "rimraf": "^6.1.3",
41
41
  "typescript": "~5.8.3",
42
42
  "vitest": "^3.2.4",
43
43
  "web-streams-polyfill": "^4.2.0",
44
- "@langchain/tsconfig": "0.0.1",
45
- "@langchain/eslint": "0.1.1"
44
+ "@langchain/eslint": "0.1.1",
45
+ "@langchain/tsconfig": "0.0.1"
46
46
  },
47
47
  "publishConfig": {
48
48
  "access": "public"
@@ -502,6 +502,17 @@
502
502
  "default": "./dist/structured_query/index.js"
503
503
  }
504
504
  },
505
+ "./testing": {
506
+ "input": "./src/testing/index.ts",
507
+ "require": {
508
+ "types": "./dist/testing/index.d.cts",
509
+ "default": "./dist/testing/index.cjs"
510
+ },
511
+ "import": {
512
+ "types": "./dist/testing/index.d.ts",
513
+ "default": "./dist/testing/index.js"
514
+ }
515
+ },
505
516
  "./tools": {
506
517
  "input": "./src/tools/index.ts",
507
518
  "require": {
@@ -862,6 +873,7 @@
862
873
  "runnables.cjs",
863
874
  "runnables.d.ts",
864
875
  "runnables.js",
876
+ "testing",
865
877
  "tools.d.cts",
866
878
  "tools.cjs",
867
879
  "tools.d.ts",
@@ -1 +0,0 @@
1
- {"version":3,"file":"fake_model_builder.cjs","names":["BaseChatModel","BaseMessage","RunnableLambda","AIMessage"],"sources":["../../../src/utils/testing/fake_model_builder.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { CallbackManagerForLLMRun } from \"../../callbacks/manager.js\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"../../language_models/chat_models.js\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n StructuredOutputMethodParams,\n} from \"../../language_models/base.js\";\nimport { BaseMessage, AIMessage } from \"../../messages/index.js\";\nimport type { ToolCall } from \"../../messages/tool.js\";\nimport type { ChatResult } from \"../../outputs.js\";\nimport { Runnable, RunnableLambda } from \"../../runnables/base.js\";\nimport { StructuredTool } from \"../../tools/index.js\";\nimport type { InteropZodType } from \"../types/zod.js\";\nimport type { ToolSpec } from \"./chat_models.js\";\n\ntype ResponseFactory = (messages: BaseMessage[]) => BaseMessage | Error;\n\ntype QueueEntry =\n | { kind: \"message\"; message: BaseMessage }\n | { kind: \"toolCalls\"; toolCalls: ToolCall[] }\n | { kind: \"error\"; error: Error }\n | { kind: \"factory\"; factory: ResponseFactory };\n\ninterface FakeModelCall {\n messages: BaseMessage[];\n options: any;\n}\n\nfunction deriveContent(messages: BaseMessage[]): string {\n return messages\n .map((m) => m.text)\n .filter(Boolean)\n .join(\"-\");\n}\n\nlet idCounter = 0;\nfunction nextToolCallId(): string {\n idCounter += 1;\n return `fake_tc_${idCounter}`;\n}\n\n/**\n * A fake chat model for testing, created via {@link fakeModel}.\n *\n * Queue responses with `.respond()` and `.respondWithTools()`, then\n * pass the instance directly wherever a chat model is expected.\n *\n * Each builder method queues a model response consumed in order per `invoke()`:\n *\n * `.respond(entry)` — enqueue a `BaseMessage`, `Error`, or factory function.\n *\n * `.respondWithTools(toolCalls[])` — enqueue an `AIMessage` with the given\n * tool calls. Content is derived from the input messages automatically.\n *\n * Both can be mixed freely in one chain. When all queued responses are\n * consumed, further invocations throw.\n *\n * Additional configuration:\n * - `.alwaysThrow(error)` — every call throws (overrides the queue)\n * - `.structuredResponse(value)` — value returned by `withStructuredOutput()`\n *\n * The model records all invocations in `.calls` / `.callCount`.\n */\nclass FakeBuiltModel extends BaseChatModel {\n private queue: QueueEntry[] = [];\n\n private _alwaysThrowError: Error | undefined;\n\n private _structuredResponseValue: any;\n\n private _tools: (StructuredTool | ToolSpec)[] = [];\n\n private _callIndex = 0;\n\n private _calls: FakeModelCall[] = [];\n\n get calls(): FakeModelCall[] {\n return this._calls;\n }\n\n get callCount(): number {\n return this._calls.length;\n }\n\n constructor() {\n super({});\n }\n\n _llmType(): string {\n return \"fake-model-builder\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n respond(entry: BaseMessage | Error | ResponseFactory): this {\n if (typeof entry === \"function\") {\n this.queue.push({ kind: \"factory\", factory: entry });\n } else if (BaseMessage.isInstance(entry)) {\n this.queue.push({ kind: \"message\", message: entry });\n } else {\n this.queue.push({ kind: \"error\", error: entry });\n }\n return this;\n }\n\n respondWithTools(\n toolCalls: Array<{ name: string; args: Record<string, any>; id?: string }>\n ): this {\n this.queue.push({\n kind: \"toolCalls\",\n toolCalls: toolCalls.map((tc) => ({\n name: tc.name,\n args: tc.args,\n id: tc.id ?? nextToolCallId(),\n type: \"tool_call\" as const,\n })),\n });\n return this;\n }\n\n alwaysThrow(error: Error): this {\n this._alwaysThrowError = error;\n return this;\n }\n\n structuredResponse(value: Record<string, any>): this {\n this._structuredResponseValue = value;\n return this;\n }\n\n bindTools(tools: (StructuredTool | ToolSpec)[]) {\n const merged = [...this._tools, ...tools];\n const next = new FakeBuiltModel();\n next.queue = this.queue;\n next._alwaysThrowError = this._alwaysThrowError;\n next._structuredResponseValue = this._structuredResponseValue;\n next._tools = merged;\n next._calls = this._calls;\n next._callIndex = this._callIndex;\n\n return next.withConfig({} as BaseChatModelCallOptions);\n }\n\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n | Record<string, any>,\n _config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n const { _structuredResponseValue } = this;\n return RunnableLambda.from(async () => {\n return _structuredResponseValue as RunOutput;\n }) as Runnable;\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n this._calls.push({ messages: [...messages], options });\n\n const currentCallIndex = this._callIndex;\n this._callIndex += 1;\n\n if (this._alwaysThrowError) {\n throw this._alwaysThrowError;\n }\n\n const entry = this.queue[currentCallIndex];\n if (!entry) {\n throw new Error(\n `FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`\n );\n }\n\n if (entry.kind === \"error\") {\n throw entry.error;\n }\n\n if (entry.kind === \"factory\") {\n const result = entry.factory(messages);\n if (!BaseMessage.isInstance(result)) {\n throw result;\n }\n return {\n generations: [{ text: \"\", message: result }],\n };\n }\n\n if (entry.kind === \"message\") {\n return {\n generations: [{ text: \"\", message: entry.message }],\n };\n }\n\n const content = deriveContent(messages);\n const message = new AIMessage({\n content,\n id: currentCallIndex.toString(),\n tool_calls:\n entry.toolCalls.length > 0\n ? entry.toolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [{ text: content, message }],\n llmOutput: {},\n };\n }\n}\n\n/**\n * Creates a fake chat model for testing.\n *\n * @example\n * ```typescript\n * const model = fakeModel()\n * .respondWithTools([{ name: \"search\", args: { query: \"weather\" } }])\n * .respond(new AIMessage(\"Sunny and warm.\"));\n *\n * const r1 = await model.invoke([new HumanMessage(\"What's the weather?\")]);\n * // r1.tool_calls[0].name === \"search\"\n *\n * const r2 = await model.invoke([new HumanMessage(\"Thanks\")]);\n * // r2.content === \"Sunny and warm.\"\n * ```\n */\nexport function fakeModel(): FakeBuiltModel {\n return new FakeBuiltModel();\n}\n"],"mappings":";;;;;;;AAgCA,SAAS,cAAc,UAAiC;AACtD,QAAO,SACJ,KAAK,MAAM,EAAE,KAAK,CAClB,OAAO,QAAQ,CACf,KAAK,IAAI;;AAGd,IAAI,YAAY;AAChB,SAAS,iBAAyB;AAChC,cAAa;AACb,QAAO,WAAW;;;;;;;;;;;;;;;;;;;;;;;;AAyBpB,IAAM,iBAAN,MAAM,uBAAuBA,kDAAc;CACzC,AAAQ,QAAsB,EAAE;CAEhC,AAAQ;CAER,AAAQ;CAER,AAAQ,SAAwC,EAAE;CAElD,AAAQ,aAAa;CAErB,AAAQ,SAA0B,EAAE;CAEpC,IAAI,QAAyB;AAC3B,SAAO,KAAK;;CAGd,IAAI,YAAoB;AACtB,SAAO,KAAK,OAAO;;CAGrB,cAAc;AACZ,QAAM,EAAE,CAAC;;CAGX,WAAmB;AACjB,SAAO;;CAGT,oBAAoB;AAClB,SAAO,EAAE;;CAGX,QAAQ,OAAoD;AAC1D,MAAI,OAAO,UAAU,WACnB,MAAK,M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MAAM,SAAS,QACjB,OAAM,MAAM;AAGd,MAAI,MAAM,SAAS,WAAW;GAC5B,MAAM,SAAS,MAAM,QAAQ,SAAS;AACtC,OAAI,CAACD,yBAAY,WAAW,OAAO,CACjC,OAAM;AAER,UAAO,EACL,aAAa,CAAC;IAAE,MAAM;IAAI,SAAS;IAAQ,CAAC,EAC7C;;AAGH,MAAI,MAAM,SAAS,UACjB,QAAO,EACL,aAAa,CAAC;GAAE,MAAM;GAAI,SAAS,MAAM;GAAS,CAAC,EACpD;EAGH,MAAM,UAAU,cAAc,SAAS;AAavC,SAAO;GACL,aAAa,CAAC;IAAE,MAAM;IAAS,SAbjB,IAAIE,qBAAU;KAC5B;KACA,IAAI,iBAAiB,UAAU;KAC/B,YACE,MAAM,UAAU,SAAS,IACrB,MAAM,UAAU,KAAK,QAAQ;MAC3B,GAAG;MACH,MAAM;MACP,EAAE,GACH;KACP,CAAC;IAGwC,CAAC;GACzC,WAAW,EAAE;GACd;;;;;;;;;;;;;;;;;;;AAoBL,SAAgB,YAA4B;AAC1C,QAAO,IAAI,gBAAgB"}
@@ -1,87 +0,0 @@
1
- import { BaseMessage } from "../../messages/base.cjs";
2
- import { AIMessageChunk } from "../../messages/ai.cjs";
3
- import { MessageStructure, MessageToolSet } from "../../messages/message.cjs";
4
- import { ChatResult } from "../../outputs.cjs";
5
- import { InteropZodType } from "../types/zod.cjs";
6
- import { CallbackManagerForLLMRun } from "../../callbacks/manager.cjs";
7
- import { Runnable } from "../../runnables/base.cjs";
8
- import { BaseLanguageModelInput, StructuredOutputMethodOptions, StructuredOutputMethodParams } from "../../language_models/base.cjs";
9
- import { StructuredTool } from "../../tools/index.cjs";
10
- import { BaseChatModel, BaseChatModelCallOptions } from "../../language_models/chat_models.cjs";
11
- import { ToolSpec } from "./chat_models.cjs";
12
-
13
- //#region src/utils/testing/fake_model_builder.d.ts
14
- type ResponseFactory = (messages: BaseMessage[]) => BaseMessage | Error;
15
- interface FakeModelCall {
16
- messages: BaseMessage[];
17
- options: any;
18
- }
19
- /**
20
- * A fake chat model for testing, created via {@link fakeModel}.
21
- *
22
- * Queue responses with `.respond()` and `.respondWithTools()`, then
23
- * pass the instance directly wherever a chat model is expected.
24
- *
25
- * Each builder method queues a model response consumed in order per `invoke()`:
26
- *
27
- * `.respond(entry)` — enqueue a `BaseMessage`, `Error`, or factory function.
28
- *
29
- * `.respondWithTools(toolCalls[])` — enqueue an `AIMessage` with the given
30
- * tool calls. Content is derived from the input messages automatically.
31
- *
32
- * Both can be mixed freely in one chain. When all queued responses are
33
- * consumed, further invocations throw.
34
- *
35
- * Additional configuration:
36
- * - `.alwaysThrow(error)` — every call throws (overrides the queue)
37
- * - `.structuredResponse(value)` — value returned by `withStructuredOutput()`
38
- *
39
- * The model records all invocations in `.calls` / `.callCount`.
40
- */
41
- declare class FakeBuiltModel extends BaseChatModel {
42
- private queue;
43
- private _alwaysThrowError;
44
- private _structuredResponseValue;
45
- private _tools;
46
- private _callIndex;
47
- private _calls;
48
- get calls(): FakeModelCall[];
49
- get callCount(): number;
50
- constructor();
51
- _llmType(): string;
52
- _combineLLMOutput(): never[];
53
- respond(entry: BaseMessage | Error | ResponseFactory): this;
54
- respondWithTools(toolCalls: Array<{
55
- name: string;
56
- args: Record<string, any>;
57
- id?: string;
58
- }>): this;
59
- alwaysThrow(error: Error): this;
60
- structuredResponse(value: Record<string, any>): this;
61
- bindTools(tools: (StructuredTool | ToolSpec)[]): Runnable<BaseLanguageModelInput, AIMessageChunk<MessageStructure<MessageToolSet>>, BaseChatModelCallOptions>;
62
- withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, boolean> | InteropZodType<RunOutput> | Record<string, any>, _config?: StructuredOutputMethodOptions<boolean>): Runnable<BaseLanguageModelInput, RunOutput> | Runnable<BaseLanguageModelInput, {
63
- raw: BaseMessage;
64
- parsed: RunOutput;
65
- }>;
66
- _generate(messages: BaseMessage[], options?: this["ParsedCallOptions"], _runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;
67
- }
68
- /**
69
- * Creates a fake chat model for testing.
70
- *
71
- * @example
72
- * ```typescript
73
- * const model = fakeModel()
74
- * .respondWithTools([{ name: "search", args: { query: "weather" } }])
75
- * .respond(new AIMessage("Sunny and warm."));
76
- *
77
- * const r1 = await model.invoke([new HumanMessage("What's the weather?")]);
78
- * // r1.tool_calls[0].name === "search"
79
- *
80
- * const r2 = await model.invoke([new HumanMessage("Thanks")]);
81
- * // r2.content === "Sunny and warm."
82
- * ```
83
- */
84
- declare function fakeModel(): FakeBuiltModel;
85
- //#endregion
86
- export { fakeModel };
87
- //# sourceMappingURL=fake_model_builder.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"fake_model_builder.d.cts","names":[],"sources":["../../../src/utils/testing/fake_model_builder.ts"],"mappings":";;;;;;;;;;;;;KAmBK,eAAA,IAAmB,QAAA,EAAU,WAAA,OAAkB,WAAA,GAAc,KAAA;AAAA,UAQxD,aAAA;EACR,QAAA,EAAU,WAAA;EACV,OAAA;AAAA;;;;;;;;;;;;;;AAVqE;;;;;;;;;cAgDjE,cAAA,SAAuB,aAAA;EAAA,QACnB,KAAA;EAAA,QAEA,iBAAA;EAAA,QAEA,wBAAA;EAAA,QAEA,MAAA;EAAA,QAEA,UAAA;EAAA,QAEA,MAAA;EAAA,IAEJ,KAAA,CAAA,GAAS,aAAA;EAAA,IAIT,SAAA,CAAA;EAIJ,WAAA,CAAA;EAIA,QAAA,CAAA;EAIA,iBAAA,CAAA;EAIA,OAAA,CAAQ,KAAA,EAAO,WAAA,GAAc,KAAA,GAAQ,eAAA;EAWrC,gBAAA,CACE,SAAA,EAAW,KAAA;IAAQ,IAAA;IAAc,IAAA,EAAM,MAAA;IAAqB,EAAA;EAAA;EAc9D,WAAA,CAAY,KAAA,EAAO,KAAA;EAKnB,kBAAA,CAAmB,KAAA,EAAO,MAAA;EAK1B,SAAA,CAAU,KAAA,GAAQ,cAAA,GAAiB,QAAA,MAAW,QAAA,CAAA,sBAAA,EAAA,cAAA,CAAA,gBAAA,CAAA,cAAA,IAAA,wBAAA;EAa9C,oBAAA,mBACoB,MAAA,gBAAsB,MAAA,cAAA,CAExC,OAAA,EACI,4BAAA,CAA6B,SAAA,aAC7B,cAAA,CAAe,SAAA,IACf,MAAA,eACJ,OAAA,GAAU,6BAAA,YAER,QAAA,CAAS,sBAAA,EAAwB,SAAA,IACjC,QAAA,CACE,sBAAA;IACE,GAAA,EAAK,WAAA;IAAa,MAAA,EAAQ,SAAA;EAAA;EAQ5B,SAAA,CACJ,QAAA,EAAU,WAAA,IACV,OAAA,8BACA,WAAA,GAAc,wBAAA,GACb,OAAA,CAAQ,UAAA;AAAA;;;;;;;;;;;;;;;;;iBAyEG,SAAA,CAAA,GAAa,cAAA"}
@@ -1,88 +0,0 @@
1
- import { BaseMessage } from "../../messages/base.js";
2
- import { AIMessageChunk } from "../../messages/ai.js";
3
- import { MessageStructure, MessageToolSet } from "../../messages/message.js";
4
- import { ChatResult } from "../../outputs.js";
5
- import { InteropZodType } from "../types/zod.js";
6
- import { CallbackManagerForLLMRun } from "../../callbacks/manager.js";
7
- import { Runnable } from "../../runnables/base.js";
8
- import { BaseLanguageModelInput, StructuredOutputMethodOptions, StructuredOutputMethodParams } from "../../language_models/base.js";
9
- import "../../messages/index.js";
10
- import { StructuredTool } from "../../tools/index.js";
11
- import { BaseChatModel, BaseChatModelCallOptions } from "../../language_models/chat_models.js";
12
- import { ToolSpec } from "./chat_models.js";
13
-
14
- //#region src/utils/testing/fake_model_builder.d.ts
15
- type ResponseFactory = (messages: BaseMessage[]) => BaseMessage | Error;
16
- interface FakeModelCall {
17
- messages: BaseMessage[];
18
- options: any;
19
- }
20
- /**
21
- * A fake chat model for testing, created via {@link fakeModel}.
22
- *
23
- * Queue responses with `.respond()` and `.respondWithTools()`, then
24
- * pass the instance directly wherever a chat model is expected.
25
- *
26
- * Each builder method queues a model response consumed in order per `invoke()`:
27
- *
28
- * `.respond(entry)` — enqueue a `BaseMessage`, `Error`, or factory function.
29
- *
30
- * `.respondWithTools(toolCalls[])` — enqueue an `AIMessage` with the given
31
- * tool calls. Content is derived from the input messages automatically.
32
- *
33
- * Both can be mixed freely in one chain. When all queued responses are
34
- * consumed, further invocations throw.
35
- *
36
- * Additional configuration:
37
- * - `.alwaysThrow(error)` — every call throws (overrides the queue)
38
- * - `.structuredResponse(value)` — value returned by `withStructuredOutput()`
39
- *
40
- * The model records all invocations in `.calls` / `.callCount`.
41
- */
42
- declare class FakeBuiltModel extends BaseChatModel {
43
- private queue;
44
- private _alwaysThrowError;
45
- private _structuredResponseValue;
46
- private _tools;
47
- private _callIndex;
48
- private _calls;
49
- get calls(): FakeModelCall[];
50
- get callCount(): number;
51
- constructor();
52
- _llmType(): string;
53
- _combineLLMOutput(): never[];
54
- respond(entry: BaseMessage | Error | ResponseFactory): this;
55
- respondWithTools(toolCalls: Array<{
56
- name: string;
57
- args: Record<string, any>;
58
- id?: string;
59
- }>): this;
60
- alwaysThrow(error: Error): this;
61
- structuredResponse(value: Record<string, any>): this;
62
- bindTools(tools: (StructuredTool | ToolSpec)[]): Runnable<BaseLanguageModelInput, AIMessageChunk<MessageStructure<MessageToolSet>>, BaseChatModelCallOptions>;
63
- withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, boolean> | InteropZodType<RunOutput> | Record<string, any>, _config?: StructuredOutputMethodOptions<boolean>): Runnable<BaseLanguageModelInput, RunOutput> | Runnable<BaseLanguageModelInput, {
64
- raw: BaseMessage;
65
- parsed: RunOutput;
66
- }>;
67
- _generate(messages: BaseMessage[], options?: this["ParsedCallOptions"], _runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;
68
- }
69
- /**
70
- * Creates a fake chat model for testing.
71
- *
72
- * @example
73
- * ```typescript
74
- * const model = fakeModel()
75
- * .respondWithTools([{ name: "search", args: { query: "weather" } }])
76
- * .respond(new AIMessage("Sunny and warm."));
77
- *
78
- * const r1 = await model.invoke([new HumanMessage("What's the weather?")]);
79
- * // r1.tool_calls[0].name === "search"
80
- *
81
- * const r2 = await model.invoke([new HumanMessage("Thanks")]);
82
- * // r2.content === "Sunny and warm."
83
- * ```
84
- */
85
- declare function fakeModel(): FakeBuiltModel;
86
- //#endregion
87
- export { fakeModel };
88
- //# sourceMappingURL=fake_model_builder.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"fake_model_builder.d.ts","names":[],"sources":["../../../src/utils/testing/fake_model_builder.ts"],"mappings":";;;;;;;;;;;;;;KAmBK,eAAA,IAAmB,QAAA,EAAU,WAAA,OAAkB,WAAA,GAAc,KAAA;AAAA,UAQxD,aAAA;EACR,QAAA,EAAU,WAAA;EACV,OAAA;AAAA;AAZ+C;;;;;;;;;;;;;;AAEsB;;;;;;;;AAFtB,cAkD3C,cAAA,SAAuB,aAAA;EAAA,QACnB,KAAA;EAAA,QAEA,iBAAA;EAAA,QAEA,wBAAA;EAAA,QAEA,MAAA;EAAA,QAEA,UAAA;EAAA,QAEA,MAAA;EAAA,IAEJ,KAAA,CAAA,GAAS,aAAA;EAAA,IAIT,SAAA,CAAA;EAIJ,WAAA,CAAA;EAIA,QAAA,CAAA;EAIA,iBAAA,CAAA;EAIA,OAAA,CAAQ,KAAA,EAAO,WAAA,GAAc,KAAA,GAAQ,eAAA;EAWrC,gBAAA,CACE,SAAA,EAAW,KAAA;IAAQ,IAAA;IAAc,IAAA,EAAM,MAAA;IAAqB,EAAA;EAAA;EAc9D,WAAA,CAAY,KAAA,EAAO,KAAA;EAKnB,kBAAA,CAAmB,KAAA,EAAO,MAAA;EAK1B,SAAA,CAAU,KAAA,GAAQ,cAAA,GAAiB,QAAA,MAAW,QAAA,CAAA,sBAAA,EAAA,cAAA,CAAA,gBAAA,CAAA,cAAA,IAAA,wBAAA;EAa9C,oBAAA,mBACoB,MAAA,gBAAsB,MAAA,cAAA,CAExC,OAAA,EACI,4BAAA,CAA6B,SAAA,aAC7B,cAAA,CAAe,SAAA,IACf,MAAA,eACJ,OAAA,GAAU,6BAAA,YAER,QAAA,CAAS,sBAAA,EAAwB,SAAA,IACjC,QAAA,CACE,sBAAA;IACE,GAAA,EAAK,WAAA;IAAa,MAAA,EAAQ,SAAA;EAAA;EAQ5B,SAAA,CACJ,QAAA,EAAU,WAAA,IACV,OAAA,8BACA,WAAA,GAAc,wBAAA,GACb,OAAA,CAAQ,UAAA;AAAA;;;;;;;;;;;;;;;;;iBAyEG,SAAA,CAAA,GAAa,cAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"fake_model_builder.js","names":[],"sources":["../../../src/utils/testing/fake_model_builder.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { CallbackManagerForLLMRun } from \"../../callbacks/manager.js\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n} from \"../../language_models/chat_models.js\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n StructuredOutputMethodParams,\n} from \"../../language_models/base.js\";\nimport { BaseMessage, AIMessage } from \"../../messages/index.js\";\nimport type { ToolCall } from \"../../messages/tool.js\";\nimport type { ChatResult } from \"../../outputs.js\";\nimport { Runnable, RunnableLambda } from \"../../runnables/base.js\";\nimport { StructuredTool } from \"../../tools/index.js\";\nimport type { InteropZodType } from \"../types/zod.js\";\nimport type { ToolSpec } from \"./chat_models.js\";\n\ntype ResponseFactory = (messages: BaseMessage[]) => BaseMessage | Error;\n\ntype QueueEntry =\n | { kind: \"message\"; message: BaseMessage }\n | { kind: \"toolCalls\"; toolCalls: ToolCall[] }\n | { kind: \"error\"; error: Error }\n | { kind: \"factory\"; factory: ResponseFactory };\n\ninterface FakeModelCall {\n messages: BaseMessage[];\n options: any;\n}\n\nfunction deriveContent(messages: BaseMessage[]): string {\n return messages\n .map((m) => m.text)\n .filter(Boolean)\n .join(\"-\");\n}\n\nlet idCounter = 0;\nfunction nextToolCallId(): string {\n idCounter += 1;\n return `fake_tc_${idCounter}`;\n}\n\n/**\n * A fake chat model for testing, created via {@link fakeModel}.\n *\n * Queue responses with `.respond()` and `.respondWithTools()`, then\n * pass the instance directly wherever a chat model is expected.\n *\n * Each builder method queues a model response consumed in order per `invoke()`:\n *\n * `.respond(entry)` — enqueue a `BaseMessage`, `Error`, or factory function.\n *\n * `.respondWithTools(toolCalls[])` — enqueue an `AIMessage` with the given\n * tool calls. Content is derived from the input messages automatically.\n *\n * Both can be mixed freely in one chain. When all queued responses are\n * consumed, further invocations throw.\n *\n * Additional configuration:\n * - `.alwaysThrow(error)` — every call throws (overrides the queue)\n * - `.structuredResponse(value)` — value returned by `withStructuredOutput()`\n *\n * The model records all invocations in `.calls` / `.callCount`.\n */\nclass FakeBuiltModel extends BaseChatModel {\n private queue: QueueEntry[] = [];\n\n private _alwaysThrowError: Error | undefined;\n\n private _structuredResponseValue: any;\n\n private _tools: (StructuredTool | ToolSpec)[] = [];\n\n private _callIndex = 0;\n\n private _calls: FakeModelCall[] = [];\n\n get calls(): FakeModelCall[] {\n return this._calls;\n }\n\n get callCount(): number {\n return this._calls.length;\n }\n\n constructor() {\n super({});\n }\n\n _llmType(): string {\n return \"fake-model-builder\";\n }\n\n _combineLLMOutput() {\n return [];\n }\n\n respond(entry: BaseMessage | Error | ResponseFactory): this {\n if (typeof entry === \"function\") {\n this.queue.push({ kind: \"factory\", factory: entry });\n } else if (BaseMessage.isInstance(entry)) {\n this.queue.push({ kind: \"message\", message: entry });\n } else {\n this.queue.push({ kind: \"error\", error: entry });\n }\n return this;\n }\n\n respondWithTools(\n toolCalls: Array<{ name: string; args: Record<string, any>; id?: string }>\n ): this {\n this.queue.push({\n kind: \"toolCalls\",\n toolCalls: toolCalls.map((tc) => ({\n name: tc.name,\n args: tc.args,\n id: tc.id ?? nextToolCallId(),\n type: \"tool_call\" as const,\n })),\n });\n return this;\n }\n\n alwaysThrow(error: Error): this {\n this._alwaysThrowError = error;\n return this;\n }\n\n structuredResponse(value: Record<string, any>): this {\n this._structuredResponseValue = value;\n return this;\n }\n\n bindTools(tools: (StructuredTool | ToolSpec)[]) {\n const merged = [...this._tools, ...tools];\n const next = new FakeBuiltModel();\n next.queue = this.queue;\n next._alwaysThrowError = this._alwaysThrowError;\n next._structuredResponseValue = this._structuredResponseValue;\n next._tools = merged;\n next._calls = this._calls;\n next._callIndex = this._callIndex;\n\n return next.withConfig({} as BaseChatModelCallOptions);\n }\n\n withStructuredOutput<\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n _params:\n | StructuredOutputMethodParams<RunOutput, boolean>\n | InteropZodType<RunOutput>\n | Record<string, any>,\n _config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n const { _structuredResponseValue } = this;\n return RunnableLambda.from(async () => {\n return _structuredResponseValue as RunOutput;\n }) as Runnable;\n }\n\n async _generate(\n messages: BaseMessage[],\n options?: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n this._calls.push({ messages: [...messages], options });\n\n const currentCallIndex = this._callIndex;\n this._callIndex += 1;\n\n if (this._alwaysThrowError) {\n throw this._alwaysThrowError;\n }\n\n const entry = this.queue[currentCallIndex];\n if (!entry) {\n throw new Error(\n `FakeModel: no response queued for invocation ${currentCallIndex} (${this.queue.length} total queued).`\n );\n }\n\n if (entry.kind === \"error\") {\n throw entry.error;\n }\n\n if (entry.kind === \"factory\") {\n const result = entry.factory(messages);\n if (!BaseMessage.isInstance(result)) {\n throw result;\n }\n return {\n generations: [{ text: \"\", message: result }],\n };\n }\n\n if (entry.kind === \"message\") {\n return {\n generations: [{ text: \"\", message: entry.message }],\n };\n }\n\n const content = deriveContent(messages);\n const message = new AIMessage({\n content,\n id: currentCallIndex.toString(),\n tool_calls:\n entry.toolCalls.length > 0\n ? entry.toolCalls.map((tc) => ({\n ...tc,\n type: \"tool_call\" as const,\n }))\n : undefined,\n });\n\n return {\n generations: [{ text: content, message }],\n llmOutput: {},\n };\n }\n}\n\n/**\n * Creates a fake chat model for testing.\n *\n * @example\n * ```typescript\n * const model = fakeModel()\n * .respondWithTools([{ name: \"search\", args: { query: \"weather\" } }])\n * .respond(new AIMessage(\"Sunny and warm.\"));\n *\n * const r1 = await model.invoke([new HumanMessage(\"What's the weather?\")]);\n * // r1.tool_calls[0].name === \"search\"\n *\n * const r2 = await model.invoke([new HumanMessage(\"Thanks\")]);\n * // r2.content === \"Sunny and warm.\"\n * ```\n */\nexport function fakeModel(): FakeBuiltModel {\n return new FakeBuiltModel();\n}\n"],"mappings":";;;;;;;AAgCA,SAAS,cAAc,UAAiC;AACtD,QAAO,SACJ,KAAK,MAAM,EAAE,KAAK,CAClB,OAAO,QAAQ,CACf,KAAK,IAAI;;AAGd,IAAI,YAAY;AAChB,SAAS,iBAAyB;AAChC,cAAa;AACb,QAAO,WAAW;;;;;;;;;;;;;;;;;;;;;;;;AAyBpB,IAAM,iBAAN,MAAM,uBAAuB,cAAc;CACzC,AAAQ,QAAsB,EAAE;CAEhC,AAAQ;CAER,AAAQ;CAER,AAAQ,SAAwC,EAAE;CAElD,AAAQ,aAAa;CAErB,AAAQ,SAA0B,EAAE;CAEpC,IAAI,QAAyB;AAC3B,SAAO,KAAK;;CAGd,IAAI,YAAoB;AACtB,SAAO,KAAK,OAAO;;CAGrB,cAAc;AACZ,QAAM,EAAE,CAAC;;CAGX,WAAmB;AACjB,SAAO;;CAGT,oBAAoB;AAClB,SAAO,EAAE;;CAGX,QAAQ,OAAoD;AAC1D,MAAI,OAAO,UAAU,WACnB,MAAK,MAAM,KAAK;GAAE,MAAM;GAAW,SAAS;GAAO,CAAC;WAC3C,YAAY,WAAW,MAAM,CACtC,MAAK,MAAM,KAAK;GAAE,MAAM;GAAW,SAAS;GAAO,CAAC;MAEpD,MAAK,MAAM,KAAK;GAAE,MAAM;GAAS,OAAO;GAAO,CAAC;AAElD,SAAO;;CAGT,iBACE,WACM;AACN,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