langchain 1.2.37 → 1.2.39

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 (62) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/agents/ReactAgent.cjs +2 -1
  3. package/dist/agents/ReactAgent.cjs.map +1 -1
  4. package/dist/agents/ReactAgent.d.cts.map +1 -1
  5. package/dist/agents/ReactAgent.d.ts.map +1 -1
  6. package/dist/agents/ReactAgent.js +2 -1
  7. package/dist/agents/ReactAgent.js.map +1 -1
  8. package/dist/agents/middleware/modelFallback.cjs.map +1 -1
  9. package/dist/agents/middleware/modelFallback.d.cts +2 -2
  10. package/dist/agents/middleware/modelFallback.d.cts.map +1 -1
  11. package/dist/agents/middleware/modelFallback.d.ts +2 -2
  12. package/dist/agents/middleware/modelFallback.d.ts.map +1 -1
  13. package/dist/agents/middleware/modelFallback.js.map +1 -1
  14. package/dist/agents/middleware/summarization.cjs +1 -1
  15. package/dist/agents/middleware/summarization.js +21 -21
  16. package/dist/agents/middleware/summarization.js.map +1 -1
  17. package/dist/agents/middleware/toolCallLimit.cjs +1 -1
  18. package/dist/agents/middleware/toolCallLimit.js +11 -11
  19. package/dist/agents/middleware/toolCallLimit.js.map +1 -1
  20. package/dist/agents/model.cjs.map +1 -1
  21. package/dist/agents/model.d.cts +9 -0
  22. package/dist/agents/model.d.cts.map +1 -0
  23. package/dist/agents/model.d.ts +9 -0
  24. package/dist/agents/model.d.ts.map +1 -0
  25. package/dist/agents/model.js.map +1 -1
  26. package/dist/agents/nodes/AgentNode.cjs +26 -14
  27. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  28. package/dist/agents/nodes/AgentNode.js +26 -14
  29. package/dist/agents/nodes/AgentNode.js.map +1 -1
  30. package/dist/agents/nodes/types.d.cts +9 -3
  31. package/dist/agents/nodes/types.d.cts.map +1 -1
  32. package/dist/agents/nodes/types.d.ts +9 -3
  33. package/dist/agents/nodes/types.d.ts.map +1 -1
  34. package/dist/agents/nodes/utils.cjs +10 -10
  35. package/dist/agents/nodes/utils.cjs.map +1 -1
  36. package/dist/agents/nodes/utils.js +3 -3
  37. package/dist/agents/nodes/utils.js.map +1 -1
  38. package/dist/agents/responses.cjs.map +1 -1
  39. package/dist/agents/responses.d.cts +3 -2
  40. package/dist/agents/responses.d.cts.map +1 -1
  41. package/dist/agents/responses.d.ts +3 -2
  42. package/dist/agents/responses.d.ts.map +1 -1
  43. package/dist/agents/responses.js.map +1 -1
  44. package/dist/agents/tests/utils.d.cts +0 -1
  45. package/dist/agents/tests/utils.d.cts.map +1 -1
  46. package/dist/agents/tests/utils.d.ts +0 -1
  47. package/dist/agents/tests/utils.d.ts.map +1 -1
  48. package/dist/agents/types.d.cts +4 -5
  49. package/dist/agents/types.d.cts.map +1 -1
  50. package/dist/agents/types.d.ts +4 -5
  51. package/dist/agents/types.d.ts.map +1 -1
  52. package/dist/agents/utils.cjs.map +1 -1
  53. package/dist/agents/utils.js.map +1 -1
  54. package/dist/agents/withAgentName.cjs.map +1 -1
  55. package/dist/agents/withAgentName.js.map +1 -1
  56. package/dist/browser.cjs +106 -0
  57. package/dist/browser.cjs.map +1 -1
  58. package/dist/browser.d.cts +29 -1
  59. package/dist/browser.d.ts +29 -1
  60. package/dist/browser.js +66 -1
  61. package/dist/browser.js.map +1 -1
  62. package/package.json +8 -8
@@ -1,7 +1,7 @@
1
1
  require("../../_virtual/_rolldown/runtime.cjs");
2
2
  let _langchain_langgraph = require("@langchain/langgraph");
3
3
  let _langchain_core_utils_types = require("@langchain/core/utils/types");
4
- let zod = require("zod");
4
+ let zod_v4 = require("zod/v4");
5
5
  //#region src/agents/nodes/utils.ts
6
6
  /**
7
7
  * Helper function to initialize middleware state defaults.
@@ -22,7 +22,7 @@ async function initializeMiddlewareStates(middlewareList, state) {
22
22
  const zodShape = {};
23
23
  for (const [key, field] of Object.entries(middleware.stateSchema.fields)) if (_langchain_langgraph.ReducedValue.isInstance(field)) zodShape[key] = field.inputSchema || field.valueSchema;
24
24
  else zodShape[key] = field;
25
- zodSchema = zod.z.object(zodShape);
25
+ zodSchema = zod_v4.z.object(zodShape);
26
26
  }
27
27
  const parseResult = await (0, _langchain_core_utils_types.interopSafeParseAsync)((0, _langchain_core_utils_types.interopZodObjectMakeFieldsOptional)(zodSchema, (key) => key.startsWith("_")), state);
28
28
  if (parseResult.success) {
@@ -46,20 +46,20 @@ async function initializeMiddlewareStates(middlewareList, state) {
46
46
  */
47
47
  function derivePrivateState(stateSchema) {
48
48
  const builtInStateSchema = {
49
- messages: zod.z.custom(() => []),
50
- structuredResponse: zod.z.any().optional()
49
+ messages: zod_v4.z.custom(() => []),
50
+ structuredResponse: zod_v4.z.any().optional()
51
51
  };
52
- if (!stateSchema) return zod.z.object(builtInStateSchema);
52
+ if (!stateSchema) return zod_v4.z.object(builtInStateSchema);
53
53
  let shape;
54
54
  if (_langchain_langgraph.StateSchema.isInstance(stateSchema)) {
55
55
  shape = {};
56
56
  for (const [key, field] of Object.entries(stateSchema.fields)) if (_langchain_langgraph.ReducedValue.isInstance(field)) shape[key] = field.inputSchema || field.valueSchema;
57
57
  else shape[key] = field;
58
- } else shape = stateSchema.shape;
58
+ } else shape = (0, _langchain_core_utils_types.getInteropZodObjectShape)(stateSchema);
59
59
  const privateShape = { ...builtInStateSchema };
60
60
  for (const [key, value] of Object.entries(shape)) if (key.startsWith("_")) privateShape[key] = value.optional();
61
61
  else privateShape[key] = value;
62
- return zod.z.object(privateShape);
62
+ return zod_v4.z.object(privateShape);
63
63
  }
64
64
  /**
65
65
  * Converts any supported schema type (ZodObject, StateSchema, AnnotationRoot) to a partial Zod object.
@@ -76,11 +76,11 @@ function toPartialZodObject(schema) {
76
76
  let fieldSchema;
77
77
  if (_langchain_langgraph.ReducedValue.isInstance(field)) fieldSchema = field.inputSchema || field.valueSchema;
78
78
  else fieldSchema = field;
79
- partialShape[key] = (0, _langchain_core_utils_types.isZodSchemaV4)(fieldSchema) ? fieldSchema.optional() : zod.z.any().optional();
79
+ partialShape[key] = (0, _langchain_core_utils_types.isZodSchemaV4)(fieldSchema) ? fieldSchema.optional() : zod_v4.z.any().optional();
80
80
  }
81
- return zod.z.object(partialShape);
81
+ return zod_v4.z.object(partialShape);
82
82
  }
83
- return zod.z.object({});
83
+ return zod_v4.z.object({});
84
84
  }
85
85
  function parseJumpToTarget(target) {
86
86
  if (!target) return;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","names":["StateSchema","ReducedValue","z","END"],"sources":["../../../src/agents/nodes/utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod\";\nimport { type BaseMessage } from \"@langchain/core/messages\";\nimport {\n interopSafeParseAsync,\n interopZodObjectMakeFieldsOptional,\n interopZodObjectPartial,\n isInteropZodObject,\n isZodSchemaV4,\n type InteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport type { StateDefinitionInit } from \"@langchain/langgraph\";\nimport { END, StateSchema, ReducedValue } from \"@langchain/langgraph\";\n\nimport type { JumpTo } from \"../types.js\";\nimport type { AgentMiddleware } from \"../middleware/types.js\";\n\n/**\n * Helper function to initialize middleware state defaults.\n * This is used to ensure all middleware state properties are initialized.\n *\n * Private properties (starting with _) are automatically made optional since\n * users cannot provide them when invoking the agent.\n */\nexport async function initializeMiddlewareStates(\n middlewareList: readonly AgentMiddleware[],\n state: unknown\n): Promise<Record<string, any>> {\n const middlewareStates: Record<string, any> = {};\n\n for (const middleware of middlewareList) {\n /**\n * skip middleware if it doesn't have a state schema\n */\n if (!middleware.stateSchema) {\n continue;\n }\n\n // Convert StateSchema to Zod object if needed\n let zodSchema = middleware.stateSchema;\n if (StateSchema.isInstance(middleware.stateSchema)) {\n const zodShape: Record<string, any> = {};\n for (const [key, field] of Object.entries(\n middleware.stateSchema.fields\n )) {\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n zodShape[key] = field.inputSchema || field.valueSchema;\n } else {\n zodShape[key] = field;\n }\n }\n zodSchema = z.object(zodShape);\n }\n\n // Create a modified schema where private properties are optional\n const modifiedSchema = interopZodObjectMakeFieldsOptional(\n zodSchema,\n (key) => key.startsWith(\"_\")\n );\n\n // Use safeParse with the modified schema\n const parseResult = await interopSafeParseAsync(modifiedSchema, state);\n if (parseResult.success) {\n Object.assign(middlewareStates, parseResult.data);\n continue;\n }\n\n /**\n * If safeParse fails, there are required public fields missing.\n * Note: Zod v3 uses message \"Required\", Zod v4 uses \"Invalid input: expected X, received undefined\"\n */\n const requiredFields = parseResult.error.issues\n .filter((issue) => issue.code === \"invalid_type\")\n .map((issue) => ` - ${issue.path.join(\".\")}: Required`)\n .join(\"\\n\");\n\n throw new Error(\n `Middleware \"${middleware.name}\" has required state fields that must be initialized:\\n` +\n `${requiredFields}\\n\\n` +\n `To fix this, either:\\n` +\n `1. Provide default values in your middleware's state schema using .default():\\n` +\n ` stateSchema: z.object({\\n` +\n ` myField: z.string().default(\"default value\")\\n` +\n ` })\\n\\n` +\n `2. Or make the fields optional using .optional():\\n` +\n ` stateSchema: z.object({\\n` +\n ` myField: z.string().optional()\\n` +\n ` })\\n\\n` +\n `3. Or ensure you pass these values when invoking the agent:\\n` +\n ` agent.invoke({\\n` +\n ` messages: [...],\\n` +\n ` ${parseResult.error.issues[0]?.path.join(\".\")}: \"value\"\\n` +\n ` })`\n );\n }\n\n return middlewareStates;\n}\n\n/**\n * Users can define private and public state for a middleware. Private state properties start with an underscore.\n * This function will return the private state properties from the state schema, making all of them optional.\n * @param stateSchema - The middleware state schema\n * @returns A new schema containing only the private properties (underscore-prefixed), all made optional\n */\nexport function derivePrivateState(\n stateSchema?: z.ZodObject<z.ZodRawShape> | StateSchema<any>\n): z.ZodObject<z.ZodRawShape> {\n const builtInStateSchema = {\n messages: z.custom<BaseMessage[]>(() => []),\n // Include optional structuredResponse so after_agent hooks can access/modify it\n structuredResponse: z.any().optional(),\n };\n\n if (!stateSchema) {\n return z.object(builtInStateSchema);\n }\n\n // Extract shape from either StateSchema or Zod object\n let shape: Record<string, any>;\n if (StateSchema.isInstance(stateSchema)) {\n // For StateSchema, extract Zod schemas from fields\n shape = {};\n for (const [key, field] of Object.entries(stateSchema.fields)) {\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n shape[key] = field.inputSchema || field.valueSchema;\n } else {\n shape[key] = field;\n }\n }\n } else {\n shape = stateSchema.shape;\n }\n\n const privateShape: Record<string, any> = { ...builtInStateSchema };\n\n // Filter properties that start with underscore and make them optional\n for (const [key, value] of Object.entries(shape)) {\n if (key.startsWith(\"_\")) {\n // Make the private property optional\n privateShape[key] = value.optional();\n } else {\n privateShape[key] = value;\n }\n }\n\n // Return a new schema with only private properties (all optional)\n return z.object(privateShape);\n}\n\n/**\n * Converts any supported schema type (ZodObject, StateSchema, AnnotationRoot) to a partial Zod object.\n * This is useful for parsing state loosely where all fields are optional.\n *\n * @param schema - The schema to convert (InteropZodObject, StateSchema, or AnnotationRoot)\n * @returns A partial Zod object schema where all fields are optional\n */\nexport function toPartialZodObject(\n schema: StateDefinitionInit\n): InteropZodObject {\n // Handle ZodObject directly\n if (isInteropZodObject(schema)) {\n return interopZodObjectPartial(schema);\n }\n\n // Handle StateSchema: convert fields to Zod shape, then make partial\n if (StateSchema.isInstance(schema)) {\n const partialShape: Record<string, any> = {};\n for (const [key, field] of Object.entries(schema.fields)) {\n let fieldSchema: unknown;\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n fieldSchema = field.inputSchema || field.valueSchema;\n } else {\n fieldSchema = field;\n }\n // Only call .optional() on Zod v4 schemas, otherwise use z.any()\n partialShape[key] = isZodSchemaV4(fieldSchema)\n ? (fieldSchema as any).optional()\n : z.any().optional();\n }\n return z.object(partialShape);\n }\n\n // Fallback: return empty object schema\n return z.object({});\n}\n\n/**\n * Parse `jumpTo` target from user facing labels to a LangGraph node names\n */\nexport function parseJumpToTarget(target: string): JumpTo;\nexport function parseJumpToTarget(target?: string): JumpTo | undefined {\n if (!target) {\n return undefined;\n }\n\n /**\n * if target is already a valid jump target, return it\n */\n if ([\"model_request\", \"tools\", END].includes(target)) {\n return target as JumpTo;\n }\n\n if (target === \"model\") {\n return \"model_request\";\n }\n if (target === \"tools\") {\n return \"tools\";\n }\n if (target === \"end\") {\n return END;\n }\n\n throw new Error(\n `Invalid jump target: ${target}, must be \"model\", \"tools\" or \"end\".`\n );\n}\n\n/**\n * TypeScript currently doesn't support types for `AbortSignal.any`\n * @see https://github.com/microsoft/TypeScript/issues/60695\n */\ndeclare const AbortSignal: {\n any(signals: AbortSignal[]): AbortSignal;\n};\n\n/**\n * `config` always contains a signal from LangGraphs Pregel class.\n * To ensure we acknowledge the abort signal from the user, we merge it\n * with the signal from the ToolNode.\n *\n * @param signals - The signals to merge.\n * @returns The merged signal.\n */\nexport function mergeAbortSignals(\n ...signals: (AbortSignal | undefined)[]\n): AbortSignal {\n return AbortSignal.any(\n signals.filter(\n (maybeSignal): maybeSignal is AbortSignal =>\n maybeSignal !== null &&\n maybeSignal !== undefined &&\n typeof maybeSignal === \"object\" &&\n \"aborted\" in maybeSignal &&\n typeof maybeSignal.aborted === \"boolean\"\n )\n );\n}\n"],"mappings":";;;;;;;;;;;;AAwBA,eAAsB,2BACpB,gBACA,OAC8B;CAC9B,MAAM,mBAAwC,EAAE;AAEhD,MAAK,MAAM,cAAc,gBAAgB;;;;AAIvC,MAAI,CAAC,WAAW,YACd;EAIF,IAAI,YAAY,WAAW;AAC3B,MAAIA,qBAAAA,YAAY,WAAW,WAAW,YAAY,EAAE;GAClD,MAAM,WAAgC,EAAE;AACxC,QAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAChC,WAAW,YAAY,OACxB,CACC,KAAIC,qBAAAA,aAAa,WAAW,MAAM,CAEhC,UAAS,OAAO,MAAM,eAAe,MAAM;OAE3C,UAAS,OAAO;AAGpB,eAAYC,IAAAA,EAAE,OAAO,SAAS;;EAUhC,MA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AAA,GAAA,4BAAA,yBAA+B,OAAO;AAIxC,KAAIF,qBAAAA,YAAY,WAAW,OAAO,EAAE;EAClC,MAAM,eAAoC,EAAE;AAC5C,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,OAAO,EAAE;GACxD,IAAI;AACJ,OAAIC,qBAAAA,aAAa,WAAW,MAAM,CAEhC,eAAc,MAAM,eAAe,MAAM;OAEzC,eAAc;AAGhB,gBAAa,QAAA,GAAA,4BAAA,eAAqB,YAAY,GACzC,YAAoB,UAAU,GAC/BC,IAAAA,EAAE,KAAK,CAAC,UAAU;;AAExB,SAAOA,IAAAA,EAAE,OAAO,aAAa;;AAI/B,QAAOA,IAAAA,EAAE,OAAO,EAAE,CAAC;;AAOrB,SAAgB,kBAAkB,QAAqC;AACrE,KAAI,CAAC,OACH;;;;AAMF,KAAI;EAAC;EAAiB;EAASC,qBAAAA;EAAI,CAAC,SAAS,OAAO,CAClD,QAAO;AAGT,KAAI,WAAW,QACb,QAAO;AAET,KAAI,WAAW,QACb,QAAO;AAET,KAAI,WAAW,MACb,QAAOA,qBAAAA;AAGT,OAAM,IAAI,MACR,wBAAwB,OAAO,sCAChC;;;;;;;;;;AAmBH,SAAgB,kBACd,GAAG,SACU;AACb,QAAO,YAAY,IACjB,QAAQ,QACL,gBACC,gBAAgB,QAChB,gBAAgB,KAAA,KAChB,OAAO,gBAAgB,YACvB,aAAa,eACb,OAAO,YAAY,YAAY,UAClC,CACF"}
1
+ {"version":3,"file":"utils.cjs","names":["StateSchema","ReducedValue","z","END"],"sources":["../../../src/agents/nodes/utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v4\";\nimport { type BaseMessage } from \"@langchain/core/messages\";\nimport {\n getInteropZodObjectShape,\n interopSafeParseAsync,\n interopZodObjectMakeFieldsOptional,\n interopZodObjectPartial,\n isInteropZodObject,\n isZodSchemaV4,\n type InteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport type { StateDefinitionInit } from \"@langchain/langgraph\";\nimport { END, StateSchema, ReducedValue } from \"@langchain/langgraph\";\n\nimport type { JumpTo } from \"../types.js\";\nimport type { AgentMiddleware } from \"../middleware/types.js\";\n\n/**\n * Helper function to initialize middleware state defaults.\n * This is used to ensure all middleware state properties are initialized.\n *\n * Private properties (starting with _) are automatically made optional since\n * users cannot provide them when invoking the agent.\n */\nexport async function initializeMiddlewareStates(\n middlewareList: readonly AgentMiddleware[],\n state: unknown\n): Promise<Record<string, any>> {\n const middlewareStates: Record<string, any> = {};\n\n for (const middleware of middlewareList) {\n /**\n * skip middleware if it doesn't have a state schema\n */\n if (!middleware.stateSchema) {\n continue;\n }\n\n // Convert StateSchema to Zod object if needed\n let zodSchema = middleware.stateSchema;\n if (StateSchema.isInstance(middleware.stateSchema)) {\n const zodShape: Record<string, any> = {};\n for (const [key, field] of Object.entries(\n middleware.stateSchema.fields\n )) {\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n zodShape[key] = field.inputSchema || field.valueSchema;\n } else {\n zodShape[key] = field;\n }\n }\n zodSchema = z.object(zodShape);\n }\n\n // Create a modified schema where private properties are optional\n const modifiedSchema = interopZodObjectMakeFieldsOptional(\n zodSchema,\n (key) => key.startsWith(\"_\")\n );\n\n // Use safeParse with the modified schema\n const parseResult = await interopSafeParseAsync(modifiedSchema, state);\n if (parseResult.success) {\n Object.assign(middlewareStates, parseResult.data);\n continue;\n }\n\n /**\n * If safeParse fails, there are required public fields missing.\n * Note: Zod v3 uses message \"Required\", Zod v4 uses \"Invalid input: expected X, received undefined\"\n */\n const requiredFields = parseResult.error.issues\n .filter((issue) => issue.code === \"invalid_type\")\n .map((issue) => ` - ${issue.path.join(\".\")}: Required`)\n .join(\"\\n\");\n\n throw new Error(\n `Middleware \"${middleware.name}\" has required state fields that must be initialized:\\n` +\n `${requiredFields}\\n\\n` +\n `To fix this, either:\\n` +\n `1. Provide default values in your middleware's state schema using .default():\\n` +\n ` stateSchema: z.object({\\n` +\n ` myField: z.string().default(\"default value\")\\n` +\n ` })\\n\\n` +\n `2. Or make the fields optional using .optional():\\n` +\n ` stateSchema: z.object({\\n` +\n ` myField: z.string().optional()\\n` +\n ` })\\n\\n` +\n `3. Or ensure you pass these values when invoking the agent:\\n` +\n ` agent.invoke({\\n` +\n ` messages: [...],\\n` +\n ` ${parseResult.error.issues[0]?.path.join(\".\")}: \"value\"\\n` +\n ` })`\n );\n }\n\n return middlewareStates;\n}\n\n/**\n * Users can define private and public state for a middleware. Private state properties start with an underscore.\n * This function will return the private state properties from the state schema, making all of them optional.\n * @param stateSchema - The middleware state schema\n * @returns A new schema containing only the private properties (underscore-prefixed), all made optional\n */\nexport function derivePrivateState(\n stateSchema?: InteropZodObject | StateSchema<any>\n): InteropZodObject {\n const builtInStateSchema = {\n messages: z.custom<BaseMessage[]>(() => []),\n // Include optional structuredResponse so after_agent hooks can access/modify it\n structuredResponse: z.any().optional(),\n };\n\n if (!stateSchema) {\n return z.object(builtInStateSchema);\n }\n\n // Extract shape from either StateSchema or Zod object\n let shape: Record<string, any>;\n if (StateSchema.isInstance(stateSchema)) {\n // For StateSchema, extract Zod schemas from fields\n shape = {};\n for (const [key, field] of Object.entries(stateSchema.fields)) {\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n shape[key] = field.inputSchema || field.valueSchema;\n } else {\n shape[key] = field;\n }\n }\n } else {\n shape = getInteropZodObjectShape(stateSchema);\n }\n\n const privateShape: Record<string, any> = { ...builtInStateSchema };\n\n // Filter properties that start with underscore and make them optional\n for (const [key, value] of Object.entries(shape)) {\n if (key.startsWith(\"_\")) {\n // Make the private property optional\n privateShape[key] = value.optional();\n } else {\n privateShape[key] = value;\n }\n }\n\n // Return a new schema with only private properties (all optional)\n return z.object(privateShape);\n}\n\n/**\n * Converts any supported schema type (ZodObject, StateSchema, AnnotationRoot) to a partial Zod object.\n * This is useful for parsing state loosely where all fields are optional.\n *\n * @param schema - The schema to convert (InteropZodObject, StateSchema, or AnnotationRoot)\n * @returns A partial Zod object schema where all fields are optional\n */\nexport function toPartialZodObject(\n schema: StateDefinitionInit\n): InteropZodObject {\n // Handle ZodObject directly\n if (isInteropZodObject(schema)) {\n return interopZodObjectPartial(schema);\n }\n\n // Handle StateSchema: convert fields to Zod shape, then make partial\n if (StateSchema.isInstance(schema)) {\n const partialShape: Record<string, any> = {};\n for (const [key, field] of Object.entries(schema.fields)) {\n let fieldSchema: unknown;\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n fieldSchema = field.inputSchema || field.valueSchema;\n } else {\n fieldSchema = field;\n }\n // Only call .optional() on Zod v4 schemas, otherwise use z.any()\n partialShape[key] = isZodSchemaV4(fieldSchema)\n ? (fieldSchema as any).optional()\n : z.any().optional();\n }\n return z.object(partialShape);\n }\n\n // Fallback: return empty object schema\n return z.object({});\n}\n\n/**\n * Parse `jumpTo` target from user facing labels to a LangGraph node names\n */\nexport function parseJumpToTarget(target: string): JumpTo;\nexport function parseJumpToTarget(target?: string): JumpTo | undefined {\n if (!target) {\n return undefined;\n }\n\n /**\n * if target is already a valid jump target, return it\n */\n if ([\"model_request\", \"tools\", END].includes(target)) {\n return target as JumpTo;\n }\n\n if (target === \"model\") {\n return \"model_request\";\n }\n if (target === \"tools\") {\n return \"tools\";\n }\n if (target === \"end\") {\n return END;\n }\n\n throw new Error(\n `Invalid jump target: ${target}, must be \"model\", \"tools\" or \"end\".`\n );\n}\n\n/**\n * TypeScript currently doesn't support types for `AbortSignal.any`\n * @see https://github.com/microsoft/TypeScript/issues/60695\n */\ndeclare const AbortSignal: {\n any(signals: AbortSignal[]): AbortSignal;\n};\n\n/**\n * `config` always contains a signal from LangGraphs Pregel class.\n * To ensure we acknowledge the abort signal from the user, we merge it\n * with the signal from the ToolNode.\n *\n * @param signals - The signals to merge.\n * @returns The merged signal.\n */\nexport function mergeAbortSignals(\n ...signals: (AbortSignal | undefined)[]\n): AbortSignal {\n return AbortSignal.any(\n signals.filter(\n (maybeSignal): maybeSignal is AbortSignal =>\n maybeSignal !== null &&\n maybeSignal !== undefined &&\n typeof maybeSignal === \"object\" &&\n \"aborted\" in maybeSignal &&\n typeof maybeSignal.aborted === \"boolean\"\n )\n );\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,eAAsB,2BACpB,gBACA,OAC8B;CAC9B,MAAM,mBAAwC,EAAE;AAEhD,MAAK,MAAM,cAAc,gBAAgB;;;;AAIvC,MAAI,CAAC,WAAW,YACd;EAIF,IAAI,YAAY,WAAW;AAC3B,MAAIA,qBAAAA,YAAY,WAAW,WAAW,YAAY,EAAE;GAClD,MAAM,WAAgC,EAAE;AACxC,QAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAChC,WAAW,YAAY,OACxB,CACC,KAAIC,qBAAAA,aAAa,WAAW,MAAM,CAEhC,UAAS,OAAO,MAAM,eAAe,MAAM;OAE3C,UAAS,OAAO;AAGpB,eAAYC,OAAAA,EAAE,OAAO,SAAS;;EAUhC,MAAM,cAAc,OAAA,GAAA,4BAAA,wBAAA,GAAA,4BAAA,oCALlB,YACC,QAAQ,IAAI,WAAW,IAAI,CAC7B,EAG+D,MAAM;AACtE,MAAI,YAAY,SAAS;AACvB,UAAO,OAAO,kBAAkB,YAAY,KAAK;AACjD;;;;;;EAOF,MAAM,iBAAiB,YAAY,MAAM,OACtC,QAAQ,UAAU,MAAM,SAAS,eAAe,CAChD,KAAK,UAAU,OAAO,MAAM,KAAK,KAAK,IAAI,CAAC,YAAY,CACvD,KAAK,KAAK;AAEb,QAAM,IAAI,MACR,eAAe,WAAW,KAAK,yDAC1B,eAAe,4aAaV,YAAY,MAAM,OAAO,IAAI,KAAK,KAAK,IAAI,CAAC,kBAEvD;;AAGH,QAAO;;;;;;;;AAST,SAAgB,mBACd,aACkB;CAClB,MAAM,qBAAqB;EACzB,UAAUA,OAAAA,EAAE,aAA4B,EAAE,CAAC;EAE3C,oBA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AAAA;EAAI,CAAC,SAAS,OAAO,CAClD,QAAO;AAGT,KAAI,WAAW,QACb,QAAO;AAET,KAAI,WAAW,QACb,QAAO;AAET,KAAI,WAAW,MACb,QAAOA,qBAAAA;AAGT,OAAM,IAAI,MACR,wBAAwB,OAAO,sCAChC;;;;;;;;;;AAmBH,SAAgB,kBACd,GAAG,SACU;AACb,QAAO,YAAY,IACjB,QAAQ,QACL,gBACC,gBAAgB,QAChB,gBAAgB,KAAA,KAChB,OAAO,gBAAgB,YACvB,aAAa,eACb,OAAO,YAAY,YAAY,UAClC,CACF"}
@@ -1,6 +1,6 @@
1
1
  import { END, ReducedValue, StateSchema } from "@langchain/langgraph";
2
- import { interopSafeParseAsync, interopZodObjectMakeFieldsOptional, interopZodObjectPartial, isInteropZodObject, isZodSchemaV4 } from "@langchain/core/utils/types";
3
- import { z } from "zod";
2
+ import { getInteropZodObjectShape, interopSafeParseAsync, interopZodObjectMakeFieldsOptional, interopZodObjectPartial, isInteropZodObject, isZodSchemaV4 } from "@langchain/core/utils/types";
3
+ import { z } from "zod/v4";
4
4
  //#region src/agents/nodes/utils.ts
5
5
  /**
6
6
  * Helper function to initialize middleware state defaults.
@@ -54,7 +54,7 @@ function derivePrivateState(stateSchema) {
54
54
  shape = {};
55
55
  for (const [key, field] of Object.entries(stateSchema.fields)) if (ReducedValue.isInstance(field)) shape[key] = field.inputSchema || field.valueSchema;
56
56
  else shape[key] = field;
57
- } else shape = stateSchema.shape;
57
+ } else shape = getInteropZodObjectShape(stateSchema);
58
58
  const privateShape = { ...builtInStateSchema };
59
59
  for (const [key, value] of Object.entries(shape)) if (key.startsWith("_")) privateShape[key] = value.optional();
60
60
  else privateShape[key] = value;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":[],"sources":["../../../src/agents/nodes/utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod\";\nimport { type BaseMessage } from \"@langchain/core/messages\";\nimport {\n interopSafeParseAsync,\n interopZodObjectMakeFieldsOptional,\n interopZodObjectPartial,\n isInteropZodObject,\n isZodSchemaV4,\n type InteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport type { StateDefinitionInit } from \"@langchain/langgraph\";\nimport { END, StateSchema, ReducedValue } from \"@langchain/langgraph\";\n\nimport type { JumpTo } from \"../types.js\";\nimport type { AgentMiddleware } from \"../middleware/types.js\";\n\n/**\n * Helper function to initialize middleware state defaults.\n * This is used to ensure all middleware state properties are initialized.\n *\n * Private properties (starting with _) are automatically made optional since\n * users cannot provide them when invoking the agent.\n */\nexport async function initializeMiddlewareStates(\n middlewareList: readonly AgentMiddleware[],\n state: unknown\n): Promise<Record<string, any>> {\n const middlewareStates: Record<string, any> = {};\n\n for (const middleware of middlewareList) {\n /**\n * skip middleware if it doesn't have a state schema\n */\n if (!middleware.stateSchema) {\n continue;\n }\n\n // Convert StateSchema to Zod object if needed\n let zodSchema = middleware.stateSchema;\n if (StateSchema.isInstance(middleware.stateSchema)) {\n const zodShape: Record<string, any> = {};\n for (const [key, field] of Object.entries(\n middleware.stateSchema.fields\n )) {\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n zodShape[key] = field.inputSchema || field.valueSchema;\n } else {\n zodShape[key] = field;\n }\n }\n zodSchema = z.object(zodShape);\n }\n\n // Create a modified schema where private properties are optional\n const modifiedSchema = interopZodObjectMakeFieldsOptional(\n zodSchema,\n (key) => key.startsWith(\"_\")\n );\n\n // Use safeParse with the modified schema\n const parseResult = await interopSafeParseAsync(modifiedSchema, state);\n if (parseResult.success) {\n Object.assign(middlewareStates, parseResult.data);\n continue;\n }\n\n /**\n * If safeParse fails, there are required public fields missing.\n * Note: Zod v3 uses message \"Required\", Zod v4 uses \"Invalid input: expected X, received undefined\"\n */\n const requiredFields = parseResult.error.issues\n .filter((issue) => issue.code === \"invalid_type\")\n .map((issue) => ` - ${issue.path.join(\".\")}: Required`)\n .join(\"\\n\");\n\n throw new Error(\n `Middleware \"${middleware.name}\" has required state fields that must be initialized:\\n` +\n `${requiredFields}\\n\\n` +\n `To fix this, either:\\n` +\n `1. Provide default values in your middleware's state schema using .default():\\n` +\n ` stateSchema: z.object({\\n` +\n ` myField: z.string().default(\"default value\")\\n` +\n ` })\\n\\n` +\n `2. Or make the fields optional using .optional():\\n` +\n ` stateSchema: z.object({\\n` +\n ` myField: z.string().optional()\\n` +\n ` })\\n\\n` +\n `3. Or ensure you pass these values when invoking the agent:\\n` +\n ` agent.invoke({\\n` +\n ` messages: [...],\\n` +\n ` ${parseResult.error.issues[0]?.path.join(\".\")}: \"value\"\\n` +\n ` })`\n );\n }\n\n return middlewareStates;\n}\n\n/**\n * Users can define private and public state for a middleware. Private state properties start with an underscore.\n * This function will return the private state properties from the state schema, making all of them optional.\n * @param stateSchema - The middleware state schema\n * @returns A new schema containing only the private properties (underscore-prefixed), all made optional\n */\nexport function derivePrivateState(\n stateSchema?: z.ZodObject<z.ZodRawShape> | StateSchema<any>\n): z.ZodObject<z.ZodRawShape> {\n const builtInStateSchema = {\n messages: z.custom<BaseMessage[]>(() => []),\n // Include optional structuredResponse so after_agent hooks can access/modify it\n structuredResponse: z.any().optional(),\n };\n\n if (!stateSchema) {\n return z.object(builtInStateSchema);\n }\n\n // Extract shape from either StateSchema or Zod object\n let shape: Record<string, any>;\n if (StateSchema.isInstance(stateSchema)) {\n // For StateSchema, extract Zod schemas from fields\n shape = {};\n for (const [key, field] of Object.entries(stateSchema.fields)) {\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n shape[key] = field.inputSchema || field.valueSchema;\n } else {\n shape[key] = field;\n }\n }\n } else {\n shape = stateSchema.shape;\n }\n\n const privateShape: Record<string, any> = { ...builtInStateSchema };\n\n // Filter properties that start with underscore and make them optional\n for (const [key, value] of Object.entries(shape)) {\n if (key.startsWith(\"_\")) {\n // Make the private property optional\n privateShape[key] = value.optional();\n } else {\n privateShape[key] = value;\n }\n }\n\n // Return a new schema with only private properties (all optional)\n return z.object(privateShape);\n}\n\n/**\n * Converts any supported schema type (ZodObject, StateSchema, AnnotationRoot) to a partial Zod object.\n * This is useful for parsing state loosely where all fields are optional.\n *\n * @param schema - The schema to convert (InteropZodObject, StateSchema, or AnnotationRoot)\n * @returns A partial Zod object schema where all fields are optional\n */\nexport function toPartialZodObject(\n schema: StateDefinitionInit\n): InteropZodObject {\n // Handle ZodObject directly\n if (isInteropZodObject(schema)) {\n return interopZodObjectPartial(schema);\n }\n\n // Handle StateSchema: convert fields to Zod shape, then make partial\n if (StateSchema.isInstance(schema)) {\n const partialShape: Record<string, any> = {};\n for (const [key, field] of Object.entries(schema.fields)) {\n let fieldSchema: unknown;\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n fieldSchema = field.inputSchema || field.valueSchema;\n } else {\n fieldSchema = field;\n }\n // Only call .optional() on Zod v4 schemas, otherwise use z.any()\n partialShape[key] = isZodSchemaV4(fieldSchema)\n ? (fieldSchema as any).optional()\n : z.any().optional();\n }\n return z.object(partialShape);\n }\n\n // Fallback: return empty object schema\n return z.object({});\n}\n\n/**\n * Parse `jumpTo` target from user facing labels to a LangGraph node names\n */\nexport function parseJumpToTarget(target: string): JumpTo;\nexport function parseJumpToTarget(target?: string): JumpTo | undefined {\n if (!target) {\n return undefined;\n }\n\n /**\n * if target is already a valid jump target, return it\n */\n if ([\"model_request\", \"tools\", END].includes(target)) {\n return target as JumpTo;\n }\n\n if (target === \"model\") {\n return \"model_request\";\n }\n if (target === \"tools\") {\n return \"tools\";\n }\n if (target === \"end\") {\n return END;\n }\n\n throw new Error(\n `Invalid jump target: ${target}, must be \"model\", \"tools\" or \"end\".`\n );\n}\n\n/**\n * TypeScript currently doesn't support types for `AbortSignal.any`\n * @see https://github.com/microsoft/TypeScript/issues/60695\n */\ndeclare const AbortSignal: {\n any(signals: AbortSignal[]): AbortSignal;\n};\n\n/**\n * `config` always contains a signal from LangGraphs Pregel class.\n * To ensure we acknowledge the abort signal from the user, we merge it\n * with the signal from the ToolNode.\n *\n * @param signals - The signals to merge.\n * @returns The merged signal.\n */\nexport function mergeAbortSignals(\n ...signals: (AbortSignal | undefined)[]\n): AbortSignal {\n return AbortSignal.any(\n signals.filter(\n (maybeSignal): maybeSignal is AbortSignal =>\n maybeSignal !== null &&\n maybeSignal !== undefined &&\n typeof maybeSignal === \"object\" &&\n \"aborted\" in maybeSignal &&\n typeof maybeSignal.aborted === \"boolean\"\n )\n );\n}\n"],"mappings":";;;;;;;;;;;AAwBA,eAAsB,2BACpB,gBACA,OAC8B;CAC9B,MAAM,mBAAwC,EAAE;AAEhD,MAAK,MAAM,cAAc,gBAAgB;;;;AAIvC,MAAI,CAAC,WAAW,YACd;EAIF,IAAI,YAAY,WAAW;AAC3B,MAAI,YAAY,WAAW,WAAW,YAAY,EAAE;GAClD,MAAM,WAAgC,EAAE;AACxC,QAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAChC,WAAW,YAAY,OACxB,CACC,KAAI,aAAa,WAAW,MAAM,CAEhC,UAAS,OAAO,MAAM,eAAe,MAAM;OAE3C,UAAS,OAAO;AAGpB,eAAY,EAAE,OAAO,SAAS;;EAUhC,MAAM,cAAc,MAAM,sBANH,mCACrB,YACC,QAAQ,IAAI,WAAW,IAAI,CAC7B,EAG+D,MAAM;AACtE,MAAI,YAAY,SAAS;AACvB,UAAO,OAAO,kBAAkB,YAAY,KAAK;AACjD;;;;;;EAOF,MAAM,iBAAiB,YAAY,MAAM,OACtC,QAAQ,UAAU,MAAM,SAAS,eAAe,CAChD,KAAK,UAAU,OAAO,MAAM,KAAK,KAAK,IAAI,CAAC,YAAY,CACvD,KAAK,KAAK;AAEb,QAAM,IAAI,MACR,eAAe,WAAW,KAAK,yDAC1B,eAAe,4aAaV,YAAY,MAAM,OAAO,IAAI,KAAK,KAAK,IAAI,CAAC,kBAEvD;;AAGH,QAAO;;;;;;;;AAST,SAAgB,mBACd,aAC4B;CAC5B,MA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AAET,KAAI,WAAW,MACb,QAAO;AAGT,OAAM,IAAI,MACR,wBAAwB,OAAO,sCAChC;;;;;;;;;;AAmBH,SAAgB,kBACd,GAAG,SACU;AACb,QAAO,YAAY,IACjB,QAAQ,QACL,gBACC,gBAAgB,QAChB,gBAAgB,KAAA,KAChB,OAAO,gBAAgB,YACvB,aAAa,eACb,OAAO,YAAY,YAAY,UAClC,CACF"}
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../../../src/agents/nodes/utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v4\";\nimport { type BaseMessage } from \"@langchain/core/messages\";\nimport {\n getInteropZodObjectShape,\n interopSafeParseAsync,\n interopZodObjectMakeFieldsOptional,\n interopZodObjectPartial,\n isInteropZodObject,\n isZodSchemaV4,\n type InteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport type { StateDefinitionInit } from \"@langchain/langgraph\";\nimport { END, StateSchema, ReducedValue } from \"@langchain/langgraph\";\n\nimport type { JumpTo } from \"../types.js\";\nimport type { AgentMiddleware } from \"../middleware/types.js\";\n\n/**\n * Helper function to initialize middleware state defaults.\n * This is used to ensure all middleware state properties are initialized.\n *\n * Private properties (starting with _) are automatically made optional since\n * users cannot provide them when invoking the agent.\n */\nexport async function initializeMiddlewareStates(\n middlewareList: readonly AgentMiddleware[],\n state: unknown\n): Promise<Record<string, any>> {\n const middlewareStates: Record<string, any> = {};\n\n for (const middleware of middlewareList) {\n /**\n * skip middleware if it doesn't have a state schema\n */\n if (!middleware.stateSchema) {\n continue;\n }\n\n // Convert StateSchema to Zod object if needed\n let zodSchema = middleware.stateSchema;\n if (StateSchema.isInstance(middleware.stateSchema)) {\n const zodShape: Record<string, any> = {};\n for (const [key, field] of Object.entries(\n middleware.stateSchema.fields\n )) {\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n zodShape[key] = field.inputSchema || field.valueSchema;\n } else {\n zodShape[key] = field;\n }\n }\n zodSchema = z.object(zodShape);\n }\n\n // Create a modified schema where private properties are optional\n const modifiedSchema = interopZodObjectMakeFieldsOptional(\n zodSchema,\n (key) => key.startsWith(\"_\")\n );\n\n // Use safeParse with the modified schema\n const parseResult = await interopSafeParseAsync(modifiedSchema, state);\n if (parseResult.success) {\n Object.assign(middlewareStates, parseResult.data);\n continue;\n }\n\n /**\n * If safeParse fails, there are required public fields missing.\n * Note: Zod v3 uses message \"Required\", Zod v4 uses \"Invalid input: expected X, received undefined\"\n */\n const requiredFields = parseResult.error.issues\n .filter((issue) => issue.code === \"invalid_type\")\n .map((issue) => ` - ${issue.path.join(\".\")}: Required`)\n .join(\"\\n\");\n\n throw new Error(\n `Middleware \"${middleware.name}\" has required state fields that must be initialized:\\n` +\n `${requiredFields}\\n\\n` +\n `To fix this, either:\\n` +\n `1. Provide default values in your middleware's state schema using .default():\\n` +\n ` stateSchema: z.object({\\n` +\n ` myField: z.string().default(\"default value\")\\n` +\n ` })\\n\\n` +\n `2. Or make the fields optional using .optional():\\n` +\n ` stateSchema: z.object({\\n` +\n ` myField: z.string().optional()\\n` +\n ` })\\n\\n` +\n `3. Or ensure you pass these values when invoking the agent:\\n` +\n ` agent.invoke({\\n` +\n ` messages: [...],\\n` +\n ` ${parseResult.error.issues[0]?.path.join(\".\")}: \"value\"\\n` +\n ` })`\n );\n }\n\n return middlewareStates;\n}\n\n/**\n * Users can define private and public state for a middleware. Private state properties start with an underscore.\n * This function will return the private state properties from the state schema, making all of them optional.\n * @param stateSchema - The middleware state schema\n * @returns A new schema containing only the private properties (underscore-prefixed), all made optional\n */\nexport function derivePrivateState(\n stateSchema?: InteropZodObject | StateSchema<any>\n): InteropZodObject {\n const builtInStateSchema = {\n messages: z.custom<BaseMessage[]>(() => []),\n // Include optional structuredResponse so after_agent hooks can access/modify it\n structuredResponse: z.any().optional(),\n };\n\n if (!stateSchema) {\n return z.object(builtInStateSchema);\n }\n\n // Extract shape from either StateSchema or Zod object\n let shape: Record<string, any>;\n if (StateSchema.isInstance(stateSchema)) {\n // For StateSchema, extract Zod schemas from fields\n shape = {};\n for (const [key, field] of Object.entries(stateSchema.fields)) {\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n shape[key] = field.inputSchema || field.valueSchema;\n } else {\n shape[key] = field;\n }\n }\n } else {\n shape = getInteropZodObjectShape(stateSchema);\n }\n\n const privateShape: Record<string, any> = { ...builtInStateSchema };\n\n // Filter properties that start with underscore and make them optional\n for (const [key, value] of Object.entries(shape)) {\n if (key.startsWith(\"_\")) {\n // Make the private property optional\n privateShape[key] = value.optional();\n } else {\n privateShape[key] = value;\n }\n }\n\n // Return a new schema with only private properties (all optional)\n return z.object(privateShape);\n}\n\n/**\n * Converts any supported schema type (ZodObject, StateSchema, AnnotationRoot) to a partial Zod object.\n * This is useful for parsing state loosely where all fields are optional.\n *\n * @param schema - The schema to convert (InteropZodObject, StateSchema, or AnnotationRoot)\n * @returns A partial Zod object schema where all fields are optional\n */\nexport function toPartialZodObject(\n schema: StateDefinitionInit\n): InteropZodObject {\n // Handle ZodObject directly\n if (isInteropZodObject(schema)) {\n return interopZodObjectPartial(schema);\n }\n\n // Handle StateSchema: convert fields to Zod shape, then make partial\n if (StateSchema.isInstance(schema)) {\n const partialShape: Record<string, any> = {};\n for (const [key, field] of Object.entries(schema.fields)) {\n let fieldSchema: unknown;\n if (ReducedValue.isInstance(field)) {\n // For ReducedValue, use inputSchema if available, otherwise valueSchema\n fieldSchema = field.inputSchema || field.valueSchema;\n } else {\n fieldSchema = field;\n }\n // Only call .optional() on Zod v4 schemas, otherwise use z.any()\n partialShape[key] = isZodSchemaV4(fieldSchema)\n ? (fieldSchema as any).optional()\n : z.any().optional();\n }\n return z.object(partialShape);\n }\n\n // Fallback: return empty object schema\n return z.object({});\n}\n\n/**\n * Parse `jumpTo` target from user facing labels to a LangGraph node names\n */\nexport function parseJumpToTarget(target: string): JumpTo;\nexport function parseJumpToTarget(target?: string): JumpTo | undefined {\n if (!target) {\n return undefined;\n }\n\n /**\n * if target is already a valid jump target, return it\n */\n if ([\"model_request\", \"tools\", END].includes(target)) {\n return target as JumpTo;\n }\n\n if (target === \"model\") {\n return \"model_request\";\n }\n if (target === \"tools\") {\n return \"tools\";\n }\n if (target === \"end\") {\n return END;\n }\n\n throw new Error(\n `Invalid jump target: ${target}, must be \"model\", \"tools\" or \"end\".`\n );\n}\n\n/**\n * TypeScript currently doesn't support types for `AbortSignal.any`\n * @see https://github.com/microsoft/TypeScript/issues/60695\n */\ndeclare const AbortSignal: {\n any(signals: AbortSignal[]): AbortSignal;\n};\n\n/**\n * `config` always contains a signal from LangGraphs Pregel class.\n * To ensure we acknowledge the abort signal from the user, we merge it\n * with the signal from the ToolNode.\n *\n * @param signals - The signals to merge.\n * @returns The merged signal.\n */\nexport function mergeAbortSignals(\n ...signals: (AbortSignal | undefined)[]\n): AbortSignal {\n return AbortSignal.any(\n signals.filter(\n (maybeSignal): maybeSignal is AbortSignal =>\n maybeSignal !== null &&\n maybeSignal !== undefined &&\n typeof maybeSignal === \"object\" &&\n \"aborted\" in maybeSignal &&\n typeof maybeSignal.aborted === \"boolean\"\n )\n );\n}\n"],"mappings":";;;;;;;;;;;AAyBA,eAAsB,2BACpB,gBACA,OAC8B;CAC9B,MAAM,mBAAwC,EAAE;AAEhD,MAAK,MAAM,cAAc,gBAAgB;;;;AAIvC,MAAI,CAAC,WAAW,YACd;EAIF,IAAI,YAAY,WAAW;AAC3B,MAAI,YAAY,WAAW,WAAW,YAAY,EAAE;GAClD,MAAM,WAAgC,EAAE;AACxC,QAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAChC,WAAW,YAAY,OACxB,CACC,KAAI,aAAa,WAAW,MAAM,CAEhC,UAAS,OAAO,MAAM,eAAe,MAAM;OAE3C,UAAS,OAAO;AAGpB,eAAY,EAAE,OAAO,SAAS;;EAUhC,MAAM,cAAc,MAAM,sBANH,mCACrB,YACC,QAAQ,IAAI,WAAW,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AO,EAAE;GACxD,IAAI;AACJ,OAAI,aAAa,WAAW,MAAM,CAEhC,eAAc,MAAM,eAAe,MAAM;OAEzC,eAAc;AAGhB,gBAAa,OAAO,cAAc,YAAY,GACzC,YAAoB,UAAU,GAC/B,EAAE,KAAK,CAAC,UAAU;;AAExB,SAAO,EAAE,OAAO,aAAa;;AAI/B,QAAO,EAAE,OAAO,EAAE,CAAC;;AAOrB,SAAgB,kBAAkB,QAAqC;AACrE,KAAI,CAAC,OACH;;;;AAMF,KAAI;EAAC;EAAiB;EAAS;EAAI,CAAC,SAAS,OAAO,CAClD,QAAO;AAGT,KAAI,WAAW,QACb,QAAO;AAET,KAAI,WAAW,QACb,QAAO;AAET,KAAI,WAAW,MACb,QAAO;AAGT,OAAM,IAAI,MACR,wBAAwB,OAAO,sCAChC;;;;;;;;;;AAmBH,SAAgB,kBACd,GAAG,SACU;AACb,QAAO,YAAY,IACjB,QAAQ,QACL,gBACC,gBAAgB,QAChB,gBAAgB,KAAA,KAChB,OAAO,gBAAgB,YACvB,aAAa,eACb,OAAO,YAAY,YAAY,UAClC,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"responses.cjs","names":["Validator","StructuredOutputParsingError","isBaseChatModel"],"sources":["../../src/agents/responses.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n InteropZodObject,\n isInteropZodSchema,\n InteropZodType,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { toJsonSchema, Validator } from \"@langchain/core/utils/json_schema\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport {\n type SerializableSchema,\n isSerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\nimport { isBaseChatModel } from \"./model.js\";\n\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n\n/**\n * Default value for strict mode in providerStrategy.\n *\n * When using providerStrategy with json_schema response format, OpenAI's parse() method\n * requires all function tools to have strict: true. This ensures the model's output\n * exactly matches the provided JSON schema.\n *\n * @see https://platform.openai.com/docs/guides/structured-outputs\n */\nconst PROVIDER_STRATEGY_DEFAULT_STRICT = true;\n\n/**\n * This is a global counter for generating unique names for tools.\n */\nlet bindingIdentifier = 0;\n\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport class ToolStrategy<_T = unknown> {\n private constructor(\n /**\n * The original JSON Schema provided for structured output\n */\n public readonly schema: Record<string, unknown>,\n\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n public readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n },\n\n /**\n * The options to use for the tool output.\n */\n public readonly options?: ToolStrategyOptions\n ) {}\n\n get name() {\n return this.tool.function.name;\n }\n\n static fromSchema<S extends InteropZodObject>(\n schema: S,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n\n static fromSchema(\n schema: SerializableSchema,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | SerializableSchema | Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<any> {\n /**\n * It is required for tools to have a name so we can map the tool call to the correct tool\n * when parsing the response.\n */\n function getFunctionName(name?: string) {\n return name ?? `extract-${++bindingIdentifier}`;\n }\n\n if (isSerializableSchema(schema) || isInteropZodSchema(schema)) {\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: {\n name: getFunctionName(asJsonSchema.title),\n strict: false,\n description:\n asJsonSchema.description ??\n \"Tool for extracting structured output from the model's response.\",\n parameters: asJsonSchema,\n },\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n let functionDefinition: FunctionDefinition;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n functionDefinition = schema as unknown as FunctionDefinition;\n } else {\n functionDefinition = {\n name: getFunctionName(schema.title as string),\n description: (schema.description as string) ?? \"\",\n parameters: schema.schema || (schema as Record<string, unknown>),\n };\n }\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: functionDefinition,\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown> {\n const validator = new Validator(this.schema);\n const result = validator.validate(toolArgs);\n if (!result.valid) {\n throw new StructuredOutputParsingError(\n this.name,\n result.errors.map((e) => e.error)\n );\n }\n return toolArgs;\n }\n}\n\nexport class ProviderStrategy<T = unknown> {\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?: T;\n\n /**\n * The schema to use for the provider strategy\n */\n public readonly schema: Record<string, unknown>;\n\n /**\n * Whether to use strict mode for the provider strategy\n */\n public readonly strict: boolean;\n\n private constructor(options: {\n schema: Record<string, unknown>;\n strict?: boolean;\n });\n private constructor(schema: Record<string, unknown>, strict?: boolean);\n private constructor(\n schemaOrOptions:\n | Record<string, unknown>\n | { schema: Record<string, unknown>; strict?: boolean },\n strict?: boolean\n ) {\n if (\n \"schema\" in schemaOrOptions &&\n typeof schemaOrOptions.schema === \"object\" &&\n schemaOrOptions.schema !== null &&\n !(\"type\" in schemaOrOptions)\n ) {\n const options = schemaOrOptions as {\n schema: Record<string, unknown>;\n strict?: boolean;\n };\n this.schema = options.schema;\n this.strict = options.strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT;\n } else {\n this.schema = schemaOrOptions as Record<string, unknown>;\n this.strict = strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT;\n }\n }\n\n static fromSchema<T>(\n schema: InteropZodType<T>,\n strict?: boolean\n ): ProviderStrategy<T>;\n\n static fromSchema(\n schema: SerializableSchema,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | SerializableSchema | Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<T> | ProviderStrategy<Record<string, unknown>> {\n const asJsonSchema = toJsonSchema(schema);\n return new ProviderStrategy(asJsonSchema, strict) as\n | ProviderStrategy<T>\n | ProviderStrategy<Record<string, unknown>>;\n }\n\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param response - The AI message response to parse\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage) {\n /**\n * Extract text content from the response.\n * Handles both string content and array content (e.g., from thinking models).\n */\n let textContent: string | undefined;\n\n if (typeof response.content === \"string\") {\n textContent = response.content;\n } else if (Array.isArray(response.content)) {\n /**\n * For thinking models, content is an array with thinking blocks and text blocks.\n * Extract the text from text blocks.\n */\n for (const block of response.content) {\n if (\n typeof block === \"object\" &&\n block !== null &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n typeof block.text === \"string\"\n ) {\n textContent = block.text;\n break; // Use the first text block found\n }\n }\n }\n\n // Return if no valid text content found\n if (!textContent || textContent === \"\") {\n return;\n }\n\n try {\n const content = JSON.parse(textContent);\n const validator = new Validator(this.schema);\n const result = validator.validate(content);\n if (!result.valid) {\n return;\n }\n\n return content;\n } catch {\n // no-op\n }\n }\n}\n\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport function transformResponseFormat(\n responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | SerializableSchema\n | SerializableSchema[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions,\n model?: LanguageModelLike\n): ResponseFormat[] {\n if (!responseFormat) {\n return [];\n }\n\n // Handle ResponseFormatUndefined case\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"__responseFormatUndefined\" in responseFormat\n ) {\n return [];\n }\n\n /**\n * If users provide an array, it should only contain raw schemas (Zod, Standard Schema or JSON schema),\n * not ToolStrategy or ProviderStrategy instances.\n */\n if (Array.isArray(responseFormat)) {\n /**\n * if every entry is a ToolStrategy or ProviderStrategy instance, return the array as is\n */\n if (\n responseFormat.every(\n (item) =>\n item instanceof ToolStrategy || item instanceof ProviderStrategy\n )\n ) {\n return responseFormat as unknown as ResponseFormat[];\n }\n\n /**\n * Check if all items are Standard Schema\n */\n if (responseFormat.every((item) => isSerializableSchema(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as SerializableSchema, options)\n );\n }\n\n /**\n * Check if all items are Zod schemas\n */\n if (responseFormat.every((item) => isInteropZodObject(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as InteropZodObject, options)\n );\n }\n\n /**\n * Check if all items are plain objects (JSON schema)\n */\n if (\n responseFormat.every(\n (item) =>\n typeof item === \"object\" &&\n item !== null &&\n !isInteropZodObject(item) &&\n !isSerializableSchema(item)\n )\n ) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as JsonSchemaFormat, options)\n );\n }\n\n throw new Error(\n `Invalid response format: list contains mixed types.\\n` +\n `All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`\n );\n }\n\n if (\n responseFormat instanceof ToolStrategy ||\n responseFormat instanceof ProviderStrategy\n ) {\n return [responseFormat];\n }\n\n const useProviderStrategy = hasSupportForJsonSchemaOutput(model);\n\n /**\n * `responseFormat` is a Standard Schema\n */\n if (isSerializableSchema(responseFormat)) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat)]\n : [ToolStrategy.fromSchema(responseFormat, options)];\n }\n\n /**\n * `responseFormat` is a Zod schema\n */\n if (isInteropZodObject(responseFormat)) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat)]\n : [ToolStrategy.fromSchema(responseFormat, options)];\n }\n\n /**\n * Handle plain object (JSON schema)\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"properties\" in responseFormat\n ) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat as JsonSchemaFormat)]\n : [ToolStrategy.fromSchema(responseFormat as JsonSchemaFormat, options)];\n }\n\n throw new Error(`Invalid response format: ${String(responseFormat)}`);\n}\n\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<\n ToolStrategy<any>\n> {\n _schemaType?: T;\n}\nexport type ToolStrategyError =\n | StructuredOutputParsingError\n | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n *\n * @default true\n */\n handleError?:\n | boolean\n | string\n | ((error: ToolStrategyError) => Promise<string> | string);\n}\n\nexport function toolStrategy<T extends InteropZodType<any>>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function toolStrategy<T extends readonly InteropZodType<any>[]>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<\n { [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]\n>;\nexport function toolStrategy(\n responseFormat: SerializableSchema,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: SerializableSchema[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\n\n/**\n * Creates a tool strategy for structured output using function calling.\n *\n * This function configures structured output by converting schemas into function tools that\n * the model calls. Unlike `providerStrategy`, which uses native JSON schema support,\n * `toolStrategy` works with any model that supports function calling, making it more\n * widely compatible across providers and model versions.\n *\n * The model will call a function with arguments matching your schema, and the agent will\n * extract and validate the structured output from the tool call. This approach is automatically\n * used when your model doesn't support native JSON schema output.\n *\n * @param responseFormat - The schema(s) to enforce. Can be a single Zod schema, a Standard Schema\n * (e.g., Valibot, ArkType, TypeBox), a JSON schema object, or arrays of any of these.\n * @param options - Optional configuration for the tool strategy\n * @param options.handleError - How to handle errors when the model calls multiple structured output tools\n * or when the output doesn't match the schema. Defaults to `true` (auto-retry). Can be `false` (throw),\n * a `string` (retry with message), or a `function` (custom handler).\n * @param options.toolMessageContent - Custom message content to include in conversation history\n * when structured output is generated via tool call\n * @returns A `TypedToolStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { toolStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: toolStrategy(\n * z.object({\n * answer: z.string(),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Multiple schemas - model can choose which one to use\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: toolStrategy([\n * z.object({ name: z.string(), age: z.number() }),\n * z.object({ email: z.string(), phone: z.string() }),\n * ]),\n * });\n * ```\n */\nexport function toolStrategy(\n responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | SerializableSchema\n | SerializableSchema[]\n | JsonSchemaFormat\n | JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy {\n return transformResponseFormat(responseFormat, options) as TypedToolStrategy;\n}\n\n/**\n * Creates a provider strategy for structured output using native JSON schema support.\n *\n * This function is used to configure structured output for agents when the underlying model\n * supports native JSON schema output (e.g., OpenAI's `gpt-4o`, `gpt-4o-mini`, and newer models).\n * Unlike `toolStrategy`, which uses function calling to extract structured output, `providerStrategy`\n * leverages the provider's native structured output capabilities, resulting in more efficient\n * and reliable schema enforcement.\n *\n * When used with a model that supports JSON schema output, the model will return responses\n * that directly conform to the provided schema without requiring tool calls. This is the\n * recommended approach for structured output when your model supports it.\n *\n * @param responseFormat - The schema to enforce, either a Zod schema, a Standard Schema (e.g., Valibot, ArkType, TypeBox), a JSON schema object, or an options object with `schema` and optional `strict` flag\n * @returns A `ProviderStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { providerStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy(\n * z.object({\n * answer: z.string().describe(\"The answer to the question\"),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Using strict mode for stricter schema enforcement\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy({\n * schema: z.object({\n * name: z.string(),\n * age: z.number(),\n * }),\n * strict: true\n * }),\n * });\n * ```\n */\nexport function providerStrategy<T extends InteropZodType<unknown>>(\n responseFormat: T | { schema: T; strict?: boolean }\n): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function providerStrategy(\n responseFormat:\n | SerializableSchema\n | { schema: SerializableSchema; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | JsonSchemaFormat\n | { schema: JsonSchemaFormat; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | InteropZodType<unknown>\n | SerializableSchema\n | JsonSchemaFormat\n | {\n schema: InteropZodType<unknown> | SerializableSchema | JsonSchemaFormat;\n strict?: boolean;\n }\n): ProviderStrategy<unknown> {\n /**\n * Handle options object format\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"schema\" in responseFormat &&\n !isInteropZodSchema(responseFormat) &&\n !isSerializableSchema(responseFormat) &&\n !(\"type\" in responseFormat)\n ) {\n const { schema, strict: strictFlag } = responseFormat as {\n schema: InteropZodType<unknown> | SerializableSchema | JsonSchemaFormat;\n strict?: boolean;\n };\n return ProviderStrategy.fromSchema(\n schema as InteropZodType<unknown>,\n strictFlag\n ) as ProviderStrategy<unknown>;\n }\n\n /**\n * Handle direct schema format\n */\n return ProviderStrategy.fromSchema(\n responseFormat as InteropZodType<unknown>\n ) as ProviderStrategy<unknown>;\n}\n\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type:\n | \"null\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"number\"\n | \"string\"\n | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n\n/**\n * Identifies the models that support JSON schema output by reading\n * the model's profile metadata.\n *\n * @param model - A resolved model instance to check. Callers should resolve\n * string model names and ConfigurableModel wrappers before calling this.\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model?: LanguageModelLike\n): boolean {\n if (\n !model ||\n !isBaseChatModel(model) ||\n !(\"profile\" in model) ||\n typeof model.profile !== \"object\" ||\n !model.profile\n ) {\n return false;\n }\n\n return (\n \"structuredOutput\" in model.profile &&\n model.profile.structuredOutput === true\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAwCA,MAAM,mCAAmC;;;;AAKzC,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CACtC,YAIE,QAKA,MAQA,SACA;AAdgB,OAAA,SAAA;AAKA,OAAA,OAAA;AAQA,OAAA,UAAA;;CAGlB,IAAI,OAAO;AACT,SAAO,KAAK,KAAK,SAAS;;CAkB5B,OAAO,WACL,QACA,eACmB;;;;;EAKnB,SAAS,gBAAgB,MAAe;AACtC,UAAO,QAAQ,WAAW,EAAE;;AAG9B,OAAA,GAAA,sCAAA,sBAAyB,OAAO,KAAA,GAAA,4BAAA,oBAAuB,OAAO,EAAE;GAC9D,MAAM,gBAAA,GAAA,kCAAA,cAA4B,OAAO;AAYzC,UAAO,IAAI,aAAa,cAXX;IACX,MAAM;IACN,UAAU;KACR,MAAM,gBAAgB,aAAa,MAAM;KACzC,QAAQ;KACR,aACE,aAAa,eACb;KACF,YAAY;KACb;IACF,EAC2C,cAAc;;EAG5D,IAAI;AACJ,MACE,OAAO,OAAO,SAAS,YACvB,OAAO,OAAO,eAAe,YAC7B,OAAO,cAAc,KAErB,sBAAqB;MAErB,sBAAqB;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mBAAmB,YAC1B,mBAAmB,QACnB,gBAAgB,eAEhB,QAAO,sBACH,CAAC,iBAAiB,WAAW,eAAmC,CAAC,GACjE,CAAC,aAAa,WAAW,gBAAoC,QAAQ,CAAC;AAG5E,OAAM,IAAI,MAAM,4BAA4B,OAAO,eAAe,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqHvE,SAAgB,aACd,gBAOA,SACmB;AACnB,QAAO,wBAAwB,gBAAgB,QAAQ;;AA+DzD,SAAgB,iBACd,gBAQ2B;;;;AAI3B,KACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,YAAY,kBACZ,EAAA,GAAA,4BAAA,oBAAoB,eAAe,IACnC,EAAA,GAAA,sCAAA,sBAAsB,eAAe,IACrC,EAAE,UAAU,iBACZ;EACA,MAAM,EAAE,QAAQ,QAAQ,eAAe;AAIvC,SAAO,iBAAiB,WACtB,QACA,WACD;;;;;AAMH,QAAO,iBAAiB,WACtB,eACD;;;;;;;;;;AAiCH,SAAgB,8BACd,OACS;AACT,KACE,CAAC,SACD,CAACE,cAAAA,gBAAgB,MAAM,IACvB,EAAE,aAAa,UACf,OAAO,MAAM,YAAY,YACzB,CAAC,MAAM,QAEP,QAAO;AAGT,QACE,sBAAsB,MAAM,WAC5B,MAAM,QAAQ,qBAAqB"}
1
+ {"version":3,"file":"responses.cjs","names":["Validator","StructuredOutputParsingError","isBaseChatModel"],"sources":["../../src/agents/responses.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n InteropZodObject,\n isInteropZodSchema,\n InteropZodType,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { toJsonSchema, Validator } from \"@langchain/core/utils/json_schema\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport {\n type SerializableSchema,\n isSerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\nimport { isBaseChatModel } from \"./model.js\";\nimport type { AgentLanguageModelLike as LanguageModelLike } from \"./model.js\";\n\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n\n/**\n * Default value for strict mode in providerStrategy.\n *\n * When using providerStrategy with json_schema response format, OpenAI's parse() method\n * requires all function tools to have strict: true. This ensures the model's output\n * exactly matches the provided JSON schema.\n *\n * @see https://platform.openai.com/docs/guides/structured-outputs\n */\nconst PROVIDER_STRATEGY_DEFAULT_STRICT = true;\n\n/**\n * This is a global counter for generating unique names for tools.\n */\nlet bindingIdentifier = 0;\n\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport class ToolStrategy<_T = unknown> {\n private constructor(\n /**\n * The original JSON Schema provided for structured output\n */\n public readonly schema: Record<string, unknown>,\n\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n public readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n },\n\n /**\n * The options to use for the tool output.\n */\n public readonly options?: ToolStrategyOptions\n ) {}\n\n get name() {\n return this.tool.function.name;\n }\n\n static fromSchema<S extends InteropZodObject>(\n schema: S,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n\n static fromSchema(\n schema: SerializableSchema,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | SerializableSchema | Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<any> {\n /**\n * It is required for tools to have a name so we can map the tool call to the correct tool\n * when parsing the response.\n */\n function getFunctionName(name?: string) {\n return name ?? `extract-${++bindingIdentifier}`;\n }\n\n if (isSerializableSchema(schema) || isInteropZodSchema(schema)) {\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: {\n name: getFunctionName(asJsonSchema.title),\n strict: false,\n description:\n asJsonSchema.description ??\n \"Tool for extracting structured output from the model's response.\",\n parameters: asJsonSchema,\n },\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n let functionDefinition: FunctionDefinition;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n functionDefinition = schema as unknown as FunctionDefinition;\n } else {\n functionDefinition = {\n name: getFunctionName(schema.title as string),\n description: (schema.description as string) ?? \"\",\n parameters: schema.schema || (schema as Record<string, unknown>),\n };\n }\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: functionDefinition,\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown> {\n const validator = new Validator(this.schema);\n const result = validator.validate(toolArgs);\n if (!result.valid) {\n throw new StructuredOutputParsingError(\n this.name,\n result.errors.map((e) => e.error)\n );\n }\n return toolArgs;\n }\n}\n\nexport class ProviderStrategy<T = unknown> {\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?: T;\n\n /**\n * The schema to use for the provider strategy\n */\n public readonly schema: Record<string, unknown>;\n\n /**\n * Whether to use strict mode for the provider strategy\n */\n public readonly strict: boolean;\n\n private constructor(options: {\n schema: Record<string, unknown>;\n strict?: boolean;\n });\n private constructor(schema: Record<string, unknown>, strict?: boolean);\n private constructor(\n schemaOrOptions:\n | Record<string, unknown>\n | { schema: Record<string, unknown>; strict?: boolean },\n strict?: boolean\n ) {\n if (\n \"schema\" in schemaOrOptions &&\n typeof schemaOrOptions.schema === \"object\" &&\n schemaOrOptions.schema !== null &&\n !(\"type\" in schemaOrOptions)\n ) {\n const options = schemaOrOptions as {\n schema: Record<string, unknown>;\n strict?: boolean;\n };\n this.schema = options.schema;\n this.strict = options.strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT;\n } else {\n this.schema = schemaOrOptions as Record<string, unknown>;\n this.strict = strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT;\n }\n }\n\n static fromSchema<T>(\n schema: InteropZodType<T>,\n strict?: boolean\n ): ProviderStrategy<T>;\n\n static fromSchema(\n schema: SerializableSchema,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | SerializableSchema | Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<T> | ProviderStrategy<Record<string, unknown>> {\n const asJsonSchema = toJsonSchema(schema);\n return new ProviderStrategy(asJsonSchema, strict) as\n | ProviderStrategy<T>\n | ProviderStrategy<Record<string, unknown>>;\n }\n\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param response - The AI message response to parse\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage) {\n /**\n * Extract text content from the response.\n * Handles both string content and array content (e.g., from thinking models).\n */\n let textContent: string | undefined;\n\n if (typeof response.content === \"string\") {\n textContent = response.content;\n } else if (Array.isArray(response.content)) {\n /**\n * For thinking models, content is an array with thinking blocks and text blocks.\n * Extract the text from text blocks.\n */\n for (const block of response.content) {\n if (\n typeof block === \"object\" &&\n block !== null &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n typeof block.text === \"string\"\n ) {\n textContent = block.text;\n break; // Use the first text block found\n }\n }\n }\n\n // Return if no valid text content found\n if (!textContent || textContent === \"\") {\n return;\n }\n\n try {\n const content = JSON.parse(textContent);\n const validator = new Validator(this.schema);\n const result = validator.validate(content);\n if (!result.valid) {\n return;\n }\n\n return content;\n } catch {\n // no-op\n }\n }\n}\n\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n\nexport type ResponseFormatInput<\n StructuredResponseType extends Record<string, any> = Record<string, any>,\n> =\n | InteropZodType<StructuredResponseType>\n | InteropZodType<unknown>[]\n | SerializableSchema<StructuredResponseType>\n | SerializableSchema[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ResponseFormat[]\n | TypedToolStrategy<StructuredResponseType>\n | ToolStrategy<StructuredResponseType>\n | ProviderStrategy<StructuredResponseType>\n | ResponseFormatUndefined;\n\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport function transformResponseFormat(\n responseFormat?: ResponseFormatInput,\n options?: ToolStrategyOptions,\n model?: LanguageModelLike\n): ResponseFormat[] {\n if (!responseFormat) {\n return [];\n }\n\n // Handle ResponseFormatUndefined case\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"__responseFormatUndefined\" in responseFormat\n ) {\n return [];\n }\n\n /**\n * If users provide an array, it should only contain raw schemas (Zod, Standard Schema or JSON schema),\n * not ToolStrategy or ProviderStrategy instances.\n */\n if (Array.isArray(responseFormat)) {\n /**\n * if every entry is a ToolStrategy or ProviderStrategy instance, return the array as is\n */\n if (\n responseFormat.every(\n (item) =>\n item instanceof ToolStrategy || item instanceof ProviderStrategy\n )\n ) {\n return responseFormat as unknown as ResponseFormat[];\n }\n\n /**\n * Check if all items are Standard Schema\n */\n if (responseFormat.every((item) => isSerializableSchema(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as SerializableSchema, options)\n );\n }\n\n /**\n * Check if all items are Zod schemas\n */\n if (responseFormat.every((item) => isInteropZodObject(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as InteropZodObject, options)\n );\n }\n\n /**\n * Check if all items are plain objects (JSON schema)\n */\n if (\n responseFormat.every(\n (item) =>\n typeof item === \"object\" &&\n item !== null &&\n !isInteropZodObject(item) &&\n !isSerializableSchema(item)\n )\n ) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as JsonSchemaFormat, options)\n );\n }\n\n throw new Error(\n `Invalid response format: list contains mixed types.\\n` +\n `All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`\n );\n }\n\n if (\n responseFormat instanceof ToolStrategy ||\n responseFormat instanceof ProviderStrategy\n ) {\n return [responseFormat];\n }\n\n const useProviderStrategy = hasSupportForJsonSchemaOutput(model);\n\n /**\n * `responseFormat` is a Standard Schema\n */\n if (isSerializableSchema(responseFormat)) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat)]\n : [ToolStrategy.fromSchema(responseFormat, options)];\n }\n\n /**\n * `responseFormat` is a Zod schema\n */\n if (isInteropZodObject(responseFormat)) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat)]\n : [ToolStrategy.fromSchema(responseFormat, options)];\n }\n\n /**\n * Handle plain object (JSON schema)\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"properties\" in responseFormat\n ) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat as JsonSchemaFormat)]\n : [ToolStrategy.fromSchema(responseFormat as JsonSchemaFormat, options)];\n }\n\n throw new Error(`Invalid response format: ${String(responseFormat)}`);\n}\n\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<\n ToolStrategy<any>\n> {\n _schemaType?: T;\n}\nexport type ToolStrategyError =\n | StructuredOutputParsingError\n | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n *\n * @default true\n */\n handleError?:\n | boolean\n | string\n | ((error: ToolStrategyError) => Promise<string> | string);\n}\n\nexport function toolStrategy<T extends InteropZodType<any>>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function toolStrategy<T extends readonly InteropZodType<any>[]>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<\n { [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]\n>;\nexport function toolStrategy(\n responseFormat: SerializableSchema,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: SerializableSchema[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\n\n/**\n * Creates a tool strategy for structured output using function calling.\n *\n * This function configures structured output by converting schemas into function tools that\n * the model calls. Unlike `providerStrategy`, which uses native JSON schema support,\n * `toolStrategy` works with any model that supports function calling, making it more\n * widely compatible across providers and model versions.\n *\n * The model will call a function with arguments matching your schema, and the agent will\n * extract and validate the structured output from the tool call. This approach is automatically\n * used when your model doesn't support native JSON schema output.\n *\n * @param responseFormat - The schema(s) to enforce. Can be a single Zod schema, a Standard Schema\n * (e.g., Valibot, ArkType, TypeBox), a JSON schema object, or arrays of any of these.\n * @param options - Optional configuration for the tool strategy\n * @param options.handleError - How to handle errors when the model calls multiple structured output tools\n * or when the output doesn't match the schema. Defaults to `true` (auto-retry). Can be `false` (throw),\n * a `string` (retry with message), or a `function` (custom handler).\n * @param options.toolMessageContent - Custom message content to include in conversation history\n * when structured output is generated via tool call\n * @returns A `TypedToolStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { toolStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: toolStrategy(\n * z.object({\n * answer: z.string(),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Multiple schemas - model can choose which one to use\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: toolStrategy([\n * z.object({ name: z.string(), age: z.number() }),\n * z.object({ email: z.string(), phone: z.string() }),\n * ]),\n * });\n * ```\n */\nexport function toolStrategy(\n responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | SerializableSchema\n | SerializableSchema[]\n | JsonSchemaFormat\n | JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy {\n return transformResponseFormat(responseFormat, options) as TypedToolStrategy;\n}\n\n/**\n * Creates a provider strategy for structured output using native JSON schema support.\n *\n * This function is used to configure structured output for agents when the underlying model\n * supports native JSON schema output (e.g., OpenAI's `gpt-4o`, `gpt-4o-mini`, and newer models).\n * Unlike `toolStrategy`, which uses function calling to extract structured output, `providerStrategy`\n * leverages the provider's native structured output capabilities, resulting in more efficient\n * and reliable schema enforcement.\n *\n * When used with a model that supports JSON schema output, the model will return responses\n * that directly conform to the provided schema without requiring tool calls. This is the\n * recommended approach for structured output when your model supports it.\n *\n * @param responseFormat - The schema to enforce, either a Zod schema, a Standard Schema (e.g., Valibot, ArkType, TypeBox), a JSON schema object, or an options object with `schema` and optional `strict` flag\n * @returns A `ProviderStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { providerStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy(\n * z.object({\n * answer: z.string().describe(\"The answer to the question\"),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Using strict mode for stricter schema enforcement\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy({\n * schema: z.object({\n * name: z.string(),\n * age: z.number(),\n * }),\n * strict: true\n * }),\n * });\n * ```\n */\nexport function providerStrategy<T extends InteropZodType<unknown>>(\n responseFormat: T | { schema: T; strict?: boolean }\n): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function providerStrategy(\n responseFormat:\n | SerializableSchema\n | { schema: SerializableSchema; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | JsonSchemaFormat\n | { schema: JsonSchemaFormat; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | InteropZodType<unknown>\n | SerializableSchema\n | JsonSchemaFormat\n | {\n schema: InteropZodType<unknown> | SerializableSchema | JsonSchemaFormat;\n strict?: boolean;\n }\n): ProviderStrategy<unknown> {\n /**\n * Handle options object format\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"schema\" in responseFormat &&\n !isInteropZodSchema(responseFormat) &&\n !isSerializableSchema(responseFormat) &&\n !(\"type\" in responseFormat)\n ) {\n const { schema, strict: strictFlag } = responseFormat as {\n schema: InteropZodType<unknown> | SerializableSchema | JsonSchemaFormat;\n strict?: boolean;\n };\n return ProviderStrategy.fromSchema(\n schema as InteropZodType<unknown>,\n strictFlag\n ) as ProviderStrategy<unknown>;\n }\n\n /**\n * Handle direct schema format\n */\n return ProviderStrategy.fromSchema(\n responseFormat as InteropZodType<unknown>\n ) as ProviderStrategy<unknown>;\n}\n\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type:\n | \"null\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"number\"\n | \"string\"\n | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n\n/**\n * Identifies the models that support JSON schema output by reading\n * the model's profile metadata.\n *\n * @param model - A resolved model instance to check. Callers should resolve\n * string model names and ConfigurableModel wrappers before calling this.\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model?: LanguageModelLike\n): boolean {\n if (\n !model ||\n !isBaseChatModel(model) ||\n !(\"profile\" in model) ||\n typeof model.profile !== \"object\" ||\n !model.profile\n ) {\n return false;\n }\n\n return (\n \"structuredOutput\" in model.profile &&\n model.profile.structuredOutput === true\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAwCA,MAAM,mCAAmC;;;;AAKzC,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CACtC,YAIE,QAKA,MAQA,SACA;AAdgB,OAAA,SAAA;AAKA,OAAA,OAAA;AAQA,OAAA,UAAA;;CAGlB,IAAI,OAAO;AACT,SAAO,KAAK,KAAK,SAAS;;CAkB5B,OAAO,WACL,QACA,eACmB;;;;;EAKnB,SAAS,gBAAgB,MAAe;AACtC,UAAO,QAAQ,WAAW,EAAE;;AAG9B,OAAA,GAAA,sCAAA,sBAAyB,OAAO,KAAA,GAAA,4BAAA,oBAAuB,OAAO,EAAE;G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IMessage } from "@langchain/core/messages";
3
- import { FunctionDefinition, LanguageModelLike } from "@langchain/core/language_models/base";
3
+ import { FunctionDefinition } from "@langchain/core/language_models/base";
4
4
  import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
5
5
  import { SerializableSchema } from "@langchain/core/utils/standard_schema";
6
6
 
@@ -72,6 +72,7 @@ declare class ProviderStrategy<T = unknown> {
72
72
  parse(response: AIMessage): any;
73
73
  }
74
74
  type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;
75
+ type ResponseFormatInput<StructuredResponseType extends Record<string, any> = Record<string, any>> = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | SerializableSchema<StructuredResponseType> | SerializableSchema[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | ResponseFormat[] | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined;
75
76
  /**
76
77
  * Branded type for ToolStrategy arrays that preserves type information
77
78
  */
@@ -180,5 +181,5 @@ type JsonSchemaFormat = {
180
181
  __brand?: never;
181
182
  };
182
183
  //#endregion
183
- export { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy };
184
+ export { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatInput, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy };
184
185
  //# sourceMappingURL=responses.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"responses.d.cts","names":[],"sources":["../../src/agents/responses.ts"],"mappings":";;;;;;;;AA2BA;;;KAAY,uBAAA;EACV,yBAAA;AAAA;;;;;;;cAyBW,YAAA;EA2BO;;;EAAA,SAtBA,MAAA,EAAQ,MAAA;EA0BhB;;;EAAA,SArBQ,IAAA;IACd,IAAA;IACA,QAAA,EAAU,kBAAA;EAAA;EA0BX;;;EAAA,SApBe,OAAA,GAAQ,mBAAA;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AAA;;;;AApNrB;;;;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAkUgB,gBAAA,WAA2B,cAAA,UAAA,CACzC,cAAA,EAAgB,CAAA;EAAM,MAAA,EAAQ,CAAA;EAAG,MAAA;AAAA,IAChC,gBAAA,CAAiB,CAAA,SAAU,cAAA,YAA0B,CAAA;AAAA,iBACxC,gBAAA,CACd,cAAA,EACI,kBAAA;EACE,MAAA,EAAQ,kBAAA;EAAoB,MAAA;AAAA,IACjC,gBAAA,CAAiB,MAAA;AAAA,iBACJ,gBAAA,CACd,cAAA,EACI,gBAAA;EACE,MAAA,EAAQ,gBAAA;EAAkB,MAAA;AAAA,IAC/B,gBAAA,CAAiB,MAAA;;;;;KA4CR,gBAAA;EACV,IAAA;EAQA,UAAA,GAAa,MAAA;EACb,QAAA;EACA,oBAAA;EAAA,CACC,GAAA;AAAA;EAGD,OAAA;AAAA"}
@@ -2,7 +2,7 @@ import { MultipleStructuredOutputsError, StructuredOutputParsingError } from "./
2
2
  import { AIMessage } from "@langchain/core/messages";
3
3
  import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
4
4
  import { SerializableSchema } from "@langchain/core/utils/standard_schema";
5
- import { FunctionDefinition, LanguageModelLike } from "@langchain/core/language_models/base";
5
+ import { FunctionDefinition } from "@langchain/core/language_models/base";
6
6
 
7
7
  //#region src/agents/responses.d.ts
8
8
  /**
@@ -72,6 +72,7 @@ declare class ProviderStrategy<T = unknown> {
72
72
  parse(response: AIMessage): any;
73
73
  }
74
74
  type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;
75
+ type ResponseFormatInput<StructuredResponseType extends Record<string, any> = Record<string, any>> = InteropZodType<StructuredResponseType> | InteropZodType<unknown>[] | SerializableSchema<StructuredResponseType> | SerializableSchema[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | ResponseFormat[] | TypedToolStrategy<StructuredResponseType> | ToolStrategy<StructuredResponseType> | ProviderStrategy<StructuredResponseType> | ResponseFormatUndefined;
75
76
  /**
76
77
  * Branded type for ToolStrategy arrays that preserves type information
77
78
  */
@@ -180,5 +181,5 @@ type JsonSchemaFormat = {
180
181
  __brand?: never;
181
182
  };
182
183
  //#endregion
183
- export { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy };
184
+ export { JsonSchemaFormat, ProviderStrategy, ResponseFormat, ResponseFormatInput, ResponseFormatUndefined, ToolStrategy, TypedToolStrategy, providerStrategy, toolStrategy };
184
185
  //# sourceMappingURL=responses.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"responses.d.ts","names":[],"sources":["../../src/agents/responses.ts"],"mappings":";;;;;;;;AA2BA;;;KAAY,uBAAA;EACV,yBAAA;AAAA;;;;;;;cAyBW,YAAA;EA2BO;;;EAAA,SAtBA,MAAA,EAAQ,MAAA;EA0BhB;;;EAAA,SArBQ,IAAA;IACd,IAAA;IACA,QAAA,EAAU,kBAAA;EAAA;EA0BX;;;EAAA,SApBe,OAAA,GAAQ,mBAAA;EAAA,QAjBnB,WAAA,CAAA;EAAA,IAoBH,IAAA,CAAA;EAAA,OAIG,UAAA,WAAqB,gBAAA,CAAA,CAC1B,MAAA,EAAQ,CAAA,EACR,aAAA,GAAgB,mBAAA,GACf,YAAA,CAAa,CAAA,SAAU,cAAA,YAA0B,CAAA;EAAA,OAE7C,UAAA,CACL,MAAA,EAAQ,kBAAA,EACR,aAAA,GAAgB,mBAAA,GACf,YAAA,CAAa,MAAA;EAAA,OAET,UAAA,CACL,MAAA,EAAQ,MAAA,mBACR,aAAA,GAAgB,mBAAA,GACf,YAAA,CAAa,MAAA;EA3BZ;;;;;;;EAsFJ,KAAA,CAAM,QAAA,EAAU,MAAA,oBAA0B,MAAA;AAAA;AAAA,cAa/B,gBAAA;EAAA,QAEH,WAAA;EAtFN;;;EAAA,SA2Fc,MAAA,EAAQ,MAAA;EAzFR;;;EAAA,SA8FA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,CACC,GAAA;AAAA;EAGD,OAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"responses.js","names":[],"sources":["../../src/agents/responses.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n InteropZodObject,\n isInteropZodSchema,\n InteropZodType,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { toJsonSchema, Validator } from \"@langchain/core/utils/json_schema\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport {\n type SerializableSchema,\n isSerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\nimport { isBaseChatModel } from \"./model.js\";\n\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n\n/**\n * Default value for strict mode in providerStrategy.\n *\n * When using providerStrategy with json_schema response format, OpenAI's parse() method\n * requires all function tools to have strict: true. This ensures the model's output\n * exactly matches the provided JSON schema.\n *\n * @see https://platform.openai.com/docs/guides/structured-outputs\n */\nconst PROVIDER_STRATEGY_DEFAULT_STRICT = true;\n\n/**\n * This is a global counter for generating unique names for tools.\n */\nlet bindingIdentifier = 0;\n\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport class ToolStrategy<_T = unknown> {\n private constructor(\n /**\n * The original JSON Schema provided for structured output\n */\n public readonly schema: Record<string, unknown>,\n\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n public readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n },\n\n /**\n * The options to use for the tool output.\n */\n public readonly options?: ToolStrategyOptions\n ) {}\n\n get name() {\n return this.tool.function.name;\n }\n\n static fromSchema<S extends InteropZodObject>(\n schema: S,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n\n static fromSchema(\n schema: SerializableSchema,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | SerializableSchema | Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<any> {\n /**\n * It is required for tools to have a name so we can map the tool call to the correct tool\n * when parsing the response.\n */\n function getFunctionName(name?: string) {\n return name ?? `extract-${++bindingIdentifier}`;\n }\n\n if (isSerializableSchema(schema) || isInteropZodSchema(schema)) {\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: {\n name: getFunctionName(asJsonSchema.title),\n strict: false,\n description:\n asJsonSchema.description ??\n \"Tool for extracting structured output from the model's response.\",\n parameters: asJsonSchema,\n },\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n let functionDefinition: FunctionDefinition;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n functionDefinition = schema as unknown as FunctionDefinition;\n } else {\n functionDefinition = {\n name: getFunctionName(schema.title as string),\n description: (schema.description as string) ?? \"\",\n parameters: schema.schema || (schema as Record<string, unknown>),\n };\n }\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: functionDefinition,\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown> {\n const validator = new Validator(this.schema);\n const result = validator.validate(toolArgs);\n if (!result.valid) {\n throw new StructuredOutputParsingError(\n this.name,\n result.errors.map((e) => e.error)\n );\n }\n return toolArgs;\n }\n}\n\nexport class ProviderStrategy<T = unknown> {\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?: T;\n\n /**\n * The schema to use for the provider strategy\n */\n public readonly schema: Record<string, unknown>;\n\n /**\n * Whether to use strict mode for the provider strategy\n */\n public readonly strict: boolean;\n\n private constructor(options: {\n schema: Record<string, unknown>;\n strict?: boolean;\n });\n private constructor(schema: Record<string, unknown>, strict?: boolean);\n private constructor(\n schemaOrOptions:\n | Record<string, unknown>\n | { schema: Record<string, unknown>; strict?: boolean },\n strict?: boolean\n ) {\n if (\n \"schema\" in schemaOrOptions &&\n typeof schemaOrOptions.schema === \"object\" &&\n schemaOrOptions.schema !== null &&\n !(\"type\" in schemaOrOptions)\n ) {\n const options = schemaOrOptions as {\n schema: Record<string, unknown>;\n strict?: boolean;\n };\n this.schema = options.schema;\n this.strict = options.strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT;\n } else {\n this.schema = schemaOrOptions as Record<string, unknown>;\n this.strict = strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT;\n }\n }\n\n static fromSchema<T>(\n schema: InteropZodType<T>,\n strict?: boolean\n ): ProviderStrategy<T>;\n\n static fromSchema(\n schema: SerializableSchema,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | SerializableSchema | Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<T> | ProviderStrategy<Record<string, unknown>> {\n const asJsonSchema = toJsonSchema(schema);\n return new ProviderStrategy(asJsonSchema, strict) as\n | ProviderStrategy<T>\n | ProviderStrategy<Record<string, unknown>>;\n }\n\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param response - The AI message response to parse\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage) {\n /**\n * Extract text content from the response.\n * Handles both string content and array content (e.g., from thinking models).\n */\n let textContent: string | undefined;\n\n if (typeof response.content === \"string\") {\n textContent = response.content;\n } else if (Array.isArray(response.content)) {\n /**\n * For thinking models, content is an array with thinking blocks and text blocks.\n * Extract the text from text blocks.\n */\n for (const block of response.content) {\n if (\n typeof block === \"object\" &&\n block !== null &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n typeof block.text === \"string\"\n ) {\n textContent = block.text;\n break; // Use the first text block found\n }\n }\n }\n\n // Return if no valid text content found\n if (!textContent || textContent === \"\") {\n return;\n }\n\n try {\n const content = JSON.parse(textContent);\n const validator = new Validator(this.schema);\n const result = validator.validate(content);\n if (!result.valid) {\n return;\n }\n\n return content;\n } catch {\n // no-op\n }\n }\n}\n\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport function transformResponseFormat(\n responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | SerializableSchema\n | SerializableSchema[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions,\n model?: LanguageModelLike\n): ResponseFormat[] {\n if (!responseFormat) {\n return [];\n }\n\n // Handle ResponseFormatUndefined case\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"__responseFormatUndefined\" in responseFormat\n ) {\n return [];\n }\n\n /**\n * If users provide an array, it should only contain raw schemas (Zod, Standard Schema or JSON schema),\n * not ToolStrategy or ProviderStrategy instances.\n */\n if (Array.isArray(responseFormat)) {\n /**\n * if every entry is a ToolStrategy or ProviderStrategy instance, return the array as is\n */\n if (\n responseFormat.every(\n (item) =>\n item instanceof ToolStrategy || item instanceof ProviderStrategy\n )\n ) {\n return responseFormat as unknown as ResponseFormat[];\n }\n\n /**\n * Check if all items are Standard Schema\n */\n if (responseFormat.every((item) => isSerializableSchema(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as SerializableSchema, options)\n );\n }\n\n /**\n * Check if all items are Zod schemas\n */\n if (responseFormat.every((item) => isInteropZodObject(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as InteropZodObject, options)\n );\n }\n\n /**\n * Check if all items are plain objects (JSON schema)\n */\n if (\n responseFormat.every(\n (item) =>\n typeof item === \"object\" &&\n item !== null &&\n !isInteropZodObject(item) &&\n !isSerializableSchema(item)\n )\n ) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as JsonSchemaFormat, options)\n );\n }\n\n throw new Error(\n `Invalid response format: list contains mixed types.\\n` +\n `All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`\n );\n }\n\n if (\n responseFormat instanceof ToolStrategy ||\n responseFormat instanceof ProviderStrategy\n ) {\n return [responseFormat];\n }\n\n const useProviderStrategy = hasSupportForJsonSchemaOutput(model);\n\n /**\n * `responseFormat` is a Standard Schema\n */\n if (isSerializableSchema(responseFormat)) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat)]\n : [ToolStrategy.fromSchema(responseFormat, options)];\n }\n\n /**\n * `responseFormat` is a Zod schema\n */\n if (isInteropZodObject(responseFormat)) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat)]\n : [ToolStrategy.fromSchema(responseFormat, options)];\n }\n\n /**\n * Handle plain object (JSON schema)\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"properties\" in responseFormat\n ) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat as JsonSchemaFormat)]\n : [ToolStrategy.fromSchema(responseFormat as JsonSchemaFormat, options)];\n }\n\n throw new Error(`Invalid response format: ${String(responseFormat)}`);\n}\n\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<\n ToolStrategy<any>\n> {\n _schemaType?: T;\n}\nexport type ToolStrategyError =\n | StructuredOutputParsingError\n | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n *\n * @default true\n */\n handleError?:\n | boolean\n | string\n | ((error: ToolStrategyError) => Promise<string> | string);\n}\n\nexport function toolStrategy<T extends InteropZodType<any>>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function toolStrategy<T extends readonly InteropZodType<any>[]>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<\n { [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]\n>;\nexport function toolStrategy(\n responseFormat: SerializableSchema,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: SerializableSchema[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\n\n/**\n * Creates a tool strategy for structured output using function calling.\n *\n * This function configures structured output by converting schemas into function tools that\n * the model calls. Unlike `providerStrategy`, which uses native JSON schema support,\n * `toolStrategy` works with any model that supports function calling, making it more\n * widely compatible across providers and model versions.\n *\n * The model will call a function with arguments matching your schema, and the agent will\n * extract and validate the structured output from the tool call. This approach is automatically\n * used when your model doesn't support native JSON schema output.\n *\n * @param responseFormat - The schema(s) to enforce. Can be a single Zod schema, a Standard Schema\n * (e.g., Valibot, ArkType, TypeBox), a JSON schema object, or arrays of any of these.\n * @param options - Optional configuration for the tool strategy\n * @param options.handleError - How to handle errors when the model calls multiple structured output tools\n * or when the output doesn't match the schema. Defaults to `true` (auto-retry). Can be `false` (throw),\n * a `string` (retry with message), or a `function` (custom handler).\n * @param options.toolMessageContent - Custom message content to include in conversation history\n * when structured output is generated via tool call\n * @returns A `TypedToolStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { toolStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: toolStrategy(\n * z.object({\n * answer: z.string(),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Multiple schemas - model can choose which one to use\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: toolStrategy([\n * z.object({ name: z.string(), age: z.number() }),\n * z.object({ email: z.string(), phone: z.string() }),\n * ]),\n * });\n * ```\n */\nexport function toolStrategy(\n responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | SerializableSchema\n | SerializableSchema[]\n | JsonSchemaFormat\n | JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy {\n return transformResponseFormat(responseFormat, options) as TypedToolStrategy;\n}\n\n/**\n * Creates a provider strategy for structured output using native JSON schema support.\n *\n * This function is used to configure structured output for agents when the underlying model\n * supports native JSON schema output (e.g., OpenAI's `gpt-4o`, `gpt-4o-mini`, and newer models).\n * Unlike `toolStrategy`, which uses function calling to extract structured output, `providerStrategy`\n * leverages the provider's native structured output capabilities, resulting in more efficient\n * and reliable schema enforcement.\n *\n * When used with a model that supports JSON schema output, the model will return responses\n * that directly conform to the provided schema without requiring tool calls. This is the\n * recommended approach for structured output when your model supports it.\n *\n * @param responseFormat - The schema to enforce, either a Zod schema, a Standard Schema (e.g., Valibot, ArkType, TypeBox), a JSON schema object, or an options object with `schema` and optional `strict` flag\n * @returns A `ProviderStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { providerStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy(\n * z.object({\n * answer: z.string().describe(\"The answer to the question\"),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Using strict mode for stricter schema enforcement\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy({\n * schema: z.object({\n * name: z.string(),\n * age: z.number(),\n * }),\n * strict: true\n * }),\n * });\n * ```\n */\nexport function providerStrategy<T extends InteropZodType<unknown>>(\n responseFormat: T | { schema: T; strict?: boolean }\n): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function providerStrategy(\n responseFormat:\n | SerializableSchema\n | { schema: SerializableSchema; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | JsonSchemaFormat\n | { schema: JsonSchemaFormat; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | InteropZodType<unknown>\n | SerializableSchema\n | JsonSchemaFormat\n | {\n schema: InteropZodType<unknown> | SerializableSchema | JsonSchemaFormat;\n strict?: boolean;\n }\n): ProviderStrategy<unknown> {\n /**\n * Handle options object format\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"schema\" in responseFormat &&\n !isInteropZodSchema(responseFormat) &&\n !isSerializableSchema(responseFormat) &&\n !(\"type\" in responseFormat)\n ) {\n const { schema, strict: strictFlag } = responseFormat as {\n schema: InteropZodType<unknown> | SerializableSchema | JsonSchemaFormat;\n strict?: boolean;\n };\n return ProviderStrategy.fromSchema(\n schema as InteropZodType<unknown>,\n strictFlag\n ) as ProviderStrategy<unknown>;\n }\n\n /**\n * Handle direct schema format\n */\n return ProviderStrategy.fromSchema(\n responseFormat as InteropZodType<unknown>\n ) as ProviderStrategy<unknown>;\n}\n\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type:\n | \"null\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"number\"\n | \"string\"\n | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n\n/**\n * Identifies the models that support JSON schema output by reading\n * the model's profile metadata.\n *\n * @param model - A resolved model instance to check. Callers should resolve\n * string model names and ConfigurableModel wrappers before calling this.\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model?: LanguageModelLike\n): boolean {\n if (\n !model ||\n !isBaseChatModel(model) ||\n !(\"profile\" in model) ||\n typeof model.profile !== \"object\" ||\n !model.profile\n ) {\n return false;\n }\n\n return (\n \"structuredOutput\" in model.profile &&\n model.profile.structuredOutput === true\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwCA,MAAM,mCAAmC;;;;AAKzC,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CACtC,YAIE,QAKA,MAQA,SACA;AAdgB,OAAA,SAAA;AAKA,OAAA,OAAA;AAQA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"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable no-instanceof/no-instanceof */\nimport {\n InteropZodObject,\n isInteropZodSchema,\n InteropZodType,\n isInteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { toJsonSchema, Validator } from \"@langchain/core/utils/json_schema\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport {\n type SerializableSchema,\n isSerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\nimport { isBaseChatModel } from \"./model.js\";\nimport type { AgentLanguageModelLike as LanguageModelLike } from \"./model.js\";\n\n/**\n * Special type to indicate that no response format is provided.\n * When this type is used, the structuredResponse property should not be present in the result.\n */\nexport type ResponseFormatUndefined = {\n __responseFormatUndefined: true;\n};\n\n/**\n * Default value for strict mode in providerStrategy.\n *\n * When using providerStrategy with json_schema response format, OpenAI's parse() method\n * requires all function tools to have strict: true. This ensures the model's output\n * exactly matches the provided JSON schema.\n *\n * @see https://platform.openai.com/docs/guides/structured-outputs\n */\nconst PROVIDER_STRATEGY_DEFAULT_STRICT = true;\n\n/**\n * This is a global counter for generating unique names for tools.\n */\nlet bindingIdentifier = 0;\n\n/**\n * Information for tracking structured output tool metadata.\n * This contains all necessary information to handle structured responses generated\n * via tool calls, including the original schema, its type classification, and the\n * corresponding tool implementation used by the tools strategy.\n */\nexport class ToolStrategy<_T = unknown> {\n private constructor(\n /**\n * The original JSON Schema provided for structured output\n */\n public readonly schema: Record<string, unknown>,\n\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n public readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n },\n\n /**\n * The options to use for the tool output.\n */\n public readonly options?: ToolStrategyOptions\n ) {}\n\n get name() {\n return this.tool.function.name;\n }\n\n static fromSchema<S extends InteropZodObject>(\n schema: S,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n\n static fromSchema(\n schema: SerializableSchema,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | SerializableSchema | Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<any> {\n /**\n * It is required for tools to have a name so we can map the tool call to the correct tool\n * when parsing the response.\n */\n function getFunctionName(name?: string) {\n return name ?? `extract-${++bindingIdentifier}`;\n }\n\n if (isSerializableSchema(schema) || isInteropZodSchema(schema)) {\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: {\n name: getFunctionName(asJsonSchema.title),\n strict: false,\n description:\n asJsonSchema.description ??\n \"Tool for extracting structured output from the model's response.\",\n parameters: asJsonSchema,\n },\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n let functionDefinition: FunctionDefinition;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n functionDefinition = schema as unknown as FunctionDefinition;\n } else {\n functionDefinition = {\n name: getFunctionName(schema.title as string),\n description: (schema.description as string) ?? \"\",\n parameters: schema.schema || (schema as Record<string, unknown>),\n };\n }\n const asJsonSchema = toJsonSchema(schema);\n const tool = {\n type: \"function\" as const,\n function: functionDefinition,\n };\n return new ToolStrategy(asJsonSchema, tool, outputOptions);\n }\n\n /**\n * Parse tool arguments according to the schema.\n *\n * @throws {StructuredOutputParsingError} if the response is not valid\n * @param toolArgs - The arguments from the tool call\n * @returns The parsed response according to the schema type\n */\n parse(toolArgs: Record<string, unknown>): Record<string, unknown> {\n const validator = new Validator(this.schema);\n const result = validator.validate(toolArgs);\n if (!result.valid) {\n throw new StructuredOutputParsingError(\n this.name,\n result.errors.map((e) => e.error)\n );\n }\n return toolArgs;\n }\n}\n\nexport class ProviderStrategy<T = unknown> {\n // @ts-expect-error - _schemaType is used only for type inference\n private _schemaType?: T;\n\n /**\n * The schema to use for the provider strategy\n */\n public readonly schema: Record<string, unknown>;\n\n /**\n * Whether to use strict mode for the provider strategy\n */\n public readonly strict: boolean;\n\n private constructor(options: {\n schema: Record<string, unknown>;\n strict?: boolean;\n });\n private constructor(schema: Record<string, unknown>, strict?: boolean);\n private constructor(\n schemaOrOptions:\n | Record<string, unknown>\n | { schema: Record<string, unknown>; strict?: boolean },\n strict?: boolean\n ) {\n if (\n \"schema\" in schemaOrOptions &&\n typeof schemaOrOptions.schema === \"object\" &&\n schemaOrOptions.schema !== null &&\n !(\"type\" in schemaOrOptions)\n ) {\n const options = schemaOrOptions as {\n schema: Record<string, unknown>;\n strict?: boolean;\n };\n this.schema = options.schema;\n this.strict = options.strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT;\n } else {\n this.schema = schemaOrOptions as Record<string, unknown>;\n this.strict = strict ?? PROVIDER_STRATEGY_DEFAULT_STRICT;\n }\n }\n\n static fromSchema<T>(\n schema: InteropZodType<T>,\n strict?: boolean\n ): ProviderStrategy<T>;\n\n static fromSchema(\n schema: SerializableSchema,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | SerializableSchema | Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<T> | ProviderStrategy<Record<string, unknown>> {\n const asJsonSchema = toJsonSchema(schema);\n return new ProviderStrategy(asJsonSchema, strict) as\n | ProviderStrategy<T>\n | ProviderStrategy<Record<string, unknown>>;\n }\n\n /**\n * Parse tool arguments according to the schema. If the response is not valid, return undefined.\n *\n * @param response - The AI message response to parse\n * @returns The parsed response according to the schema type\n */\n parse(response: AIMessage) {\n /**\n * Extract text content from the response.\n * Handles both string content and array content (e.g., from thinking models).\n */\n let textContent: string | undefined;\n\n if (typeof response.content === \"string\") {\n textContent = response.content;\n } else if (Array.isArray(response.content)) {\n /**\n * For thinking models, content is an array with thinking blocks and text blocks.\n * Extract the text from text blocks.\n */\n for (const block of response.content) {\n if (\n typeof block === \"object\" &&\n block !== null &&\n \"type\" in block &&\n block.type === \"text\" &&\n \"text\" in block &&\n typeof block.text === \"string\"\n ) {\n textContent = block.text;\n break; // Use the first text block found\n }\n }\n }\n\n // Return if no valid text content found\n if (!textContent || textContent === \"\") {\n return;\n }\n\n try {\n const content = JSON.parse(textContent);\n const validator = new Validator(this.schema);\n const result = validator.validate(content);\n if (!result.valid) {\n return;\n }\n\n return content;\n } catch {\n // no-op\n }\n }\n}\n\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\n\nexport type ResponseFormatInput<\n StructuredResponseType extends Record<string, any> = Record<string, any>,\n> =\n | InteropZodType<StructuredResponseType>\n | InteropZodType<unknown>[]\n | SerializableSchema<StructuredResponseType>\n | SerializableSchema[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ResponseFormat[]\n | TypedToolStrategy<StructuredResponseType>\n | ToolStrategy<StructuredResponseType>\n | ProviderStrategy<StructuredResponseType>\n | ResponseFormatUndefined;\n\n/**\n * Handle user input for `responseFormat` parameter of `CreateAgentParams`.\n * This function defines the default behavior for the `responseFormat` parameter, which is:\n *\n * - if value is a Zod schema, default to structured output via tool calling\n * - if value is a JSON schema, default to structured output via tool calling\n * - if value is a custom response format, return it as is\n * - if value is an array, ensure all array elements are instance of `ToolStrategy`\n * @param responseFormat - The response format to transform, provided by the user\n * @param options - The response format options for tool strategy\n * @param model - The model to check if it supports JSON schema output\n * @returns\n */\nexport function transformResponseFormat(\n responseFormat?: ResponseFormatInput,\n options?: ToolStrategyOptions,\n model?: LanguageModelLike\n): ResponseFormat[] {\n if (!responseFormat) {\n return [];\n }\n\n // Handle ResponseFormatUndefined case\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"__responseFormatUndefined\" in responseFormat\n ) {\n return [];\n }\n\n /**\n * If users provide an array, it should only contain raw schemas (Zod, Standard Schema or JSON schema),\n * not ToolStrategy or ProviderStrategy instances.\n */\n if (Array.isArray(responseFormat)) {\n /**\n * if every entry is a ToolStrategy or ProviderStrategy instance, return the array as is\n */\n if (\n responseFormat.every(\n (item) =>\n item instanceof ToolStrategy || item instanceof ProviderStrategy\n )\n ) {\n return responseFormat as unknown as ResponseFormat[];\n }\n\n /**\n * Check if all items are Standard Schema\n */\n if (responseFormat.every((item) => isSerializableSchema(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as SerializableSchema, options)\n );\n }\n\n /**\n * Check if all items are Zod schemas\n */\n if (responseFormat.every((item) => isInteropZodObject(item))) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as InteropZodObject, options)\n );\n }\n\n /**\n * Check if all items are plain objects (JSON schema)\n */\n if (\n responseFormat.every(\n (item) =>\n typeof item === \"object\" &&\n item !== null &&\n !isInteropZodObject(item) &&\n !isSerializableSchema(item)\n )\n ) {\n return responseFormat.map((item) =>\n ToolStrategy.fromSchema(item as JsonSchemaFormat, options)\n );\n }\n\n throw new Error(\n `Invalid response format: list contains mixed types.\\n` +\n `All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`\n );\n }\n\n if (\n responseFormat instanceof ToolStrategy ||\n responseFormat instanceof ProviderStrategy\n ) {\n return [responseFormat];\n }\n\n const useProviderStrategy = hasSupportForJsonSchemaOutput(model);\n\n /**\n * `responseFormat` is a Standard Schema\n */\n if (isSerializableSchema(responseFormat)) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat)]\n : [ToolStrategy.fromSchema(responseFormat, options)];\n }\n\n /**\n * `responseFormat` is a Zod schema\n */\n if (isInteropZodObject(responseFormat)) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat)]\n : [ToolStrategy.fromSchema(responseFormat, options)];\n }\n\n /**\n * Handle plain object (JSON schema)\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"properties\" in responseFormat\n ) {\n return useProviderStrategy\n ? [ProviderStrategy.fromSchema(responseFormat as JsonSchemaFormat)]\n : [ToolStrategy.fromSchema(responseFormat as JsonSchemaFormat, options)];\n }\n\n throw new Error(`Invalid response format: ${String(responseFormat)}`);\n}\n\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<\n ToolStrategy<any>\n> {\n _schemaType?: T;\n}\nexport type ToolStrategyError =\n | StructuredOutputParsingError\n | MultipleStructuredOutputsError;\nexport interface ToolStrategyOptions {\n /**\n * Allows you to customize the message that appears in the conversation history when structured\n * output is generated.\n */\n toolMessageContent?: string;\n /**\n * Handle errors from the structured output tool call. Using tools to generate structured output\n * can cause errors, e.g. if:\n * - you provide multiple structured output schemas and the model calls multiple structured output tools\n * - if the structured output generated by the tool call doesn't match provided schema\n *\n * This property allows to handle these errors in different ways:\n * - `true` - retry the tool call\n * - `false` - throw an error\n * - `string` - retry the tool call with the provided message\n * - `(error: ToolStrategyError) => Promise<string> | string` - retry with the provided message or throw the error\n *\n * @default true\n */\n handleError?:\n | boolean\n | string\n | ((error: ToolStrategyError) => Promise<string> | string);\n}\n\nexport function toolStrategy<T extends InteropZodType<any>>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function toolStrategy<T extends readonly InteropZodType<any>[]>(\n responseFormat: T,\n options?: ToolStrategyOptions\n): TypedToolStrategy<\n { [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never }[number]\n>;\nexport function toolStrategy(\n responseFormat: SerializableSchema,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: SerializableSchema[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat,\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\nexport function toolStrategy(\n responseFormat: JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy<Record<string, unknown>>;\n\n/**\n * Creates a tool strategy for structured output using function calling.\n *\n * This function configures structured output by converting schemas into function tools that\n * the model calls. Unlike `providerStrategy`, which uses native JSON schema support,\n * `toolStrategy` works with any model that supports function calling, making it more\n * widely compatible across providers and model versions.\n *\n * The model will call a function with arguments matching your schema, and the agent will\n * extract and validate the structured output from the tool call. This approach is automatically\n * used when your model doesn't support native JSON schema output.\n *\n * @param responseFormat - The schema(s) to enforce. Can be a single Zod schema, a Standard Schema\n * (e.g., Valibot, ArkType, TypeBox), a JSON schema object, or arrays of any of these.\n * @param options - Optional configuration for the tool strategy\n * @param options.handleError - How to handle errors when the model calls multiple structured output tools\n * or when the output doesn't match the schema. Defaults to `true` (auto-retry). Can be `false` (throw),\n * a `string` (retry with message), or a `function` (custom handler).\n * @param options.toolMessageContent - Custom message content to include in conversation history\n * when structured output is generated via tool call\n * @returns A `TypedToolStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { toolStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: toolStrategy(\n * z.object({\n * answer: z.string(),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Multiple schemas - model can choose which one to use\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: toolStrategy([\n * z.object({ name: z.string(), age: z.number() }),\n * z.object({ email: z.string(), phone: z.string() }),\n * ]),\n * });\n * ```\n */\nexport function toolStrategy(\n responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | SerializableSchema\n | SerializableSchema[]\n | JsonSchemaFormat\n | JsonSchemaFormat[],\n options?: ToolStrategyOptions\n): TypedToolStrategy {\n return transformResponseFormat(responseFormat, options) as TypedToolStrategy;\n}\n\n/**\n * Creates a provider strategy for structured output using native JSON schema support.\n *\n * This function is used to configure structured output for agents when the underlying model\n * supports native JSON schema output (e.g., OpenAI's `gpt-4o`, `gpt-4o-mini`, and newer models).\n * Unlike `toolStrategy`, which uses function calling to extract structured output, `providerStrategy`\n * leverages the provider's native structured output capabilities, resulting in more efficient\n * and reliable schema enforcement.\n *\n * When used with a model that supports JSON schema output, the model will return responses\n * that directly conform to the provided schema without requiring tool calls. This is the\n * recommended approach for structured output when your model supports it.\n *\n * @param responseFormat - The schema to enforce, either a Zod schema, a Standard Schema (e.g., Valibot, ArkType, TypeBox), a JSON schema object, or an options object with `schema` and optional `strict` flag\n * @returns A `ProviderStrategy` instance that can be used as the `responseFormat` in `createAgent`\n *\n * @example\n * ```ts\n * import { providerStrategy, createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy(\n * z.object({\n * answer: z.string().describe(\"The answer to the question\"),\n * confidence: z.number().min(0).max(1),\n * })\n * ),\n * });\n * ```\n *\n * @example\n * ```ts\n * // Using strict mode for stricter schema enforcement\n * const agent = createAgent({\n * model: \"claude-haiku-4-5\",\n * responseFormat: providerStrategy({\n * schema: z.object({\n * name: z.string(),\n * age: z.number(),\n * }),\n * strict: true\n * }),\n * });\n * ```\n */\nexport function providerStrategy<T extends InteropZodType<unknown>>(\n responseFormat: T | { schema: T; strict?: boolean }\n): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport function providerStrategy(\n responseFormat:\n | SerializableSchema\n | { schema: SerializableSchema; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | JsonSchemaFormat\n | { schema: JsonSchemaFormat; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | InteropZodType<unknown>\n | SerializableSchema\n | JsonSchemaFormat\n | {\n schema: InteropZodType<unknown> | SerializableSchema | JsonSchemaFormat;\n strict?: boolean;\n }\n): ProviderStrategy<unknown> {\n /**\n * Handle options object format\n */\n if (\n typeof responseFormat === \"object\" &&\n responseFormat !== null &&\n \"schema\" in responseFormat &&\n !isInteropZodSchema(responseFormat) &&\n !isSerializableSchema(responseFormat) &&\n !(\"type\" in responseFormat)\n ) {\n const { schema, strict: strictFlag } = responseFormat as {\n schema: InteropZodType<unknown> | SerializableSchema | JsonSchemaFormat;\n strict?: boolean;\n };\n return ProviderStrategy.fromSchema(\n schema as InteropZodType<unknown>,\n strictFlag\n ) as ProviderStrategy<unknown>;\n }\n\n /**\n * Handle direct schema format\n */\n return ProviderStrategy.fromSchema(\n responseFormat as InteropZodType<unknown>\n ) as ProviderStrategy<unknown>;\n}\n\n/**\n * Type representing a JSON Schema object format.\n * This is a strict type that excludes ToolStrategy and ProviderStrategy instances.\n */\nexport type JsonSchemaFormat = {\n type:\n | \"null\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"number\"\n | \"string\"\n | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n // Brand to ensure this is not a ToolStrategy or ProviderStrategy\n __brand?: never;\n};\n\n/**\n * Identifies the models that support JSON schema output by reading\n * the model's profile metadata.\n *\n * @param model - A resolved model instance to check. Callers should resolve\n * string model names and ConfigurableModel wrappers before calling this.\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model?: LanguageModelLike\n): boolean {\n if (\n !model ||\n !isBaseChatModel(model) ||\n !(\"profile\" in model) ||\n typeof model.profile !== \"object\" ||\n !model.profile\n ) {\n return false;\n }\n\n return (\n \"structuredOutput\" in model.profile &&\n model.profile.structuredOutput === true\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwCA,MAAM,mCAAmC;;;;AAKzC,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CAC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AAQ,qBAAqB"}
@@ -1,5 +1,4 @@
1
1
  import { AIMessage, BaseMessage, ToolMessage } from "@langchain/core/messages";
2
- import { LanguageModelLike } from "@langchain/core/language_models/base";
3
2
  import { BaseChatModel, BaseChatModelParams, BindToolsInput, ToolChoice } from "@langchain/core/language_models/chat_models";
4
3
  import { Runnable, RunnableBinding, RunnableConfig, RunnableLambda } from "@langchain/core/runnables";
5
4
  import { StructuredTool } from "@langchain/core/tools";
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.cts","names":[],"sources":["../../../src/agents/tests/utils.ts"],"mappings":";;;;;;;;;;;;UA2UU,UAAA;EACR,IAAA;EACA,IAAA,EAAM,MAAA;EACN,EAAA;EACA,IAAA;AAAA;AAAA,UAGQ,0BAAA;EACR,SAAA,GAAY,UAAA;EACZ,SAAA;EACA,KAAA;EACA,kBAAA;AAAA;;;;cAWW,oBAAA,SAA6B,aAAA;EACxC,SAAA,EAAW,UAAA;EAEX,SAAA;EAAA,QAGQ,QAAA;EAER,kBAAA;EAAA,QAEQ,KAAA;EAER,WAAA,CAAA;IACE,SAAA;IACA,SAAA;IACA,KAAA;IACA,kBAAA;IACA,QAAA;IAAA,GACG;EAAA,IACF,0BAAA;IAA+B,QAAA;MAAa,OAAA;IAAA;EAAA;EAAA,IAU3C,KAAA,CAAA;EAAA,IAIA,KAAA,CAAM,KAAA;EAIV,QAAA,CAAA;EAIA,iBAAA,CAAA;EAIA,SAAA,CACE,KAAA,EAAO,cAAA,KAEL,oBAAA,GACA,eAAA;IAGU,WAAA,GAAc,UAAA;EAAA;EAa5B,oBAAA,CAAqB,OAAA,QAAY,cAAA,eAAA,cAAA,CAAA,MAAA;EAQ3B,SAAA,CACJ,QAAA,EAAU,WAAA,IACV,QAAA,8BACA,WAAA,GAAc,wBAAA,GACb,OAAA,CAAQ,UAAA;AAAA"}
1
+ {"version":3,"file":"utils.d.cts","names":[],"sources":["../../../src/agents/tests/utils.ts"],"mappings":";;;;;;;;;;;UA2UU,UAAA;EACR,IAAA;EACA,IAAA,EAAM,MAAA;EACN,EAAA;EACA,IAAA;AAAA;AAAA,UAGQ,0BAAA;EACR,SAAA,GAAY,UAAA;EACZ,SAAA;EACA,KAAA;EACA,kBAAA;AAAA;;;;cAWW,oBAAA,SAA6B,aAAA;EACxC,SAAA,EAAW,UAAA;EAEX,SAAA;EAAA,QAGQ,QAAA;EAER,kBAAA;EAAA,QAEQ,KAAA;EAER,WAAA,CAAA;IACE,SAAA;IACA,SAAA;IACA,KAAA;IACA,kBAAA;IACA,QAAA;IAAA,GACG;EAAA,IACF,0BAAA;IAA+B,QAAA;MAAa,OAAA;IAAA;EAAA;EAAA,IAU3C,KAAA,CAAA;EAAA,IAIA,KAAA,CAAM,KAAA;EAIV,QAAA,CAAA;EAIA,iBAAA,CAAA;EAIA,SAAA,CACE,KAAA,EAAO,cAAA,KAEL,oBAAA,GACA,eAAA;IAGU,WAAA,GAAc,UAAA;EAAA;EAa5B,oBAAA,CAAqB,OAAA,QAAY,cAAA,eAAA,cAAA,CAAA,MAAA;EAQ3B,SAAA,CACJ,QAAA,EAAU,WAAA,IACV,QAAA,8BACA,WAAA,GAAc,wBAAA,GACb,OAAA,CAAQ,UAAA;AAAA"}
@@ -4,7 +4,6 @@ import { Runnable, RunnableBinding, RunnableConfig, RunnableLambda } from "@lang
4
4
  import { StructuredTool } from "@langchain/core/tools";
5
5
  import { BaseCheckpointSaver } from "@langchain/langgraph-checkpoint";
6
6
  import { z } from "zod/v3";
7
- import { LanguageModelLike } from "@langchain/core/language_models/base";
8
7
  import { ChatResult } from "@langchain/core/outputs";
9
8
  import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
10
9
  import { ModelProfile } from "@langchain/core/language_models/profile";
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","names":[],"sources":["../../../src/agents/tests/utils.ts"],"mappings":";;;;;;;;;;;;UA2UU,UAAA;EACR,IAAA;EACA,IAAA,EAAM,MAAA;EACN,EAAA;EACA,IAAA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