langchain 1.0.0-alpha.6 → 1.0.0-alpha.7
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/dist/agents/ReactAgent.cjs.map +1 -1
- package/dist/agents/ReactAgent.d.cts +1 -2
- package/dist/agents/ReactAgent.d.cts.map +1 -1
- package/dist/agents/ReactAgent.d.ts +1 -2
- package/dist/agents/ReactAgent.d.ts.map +1 -1
- package/dist/agents/ReactAgent.js.map +1 -1
- package/dist/agents/annotation.cjs.map +1 -1
- package/dist/agents/annotation.d.cts +12 -5
- package/dist/agents/annotation.d.cts.map +1 -1
- package/dist/agents/annotation.d.ts +12 -5
- package/dist/agents/annotation.d.ts.map +1 -1
- package/dist/agents/annotation.js.map +1 -1
- package/dist/agents/createAgent.cjs.map +1 -1
- package/dist/agents/createAgent.js.map +1 -1
- package/dist/agents/index.cjs.map +1 -1
- package/dist/agents/index.d.cts +3 -3
- package/dist/agents/index.d.cts.map +1 -1
- package/dist/agents/index.d.ts +3 -3
- package/dist/agents/index.d.ts.map +1 -1
- package/dist/agents/index.js.map +1 -1
- package/dist/agents/interrupt.d.cts +14 -1
- package/dist/agents/interrupt.d.cts.map +1 -1
- package/dist/agents/interrupt.d.ts +14 -1
- package/dist/agents/interrupt.d.ts.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.cjs +262 -55
- package/dist/agents/middlewareAgent/ReactAgent.cjs.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.d.cts +97 -10
- package/dist/agents/middlewareAgent/ReactAgent.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.d.ts +97 -10
- package/dist/agents/middlewareAgent/ReactAgent.d.ts.map +1 -1
- package/dist/agents/middlewareAgent/ReactAgent.js +264 -57
- package/dist/agents/middlewareAgent/ReactAgent.js.map +1 -1
- package/dist/agents/middlewareAgent/annotation.cjs +10 -4
- package/dist/agents/middlewareAgent/annotation.cjs.map +1 -1
- package/dist/agents/middlewareAgent/annotation.js +10 -4
- package/dist/agents/middlewareAgent/annotation.js.map +1 -1
- package/dist/agents/middlewareAgent/constants.d.cts +5 -0
- package/dist/agents/middlewareAgent/constants.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/constants.d.ts +5 -0
- package/dist/agents/middlewareAgent/constants.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/index.cjs.map +1 -1
- package/dist/agents/middlewareAgent/index.js.map +1 -1
- package/dist/agents/middlewareAgent/middleware/bigTool.cjs +162 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.d.cts +113 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.d.ts +113 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.js +161 -0
- package/dist/agents/middlewareAgent/middleware/bigTool.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.cjs +58 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.cjs.map +1 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.cts +46 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.cts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.ts +46 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.d.ts.map +1 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.js +58 -0
- package/dist/agents/middlewareAgent/middleware/dynamicSystemPrompt.js.map +1 -0
- package/dist/agents/middlewareAgent/middleware/hitl.cjs +160 -84
- package/dist/agents/middlewareAgent/middleware/hitl.cjs.map +1 -1
- package/dist/agents/middlewareAgent/middleware/hitl.d.cts +271 -51
- package/dist/agents/middlewareAgent/middleware/hitl.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/middleware/hitl.d.ts +271 -51
- package/dist/agents/middlewareAgent/middleware/hitl.d.ts.map +1 -1
- package/dist/agents/middlewareAgent/middleware/hitl.js +161 -85
- package/dist/agents/middlewareAgent/middleware/hitl.js.map +1 -1
- package/dist/agents/middlewareAgent/middleware/index.cjs +6 -0
- package/dist/agents/middlewareAgent/middleware/index.cjs.map +1 -1
- package/dist/agents/middlewareAgent/middleware/index.d.cts +6 -4
- package/dist/agents/middlewareAgent/middleware/index.d.ts +6 -4
- package/dist/agents/middlewareAgent/middleware/index.js +5 -1
- package/dist/agents/middlewareAgent/middleware/index.js.map +1 -1
- package/dist/agents/middlewareAgent/middleware/promptCaching.cjs +24 -8
- package/dist/agents/middlewareAgent/middleware/promptCaching.cjs.map +1 -1
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.cts +51 -6
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.ts +51 -6
- package/dist/agents/middlewareAgent/middleware/promptCaching.d.ts.map +1 -1
- package/dist/agents/middlewareAgent/middleware/promptCaching.js +24 -8
- package/dist/agents/middlewareAgent/middleware/promptCaching.js.map +1 -1
- package/dist/agents/middlewareAgent/middleware/summarization.cjs +24 -12
- package/dist/agents/middlewareAgent/middleware/summarization.cjs.map +1 -1
- package/dist/agents/middlewareAgent/middleware/summarization.d.cts +5 -3
- package/dist/agents/middlewareAgent/middleware/summarization.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/middleware/summarization.d.ts +11 -9
- package/dist/agents/middlewareAgent/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middlewareAgent/middleware/summarization.js +25 -13
- package/dist/agents/middlewareAgent/middleware/summarization.js.map +1 -1
- package/dist/agents/middlewareAgent/middleware.cjs +8 -5
- package/dist/agents/middlewareAgent/middleware.cjs.map +1 -1
- package/dist/agents/middlewareAgent/middleware.d.cts +67 -7
- package/dist/agents/middlewareAgent/middleware.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/middleware.d.ts +67 -7
- package/dist/agents/middlewareAgent/middleware.d.ts.map +1 -1
- package/dist/agents/middlewareAgent/middleware.js +8 -5
- package/dist/agents/middlewareAgent/middleware.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs +2 -2
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.js +2 -2
- package/dist/agents/middlewareAgent/nodes/AfterModalNode.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs +117 -68
- package/dist/agents/middlewareAgent/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/AgentNode.js +121 -72
- package/dist/agents/middlewareAgent/nodes/AgentNode.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs +2 -2
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js +2 -2
- package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/middleware.cjs +42 -17
- package/dist/agents/middlewareAgent/nodes/middleware.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/middleware.js +42 -18
- package/dist/agents/middlewareAgent/nodes/middleware.js.map +1 -1
- package/dist/agents/middlewareAgent/nodes/utils.cjs +25 -11
- package/dist/agents/middlewareAgent/nodes/utils.cjs.map +1 -1
- package/dist/agents/middlewareAgent/nodes/utils.js +26 -12
- package/dist/agents/middlewareAgent/nodes/utils.js.map +1 -1
- package/dist/agents/middlewareAgent/types.d.cts +153 -66
- package/dist/agents/middlewareAgent/types.d.cts.map +1 -1
- package/dist/agents/middlewareAgent/types.d.ts +153 -66
- package/dist/agents/middlewareAgent/types.d.ts.map +1 -1
- package/dist/agents/model.cjs +13 -0
- package/dist/agents/model.cjs.map +1 -0
- package/dist/agents/model.js +11 -0
- package/dist/agents/model.js.map +1 -0
- package/dist/agents/nodes/AgentNode.cjs +56 -28
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +57 -29
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/ToolNode.cjs +1 -1
- package/dist/agents/nodes/ToolNode.cjs.map +1 -1
- package/dist/agents/nodes/ToolNode.d.cts +1 -1
- package/dist/agents/nodes/ToolNode.js +1 -1
- package/dist/agents/nodes/ToolNode.js.map +1 -1
- package/dist/agents/responses.cjs +52 -10
- package/dist/agents/responses.cjs.map +1 -1
- package/dist/agents/responses.d.cts +12 -20
- package/dist/agents/responses.d.cts.map +1 -1
- package/dist/agents/responses.d.ts +12 -20
- package/dist/agents/responses.d.ts.map +1 -1
- package/dist/agents/responses.js +52 -11
- package/dist/agents/responses.js.map +1 -1
- package/dist/agents/types.d.cts +2 -3
- package/dist/agents/types.d.cts.map +1 -1
- package/dist/agents/types.d.ts +2 -3
- package/dist/agents/types.d.ts.map +1 -1
- package/dist/agents/utils.cjs +5 -23
- package/dist/agents/utils.cjs.map +1 -1
- package/dist/agents/utils.js +2 -19
- package/dist/agents/utils.js.map +1 -1
- package/dist/chains/query_constructor/index.d.cts +1 -1
- package/dist/chains/summarization/load.d.ts +2 -2
- package/dist/chains/summarization/load.d.ts.map +1 -1
- package/dist/embeddings/cache_backed.d.ts +1 -1
- package/dist/evaluation/comparison/pairwise.d.cts.map +1 -1
- package/dist/evaluation/comparison/pairwise.d.ts.map +1 -1
- package/dist/evaluation/criteria/criteria.d.cts.map +1 -1
- package/dist/evaluation/criteria/criteria.d.ts.map +1 -1
- package/dist/index.cjs +38 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -4
- package/dist/index.d.ts +11 -4
- package/dist/index.js +18 -4
- package/dist/index.js.map +1 -1
- package/dist/langchain-core/dist/messages/base.d.cts.map +1 -1
- package/dist/langchain-core/dist/messages/content/index.d.cts +20 -1
- package/dist/langchain-core/dist/messages/content/index.d.cts.map +1 -1
- package/dist/langchain-core/dist/messages/content/tools.d.cts +67 -6
- package/dist/langchain-core/dist/messages/content/tools.d.cts.map +1 -1
- package/dist/langchain-core/dist/messages/message.d.cts +6 -6
- package/dist/langchain-core/dist/messages/message.d.cts.map +1 -1
- package/dist/langchain-core/dist/utils/types/index.d.cts.map +1 -1
- package/dist/libs/langchain-core/dist/messages/base.d.ts.map +1 -1
- package/dist/libs/langchain-core/dist/messages/content/index.d.ts +20 -1
- package/dist/libs/langchain-core/dist/messages/content/index.d.ts.map +1 -1
- package/dist/libs/langchain-core/dist/messages/content/tools.d.ts +67 -6
- package/dist/libs/langchain-core/dist/messages/content/tools.d.ts.map +1 -1
- package/dist/libs/langchain-core/dist/messages/message.d.ts +6 -6
- package/dist/libs/langchain-core/dist/messages/message.d.ts.map +1 -1
- package/dist/libs/langchain-core/dist/utils/types/index.d.ts.map +1 -1
- package/dist/load/import_map.cjs +1 -1
- package/dist/load/import_map.js +1 -1
- package/dist/output_parsers/structured.d.cts +1 -1
- package/dist/tools/fs.d.cts +1 -1
- package/dist/tools/retriever.d.cts +1 -1
- package/package.json +7 -7
|
@@ -1,16 +1,19 @@
|
|
|
1
1
|
import { createMiddleware } from "../middleware.js";
|
|
2
|
-
import { AIMessage, ToolMessage
|
|
2
|
+
import { AIMessage, ToolMessage } from "@langchain/core/messages";
|
|
3
3
|
import { interrupt } from "@langchain/langgraph";
|
|
4
|
+
import { interopParse } from "@langchain/core/utils/types";
|
|
4
5
|
import { z } from "zod/v3";
|
|
5
|
-
import { v4 } from "uuid";
|
|
6
6
|
|
|
7
7
|
//#region src/agents/middlewareAgent/middleware/hitl.ts
|
|
8
|
+
const ToolConfigSchema = z.object({
|
|
9
|
+
allowAccept: z.boolean().optional(),
|
|
10
|
+
allowEdit: z.boolean().optional(),
|
|
11
|
+
allowRespond: z.boolean().optional(),
|
|
12
|
+
description: z.string().optional()
|
|
13
|
+
});
|
|
8
14
|
const contextSchema = z.object({
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
description: z.string().optional()
|
|
12
|
-
})).default({}),
|
|
13
|
-
messagePrefix: z.string().default("Tool execution requires approval")
|
|
15
|
+
interruptOn: z.record(z.union([z.boolean(), ToolConfigSchema])).optional(),
|
|
16
|
+
descriptionPrefix: z.string().default("Tool execution requires approval")
|
|
14
17
|
});
|
|
15
18
|
/**
|
|
16
19
|
* Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.
|
|
@@ -19,6 +22,37 @@ const contextSchema = z.object({
|
|
|
19
22
|
* capabilities before execution. It enables selective approval workflows where certain tools
|
|
20
23
|
* require human intervention while others can execute automatically.
|
|
21
24
|
*
|
|
25
|
+
* A invocation result that has been interrupted by the middleware will have a `__interrupt__`
|
|
26
|
+
* property that contains the interrupt request. You can loop over the request to determine
|
|
27
|
+
* which tools were interrupted, and how to handle them separately.
|
|
28
|
+
*
|
|
29
|
+
* ```ts
|
|
30
|
+
* import { type ToolApprovalRequest, type HumanInTheLoopMiddlewareHumanResponse } from "langchain/middleware";
|
|
31
|
+
* import { type Interrupt } from "langchain";
|
|
32
|
+
*
|
|
33
|
+
* const result = await agent.invoke(request);
|
|
34
|
+
* const interruptRequest = initialResult.__interrupt__?.[0] as Interrupt<
|
|
35
|
+
* ToolApprovalRequest[]
|
|
36
|
+
* >;
|
|
37
|
+
* const resume: HumanInTheLoopMiddlewareHumanResponse[] =
|
|
38
|
+
* interruptRequest.value.map((request) => {
|
|
39
|
+
* if (request.action === "calculator") {
|
|
40
|
+
* return { id: request.toolCallId, type: "accept" };
|
|
41
|
+
* } else if (request.action === "write_file") {
|
|
42
|
+
* return {
|
|
43
|
+
* id: request.toolCallId,
|
|
44
|
+
* type: "edit",
|
|
45
|
+
* args: { filename: "safe.txt", content: "Safe content" },
|
|
46
|
+
* };
|
|
47
|
+
* }
|
|
48
|
+
*
|
|
49
|
+
* throw new Error(`Unknown action: ${request.action}`);
|
|
50
|
+
* });
|
|
51
|
+
*
|
|
52
|
+
* // Resume with approval
|
|
53
|
+
* await agent.invoke(new Command({ resume }), config);
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
22
56
|
* ## Features
|
|
23
57
|
*
|
|
24
58
|
* - **Selective Tool Approval**: Configure which tools require human approval
|
|
@@ -35,10 +69,12 @@ const contextSchema = z.object({
|
|
|
35
69
|
* - `response`: Provide a manual response instead of executing the tool
|
|
36
70
|
*
|
|
37
71
|
* @param options - Configuration options for the middleware
|
|
38
|
-
* @param options.
|
|
39
|
-
* @param options.
|
|
40
|
-
* @param options.
|
|
41
|
-
* @param options.
|
|
72
|
+
* @param options.interruptOn - Per-tool configuration mapping tool names to their settings
|
|
73
|
+
* @param options.interruptOn[toolName].allowAccept - Whether the human can approve the current action without changes
|
|
74
|
+
* @param options.interruptOn[toolName].allowEdit - Whether the human can reject the current action with feedback
|
|
75
|
+
* @param options.interruptOn[toolName].allowRespond - Whether the human can approve the current action with edited content
|
|
76
|
+
* @param options.interruptOn[toolName].description - Custom approval message for the tool
|
|
77
|
+
* @param options.messagePrefix - Default prefix for approval messages (default: "Tool execution requires approval"). Only used for tools that do not define a custom `description` in their ToolConfig.
|
|
42
78
|
*
|
|
43
79
|
* @returns A middleware instance that can be passed to `createAgent`
|
|
44
80
|
*
|
|
@@ -49,14 +85,15 @@ const contextSchema = z.object({
|
|
|
49
85
|
* import { createAgent } from "langchain";
|
|
50
86
|
*
|
|
51
87
|
* const hitlMiddleware = humanInTheLoopMiddleware({
|
|
52
|
-
*
|
|
88
|
+
* interruptOn: {
|
|
89
|
+
* // Interrupt write_file tool and allow edits or accepts
|
|
53
90
|
* "write_file": {
|
|
54
|
-
*
|
|
91
|
+
* allowEdit: true,
|
|
92
|
+
* allowAccept: true,
|
|
55
93
|
* description: "⚠️ File write operation requires approval"
|
|
56
94
|
* },
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
* }
|
|
95
|
+
* // Auto-approve read_file tool
|
|
96
|
+
* "read_file": false
|
|
60
97
|
* }
|
|
61
98
|
* });
|
|
62
99
|
*
|
|
@@ -70,6 +107,7 @@ const contextSchema = z.object({
|
|
|
70
107
|
* @example
|
|
71
108
|
* Handling approval requests
|
|
72
109
|
* ```typescript
|
|
110
|
+
* import { type HumanInTheLoopRequest, type Interrupt } from "langchain/middleware";
|
|
73
111
|
* import { Command } from "@langchain/langgraph";
|
|
74
112
|
*
|
|
75
113
|
* // Initial agent invocation
|
|
@@ -78,15 +116,14 @@ const contextSchema = z.object({
|
|
|
78
116
|
* }, config);
|
|
79
117
|
*
|
|
80
118
|
* // Check if agent is paused for approval
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
* const requests = task?.interrupts?.[0]?.value;
|
|
119
|
+
* if (result.__interrupt__) {
|
|
120
|
+
* const interruptRequest = initialResult.__interrupt__?.[0] as Interrupt<
|
|
121
|
+
* HumanInTheLoopRequest[]
|
|
122
|
+
* >;
|
|
86
123
|
*
|
|
87
124
|
* // Show tool call details to user
|
|
88
|
-
* console.log("Tool:",
|
|
89
|
-
* console.log("
|
|
125
|
+
* console.log("Tool:", interruptRequest.value[0].actionRequest);
|
|
126
|
+
* console.log("Allowed actions:", interruptRequest.value[0].config);
|
|
90
127
|
*
|
|
91
128
|
* // Resume with approval
|
|
92
129
|
* await agent.invoke(
|
|
@@ -111,12 +148,13 @@ const contextSchema = z.object({
|
|
|
111
148
|
* })
|
|
112
149
|
*
|
|
113
150
|
* // Skip tool and terminate agent
|
|
114
|
-
* new Command({ resume: [{ type: "
|
|
151
|
+
* new Command({ resume: [{ type: "response" }] })
|
|
115
152
|
*
|
|
116
153
|
* // Provide manual response
|
|
117
154
|
* new Command({
|
|
118
155
|
* resume: [{
|
|
119
156
|
* type: "response",
|
|
157
|
+
* // this must be a string
|
|
120
158
|
* args: "File operation not allowed in demo mode"
|
|
121
159
|
* }]
|
|
122
160
|
* })
|
|
@@ -126,16 +164,16 @@ const contextSchema = z.object({
|
|
|
126
164
|
* Production use case with database operations
|
|
127
165
|
* ```typescript
|
|
128
166
|
* const hitlMiddleware = humanInTheLoopMiddleware({
|
|
129
|
-
*
|
|
167
|
+
* interruptOn: {
|
|
130
168
|
* "execute_sql": {
|
|
131
|
-
*
|
|
169
|
+
* allowAccept: true,
|
|
170
|
+
* allowEdit: true,
|
|
171
|
+
* allowRespond: true,
|
|
132
172
|
* description: "🚨 SQL query requires DBA approval\nPlease review for safety and performance"
|
|
133
173
|
* },
|
|
134
|
-
* "read_schema":
|
|
135
|
-
* requireApproval: false // Reading metadata is safe
|
|
136
|
-
* },
|
|
174
|
+
* "read_schema": false // Reading metadata is safe
|
|
137
175
|
* "delete_records": {
|
|
138
|
-
*
|
|
176
|
+
* allowAccept: true,
|
|
139
177
|
* description: "⛔ DESTRUCTIVE OPERATION - Requires manager approval"
|
|
140
178
|
* }
|
|
141
179
|
* },
|
|
@@ -154,77 +192,115 @@ const contextSchema = z.object({
|
|
|
154
192
|
* @see {@link Command} for resuming interrupted execution
|
|
155
193
|
* @public
|
|
156
194
|
*/
|
|
157
|
-
function humanInTheLoopMiddleware(options
|
|
195
|
+
function humanInTheLoopMiddleware(options) {
|
|
158
196
|
return createMiddleware({
|
|
159
197
|
name: "HumanInTheLoopMiddleware",
|
|
160
198
|
contextSchema,
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
...
|
|
165
|
-
|
|
199
|
+
afterModelJumpTo: ["model"],
|
|
200
|
+
afterModel: async (state, runtime) => {
|
|
201
|
+
const config = interopParse(contextSchema, {
|
|
202
|
+
...options,
|
|
203
|
+
...runtime.context || {}
|
|
204
|
+
});
|
|
205
|
+
if (!config) return;
|
|
166
206
|
const { messages } = state;
|
|
167
207
|
if (!messages.length) return;
|
|
168
|
-
|
|
169
|
-
if
|
|
208
|
+
/**
|
|
209
|
+
* Don't do anything if the last message isn't an AI message with tool calls.
|
|
210
|
+
*/
|
|
211
|
+
const lastMessage = [...messages].reverse().find((msg) => AIMessage.isInstance(msg));
|
|
212
|
+
if (!lastMessage || !lastMessage.tool_calls?.length) return;
|
|
213
|
+
/**
|
|
214
|
+
* If the user omits the interruptOn config, we don't do anything.
|
|
215
|
+
*/
|
|
216
|
+
if (!config.interruptOn) return;
|
|
217
|
+
const resolvedToolConfigs = {};
|
|
218
|
+
for (const [toolName, toolConfig] of Object.entries(config.interruptOn)) if (typeof toolConfig === "boolean") {
|
|
219
|
+
if (toolConfig === true) resolvedToolConfigs[toolName] = {
|
|
220
|
+
allowAccept: true,
|
|
221
|
+
allowEdit: true,
|
|
222
|
+
allowRespond: true
|
|
223
|
+
};
|
|
224
|
+
} else resolvedToolConfigs[toolName] = toolConfig;
|
|
170
225
|
const interruptToolCalls = [];
|
|
171
226
|
const autoApprovedToolCalls = [];
|
|
172
|
-
for (const toolCall of lastMessage.tool_calls)
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
};
|
|
178
|
-
const toolConfig = config.toolConfigs[normalizedToolCall.name];
|
|
179
|
-
if (toolConfig?.requireApproval) interruptToolCalls.push(normalizedToolCall);
|
|
180
|
-
else autoApprovedToolCalls.push(normalizedToolCall);
|
|
181
|
-
}
|
|
227
|
+
for (const toolCall of lastMessage.tool_calls) if (toolCall.name in resolvedToolConfigs) interruptToolCalls.push(toolCall);
|
|
228
|
+
else autoApprovedToolCalls.push(toolCall);
|
|
229
|
+
/**
|
|
230
|
+
* No interrupt tool calls, so we can just return.
|
|
231
|
+
*/
|
|
182
232
|
if (!interruptToolCalls.length) return;
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
const
|
|
186
|
-
const description = toolConfig?.description || `${config.messagePrefix}\n\nTool: ${toolCall.name}\nArgs: ${JSON.stringify(toolCall.args, null, 2)}`;
|
|
233
|
+
const hitlRequests = interruptToolCalls.map((toolCall) => {
|
|
234
|
+
const toolConfig = resolvedToolConfigs[toolCall.name];
|
|
235
|
+
const description = toolConfig.description || `${config.descriptionPrefix}\n\nTool: ${toolCall.name}\nArgs: ${JSON.stringify(toolCall.args, null, 2)}`;
|
|
187
236
|
return {
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
237
|
+
actionRequest: {
|
|
238
|
+
action: toolCall.name,
|
|
239
|
+
args: toolCall.args
|
|
240
|
+
},
|
|
241
|
+
config: toolConfig,
|
|
191
242
|
description
|
|
192
243
|
};
|
|
193
244
|
});
|
|
194
|
-
const responses = await interrupt(
|
|
195
|
-
|
|
196
|
-
|
|
245
|
+
const responses = await interrupt(hitlRequests);
|
|
246
|
+
if (responses.length !== interruptToolCalls.length) throw new Error(`Number of human responses (${responses.length}) does not match number of hanging tool calls (${interruptToolCalls.length}).`);
|
|
247
|
+
const approvedToolCalls = [...autoApprovedToolCalls];
|
|
248
|
+
const artificialToolMessages = [];
|
|
249
|
+
for (const [i, response] of responses.entries()) {
|
|
197
250
|
const toolCall = interruptToolCalls[i];
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
content: typeof response.args === "string" ? response.args : "",
|
|
212
|
-
tool_call_id: toolCall.id
|
|
213
|
-
});
|
|
214
|
-
return {
|
|
215
|
-
messages: [...state.messages, toolMessage],
|
|
216
|
-
jump_to: "model"
|
|
217
|
-
};
|
|
218
|
-
}
|
|
219
|
-
default: throw new Error(`Unknown response type: ${response.type}`);
|
|
251
|
+
const toolConfig = resolvedToolConfigs[toolCall.name];
|
|
252
|
+
if (response.type === "accept" && toolConfig?.allowAccept) {
|
|
253
|
+
approvedToolCalls.push(toolCall);
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
if (response.type === "edit" && toolConfig?.allowEdit) {
|
|
257
|
+
const edited = response.args;
|
|
258
|
+
approvedToolCalls.push({
|
|
259
|
+
id: toolCall.id,
|
|
260
|
+
name: edited.action,
|
|
261
|
+
args: edited.args
|
|
262
|
+
});
|
|
263
|
+
continue;
|
|
220
264
|
}
|
|
265
|
+
if (response.type === "response" && toolConfig?.allowRespond) {
|
|
266
|
+
const content = response.args ?? `User rejected the tool call for \`${toolCall.name}\` with id ${toolCall.id}`;
|
|
267
|
+
/**
|
|
268
|
+
* Providing a meaningful error message for this case that should never happen.
|
|
269
|
+
*/
|
|
270
|
+
if (!toolCall.id) throw new Error(`Can't provide custom tool response for tool call without an ID: ${toolCall.name}!\nThis use case is not expected to happen, please report this as a bug.`);
|
|
271
|
+
/**
|
|
272
|
+
* ToolMessage expects a string, so we need to throw an error if it's not a string
|
|
273
|
+
* as we currently have no way to proper type responses from users through the
|
|
274
|
+
* Command object.
|
|
275
|
+
*/
|
|
276
|
+
if (typeof content !== "string") throw new Error(`Tool call response for "${toolCall.name}" must be a string, got ${typeof content}`);
|
|
277
|
+
artificialToolMessages.push(new ToolMessage({
|
|
278
|
+
content,
|
|
279
|
+
name: toolCall.name,
|
|
280
|
+
tool_call_id: toolCall.id,
|
|
281
|
+
status: "error"
|
|
282
|
+
}));
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
const allowedActions = [
|
|
286
|
+
toolConfig?.allowAccept && "accept",
|
|
287
|
+
toolConfig?.allowEdit && "edit",
|
|
288
|
+
toolConfig?.allowRespond && "response"
|
|
289
|
+
].filter(Boolean).join("\", \"");
|
|
290
|
+
throw new Error(`Unexpected human response: ${JSON.stringify(response)}. Response action '${response.type}' is not allowed for tool '${toolCall.name}'. Expected one of: "${allowedActions}", based on the tool's configuration.`);
|
|
221
291
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
292
|
+
/**
|
|
293
|
+
* Replace the tool calls with the approved tool calls
|
|
294
|
+
*/
|
|
295
|
+
if (AIMessage.isInstance(lastMessage)) lastMessage.tool_calls = lastMessage.tool_calls?.map((tc) => {
|
|
296
|
+
const approvedToolCall = approvedToolCalls.find((atc) => atc.id === tc.id);
|
|
297
|
+
return approvedToolCall ?? tc;
|
|
226
298
|
});
|
|
227
|
-
return { messages: [...state.messages
|
|
299
|
+
if (approvedToolCalls.length > 0) return { messages: [...state.messages, ...artificialToolMessages] };
|
|
300
|
+
return {
|
|
301
|
+
jumpTo: "model",
|
|
302
|
+
messages: [...state.messages, ...artificialToolMessages]
|
|
303
|
+
};
|
|
228
304
|
}
|
|
229
305
|
});
|
|
230
306
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hitl.js","names":["options: z.input<typeof contextSchema>","interruptToolCalls: ToolCall[]","autoApprovedToolCalls: ToolCall[]","normalizedToolCall: ToolCall","uuid","requests: ToolApprovalRequest[]"],"sources":["../../../../src/agents/middlewareAgent/middleware/hitl.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v3\";\nimport { v4 as uuid } from \"uuid\";\nimport { AIMessage, ToolMessage, isAIMessage } from \"@langchain/core/messages\";\nimport { interrupt } from \"@langchain/langgraph\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { ToolCall } from \"../types.js\";\nimport { HumanResponse } from \"../../interrupt.js\";\n\n/**\n * Interrupt request for tool approval\n */\ninterface ToolApprovalRequest {\n action: string;\n args: Record<string, any>;\n toolCallId: string;\n description?: string;\n}\n\nconst contextSchema = z.object({\n toolConfigs: z\n .record(\n z.object({\n requireApproval: z.boolean().optional(),\n description: z.string().optional(),\n })\n )\n .default({}),\n messagePrefix: z.string().default(\"Tool execution requires approval\"),\n});\n\n/**\n * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.\n *\n * This middleware intercepts tool calls made by an AI agent and provides human oversight\n * capabilities before execution. It enables selective approval workflows where certain tools\n * require human intervention while others can execute automatically.\n *\n * ## Features\n *\n * - **Selective Tool Approval**: Configure which tools require human approval\n * - **Multiple Response Types**: Accept, edit, ignore, or manually respond to tool calls\n * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval\n * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests\n *\n * ## Response Types\n *\n * When a tool requires approval, the human operator can respond with:\n * - `accept`: Execute the tool with original arguments\n * - `edit`: Modify the tool arguments before execution\n * - `ignore`: Skip the tool and terminate the agent\n * - `response`: Provide a manual response instead of executing the tool\n *\n * @param options - Configuration options for the middleware\n * @param options.toolConfigs - Per-tool configuration mapping tool names to their settings\n * @param options.toolConfigs[toolName].requireApproval - Whether the tool requires human approval\n * @param options.toolConfigs[toolName].description - Custom approval message for the tool\n * @param options.messagePrefix - Default prefix for approval messages (default: \"Tool execution requires approval\")\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @example\n * Basic usage with selective tool approval\n * ```typescript\n * import { humanInTheLoopMiddleware } from \"langchain/middleware\";\n * import { createAgent } from \"langchain\";\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * toolConfigs: {\n * \"write_file\": {\n * requireApproval: true,\n * description: \"⚠️ File write operation requires approval\"\n * },\n * \"read_file\": {\n * requireApproval: false // Safe operation, no approval needed\n * }\n * }\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * tools: [writeFileTool, readFileTool],\n * middleware: [hitlMiddleware]\n * });\n * ```\n *\n * @example\n * Handling approval requests\n * ```typescript\n * import { Command } from \"@langchain/langgraph\";\n *\n * // Initial agent invocation\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Write 'Hello' to output.txt\")]\n * }, config);\n *\n * // Check if agent is paused for approval\n * const state = await agent.graph.getState(config);\n * if (state.next?.length > 0) {\n * // Get interrupt details\n * const task = state.tasks?.[0];\n * const requests = task?.interrupts?.[0]?.value;\n *\n * // Show tool call details to user\n * console.log(\"Tool:\", requests[0].action);\n * console.log(\"Args:\", requests[0].args);\n *\n * // Resume with approval\n * await agent.invoke(\n * new Command({ resume: [{ type: \"accept\" }] }),\n * config\n * );\n * }\n * ```\n *\n * @example\n * Different response types\n * ```typescript\n * // Accept the tool call as-is\n * new Command({ resume: [{ type: \"accept\" }] })\n *\n * // Edit the tool arguments\n * new Command({\n * resume: [{\n * type: \"edit\",\n * args: { action: \"write_file\", args: { filename: \"safe.txt\", content: \"Modified\" } }\n * }]\n * })\n *\n * // Skip tool and terminate agent\n * new Command({ resume: [{ type: \"ignore\" }] })\n *\n * // Provide manual response\n * new Command({\n * resume: [{\n * type: \"response\",\n * args: \"File operation not allowed in demo mode\"\n * }]\n * })\n * ```\n *\n * @example\n * Production use case with database operations\n * ```typescript\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * toolConfigs: {\n * \"execute_sql\": {\n * requireApproval: true,\n * description: \"🚨 SQL query requires DBA approval\\nPlease review for safety and performance\"\n * },\n * \"read_schema\": {\n * requireApproval: false // Reading metadata is safe\n * },\n * \"delete_records\": {\n * requireApproval: true,\n * description: \"⛔ DESTRUCTIVE OPERATION - Requires manager approval\"\n * }\n * },\n * messagePrefix: \"Database operation pending approval\"\n * });\n * ```\n *\n * @remarks\n * - Tool calls are processed in the order they appear in the AI message\n * - Auto-approved tools execute immediately without interruption\n * - Multiple tools requiring approval are bundled into a single interrupt\n * - The middleware operates in the `afterModel` phase, intercepting before tool execution\n * - Requires a checkpointer to maintain state across interruptions\n *\n * @see {@link createAgent} for agent creation\n * @see {@link Command} for resuming interrupted execution\n * @public\n */\nexport function humanInTheLoopMiddleware(\n options: z.input<typeof contextSchema> = {}\n) {\n return createMiddleware({\n name: \"HumanInTheLoopMiddleware\",\n contextSchema,\n afterModel: async (state, runtime, controls) => {\n const config = { ...contextSchema.parse(options), ...runtime.context };\n const { messages } = state;\n\n if (!messages.length) {\n return;\n }\n\n const lastMessage = messages[messages.length - 1];\n\n // Check if it's an AI message with tool calls\n if (!isAIMessage(lastMessage) || !lastMessage.tool_calls?.length) {\n return;\n }\n\n // Separate tool calls that need interrupts from those that don't\n const interruptToolCalls: ToolCall[] = [];\n const autoApprovedToolCalls: ToolCall[] = [];\n\n for (const toolCall of lastMessage.tool_calls) {\n // Ensure tool call has an ID\n const normalizedToolCall: ToolCall = {\n id: toolCall.id || uuid(),\n name: toolCall.name,\n args: toolCall.args,\n };\n\n const toolConfig = config.toolConfigs[normalizedToolCall.name];\n\n if (toolConfig?.requireApproval) {\n interruptToolCalls.push(normalizedToolCall);\n } else {\n autoApprovedToolCalls.push(normalizedToolCall);\n }\n }\n\n // If no interrupts needed, return early\n if (!interruptToolCalls.length) {\n return;\n }\n\n const approvedToolCalls = [...autoApprovedToolCalls];\n\n // Process tool calls that need interrupts\n const requests: ToolApprovalRequest[] = interruptToolCalls.map(\n (toolCall) => {\n const toolConfig = config.toolConfigs[toolCall.name];\n const description =\n toolConfig?.description ||\n `${config.messagePrefix}\\n\\nTool: ${\n toolCall.name\n }\\nArgs: ${JSON.stringify(toolCall.args, null, 2)}`;\n\n return {\n action: toolCall.name,\n args: toolCall.args,\n toolCallId: toolCall.id,\n description,\n };\n }\n );\n\n // Interrupt and wait for human responses\n const responses = (await interrupt(requests)) as HumanResponse[];\n\n // Process responses\n for (let i = 0; i < responses.length; i++) {\n const response = responses[i];\n const toolCall = interruptToolCalls[i];\n\n switch (response.type) {\n case \"accept\":\n approvedToolCalls.push(toolCall);\n break;\n\n case \"edit\":\n // For edit, args is an ActionRequest with updated args\n if (\n response.args &&\n typeof response.args === \"object\" &&\n \"args\" in response.args\n ) {\n approvedToolCalls.push({\n ...toolCall,\n args: (\n response.args as { action: string; args: Record<string, any> }\n ).args,\n });\n }\n break;\n\n case \"ignore\":\n // Skip to end - terminate the agent\n return controls.terminate();\n\n case \"response\": {\n // Return manual tool response and jump back to model\n // For response, args is a string\n const toolMessage = new ToolMessage({\n content: typeof response.args === \"string\" ? response.args : \"\",\n tool_call_id: toolCall.id,\n });\n return {\n messages: [...state.messages, toolMessage],\n jump_to: \"model\",\n };\n }\n default:\n throw new Error(`Unknown response type: ${(response as any).type}`);\n }\n }\n\n // Update the last message with approved tool calls\n const updatedMessage = new AIMessage({\n content: lastMessage.content,\n tool_calls: approvedToolCalls,\n id: lastMessage.id,\n });\n\n // Replace the last message with the updated one\n return {\n messages: [...state.messages.slice(0, -1), updatedMessage],\n };\n },\n });\n}\n"],"mappings":";;;;;;;AAoBA,MAAM,gBAAgB,EAAE,OAAO;CAC7B,aAAa,EACV,OACC,EAAE,OAAO;EACP,iBAAiB,EAAE,SAAS,CAAC,UAAU;EACvC,aAAa,EAAE,QAAQ,CAAC,UAAU;CACnC,EAAC,CACH,CACA,QAAQ,CAAE,EAAC;CACd,eAAe,EAAE,QAAQ,CAAC,QAAQ,mCAAmC;AACtE,EAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgJF,SAAgB,yBACdA,UAAyC,CAAE,GAC3C;AACA,QAAO,iBAAiB;EACtB,MAAM;EACN;EACA,YAAY,OAAO,OAAO,SAAS,aAAa;GAC9C,MAAM,SAAS;IAAE,GAAG,cAAc,MAAM,QAAQ;IAAE,GAAG,QAAQ;GAAS;GACtE,MAAM,EAAE,UAAU,GAAG;AAErB,OAAI,CAAC,SAAS,OACZ;GAGF,MAAM,cAAc,SAAS,SAAS,SAAS;AAG/C,OAAI,CAAC,YAAY,YAAY,IAAI,CAAC,YAAY,YAAY,OACxD;GAIF,MAAMC,qBAAiC,CAAE;GACzC,MAAMC,wBAAoC,CAAE;AAE5C,QAAK,MAAM,YAAY,YAAY,YAAY;IAE7C,MAAMC,qBAA+B;KACnC,IAAI,SAAS,MAAMC,IAAM;KACzB,MAAM,SAAS;KACf,MAAM,SAAS;IAChB;IAED,MAAM,aAAa,OAAO,YAAY,mBAAmB;AAEzD,QAAI,YAAY,iBACd,mBAAmB,KAAK,mBAAmB;SAE3C,sBAAsB,KAAK,mBAAmB;GAEjD;AAGD,OAAI,CAAC,mBAAmB,OACtB;GAGF,MAAM,oBAAoB,CAAC,GAAG,qBAAsB;GAGpD,MAAMC,WAAkC,mBAAmB,IACzD,CAAC,aAAa;IACZ,MAAM,aAAa,OAAO,YAAY,SAAS;IAC/C,MAAM,cACJ,YAAY,eACZ,GAAG,OAAO,cAAc,UAAU,EAChC,SAAS,KACV,QAAQ,EAAE,KAAK,UAAU,SAAS,MAAM,MAAM,EAAE,EAAE;AAErD,WAAO;KACL,QAAQ,SAAS;KACjB,MAAM,SAAS;KACf,YAAY,SAAS;KACrB;IACD;GACF,EACF;GAGD,MAAM,YAAa,MAAM,UAAU,SAAS;AAG5C,QAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;IACzC,MAAM,WAAW,UAAU;IAC3B,MAAM,WAAW,mBAAmB;AAEpC,YAAQ,SAAS,MAAjB;KACE,KAAK;MACH,kBAAkB,KAAK,SAAS;AAChC;KAEF,KAAK;AAEH,UACE,SAAS,QACT,OAAO,SAAS,SAAS,YACzB,UAAU,SAAS,MAEnB,kBAAkB,KAAK;OACrB,GAAG;OACH,MACE,SAAS,KACT;MACH,EAAC;AAEJ;KAEF,KAAK,SAEH,QAAO,SAAS,WAAW;KAE7B,KAAK,YAAY;MAGf,MAAM,cAAc,IAAI,YAAY;OAClC,SAAS,OAAO,SAAS,SAAS,WAAW,SAAS,OAAO;OAC7D,cAAc,SAAS;MACxB;AACD,aAAO;OACL,UAAU,CAAC,GAAG,MAAM,UAAU,WAAY;OAC1C,SAAS;MACV;KACF;KACD,QACE,OAAM,IAAI,MAAM,CAAC,uBAAuB,EAAG,SAAiB,MAAM;IACrE;GACF;GAGD,MAAM,iBAAiB,IAAI,UAAU;IACnC,SAAS,YAAY;IACrB,YAAY;IACZ,IAAI,YAAY;GACjB;AAGD,UAAO,EACL,UAAU,CAAC,GAAG,MAAM,SAAS,MAAM,GAAG,GAAG,EAAE,cAAe,EAC3D;EACF;CACF,EAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"hitl.js","names":["options: NonNullable<HumanInTheLoopMiddlewareConfig>","resolvedToolConfigs: Record<string, ToolConfig>","interruptToolCalls: ToolCall[]","autoApprovedToolCalls: ToolCall[]","hitlRequests: HumanInTheLoopRequest[]","approvedToolCalls: ToolCall[]","artificialToolMessages: ToolMessage[]"],"sources":["../../../../src/agents/middlewareAgent/middleware/hitl.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { z } from \"zod/v3\";\nimport { AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport {\n InferInteropZodInput,\n interopParse,\n} from \"@langchain/core/utils/types\";\nimport { interrupt } from \"@langchain/langgraph\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\nconst ToolConfigSchema = z.object({\n /**\n * Whether the human can approve the current action without changes\n */\n allowAccept: z.boolean().optional(),\n /**\n * Whether the human can reject the current action with feedback\n */\n allowEdit: z.boolean().optional(),\n /**\n * Whether the human can approve the current action with edited content\n */\n allowRespond: z.boolean().optional(),\n /**\n * The description attached to the request for human input\n */\n description: z.string().optional(),\n});\n\ntype ToolConfigSchema = z.input<typeof ToolConfigSchema>;\ntype ToolCall = NonNullable<AIMessage[\"tool_calls\"]>[number];\n\n/**\n * Represents information about an interrupt.\n */\nexport interface Interrupt<TValue = unknown> {\n /**\n * The ID of the interrupt.\n */\n id: string;\n /**\n * The requests for human input.\n */\n value: TValue;\n}\n\n/**\n * Configuration that defines which reviewer response types are permitted during a human interrupt.\n * These flags control what the human reviewer may do (e.g., accept/edit/respond),\n * not the tool action the agent has requested.\n */\nexport interface HumanInTheLoopConfig\n extends Omit<ToolConfigSchema, \"description\"> {}\n\n/**\n * Describes the agent-requested tool action (name and arguments).\n * This is what the AI intends to execute, subject to human review.\n */\nexport interface ActionRequest {\n /**\n * The tool/action name requested by the agent (e.g., \"send_email\").\n */\n action: string;\n /**\n * Arguments for the requested tool call (e.g., {\"a\": 1, \"b\": 2}).\n */\n args: Record<string, any>;\n}\n\n/**\n * Represents an interrupt triggered by the graph that requires human intervention\n * to approve, edit, or respond to an agent-requested tool action.\n *\n * @example\n * ```ts\n * const hitlRequest: HumanInTheLoopRequest = {\n * actionRequest: { action: \"Approve XYZ action\", args: { ... } },\n * config: { allowAccept: true, allowEdit: true, allowRespond: true },\n * description: \"Please review the command before execution\"\n * };\n * response = interrupt([request])[0]\n * ```\n */\nexport interface HumanInTheLoopRequest {\n /**\n * The agent-requested tool action to be reviewed.\n */\n actionRequest: ActionRequest;\n /**\n * Which reviewer responses are allowed (accept/edit/respond).\n */\n config: HumanInTheLoopConfig;\n /**\n * Optional human-facing description shown in the approval prompt.\n */\n description?: string;\n}\n\n/**\n * Response when a human approves the agent-requested action.\n */\nexport interface AcceptPayload {\n type: \"accept\";\n}\n\n/**\n * Response when a human provides a manual response instead of executing\n * the agent-requested action.\n */\nexport interface ResponsePayload {\n type: \"response\";\n args?: string;\n}\n\n/**\n * Response when a human edits the agent-requested action (tool name and/or args).\n */\nexport interface EditPayload {\n type: \"edit\";\n args: ActionRequest;\n}\n\nexport type HumanInTheLoopMiddlewareHumanResponse =\n | AcceptPayload\n | ResponsePayload\n | EditPayload;\n\n/**\n * Configuration for a tool requiring human in the loop.\n */\nexport interface ToolConfig extends HumanInTheLoopConfig {\n /**\n * Human-facing description shown in the approval request.\n */\n description?: string;\n}\n\nconst contextSchema = z.object({\n /**\n * Mapping of tool name to allowed reviewer responses.\n * If a tool doesn't have an entry, it's auto-approved by default.\n *\n * - `true` -> pause for approval and allow accept/edit/respond\n * - `false` -> auto-approve (no human review)\n * - `ToolConfig` -> explicitly specify which reviewer responses are allowed for this tool\n */\n interruptOn: z.record(z.union([z.boolean(), ToolConfigSchema])).optional(),\n /**\n * Prefix used when constructing human-facing approval messages.\n * Provides context about the tool call being reviewed; does not change the underlying action.\n *\n * Note: This prefix is only applied for tools that do not provide a custom\n * `description` via their {@link ToolConfig}. If a tool specifies a custom\n * `description`, that per-tool text is used and this prefix is ignored.\n */\n descriptionPrefix: z.string().default(\"Tool execution requires approval\"),\n});\nexport type HumanInTheLoopMiddlewareConfig = InferInteropZodInput<\n typeof contextSchema\n>;\n\n/**\n * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.\n *\n * This middleware intercepts tool calls made by an AI agent and provides human oversight\n * capabilities before execution. It enables selective approval workflows where certain tools\n * require human intervention while others can execute automatically.\n *\n * A invocation result that has been interrupted by the middleware will have a `__interrupt__`\n * property that contains the interrupt request. You can loop over the request to determine\n * which tools were interrupted, and how to handle them separately.\n *\n * ```ts\n * import { type ToolApprovalRequest, type HumanInTheLoopMiddlewareHumanResponse } from \"langchain/middleware\";\n * import { type Interrupt } from \"langchain\";\n *\n * const result = await agent.invoke(request);\n * const interruptRequest = initialResult.__interrupt__?.[0] as Interrupt<\n * ToolApprovalRequest[]\n * >;\n * const resume: HumanInTheLoopMiddlewareHumanResponse[] =\n * interruptRequest.value.map((request) => {\n * if (request.action === \"calculator\") {\n * return { id: request.toolCallId, type: \"accept\" };\n * } else if (request.action === \"write_file\") {\n * return {\n * id: request.toolCallId,\n * type: \"edit\",\n * args: { filename: \"safe.txt\", content: \"Safe content\" },\n * };\n * }\n *\n * throw new Error(`Unknown action: ${request.action}`);\n * });\n *\n * // Resume with approval\n * await agent.invoke(new Command({ resume }), config);\n * ```\n *\n * ## Features\n *\n * - **Selective Tool Approval**: Configure which tools require human approval\n * - **Multiple Response Types**: Accept, edit, ignore, or manually respond to tool calls\n * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval\n * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests\n *\n * ## Response Types\n *\n * When a tool requires approval, the human operator can respond with:\n * - `accept`: Execute the tool with original arguments\n * - `edit`: Modify the tool arguments before execution\n * - `ignore`: Skip the tool and terminate the agent\n * - `response`: Provide a manual response instead of executing the tool\n *\n * @param options - Configuration options for the middleware\n * @param options.interruptOn - Per-tool configuration mapping tool names to their settings\n * @param options.interruptOn[toolName].allowAccept - Whether the human can approve the current action without changes\n * @param options.interruptOn[toolName].allowEdit - Whether the human can reject the current action with feedback\n * @param options.interruptOn[toolName].allowRespond - Whether the human can approve the current action with edited content\n * @param options.interruptOn[toolName].description - Custom approval message for the tool\n * @param options.messagePrefix - Default prefix for approval messages (default: \"Tool execution requires approval\"). Only used for tools that do not define a custom `description` in their ToolConfig.\n *\n * @returns A middleware instance that can be passed to `createAgent`\n *\n * @example\n * Basic usage with selective tool approval\n * ```typescript\n * import { humanInTheLoopMiddleware } from \"langchain/middleware\";\n * import { createAgent } from \"langchain\";\n *\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * // Interrupt write_file tool and allow edits or accepts\n * \"write_file\": {\n * allowEdit: true,\n * allowAccept: true,\n * description: \"⚠️ File write operation requires approval\"\n * },\n * // Auto-approve read_file tool\n * \"read_file\": false\n * }\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * tools: [writeFileTool, readFileTool],\n * middleware: [hitlMiddleware]\n * });\n * ```\n *\n * @example\n * Handling approval requests\n * ```typescript\n * import { type HumanInTheLoopRequest, type Interrupt } from \"langchain/middleware\";\n * import { Command } from \"@langchain/langgraph\";\n *\n * // Initial agent invocation\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Write 'Hello' to output.txt\")]\n * }, config);\n *\n * // Check if agent is paused for approval\n * if (result.__interrupt__) {\n * const interruptRequest = initialResult.__interrupt__?.[0] as Interrupt<\n * HumanInTheLoopRequest[]\n * >;\n *\n * // Show tool call details to user\n * console.log(\"Tool:\", interruptRequest.value[0].actionRequest);\n * console.log(\"Allowed actions:\", interruptRequest.value[0].config);\n *\n * // Resume with approval\n * await agent.invoke(\n * new Command({ resume: [{ type: \"accept\" }] }),\n * config\n * );\n * }\n * ```\n *\n * @example\n * Different response types\n * ```typescript\n * // Accept the tool call as-is\n * new Command({ resume: [{ type: \"accept\" }] })\n *\n * // Edit the tool arguments\n * new Command({\n * resume: [{\n * type: \"edit\",\n * args: { action: \"write_file\", args: { filename: \"safe.txt\", content: \"Modified\" } }\n * }]\n * })\n *\n * // Skip tool and terminate agent\n * new Command({ resume: [{ type: \"response\" }] })\n *\n * // Provide manual response\n * new Command({\n * resume: [{\n * type: \"response\",\n * // this must be a string\n * args: \"File operation not allowed in demo mode\"\n * }]\n * })\n * ```\n *\n * @example\n * Production use case with database operations\n * ```typescript\n * const hitlMiddleware = humanInTheLoopMiddleware({\n * interruptOn: {\n * \"execute_sql\": {\n * allowAccept: true,\n * allowEdit: true,\n * allowRespond: true,\n * description: \"🚨 SQL query requires DBA approval\\nPlease review for safety and performance\"\n * },\n * \"read_schema\": false // Reading metadata is safe\n * \"delete_records\": {\n * allowAccept: true,\n * description: \"⛔ DESTRUCTIVE OPERATION - Requires manager approval\"\n * }\n * },\n * messagePrefix: \"Database operation pending approval\"\n * });\n * ```\n *\n * @remarks\n * - Tool calls are processed in the order they appear in the AI message\n * - Auto-approved tools execute immediately without interruption\n * - Multiple tools requiring approval are bundled into a single interrupt\n * - The middleware operates in the `afterModel` phase, intercepting before tool execution\n * - Requires a checkpointer to maintain state across interruptions\n *\n * @see {@link createAgent} for agent creation\n * @see {@link Command} for resuming interrupted execution\n * @public\n */\nexport function humanInTheLoopMiddleware(\n options: NonNullable<HumanInTheLoopMiddlewareConfig>\n) {\n return createMiddleware({\n name: \"HumanInTheLoopMiddleware\",\n contextSchema,\n afterModelJumpTo: [\"model\"],\n afterModel: async (state, runtime) => {\n const config = interopParse(contextSchema, {\n ...options,\n ...(runtime.context || {}),\n });\n if (!config) {\n return;\n }\n\n const { messages } = state;\n if (!messages.length) {\n return;\n }\n\n /**\n * Don't do anything if the last message isn't an AI message with tool calls.\n */\n const lastMessage = [...messages]\n .reverse()\n .find((msg) => AIMessage.isInstance(msg)) as AIMessage;\n if (!lastMessage || !lastMessage.tool_calls?.length) {\n return;\n }\n\n /**\n * If the user omits the interruptOn config, we don't do anything.\n */\n if (!config.interruptOn) {\n return;\n }\n\n // Resolve per-tool configs (boolean true -> all actions allowed; false -> auto-approve)\n const resolvedToolConfigs: Record<string, ToolConfig> = {};\n for (const [toolName, toolConfig] of Object.entries(config.interruptOn)) {\n if (typeof toolConfig === \"boolean\") {\n if (toolConfig === true) {\n resolvedToolConfigs[toolName] = {\n allowAccept: true,\n allowEdit: true,\n allowRespond: true,\n };\n }\n } else {\n resolvedToolConfigs[toolName] = toolConfig;\n }\n }\n\n const interruptToolCalls: ToolCall[] = [];\n const autoApprovedToolCalls: ToolCall[] = [];\n\n for (const toolCall of lastMessage.tool_calls) {\n if (toolCall.name in resolvedToolConfigs) {\n interruptToolCalls.push(toolCall);\n } else {\n autoApprovedToolCalls.push(toolCall);\n }\n }\n\n /**\n * No interrupt tool calls, so we can just return.\n */\n if (!interruptToolCalls.length) {\n return;\n }\n\n const hitlRequests: HumanInTheLoopRequest[] = interruptToolCalls.map(\n (toolCall) => {\n const toolConfig = resolvedToolConfigs[toolCall.name]!;\n const description =\n toolConfig.description ||\n `${config.descriptionPrefix}\\n\\nTool: ${\n toolCall.name\n }\\nArgs: ${JSON.stringify(toolCall.args, null, 2)}`;\n return {\n actionRequest: { action: toolCall.name, args: toolCall.args },\n config: toolConfig,\n description,\n };\n }\n );\n\n const responses = (await interrupt(\n hitlRequests\n )) as HumanInTheLoopMiddlewareHumanResponse[];\n\n if (responses.length !== interruptToolCalls.length) {\n throw new Error(\n `Number of human responses (${responses.length}) does not match number of hanging tool calls (${interruptToolCalls.length}).`\n );\n }\n\n const approvedToolCalls: ToolCall[] = [...autoApprovedToolCalls];\n const artificialToolMessages: ToolMessage[] = [];\n\n for (const [i, response] of responses.entries()) {\n const toolCall = interruptToolCalls[i]!;\n const toolConfig = resolvedToolConfigs[toolCall.name]!;\n\n if (response.type === \"accept\" && toolConfig?.allowAccept) {\n approvedToolCalls.push(toolCall);\n continue;\n }\n\n if (response.type === \"edit\" && toolConfig?.allowEdit) {\n const edited = response.args;\n approvedToolCalls.push({\n id: toolCall.id,\n name: edited.action,\n args: edited.args,\n });\n continue;\n }\n\n if (response.type === \"response\" && toolConfig?.allowRespond) {\n const content =\n response.args ??\n `User rejected the tool call for \\`${toolCall.name}\\` with id ${toolCall.id}`;\n\n /**\n * Providing a meaningful error message for this case that should never happen.\n */\n if (!toolCall.id) {\n throw new Error(\n `Can't provide custom tool response for tool call without an ID: ${toolCall.name}!\\n` +\n \"This use case is not expected to happen, please report this as a bug.\"\n );\n }\n\n /**\n * ToolMessage expects a string, so we need to throw an error if it's not a string\n * as we currently have no way to proper type responses from users through the\n * Command object.\n */\n if (typeof content !== \"string\") {\n throw new Error(\n `Tool call response for \"${\n toolCall.name\n }\" must be a string, got ${typeof content}`\n );\n }\n\n artificialToolMessages.push(\n new ToolMessage({\n content,\n name: toolCall.name,\n tool_call_id: toolCall.id,\n status: \"error\",\n })\n );\n continue;\n }\n\n const allowedActions = [\n toolConfig?.allowAccept && \"accept\",\n toolConfig?.allowEdit && \"edit\",\n toolConfig?.allowRespond && \"response\",\n ]\n .filter(Boolean)\n .join('\", \"');\n throw new Error(\n `Unexpected human response: ${JSON.stringify(\n response\n )}. Response action '${response.type}' is not allowed for tool '${\n toolCall.name\n }'. Expected one of: \"${allowedActions}\", based on the tool's configuration.`\n );\n }\n\n /**\n * Replace the tool calls with the approved tool calls\n */\n if (AIMessage.isInstance(lastMessage)) {\n lastMessage.tool_calls = lastMessage.tool_calls?.map((tc) => {\n const approvedToolCall = approvedToolCalls.find(\n (atc) => atc.id === tc.id\n );\n return approvedToolCall ?? tc;\n });\n }\n\n if (approvedToolCalls.length > 0) {\n return { messages: [...state.messages, ...artificialToolMessages] };\n }\n\n return {\n jumpTo: \"model\",\n messages: [...state.messages, ...artificialToolMessages],\n };\n },\n });\n}\n"],"mappings":"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"}
|
|
@@ -2,20 +2,26 @@ const require_rolldown_runtime = require('../../../_virtual/rolldown_runtime.cjs
|
|
|
2
2
|
const require_summarization = require('./summarization.cjs');
|
|
3
3
|
const require_hitl = require('./hitl.cjs');
|
|
4
4
|
const require_promptCaching = require('./promptCaching.cjs');
|
|
5
|
+
const require_dynamicSystemPrompt = require('./dynamicSystemPrompt.cjs');
|
|
6
|
+
const require_bigTool = require('./bigTool.cjs');
|
|
5
7
|
|
|
6
8
|
//#region src/agents/middlewareAgent/middleware/index.ts
|
|
7
9
|
var middleware_exports = {};
|
|
8
10
|
require_rolldown_runtime.__export(middleware_exports, {
|
|
9
11
|
anthropicPromptCachingMiddleware: () => require_promptCaching.anthropicPromptCachingMiddleware,
|
|
10
12
|
countTokensApproximately: () => require_summarization.countTokensApproximately,
|
|
13
|
+
dynamicSystemPromptMiddleware: () => require_dynamicSystemPrompt.dynamicSystemPromptMiddleware,
|
|
11
14
|
humanInTheLoopMiddleware: () => require_hitl.humanInTheLoopMiddleware,
|
|
15
|
+
llmToolSelectorMiddleware: () => require_bigTool.llmToolSelectorMiddleware,
|
|
12
16
|
summarizationMiddleware: () => require_summarization.summarizationMiddleware
|
|
13
17
|
});
|
|
14
18
|
|
|
15
19
|
//#endregion
|
|
16
20
|
exports.anthropicPromptCachingMiddleware = require_promptCaching.anthropicPromptCachingMiddleware;
|
|
17
21
|
exports.countTokensApproximately = require_summarization.countTokensApproximately;
|
|
22
|
+
exports.dynamicSystemPromptMiddleware = require_dynamicSystemPrompt.dynamicSystemPromptMiddleware;
|
|
18
23
|
exports.humanInTheLoopMiddleware = require_hitl.humanInTheLoopMiddleware;
|
|
24
|
+
exports.llmToolSelectorMiddleware = require_bigTool.llmToolSelectorMiddleware;
|
|
19
25
|
Object.defineProperty(exports, 'middleware_exports', {
|
|
20
26
|
enumerable: true,
|
|
21
27
|
get: function () {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../../../src/agents/middlewareAgent/middleware/index.ts"],"sourcesContent":["export {\n summarizationMiddleware,\n countTokensApproximately,\n} from \"./summarization.js\";\nexport {
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../../../src/agents/middlewareAgent/middleware/index.ts"],"sourcesContent":["export {\n summarizationMiddleware,\n countTokensApproximately,\n type SummarizationMiddlewareConfig,\n} from \"./summarization.js\";\nexport {\n humanInTheLoopMiddleware,\n type HumanInTheLoopRequest,\n type HumanInTheLoopMiddlewareHumanResponse,\n type HumanInTheLoopMiddlewareConfig,\n type ActionRequest,\n} from \"./hitl.js\";\nexport {\n anthropicPromptCachingMiddleware,\n type PromptCachingMiddlewareConfig,\n} from \"./promptCaching.js\";\nexport {\n dynamicSystemPromptMiddleware,\n type DynamicSystemPromptMiddlewareConfig,\n} from \"./dynamicSystemPrompt.js\";\nexport {\n llmToolSelectorMiddleware,\n type LLMToolSelectorConfig,\n} from \"./bigTool.js\";\n"],"mappings":""}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { countTokensApproximately, summarizationMiddleware } from "./summarization.cjs";
|
|
2
|
-
import { humanInTheLoopMiddleware } from "./hitl.cjs";
|
|
3
|
-
import { anthropicPromptCachingMiddleware } from "./promptCaching.cjs";
|
|
4
|
-
|
|
1
|
+
import { SummarizationMiddlewareConfig, countTokensApproximately, summarizationMiddleware } from "./summarization.cjs";
|
|
2
|
+
import { ActionRequest, HumanInTheLoopMiddlewareConfig, HumanInTheLoopMiddlewareHumanResponse, HumanInTheLoopRequest, humanInTheLoopMiddleware } from "./hitl.cjs";
|
|
3
|
+
import { PromptCachingMiddlewareConfig, anthropicPromptCachingMiddleware } from "./promptCaching.cjs";
|
|
4
|
+
import { DynamicSystemPromptMiddlewareConfig, dynamicSystemPromptMiddleware } from "./dynamicSystemPrompt.cjs";
|
|
5
|
+
import { LLMToolSelectorConfig, llmToolSelectorMiddleware } from "./bigTool.cjs";
|
|
6
|
+
export { type ActionRequest, type DynamicSystemPromptMiddlewareConfig, type HumanInTheLoopMiddlewareConfig, type HumanInTheLoopMiddlewareHumanResponse, type HumanInTheLoopRequest, type LLMToolSelectorConfig, type PromptCachingMiddlewareConfig, type SummarizationMiddlewareConfig, anthropicPromptCachingMiddleware, countTokensApproximately, dynamicSystemPromptMiddleware, humanInTheLoopMiddleware, llmToolSelectorMiddleware, summarizationMiddleware };
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { countTokensApproximately, summarizationMiddleware } from "./summarization.js";
|
|
2
|
-
import { humanInTheLoopMiddleware } from "./hitl.js";
|
|
3
|
-
import { anthropicPromptCachingMiddleware } from "./promptCaching.js";
|
|
4
|
-
|
|
1
|
+
import { SummarizationMiddlewareConfig, countTokensApproximately, summarizationMiddleware } from "./summarization.js";
|
|
2
|
+
import { ActionRequest, HumanInTheLoopMiddlewareConfig, HumanInTheLoopMiddlewareHumanResponse, HumanInTheLoopRequest, humanInTheLoopMiddleware } from "./hitl.js";
|
|
3
|
+
import { PromptCachingMiddlewareConfig, anthropicPromptCachingMiddleware } from "./promptCaching.js";
|
|
4
|
+
import { DynamicSystemPromptMiddlewareConfig, dynamicSystemPromptMiddleware } from "./dynamicSystemPrompt.js";
|
|
5
|
+
import { LLMToolSelectorConfig, llmToolSelectorMiddleware } from "./bigTool.js";
|
|
6
|
+
export { type ActionRequest, type DynamicSystemPromptMiddlewareConfig, type HumanInTheLoopMiddlewareConfig, type HumanInTheLoopMiddlewareHumanResponse, type HumanInTheLoopRequest, type LLMToolSelectorConfig, type PromptCachingMiddlewareConfig, type SummarizationMiddlewareConfig, anthropicPromptCachingMiddleware, countTokensApproximately, dynamicSystemPromptMiddleware, humanInTheLoopMiddleware, llmToolSelectorMiddleware, summarizationMiddleware };
|
|
@@ -2,16 +2,20 @@ import { __export } from "../../../_virtual/rolldown_runtime.js";
|
|
|
2
2
|
import { countTokensApproximately, summarizationMiddleware } from "./summarization.js";
|
|
3
3
|
import { humanInTheLoopMiddleware } from "./hitl.js";
|
|
4
4
|
import { anthropicPromptCachingMiddleware } from "./promptCaching.js";
|
|
5
|
+
import { dynamicSystemPromptMiddleware } from "./dynamicSystemPrompt.js";
|
|
6
|
+
import { llmToolSelectorMiddleware } from "./bigTool.js";
|
|
5
7
|
|
|
6
8
|
//#region src/agents/middlewareAgent/middleware/index.ts
|
|
7
9
|
var middleware_exports = {};
|
|
8
10
|
__export(middleware_exports, {
|
|
9
11
|
anthropicPromptCachingMiddleware: () => anthropicPromptCachingMiddleware,
|
|
10
12
|
countTokensApproximately: () => countTokensApproximately,
|
|
13
|
+
dynamicSystemPromptMiddleware: () => dynamicSystemPromptMiddleware,
|
|
11
14
|
humanInTheLoopMiddleware: () => humanInTheLoopMiddleware,
|
|
15
|
+
llmToolSelectorMiddleware: () => llmToolSelectorMiddleware,
|
|
12
16
|
summarizationMiddleware: () => summarizationMiddleware
|
|
13
17
|
});
|
|
14
18
|
|
|
15
19
|
//#endregion
|
|
16
|
-
export { anthropicPromptCachingMiddleware, countTokensApproximately, humanInTheLoopMiddleware, middleware_exports, summarizationMiddleware };
|
|
20
|
+
export { anthropicPromptCachingMiddleware, countTokensApproximately, dynamicSystemPromptMiddleware, humanInTheLoopMiddleware, llmToolSelectorMiddleware, middleware_exports, summarizationMiddleware };
|
|
17
21
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/agents/middlewareAgent/middleware/index.ts"],"sourcesContent":["export {\n summarizationMiddleware,\n countTokensApproximately,\n} from \"./summarization.js\";\nexport {
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/agents/middlewareAgent/middleware/index.ts"],"sourcesContent":["export {\n summarizationMiddleware,\n countTokensApproximately,\n type SummarizationMiddlewareConfig,\n} from \"./summarization.js\";\nexport {\n humanInTheLoopMiddleware,\n type HumanInTheLoopRequest,\n type HumanInTheLoopMiddlewareHumanResponse,\n type HumanInTheLoopMiddlewareConfig,\n type ActionRequest,\n} from \"./hitl.js\";\nexport {\n anthropicPromptCachingMiddleware,\n type PromptCachingMiddlewareConfig,\n} from \"./promptCaching.js\";\nexport {\n dynamicSystemPromptMiddleware,\n type DynamicSystemPromptMiddlewareConfig,\n} from \"./dynamicSystemPrompt.js\";\nexport {\n llmToolSelectorMiddleware,\n type LLMToolSelectorConfig,\n} from \"./bigTool.js\";\n"],"mappings":""}
|
|
@@ -6,10 +6,16 @@ const zod_v3 = require_rolldown_runtime.__toESM(require("zod/v3"));
|
|
|
6
6
|
const DEFAULT_ENABLE_CACHING = true;
|
|
7
7
|
const DEFAULT_TTL = "5m";
|
|
8
8
|
const DEFAULT_MIN_MESSAGES_TO_CACHE = 3;
|
|
9
|
+
const DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR = "warn";
|
|
9
10
|
const contextSchema = zod_v3.z.object({
|
|
10
11
|
enableCaching: zod_v3.z.boolean().default(DEFAULT_ENABLE_CACHING),
|
|
11
12
|
ttl: zod_v3.z.enum(["5m", "1h"]).default(DEFAULT_TTL),
|
|
12
|
-
minMessagesToCache: zod_v3.z.number().default(DEFAULT_MIN_MESSAGES_TO_CACHE)
|
|
13
|
+
minMessagesToCache: zod_v3.z.number().default(DEFAULT_MIN_MESSAGES_TO_CACHE),
|
|
14
|
+
unsupportedModelBehavior: zod_v3.z.enum([
|
|
15
|
+
"ignore",
|
|
16
|
+
"warn",
|
|
17
|
+
"raise"
|
|
18
|
+
]).default(DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR)
|
|
13
19
|
});
|
|
14
20
|
var PromptCachingMiddlewareError = class extends Error {
|
|
15
21
|
constructor(message) {
|
|
@@ -41,6 +47,7 @@ var PromptCachingMiddlewareError = class extends Error {
|
|
|
41
47
|
* @param middlewareOptions.enableCaching - Whether to enable prompt caching (default: `true`)
|
|
42
48
|
* @param middlewareOptions.ttl - Cache time-to-live: `"5m"` for 5 minutes or `"1h"` for 1 hour (default: `"5m"`)
|
|
43
49
|
* @param middlewareOptions.minMessagesToCache - Minimum number of messages required before caching is applied (default: `3`)
|
|
50
|
+
* @param middlewareOptions.unsupportedModelBehavior - The behavior to take when an unsupported model is used (default: `"warn"`)
|
|
44
51
|
*
|
|
45
52
|
* @returns A middleware instance that can be passed to `createAgent`
|
|
46
53
|
*
|
|
@@ -70,7 +77,7 @@ var PromptCachingMiddlewareError = class extends Error {
|
|
|
70
77
|
*
|
|
71
78
|
* const agent = createAgent({
|
|
72
79
|
* model: "anthropic:claude-3-5-sonnet",
|
|
73
|
-
*
|
|
80
|
+
* systemPrompt: "You are a helpful assistant with deep knowledge of...", // Long system prompt
|
|
74
81
|
* middleware: [cachingMiddleware]
|
|
75
82
|
* });
|
|
76
83
|
* ```
|
|
@@ -104,7 +111,7 @@ var PromptCachingMiddlewareError = class extends Error {
|
|
|
104
111
|
* ```typescript
|
|
105
112
|
* const supportAgent = createAgent({
|
|
106
113
|
* model: "anthropic:claude-3-5-sonnet",
|
|
107
|
-
*
|
|
114
|
+
* systemPrompt: `You are a customer support agent for ACME Corp.
|
|
108
115
|
*
|
|
109
116
|
* Company policies:
|
|
110
117
|
* - Always be polite and professional
|
|
@@ -138,7 +145,7 @@ function anthropicPromptCachingMiddleware(middlewareOptions) {
|
|
|
138
145
|
return require_middleware.createMiddleware({
|
|
139
146
|
name: "PromptCachingMiddleware",
|
|
140
147
|
contextSchema,
|
|
141
|
-
|
|
148
|
+
modifyModelRequest: (options, state, runtime) => {
|
|
142
149
|
/**
|
|
143
150
|
* If the runtime values match the schema default values, use the middleware option
|
|
144
151
|
* values otherwise use the runtime values. This allows to apply general configurations
|
|
@@ -146,10 +153,19 @@ function anthropicPromptCachingMiddleware(middlewareOptions) {
|
|
|
146
153
|
*/
|
|
147
154
|
const enableCaching = runtime.context.enableCaching === DEFAULT_ENABLE_CACHING ? middlewareOptions?.enableCaching ?? runtime.context.enableCaching : runtime.context.enableCaching ?? middlewareOptions?.enableCaching;
|
|
148
155
|
const ttl = runtime.context.ttl === DEFAULT_TTL ? middlewareOptions?.ttl ?? runtime.context.ttl : runtime.context.ttl ?? middlewareOptions?.ttl;
|
|
149
|
-
const minMessagesToCache = runtime.context.minMessagesToCache === DEFAULT_MIN_MESSAGES_TO_CACHE ? middlewareOptions?.minMessagesToCache ?? runtime.context.minMessagesToCache : runtime.context.minMessagesToCache ?? middlewareOptions?.minMessagesToCache;
|
|
150
|
-
|
|
151
|
-
if (options.model
|
|
152
|
-
const
|
|
156
|
+
const minMessagesToCache = runtime.context.minMessagesToCache === DEFAULT_MIN_MESSAGES_TO_CACHE ? middlewareOptions?.minMessagesToCache ?? runtime.context.minMessagesToCache : runtime.context.minMessagesToCache ?? middlewareOptions?.minMessagesToCache ?? DEFAULT_MIN_MESSAGES_TO_CACHE;
|
|
157
|
+
const unsupportedModelBehavior = runtime.context.unsupportedModelBehavior === DEFAULT_UNSUPPORTED_MODEL_BEHAVIOR ? middlewareOptions?.unsupportedModelBehavior ?? runtime.context.unsupportedModelBehavior : runtime.context.unsupportedModelBehavior ?? middlewareOptions?.unsupportedModelBehavior;
|
|
158
|
+
if (!enableCaching || !options.model) return void 0;
|
|
159
|
+
const isAnthropicModel = options.model.getName() === "ChatAnthropic" || options.model.getName() === "ConfigurableModel" && options.model._defaultConfig?.modelProvider === "anthropic";
|
|
160
|
+
if (!isAnthropicModel) {
|
|
161
|
+
const modelName = options.model.getName();
|
|
162
|
+
const modelInfo = options.model.getName() === "ConfigurableModel" ? `${modelName} (${options.model._defaultConfig?.modelProvider})` : modelName;
|
|
163
|
+
const baseMessage = `Unsupported model '${modelInfo}'. Prompt caching requires an Anthropic model`;
|
|
164
|
+
if (unsupportedModelBehavior === "raise") throw new PromptCachingMiddlewareError(`${baseMessage} (e.g., 'anthropic:claude-4-0-sonnet').`);
|
|
165
|
+
else if (unsupportedModelBehavior === "warn") console.warn(`PromptCachingMiddleware: Skipping caching for ${modelName}. Consider switching to an Anthropic model for caching benefits.`);
|
|
166
|
+
return void 0;
|
|
167
|
+
}
|
|
168
|
+
const messagesCount = state.messages.length + (options.systemPrompt ? 1 : 0);
|
|
153
169
|
if (messagesCount < minMessagesToCache) return options;
|
|
154
170
|
/**
|
|
155
171
|
* Add cache_control to the last message
|