langchain 1.2.19 → 1.2.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/dist/agents/middleware/llmToolSelector.d.ts +4 -4
- package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
- package/dist/agents/middleware/summarization.d.ts +8 -8
- package/dist/agents/middleware/summarization.d.ts.map +1 -1
- package/dist/agents/middleware/types.cjs.map +1 -1
- package/dist/agents/middleware/types.d.cts +1 -1
- package/dist/agents/middleware/types.d.cts.map +1 -1
- package/dist/agents/middleware/types.d.ts +1 -1
- package/dist/agents/middleware/types.d.ts.map +1 -1
- package/dist/agents/middleware/types.js.map +1 -1
- package/dist/agents/middleware/utils.cjs +20 -3
- package/dist/agents/middleware/utils.cjs.map +1 -1
- package/dist/agents/middleware/utils.d.cts +8 -2
- package/dist/agents/middleware/utils.d.cts.map +1 -1
- package/dist/agents/middleware/utils.d.ts +8 -2
- package/dist/agents/middleware/utils.d.ts.map +1 -1
- package/dist/agents/middleware/utils.js +20 -3
- package/dist/agents/middleware/utils.js.map +1 -1
- package/dist/agents/nodes/AgentNode.cjs +86 -51
- package/dist/agents/nodes/AgentNode.cjs.map +1 -1
- package/dist/agents/nodes/AgentNode.js +87 -52
- package/dist/agents/nodes/AgentNode.js.map +1 -1
- package/dist/agents/nodes/middleware.cjs +4 -5
- package/dist/agents/nodes/middleware.cjs.map +1 -1
- package/dist/agents/nodes/middleware.js +4 -5
- package/dist/agents/nodes/middleware.js.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# langchain
|
|
2
2
|
|
|
3
|
+
## 1.2.20
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#9983](https://github.com/langchain-ai/langchainjs/pull/9983) [`ea7e791`](https://github.com/langchain-ai/langchainjs/commit/ea7e791ff6c93188b7febbd98ea22359fa96eb20) Thanks [@encodedz](https://github.com/encodedz)! - Support concurrent `agentNode` dynamic prompts properly.
|
|
8
|
+
|
|
9
|
+
- [#9986](https://github.com/langchain-ai/langchainjs/pull/9986) [`8a52dad`](https://github.com/langchain-ai/langchainjs/commit/8a52dad1eace191b19d24cc5683acb22a5b9e964) Thanks [@brettshollenberger](https://github.com/brettshollenberger)! - Don't re-emit input state from middleware hooks that return void
|
|
10
|
+
|
|
11
|
+
- [#9982](https://github.com/langchain-ai/langchainjs/pull/9982) [`4558fa6`](https://github.com/langchain-ai/langchainjs/commit/4558fa6438749b9f6eca980099241d97c56b1a8f) Thanks [@hntrl](https://github.com/hntrl)! - feat(langchain): add optional `tools` parameter to `countTokensApproximately` for more accurate token estimates when tools are bound to a model
|
|
12
|
+
|
|
13
|
+
- [#9981](https://github.com/langchain-ai/langchainjs/pull/9981) [`5f28338`](https://github.com/langchain-ai/langchainjs/commit/5f283389c0dba1822f37139f0913016d77167734) Thanks [@hntrl](https://github.com/hntrl)! - feat(agents): support returning Command from wrapModelCall middleware
|
|
14
|
+
|
|
15
|
+
Allow `wrapModelCall` middleware hooks to return `Command` objects for advanced
|
|
16
|
+
control flow (routing, state updates), matching the existing `wrapToolCall`
|
|
17
|
+
pattern. The framework tracks the effective AIMessage through the middleware
|
|
18
|
+
chain so outer middleware always receive an AIMessage from `handler()`, even
|
|
19
|
+
when an inner middleware returns a Command.
|
|
20
|
+
|
|
21
|
+
- Updated dependencies [[`d5e3db0`](https://github.com/langchain-ai/langchainjs/commit/d5e3db0d01ab321ec70a875805b2f74aefdadf9d)]:
|
|
22
|
+
- @langchain/core@1.1.21
|
|
23
|
+
|
|
3
24
|
## 1.2.19
|
|
4
25
|
|
|
5
26
|
### Patch Changes
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createMiddleware } from "../middleware.js";
|
|
2
2
|
import { InferInteropZodInput } from "@langchain/core/utils/types";
|
|
3
3
|
import { z } from "zod/v3";
|
|
4
|
-
import * as
|
|
4
|
+
import * as _langchain_core_language_models_base8 from "@langchain/core/language_models/base";
|
|
5
5
|
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
6
6
|
|
|
7
7
|
//#region src/agents/middleware/llmToolSelector.d.ts
|
|
@@ -12,7 +12,7 @@ declare const LLMToolSelectorOptionsSchema: z.ZodObject<{
|
|
|
12
12
|
/**
|
|
13
13
|
* The language model to use for tool selection (default: the provided model from the agent options).
|
|
14
14
|
*/
|
|
15
|
-
model: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<BaseLanguageModel<unknown,
|
|
15
|
+
model: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<BaseLanguageModel<unknown, _langchain_core_language_models_base8.BaseLanguageModelCallOptions>, z.ZodTypeDef, BaseLanguageModel<unknown, _langchain_core_language_models_base8.BaseLanguageModelCallOptions>>]>>;
|
|
16
16
|
/**
|
|
17
17
|
* System prompt for the tool selection model.
|
|
18
18
|
*/
|
|
@@ -28,12 +28,12 @@ declare const LLMToolSelectorOptionsSchema: z.ZodObject<{
|
|
|
28
28
|
*/
|
|
29
29
|
alwaysInclude: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
30
30
|
}, "strip", z.ZodTypeAny, {
|
|
31
|
-
model?: string | BaseLanguageModel<unknown,
|
|
31
|
+
model?: string | BaseLanguageModel<unknown, _langchain_core_language_models_base8.BaseLanguageModelCallOptions> | undefined;
|
|
32
32
|
systemPrompt?: string | undefined;
|
|
33
33
|
maxTools?: number | undefined;
|
|
34
34
|
alwaysInclude?: string[] | undefined;
|
|
35
35
|
}, {
|
|
36
|
-
model?: string | BaseLanguageModel<unknown,
|
|
36
|
+
model?: string | BaseLanguageModel<unknown, _langchain_core_language_models_base8.BaseLanguageModelCallOptions> | undefined;
|
|
37
37
|
systemPrompt?: string | undefined;
|
|
38
38
|
maxTools?: number | undefined;
|
|
39
39
|
alwaysInclude?: string[] | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"llmToolSelector.d.ts","names":["z","BaseLanguageModel","InferInteropZodInput","createMiddleware","LLMToolSelectorOptionsSchema","ZodString","
|
|
1
|
+
{"version":3,"file":"llmToolSelector.d.ts","names":["z","BaseLanguageModel","InferInteropZodInput","createMiddleware","LLMToolSelectorOptionsSchema","ZodString","_langchain_core_language_models_base8","BaseLanguageModelCallOptions","ZodTypeDef","ZodType","ZodUnion","ZodOptional","ZodNumber","ZodArray","ZodTypeAny","ZodObject","LLMToolSelectorConfig","llmToolSelectorMiddleware","ReturnType"],"sources":["../../../src/agents/middleware/llmToolSelector.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\nimport { createMiddleware } from \"../middleware.js\";\n/**\n * Options for configuring the LLM Tool Selector middleware.\n */\nexport declare const LLMToolSelectorOptionsSchema: z.ZodObject<{\n /**\n * The language model to use for tool selection (default: the provided model from the agent options).\n */\n model: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodType<BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>, z.ZodTypeDef, BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>>]>>;\n /**\n * System prompt for the tool selection model.\n */\n systemPrompt: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n */\n maxTools: z.ZodOptional<z.ZodNumber>;\n /**\n * Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n */\n alwaysInclude: z.ZodOptional<z.ZodArray<z.ZodString, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n model?: string | BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n systemPrompt?: string | undefined;\n maxTools?: number | undefined;\n alwaysInclude?: string[] | undefined;\n}, {\n model?: string | BaseLanguageModel<unknown, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n systemPrompt?: string | undefined;\n maxTools?: number | undefined;\n alwaysInclude?: string[] | undefined;\n}>;\nexport type LLMToolSelectorConfig = InferInteropZodInput<typeof LLMToolSelectorOptionsSchema>;\n/**\n * Middleware for selecting tools using an LLM-based strategy.\n *\n * When an agent has many tools available, this middleware filters them down\n * to only the most relevant ones for the user's query. This reduces token usage\n * and helps the main model focus on the right tools.\n *\n * @param options - Configuration options for the middleware\n * @param options.model - The language model to use for tool selection (default: the provided model from the agent options).\n * @param options.systemPrompt - Instructions for the selection model.\n * @param options.maxTools - Maximum number of tools to select. If the model selects more,\n * only the first maxTools will be used. No limit if not specified.\n * @param options.alwaysInclude - Tool names to always include regardless of selection.\n * These do not count against the maxTools limit.\n *\n * @example\n * Limit to 3 tools:\n * ```ts\n * import { llmToolSelectorMiddleware } from \"langchain/agents/middleware\";\n *\n * const middleware = llmToolSelectorMiddleware({ maxTools: 3 });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [tool1, tool2, tool3, tool4, tool5],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example\n * Use a smaller model for selection:\n * ```ts\n * const middleware = llmToolSelectorMiddleware({\n * model: \"openai:gpt-4o-mini\",\n * maxTools: 2\n * });\n * ```\n */\nexport declare function llmToolSelectorMiddleware(options: LLMToolSelectorConfig): ReturnType<typeof createMiddleware>;\n//# sourceMappingURL=llmToolSelector.d.ts.map"],"mappings":";;;;;;;;;;AAOqBI,cAAAA,4BA6BnB,EA7BiDJ,CAAAA,CAAEe,SA6BnD,CAAA;EAzBqCV;;;EAAgIG,KAAAA,EAA5JR,CAAAA,CAAEW,WAA0JH,CAA9IR,CAAAA,CAAEU,QAA4IF,CAAAA,CAAlIR,CAAAA,CAAEK,SAAgIG,EAArHR,CAAAA,CAAES,OAAmHD,CAA3GP,iBAA2GO,CAAAA,OAAAA,EAAvHF,qCAAAA,CAAsFC,4BAAAA,CAA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BAAkBf"}
|
|
@@ -4,7 +4,7 @@ import { BaseMessage } from "@langchain/core/messages";
|
|
|
4
4
|
import * as _langchain_core_tools1 from "@langchain/core/tools";
|
|
5
5
|
import { InferInteropZodInput } from "@langchain/core/utils/types";
|
|
6
6
|
import { z } from "zod/v3";
|
|
7
|
-
import * as
|
|
7
|
+
import * as _langchain_core_language_models_base0 from "@langchain/core/language_models/base";
|
|
8
8
|
import { BaseLanguageModel } from "@langchain/core/language_models/base";
|
|
9
9
|
|
|
10
10
|
//#region src/agents/middleware/summarization.d.ts
|
|
@@ -72,7 +72,7 @@ declare const contextSchema: z.ZodObject<{
|
|
|
72
72
|
/**
|
|
73
73
|
* Model to use for summarization
|
|
74
74
|
*/
|
|
75
|
-
model: z.ZodType<string | BaseLanguageModel<any,
|
|
75
|
+
model: z.ZodType<string | BaseLanguageModel<any, _langchain_core_language_models_base0.BaseLanguageModelCallOptions>, z.ZodTypeDef, string | BaseLanguageModel<any, _langchain_core_language_models_base0.BaseLanguageModelCallOptions>>;
|
|
76
76
|
/**
|
|
77
77
|
* Trigger conditions for summarization.
|
|
78
78
|
* Can be a single condition object (all properties must be met) or an array of conditions (any condition must be met).
|
|
@@ -204,7 +204,7 @@ declare const contextSchema: z.ZodObject<{
|
|
|
204
204
|
*/
|
|
205
205
|
messagesToKeep: z.ZodOptional<z.ZodNumber>;
|
|
206
206
|
}, "strip", z.ZodTypeAny, {
|
|
207
|
-
model: string | BaseLanguageModel<any,
|
|
207
|
+
model: string | BaseLanguageModel<any, _langchain_core_language_models_base0.BaseLanguageModelCallOptions>;
|
|
208
208
|
trigger?: {
|
|
209
209
|
fraction?: number | undefined;
|
|
210
210
|
tokens?: number | undefined;
|
|
@@ -226,7 +226,7 @@ declare const contextSchema: z.ZodObject<{
|
|
|
226
226
|
maxTokensBeforeSummary?: number | undefined;
|
|
227
227
|
messagesToKeep?: number | undefined;
|
|
228
228
|
}, {
|
|
229
|
-
model: string | BaseLanguageModel<any,
|
|
229
|
+
model: string | BaseLanguageModel<any, _langchain_core_language_models_base0.BaseLanguageModelCallOptions>;
|
|
230
230
|
trigger?: {
|
|
231
231
|
fraction?: number | undefined;
|
|
232
232
|
tokens?: number | undefined;
|
|
@@ -389,7 +389,7 @@ declare function summarizationMiddleware(options: SummarizationMiddlewareConfig)
|
|
|
389
389
|
maxTokensBeforeSummary: z.ZodOptional<z.ZodNumber>;
|
|
390
390
|
messagesToKeep: z.ZodOptional<z.ZodNumber>;
|
|
391
391
|
} & {
|
|
392
|
-
model: z.ZodOptional<z.ZodType<BaseLanguageModel<any,
|
|
392
|
+
model: z.ZodOptional<z.ZodType<BaseLanguageModel<any, _langchain_core_language_models_base0.BaseLanguageModelCallOptions>, z.ZodTypeDef, BaseLanguageModel<any, _langchain_core_language_models_base0.BaseLanguageModelCallOptions>>>;
|
|
393
393
|
}, "strip", z.ZodTypeAny, {
|
|
394
394
|
trigger?: {
|
|
395
395
|
fraction?: number | undefined;
|
|
@@ -411,7 +411,7 @@ declare function summarizationMiddleware(options: SummarizationMiddlewareConfig)
|
|
|
411
411
|
summaryPrefix?: string | undefined;
|
|
412
412
|
maxTokensBeforeSummary?: number | undefined;
|
|
413
413
|
messagesToKeep?: number | undefined;
|
|
414
|
-
model?: BaseLanguageModel<any,
|
|
414
|
+
model?: BaseLanguageModel<any, _langchain_core_language_models_base0.BaseLanguageModelCallOptions> | undefined;
|
|
415
415
|
}, {
|
|
416
416
|
trigger?: {
|
|
417
417
|
fraction?: number | undefined;
|
|
@@ -433,7 +433,7 @@ declare function summarizationMiddleware(options: SummarizationMiddlewareConfig)
|
|
|
433
433
|
summaryPrefix?: string | undefined;
|
|
434
434
|
maxTokensBeforeSummary?: number | undefined;
|
|
435
435
|
messagesToKeep?: number | undefined;
|
|
436
|
-
model?: BaseLanguageModel<any,
|
|
436
|
+
model?: BaseLanguageModel<any, _langchain_core_language_models_base0.BaseLanguageModelCallOptions> | undefined;
|
|
437
437
|
}>, {
|
|
438
438
|
trigger?: {
|
|
439
439
|
fraction?: number | undefined;
|
|
@@ -455,7 +455,7 @@ declare function summarizationMiddleware(options: SummarizationMiddlewareConfig)
|
|
|
455
455
|
summaryPrefix?: string | undefined;
|
|
456
456
|
maxTokensBeforeSummary?: number | undefined;
|
|
457
457
|
messagesToKeep?: number | undefined;
|
|
458
|
-
model?: BaseLanguageModel<any,
|
|
458
|
+
model?: BaseLanguageModel<any, _langchain_core_language_models_base0.BaseLanguageModelCallOptions> | undefined;
|
|
459
459
|
}, readonly (_langchain_core_tools1.ServerTool | _langchain_core_tools1.ClientTool)[]>;
|
|
460
460
|
//#endregion
|
|
461
461
|
export { ContextSize, KeepSize, SummarizationMiddlewareConfig, TokenCounter, summarizationMiddleware };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"summarization.d.ts","names":["_langchain_core_messages0","_langchain_core_tools1","__types_js8","z","BaseMessage","BaseLanguageModel","InferInteropZodInput","DEFAULT_SUMMARY_PROMPT","TokenCounter","Promise","contextSizeSchema","ZodNumber","ZodOptional","ZodTypeAny","ZodObject","ZodEffects","ContextSize","infer","keepSchema","KeepSize","contextSchema","_langchain_core_language_models_base3","BaseLanguageModelCallOptions","ZodTypeDef","ZodType","ZodArray","ZodUnion","MessageToolSet","MessageStructure","MessageType","ZodUnknown","ZodTuple","ZodPromise","ZodFunction","ZodString","ZodDefault","SummarizationMiddlewareConfig","getProfileLimits","summarizationMiddleware","ServerTool","ClientTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/summarization.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\nexport declare const DEFAULT_SUMMARY_PROMPT = \"<role>\\nContext Extraction Assistant\\n</role>\\n\\n<primary_objective>\\nYour sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.\\n</primary_objective>\\n\\n<objective_information>\\nYou're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.\\nThis context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.\\n</objective_information>\\n\\n<instructions>\\nThe conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.\\nYou want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.\\n</instructions>\\n\\nThe user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:\\n\\nWith all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.\\nRespond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.\\n\\n<messages>\\nMessages to summarize:\\n{messages}\\n</messages>\";\nexport type TokenCounter = (messages: BaseMessage[]) => number | Promise<number>;\nexport declare const contextSizeSchema: z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of messages to use as the trigger\n */\n messages: z.ZodOptional<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}>;\nexport type ContextSize = z.infer<typeof contextSizeSchema>;\nexport declare const keepSchema: z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to keep\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to keep\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n messages: z.ZodOptional<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}>;\nexport type KeepSize = z.infer<typeof keepSchema>;\ndeclare const contextSchema: z.ZodObject<{\n /**\n * Model to use for summarization\n */\n model: z.ZodType<string | BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>, z.ZodTypeDef, string | BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>>;\n /**\n * Trigger conditions for summarization.\n * Can be a single condition object (all properties must be met) or an array of conditions (any condition must be met).\n *\n * @example\n * ```ts\n * // Single condition: trigger if tokens >= 5000 AND messages >= 3\n * trigger: { tokens: 5000, messages: 3 }\n *\n * // Multiple conditions: trigger if (tokens >= 5000 AND messages >= 3) OR (tokens >= 3000 AND messages >= 6)\n * trigger: [\n * { tokens: 5000, messages: 3 },\n * { tokens: 3000, messages: 6 }\n * ]\n * ```\n */\n trigger: z.ZodOptional<z.ZodUnion<[z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of messages to use as the trigger\n */\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, z.ZodArray<z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of messages to use as the trigger\n */\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, \"many\">]>>;\n /**\n * Keep conditions for summarization\n */\n keep: z.ZodOptional<z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to keep\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to keep\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>>;\n /**\n * Token counter function to use for summarization\n */\n tokenCounter: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodArray<z.ZodType<BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>, z.ZodTypeDef, BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>>, \"many\">], z.ZodUnknown>, z.ZodUnion<[z.ZodNumber, z.ZodPromise<z.ZodNumber>]>>>;\n /**\n * Summary prompt to use for summarization\n * @default {@link DEFAULT_SUMMARY_PROMPT}\n */\n summaryPrompt: z.ZodDefault<z.ZodString>;\n /**\n * Number of tokens to trim to before summarizing\n */\n trimTokensToSummarize: z.ZodOptional<z.ZodNumber>;\n /**\n * Prefix to add to the summary\n */\n summaryPrefix: z.ZodOptional<z.ZodString>;\n /**\n * @deprecated Use `trigger: { tokens: value }` instead.\n */\n maxTokensBeforeSummary: z.ZodOptional<z.ZodNumber>;\n /**\n * @deprecated Use `keep: { messages: value }` instead.\n */\n messagesToKeep: z.ZodOptional<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n model: string | BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>;\n trigger?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }[] | {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n keep?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n tokenCounter?: ((args_0: BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[], ...args: unknown[]) => number | Promise<number>) | undefined;\n summaryPrompt: string;\n trimTokensToSummarize?: number | undefined;\n summaryPrefix?: string | undefined;\n maxTokensBeforeSummary?: number | undefined;\n messagesToKeep?: number | undefined;\n}, {\n model: string | BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>;\n trigger?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }[] | {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n keep?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n tokenCounter?: ((args_0: BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[], ...args: unknown[]) => number | Promise<number>) | undefined;\n summaryPrompt?: string | undefined;\n trimTokensToSummarize?: number | undefined;\n summaryPrefix?: string | undefined;\n maxTokensBeforeSummary?: number | undefined;\n messagesToKeep?: number | undefined;\n}>;\nexport type SummarizationMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n/**\n * Get max input tokens from model profile or fallback to model name lookup\n */\nexport declare function getProfileLimits(input: BaseLanguageModel): number | undefined;\n/**\n * Summarization middleware that automatically summarizes conversation history when token limits are approached.\n *\n * This middleware monitors message token counts and automatically summarizes older\n * messages when a threshold is reached, preserving recent messages and maintaining\n * context continuity by ensuring AI/Tool message pairs remain together.\n *\n * @param options Configuration options for the summarization middleware\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * import { summarizationMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * // Single condition: trigger if tokens >= 4000 AND messages >= 10\n * const agent1 = createAgent({\n * llm: model,\n * tools: [getWeather],\n * middleware: [\n * summarizationMiddleware({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * trigger: { tokens: 4000, messages: 10 },\n * keep: { messages: 20 },\n * })\n * ],\n * });\n *\n * // Multiple conditions: trigger if (tokens >= 5000 AND messages >= 3) OR (tokens >= 3000 AND messages >= 6)\n * const agent2 = createAgent({\n * llm: model,\n * tools: [getWeather],\n * middleware: [\n * summarizationMiddleware({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * trigger: [\n * { tokens: 5000, messages: 3 },\n * { tokens: 3000, messages: 6 },\n * ],\n * keep: { messages: 20 },\n * })\n * ],\n * });\n *\n * ```\n */\nexport declare function summarizationMiddleware(options: SummarizationMiddlewareConfig): import(\"./types.js\").AgentMiddleware<undefined, z.ZodObject<{\n trigger: z.ZodOptional<z.ZodUnion<[z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of messages to use as the trigger\n */\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, z.ZodArray<z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of messages to use as the trigger\n */\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, \"many\">]>>;\n keep: z.ZodOptional<z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to keep\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to keep\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>>;\n tokenCounter: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodArray<z.ZodType<BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>, z.ZodTypeDef, BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>>, \"many\">], z.ZodUnknown>, z.ZodUnion<[z.ZodNumber, z.ZodPromise<z.ZodNumber>]>>>;\n summaryPrompt: z.ZodDefault<z.ZodString>;\n trimTokensToSummarize: z.ZodOptional<z.ZodNumber>;\n summaryPrefix: z.ZodOptional<z.ZodString>;\n maxTokensBeforeSummary: z.ZodOptional<z.ZodNumber>;\n messagesToKeep: z.ZodOptional<z.ZodNumber>;\n} & {\n model: z.ZodOptional<z.ZodType<BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>, z.ZodTypeDef, BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>>>;\n}, \"strip\", z.ZodTypeAny, {\n trigger?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }[] | {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n keep?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n tokenCounter?: ((args_0: BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[], ...args: unknown[]) => number | Promise<number>) | undefined;\n summaryPrompt: string;\n trimTokensToSummarize?: number | undefined;\n summaryPrefix?: string | undefined;\n maxTokensBeforeSummary?: number | undefined;\n messagesToKeep?: number | undefined;\n model?: BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n}, {\n trigger?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }[] | {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n keep?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n tokenCounter?: ((args_0: BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[], ...args: unknown[]) => number | Promise<number>) | undefined;\n summaryPrompt?: string | undefined;\n trimTokensToSummarize?: number | undefined;\n summaryPrefix?: string | undefined;\n maxTokensBeforeSummary?: number | undefined;\n messagesToKeep?: number | undefined;\n model?: BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n}>, {\n trigger?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }[] | {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n keep?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n tokenCounter?: ((args_0: BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[], ...args: unknown[]) => number | Promise<number>) | undefined;\n summaryPrompt: string;\n trimTokensToSummarize?: number | undefined;\n summaryPrefix?: string | undefined;\n maxTokensBeforeSummary?: number | undefined;\n messagesToKeep?: number | undefined;\n model?: BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n}, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\nexport {};\n//# sourceMappingURL=summarization.d.ts.map"],"mappings":";;;;;;;;;;KAKYQ,YAAAA,cAA0BJ,2BAA2BK;cAC5CC,mBAAmBP,CAAAA,CAAEY,WAAWZ,CAAAA,CAAEW;;;;EAD3CN,QAAAA,EAKEL,CAAAA,CAAES,WALQ,CAKIT,CAAAA,CAAEQ,SALQP,CAAAA;EACjBM;;;EAQOC,MAAAA,EAAhBR,CAAAA,CAAES,WAAcD,CAAFR,CAAAA,C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core_tools1","__types_js8","z","BaseMessage","BaseLanguageModel","InferInteropZodInput","DEFAULT_SUMMARY_PROMPT","TokenCounter","Promise","contextSizeSchema","ZodNumber","ZodOptional","ZodTypeAny","ZodObject","ZodEffects","ContextSize","infer","keepSchema","KeepSize","contextSchema","_langchain_core_language_models_base0","BaseLanguageModelCallOptions","ZodTypeDef","ZodType","ZodArray","ZodUnion","MessageToolSet","MessageStructure","MessageType","ZodUnknown","ZodTuple","ZodPromise","ZodFunction","ZodString","ZodDefault","SummarizationMiddlewareConfig","getProfileLimits","summarizationMiddleware","ServerTool","ClientTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/summarization.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport { InferInteropZodInput } from \"@langchain/core/utils/types\";\nexport declare const DEFAULT_SUMMARY_PROMPT = \"<role>\\nContext Extraction Assistant\\n</role>\\n\\n<primary_objective>\\nYour sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.\\n</primary_objective>\\n\\n<objective_information>\\nYou're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.\\nThis context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.\\n</objective_information>\\n\\n<instructions>\\nThe conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.\\nYou want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.\\n</instructions>\\n\\nThe user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:\\n\\nWith all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.\\nRespond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.\\n\\n<messages>\\nMessages to summarize:\\n{messages}\\n</messages>\";\nexport type TokenCounter = (messages: BaseMessage[]) => number | Promise<number>;\nexport declare const contextSizeSchema: z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of messages to use as the trigger\n */\n messages: z.ZodOptional<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}>;\nexport type ContextSize = z.infer<typeof contextSizeSchema>;\nexport declare const keepSchema: z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to keep\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to keep\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n messages: z.ZodOptional<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n}>;\nexport type KeepSize = z.infer<typeof keepSchema>;\ndeclare const contextSchema: z.ZodObject<{\n /**\n * Model to use for summarization\n */\n model: z.ZodType<string | BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>, z.ZodTypeDef, string | BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>>;\n /**\n * Trigger conditions for summarization.\n * Can be a single condition object (all properties must be met) or an array of conditions (any condition must be met).\n *\n * @example\n * ```ts\n * // Single condition: trigger if tokens >= 5000 AND messages >= 3\n * trigger: { tokens: 5000, messages: 3 }\n *\n * // Multiple conditions: trigger if (tokens >= 5000 AND messages >= 3) OR (tokens >= 3000 AND messages >= 6)\n * trigger: [\n * { tokens: 5000, messages: 3 },\n * { tokens: 3000, messages: 6 }\n * ]\n * ```\n */\n trigger: z.ZodOptional<z.ZodUnion<[z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of messages to use as the trigger\n */\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, z.ZodArray<z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of messages to use as the trigger\n */\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, \"many\">]>>;\n /**\n * Keep conditions for summarization\n */\n keep: z.ZodOptional<z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to keep\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to keep\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>>;\n /**\n * Token counter function to use for summarization\n */\n tokenCounter: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodArray<z.ZodType<BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>, z.ZodTypeDef, BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>>, \"many\">], z.ZodUnknown>, z.ZodUnion<[z.ZodNumber, z.ZodPromise<z.ZodNumber>]>>>;\n /**\n * Summary prompt to use for summarization\n * @default {@link DEFAULT_SUMMARY_PROMPT}\n */\n summaryPrompt: z.ZodDefault<z.ZodString>;\n /**\n * Number of tokens to trim to before summarizing\n */\n trimTokensToSummarize: z.ZodOptional<z.ZodNumber>;\n /**\n * Prefix to add to the summary\n */\n summaryPrefix: z.ZodOptional<z.ZodString>;\n /**\n * @deprecated Use `trigger: { tokens: value }` instead.\n */\n maxTokensBeforeSummary: z.ZodOptional<z.ZodNumber>;\n /**\n * @deprecated Use `keep: { messages: value }` instead.\n */\n messagesToKeep: z.ZodOptional<z.ZodNumber>;\n}, \"strip\", z.ZodTypeAny, {\n model: string | BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>;\n trigger?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }[] | {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n keep?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n tokenCounter?: ((args_0: BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[], ...args: unknown[]) => number | Promise<number>) | undefined;\n summaryPrompt: string;\n trimTokensToSummarize?: number | undefined;\n summaryPrefix?: string | undefined;\n maxTokensBeforeSummary?: number | undefined;\n messagesToKeep?: number | undefined;\n}, {\n model: string | BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>;\n trigger?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }[] | {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n keep?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n tokenCounter?: ((args_0: BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[], ...args: unknown[]) => number | Promise<number>) | undefined;\n summaryPrompt?: string | undefined;\n trimTokensToSummarize?: number | undefined;\n summaryPrefix?: string | undefined;\n maxTokensBeforeSummary?: number | undefined;\n messagesToKeep?: number | undefined;\n}>;\nexport type SummarizationMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n/**\n * Get max input tokens from model profile or fallback to model name lookup\n */\nexport declare function getProfileLimits(input: BaseLanguageModel): number | undefined;\n/**\n * Summarization middleware that automatically summarizes conversation history when token limits are approached.\n *\n * This middleware monitors message token counts and automatically summarizes older\n * messages when a threshold is reached, preserving recent messages and maintaining\n * context continuity by ensuring AI/Tool message pairs remain together.\n *\n * @param options Configuration options for the summarization middleware\n * @returns A middleware instance\n *\n * @example\n * ```ts\n * import { summarizationMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * // Single condition: trigger if tokens >= 4000 AND messages >= 10\n * const agent1 = createAgent({\n * llm: model,\n * tools: [getWeather],\n * middleware: [\n * summarizationMiddleware({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * trigger: { tokens: 4000, messages: 10 },\n * keep: { messages: 20 },\n * })\n * ],\n * });\n *\n * // Multiple conditions: trigger if (tokens >= 5000 AND messages >= 3) OR (tokens >= 3000 AND messages >= 6)\n * const agent2 = createAgent({\n * llm: model,\n * tools: [getWeather],\n * middleware: [\n * summarizationMiddleware({\n * model: new ChatOpenAI({ model: \"gpt-4o\" }),\n * trigger: [\n * { tokens: 5000, messages: 3 },\n * { tokens: 3000, messages: 6 },\n * ],\n * keep: { messages: 20 },\n * })\n * ],\n * });\n *\n * ```\n */\nexport declare function summarizationMiddleware(options: SummarizationMiddlewareConfig): import(\"./types.js\").AgentMiddleware<undefined, z.ZodObject<{\n trigger: z.ZodOptional<z.ZodUnion<[z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of messages to use as the trigger\n */\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, z.ZodArray<z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of messages to use as the trigger\n */\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, \"many\">]>>;\n keep: z.ZodOptional<z.ZodEffects<z.ZodObject<{\n /**\n * Fraction of the model's context size to keep\n */\n fraction: z.ZodOptional<z.ZodNumber>;\n /**\n * Number of tokens to keep\n */\n tokens: z.ZodOptional<z.ZodNumber>;\n messages: z.ZodOptional<z.ZodNumber>;\n }, \"strip\", z.ZodTypeAny, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }, {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }>>;\n tokenCounter: z.ZodOptional<z.ZodFunction<z.ZodTuple<[z.ZodArray<z.ZodType<BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>, z.ZodTypeDef, BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>>, \"many\">], z.ZodUnknown>, z.ZodUnion<[z.ZodNumber, z.ZodPromise<z.ZodNumber>]>>>;\n summaryPrompt: z.ZodDefault<z.ZodString>;\n trimTokensToSummarize: z.ZodOptional<z.ZodNumber>;\n summaryPrefix: z.ZodOptional<z.ZodString>;\n maxTokensBeforeSummary: z.ZodOptional<z.ZodNumber>;\n messagesToKeep: z.ZodOptional<z.ZodNumber>;\n} & {\n model: z.ZodOptional<z.ZodType<BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>, z.ZodTypeDef, BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions>>>;\n}, \"strip\", z.ZodTypeAny, {\n trigger?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }[] | {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n keep?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n tokenCounter?: ((args_0: BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[], ...args: unknown[]) => number | Promise<number>) | undefined;\n summaryPrompt: string;\n trimTokensToSummarize?: number | undefined;\n summaryPrefix?: string | undefined;\n maxTokensBeforeSummary?: number | undefined;\n messagesToKeep?: number | undefined;\n model?: BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n}, {\n trigger?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }[] | {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n keep?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n tokenCounter?: ((args_0: BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[], ...args: unknown[]) => number | Promise<number>) | undefined;\n summaryPrompt?: string | undefined;\n trimTokensToSummarize?: number | undefined;\n summaryPrefix?: string | undefined;\n maxTokensBeforeSummary?: number | undefined;\n messagesToKeep?: number | undefined;\n model?: BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n}>, {\n trigger?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n }[] | {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n keep?: {\n fraction?: number | undefined;\n tokens?: number | undefined;\n messages?: number | undefined;\n } | undefined;\n tokenCounter?: ((args_0: BaseMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>, import(\"@langchain/core/messages\").MessageType>[], ...args: unknown[]) => number | Promise<number>) | undefined;\n summaryPrompt: string;\n trimTokensToSummarize?: number | undefined;\n summaryPrefix?: string | undefined;\n maxTokensBeforeSummary?: number | undefined;\n messagesToKeep?: number | undefined;\n model?: BaseLanguageModel<any, import(\"@langchain/core/language_models/base\").BaseLanguageModelCallOptions> | undefined;\n}, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\nexport {};\n//# sourceMappingURL=summarization.d.ts.map"],"mappings":";;;;;;;;;;KAKYQ,YAAAA,cAA0BJ,2BAA2BK;cAC5CC,mBAAmBP,CAAAA,CAAEY,WAAWZ,CAAAA,CAAEW;;;;EAD3CN,QAAAA,EAKEL,CAAAA,CAAES,WALQ,CAKIT,CAAAA,CAAEQ,SALQP,CAAAA;EACjBM;;;EAQOC,MAAAA,EAAhBR,CAAAA,CAAES,WAAcD,CAAFR,CAAAA,CAAEQ,SAAAA,CAAAA;EAAdC;;;EAKAC,QAAAA,EADAV,CAAAA,CAAES,WACFC,CADcV,CAAAA,CAAEQ,SAChBE,CAAAA;CAbuCV,EAAEW,OAAAA,EAa3CX,CAAAA,CAAEU,UAbyCC,EAAAA;EAAbC,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAU,MAAA,CAAA,EAAA,MAAA,GAAA,SAAA;EA8BxCC,QAAAA,CAAAA,EAAAA,MAAW,GAAA,SAAkBN;AACzC,CAAA,EAAA;EAI8BC,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAdC,MAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAIYD,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;CAAhBR,CAAAA,EAAES;EACgBD,QAAAA,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;YAChNnB,CAAAA,CAAEU;;;;;;;;;;;;;;;2BAeeT,YAAiHJ,yBAAAA,CAAlE4B,iBAfpD5B,yBAAAA,CAewG2B,cAAAA,GAApC3B,yBAAAA,CAAwF6B,WAAAA,qCAAgDpB;;;;;;UAMxNJ,uBAN+NgB,qCAAAA,CAMzJC,4BAAAA;;;;;;;;;;;;;;;;2BAgBrDlB,YAAiHJ,yBAAAA,CAAlE4B,iBAhB/C5B,yBAAAA,CAgBmG2B,cAAAA,GAApC3B,yBAAAA,CAAwF6B,WAAAA,qCAAgDpB;;;;;;UAMxNJ,uBAN+NgB,qCAAAA,CAMzJC,4BAAAA;;;;;;;;;;;;;;;;2BAgBrDlB,YAAiHJ,yBAAAA,CAAlE4B,iBA1JwE5B,yBAAAA,CA0JpB2B,cAAAA,GAApC3B,yBAAAA,CAAwF6B,WAAAA,qCAAgDpB;;;;;;UAMxNJ,uBAN+NgB,qCAAAA,CAMzJC,4BAAAA;aAArDrB,sBAAAA,CACgBsC,UAAAA,GAAUtC,sBAAAA,CAAmCuC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","names":["MIDDLEWARE_BRAND: unique symbol"],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type {\n AnnotationRoot,\n StateSchema,\n InferStateSchemaUpdate,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\nimport type {\n AIMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n\n/**\n * Type bag that encapsulates all middleware type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the middleware system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TSchema - The middleware state schema type. Can be a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) or `undefined`.\n *\n * @typeParam TContextSchema - The middleware context schema type. Can be an `InteropZodObject`,\n * `InteropZodDefault`, `InteropZodOptional`, or `undefined`.\n *\n * @typeParam TFullContext - The full context type available to middleware hooks.\n *\n * @typeParam TTools - The tools array type registered by the middleware.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyMiddlewareTypes = MiddlewareTypeConfig<\n * typeof myStateSchema,\n * typeof myContextSchema,\n * MyContextType,\n * typeof myTools\n * >;\n * ```\n */\nexport interface MiddlewareTypeConfig<\n TSchema extends StateDefinitionInit | undefined =\n | StateDefinitionInit\n | undefined,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined =\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /** The middleware state schema type */\n Schema: TSchema;\n /** The middleware context schema type */\n ContextSchema: TContextSchema;\n /** The full context type */\n FullContext: TFullContext;\n /** The tools array type */\n Tools: TTools;\n}\n\n/**\n * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\n\nexport type NormalizedSchemaInput<\n TSchema extends StateDefinitionInit | undefined | never = any,\n> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaInput<TSchema> & AgentBuiltInState\n : AgentBuiltInState;\n\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> =\n | (TState & {\n jumpTo?: JumpToTarget;\n })\n | void;\n\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown,\n> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n *\n * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<\n TSchema extends Record<string, unknown> = AgentBuiltInState,\n TContext = unknown,\n> = (\n request: ToolCallRequest<TSchema, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: Omit<\n ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n /**\n * allow to reset the system prompt or system message\n */\n \"systemPrompt\" | \"systemMessage\"\n > & { systemPrompt?: string; systemMessage?: SystemMessage }\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport const MIDDLEWARE_BRAND: unique symbol = Symbol(\"AgentMiddleware\");\n\n/**\n * Base middleware interface.\n *\n * @typeParam TSchema - The middleware state schema type\n * @typeParam TContextSchema - The middleware context schema type\n * @typeParam TFullContext - The full context type available to hooks\n * @typeParam TTools - The tools array type registered by the middleware\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"myMiddleware\",\n * stateSchema: z.object({ count: z.number() }),\n * tools: [myTool],\n * });\n * ```\n */\nexport interface AgentMiddleware<\n TSchema extends StateDefinitionInit | undefined = any,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined = any,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /**\n * Brand property to distinguish middleware instances from plain objects or functions.\n * This is required and prevents accidental assignment of functions to middleware arrays.\n */\n readonly [MIDDLEWARE_BRAND]: true;\n\n /**\n * Type marker for extracting the MiddlewareTypeConfig from a middleware instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n readonly \"~middlewareTypes\"?: MiddlewareTypeConfig<\n TSchema,\n TContextSchema,\n TFullContext,\n TTools\n >;\n\n /**\n * The name of the middleware.\n */\n name: string;\n\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n\n/**\n * Helper type to resolve a MiddlewareTypeConfig from either:\n * - A MiddlewareTypeConfig directly\n * - An AgentMiddleware instance (using `typeof middleware`)\n */\nexport type ResolveMiddlewareTypeConfig<T> = T extends {\n \"~middlewareTypes\"?: infer Types;\n}\n ? Types extends MiddlewareTypeConfig\n ? Types\n : never\n : T extends MiddlewareTypeConfig\n ? T\n : never;\n\n/**\n * Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.\n *\n * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from\n * @typeParam K - The property key to extract (\"Schema\" | \"ContextSchema\" | \"FullContext\" | \"Tools\")\n */\nexport type InferMiddlewareType<\n T,\n K extends keyof MiddlewareTypeConfig,\n> = ResolveMiddlewareTypeConfig<T>[K];\n\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<\n T,\n \"ContextSchema\"\n>;\n\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<\n T,\n \"FullContext\"\n>;\n\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\n\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> =\n T extends AnyAnnotationRoot\n ? ToAnnotationRoot<T>[\"State\"]\n : T extends InteropZodObject\n ? InferInteropZodInput<T>\n : {};\n\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodOutput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodInput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareState<First> & InferMiddlewareStates<Rest>\n : InferMiddlewareState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest>\n : InferMiddlewareInputState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareInputStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodOptional<infer Inner>\n ? InferInteropZodInput<Inner> | undefined\n : TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest>\n : InferMiddlewareContext<First>\n : {}\n : {};\n\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined]\n ? [B] extends [undefined]\n ? undefined\n : B | undefined\n : [B] extends [undefined]\n ? A | undefined\n : [A] extends [B]\n ? A\n : [B] extends [A]\n ? B\n : A & B;\n\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? MergeContextTypes<\n InferMiddlewareContextInput<First>,\n InferMiddlewareContextInputs<Rest>\n >\n : InferMiddlewareContextInput<First>\n : {}\n : {};\n\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n> = ContextSchema extends InteropZodObject\n ? InferInteropZodInput<ContextSchema>\n : ContextSchema extends AnyAnnotationRoot\n ? ToAnnotationRoot<ContextSchema>[\"State\"]\n : {};\n\nexport type ToAnnotationRoot<A extends StateDefinitionInit> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? InteropZodToStateDefinition<A>\n : never;\n\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields>\n : A extends InteropZodObject\n ? InferInteropZodOutput<A>\n : A extends AnyAnnotationRoot\n ? A[\"State\"]\n : {};\n"],"mappings":";;;;;;;AAmVA,MAAaA,mBAAkC,OAAO,kBAAkB"}
|
|
1
|
+
{"version":3,"file":"types.cjs","names":["MIDDLEWARE_BRAND: unique symbol"],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type {\n AnnotationRoot,\n StateSchema,\n InferStateSchemaUpdate,\n StateDefinitionInit,\n} from \"@langchain/langgraph\";\nimport type {\n AIMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n\n/**\n * Type bag that encapsulates all middleware type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the middleware system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TSchema - The middleware state schema type. Can be a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) or `undefined`.\n *\n * @typeParam TContextSchema - The middleware context schema type. Can be an `InteropZodObject`,\n * `InteropZodDefault`, `InteropZodOptional`, or `undefined`.\n *\n * @typeParam TFullContext - The full context type available to middleware hooks.\n *\n * @typeParam TTools - The tools array type registered by the middleware.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyMiddlewareTypes = MiddlewareTypeConfig<\n * typeof myStateSchema,\n * typeof myContextSchema,\n * MyContextType,\n * typeof myTools\n * >;\n * ```\n */\nexport interface MiddlewareTypeConfig<\n TSchema extends StateDefinitionInit | undefined =\n | StateDefinitionInit\n | undefined,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined =\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /** The middleware state schema type */\n Schema: TSchema;\n /** The middleware context schema type */\n ContextSchema: TContextSchema;\n /** The full context type */\n FullContext: TFullContext;\n /** The tools array type */\n Tools: TTools;\n}\n\n/**\n * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\n\nexport type NormalizedSchemaInput<\n TSchema extends StateDefinitionInit | undefined | never = any,\n> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaInput<TSchema> & AgentBuiltInState\n : AgentBuiltInState;\n\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> =\n | (TState & {\n jumpTo?: JumpToTarget;\n })\n | void;\n\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown,\n> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n *\n * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<\n TSchema extends Record<string, unknown> = AgentBuiltInState,\n TContext = unknown,\n> = (\n request: ToolCallRequest<TSchema, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: Omit<\n ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n /**\n * allow to reset the system prompt or system message\n */\n \"systemPrompt\" | \"systemMessage\"\n > & { systemPrompt?: string; systemMessage?: SystemMessage }\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage | Command>;\n\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<\n TSchema extends StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> =\n | AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport const MIDDLEWARE_BRAND: unique symbol = Symbol(\"AgentMiddleware\");\n\n/**\n * Base middleware interface.\n *\n * @typeParam TSchema - The middleware state schema type\n * @typeParam TContextSchema - The middleware context schema type\n * @typeParam TFullContext - The full context type available to hooks\n * @typeParam TTools - The tools array type registered by the middleware\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"myMiddleware\",\n * stateSchema: z.object({ count: z.number() }),\n * tools: [myTool],\n * });\n * ```\n */\nexport interface AgentMiddleware<\n TSchema extends StateDefinitionInit | undefined = any,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined = any,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[],\n> {\n /**\n * Brand property to distinguish middleware instances from plain objects or functions.\n * This is required and prevents accidental assignment of functions to middleware arrays.\n */\n readonly [MIDDLEWARE_BRAND]: true;\n\n /**\n * Type marker for extracting the MiddlewareTypeConfig from a middleware instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n readonly \"~middlewareTypes\"?: MiddlewareTypeConfig<\n TSchema,\n TContextSchema,\n TFullContext,\n TTools\n >;\n\n /**\n * The name of the middleware.\n */\n name: string;\n\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\n\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n\n/**\n * Helper type to resolve a MiddlewareTypeConfig from either:\n * - A MiddlewareTypeConfig directly\n * - An AgentMiddleware instance (using `typeof middleware`)\n */\nexport type ResolveMiddlewareTypeConfig<T> = T extends {\n \"~middlewareTypes\"?: infer Types;\n}\n ? Types extends MiddlewareTypeConfig\n ? Types\n : never\n : T extends MiddlewareTypeConfig\n ? T\n : never;\n\n/**\n * Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.\n *\n * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from\n * @typeParam K - The property key to extract (\"Schema\" | \"ContextSchema\" | \"FullContext\" | \"Tools\")\n */\nexport type InferMiddlewareType<\n T,\n K extends keyof MiddlewareTypeConfig,\n> = ResolveMiddlewareTypeConfig<T>[K];\n\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<\n T,\n \"ContextSchema\"\n>;\n\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<\n T,\n \"FullContext\"\n>;\n\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\n\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> =\n T extends AnyAnnotationRoot\n ? ToAnnotationRoot<T>[\"State\"]\n : T extends InteropZodObject\n ? InferInteropZodInput<T>\n : {};\n\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodOutput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodInput<TSchema>>\n : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareState<First> & InferMiddlewareStates<Rest>\n : InferMiddlewareState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest>\n : InferMiddlewareInputState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareInputStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodOptional<infer Inner>\n ? InferInteropZodInput<Inner> | undefined\n : TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest>\n : InferMiddlewareContext<First>\n : {}\n : {};\n\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined]\n ? [B] extends [undefined]\n ? undefined\n : B | undefined\n : [B] extends [undefined]\n ? A | undefined\n : [A] extends [B]\n ? A\n : [B] extends [A]\n ? B\n : A & B;\n\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? MergeContextTypes<\n InferMiddlewareContextInput<First>,\n InferMiddlewareContextInputs<Rest>\n >\n : InferMiddlewareContextInput<First>\n : {}\n : {};\n\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n> = ContextSchema extends InteropZodObject\n ? InferInteropZodInput<ContextSchema>\n : ContextSchema extends AnyAnnotationRoot\n ? ToAnnotationRoot<ContextSchema>[\"State\"]\n : {};\n\nexport type ToAnnotationRoot<A extends StateDefinitionInit> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? InteropZodToStateDefinition<A>\n : never;\n\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields>\n : A extends InteropZodObject\n ? InferInteropZodOutput<A>\n : A extends AnyAnnotationRoot\n ? A[\"State\"]\n : {};\n"],"mappings":";;;;;;;AAmVA,MAAaA,mBAAkC,OAAO,kBAAkB"}
|
|
@@ -138,7 +138,7 @@ type WrapModelCallHandler<TSchema$1 extends StateDefinitionInit | undefined = un
|
|
|
138
138
|
* @param handler - The function that invokes the model. Call this with a ModelRequest to get the response
|
|
139
139
|
* @returns The AI message response from the model (or a modified version)
|
|
140
140
|
*/
|
|
141
|
-
type WrapModelCallHook<TSchema$1 extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ModelRequest<NormalizedSchemaInput<TSchema$1>, TContext>, handler: WrapModelCallHandler<TSchema$1, TContext>) => PromiseOrValue<AIMessage>;
|
|
141
|
+
type WrapModelCallHook<TSchema$1 extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ModelRequest<NormalizedSchemaInput<TSchema$1>, TContext>, handler: WrapModelCallHandler<TSchema$1, TContext>) => PromiseOrValue<AIMessage | Command>;
|
|
142
142
|
/**
|
|
143
143
|
* Handler function type for the beforeAgent hook.
|
|
144
144
|
* Called once at the start of agent invocation before any model calls or tool executions.
|