langchain 1.0.0-alpha.4 → 1.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/dist/agents/RunnableCallable.cjs +5 -0
  2. package/dist/agents/RunnableCallable.cjs.map +1 -1
  3. package/dist/agents/RunnableCallable.d.cts +2 -0
  4. package/dist/agents/RunnableCallable.d.cts.map +1 -1
  5. package/dist/agents/RunnableCallable.d.ts +2 -0
  6. package/dist/agents/RunnableCallable.d.ts.map +1 -1
  7. package/dist/agents/RunnableCallable.js +5 -0
  8. package/dist/agents/RunnableCallable.js.map +1 -1
  9. package/dist/agents/annotation.d.cts +1 -1
  10. package/dist/agents/createAgent.cjs +10 -0
  11. package/dist/agents/createAgent.cjs.map +1 -0
  12. package/dist/agents/createAgent.js +10 -0
  13. package/dist/agents/createAgent.js.map +1 -0
  14. package/dist/agents/index.cjs +23 -4
  15. package/dist/agents/index.cjs.map +1 -1
  16. package/dist/agents/index.d.cts +83 -20
  17. package/dist/agents/index.d.cts.map +1 -1
  18. package/dist/agents/index.d.ts +83 -20
  19. package/dist/agents/index.d.ts.map +1 -1
  20. package/dist/agents/index.js +23 -4
  21. package/dist/agents/index.js.map +1 -1
  22. package/dist/agents/middlewareAgent/ReactAgent.cjs +255 -0
  23. package/dist/agents/middlewareAgent/ReactAgent.cjs.map +1 -0
  24. package/dist/agents/middlewareAgent/ReactAgent.d.cts +68 -0
  25. package/dist/agents/middlewareAgent/ReactAgent.d.cts.map +1 -0
  26. package/dist/agents/middlewareAgent/ReactAgent.d.ts +68 -0
  27. package/dist/agents/middlewareAgent/ReactAgent.d.ts.map +1 -0
  28. package/dist/agents/middlewareAgent/ReactAgent.js +254 -0
  29. package/dist/agents/middlewareAgent/ReactAgent.js.map +1 -0
  30. package/dist/agents/middlewareAgent/annotation.cjs +39 -0
  31. package/dist/agents/middlewareAgent/annotation.cjs.map +1 -0
  32. package/dist/agents/middlewareAgent/annotation.js +38 -0
  33. package/dist/agents/middlewareAgent/annotation.js.map +1 -0
  34. package/dist/agents/middlewareAgent/index.cjs +11 -0
  35. package/dist/agents/middlewareAgent/index.cjs.map +1 -0
  36. package/dist/agents/middlewareAgent/index.js +11 -0
  37. package/dist/agents/middlewareAgent/index.js.map +1 -0
  38. package/dist/agents/middlewareAgent/middleware.cjs +47 -0
  39. package/dist/agents/middlewareAgent/middleware.cjs.map +1 -0
  40. package/dist/agents/middlewareAgent/middleware.d.cts +46 -0
  41. package/dist/agents/middlewareAgent/middleware.d.cts.map +1 -0
  42. package/dist/agents/middlewareAgent/middleware.d.ts +46 -0
  43. package/dist/agents/middlewareAgent/middleware.d.ts.map +1 -0
  44. package/dist/agents/middlewareAgent/middleware.js +46 -0
  45. package/dist/agents/middlewareAgent/middleware.js.map +1 -0
  46. package/dist/agents/middlewareAgent/middlewares/hitl.cjs +235 -0
  47. package/dist/agents/middlewareAgent/middlewares/hitl.cjs.map +1 -0
  48. package/dist/agents/middlewareAgent/middlewares/hitl.d.cts +199 -0
  49. package/dist/agents/middlewareAgent/middlewares/hitl.d.cts.map +1 -0
  50. package/dist/agents/middlewareAgent/middlewares/hitl.d.ts +199 -0
  51. package/dist/agents/middlewareAgent/middlewares/hitl.d.ts.map +1 -0
  52. package/dist/agents/middlewareAgent/middlewares/hitl.js +234 -0
  53. package/dist/agents/middlewareAgent/middlewares/hitl.js.map +1 -0
  54. package/dist/agents/middlewareAgent/middlewares/index.cjs +8 -0
  55. package/dist/agents/middlewareAgent/middlewares/index.d.cts +4 -0
  56. package/dist/agents/middlewareAgent/middlewares/index.d.ts +4 -0
  57. package/dist/agents/middlewareAgent/middlewares/index.js +5 -0
  58. package/dist/agents/middlewareAgent/middlewares/promptCaching.cjs +153 -0
  59. package/dist/agents/middlewareAgent/middlewares/promptCaching.cjs.map +1 -0
  60. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.cts +152 -0
  61. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.cts.map +1 -0
  62. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.ts +152 -0
  63. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.ts.map +1 -0
  64. package/dist/agents/middlewareAgent/middlewares/promptCaching.js +152 -0
  65. package/dist/agents/middlewareAgent/middlewares/promptCaching.js.map +1 -0
  66. package/dist/agents/middlewareAgent/middlewares/summarization.cjs +262 -0
  67. package/dist/agents/middlewareAgent/middlewares/summarization.cjs.map +1 -0
  68. package/dist/agents/middlewareAgent/middlewares/summarization.d.cts +89 -0
  69. package/dist/agents/middlewareAgent/middlewares/summarization.d.cts.map +1 -0
  70. package/dist/agents/middlewareAgent/middlewares/summarization.d.ts +89 -0
  71. package/dist/agents/middlewareAgent/middlewares/summarization.d.ts.map +1 -0
  72. package/dist/agents/middlewareAgent/middlewares/summarization.js +260 -0
  73. package/dist/agents/middlewareAgent/middlewares/summarization.js.map +1 -0
  74. package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs +29 -0
  75. package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs.map +1 -0
  76. package/dist/agents/middlewareAgent/nodes/AfterModalNode.js +29 -0
  77. package/dist/agents/middlewareAgent/nodes/AfterModalNode.js.map +1 -0
  78. package/dist/agents/middlewareAgent/nodes/AgentNode.cjs +332 -0
  79. package/dist/agents/middlewareAgent/nodes/AgentNode.cjs.map +1 -0
  80. package/dist/agents/middlewareAgent/nodes/AgentNode.js +331 -0
  81. package/dist/agents/middlewareAgent/nodes/AgentNode.js.map +1 -0
  82. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs +27 -0
  83. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs.map +1 -0
  84. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js +27 -0
  85. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js.map +1 -0
  86. package/dist/agents/middlewareAgent/nodes/middleware.cjs +73 -0
  87. package/dist/agents/middlewareAgent/nodes/middleware.cjs.map +1 -0
  88. package/dist/agents/middlewareAgent/nodes/middleware.js +73 -0
  89. package/dist/agents/middlewareAgent/nodes/middleware.js.map +1 -0
  90. package/dist/agents/middlewareAgent/nodes/utils.cjs +74 -0
  91. package/dist/agents/middlewareAgent/nodes/utils.cjs.map +1 -0
  92. package/dist/agents/middlewareAgent/nodes/utils.js +70 -0
  93. package/dist/agents/middlewareAgent/nodes/utils.js.map +1 -0
  94. package/dist/agents/middlewareAgent/types.d.cts +393 -0
  95. package/dist/agents/middlewareAgent/types.d.cts.map +1 -0
  96. package/dist/agents/middlewareAgent/types.d.ts +393 -0
  97. package/dist/agents/middlewareAgent/types.d.ts.map +1 -0
  98. package/dist/agents/nodes/ToolNode.d.cts +3 -3
  99. package/dist/agents/types.d.cts +4 -4
  100. package/dist/chains/api/api_chain.d.cts +1 -1
  101. package/dist/chains/base.d.cts +1 -1
  102. package/dist/chains/combine_docs_chain.d.cts +1 -1
  103. package/dist/chains/combine_documents/stuff.d.cts +1 -1
  104. package/dist/chains/conversational_retrieval_chain.d.cts +1 -1
  105. package/dist/chains/graph_qa/cypher.d.cts +1 -1
  106. package/dist/chains/history_aware_retriever.d.cts +2 -2
  107. package/dist/chains/llm_chain.d.cts +3 -3
  108. package/dist/chains/openai_functions/base.d.cts +3 -3
  109. package/dist/chains/openai_functions/openapi.d.cts +1 -1
  110. package/dist/chains/openai_functions/structured_output.d.cts +3 -3
  111. package/dist/chains/openai_functions/tagging.d.cts +1 -1
  112. package/dist/chains/query_constructor/index.cjs +1 -1
  113. package/dist/chains/query_constructor/index.d.cts +2 -2
  114. package/dist/chains/query_constructor/index.d.ts +1 -1
  115. package/dist/chains/query_constructor/index.js +1 -1
  116. package/dist/chains/question_answering/load.d.ts +2 -2
  117. package/dist/chains/question_answering/load.d.ts.map +1 -1
  118. package/dist/chains/retrieval.d.cts +1 -1
  119. package/dist/chains/router/llm_router.d.cts +1 -1
  120. package/dist/chains/router/multi_prompt.cjs +1 -1
  121. package/dist/chains/router/multi_prompt.js +1 -1
  122. package/dist/chains/router/multi_retrieval_qa.cjs +1 -1
  123. package/dist/chains/router/multi_retrieval_qa.js +1 -1
  124. package/dist/chains/sql_db/sql_db_chain.d.cts +2 -2
  125. package/dist/chains/summarization/load.d.ts +2 -2
  126. package/dist/chains/summarization/load.d.ts.map +1 -1
  127. package/dist/chat_models/universal.d.cts +3 -3
  128. package/dist/evaluation/agents/trajectory.d.cts +3 -3
  129. package/dist/evaluation/agents/trajectory.d.ts.map +1 -1
  130. package/dist/evaluation/comparison/pairwise.d.cts +1 -1
  131. package/dist/evaluation/comparison/pairwise.d.cts.map +1 -1
  132. package/dist/evaluation/comparison/pairwise.d.ts.map +1 -1
  133. package/dist/evaluation/criteria/criteria.d.cts +1 -1
  134. package/dist/evaluation/criteria/criteria.d.cts.map +1 -1
  135. package/dist/evaluation/criteria/criteria.d.ts.map +1 -1
  136. package/dist/evaluation/qa/eval_chain.d.cts +1 -1
  137. package/dist/index.cjs +3 -0
  138. package/dist/index.cjs.map +1 -1
  139. package/dist/index.d.cts +5 -4
  140. package/dist/index.d.ts +3 -2
  141. package/dist/index.js +3 -1
  142. package/dist/index.js.map +1 -1
  143. package/dist/load/import_map.cjs +1 -1
  144. package/dist/load/import_map.js +1 -1
  145. package/dist/memory/summary.d.cts +1 -1
  146. package/dist/output_parsers/fix.d.cts +1 -1
  147. package/dist/output_parsers/http_response.d.cts +1 -1
  148. package/dist/output_parsers/structured.cjs +1 -1
  149. package/dist/output_parsers/structured.d.cts +2 -2
  150. package/dist/output_parsers/structured.d.ts +1 -1
  151. package/dist/output_parsers/structured.js +1 -1
  152. package/dist/tools/fs.d.cts +1 -1
  153. package/dist/tools/json.d.cts +1 -1
  154. package/dist/tools/retriever.d.cts +1 -1
  155. package/dist/tools/vectorstore.d.cts +1 -1
  156. package/dist/tools/webbrowser.d.cts +1 -1
  157. package/package.json +17 -6
@@ -0,0 +1,199 @@
1
+ import { AgentMiddleware } from "../types.js";
2
+ import { z } from "zod";
3
+
4
+ //#region src/agents/middlewareAgent/middlewares/hitl.d.ts
5
+ declare const contextSchema: z.ZodObject<{
6
+ toolConfigs: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
7
+ requireApproval: z.ZodOptional<z.ZodBoolean>;
8
+ description: z.ZodOptional<z.ZodString>;
9
+ }, "strip", z.ZodTypeAny, {
10
+ requireApproval?: boolean | undefined;
11
+ description?: string | undefined;
12
+ }, {
13
+ requireApproval?: boolean | undefined;
14
+ description?: string | undefined;
15
+ }>>>;
16
+ messagePrefix: z.ZodDefault<z.ZodString>;
17
+ }, "strip", z.ZodTypeAny, {
18
+ toolConfigs: Record<string, {
19
+ requireApproval?: boolean | undefined;
20
+ description?: string | undefined;
21
+ }>;
22
+ messagePrefix: string;
23
+ }, {
24
+ toolConfigs?: Record<string, {
25
+ requireApproval?: boolean | undefined;
26
+ description?: string | undefined;
27
+ }> | undefined;
28
+ messagePrefix?: string | undefined;
29
+ }>;
30
+ /**
31
+ * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.
32
+ *
33
+ * This middleware intercepts tool calls made by an AI agent and provides human oversight
34
+ * capabilities before execution. It enables selective approval workflows where certain tools
35
+ * require human intervention while others can execute automatically.
36
+ *
37
+ * ## Features
38
+ *
39
+ * - **Selective Tool Approval**: Configure which tools require human approval
40
+ * - **Multiple Response Types**: Accept, edit, ignore, or manually respond to tool calls
41
+ * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval
42
+ * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests
43
+ *
44
+ * ## Response Types
45
+ *
46
+ * When a tool requires approval, the human operator can respond with:
47
+ * - `accept`: Execute the tool with original arguments
48
+ * - `edit`: Modify the tool arguments before execution
49
+ * - `ignore`: Skip the tool and terminate the agent
50
+ * - `response`: Provide a manual response instead of executing the tool
51
+ *
52
+ * @param options - Configuration options for the middleware
53
+ * @param options.toolConfigs - Per-tool configuration mapping tool names to their settings
54
+ * @param options.toolConfigs[toolName].requireApproval - Whether the tool requires human approval
55
+ * @param options.toolConfigs[toolName].description - Custom approval message for the tool
56
+ * @param options.messagePrefix - Default prefix for approval messages (default: "Tool execution requires approval")
57
+ *
58
+ * @returns A middleware instance that can be passed to `createAgent`
59
+ *
60
+ * @example
61
+ * Basic usage with selective tool approval
62
+ * ```typescript
63
+ * import { humanInTheLoopMiddleware } from "langchain/middleware";
64
+ * import { createAgent } from "langchain";
65
+ *
66
+ * const hitlMiddleware = humanInTheLoopMiddleware({
67
+ * toolConfigs: {
68
+ * "write_file": {
69
+ * requireApproval: true,
70
+ * description: "⚠️ File write operation requires approval"
71
+ * },
72
+ * "read_file": {
73
+ * requireApproval: false // Safe operation, no approval needed
74
+ * }
75
+ * }
76
+ * });
77
+ *
78
+ * const agent = createAgent({
79
+ * model: "openai:gpt-4",
80
+ * tools: [writeFileTool, readFileTool],
81
+ * middlewares: [hitlMiddleware]
82
+ * });
83
+ * ```
84
+ *
85
+ * @example
86
+ * Handling approval requests
87
+ * ```typescript
88
+ * import { Command } from "@langchain/langgraph";
89
+ *
90
+ * // Initial agent invocation
91
+ * const result = await agent.invoke({
92
+ * messages: [new HumanMessage("Write 'Hello' to output.txt")]
93
+ * }, config);
94
+ *
95
+ * // Check if agent is paused for approval
96
+ * const state = await agent.graph.getState(config);
97
+ * if (state.next?.length > 0) {
98
+ * // Get interrupt details
99
+ * const task = state.tasks?.[0];
100
+ * const requests = task?.interrupts?.[0]?.value;
101
+ *
102
+ * // Show tool call details to user
103
+ * console.log("Tool:", requests[0].action);
104
+ * console.log("Args:", requests[0].args);
105
+ *
106
+ * // Resume with approval
107
+ * await agent.invoke(
108
+ * new Command({ resume: [{ type: "accept" }] }),
109
+ * config
110
+ * );
111
+ * }
112
+ * ```
113
+ *
114
+ * @example
115
+ * Different response types
116
+ * ```typescript
117
+ * // Accept the tool call as-is
118
+ * new Command({ resume: [{ type: "accept" }] })
119
+ *
120
+ * // Edit the tool arguments
121
+ * new Command({
122
+ * resume: [{
123
+ * type: "edit",
124
+ * args: { action: "write_file", args: { filename: "safe.txt", content: "Modified" } }
125
+ * }]
126
+ * })
127
+ *
128
+ * // Skip tool and terminate agent
129
+ * new Command({ resume: [{ type: "ignore" }] })
130
+ *
131
+ * // Provide manual response
132
+ * new Command({
133
+ * resume: [{
134
+ * type: "response",
135
+ * args: "File operation not allowed in demo mode"
136
+ * }]
137
+ * })
138
+ * ```
139
+ *
140
+ * @example
141
+ * Production use case with database operations
142
+ * ```typescript
143
+ * const hitlMiddleware = humanInTheLoopMiddleware({
144
+ * toolConfigs: {
145
+ * "execute_sql": {
146
+ * requireApproval: true,
147
+ * description: "🚨 SQL query requires DBA approval\nPlease review for safety and performance"
148
+ * },
149
+ * "read_schema": {
150
+ * requireApproval: false // Reading metadata is safe
151
+ * },
152
+ * "delete_records": {
153
+ * requireApproval: true,
154
+ * description: "⛔ DESTRUCTIVE OPERATION - Requires manager approval"
155
+ * }
156
+ * },
157
+ * messagePrefix: "Database operation pending approval"
158
+ * });
159
+ * ```
160
+ *
161
+ * @remarks
162
+ * - Tool calls are processed in the order they appear in the AI message
163
+ * - Auto-approved tools execute immediately without interruption
164
+ * - Multiple tools requiring approval are bundled into a single interrupt
165
+ * - The middleware operates in the `afterModel` phase, intercepting before tool execution
166
+ * - Requires a checkpointer to maintain state across interruptions
167
+ *
168
+ * @see {@link createAgent} for agent creation
169
+ * @see {@link Command} for resuming interrupted execution
170
+ * @public
171
+ */
172
+ declare function humanInTheLoopMiddleware(options?: z.input<typeof contextSchema>): AgentMiddleware<undefined, z.ZodObject<{
173
+ toolConfigs: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
174
+ requireApproval: z.ZodOptional<z.ZodBoolean>;
175
+ description: z.ZodOptional<z.ZodString>;
176
+ }, "strip", z.ZodTypeAny, {
177
+ requireApproval?: boolean | undefined;
178
+ description?: string | undefined;
179
+ }, {
180
+ requireApproval?: boolean | undefined;
181
+ description?: string | undefined;
182
+ }>>>;
183
+ messagePrefix: z.ZodDefault<z.ZodString>;
184
+ }, "strip", z.ZodTypeAny, {
185
+ toolConfigs: Record<string, {
186
+ requireApproval?: boolean | undefined;
187
+ description?: string | undefined;
188
+ }>;
189
+ messagePrefix: string;
190
+ }, {
191
+ toolConfigs?: Record<string, {
192
+ requireApproval?: boolean | undefined;
193
+ description?: string | undefined;
194
+ }> | undefined;
195
+ messagePrefix?: string | undefined;
196
+ }>, any>;
197
+ //#endregion
198
+ export { humanInTheLoopMiddleware };
199
+ //# sourceMappingURL=hitl.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hitl.d.ts","names":["z","contextSchema","ZodString","ZodBoolean","ZodOptional","ZodTypeAny","ZodObject","ZodRecord","ZodDefault","Record","humanInTheLoopMiddleware","input","___types_js1","AgentMiddleware"],"sources":["../../../../src/agents/middlewareAgent/middlewares/hitl.d.ts"],"sourcesContent":["import { z } from \"zod\";\ndeclare const contextSchema: z.ZodObject<{\n toolConfigs: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{\n requireApproval: z.ZodOptional<z.ZodBoolean>;\n description: z.ZodOptional<z.ZodString>;\n }, \"strip\", z.ZodTypeAny, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>>>;\n messagePrefix: z.ZodDefault<z.ZodString>;\n}, \"strip\", z.ZodTypeAny, {\n toolConfigs: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>;\n messagePrefix: string;\n}, {\n toolConfigs?: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }> | undefined;\n messagePrefix?: string | undefined;\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 * middlewares: [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 declare function humanInTheLoopMiddleware(options?: z.input<typeof contextSchema>): import(\"../types.js\").AgentMiddleware<undefined, z.ZodObject<{\n toolConfigs: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{\n requireApproval: z.ZodOptional<z.ZodBoolean>;\n description: z.ZodOptional<z.ZodString>;\n }, \"strip\", z.ZodTypeAny, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>>>;\n messagePrefix: z.ZodDefault<z.ZodString>;\n}, \"strip\", z.ZodTypeAny, {\n toolConfigs: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }>;\n messagePrefix: string;\n}, {\n toolConfigs?: Record<string, {\n requireApproval?: boolean | undefined;\n description?: string | undefined;\n }> | undefined;\n messagePrefix?: string | undefined;\n}>, any>;\nexport {};\n"],"mappings":";;;;cACcC,eAAeD,CAAAA,CAAEM;eACdN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,UAAUP,CAAAA,CAAEE,WAAWF,CAAAA,CAAEM;qBAChCN,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;IAF3BF,WAAAA,EAGOD,CAAAA,CAAEI,WAqBrB,CArBiCJ,CAAAA,CAAEE,SAqBnC,CAAA;EAAA,CAAA,EAAA,OAAA,EApBcF,CAAAA,CAAEK,UAoBhB,EAAA;IAvBwCL,eAAEE,CAAAA,EAAAA,OAAAA,GAAAA,SAAAA;IACLF,WAAEG,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAU,CAAA,EAA1BH;IACUA,eAAEE,CAAAA,EAAAA,OAAAA,GAAAA,SAAAA;IAAhBF,WAAEI,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAW,CAAA,CAAA,CAClBJ,CAAAA;EAAY,aAH6BM,EAUtCN,CAAAA,CAAEQ,UAVoCF,CAUzBN,CAAAA,CAAEE,SAVuBI,CAAAA;CAAS,EAAA,OAAlCC,EAWpBP,CAAAA,CAAEK,UAXkBE,EAAAA;EAAS,WAAtBC,EAYFC,MAZED,CAAAA,MAAAA,EAAAA;IAUaR,eAAEE,CAAAA,EAAAA,OAAAA,GAAAA,SAAAA;IAAfF,WAAEQ,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAU,CAAA,CAAA;EACP,aACPC,EAAAA,MAAAA;CAAM,EAAA;EAMC,WAnBOH,CAAAA,EAmBbG,MAnBaH,CAAAA,MAAAA,EAAAA;IAAS,eAAA,CAAA,EAAA,OAAA,GAAA,SAAA;IAuKhBI,WAAAA,CAAAA,EAAAA,MAAAA,GAAwB,SAAA;EAAA,CAAA,CAAA,GAAA,SAAA;EAAA,aAA0BT,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;CAAa,CAAA;;;;;;;;;;;;;;;;;AAAyC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAxGS,wBAAAA,WAAmCV,CAAAA,CAAEW,aAAaV,iBAA6E,2BAAXD,CAAAA,CAAEM;eAC7HN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,UAAUP,CAAAA,CAAEE,WAAWF,CAAAA,CAAEM;qBAChCN,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEG;iBACpBH,CAAAA,CAAEI,YAAYJ,CAAAA,CAAEE;cACrBF,CAAAA,CAAEK;;;;;;;iBAOCL,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEE;YACtBF,CAAAA,CAAEK;eACGI;;;;;;gBAMCA"}
@@ -0,0 +1,234 @@
1
+ import { createMiddleware } from "../middleware.js";
2
+ import { AIMessage, ToolMessage, isAIMessage } from "@langchain/core/messages";
3
+ import { interrupt } from "@langchain/langgraph";
4
+ import { z } from "zod";
5
+ import { v4 } from "uuid";
6
+
7
+ //#region src/agents/middlewareAgent/middlewares/hitl.ts
8
+ const contextSchema = z.object({
9
+ toolConfigs: z.record(z.object({
10
+ requireApproval: z.boolean().optional(),
11
+ description: z.string().optional()
12
+ })).default({}),
13
+ messagePrefix: z.string().default("Tool execution requires approval")
14
+ });
15
+ /**
16
+ * Creates a Human-in-the-Loop (HITL) middleware for tool approval and oversight.
17
+ *
18
+ * This middleware intercepts tool calls made by an AI agent and provides human oversight
19
+ * capabilities before execution. It enables selective approval workflows where certain tools
20
+ * require human intervention while others can execute automatically.
21
+ *
22
+ * ## Features
23
+ *
24
+ * - **Selective Tool Approval**: Configure which tools require human approval
25
+ * - **Multiple Response Types**: Accept, edit, ignore, or manually respond to tool calls
26
+ * - **Asynchronous Workflow**: Uses LangGraph's interrupt mechanism for non-blocking approval
27
+ * - **Custom Approval Messages**: Provide context-specific descriptions for approval requests
28
+ *
29
+ * ## Response Types
30
+ *
31
+ * When a tool requires approval, the human operator can respond with:
32
+ * - `accept`: Execute the tool with original arguments
33
+ * - `edit`: Modify the tool arguments before execution
34
+ * - `ignore`: Skip the tool and terminate the agent
35
+ * - `response`: Provide a manual response instead of executing the tool
36
+ *
37
+ * @param options - Configuration options for the middleware
38
+ * @param options.toolConfigs - Per-tool configuration mapping tool names to their settings
39
+ * @param options.toolConfigs[toolName].requireApproval - Whether the tool requires human approval
40
+ * @param options.toolConfigs[toolName].description - Custom approval message for the tool
41
+ * @param options.messagePrefix - Default prefix for approval messages (default: "Tool execution requires approval")
42
+ *
43
+ * @returns A middleware instance that can be passed to `createAgent`
44
+ *
45
+ * @example
46
+ * Basic usage with selective tool approval
47
+ * ```typescript
48
+ * import { humanInTheLoopMiddleware } from "langchain/middleware";
49
+ * import { createAgent } from "langchain";
50
+ *
51
+ * const hitlMiddleware = humanInTheLoopMiddleware({
52
+ * toolConfigs: {
53
+ * "write_file": {
54
+ * requireApproval: true,
55
+ * description: "⚠️ File write operation requires approval"
56
+ * },
57
+ * "read_file": {
58
+ * requireApproval: false // Safe operation, no approval needed
59
+ * }
60
+ * }
61
+ * });
62
+ *
63
+ * const agent = createAgent({
64
+ * model: "openai:gpt-4",
65
+ * tools: [writeFileTool, readFileTool],
66
+ * middlewares: [hitlMiddleware]
67
+ * });
68
+ * ```
69
+ *
70
+ * @example
71
+ * Handling approval requests
72
+ * ```typescript
73
+ * import { Command } from "@langchain/langgraph";
74
+ *
75
+ * // Initial agent invocation
76
+ * const result = await agent.invoke({
77
+ * messages: [new HumanMessage("Write 'Hello' to output.txt")]
78
+ * }, config);
79
+ *
80
+ * // Check if agent is paused for approval
81
+ * const state = await agent.graph.getState(config);
82
+ * if (state.next?.length > 0) {
83
+ * // Get interrupt details
84
+ * const task = state.tasks?.[0];
85
+ * const requests = task?.interrupts?.[0]?.value;
86
+ *
87
+ * // Show tool call details to user
88
+ * console.log("Tool:", requests[0].action);
89
+ * console.log("Args:", requests[0].args);
90
+ *
91
+ * // Resume with approval
92
+ * await agent.invoke(
93
+ * new Command({ resume: [{ type: "accept" }] }),
94
+ * config
95
+ * );
96
+ * }
97
+ * ```
98
+ *
99
+ * @example
100
+ * Different response types
101
+ * ```typescript
102
+ * // Accept the tool call as-is
103
+ * new Command({ resume: [{ type: "accept" }] })
104
+ *
105
+ * // Edit the tool arguments
106
+ * new Command({
107
+ * resume: [{
108
+ * type: "edit",
109
+ * args: { action: "write_file", args: { filename: "safe.txt", content: "Modified" } }
110
+ * }]
111
+ * })
112
+ *
113
+ * // Skip tool and terminate agent
114
+ * new Command({ resume: [{ type: "ignore" }] })
115
+ *
116
+ * // Provide manual response
117
+ * new Command({
118
+ * resume: [{
119
+ * type: "response",
120
+ * args: "File operation not allowed in demo mode"
121
+ * }]
122
+ * })
123
+ * ```
124
+ *
125
+ * @example
126
+ * Production use case with database operations
127
+ * ```typescript
128
+ * const hitlMiddleware = humanInTheLoopMiddleware({
129
+ * toolConfigs: {
130
+ * "execute_sql": {
131
+ * requireApproval: true,
132
+ * description: "🚨 SQL query requires DBA approval\nPlease review for safety and performance"
133
+ * },
134
+ * "read_schema": {
135
+ * requireApproval: false // Reading metadata is safe
136
+ * },
137
+ * "delete_records": {
138
+ * requireApproval: true,
139
+ * description: "⛔ DESTRUCTIVE OPERATION - Requires manager approval"
140
+ * }
141
+ * },
142
+ * messagePrefix: "Database operation pending approval"
143
+ * });
144
+ * ```
145
+ *
146
+ * @remarks
147
+ * - Tool calls are processed in the order they appear in the AI message
148
+ * - Auto-approved tools execute immediately without interruption
149
+ * - Multiple tools requiring approval are bundled into a single interrupt
150
+ * - The middleware operates in the `afterModel` phase, intercepting before tool execution
151
+ * - Requires a checkpointer to maintain state across interruptions
152
+ *
153
+ * @see {@link createAgent} for agent creation
154
+ * @see {@link Command} for resuming interrupted execution
155
+ * @public
156
+ */
157
+ function humanInTheLoopMiddleware(options = {}) {
158
+ return createMiddleware({
159
+ name: "HumanInTheLoopMiddleware",
160
+ contextSchema,
161
+ afterModel: async (state, runtime, controls) => {
162
+ const config = {
163
+ ...contextSchema.parse(options),
164
+ ...runtime.context
165
+ };
166
+ const { messages } = state;
167
+ if (!messages.length) return;
168
+ const lastMessage = messages[messages.length - 1];
169
+ if (!isAIMessage(lastMessage) || !lastMessage.tool_calls?.length) return;
170
+ const interruptToolCalls = [];
171
+ const autoApprovedToolCalls = [];
172
+ for (const toolCall of lastMessage.tool_calls) {
173
+ const normalizedToolCall = {
174
+ id: toolCall.id || v4(),
175
+ name: toolCall.name,
176
+ args: toolCall.args
177
+ };
178
+ const toolConfig = config.toolConfigs[normalizedToolCall.name];
179
+ if (toolConfig?.requireApproval) interruptToolCalls.push(normalizedToolCall);
180
+ else autoApprovedToolCalls.push(normalizedToolCall);
181
+ }
182
+ if (!interruptToolCalls.length) return;
183
+ const approvedToolCalls = [...autoApprovedToolCalls];
184
+ const requests = interruptToolCalls.map((toolCall) => {
185
+ const toolConfig = config.toolConfigs[toolCall.name];
186
+ const description = toolConfig?.description || `${config.messagePrefix}\n\nTool: ${toolCall.name}\nArgs: ${JSON.stringify(toolCall.args, null, 2)}`;
187
+ return {
188
+ action: toolCall.name,
189
+ args: toolCall.args,
190
+ toolCallId: toolCall.id,
191
+ description
192
+ };
193
+ });
194
+ const responses = await interrupt(requests);
195
+ for (let i = 0; i < responses.length; i++) {
196
+ const response = responses[i];
197
+ const toolCall = interruptToolCalls[i];
198
+ switch (response.type) {
199
+ case "accept":
200
+ approvedToolCalls.push(toolCall);
201
+ break;
202
+ case "edit":
203
+ if (response.args && typeof response.args === "object" && "args" in response.args) approvedToolCalls.push({
204
+ ...toolCall,
205
+ args: response.args.args
206
+ });
207
+ break;
208
+ case "ignore": return controls.terminate();
209
+ case "response": {
210
+ const toolMessage = new ToolMessage({
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}`);
220
+ }
221
+ }
222
+ const updatedMessage = new AIMessage({
223
+ content: lastMessage.content,
224
+ tool_calls: approvedToolCalls,
225
+ id: lastMessage.id
226
+ });
227
+ return { messages: [...state.messages.slice(0, -1), updatedMessage] };
228
+ }
229
+ });
230
+ }
231
+
232
+ //#endregion
233
+ export { humanInTheLoopMiddleware };
234
+ //# sourceMappingURL=hitl.js.map
@@ -0,0 +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/middlewares/hitl.ts"],"sourcesContent":["import { z } from \"zod\";\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 * middlewares: [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":";;;;;;;AAmBA,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"}
@@ -0,0 +1,8 @@
1
+ const require_summarization = require('./summarization.cjs');
2
+ const require_hitl = require('./hitl.cjs');
3
+ const require_promptCaching = require('./promptCaching.cjs');
4
+
5
+ exports.anthropicPromptCachingMiddleware = require_promptCaching.anthropicPromptCachingMiddleware;
6
+ exports.countTokensApproximately = require_summarization.countTokensApproximately;
7
+ exports.humanInTheLoopMiddleware = require_hitl.humanInTheLoopMiddleware;
8
+ exports.summarizationMiddleware = require_summarization.summarizationMiddleware;
@@ -0,0 +1,4 @@
1
+ import { countTokensApproximately, summarizationMiddleware } from "./summarization.cjs";
2
+ import { humanInTheLoopMiddleware } from "./hitl.cjs";
3
+ import { anthropicPromptCachingMiddleware } from "./promptCaching.cjs";
4
+ export { anthropicPromptCachingMiddleware, countTokensApproximately, humanInTheLoopMiddleware, summarizationMiddleware };
@@ -0,0 +1,4 @@
1
+ import { countTokensApproximately, summarizationMiddleware } from "./summarization.js";
2
+ import { humanInTheLoopMiddleware } from "./hitl.js";
3
+ import { anthropicPromptCachingMiddleware } from "./promptCaching.js";
4
+ export { anthropicPromptCachingMiddleware, countTokensApproximately, humanInTheLoopMiddleware, summarizationMiddleware };
@@ -0,0 +1,5 @@
1
+ import { countTokensApproximately, summarizationMiddleware } from "./summarization.js";
2
+ import { humanInTheLoopMiddleware } from "./hitl.js";
3
+ import { anthropicPromptCachingMiddleware } from "./promptCaching.js";
4
+
5
+ export { anthropicPromptCachingMiddleware, countTokensApproximately, humanInTheLoopMiddleware, summarizationMiddleware };
@@ -0,0 +1,153 @@
1
+ const require_rolldown_runtime = require('../../../_virtual/rolldown_runtime.cjs');
2
+ const require_middleware = require('../middleware.cjs');
3
+ const zod = require_rolldown_runtime.__toESM(require("zod"));
4
+
5
+ //#region src/agents/middlewareAgent/middlewares/promptCaching.ts
6
+ const contextSchema = zod.z.object({
7
+ enableCaching: zod.z.boolean().default(true),
8
+ ttl: zod.z.enum(["5m", "1h"]).default("5m"),
9
+ minMessagesToCache: zod.z.number().default(3)
10
+ });
11
+ /**
12
+ * Creates a prompt caching middleware for Anthropic models to optimize API usage.
13
+ *
14
+ * This middleware automatically adds cache control headers to messages when using Anthropic models,
15
+ * enabling their prompt caching feature. This can significantly reduce costs and latency for
16
+ * applications with repetitive prompts, long system messages, or extensive conversation histories.
17
+ *
18
+ * ## How It Works
19
+ *
20
+ * The middleware intercepts model requests and adds cache control metadata that tells Anthropic's
21
+ * API to cache processed prompt prefixes. On subsequent requests with matching prefixes, the
22
+ * cached representations are reused, skipping redundant token processing.
23
+ *
24
+ * ## Benefits
25
+ *
26
+ * - **Cost Reduction**: Avoid reprocessing the same tokens repeatedly (up to 90% savings on cached portions)
27
+ * - **Lower Latency**: Cached prompts are processed faster as embeddings are pre-computed
28
+ * - **Better Scalability**: Reduced computational load enables handling more requests
29
+ * - **Consistent Performance**: Stable response times for repetitive queries
30
+ *
31
+ * @param middlewareOptions - Configuration options for the caching behavior
32
+ * @param middlewareOptions.enableCaching - Whether to enable prompt caching (default: `true`)
33
+ * @param middlewareOptions.ttl - Cache time-to-live: `"5m"` for 5 minutes or `"1h"` for 1 hour (default: `"5m"`)
34
+ * @param middlewareOptions.minMessagesToCache - Minimum number of messages required before caching is applied (default: `3`)
35
+ *
36
+ * @returns A middleware instance that can be passed to `createAgent`
37
+ *
38
+ * @throws {Error} If used with non-Anthropic models
39
+ *
40
+ * @example
41
+ * Basic usage with default settings
42
+ * ```typescript
43
+ * import { createAgent } from "langchain";
44
+ * import { anthropicPromptCachingMiddleware } from "langchain/middleware";
45
+ *
46
+ * const agent = createAgent({
47
+ * model: "anthropic:claude-3-5-sonnet",
48
+ * middlewares: [
49
+ * anthropicPromptCachingMiddleware()
50
+ * ]
51
+ * });
52
+ * ```
53
+ *
54
+ * @example
55
+ * Custom configuration for longer conversations
56
+ * ```typescript
57
+ * const cachingMiddleware = anthropicPromptCachingMiddleware({
58
+ * ttl: "1h", // Cache for 1 hour instead of default 5 minutes
59
+ * minMessagesToCache: 5 // Only cache after 5 messages
60
+ * });
61
+ *
62
+ * const agent = createAgent({
63
+ * model: "anthropic:claude-3-5-sonnet",
64
+ * systemMessage: "You are a helpful assistant with deep knowledge of...", // Long system prompt
65
+ * middlewares: [cachingMiddleware]
66
+ * });
67
+ * ```
68
+ *
69
+ * @example
70
+ * Conditional caching based on runtime context
71
+ * ```typescript
72
+ * const agent = createAgent({
73
+ * model: "anthropic:claude-3-5-sonnet",
74
+ * middlewares: [
75
+ * anthropicPromptCachingMiddleware({
76
+ * enableCaching: true,
77
+ * ttl: "5m"
78
+ * })
79
+ * ]
80
+ * });
81
+ *
82
+ * // Disable caching for specific requests
83
+ * await agent.invoke(
84
+ * { messages: [new HumanMessage("Process this without caching")] },
85
+ * {
86
+ * configurable: {
87
+ * middleware_context: { enableCaching: false }
88
+ * }
89
+ * }
90
+ * );
91
+ * ```
92
+ *
93
+ * @example
94
+ * Optimal setup for customer support chatbot
95
+ * ```typescript
96
+ * const supportAgent = createAgent({
97
+ * model: "anthropic:claude-3-5-sonnet",
98
+ * systemMessage: `You are a customer support agent for ACME Corp.
99
+ *
100
+ * Company policies:
101
+ * - Always be polite and professional
102
+ * - Refer to knowledge base for product information
103
+ * - Escalate billing issues to human agents
104
+ * ... (extensive policies and guidelines)
105
+ * `,
106
+ * tools: [searchKnowledgeBase, createTicket, checkOrderStatus],
107
+ * middlewares: [
108
+ * anthropicPromptCachingMiddleware({
109
+ * ttl: "1h", // Long TTL for stable system prompt
110
+ * minMessagesToCache: 1 // Cache immediately due to large system prompt
111
+ * })
112
+ * ]
113
+ * });
114
+ * ```
115
+ *
116
+ * @remarks
117
+ * - **Anthropic Only**: This middleware only works with Anthropic models and will throw an error if used with other providers
118
+ * - **Automatic Application**: Caching is applied automatically when message count exceeds `minMessagesToCache`
119
+ * - **Cache Scope**: Caches are isolated per API key and cannot be shared across different keys
120
+ * - **TTL Options**: Only supports "5m" (5 minutes) and "1h" (1 hour) as TTL values per Anthropic's API
121
+ * - **Best Use Cases**: Long system prompts, multi-turn conversations, repetitive queries, RAG applications
122
+ * - **Cost Impact**: Cached tokens are billed at 10% of the base input token price, cache writes are billed at 25% of the base
123
+ *
124
+ * @see {@link createAgent} for agent creation
125
+ * @see {@link https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching} Anthropic's prompt caching documentation
126
+ * @public
127
+ */
128
+ function anthropicPromptCachingMiddleware(middlewareOptions) {
129
+ return require_middleware.createMiddleware({
130
+ name: "PromptCachingMiddleware",
131
+ contextSchema,
132
+ prepareModelRequest: (options, state, runtime) => {
133
+ const enableCaching = runtime.context.enableCaching ?? middlewareOptions?.enableCaching;
134
+ const ttl = runtime.context.ttl ?? middlewareOptions?.ttl;
135
+ const minMessagesToCache = runtime.context.minMessagesToCache ?? middlewareOptions?.minMessagesToCache;
136
+ if (!enableCaching) return void 0;
137
+ if (options.model?.getName() !== "anthropic") throw new Error("Prompt caching is only supported for Anthropic models");
138
+ const messagesCount = state.messages.length + (options.systemMessage ? 1 : 0);
139
+ if (messagesCount < minMessagesToCache) return options;
140
+ return {
141
+ ...options,
142
+ modelSettings: { cache_control: {
143
+ type: "ephemeral",
144
+ ttl
145
+ } }
146
+ };
147
+ }
148
+ });
149
+ }
150
+
151
+ //#endregion
152
+ exports.anthropicPromptCachingMiddleware = anthropicPromptCachingMiddleware;
153
+ //# sourceMappingURL=promptCaching.cjs.map