langchain 1.2.24 → 1.2.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/dist/_virtual/{rolldown_runtime.cjs → _rolldown/runtime.cjs} +24 -13
- package/dist/_virtual/_rolldown/runtime.js +36 -0
- package/dist/agents/ReactAgent.cjs +52 -65
- package/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js +11 -24
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/RunnableCallable.cjs +7 -7
- package/dist/agents/RunnableCallable.cjs.map +1 -1
- package/dist/agents/RunnableCallable.js.map +1 -1
- package/dist/agents/annotation.cjs +41 -37
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.js +21 -17
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/constants.d.cts.map +1 -1
- package/dist/agents/constants.d.ts.map +1 -1
- package/dist/agents/errors.cjs +3 -3
- package/dist/agents/errors.cjs.map +1 -1
- package/dist/agents/errors.d.cts.map +1 -1
- package/dist/agents/errors.d.ts.map +1 -1
- package/dist/agents/errors.js.map +1 -1
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +2 -2
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +2 -2
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/middleware/constants.cjs +2 -2
- package/dist/agents/middleware/constants.cjs.map +1 -1
- package/dist/agents/middleware/constants.js.map +1 -1
- package/dist/agents/middleware/contextEditing.cjs +14 -27
- package/dist/agents/middleware/contextEditing.cjs.map +1 -1
- package/dist/agents/middleware/contextEditing.d.cts +2 -3
- package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
- package/dist/agents/middleware/contextEditing.d.ts +2 -3
- package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
- package/dist/agents/middleware/contextEditing.js +5 -18
- package/dist/agents/middleware/contextEditing.js.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.cjs +3 -4
- package/dist/agents/middleware/dynamicSystemPrompt.cjs.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts +2 -2
- package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts +2 -2
- package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
- package/dist/agents/middleware/dynamicSystemPrompt.js +1 -2
- package/dist/agents/middleware/dynamicSystemPrompt.js.map +1 -1
- package/dist/agents/middleware/error.cjs +2 -2
- package/dist/agents/middleware/error.cjs.map +1 -1
- package/dist/agents/middleware/error.js.map +1 -1
- package/dist/agents/middleware/hitl.cjs +16 -26
- package/dist/agents/middleware/hitl.cjs.map +1 -1
- package/dist/agents/middleware/hitl.d.cts.map +1 -1
- package/dist/agents/middleware/hitl.d.ts.map +1 -1
- package/dist/agents/middleware/hitl.js +8 -18
- package/dist/agents/middleware/hitl.js.map +1 -1
- package/dist/agents/middleware/index.js +2 -0
- package/dist/agents/middleware/llmToolSelector.cjs +9 -10
- package/dist/agents/middleware/llmToolSelector.cjs.map +1 -1
- package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
- package/dist/agents/middleware/llmToolSelector.d.ts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
- package/dist/agents/middleware/llmToolSelector.js +3 -4
- package/dist/agents/middleware/llmToolSelector.js.map +1 -1
- package/dist/agents/middleware/modelCallLimit.cjs +5 -5
- package/dist/agents/middleware/modelCallLimit.cjs.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.cts +2 -2
- package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.d.ts +2 -2
- package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/modelCallLimit.js.map +1 -1
- package/dist/agents/middleware/modelFallback.cjs.map +1 -1
- package/dist/agents/middleware/modelFallback.d.cts +0 -1
- package/dist/agents/middleware/modelFallback.d.cts.map +1 -1
- package/dist/agents/middleware/modelFallback.d.ts +0 -1
- package/dist/agents/middleware/modelFallback.d.ts.map +1 -1
- package/dist/agents/middleware/modelFallback.js.map +1 -1
- package/dist/agents/middleware/modelRetry.cjs +19 -17
- package/dist/agents/middleware/modelRetry.cjs.map +1 -1
- package/dist/agents/middleware/modelRetry.d.cts +0 -1
- package/dist/agents/middleware/modelRetry.d.cts.map +1 -1
- package/dist/agents/middleware/modelRetry.d.ts +0 -1
- package/dist/agents/middleware/modelRetry.d.ts.map +1 -1
- package/dist/agents/middleware/modelRetry.js +15 -13
- package/dist/agents/middleware/modelRetry.js.map +1 -1
- package/dist/agents/middleware/pii.cjs +21 -32
- package/dist/agents/middleware/pii.cjs.map +1 -1
- package/dist/agents/middleware/pii.d.cts +0 -1
- package/dist/agents/middleware/pii.d.cts.map +1 -1
- package/dist/agents/middleware/pii.d.ts +0 -1
- package/dist/agents/middleware/pii.d.ts.map +1 -1
- package/dist/agents/middleware/pii.js +10 -21
- package/dist/agents/middleware/pii.js.map +1 -1
- package/dist/agents/middleware/piiRedaction.cjs +22 -28
- package/dist/agents/middleware/piiRedaction.cjs.map +1 -1
- package/dist/agents/middleware/piiRedaction.d.cts +0 -1
- package/dist/agents/middleware/piiRedaction.d.cts.map +1 -1
- package/dist/agents/middleware/piiRedaction.d.ts +0 -1
- package/dist/agents/middleware/piiRedaction.d.ts.map +1 -1
- package/dist/agents/middleware/piiRedaction.js +8 -14
- package/dist/agents/middleware/piiRedaction.js.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.cjs +5 -8
- package/dist/agents/middleware/provider/anthropic/promptCaching.cjs.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts +2 -2
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts +2 -2
- package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts.map +1 -1
- package/dist/agents/middleware/provider/anthropic/promptCaching.js +3 -6
- package/dist/agents/middleware/provider/anthropic/promptCaching.js.map +1 -1
- package/dist/agents/middleware/provider/openai/moderation.cjs +17 -22
- package/dist/agents/middleware/provider/openai/moderation.cjs.map +1 -1
- package/dist/agents/middleware/provider/openai/moderation.d.cts +0 -2
- package/dist/agents/middleware/provider/openai/moderation.d.cts.map +1 -1
- package/dist/agents/middleware/provider/openai/moderation.d.ts +0 -2
- package/dist/agents/middleware/provider/openai/moderation.d.ts.map +1 -1
- package/dist/agents/middleware/provider/openai/moderation.js +10 -15
- package/dist/agents/middleware/provider/openai/moderation.js.map +1 -1
- package/dist/agents/middleware/summarization.cjs +39 -62
- package/dist/agents/middleware/summarization.cjs.map +1 -1
- package/dist/agents/middleware/summarization.d.cts +2 -2
- package/dist/agents/middleware/summarization.d.cts.map +1 -1
- package/dist/agents/middleware/summarization.d.ts +2 -2
- package/dist/agents/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.js +17 -40
- package/dist/agents/middleware/summarization.js.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.cjs +21 -27
- package/dist/agents/middleware/todoListMiddleware.cjs.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.cts +4 -4
- package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.d.ts +4 -4
- package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
- package/dist/agents/middleware/todoListMiddleware.js +12 -18
- package/dist/agents/middleware/todoListMiddleware.js.map +1 -1
- package/dist/agents/middleware/toolCallLimit.cjs +24 -46
- package/dist/agents/middleware/toolCallLimit.cjs.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.cts +2 -3
- package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.d.ts +2 -3
- package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
- package/dist/agents/middleware/toolCallLimit.js +17 -39
- package/dist/agents/middleware/toolCallLimit.js.map +1 -1
- package/dist/agents/middleware/toolEmulator.cjs +8 -13
- package/dist/agents/middleware/toolEmulator.cjs.map +1 -1
- package/dist/agents/middleware/toolEmulator.d.cts +0 -1
- package/dist/agents/middleware/toolEmulator.d.cts.map +1 -1
- package/dist/agents/middleware/toolEmulator.d.ts +0 -1
- package/dist/agents/middleware/toolEmulator.d.ts.map +1 -1
- package/dist/agents/middleware/toolEmulator.js +5 -10
- package/dist/agents/middleware/toolEmulator.js.map +1 -1
- package/dist/agents/middleware/toolRetry.cjs +19 -17
- package/dist/agents/middleware/toolRetry.cjs.map +1 -1
- package/dist/agents/middleware/toolRetry.d.cts +0 -1
- package/dist/agents/middleware/toolRetry.d.cts.map +1 -1
- package/dist/agents/middleware/toolRetry.d.ts +0 -1
- package/dist/agents/middleware/toolRetry.d.ts.map +1 -1
- package/dist/agents/middleware/toolRetry.js +15 -13
- package/dist/agents/middleware/toolRetry.js.map +1 -1
- package/dist/agents/middleware/types.cjs.map +1 -1
- package/dist/agents/middleware/types.d.cts +33 -33
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/middleware/types.d.ts +33 -33
- package/dist/agents/middleware/types.d.ts.map +1 -1
- package/dist/agents/middleware/types.js.map +1 -1
- package/dist/agents/middleware/utils.cjs +8 -8
- package/dist/agents/middleware/utils.cjs.map +1 -1
- package/dist/agents/middleware/utils.d.cts +0 -1
- package/dist/agents/middleware/utils.d.cts.map +1 -1
- package/dist/agents/middleware/utils.d.ts +0 -1
- package/dist/agents/middleware/utils.d.ts.map +1 -1
- package/dist/agents/middleware/utils.js +3 -3
- package/dist/agents/middleware/utils.js.map +1 -1
- package/dist/agents/middleware.cjs +1 -2
- package/dist/agents/middleware.cjs.map +1 -1
- package/dist/agents/middleware.d.cts +0 -1
- package/dist/agents/middleware.d.cts.map +1 -1
- package/dist/agents/middleware.d.ts +0 -1
- package/dist/agents/middleware.d.ts.map +1 -1
- package/dist/agents/middleware.js +1 -2
- package/dist/agents/middleware.js.map +1 -1
- package/dist/agents/model.cjs.map +1 -1
- package/dist/agents/model.js.map +1 -1
- package/dist/agents/nodes/AfterAgentNode.cjs +1 -2
- package/dist/agents/nodes/AfterAgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AfterAgentNode.js +1 -2
- package/dist/agents/nodes/AfterAgentNode.js.map +1 -1
- package/dist/agents/nodes/AfterModelNode.cjs +1 -2
- package/dist/agents/nodes/AfterModelNode.cjs.map +1 -1
- package/dist/agents/nodes/AfterModelNode.js +1 -2
- package/dist/agents/nodes/AfterModelNode.js.map +1 -1
- package/dist/agents/nodes/AgentNode.cjs +46 -58
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +16 -28
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/BeforeAgentNode.cjs +1 -2
- package/dist/agents/nodes/BeforeAgentNode.cjs.map +1 -1
- package/dist/agents/nodes/BeforeAgentNode.js +1 -2
- package/dist/agents/nodes/BeforeAgentNode.js.map +1 -1
- package/dist/agents/nodes/BeforeModelNode.cjs +1 -2
- package/dist/agents/nodes/BeforeModelNode.cjs.map +1 -1
- package/dist/agents/nodes/BeforeModelNode.js +1 -2
- package/dist/agents/nodes/BeforeModelNode.js.map +1 -1
- package/dist/agents/nodes/ToolNode.cjs +25 -25
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.js +6 -6
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/nodes/middleware.cjs +3 -3
- package/dist/agents/nodes/middleware.cjs.map +1 -1
- package/dist/agents/nodes/middleware.js.map +1 -1
- package/dist/agents/nodes/types.d.cts +0 -1
- package/dist/agents/nodes/types.d.cts.map +1 -1
- package/dist/agents/nodes/types.d.ts +0 -1
- package/dist/agents/nodes/types.d.ts.map +1 -1
- package/dist/agents/nodes/utils.cjs +16 -17
- package/dist/agents/nodes/utils.cjs.map +1 -1
- package/dist/agents/nodes/utils.js +2 -3
- package/dist/agents/nodes/utils.js.map +1 -1
- package/dist/agents/responses.cjs +20 -30
- package/dist/agents/responses.cjs.map +1 -1
- package/dist/agents/responses.d.cts +0 -1
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts +0 -1
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/responses.js +12 -22
- package/dist/agents/responses.js.map +1 -1
- package/dist/agents/runtime.d.cts +0 -1
- package/dist/agents/runtime.d.cts.map +1 -1
- package/dist/agents/runtime.d.ts +0 -1
- package/dist/agents/runtime.d.ts.map +1 -1
- package/dist/agents/state.cjs +1 -2
- package/dist/agents/state.cjs.map +1 -1
- package/dist/agents/state.js +1 -2
- package/dist/agents/state.js.map +1 -1
- package/dist/agents/tests/utils.cjs +21 -26
- package/dist/agents/tests/utils.cjs.map +1 -1
- package/dist/agents/tests/utils.d.cts +0 -1
- package/dist/agents/tests/utils.d.cts.map +1 -1
- package/dist/agents/tests/utils.d.ts +0 -1
- package/dist/agents/tests/utils.d.ts.map +1 -1
- package/dist/agents/tests/utils.js +12 -17
- package/dist/agents/tests/utils.js.map +1 -1
- package/dist/agents/types.d.cts +4 -5
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +4 -5
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/utils.cjs +32 -32
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js +6 -6
- package/dist/agents/utils.js.map +1 -1
- package/dist/agents/withAgentName.cjs +5 -5
- package/dist/agents/withAgentName.cjs.map +1 -1
- package/dist/agents/withAgentName.js.map +1 -1
- package/dist/chat_models/universal.cjs +34 -41
- package/dist/chat_models/universal.cjs.map +1 -1
- package/dist/chat_models/universal.d.cts.map +1 -1
- package/dist/chat_models/universal.d.ts.map +1 -1
- package/dist/chat_models/universal.js +21 -29
- package/dist/chat_models/universal.js.map +1 -1
- package/dist/hub/base.cjs +3 -4
- package/dist/hub/base.cjs.map +1 -1
- package/dist/hub/base.d.cts +0 -1
- package/dist/hub/base.d.cts.map +1 -1
- package/dist/hub/base.d.ts +0 -1
- package/dist/hub/base.d.ts.map +1 -1
- package/dist/hub/base.js +1 -2
- package/dist/hub/base.js.map +1 -1
- package/dist/hub/index.cjs +2 -2
- package/dist/hub/index.cjs.map +1 -1
- package/dist/hub/index.d.cts +0 -1
- package/dist/hub/index.d.cts.map +1 -1
- package/dist/hub/index.d.ts +0 -1
- package/dist/hub/index.d.ts.map +1 -1
- package/dist/hub/index.js +1 -2
- package/dist/hub/index.js.map +1 -1
- package/dist/hub/node.cjs +7 -13
- package/dist/hub/node.cjs.map +1 -1
- package/dist/hub/node.d.cts +0 -1
- package/dist/hub/node.d.cts.map +1 -1
- package/dist/hub/node.d.ts +0 -1
- package/dist/hub/node.d.ts.map +1 -1
- package/dist/hub/node.js +6 -13
- package/dist/hub/node.js.map +1 -1
- package/dist/index.cjs +48 -48
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -3
- package/dist/load/import_constants.cjs.map +1 -1
- package/dist/load/import_constants.js.map +1 -1
- package/dist/load/import_map.cjs +46 -47
- package/dist/load/import_map.cjs.map +1 -1
- package/dist/load/import_map.js +2 -3
- package/dist/load/import_map.js.map +1 -1
- package/dist/load/import_type.d.cts.map +1 -1
- package/dist/load/import_type.d.ts.map +1 -1
- package/dist/load/index.cjs +13 -3
- package/dist/load/index.cjs.map +1 -1
- package/dist/load/index.d.cts +9 -1
- package/dist/load/index.d.cts.map +1 -1
- package/dist/load/index.d.ts +9 -1
- package/dist/load/index.d.ts.map +1 -1
- package/dist/load/index.js +9 -0
- package/dist/load/index.js.map +1 -1
- package/dist/load/serializable.cjs +7 -6
- package/dist/load/serializable.js +4 -4
- package/dist/storage/encoder_backed.cjs +9 -10
- package/dist/storage/encoder_backed.cjs.map +1 -1
- package/dist/storage/encoder_backed.d.cts +0 -1
- package/dist/storage/encoder_backed.d.cts.map +1 -1
- package/dist/storage/encoder_backed.d.ts +0 -1
- package/dist/storage/encoder_backed.d.ts.map +1 -1
- package/dist/storage/encoder_backed.js +4 -6
- package/dist/storage/encoder_backed.js.map +1 -1
- package/dist/storage/file_system.cjs +12 -11
- package/dist/storage/file_system.cjs.map +1 -1
- package/dist/storage/file_system.d.cts +0 -1
- package/dist/storage/file_system.d.cts.map +1 -1
- package/dist/storage/file_system.d.ts +0 -1
- package/dist/storage/file_system.d.ts.map +1 -1
- package/dist/storage/file_system.js +5 -7
- package/dist/storage/file_system.js.map +1 -1
- package/dist/storage/in_memory.cjs +5 -5
- package/dist/storage/in_memory.js +2 -3
- package/package.json +6 -6
- package/dist/_virtual/rolldown_runtime.js +0 -25
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
const
|
|
1
|
+
const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
|
|
2
2
|
const require_model = require('./model.cjs');
|
|
3
3
|
const require_errors = require('./errors.cjs');
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
let _langchain_core_utils_types = require("@langchain/core/utils/types");
|
|
5
|
+
let _langchain_core_utils_json_schema = require("@langchain/core/utils/json_schema");
|
|
6
6
|
|
|
7
7
|
//#region src/agents/responses.ts
|
|
8
8
|
/**
|
|
@@ -42,18 +42,17 @@ var ToolStrategy = class ToolStrategy {
|
|
|
42
42
|
function getFunctionName(name) {
|
|
43
43
|
return name ?? `extract-${++bindingIdentifier}`;
|
|
44
44
|
}
|
|
45
|
-
if ((0,
|
|
46
|
-
const asJsonSchema
|
|
47
|
-
|
|
45
|
+
if ((0, _langchain_core_utils_types.isInteropZodSchema)(schema)) {
|
|
46
|
+
const asJsonSchema = (0, _langchain_core_utils_json_schema.toJsonSchema)(schema);
|
|
47
|
+
return new ToolStrategy(asJsonSchema, {
|
|
48
48
|
type: "function",
|
|
49
49
|
function: {
|
|
50
|
-
name: getFunctionName(asJsonSchema
|
|
50
|
+
name: getFunctionName(asJsonSchema.title),
|
|
51
51
|
strict: false,
|
|
52
|
-
description: asJsonSchema
|
|
53
|
-
parameters: asJsonSchema
|
|
52
|
+
description: asJsonSchema.description ?? "Tool for extracting structured output from the model's response.",
|
|
53
|
+
parameters: asJsonSchema
|
|
54
54
|
}
|
|
55
|
-
};
|
|
56
|
-
return new ToolStrategy(asJsonSchema$1, tool$1, outputOptions);
|
|
55
|
+
}, outputOptions);
|
|
57
56
|
}
|
|
58
57
|
let functionDefinition;
|
|
59
58
|
if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) functionDefinition = schema;
|
|
@@ -62,12 +61,10 @@ var ToolStrategy = class ToolStrategy {
|
|
|
62
61
|
description: schema.description ?? "",
|
|
63
62
|
parameters: schema.schema || schema
|
|
64
63
|
};
|
|
65
|
-
|
|
66
|
-
const tool = {
|
|
64
|
+
return new ToolStrategy((0, _langchain_core_utils_json_schema.toJsonSchema)(schema), {
|
|
67
65
|
type: "function",
|
|
68
66
|
function: functionDefinition
|
|
69
|
-
};
|
|
70
|
-
return new ToolStrategy(asJsonSchema, tool, outputOptions);
|
|
67
|
+
}, outputOptions);
|
|
71
68
|
}
|
|
72
69
|
/**
|
|
73
70
|
* Parse tool arguments according to the schema.
|
|
@@ -77,8 +74,7 @@ var ToolStrategy = class ToolStrategy {
|
|
|
77
74
|
* @returns The parsed response according to the schema type
|
|
78
75
|
*/
|
|
79
76
|
parse(toolArgs) {
|
|
80
|
-
const
|
|
81
|
-
const result = validator.validate(toolArgs);
|
|
77
|
+
const result = new _langchain_core_utils_json_schema.Validator(this.schema).validate(toolArgs);
|
|
82
78
|
if (!result.valid) throw new require_errors.StructuredOutputParsingError(this.name, result.errors.map((e) => e.error));
|
|
83
79
|
return toolArgs;
|
|
84
80
|
}
|
|
@@ -104,8 +100,7 @@ var ProviderStrategy = class ProviderStrategy {
|
|
|
104
100
|
}
|
|
105
101
|
}
|
|
106
102
|
static fromSchema(schema, strict) {
|
|
107
|
-
|
|
108
|
-
return new ProviderStrategy(asJsonSchema, strict);
|
|
103
|
+
return new ProviderStrategy((0, _langchain_core_utils_json_schema.toJsonSchema)(schema), strict);
|
|
109
104
|
}
|
|
110
105
|
/**
|
|
111
106
|
* Parse tool arguments according to the schema. If the response is not valid, return undefined.
|
|
@@ -133,9 +128,7 @@ var ProviderStrategy = class ProviderStrategy {
|
|
|
133
128
|
if (!textContent || textContent === "") return;
|
|
134
129
|
try {
|
|
135
130
|
const content = JSON.parse(textContent);
|
|
136
|
-
|
|
137
|
-
const result = validator.validate(content);
|
|
138
|
-
if (!result.valid) return;
|
|
131
|
+
if (!new _langchain_core_utils_json_schema.Validator(this.schema).validate(content).valid) return;
|
|
139
132
|
return content;
|
|
140
133
|
} catch {}
|
|
141
134
|
}
|
|
@@ -168,11 +161,11 @@ function transformResponseFormat(responseFormat, options, model) {
|
|
|
168
161
|
/**
|
|
169
162
|
* Check if all items are Zod schemas
|
|
170
163
|
*/
|
|
171
|
-
if (responseFormat.every((item) => (0,
|
|
164
|
+
if (responseFormat.every((item) => (0, _langchain_core_utils_types.isInteropZodObject)(item))) return responseFormat.map((item) => ToolStrategy.fromSchema(item, options));
|
|
172
165
|
/**
|
|
173
166
|
* Check if all items are plain objects (JSON schema)
|
|
174
167
|
*/
|
|
175
|
-
if (responseFormat.every((item) => typeof item === "object" && item !== null && !(0,
|
|
168
|
+
if (responseFormat.every((item) => typeof item === "object" && item !== null && !(0, _langchain_core_utils_types.isInteropZodObject)(item))) return responseFormat.map((item) => ToolStrategy.fromSchema(item, options));
|
|
176
169
|
throw new Error("Invalid response format: list contains mixed types.\nAll items must be either InteropZodObject or plain JSON schema objects.");
|
|
177
170
|
}
|
|
178
171
|
if (responseFormat instanceof ToolStrategy || responseFormat instanceof ProviderStrategy) return [responseFormat];
|
|
@@ -180,7 +173,7 @@ function transformResponseFormat(responseFormat, options, model) {
|
|
|
180
173
|
/**
|
|
181
174
|
* `responseFormat` is a Zod schema
|
|
182
175
|
*/
|
|
183
|
-
if ((0,
|
|
176
|
+
if ((0, _langchain_core_utils_types.isInteropZodObject)(responseFormat)) return useProviderStrategy ? [ProviderStrategy.fromSchema(responseFormat)] : [ToolStrategy.fromSchema(responseFormat, options)];
|
|
184
177
|
/**
|
|
185
178
|
* Handle plain object (JSON schema)
|
|
186
179
|
*/
|
|
@@ -244,7 +237,7 @@ function providerStrategy(responseFormat) {
|
|
|
244
237
|
/**
|
|
245
238
|
* Handle options object format
|
|
246
239
|
*/
|
|
247
|
-
if (typeof responseFormat === "object" && responseFormat !== null && "schema" in responseFormat && !(0,
|
|
240
|
+
if (typeof responseFormat === "object" && responseFormat !== null && "schema" in responseFormat && !(0, _langchain_core_utils_types.isInteropZodSchema)(responseFormat) && !("type" in responseFormat)) {
|
|
248
241
|
const { schema, strict: strictFlag } = responseFormat;
|
|
249
242
|
return ProviderStrategy.fromSchema(schema, strictFlag);
|
|
250
243
|
}
|
|
@@ -274,10 +267,7 @@ function hasSupportForJsonSchemaOutput(model) {
|
|
|
274
267
|
const modelName = model.split(":").pop();
|
|
275
268
|
return MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some((modelNameSnippet) => modelName.includes(modelNameSnippet));
|
|
276
269
|
}
|
|
277
|
-
if (require_model.isConfigurableModel(model))
|
|
278
|
-
const configurableModel = model;
|
|
279
|
-
return hasSupportForJsonSchemaOutput(configurableModel._defaultConfig.model);
|
|
280
|
-
}
|
|
270
|
+
if (require_model.isConfigurableModel(model)) return hasSupportForJsonSchemaOutput(model._defaultConfig.model);
|
|
281
271
|
if (!require_model.isBaseChatModel(model)) return false;
|
|
282
272
|
const chatModelClass = model.getName();
|
|
283
273
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responses.cjs","names":["schema: Record<string, unknown>","tool: {\n type: \"function\";\n function: FunctionDefinition;\n }","options?: ToolStrategyOptions","schema: InteropZodObject | Record<string, unknown>","outputOptions?: ToolStrategyOptions","name?: string","asJsonSchema","tool","functionDefinition: FunctionDefinition","toolArgs: Record<string, unknown>","Validator","StructuredOutputParsingError","schemaOrOptions:\n | Record<string, unknown>\n | { schema: Record<string, unknown>; strict?: boolean }","strict?: boolean","schema: InteropZodType<T> | Record<string, unknown>","response: AIMessage","textContent: string | undefined","responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined","model?: LanguageModelLike | string","responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]","responseFormat:\n | InteropZodType<unknown>\n | JsonSchemaFormat\n | { schema: InteropZodType<unknown> | JsonSchemaFormat; strict?: boolean }","isConfigurableModel","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\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\nimport { isConfigurableModel, 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: Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | 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 (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: Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | 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 | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions,\n model?: LanguageModelLike | string\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 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 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\" && item !== null && !isInteropZodObject(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 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 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: 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, an array of Zod schemas,\n * a JSON schema object, or an array of JSON schema objects.\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 | 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 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 | JsonSchemaFormat\n | { schema: JsonSchemaFormat; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | InteropZodType<unknown>\n | JsonSchemaFormat\n | { schema: InteropZodType<unknown> | JsonSchemaFormat; strict?: boolean }\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 !(\"type\" in responseFormat)\n ) {\n const { schema, strict: strictFlag } = responseFormat as {\n schema: InteropZodType<unknown> | 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\nconst CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\"ChatOpenAI\", \"ChatXAI\"];\nconst MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\n \"grok\",\n \"gpt-5\",\n \"gpt-4.1\",\n \"gpt-4o\",\n \"gpt-oss\",\n \"o3-pro\",\n \"o3-mini\",\n];\n\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model?: LanguageModelLike | string\n): boolean {\n if (!model) {\n return false;\n }\n\n if (typeof model === \"string\") {\n const modelName = model.split(\":\").pop() as string;\n return MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) => modelName.includes(modelNameSnippet)\n );\n }\n\n if (isConfigurableModel(model)) {\n const configurableModel = model as unknown as {\n _defaultConfig: { model: string };\n };\n return hasSupportForJsonSchemaOutput(\n configurableModel._defaultConfig.model\n );\n }\n\n if (!isBaseChatModel(model)) {\n return false;\n }\n\n const chatModelClass = model.getName();\n\n /**\n * for testing purposes only\n */\n if (chatModelClass === \"FakeToolCallingChatModel\") {\n return true;\n }\n\n if (\n CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.includes(chatModelClass) &&\n /**\n * OpenAI models\n */ ((\"model\" in model &&\n MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) =>\n typeof model.model === \"string\" &&\n model.model.includes(modelNameSnippet)\n )) ||\n /**\n * for testing purposes only\n */\n (chatModelClass === \"FakeToolCallingModel\" &&\n \"structuredResponse\" in model))\n ) {\n return true;\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoCA,MAAM,mCAAmC;;;;AAKzC,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CACtC,AAAQ,YAIUA,QAKAC,MAQAC,SAChB;EAdgB;EAKA;EAQA;CACd;CAEJ,IAAI,OAAO;AACT,SAAO,KAAK,KAAK,SAAS;CAC3B;CAYD,OAAO,WACLC,QACAC,eACmB;;;;;EAKnB,SAAS,gBAAgBC,MAAe;AACtC,UAAO,QAAQ,CAAC,QAAQ,EAAE,EAAE,mBAAmB;EAChD;AAED,2DAAuB,OAAO,EAAE;GAC9B,MAAMC,sEAA4B,OAAO;GACzC,MAAMC,SAAO;IACX,MAAM;IACN,UAAU;KACR,MAAM,gBAAgBD,eAAa,MAAM;KACzC,QAAQ;KACR,aACEA,eAAa,eACb;KACF,YAAYA;IACb;GACF;AACD,UAAO,IAAI,aAAaA,gBAAcC,QAAM;EAC7C;EAED,IAAIC;AACJ,MACE,OAAO,OAAO,SAAS,YACvB,OAAO,OAAO,eAAe,YAC7B,OAAO,cAAc,MAErB,qBAAqB;OAErB,qBAAqB;GACnB,MAAM,gBAAgB,OAAO,MAAgB;GAC7C,aAAc,OAAO,eAA0B;GAC/C,YAAY,OAAO,UAAW;EAC/B;EAEH,MAAM,oEAA4B,OAAO;EACzC,MAAM,OAAO;GACX,MAAM;GACN,UAAU;EACX;AACD,SAAO,IAAI,aAAa,cAAc,MAAM;CAC7C;;;;;;;;CASD,MAAMC,UAA4D;EAChE,MAAM,YAAY,IAAIC,6CAAU,KAAK;EACrC,MAAM,SAAS,UAAU,SAAS,SAAS;AAC3C,MAAI,CAAC,OAAO,MACV,OAAM,IAAIC,4CACR,KAAK,MACL,OAAO,OAAO,IAAI,CAAC,MAAM,EAAE,MAAM;AAGrC,SAAO;CACR;AAC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7E,MAAM,8CAA8C;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAOD,SAAgB,8BACdF,OACS;AACT,KAAI,CAAC,MACH,QAAO;AAGT,KAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,YAAY,MAAM,MAAM,IAAI,CAAC,KAAK;AACxC,SAAO,4CAA4C,KACjD,CAAC,qBAAqB,UAAU,SAAS,iBAAiB,CAC3D;CACF;AAED,KAAIG,kCAAoB,MAAM,EAAE;EAC9B,MAAM,oBAAoB;AAG1B,SAAO,8BACL,kBAAkB,eAAe,MAClC;CACF;AAED,KAAI,CAACC,8BAAgB,MAAM,CACzB,QAAO;CAGT,MAAM,iBAAiB,MAAM,SAAS;;;;AAKtC,KAAI,mBAAmB,2BACrB,QAAO;AAGT,KACE,4CAA4C,SAAS,eAAe,KAG9D,WAAW,SACf,4CAA4C,KAC1C,CAAC,qBACC,OAAO,MAAM,UAAU,YACvB,MAAM,MAAM,SAAS,iBAAiB,CACzC,IAIA,mBAAmB,0BAClB,wBAAwB,OAE5B,QAAO;AAGT,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"responses.cjs","names":["Validator","StructuredOutputParsingError","isConfigurableModel","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\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\nimport { isConfigurableModel, 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: Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | 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 (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: Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | 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 | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions,\n model?: LanguageModelLike | string\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 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 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\" && item !== null && !isInteropZodObject(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 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 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: 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, an array of Zod schemas,\n * a JSON schema object, or an array of JSON schema objects.\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 | 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 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 | JsonSchemaFormat\n | { schema: JsonSchemaFormat; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | InteropZodType<unknown>\n | JsonSchemaFormat\n | { schema: InteropZodType<unknown> | JsonSchemaFormat; strict?: boolean }\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 !(\"type\" in responseFormat)\n ) {\n const { schema, strict: strictFlag } = responseFormat as {\n schema: InteropZodType<unknown> | 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\nconst CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\"ChatOpenAI\", \"ChatXAI\"];\nconst MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\n \"grok\",\n \"gpt-5\",\n \"gpt-4.1\",\n \"gpt-4o\",\n \"gpt-oss\",\n \"o3-pro\",\n \"o3-mini\",\n];\n\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model?: LanguageModelLike | string\n): boolean {\n if (!model) {\n return false;\n }\n\n if (typeof model === \"string\") {\n const modelName = model.split(\":\").pop() as string;\n return MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) => modelName.includes(modelNameSnippet)\n );\n }\n\n if (isConfigurableModel(model)) {\n const configurableModel = model as unknown as {\n _defaultConfig: { model: string };\n };\n return hasSupportForJsonSchemaOutput(\n configurableModel._defaultConfig.model\n );\n }\n\n if (!isBaseChatModel(model)) {\n return false;\n }\n\n const chatModelClass = model.getName();\n\n /**\n * for testing purposes only\n */\n if (chatModelClass === \"FakeToolCallingChatModel\") {\n return true;\n }\n\n if (\n CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.includes(chatModelClass) &&\n /**\n * OpenAI models\n */ ((\"model\" in model &&\n MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) =>\n typeof model.model === \"string\" &&\n model.model.includes(modelNameSnippet)\n )) ||\n /**\n * for testing purposes only\n */\n (chatModelClass === \"FakeToolCallingModel\" &&\n \"structuredResponse\" in model))\n ) {\n return true;\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoCA,MAAM,mCAAmC;;;;AAKzC,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CACtC,AAAQ,YAIN,AAAgB,QAKhB,AAAgB,MAQhB,AAAgB,SAChB;EAdgB;EAKA;EAQA;;CAGlB,IAAI,OAAO;AACT,SAAO,KAAK,KAAK,SAAS;;CAa5B,OAAO,WACL,QACA,eACmB;;;;;EAKnB,SAAS,gBAAgB,MAAe;AACtC,UAAO,QAAQ,WAAW,EAAE;;AAG9B,0DAAuB,OAAO,EAAE;GAC9B,MAAM,mEAA4B,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;GACnB,MAAM,gBAAgB,OAAO,MAAgB;GAC7C,aAAc,OAAO,eAA0B;GAC/C,YAAY,OAAO,UAAW;GAC/B;AAOH,SAAO,IAAI,iEALuB,OAAO,EAC5B;GACX,MAAM;GACN,UAAU;GACX,EAC2C,cAAc;;;;;;;;;CAU5D,MAAM,UAA4D;EAEhE,MAAM,SADY,IAAIA,4CAAU,KAAK,OAAO,CACnB,SAAS,SAAS;AAC3C,MAAI,CAAC,OAAO,MACV,OAAM,IA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ACS;AACT,KAAI,CAAC,MACH,QAAO;AAGT,KAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,YAAY,MAAM,MAAM,IAAI,CAAC,KAAK;AACxC,SAAO,4CAA4C,MAChD,qBAAqB,UAAU,SAAS,iBAAiB,CAC3D;;AAGH,KAAIE,kCAAoB,MAAM,CAI5B,QAAO,8BAHmB,MAIN,eAAe,MAClC;AAGH,KAAI,CAACC,8BAAgB,MAAM,CACzB,QAAO;CAGT,MAAM,iBAAiB,MAAM,SAAS;;;;AAKtC,KAAI,mBAAmB,2BACrB,QAAO;AAGT,KACE,4CAA4C,SAAS,eAAe,KAG9D,WAAW,SACf,4CAA4C,MACzC,qBACC,OAAO,MAAM,UAAU,YACvB,MAAM,MAAM,SAAS,iBAAiB,CACzC,IAIA,mBAAmB,0BAClB,wBAAwB,OAE5B,QAAO;AAGT,QAAO"}
|
|
@@ -4,7 +4,6 @@ import { AIMessage } from "@langchain/core/messages";
|
|
|
4
4
|
import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
|
|
5
5
|
|
|
6
6
|
//#region src/agents/responses.d.ts
|
|
7
|
-
|
|
8
7
|
/**
|
|
9
8
|
* Special type to indicate that no response format is provided.
|
|
10
9
|
* When this type is used, the structuredResponse property should not be present in the result.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responses.d.cts","names":["InteropZodObject","InteropZodType","AIMessage","LanguageModelLike","FunctionDefinition","StructuredOutputParsingError","MultipleStructuredOutputsError","ResponseFormatUndefined","ToolStrategy","S","_T","Record","ToolStrategyOptions","U","ProviderStrategy","T","ResponseFormat","transformResponseFormat","JsonSchemaFormat","TypedToolStrategy","Array","ToolStrategyError","Promise","toolStrategy","K","providerStrategy","hasSupportForJsonSchemaOutput"],"sources":["../../src/agents/responses.d.ts"],"sourcesContent":["import { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport { StructuredOutputParsingError, MultipleStructuredOutputsError } from \"./errors.js\";\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 * 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 declare class ToolStrategy<_T = unknown> {\n /**\n * The original JSON Schema provided for structured output\n */\n readonly schema: Record<string, unknown>;\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n };\n /**\n * The options to use for the tool output.\n */\n readonly options?: ToolStrategyOptions | undefined;\n private constructor();\n get name(): string;\n static fromSchema<S extends InteropZodObject>(schema: S, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n static fromSchema(schema: Record<string, unknown>, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;\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}\nexport declare class ProviderStrategy<T = unknown> {\n private _schemaType?;\n /**\n * The schema to use for the provider strategy\n */\n readonly schema: Record<string, unknown>;\n /**\n * Whether to use strict mode for the provider strategy\n */\n readonly strict: boolean;\n private constructor();\n private constructor();\n static fromSchema<T>(schema: InteropZodType<T>, strict?: boolean): ProviderStrategy<T>;\n static fromSchema(schema: Record<string, unknown>, strict?: boolean): ProviderStrategy<Record<string, unknown>>;\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): any;\n}\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\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 declare function transformResponseFormat(responseFormat?: InteropZodType<any> | InteropZodType<any>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | ToolStrategy<any>[] | ResponseFormatUndefined, options?: ToolStrategyOptions, model?: LanguageModelLike | string): ResponseFormat[];\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError = StructuredOutputParsingError | 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?: boolean | string | ((error: ToolStrategyError) => Promise<string> | string);\n}\nexport declare function toolStrategy<T extends InteropZodType<any>>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function toolStrategy<T extends readonly InteropZodType<any>[]>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<{\n [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never;\n}[number]>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\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 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 declare function providerStrategy<T extends InteropZodType<unknown>>(responseFormat: T | {\n schema: T;\n strict?: boolean;\n}): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function providerStrategy(responseFormat: JsonSchemaFormat | {\n schema: JsonSchemaFormat;\n strict?: boolean;\n}): ProviderStrategy<Record<string, unknown>>;\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: \"null\" | \"boolean\" | \"object\" | \"array\" | \"number\" | \"string\" | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n __brand?: never;\n};\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport declare function hasSupportForJsonSchemaOutput(model?: LanguageModelLike | string): boolean;\n//# sourceMappingURL=responses.d.ts.map"],"mappings":";;;;;;;;AASA;AASA;;AAUkBI,KAnBNG,uBAAAA,GAmBMH;EAKKQ,yBAAAA,EAAAA,IAAAA;CAGSZ;;;;;;;AACFW,cAnBTH,YAmBSG,CAAAA,KAAAA,OAAAA,CAAAA,CAAAA;EAAyCC;;;EAQnDD,SAAAA,MAAAA,EAvBCA,MAuBDA,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;EAA0BA;AAAM;AAEpD;EAKqBA,SAAAA,IAAAA,EAAAA;IAO2BI,IAAAA,EAAAA,UAAAA;IAAfd,QAAAA,EA/BfG,kBA+BeH;EAAuDc,CAAAA;EAAjBD;;;EACGA,SAAAA,OAAAA,CAAAA,EA3BnDF,mBA2BmDE,GAAAA,SAAAA;EAOtDZ,QAAAA,WAAAA,CAAAA;EAAS,IAAA,IAAA,CAAA,CAAA,EAAA,MAAA;EAEjBc,OAAAA,UAAc,CAAA,UAjCMhB,gBAiCiBc,CAAAA,CAAAA,MAAAA,EAjCSL,CAiCTK,EAAAA,aAAgB,CAAA,EAjCYF,mBAiCZ,CAAA,EAjCkCJ,YAiClC,CAjC+CC,CAiC/C,SAjCyDR,cAiCzD,CAAA,KAAA,EAAA,CAAA,GAjCmFY,CAiCnF,GAAA,OAAA,CAAA;EAkBhDM,OAAAA,UAAAA,CAAAA,MAAiB,EAlDJR,MAkDI,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,aAAA,CAAA,EAlDqCC,mBAkDrC,CAAA,EAlD2DJ,YAkD3D,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,OAAA,GAAU,mBAAA,GACT,iBAAA,CAAkB,MAAA;;;;;;;;;AA9CrB;;;;;AAGA;;;;;;;;;;;AA0BA;;;;;;;;;;;;;;;;;;;;;;;iBA+HgB,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,gBAAA;EACE,MAAA,EAAQ,gBAAA;EAAkB,MAAA;AAAA,IAC/B,gBAAA,CAAiB,MAAA;;;;;KAuCR,gBAAA;EACV,IAAA;EAQA,UAAA,GAAa,MAAA;EACb,QAAA;EACA,oBAAA;EAAA,CACC,GAAA;AAAA;EAGD,OAAA;AAAA"}
|
|
@@ -4,7 +4,6 @@ import { InteropZodObject, InteropZodType } from "@langchain/core/utils/types";
|
|
|
4
4
|
import { FunctionDefinition, LanguageModelLike } from "@langchain/core/language_models/base";
|
|
5
5
|
|
|
6
6
|
//#region src/agents/responses.d.ts
|
|
7
|
-
|
|
8
7
|
/**
|
|
9
8
|
* Special type to indicate that no response format is provided.
|
|
10
9
|
* When this type is used, the structuredResponse property should not be present in the result.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responses.d.ts","names":["InteropZodObject","InteropZodType","AIMessage","LanguageModelLike","FunctionDefinition","StructuredOutputParsingError","MultipleStructuredOutputsError","ResponseFormatUndefined","ToolStrategy","S","_T","Record","ToolStrategyOptions","U","ProviderStrategy","T","ResponseFormat","transformResponseFormat","JsonSchemaFormat","TypedToolStrategy","Array","ToolStrategyError","Promise","toolStrategy","K","providerStrategy","hasSupportForJsonSchemaOutput"],"sources":["../../src/agents/responses.d.ts"],"sourcesContent":["import { InteropZodObject, InteropZodType } from \"@langchain/core/utils/types\";\nimport { type AIMessage } from \"@langchain/core/messages\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type FunctionDefinition } from \"@langchain/core/language_models/base\";\nimport { StructuredOutputParsingError, MultipleStructuredOutputsError } from \"./errors.js\";\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 * 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 declare class ToolStrategy<_T = unknown> {\n /**\n * The original JSON Schema provided for structured output\n */\n readonly schema: Record<string, unknown>;\n /**\n * The tool that will be used to parse the tool call arguments.\n */\n readonly tool: {\n type: \"function\";\n function: FunctionDefinition;\n };\n /**\n * The options to use for the tool output.\n */\n readonly options?: ToolStrategyOptions | undefined;\n private constructor();\n get name(): string;\n static fromSchema<S extends InteropZodObject>(schema: S, outputOptions?: ToolStrategyOptions): ToolStrategy<S extends InteropZodType<infer U> ? U : unknown>;\n static fromSchema(schema: Record<string, unknown>, outputOptions?: ToolStrategyOptions): ToolStrategy<Record<string, unknown>>;\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}\nexport declare class ProviderStrategy<T = unknown> {\n private _schemaType?;\n /**\n * The schema to use for the provider strategy\n */\n readonly schema: Record<string, unknown>;\n /**\n * Whether to use strict mode for the provider strategy\n */\n readonly strict: boolean;\n private constructor();\n private constructor();\n static fromSchema<T>(schema: InteropZodType<T>, strict?: boolean): ProviderStrategy<T>;\n static fromSchema(schema: Record<string, unknown>, strict?: boolean): ProviderStrategy<Record<string, unknown>>;\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): any;\n}\nexport type ResponseFormat = ToolStrategy<any> | ProviderStrategy<any>;\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 declare function transformResponseFormat(responseFormat?: InteropZodType<any> | InteropZodType<any>[] | JsonSchemaFormat | JsonSchemaFormat[] | ResponseFormat | ToolStrategy<any>[] | ResponseFormatUndefined, options?: ToolStrategyOptions, model?: LanguageModelLike | string): ResponseFormat[];\n/**\n * Branded type for ToolStrategy arrays that preserves type information\n */\nexport interface TypedToolStrategy<T = unknown> extends Array<ToolStrategy<any>> {\n _schemaType?: T;\n}\nexport type ToolStrategyError = StructuredOutputParsingError | 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?: boolean | string | ((error: ToolStrategyError) => Promise<string> | string);\n}\nexport declare function toolStrategy<T extends InteropZodType<any>>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function toolStrategy<T extends readonly InteropZodType<any>[]>(responseFormat: T, options?: ToolStrategyOptions): TypedToolStrategy<{\n [K in keyof T]: T[K] extends InteropZodType<infer U> ? U : never;\n}[number]>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat, options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\nexport declare function toolStrategy(responseFormat: JsonSchemaFormat[], options?: ToolStrategyOptions): TypedToolStrategy<Record<string, unknown>>;\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 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 declare function providerStrategy<T extends InteropZodType<unknown>>(responseFormat: T | {\n schema: T;\n strict?: boolean;\n}): ProviderStrategy<T extends InteropZodType<infer U> ? U : never>;\nexport declare function providerStrategy(responseFormat: JsonSchemaFormat | {\n schema: JsonSchemaFormat;\n strict?: boolean;\n}): ProviderStrategy<Record<string, unknown>>;\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: \"null\" | \"boolean\" | \"object\" | \"array\" | \"number\" | \"string\" | \"integer\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n [key: string]: unknown;\n} & {\n __brand?: never;\n};\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport declare function hasSupportForJsonSchemaOutput(model?: LanguageModelLike | string): boolean;\n//# sourceMappingURL=responses.d.ts.map"],"mappings":";;;;;;;;AASA;AASA;;AAUkBI,KAnBNG,uBAAAA,GAmBMH;EAKKQ,yBAAAA,EAAAA,IAAAA;CAGSZ;;;;;;;AACFW,cAnBTH,YAmBSG,CAAAA,KAAAA,OAAAA,CAAAA,CAAAA;EAAyCC;;;EAQnDD,SAAAA,MAAAA,EAvBCA,MAuBDA,CAAAA,MAAAA,EAAAA,OAAAA,CAAAA;EAA0BA;AAAM;AAEpD;EAKqBA,SAAAA,IAAAA,EAAAA;IAO2BI,IAAAA,EAAAA,UAAAA;IAAfd,QAAAA,EA/BfG,kBA+BeH;EAAuDc,CAAAA;EAAjBD;;;EACGA,SAAAA,OAAAA,CAAAA,EA3BnDF,mBA2BmDE,GAAAA,SAAAA;EAOtDZ,QAAAA,WAAAA,CAAAA;EAAS,IAAA,IAAA,CAAA,CAAA,EAAA,MAAA;EAEjBc,OAAAA,UAAc,CAAA,UAjCMhB,gBAiCiBc,CAAAA,CAAAA,MAAAA,EAjCSL,CAiCTK,EAAAA,aAAgB,CAAA,EAjCYF,mBAiCZ,CAAA,EAjCkCJ,YAiClC,CAjC+CC,CAiC/C,SAjCyDR,cAiCzD,CAAA,KAAA,EAAA,CAAA,GAjCmFY,CAiCnF,GAAA,OAAA,CAAA;EAkBhDM,OAAAA,UAAAA,CAAAA,MAAiB,EAlDJR,MAkDII,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,aAAA,CAAA,EAlDqCH,mBAkDrC,CAAA,EAlD2DJ,YAkD3D,CAlDwEG,M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U,mBAAA,GACT,iBAAA,CAAkB,MAAA;;;;;;;;;AA9CrB;;;;;AAGA;;;;;;;;;;;AA0BA;;;;;;;;;;;;;;;;;;;;;;;iBA+HgB,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,gBAAA;EACE,MAAA,EAAQ,gBAAA;EAAkB,MAAA;AAAA,IAC/B,gBAAA,CAAiB,MAAA;;;;;KAuCR,gBAAA;EACV,IAAA;EAQA,UAAA,GAAa,MAAA;EACb,QAAA;EACA,oBAAA;EAAA,CACC,GAAA;AAAA;EAGD,OAAA;AAAA"}
|
package/dist/agents/responses.js
CHANGED
|
@@ -42,17 +42,16 @@ var ToolStrategy = class ToolStrategy {
|
|
|
42
42
|
return name ?? `extract-${++bindingIdentifier}`;
|
|
43
43
|
}
|
|
44
44
|
if (isInteropZodSchema(schema)) {
|
|
45
|
-
const asJsonSchema
|
|
46
|
-
|
|
45
|
+
const asJsonSchema = toJsonSchema(schema);
|
|
46
|
+
return new ToolStrategy(asJsonSchema, {
|
|
47
47
|
type: "function",
|
|
48
48
|
function: {
|
|
49
|
-
name: getFunctionName(asJsonSchema
|
|
49
|
+
name: getFunctionName(asJsonSchema.title),
|
|
50
50
|
strict: false,
|
|
51
|
-
description: asJsonSchema
|
|
52
|
-
parameters: asJsonSchema
|
|
51
|
+
description: asJsonSchema.description ?? "Tool for extracting structured output from the model's response.",
|
|
52
|
+
parameters: asJsonSchema
|
|
53
53
|
}
|
|
54
|
-
};
|
|
55
|
-
return new ToolStrategy(asJsonSchema$1, tool$1, outputOptions);
|
|
54
|
+
}, outputOptions);
|
|
56
55
|
}
|
|
57
56
|
let functionDefinition;
|
|
58
57
|
if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) functionDefinition = schema;
|
|
@@ -61,12 +60,10 @@ var ToolStrategy = class ToolStrategy {
|
|
|
61
60
|
description: schema.description ?? "",
|
|
62
61
|
parameters: schema.schema || schema
|
|
63
62
|
};
|
|
64
|
-
|
|
65
|
-
const tool = {
|
|
63
|
+
return new ToolStrategy(toJsonSchema(schema), {
|
|
66
64
|
type: "function",
|
|
67
65
|
function: functionDefinition
|
|
68
|
-
};
|
|
69
|
-
return new ToolStrategy(asJsonSchema, tool, outputOptions);
|
|
66
|
+
}, outputOptions);
|
|
70
67
|
}
|
|
71
68
|
/**
|
|
72
69
|
* Parse tool arguments according to the schema.
|
|
@@ -76,8 +73,7 @@ var ToolStrategy = class ToolStrategy {
|
|
|
76
73
|
* @returns The parsed response according to the schema type
|
|
77
74
|
*/
|
|
78
75
|
parse(toolArgs) {
|
|
79
|
-
const
|
|
80
|
-
const result = validator.validate(toolArgs);
|
|
76
|
+
const result = new Validator(this.schema).validate(toolArgs);
|
|
81
77
|
if (!result.valid) throw new StructuredOutputParsingError(this.name, result.errors.map((e) => e.error));
|
|
82
78
|
return toolArgs;
|
|
83
79
|
}
|
|
@@ -103,8 +99,7 @@ var ProviderStrategy = class ProviderStrategy {
|
|
|
103
99
|
}
|
|
104
100
|
}
|
|
105
101
|
static fromSchema(schema, strict) {
|
|
106
|
-
|
|
107
|
-
return new ProviderStrategy(asJsonSchema, strict);
|
|
102
|
+
return new ProviderStrategy(toJsonSchema(schema), strict);
|
|
108
103
|
}
|
|
109
104
|
/**
|
|
110
105
|
* Parse tool arguments according to the schema. If the response is not valid, return undefined.
|
|
@@ -132,9 +127,7 @@ var ProviderStrategy = class ProviderStrategy {
|
|
|
132
127
|
if (!textContent || textContent === "") return;
|
|
133
128
|
try {
|
|
134
129
|
const content = JSON.parse(textContent);
|
|
135
|
-
|
|
136
|
-
const result = validator.validate(content);
|
|
137
|
-
if (!result.valid) return;
|
|
130
|
+
if (!new Validator(this.schema).validate(content).valid) return;
|
|
138
131
|
return content;
|
|
139
132
|
} catch {}
|
|
140
133
|
}
|
|
@@ -273,10 +266,7 @@ function hasSupportForJsonSchemaOutput(model) {
|
|
|
273
266
|
const modelName = model.split(":").pop();
|
|
274
267
|
return MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some((modelNameSnippet) => modelName.includes(modelNameSnippet));
|
|
275
268
|
}
|
|
276
|
-
if (isConfigurableModel(model))
|
|
277
|
-
const configurableModel = model;
|
|
278
|
-
return hasSupportForJsonSchemaOutput(configurableModel._defaultConfig.model);
|
|
279
|
-
}
|
|
269
|
+
if (isConfigurableModel(model)) return hasSupportForJsonSchemaOutput(model._defaultConfig.model);
|
|
280
270
|
if (!isBaseChatModel(model)) return false;
|
|
281
271
|
const chatModelClass = model.getName();
|
|
282
272
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responses.js","names":["schema: Record<string, unknown>","tool: {\n type: \"function\";\n function: FunctionDefinition;\n }","options?: ToolStrategyOptions","schema: InteropZodObject | Record<string, unknown>","outputOptions?: ToolStrategyOptions","name?: string","asJsonSchema","tool","functionDefinition: FunctionDefinition","toolArgs: Record<string, unknown>","schemaOrOptions:\n | Record<string, unknown>\n | { schema: Record<string, unknown>; strict?: boolean }","strict?: boolean","schema: InteropZodType<T> | Record<string, unknown>","response: AIMessage","textContent: string | undefined","responseFormat?:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined","model?: LanguageModelLike | string","responseFormat:\n | InteropZodType<any>\n | InteropZodType<any>[]\n | JsonSchemaFormat\n | JsonSchemaFormat[]","responseFormat:\n | InteropZodType<unknown>\n | JsonSchemaFormat\n | { schema: InteropZodType<unknown> | JsonSchemaFormat; strict?: boolean }"],"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\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\nimport { isConfigurableModel, 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: Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | 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 (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: Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | 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 | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions,\n model?: LanguageModelLike | string\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 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 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\" && item !== null && !isInteropZodObject(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 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 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: 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, an array of Zod schemas,\n * a JSON schema object, or an array of JSON schema objects.\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 | 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 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 | JsonSchemaFormat\n | { schema: JsonSchemaFormat; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | InteropZodType<unknown>\n | JsonSchemaFormat\n | { schema: InteropZodType<unknown> | JsonSchemaFormat; strict?: boolean }\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 !(\"type\" in responseFormat)\n ) {\n const { schema, strict: strictFlag } = responseFormat as {\n schema: InteropZodType<unknown> | 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\nconst CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\"ChatOpenAI\", \"ChatXAI\"];\nconst MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\n \"grok\",\n \"gpt-5\",\n \"gpt-4.1\",\n \"gpt-4o\",\n \"gpt-oss\",\n \"o3-pro\",\n \"o3-mini\",\n];\n\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model?: LanguageModelLike | string\n): boolean {\n if (!model) {\n return false;\n }\n\n if (typeof model === \"string\") {\n const modelName = model.split(\":\").pop() as string;\n return MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) => modelName.includes(modelNameSnippet)\n );\n }\n\n if (isConfigurableModel(model)) {\n const configurableModel = model as unknown as {\n _defaultConfig: { model: string };\n };\n return hasSupportForJsonSchemaOutput(\n configurableModel._defaultConfig.model\n );\n }\n\n if (!isBaseChatModel(model)) {\n return false;\n }\n\n const chatModelClass = model.getName();\n\n /**\n * for testing purposes only\n */\n if (chatModelClass === \"FakeToolCallingChatModel\") {\n return true;\n }\n\n if (\n CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.includes(chatModelClass) &&\n /**\n * OpenAI models\n */ ((\"model\" in model &&\n MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) =>\n typeof model.model === \"string\" &&\n model.model.includes(modelNameSnippet)\n )) ||\n /**\n * for testing purposes only\n */\n (chatModelClass === \"FakeToolCallingModel\" &&\n \"structuredResponse\" in model))\n ) {\n return true;\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoCA,MAAM,mCAAmC;;;;AAKzC,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CACtC,AAAQ,YAIUA,QAKAC,MAQAC,SAChB;EAdgB;EAKA;EAQA;CACd;CAEJ,IAAI,OAAO;AACT,SAAO,KAAK,KAAK,SAAS;CAC3B;CAYD,OAAO,WACLC,QACAC,eACmB;;;;;EAKnB,SAAS,gBAAgBC,MAAe;AACtC,UAAO,QAAQ,CAAC,QAAQ,EAAE,EAAE,mBAAmB;EAChD;AAED,MAAI,mBAAmB,OAAO,EAAE;GAC9B,MAAMC,iBAAe,aAAa,OAAO;GACzC,MAAMC,SAAO;IACX,MAAM;IACN,UAAU;KACR,MAAM,gBAAgBD,eAAa,MAAM;KACzC,QAAQ;KACR,aACEA,eAAa,eACb;KACF,YAAYA;IACb;GACF;AACD,UAAO,IAAI,aAAaA,gBAAcC,QAAM;EAC7C;EAED,IA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R"}
|
|
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\";\n\nimport {\n StructuredOutputParsingError,\n MultipleStructuredOutputsError,\n} from \"./errors.js\";\nimport { isConfigurableModel, 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: Record<string, unknown>,\n outputOptions?: ToolStrategyOptions\n ): ToolStrategy<Record<string, unknown>>;\n\n static fromSchema(\n schema: InteropZodObject | 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 (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: Record<string, unknown>,\n strict?: boolean\n ): ProviderStrategy<Record<string, unknown>>;\n\n static fromSchema<T = unknown>(\n schema: InteropZodType<T> | 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 | JsonSchemaFormat\n | JsonSchemaFormat[]\n | ResponseFormat\n | ToolStrategy<any>[]\n | ResponseFormatUndefined,\n options?: ToolStrategyOptions,\n model?: LanguageModelLike | string\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 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 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\" && item !== null && !isInteropZodObject(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 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 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: 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, an array of Zod schemas,\n * a JSON schema object, or an array of JSON schema objects.\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 | 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 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 | JsonSchemaFormat\n | { schema: JsonSchemaFormat; strict?: boolean }\n): ProviderStrategy<Record<string, unknown>>;\nexport function providerStrategy(\n responseFormat:\n | InteropZodType<unknown>\n | JsonSchemaFormat\n | { schema: InteropZodType<unknown> | JsonSchemaFormat; strict?: boolean }\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 !(\"type\" in responseFormat)\n ) {\n const { schema, strict: strictFlag } = responseFormat as {\n schema: InteropZodType<unknown> | 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\nconst CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\"ChatOpenAI\", \"ChatXAI\"];\nconst MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT = [\n \"grok\",\n \"gpt-5\",\n \"gpt-4.1\",\n \"gpt-4o\",\n \"gpt-oss\",\n \"o3-pro\",\n \"o3-mini\",\n];\n\n/**\n * Identifies the models that support JSON schema output\n * @param model - The model to check\n * @returns True if the model supports JSON schema output, false otherwise\n */\nexport function hasSupportForJsonSchemaOutput(\n model?: LanguageModelLike | string\n): boolean {\n if (!model) {\n return false;\n }\n\n if (typeof model === \"string\") {\n const modelName = model.split(\":\").pop() as string;\n return MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) => modelName.includes(modelNameSnippet)\n );\n }\n\n if (isConfigurableModel(model)) {\n const configurableModel = model as unknown as {\n _defaultConfig: { model: string };\n };\n return hasSupportForJsonSchemaOutput(\n configurableModel._defaultConfig.model\n );\n }\n\n if (!isBaseChatModel(model)) {\n return false;\n }\n\n const chatModelClass = model.getName();\n\n /**\n * for testing purposes only\n */\n if (chatModelClass === \"FakeToolCallingChatModel\") {\n return true;\n }\n\n if (\n CHAT_MODELS_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.includes(chatModelClass) &&\n /**\n * OpenAI models\n */ ((\"model\" in model &&\n MODEL_NAMES_THAT_SUPPORT_JSON_SCHEMA_OUTPUT.some(\n (modelNameSnippet) =>\n typeof model.model === \"string\" &&\n model.model.includes(modelNameSnippet)\n )) ||\n /**\n * for testing purposes only\n */\n (chatModelClass === \"FakeToolCallingModel\" &&\n \"structuredResponse\" in model))\n ) {\n return true;\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoCA,MAAM,mCAAmC;;;;AAKzC,IAAI,oBAAoB;;;;;;;AAQxB,IAAa,eAAb,MAAa,aAA2B;CACtC,AAAQ,YAIN,AAAgB,QAKhB,AAAgB,MAQhB,AAAgB,SAChB;EAdgB;EAKA;EAQA;;CAGlB,IAAI,OAAO;AACT,SAAO,KAAK,KAAK,SAAS;;CAa5B,OAAO,WACL,QACA,eACmB;;;;;EAKnB,SAAS,gBAAgB,MAAe;AACtC,UAAO,QAAQ,WAAW,EAAE;;AAG9B,MAAI,mBAAmB,OAAO,EAAE;GAC9B,MAAM,eAAe,aAAa,OAAO;AAYzC,UAAO,IAAI,aAAa,cAXX;IACX,MAAM;IACN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