langchain 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/agents/ReactAgent.cjs +15 -17
  3. package/dist/agents/ReactAgent.cjs.map +1 -1
  4. package/dist/agents/ReactAgent.d.cts +3 -3
  5. package/dist/agents/ReactAgent.d.cts.map +1 -1
  6. package/dist/agents/ReactAgent.d.ts +3 -3
  7. package/dist/agents/ReactAgent.d.ts.map +1 -1
  8. package/dist/agents/ReactAgent.js +15 -17
  9. package/dist/agents/ReactAgent.js.map +1 -1
  10. package/dist/agents/middleware/contextEditing.cjs +302 -33
  11. package/dist/agents/middleware/contextEditing.cjs.map +1 -1
  12. package/dist/agents/middleware/contextEditing.d.cts +125 -41
  13. package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
  14. package/dist/agents/middleware/contextEditing.d.ts +125 -41
  15. package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
  16. package/dist/agents/middleware/contextEditing.js +302 -33
  17. package/dist/agents/middleware/contextEditing.js.map +1 -1
  18. package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
  19. package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
  20. package/dist/agents/middleware/hitl.d.cts.map +1 -1
  21. package/dist/agents/middleware/hitl.d.ts.map +1 -1
  22. package/dist/agents/middleware/index.cjs +2 -0
  23. package/dist/agents/middleware/index.js +2 -0
  24. package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
  25. package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
  26. package/dist/agents/middleware/modelCallLimit.cjs +6 -2
  27. package/dist/agents/middleware/modelCallLimit.cjs.map +1 -1
  28. package/dist/agents/middleware/modelCallLimit.d.cts +8 -8
  29. package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
  30. package/dist/agents/middleware/modelCallLimit.d.ts +8 -8
  31. package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
  32. package/dist/agents/middleware/modelCallLimit.js +6 -2
  33. package/dist/agents/middleware/modelCallLimit.js.map +1 -1
  34. package/dist/agents/middleware/modelFallback.cjs +2 -2
  35. package/dist/agents/middleware/modelFallback.cjs.map +1 -1
  36. package/dist/agents/middleware/modelFallback.d.cts +2 -2
  37. package/dist/agents/middleware/modelFallback.d.cts.map +1 -1
  38. package/dist/agents/middleware/modelFallback.d.ts +2 -2
  39. package/dist/agents/middleware/modelFallback.d.ts.map +1 -1
  40. package/dist/agents/middleware/modelFallback.js +2 -2
  41. package/dist/agents/middleware/modelFallback.js.map +1 -1
  42. package/dist/agents/middleware/pii.cjs +445 -0
  43. package/dist/agents/middleware/pii.cjs.map +1 -0
  44. package/dist/agents/middleware/pii.d.cts +216 -0
  45. package/dist/agents/middleware/pii.d.cts.map +1 -0
  46. package/dist/agents/middleware/pii.d.ts +216 -0
  47. package/dist/agents/middleware/pii.d.ts.map +1 -0
  48. package/dist/agents/middleware/pii.js +436 -0
  49. package/dist/agents/middleware/pii.js.map +1 -0
  50. package/dist/agents/middleware/piiRedaction.cjs +2 -1
  51. package/dist/agents/middleware/piiRedaction.cjs.map +1 -1
  52. package/dist/agents/middleware/piiRedaction.d.cts +4 -1
  53. package/dist/agents/middleware/piiRedaction.d.cts.map +1 -1
  54. package/dist/agents/middleware/piiRedaction.d.ts +4 -1
  55. package/dist/agents/middleware/piiRedaction.d.ts.map +1 -1
  56. package/dist/agents/middleware/piiRedaction.js +2 -1
  57. package/dist/agents/middleware/piiRedaction.js.map +1 -1
  58. package/dist/agents/middleware/promptCaching.d.cts.map +1 -1
  59. package/dist/agents/middleware/promptCaching.d.ts.map +1 -1
  60. package/dist/agents/middleware/summarization.cjs +15 -24
  61. package/dist/agents/middleware/summarization.cjs.map +1 -1
  62. package/dist/agents/middleware/summarization.d.cts +72 -9
  63. package/dist/agents/middleware/summarization.d.cts.map +1 -1
  64. package/dist/agents/middleware/summarization.d.ts +65 -2
  65. package/dist/agents/middleware/summarization.d.ts.map +1 -1
  66. package/dist/agents/middleware/summarization.js +13 -25
  67. package/dist/agents/middleware/summarization.js.map +1 -1
  68. package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
  69. package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
  70. package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
  71. package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
  72. package/dist/agents/middleware/toolEmulator.cjs +118 -0
  73. package/dist/agents/middleware/toolEmulator.cjs.map +1 -0
  74. package/dist/agents/middleware/toolEmulator.d.cts +76 -0
  75. package/dist/agents/middleware/toolEmulator.d.cts.map +1 -0
  76. package/dist/agents/middleware/toolEmulator.d.ts +76 -0
  77. package/dist/agents/middleware/toolEmulator.d.ts.map +1 -0
  78. package/dist/agents/middleware/toolEmulator.js +117 -0
  79. package/dist/agents/middleware/toolEmulator.js.map +1 -0
  80. package/dist/agents/middleware/types.d.cts.map +1 -1
  81. package/dist/agents/middleware/types.d.ts.map +1 -1
  82. package/dist/agents/middleware/utils.cjs +4 -0
  83. package/dist/agents/middleware/utils.cjs.map +1 -1
  84. package/dist/agents/middleware/utils.d.cts.map +1 -1
  85. package/dist/agents/middleware/utils.d.ts.map +1 -1
  86. package/dist/agents/middleware/utils.js +4 -0
  87. package/dist/agents/middleware/utils.js.map +1 -1
  88. package/dist/agents/nodes/AgentNode.cjs +1 -1
  89. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  90. package/dist/agents/nodes/AgentNode.js +1 -1
  91. package/dist/agents/nodes/AgentNode.js.map +1 -1
  92. package/dist/agents/runtime.d.cts +5 -5
  93. package/dist/agents/runtime.d.cts.map +1 -1
  94. package/dist/agents/runtime.d.ts +5 -5
  95. package/dist/agents/runtime.d.ts.map +1 -1
  96. package/dist/index.cjs +22 -0
  97. package/dist/index.d.cts +5 -3
  98. package/dist/index.d.ts +5 -3
  99. package/dist/index.js +13 -1
  100. package/package.json +9 -8
@@ -1 +1 @@
1
- {"version":3,"file":"summarization.js","names":["model: BaseLanguageModel","options: SummarizationMiddlewareConfig","z4","trigger: ContextSize | ContextSize[] | undefined","keep: ContextSize","triggerConditions: ContextSize[]","uuid","messages: BaseMessage[]","systemPrompt: SystemMessage | undefined","conversationMessages: BaseMessage[]","cutoffIndex: number","totalTokens: number","tokenCounter: TokenCounter","targetTokenCount: number","messagesToKeep: number","aiMessage: AIMessage","aiMessageIndex: number","toolCallIds: Set<string>","messagesToSummarize: BaseMessage[]","summaryPrompt: string","trimTokensToSummarize: number | undefined"],"sources":["../../../src/agents/middleware/summarization.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4 } from \"zod/v4\";\nimport { v4 as uuid } from \"uuid\";\nimport {\n BaseMessage,\n AIMessage,\n SystemMessage,\n ToolMessage,\n RemoveMessage,\n trimMessages,\n HumanMessage,\n} from \"@langchain/core/messages\";\nimport {\n BaseLanguageModel,\n getModelContextSize,\n} from \"@langchain/core/language_models/base\";\nimport {\n interopSafeParse,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport { REMOVE_ALL_MESSAGES } from \"@langchain/langgraph\";\nimport { createMiddleware } from \"../middleware.js\";\nimport { countTokensApproximately } from \"./utils.js\";\nimport { hasToolCalls } from \"../utils.js\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\n\nexport 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>`;\n\nconst DEFAULT_MESSAGES_TO_KEEP = 20;\nconst DEFAULT_TRIM_TOKEN_LIMIT = 4000;\nconst DEFAULT_FALLBACK_MESSAGE_COUNT = 15;\nconst SEARCH_RANGE_FOR_TOOL_PAIRS = 5;\n\nconst tokenCounterSchema = z\n .function()\n .args(z.array(z.custom<BaseMessage>()))\n .returns(z.union([z.number(), z.promise(z.number())]));\nexport type TokenCounter = (\n messages: BaseMessage[]\n) => number | Promise<number>;\n\nconst contextSizeSchema = z\n .object({\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z\n .number()\n .gt(0, \"Fraction must be greater than 0\")\n .max(1, \"Fraction must be less than or equal to 1\")\n .optional(),\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.number().positive(\"Tokens must be greater than 0\").optional(),\n /**\n * Number of messages to use as the trigger\n */\n messages: z\n .number()\n .int(\"Messages must be an integer\")\n .positive(\"Messages must be greater than 0\")\n .optional(),\n })\n .refine(\n (data) => {\n const count = [data.fraction, data.tokens, data.messages].filter(\n (v) => v !== undefined\n ).length;\n return count >= 1;\n },\n {\n message: \"At least one of fraction, tokens, or messages must be provided\",\n }\n );\nexport type ContextSize = z.infer<typeof contextSizeSchema>;\n\nconst keepSchema = z\n .object({\n /**\n * Fraction of the model's context size to keep\n */\n fraction: z\n .number()\n .gt(0, \"Fraction must be greater than 0\")\n .max(1, \"Fraction must be less than or equal to 1\")\n .optional(),\n /**\n * Number of tokens to keep\n */\n tokens: z.number().positive(\"Tokens must be greater than 0\").optional(),\n messages: z\n .number()\n .int(\"Messages must be an integer\")\n .positive(\"Messages must be greater than 0\")\n .optional(),\n })\n .refine(\n (data) => {\n const count = [data.fraction, data.tokens, data.messages].filter(\n (v) => v !== undefined\n ).length;\n return count === 1;\n },\n {\n message: \"Exactly one of fraction, tokens, or messages must be provided\",\n }\n );\n\nconst contextSchema = z.object({\n /**\n * Model to use for summarization\n */\n model: z.custom<string | BaseLanguageModel>(),\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.union([contextSizeSchema, z.array(contextSizeSchema)]).optional(),\n /**\n * Keep conditions for summarization\n */\n keep: keepSchema.optional(),\n /**\n * Token counter function to use for summarization\n */\n tokenCounter: tokenCounterSchema.optional(),\n /**\n * Summary prompt to use for summarization\n * @default {@link DEFAULT_SUMMARY_PROMPT}\n */\n summaryPrompt: z.string().default(DEFAULT_SUMMARY_PROMPT),\n /**\n * Number of tokens to trim to before summarizing\n */\n trimTokensToSummarize: z.number().optional(),\n /**\n * Prefix to add to the summary\n */\n summaryPrefix: z.string().optional(),\n /**\n * @deprecated Use `trigger: { tokens: value }` instead.\n */\n maxTokensBeforeSummary: z.number().optional(),\n /**\n * @deprecated Use `keep: { messages: value }` instead.\n */\n messagesToKeep: z.number().optional(),\n});\n\nexport type SummarizationMiddlewareConfig = InferInteropZodInput<\n typeof contextSchema\n>;\n\n/**\n * Get max input tokens from model profile or fallback to model name lookup\n */\nfunction getProfileLimits(model: BaseLanguageModel): number | undefined {\n try {\n /**\n * Try to access profile property (for future compatibility with model-profiles)\n */\n const modelWithProfile = model as BaseLanguageModel & {\n profile?: { max_input_tokens?: number };\n };\n if (\n modelWithProfile.profile &&\n typeof modelWithProfile.profile.max_input_tokens === \"number\"\n ) {\n return modelWithProfile.profile.max_input_tokens;\n }\n } catch {\n /**\n * Profile not available, continue to fallback\n */\n }\n\n /**\n * Fallback: try to get model name and use getModelContextSize\n */\n try {\n const modelWithName = model as BaseLanguageModel & {\n model?: string;\n modelName?: string;\n };\n const modelName = modelWithName.model || modelWithName.modelName;\n if (typeof modelName === \"string\") {\n return getModelContextSize(modelName);\n }\n } catch {\n /**\n * Model name not available\n */\n }\n\n return undefined;\n}\n\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 function summarizationMiddleware(\n options: SummarizationMiddlewareConfig\n) {\n /**\n * Parse user options to get their explicit values\n */\n const { data: userOptions, error } = interopSafeParse(contextSchema, options);\n if (error) {\n throw new Error(\n `Invalid summarization middleware options: ${z4.prettifyError(error)}`\n );\n }\n\n return createMiddleware({\n name: \"SummarizationMiddleware\",\n contextSchema: contextSchema.extend({\n /**\n * `model` should be required when initializing the middleware,\n * but can be omitted within context when invoking the middleware.\n */\n model: z.custom<BaseLanguageModel>().optional(),\n }),\n beforeModel: async (state, runtime) => {\n let trigger: ContextSize | ContextSize[] | undefined =\n userOptions.trigger;\n let keep: ContextSize = userOptions.keep as InferInteropZodOutput<\n typeof keepSchema\n >;\n\n /**\n * Handle deprecated parameters\n */\n if (userOptions.maxTokensBeforeSummary !== undefined) {\n console.warn(\n \"maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead.\"\n );\n if (trigger === undefined) {\n trigger = { tokens: userOptions.maxTokensBeforeSummary };\n }\n }\n\n /**\n * Handle deprecated parameters\n */\n if (userOptions.messagesToKeep !== undefined) {\n console.warn(\n \"messagesToKeep is deprecated. Use `keep: { messages: value }` instead.\"\n );\n if (\n !keep ||\n (keep &&\n \"messages\" in keep &&\n keep.messages === DEFAULT_MESSAGES_TO_KEEP)\n ) {\n keep = { messages: userOptions.messagesToKeep };\n }\n }\n\n /**\n * Merge context with user options\n */\n const resolvedTrigger =\n runtime.context.trigger !== undefined\n ? runtime.context.trigger\n : trigger;\n const resolvedKeep =\n runtime.context.keep !== undefined\n ? runtime.context.keep\n : keep ?? { messages: DEFAULT_MESSAGES_TO_KEEP };\n\n const validatedKeep = keepSchema.parse(resolvedKeep);\n\n /**\n * Validate trigger conditions\n */\n let triggerConditions: ContextSize[] = [];\n if (resolvedTrigger === undefined) {\n triggerConditions = [];\n } else if (Array.isArray(resolvedTrigger)) {\n /**\n * It's an array of ContextSize objects\n */\n triggerConditions = (resolvedTrigger as ContextSize[]).map((t) =>\n contextSizeSchema.parse(t)\n );\n } else {\n /**\n * Single ContextSize object - all properties must be satisfied (AND logic)\n */\n triggerConditions = [contextSizeSchema.parse(resolvedTrigger)];\n }\n\n /**\n * Check if profile is required\n */\n const requiresProfile =\n triggerConditions.some((c) => \"fraction\" in c) ||\n \"fraction\" in validatedKeep;\n\n const model =\n typeof userOptions.model === \"string\"\n ? await initChatModel(userOptions.model)\n : userOptions.model;\n\n if (requiresProfile && !getProfileLimits(model)) {\n throw new Error(\n \"Model profile information is required to use fractional token limits. \" +\n \"Use absolute token counts instead.\"\n );\n }\n\n const summaryPrompt =\n runtime.context.summaryPrompt === DEFAULT_SUMMARY_PROMPT\n ? userOptions.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT\n : runtime.context.summaryPrompt ??\n userOptions.summaryPrompt ??\n DEFAULT_SUMMARY_PROMPT;\n const trimTokensToSummarize =\n runtime.context.trimTokensToSummarize !== undefined\n ? runtime.context.trimTokensToSummarize\n : userOptions.trimTokensToSummarize ?? DEFAULT_TRIM_TOKEN_LIMIT;\n\n /**\n * Ensure all messages have IDs\n */\n ensureMessageIds(state.messages);\n\n const tokenCounter =\n runtime.context.tokenCounter !== undefined\n ? runtime.context.tokenCounter\n : userOptions.tokenCounter ?? countTokensApproximately;\n const totalTokens = await tokenCounter(state.messages);\n const doSummarize = await shouldSummarize(\n state.messages,\n totalTokens,\n triggerConditions,\n model\n );\n\n if (!doSummarize) {\n return;\n }\n\n const { systemPrompt, conversationMessages } = splitSystemMessage(\n state.messages\n );\n const cutoffIndex = await determineCutoffIndex(\n conversationMessages,\n validatedKeep,\n tokenCounter,\n model\n );\n\n if (cutoffIndex <= 0) {\n return;\n }\n\n const { messagesToSummarize, preservedMessages } = partitionMessages(\n systemPrompt,\n conversationMessages,\n cutoffIndex\n );\n\n const summary = await createSummary(\n messagesToSummarize,\n model,\n summaryPrompt,\n tokenCounter,\n trimTokensToSummarize\n );\n\n const summaryMessage = new HumanMessage({\n content: `Here is a summary of the conversation to date:\\n\\n${summary}`,\n id: uuid(),\n });\n\n return {\n messages: [\n new RemoveMessage({ id: REMOVE_ALL_MESSAGES }),\n summaryMessage,\n ...preservedMessages,\n ],\n };\n },\n });\n}\n\n/**\n * Ensure all messages have unique IDs\n */\nfunction ensureMessageIds(messages: BaseMessage[]): void {\n for (const msg of messages) {\n if (!msg.id) {\n msg.id = uuid();\n }\n }\n}\n\n/**\n * Separate system message from conversation messages\n */\nfunction splitSystemMessage(messages: BaseMessage[]): {\n systemPrompt?: SystemMessage;\n conversationMessages: BaseMessage[];\n} {\n if (messages.length > 0 && SystemMessage.isInstance(messages[0])) {\n return {\n systemPrompt: messages[0] as SystemMessage,\n conversationMessages: messages.slice(1),\n };\n }\n return {\n conversationMessages: messages,\n };\n}\n\n/**\n * Partition messages into those to summarize and those to preserve\n */\nfunction partitionMessages(\n systemPrompt: SystemMessage | undefined,\n conversationMessages: BaseMessage[],\n cutoffIndex: number\n): { messagesToSummarize: BaseMessage[]; preservedMessages: BaseMessage[] } {\n const messagesToSummarize = conversationMessages.slice(0, cutoffIndex);\n const preservedMessages = conversationMessages.slice(cutoffIndex);\n\n // Include system message in messages to summarize to capture previous summaries\n if (systemPrompt) {\n messagesToSummarize.unshift(systemPrompt);\n }\n\n return { messagesToSummarize, preservedMessages };\n}\n\n/**\n * Determine whether summarization should run for the current token usage\n *\n * @param messages - Current messages in the conversation\n * @param totalTokens - Total token count for all messages\n * @param triggerConditions - Array of trigger conditions. Returns true if ANY condition is satisfied (OR logic).\n * Within each condition, ALL specified properties must be satisfied (AND logic).\n * @param model - The language model being used\n * @returns true if summarization should be triggered\n */\nasync function shouldSummarize(\n messages: BaseMessage[],\n totalTokens: number,\n triggerConditions: ContextSize[],\n model: BaseLanguageModel\n): Promise<boolean> {\n if (triggerConditions.length === 0) {\n return false;\n }\n\n /**\n * Check each condition (OR logic between conditions)\n */\n for (const trigger of triggerConditions) {\n /**\n * Within a single condition, all specified properties must be satisfied (AND logic)\n */\n let conditionMet = true;\n let hasAnyProperty = false;\n\n if (trigger.messages !== undefined) {\n hasAnyProperty = true;\n if (messages.length < trigger.messages) {\n conditionMet = false;\n }\n }\n\n if (trigger.tokens !== undefined) {\n hasAnyProperty = true;\n if (totalTokens < trigger.tokens) {\n conditionMet = false;\n }\n }\n\n if (trigger.fraction !== undefined) {\n hasAnyProperty = true;\n const maxInputTokens = getProfileLimits(model);\n if (typeof maxInputTokens === \"number\") {\n const threshold = Math.floor(maxInputTokens * trigger.fraction);\n if (totalTokens < threshold) {\n conditionMet = false;\n }\n } else {\n /**\n * If fraction is specified but we can't get model limits, skip this condition\n */\n conditionMet = false;\n }\n }\n\n /**\n * If condition has at least one property and all properties are satisfied, trigger summarization\n */\n if (hasAnyProperty && conditionMet) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Determine cutoff index respecting retention configuration\n */\nasync function determineCutoffIndex(\n messages: BaseMessage[],\n keep: ContextSize,\n tokenCounter: TokenCounter,\n model: BaseLanguageModel\n): Promise<number> {\n if (\"tokens\" in keep || \"fraction\" in keep) {\n const tokenBasedCutoff = await findTokenBasedCutoff(\n messages,\n keep,\n tokenCounter,\n model\n );\n if (typeof tokenBasedCutoff === \"number\") {\n return tokenBasedCutoff;\n }\n /**\n * Fallback to message count if token-based fails\n */\n return findSafeCutoff(messages, DEFAULT_MESSAGES_TO_KEEP);\n }\n /**\n * find cutoff index based on message count\n */\n return findSafeCutoff(messages, keep.messages ?? DEFAULT_MESSAGES_TO_KEEP);\n}\n\n/**\n * Find cutoff index based on target token retention\n */\nasync function findTokenBasedCutoff(\n messages: BaseMessage[],\n keep: ContextSize,\n tokenCounter: TokenCounter,\n model: BaseLanguageModel\n): Promise<number | undefined> {\n if (messages.length === 0) {\n return 0;\n }\n\n let targetTokenCount: number;\n\n if (\"fraction\" in keep && keep.fraction !== undefined) {\n const maxInputTokens = getProfileLimits(model);\n if (typeof maxInputTokens !== \"number\") {\n return;\n }\n targetTokenCount = Math.floor(maxInputTokens * keep.fraction);\n } else if (\"tokens\" in keep && keep.tokens !== undefined) {\n targetTokenCount = Math.floor(keep.tokens);\n } else {\n return;\n }\n\n if (targetTokenCount <= 0) {\n targetTokenCount = 1;\n }\n\n const totalTokens = await tokenCounter(messages);\n if (totalTokens <= targetTokenCount) {\n return 0;\n }\n\n /**\n * Use binary search to identify the earliest message index that keeps the\n * suffix within the token budget.\n */\n let left = 0;\n let right = messages.length;\n let cutoffCandidate = messages.length;\n const maxIterations = Math.floor(Math.log2(messages.length)) + 1;\n\n for (let i = 0; i < maxIterations; i++) {\n if (left >= right) {\n break;\n }\n\n const mid = Math.floor((left + right) / 2);\n const suffixTokens = await tokenCounter(messages.slice(mid));\n if (suffixTokens <= targetTokenCount) {\n cutoffCandidate = mid;\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n\n if (cutoffCandidate === messages.length) {\n cutoffCandidate = left;\n }\n\n if (cutoffCandidate >= messages.length) {\n if (messages.length === 1) {\n return 0;\n }\n cutoffCandidate = messages.length - 1;\n }\n\n /**\n * Find safe cutoff point that preserves tool pairs\n */\n for (let i = cutoffCandidate; i >= 0; i--) {\n if (isSafeCutoffPoint(messages, i)) {\n return i;\n }\n }\n\n return 0;\n}\n\n/**\n * Find safe cutoff point that preserves AI/Tool message pairs\n */\nfunction findSafeCutoff(\n messages: BaseMessage[],\n messagesToKeep: number\n): number {\n if (messages.length <= messagesToKeep) {\n return 0;\n }\n\n const targetCutoff = messages.length - messagesToKeep;\n\n for (let i = targetCutoff; i >= 0; i--) {\n if (isSafeCutoffPoint(messages, i)) {\n return i;\n }\n }\n\n return 0;\n}\n\n/**\n * Check if cutting at index would separate AI/Tool message pairs\n */\nfunction isSafeCutoffPoint(\n messages: BaseMessage[],\n cutoffIndex: number\n): boolean {\n if (cutoffIndex >= messages.length) {\n return true;\n }\n\n /**\n * Prevent preserved messages from starting with AI message containing tool calls\n */\n if (\n cutoffIndex < messages.length &&\n AIMessage.isInstance(messages[cutoffIndex]) &&\n hasToolCalls(messages[cutoffIndex])\n ) {\n return false;\n }\n\n const searchStart = Math.max(0, cutoffIndex - SEARCH_RANGE_FOR_TOOL_PAIRS);\n const searchEnd = Math.min(\n messages.length,\n cutoffIndex + SEARCH_RANGE_FOR_TOOL_PAIRS\n );\n\n for (let i = searchStart; i < searchEnd; i++) {\n if (!hasToolCalls(messages[i])) {\n continue;\n }\n\n const toolCallIds = extractToolCallIds(messages[i] as AIMessage);\n if (cutoffSeparatesToolPair(messages, i, cutoffIndex, toolCallIds)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Extract tool call IDs from an AI message\n */\nfunction extractToolCallIds(aiMessage: AIMessage): Set<string> {\n const toolCallIds = new Set<string>();\n if (aiMessage.tool_calls) {\n for (const toolCall of aiMessage.tool_calls) {\n const id =\n typeof toolCall === \"object\" && \"id\" in toolCall ? toolCall.id : null;\n if (id) {\n toolCallIds.add(id);\n }\n }\n }\n return toolCallIds;\n}\n\n/**\n * Check if cutoff separates an AI message from its corresponding tool messages\n */\nfunction cutoffSeparatesToolPair(\n messages: BaseMessage[],\n aiMessageIndex: number,\n cutoffIndex: number,\n toolCallIds: Set<string>\n): boolean {\n for (let j = aiMessageIndex + 1; j < messages.length; j++) {\n const message = messages[j];\n if (\n ToolMessage.isInstance(message) &&\n toolCallIds.has(message.tool_call_id)\n ) {\n const aiBeforeCutoff = aiMessageIndex < cutoffIndex;\n const toolBeforeCutoff = j < cutoffIndex;\n if (aiBeforeCutoff !== toolBeforeCutoff) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Generate summary for the given messages\n */\nasync function createSummary(\n messagesToSummarize: BaseMessage[],\n model: BaseLanguageModel,\n summaryPrompt: string,\n tokenCounter: TokenCounter,\n trimTokensToSummarize: number | undefined\n): Promise<string> {\n if (!messagesToSummarize.length) {\n return \"No previous conversation history.\";\n }\n\n const trimmedMessages = await trimMessagesForSummary(\n messagesToSummarize,\n tokenCounter,\n trimTokensToSummarize\n );\n\n if (!trimmedMessages.length) {\n return \"Previous conversation was too long to summarize.\";\n }\n\n try {\n const formattedPrompt = summaryPrompt.replace(\n \"{messages}\",\n JSON.stringify(trimmedMessages, null, 2)\n );\n const response = await model.invoke(formattedPrompt);\n const content = response.content;\n /**\n * Handle both string content and MessageContent array\n */\n if (typeof content === \"string\") {\n return content.trim();\n } else if (Array.isArray(content)) {\n /**\n * Extract text from MessageContent array\n */\n const textContent = content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (typeof item === \"object\" && item !== null && \"text\" in item) {\n return (item as { text: string }).text;\n }\n return \"\";\n })\n .join(\"\");\n return textContent.trim();\n }\n return \"Error generating summary: Invalid response format\";\n } catch (e) {\n return `Error generating summary: ${e}`;\n }\n}\n\n/**\n * Trim messages to fit within summary generation limits\n */\nasync function trimMessagesForSummary(\n messages: BaseMessage[],\n tokenCounter: TokenCounter,\n trimTokensToSummarize: number | undefined\n): Promise<BaseMessage[]> {\n if (trimTokensToSummarize === undefined) {\n return messages;\n }\n\n try {\n return await trimMessages(messages, {\n maxTokens: trimTokensToSummarize,\n tokenCounter: async (msgs) => tokenCounter(msgs),\n strategy: \"last\",\n allowPartial: true,\n includeSystem: true,\n });\n } catch {\n /**\n * Fallback to last N messages if trimming fails\n */\n return messages.slice(-DEFAULT_FALLBACK_MESSAGE_COUNT);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,MAAa,yBAAyB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;WA0B5B,CAAC;AAEZ,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,iCAAiC;AACvC,MAAM,8BAA8B;AAEpC,MAAM,qBAAqB,EACxB,UAAU,CACV,KAAK,EAAE,MAAM,EAAE,QAAqB,CAAC,CAAC,CACtC,QAAQ,EAAE,MAAM,CAAC,EAAE,QAAQ,EAAE,EAAE,QAAQ,EAAE,QAAQ,CAAC,AAAC,EAAC,CAAC;AAKxD,MAAM,oBAAoB,EACvB,OAAO;CAIN,UAAU,EACP,QAAQ,CACR,GAAG,GAAG,kCAAkC,CACxC,IAAI,GAAG,2CAA2C,CAClD,UAAU;CAIb,QAAQ,EAAE,QAAQ,CAAC,SAAS,gCAAgC,CAAC,UAAU;CAIvE,UAAU,EACP,QAAQ,CACR,IAAI,8BAA8B,CAClC,SAAS,kCAAkC,CAC3C,UAAU;AACd,EAA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,OACAmB,eACAP,cACAQ,uBACiB;AACjB,KAAI,CAAC,oBAAoB,OACvB,QAAO;CAGT,MAAM,kBAAkB,MAAM,uBAC5B,qBACA,cACA,sBACD;AAED,KAAI,CAAC,gBAAgB,OACnB,QAAO;AAGT,KAAI;EACF,MAAM,kBAAkB,cAAc,QACpC,cACA,KAAK,UAAU,iBAAiB,MAAM,EAAE,CACzC;EACD,MAAM,WAAW,MAAM,MAAM,OAAO,gBAAgB;EACpD,MAAM,UAAU,SAAS;;;;AAIzB,MAAI,OAAO,YAAY,SACrB,QAAO,QAAQ,MAAM;WACZ,MAAM,QAAQ,QAAQ,EAAE;;;;GAIjC,MAAM,cAAc,QACjB,IAAI,CAAC,SAAS;AACb,QAAI,OAAO,SAAS,SAAU,QAAO;AACrC,QAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,UAAU,KACzD,QAAQ,KAA0B;AAEpC,WAAO;GACR,EAAC,CACD,KAAK,GAAG;AACX,UAAO,YAAY,MAAM;EAC1B;AACD,SAAO;CACR,SAAQ,GAAG;AACV,SAAO,CAAC,0BAA0B,EAAE,GAAG;CACxC;AACF;;;;AAKD,eAAe,uBACbb,UACAK,cACAQ,uBACwB;AACxB,KAAI,0BAA0B,OAC5B,QAAO;AAGT,KAAI;AACF,SAAO,MAAM,aAAa,UAAU;GAClC,WAAW;GACX,cAAc,OAAO,SAAS,aAAa,KAAK;GAChD,UAAU;GACV,cAAc;GACd,eAAe;EAChB,EAAC;CACH,QAAO;;;;AAIN,SAAO,SAAS,MAAM,CAAC,+BAA+B;CACvD;AACF"}
1
+ {"version":3,"file":"summarization.js","names":["input: BaseLanguageModel","options: SummarizationMiddlewareConfig","z4","trigger: ContextSize | ContextSize[] | undefined","keep: ContextSize","triggerConditions: ContextSize[]","uuid","messages: BaseMessage[]","systemPrompt: SystemMessage | undefined","conversationMessages: BaseMessage[]","cutoffIndex: number","totalTokens: number","model: BaseLanguageModel","tokenCounter: TokenCounter","targetTokenCount: number","messagesToKeep: number","aiMessage: AIMessage","aiMessageIndex: number","toolCallIds: Set<string>","messagesToSummarize: BaseMessage[]","summaryPrompt: string","trimTokensToSummarize: number | undefined"],"sources":["../../../src/agents/middleware/summarization.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { z as z4 } from \"zod/v4\";\nimport { v4 as uuid } from \"uuid\";\nimport {\n BaseMessage,\n AIMessage,\n SystemMessage,\n ToolMessage,\n RemoveMessage,\n trimMessages,\n HumanMessage,\n} from \"@langchain/core/messages\";\nimport {\n BaseLanguageModel,\n getModelContextSize,\n} from \"@langchain/core/language_models/base\";\nimport {\n interopSafeParse,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport { REMOVE_ALL_MESSAGES } from \"@langchain/langgraph\";\nimport { createMiddleware } from \"../middleware.js\";\nimport { countTokensApproximately } from \"./utils.js\";\nimport { hasToolCalls } from \"../utils.js\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\n\nexport 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>`;\n\nconst DEFAULT_MESSAGES_TO_KEEP = 20;\nconst DEFAULT_TRIM_TOKEN_LIMIT = 4000;\nconst DEFAULT_FALLBACK_MESSAGE_COUNT = 15;\nconst SEARCH_RANGE_FOR_TOOL_PAIRS = 5;\n\nconst tokenCounterSchema = z\n .function()\n .args(z.array(z.custom<BaseMessage>()))\n .returns(z.union([z.number(), z.promise(z.number())]));\nexport type TokenCounter = (\n messages: BaseMessage[]\n) => number | Promise<number>;\n\nexport const contextSizeSchema = z\n .object({\n /**\n * Fraction of the model's context size to use as the trigger\n */\n fraction: z\n .number()\n .gt(0, \"Fraction must be greater than 0\")\n .max(1, \"Fraction must be less than or equal to 1\")\n .optional(),\n /**\n * Number of tokens to use as the trigger\n */\n tokens: z.number().positive(\"Tokens must be greater than 0\").optional(),\n /**\n * Number of messages to use as the trigger\n */\n messages: z\n .number()\n .int(\"Messages must be an integer\")\n .positive(\"Messages must be greater than 0\")\n .optional(),\n })\n .refine(\n (data) => {\n const count = [data.fraction, data.tokens, data.messages].filter(\n (v) => v !== undefined\n ).length;\n return count >= 1;\n },\n {\n message: \"At least one of fraction, tokens, or messages must be provided\",\n }\n );\nexport type ContextSize = z.infer<typeof contextSizeSchema>;\n\nexport const keepSchema = z\n .object({\n /**\n * Fraction of the model's context size to keep\n */\n fraction: z\n .number()\n .min(0, \"Messages must be non-negative\")\n .max(1, \"Fraction must be less than or equal to 1\")\n .optional(),\n /**\n * Number of tokens to keep\n */\n tokens: z\n .number()\n .min(0, \"Tokens must be greater than or equal to 0\")\n .optional(),\n messages: z\n .number()\n .int(\"Messages must be an integer\")\n .min(0, \"Messages must be non-negative\")\n .optional(),\n })\n .refine(\n (data) => {\n const count = [data.fraction, data.tokens, data.messages].filter(\n (v) => v !== undefined\n ).length;\n return count === 1;\n },\n {\n message: \"Exactly one of fraction, tokens, or messages must be provided\",\n }\n );\nexport type KeepSize = z.infer<typeof keepSchema>;\n\nconst contextSchema = z.object({\n /**\n * Model to use for summarization\n */\n model: z.custom<string | BaseLanguageModel>(),\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.union([contextSizeSchema, z.array(contextSizeSchema)]).optional(),\n /**\n * Keep conditions for summarization\n */\n keep: keepSchema.optional(),\n /**\n * Token counter function to use for summarization\n */\n tokenCounter: tokenCounterSchema.optional(),\n /**\n * Summary prompt to use for summarization\n * @default {@link DEFAULT_SUMMARY_PROMPT}\n */\n summaryPrompt: z.string().default(DEFAULT_SUMMARY_PROMPT),\n /**\n * Number of tokens to trim to before summarizing\n */\n trimTokensToSummarize: z.number().optional(),\n /**\n * Prefix to add to the summary\n */\n summaryPrefix: z.string().optional(),\n /**\n * @deprecated Use `trigger: { tokens: value }` instead.\n */\n maxTokensBeforeSummary: z.number().optional(),\n /**\n * @deprecated Use `keep: { messages: value }` instead.\n */\n messagesToKeep: z.number().optional(),\n});\n\nexport type SummarizationMiddlewareConfig = InferInteropZodInput<\n typeof contextSchema\n>;\n\n/**\n * Get max input tokens from model profile or fallback to model name lookup\n */\nexport function getProfileLimits(input: BaseLanguageModel): number | undefined {\n // Access maxInputTokens on the model profile directly if available\n if (\n \"profile\" in input &&\n typeof input.profile === \"object\" &&\n input.profile &&\n \"maxInputTokens\" in input.profile &&\n (typeof input.profile.maxInputTokens === \"number\" ||\n input.profile.maxInputTokens == null)\n ) {\n return input.profile.maxInputTokens ?? undefined;\n }\n\n // Fallback to using model name if available\n if (\"model\" in input && typeof input.model === \"string\") {\n return getModelContextSize(input.model);\n }\n if (\"modelName\" in input && typeof input.modelName === \"string\") {\n return getModelContextSize(input.modelName);\n }\n\n return undefined;\n}\n\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 function summarizationMiddleware(\n options: SummarizationMiddlewareConfig\n) {\n /**\n * Parse user options to get their explicit values\n */\n const { data: userOptions, error } = interopSafeParse(contextSchema, options);\n if (error) {\n throw new Error(\n `Invalid summarization middleware options: ${z4.prettifyError(error)}`\n );\n }\n\n return createMiddleware({\n name: \"SummarizationMiddleware\",\n contextSchema: contextSchema.extend({\n /**\n * `model` should be required when initializing the middleware,\n * but can be omitted within context when invoking the middleware.\n */\n model: z.custom<BaseLanguageModel>().optional(),\n }),\n beforeModel: async (state, runtime) => {\n let trigger: ContextSize | ContextSize[] | undefined =\n userOptions.trigger;\n let keep: ContextSize = userOptions.keep as InferInteropZodOutput<\n typeof keepSchema\n >;\n\n /**\n * Handle deprecated parameters\n */\n if (userOptions.maxTokensBeforeSummary !== undefined) {\n console.warn(\n \"maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead.\"\n );\n if (trigger === undefined) {\n trigger = { tokens: userOptions.maxTokensBeforeSummary };\n }\n }\n\n /**\n * Handle deprecated parameters\n */\n if (userOptions.messagesToKeep !== undefined) {\n console.warn(\n \"messagesToKeep is deprecated. Use `keep: { messages: value }` instead.\"\n );\n if (\n !keep ||\n (keep &&\n \"messages\" in keep &&\n keep.messages === DEFAULT_MESSAGES_TO_KEEP)\n ) {\n keep = { messages: userOptions.messagesToKeep };\n }\n }\n\n /**\n * Merge context with user options\n */\n const resolvedTrigger =\n runtime.context?.trigger !== undefined\n ? runtime.context.trigger\n : trigger;\n const resolvedKeep =\n runtime.context?.keep !== undefined\n ? runtime.context.keep\n : keep ?? { messages: DEFAULT_MESSAGES_TO_KEEP };\n\n const validatedKeep = keepSchema.parse(resolvedKeep);\n\n /**\n * Validate trigger conditions\n */\n let triggerConditions: ContextSize[] = [];\n if (resolvedTrigger === undefined) {\n triggerConditions = [];\n } else if (Array.isArray(resolvedTrigger)) {\n /**\n * It's an array of ContextSize objects\n */\n triggerConditions = (resolvedTrigger as ContextSize[]).map((t) =>\n contextSizeSchema.parse(t)\n );\n } else {\n /**\n * Single ContextSize object - all properties must be satisfied (AND logic)\n */\n triggerConditions = [contextSizeSchema.parse(resolvedTrigger)];\n }\n\n /**\n * Check if profile is required\n */\n const requiresProfile =\n triggerConditions.some((c) => \"fraction\" in c) ||\n \"fraction\" in validatedKeep;\n\n const model =\n typeof userOptions.model === \"string\"\n ? await initChatModel(userOptions.model)\n : userOptions.model;\n\n if (requiresProfile && !getProfileLimits(model)) {\n throw new Error(\n \"Model profile information is required to use fractional token limits. \" +\n \"Use absolute token counts instead.\"\n );\n }\n\n const summaryPrompt =\n runtime.context?.summaryPrompt === DEFAULT_SUMMARY_PROMPT\n ? userOptions.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT\n : runtime.context?.summaryPrompt ??\n userOptions.summaryPrompt ??\n DEFAULT_SUMMARY_PROMPT;\n const trimTokensToSummarize =\n runtime.context?.trimTokensToSummarize !== undefined\n ? runtime.context.trimTokensToSummarize\n : userOptions.trimTokensToSummarize ?? DEFAULT_TRIM_TOKEN_LIMIT;\n\n /**\n * Ensure all messages have IDs\n */\n ensureMessageIds(state.messages);\n\n const tokenCounter =\n runtime.context?.tokenCounter !== undefined\n ? runtime.context.tokenCounter\n : userOptions.tokenCounter ?? countTokensApproximately;\n const totalTokens = await tokenCounter(state.messages);\n const doSummarize = await shouldSummarize(\n state.messages,\n totalTokens,\n triggerConditions,\n model\n );\n\n if (!doSummarize) {\n return;\n }\n\n const { systemPrompt, conversationMessages } = splitSystemMessage(\n state.messages\n );\n const cutoffIndex = await determineCutoffIndex(\n conversationMessages,\n validatedKeep,\n tokenCounter,\n model\n );\n\n if (cutoffIndex <= 0) {\n return;\n }\n\n const { messagesToSummarize, preservedMessages } = partitionMessages(\n systemPrompt,\n conversationMessages,\n cutoffIndex\n );\n\n const summary = await createSummary(\n messagesToSummarize,\n model,\n summaryPrompt,\n tokenCounter,\n trimTokensToSummarize\n );\n\n const summaryMessage = new HumanMessage({\n content: `Here is a summary of the conversation to date:\\n\\n${summary}`,\n id: uuid(),\n });\n\n return {\n messages: [\n new RemoveMessage({ id: REMOVE_ALL_MESSAGES }),\n summaryMessage,\n ...preservedMessages,\n ],\n };\n },\n });\n}\n\n/**\n * Ensure all messages have unique IDs\n */\nfunction ensureMessageIds(messages: BaseMessage[]): void {\n for (const msg of messages) {\n if (!msg.id) {\n msg.id = uuid();\n }\n }\n}\n\n/**\n * Separate system message from conversation messages\n */\nfunction splitSystemMessage(messages: BaseMessage[]): {\n systemPrompt?: SystemMessage;\n conversationMessages: BaseMessage[];\n} {\n if (messages.length > 0 && SystemMessage.isInstance(messages[0])) {\n return {\n systemPrompt: messages[0] as SystemMessage,\n conversationMessages: messages.slice(1),\n };\n }\n return {\n conversationMessages: messages,\n };\n}\n\n/**\n * Partition messages into those to summarize and those to preserve\n */\nfunction partitionMessages(\n systemPrompt: SystemMessage | undefined,\n conversationMessages: BaseMessage[],\n cutoffIndex: number\n): { messagesToSummarize: BaseMessage[]; preservedMessages: BaseMessage[] } {\n const messagesToSummarize = conversationMessages.slice(0, cutoffIndex);\n const preservedMessages = conversationMessages.slice(cutoffIndex);\n\n // Include system message in messages to summarize to capture previous summaries\n if (systemPrompt) {\n messagesToSummarize.unshift(systemPrompt);\n }\n\n return { messagesToSummarize, preservedMessages };\n}\n\n/**\n * Determine whether summarization should run for the current token usage\n *\n * @param messages - Current messages in the conversation\n * @param totalTokens - Total token count for all messages\n * @param triggerConditions - Array of trigger conditions. Returns true if ANY condition is satisfied (OR logic).\n * Within each condition, ALL specified properties must be satisfied (AND logic).\n * @param model - The language model being used\n * @returns true if summarization should be triggered\n */\nasync function shouldSummarize(\n messages: BaseMessage[],\n totalTokens: number,\n triggerConditions: ContextSize[],\n model: BaseLanguageModel\n): Promise<boolean> {\n if (triggerConditions.length === 0) {\n return false;\n }\n\n /**\n * Check each condition (OR logic between conditions)\n */\n for (const trigger of triggerConditions) {\n /**\n * Within a single condition, all specified properties must be satisfied (AND logic)\n */\n let conditionMet = true;\n let hasAnyProperty = false;\n\n if (trigger.messages !== undefined) {\n hasAnyProperty = true;\n if (messages.length < trigger.messages) {\n conditionMet = false;\n }\n }\n\n if (trigger.tokens !== undefined) {\n hasAnyProperty = true;\n if (totalTokens < trigger.tokens) {\n conditionMet = false;\n }\n }\n\n if (trigger.fraction !== undefined) {\n hasAnyProperty = true;\n const maxInputTokens = getProfileLimits(model);\n if (typeof maxInputTokens === \"number\") {\n const threshold = Math.floor(maxInputTokens * trigger.fraction);\n if (totalTokens < threshold) {\n conditionMet = false;\n }\n } else {\n /**\n * If fraction is specified but we can't get model limits, skip this condition\n */\n conditionMet = false;\n }\n }\n\n /**\n * If condition has at least one property and all properties are satisfied, trigger summarization\n */\n if (hasAnyProperty && conditionMet) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Determine cutoff index respecting retention configuration\n */\nasync function determineCutoffIndex(\n messages: BaseMessage[],\n keep: ContextSize,\n tokenCounter: TokenCounter,\n model: BaseLanguageModel\n): Promise<number> {\n if (\"tokens\" in keep || \"fraction\" in keep) {\n const tokenBasedCutoff = await findTokenBasedCutoff(\n messages,\n keep,\n tokenCounter,\n model\n );\n if (typeof tokenBasedCutoff === \"number\") {\n return tokenBasedCutoff;\n }\n /**\n * Fallback to message count if token-based fails\n */\n return findSafeCutoff(messages, DEFAULT_MESSAGES_TO_KEEP);\n }\n /**\n * find cutoff index based on message count\n */\n return findSafeCutoff(messages, keep.messages ?? DEFAULT_MESSAGES_TO_KEEP);\n}\n\n/**\n * Find cutoff index based on target token retention\n */\nasync function findTokenBasedCutoff(\n messages: BaseMessage[],\n keep: ContextSize,\n tokenCounter: TokenCounter,\n model: BaseLanguageModel\n): Promise<number | undefined> {\n if (messages.length === 0) {\n return 0;\n }\n\n let targetTokenCount: number;\n\n if (\"fraction\" in keep && keep.fraction !== undefined) {\n const maxInputTokens = getProfileLimits(model);\n if (typeof maxInputTokens !== \"number\") {\n return;\n }\n targetTokenCount = Math.floor(maxInputTokens * keep.fraction);\n } else if (\"tokens\" in keep && keep.tokens !== undefined) {\n targetTokenCount = Math.floor(keep.tokens);\n } else {\n return;\n }\n\n if (targetTokenCount <= 0) {\n targetTokenCount = 1;\n }\n\n const totalTokens = await tokenCounter(messages);\n if (totalTokens <= targetTokenCount) {\n return 0;\n }\n\n /**\n * Use binary search to identify the earliest message index that keeps the\n * suffix within the token budget.\n */\n let left = 0;\n let right = messages.length;\n let cutoffCandidate = messages.length;\n const maxIterations = Math.floor(Math.log2(messages.length)) + 1;\n\n for (let i = 0; i < maxIterations; i++) {\n if (left >= right) {\n break;\n }\n\n const mid = Math.floor((left + right) / 2);\n const suffixTokens = await tokenCounter(messages.slice(mid));\n if (suffixTokens <= targetTokenCount) {\n cutoffCandidate = mid;\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n\n if (cutoffCandidate === messages.length) {\n cutoffCandidate = left;\n }\n\n if (cutoffCandidate >= messages.length) {\n if (messages.length === 1) {\n return 0;\n }\n cutoffCandidate = messages.length - 1;\n }\n\n /**\n * Find safe cutoff point that preserves tool pairs\n */\n for (let i = cutoffCandidate; i >= 0; i--) {\n if (isSafeCutoffPoint(messages, i)) {\n return i;\n }\n }\n\n return 0;\n}\n\n/**\n * Find safe cutoff point that preserves AI/Tool message pairs\n */\nfunction findSafeCutoff(\n messages: BaseMessage[],\n messagesToKeep: number\n): number {\n if (messages.length <= messagesToKeep) {\n return 0;\n }\n\n const targetCutoff = messages.length - messagesToKeep;\n\n for (let i = targetCutoff; i >= 0; i--) {\n if (isSafeCutoffPoint(messages, i)) {\n return i;\n }\n }\n\n return 0;\n}\n\n/**\n * Check if cutting at index would separate AI/Tool message pairs\n */\nfunction isSafeCutoffPoint(\n messages: BaseMessage[],\n cutoffIndex: number\n): boolean {\n if (cutoffIndex >= messages.length) {\n return true;\n }\n\n /**\n * Prevent preserved messages from starting with AI message containing tool calls\n */\n if (\n cutoffIndex < messages.length &&\n AIMessage.isInstance(messages[cutoffIndex]) &&\n hasToolCalls(messages[cutoffIndex])\n ) {\n return false;\n }\n\n const searchStart = Math.max(0, cutoffIndex - SEARCH_RANGE_FOR_TOOL_PAIRS);\n const searchEnd = Math.min(\n messages.length,\n cutoffIndex + SEARCH_RANGE_FOR_TOOL_PAIRS\n );\n\n for (let i = searchStart; i < searchEnd; i++) {\n if (!hasToolCalls(messages[i])) {\n continue;\n }\n\n const toolCallIds = extractToolCallIds(messages[i] as AIMessage);\n if (cutoffSeparatesToolPair(messages, i, cutoffIndex, toolCallIds)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Extract tool call IDs from an AI message\n */\nfunction extractToolCallIds(aiMessage: AIMessage): Set<string> {\n const toolCallIds = new Set<string>();\n if (aiMessage.tool_calls) {\n for (const toolCall of aiMessage.tool_calls) {\n const id =\n typeof toolCall === \"object\" && \"id\" in toolCall ? toolCall.id : null;\n if (id) {\n toolCallIds.add(id);\n }\n }\n }\n return toolCallIds;\n}\n\n/**\n * Check if cutoff separates an AI message from its corresponding tool messages\n */\nfunction cutoffSeparatesToolPair(\n messages: BaseMessage[],\n aiMessageIndex: number,\n cutoffIndex: number,\n toolCallIds: Set<string>\n): boolean {\n for (let j = aiMessageIndex + 1; j < messages.length; j++) {\n const message = messages[j];\n if (\n ToolMessage.isInstance(message) &&\n toolCallIds.has(message.tool_call_id)\n ) {\n const aiBeforeCutoff = aiMessageIndex < cutoffIndex;\n const toolBeforeCutoff = j < cutoffIndex;\n if (aiBeforeCutoff !== toolBeforeCutoff) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Generate summary for the given messages\n */\nasync function createSummary(\n messagesToSummarize: BaseMessage[],\n model: BaseLanguageModel,\n summaryPrompt: string,\n tokenCounter: TokenCounter,\n trimTokensToSummarize: number | undefined\n): Promise<string> {\n if (!messagesToSummarize.length) {\n return \"No previous conversation history.\";\n }\n\n const trimmedMessages = await trimMessagesForSummary(\n messagesToSummarize,\n tokenCounter,\n trimTokensToSummarize\n );\n\n if (!trimmedMessages.length) {\n return \"Previous conversation was too long to summarize.\";\n }\n\n try {\n const formattedPrompt = summaryPrompt.replace(\n \"{messages}\",\n JSON.stringify(trimmedMessages, null, 2)\n );\n const response = await model.invoke(formattedPrompt);\n const content = response.content;\n /**\n * Handle both string content and MessageContent array\n */\n if (typeof content === \"string\") {\n return content.trim();\n } else if (Array.isArray(content)) {\n /**\n * Extract text from MessageContent array\n */\n const textContent = content\n .map((item) => {\n if (typeof item === \"string\") return item;\n if (typeof item === \"object\" && item !== null && \"text\" in item) {\n return (item as { text: string }).text;\n }\n return \"\";\n })\n .join(\"\");\n return textContent.trim();\n }\n return \"Error generating summary: Invalid response format\";\n } catch (e) {\n return `Error generating summary: ${e}`;\n }\n}\n\n/**\n * Trim messages to fit within summary generation limits\n */\nasync function trimMessagesForSummary(\n messages: BaseMessage[],\n tokenCounter: TokenCounter,\n trimTokensToSummarize: number | undefined\n): Promise<BaseMessage[]> {\n if (trimTokensToSummarize === undefined) {\n return messages;\n }\n\n try {\n return await trimMessages(messages, {\n maxTokens: trimTokensToSummarize,\n tokenCounter: async (msgs) => tokenCounter(msgs),\n strategy: \"last\",\n allowPartial: true,\n includeSystem: true,\n });\n } catch {\n /**\n * Fallback to last N messages if trimming fails\n */\n return messages.slice(-DEFAULT_FALLBACK_MESSAGE_COUNT);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,MAAa,yBAAyB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;WA0B5B,CAAC;AAEZ,MAAM,2BAA2B;AACjC,MAAM,2BAA2B;AACjC,MAAM,iCAAiC;AACvC,MAAM,8BAA8B;AAEpC,MAAM,qBAAqB,EACxB,UAAU,CACV,KAAK,EAAE,MAAM,EAAE,QAAqB,CAAC,CAAC,CACtC,QAAQ,EAAE,MAAM,CAAC,EAAE,QAAQ,EAAE,EAAE,QAAQ,EAAE,QAAQ,CAAC,AAAC,EAAC,CAAC;AAKxD,MAAa,oBAAoB,EAC9B,OAAO;CAIN,UAAU,EACP,QAAQ,CACR,GAAG,GAAG,kCAAkC,CACxC,IAAI,GAAG,2CAA2C,CAClD,UAAU;CAIb,QAAQ,EAAE,QAAQ,CAAC,SAAS,gCAAgC,CAAC,UAAU;CAIvE,UAAU,EACP,QAAQ,CACR,IAAI,8BAA8B,CAClC,SAAS,kCAAkC,CAC3C,UAAU;AACd,EAAC,CACD,OACC,CAAC,SAAS;CACR,MAAM,QAAQ;EAAC,KAAK;EAAU,KAAK;EAAQ,KAAK;CAAS,EAAC,OACxD,CAAC,MAAM,MAAM,OACd,CAAC;AACF,QAAO,SAAS;AACjB,GACD,EACE,SAAS,iEACV,EACF;AAGH,MAAa,aAAa,EACvB,OAAO;CAIN,UAAU,EACP,QAAQ,CACR,IAAI,GAAG,gCAAgC,CACvC,IAAI,GAAG,2CAA2C,CAClD,UAAU;CAIb,QAAQ,EACL,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,OAAO,gBAAgB;EACpD,MAAM,UAAU,SAAS;;;;AAIzB,MAAI,OAAO,YAAY,SACrB,QAAO,QAAQ,MAAM;WACZ,MAAM,QAAQ,QAAQ,EAAE;;;;GAIjC,MAAM,cAAc,QACjB,IAAI,CAAC,SAAS;AACb,QAAI,OAAO,SAAS,SAAU,QAAO;AACrC,QAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,UAAU,KACzD,QAAQ,KAA0B;AAEpC,WAAO;GACR,EAAC,CACD,KAAK,GAAG;AACX,UAAO,YAAY,MAAM;EAC1B;AACD,SAAO;CACR,SAAQ,GAAG;AACV,SAAO,CAAC,0BAA0B,EAAE,GAAG;CACxC;AACF;;;;AAKD,eAAe,uBACbd,UACAM,cACAQ,uBACwB;AACxB,KAAI,0BAA0B,OAC5B,QAAO;AAGT,KAAI;AACF,SAAO,MAAM,aAAa,UAAU;GAClC,WAAW;GACX,cAAc,OAAO,SAAS,aAAa,KAAK;GAChD,UAAU;GACV,cAAc;GACd,eAAe;EAChB,EAAC;CACH,QAAO;;;;AAIN,SAAO,SAAS,MAAM,CAAC,+BAA+B;CACvD;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"todoListMiddleware.d.cts","names":["z","TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT","stateSchema","ZodString","ZodEnum","ZodTypeAny","ZodObject","ZodArray","ZodDefault","TodoMiddlewareState","infer","TodoListMiddlewareOptions","todoListMiddleware","__types_js14","AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nexport declare const TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = \"## `write_todos`\\n\\nYou have access to the `write_todos` tool to help you manage and plan complex objectives. \\nUse this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.\\nThis tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.\\n\\nIt is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.\\nFor simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.\\nWriting todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.\\n\\n## Important To-Do List Usage Notes to Remember\\n- The `write_todos` tool should never be called multiple times in parallel.\\n- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.\";\ndeclare const stateSchema: z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>;\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport declare function todoListMiddleware(options?: TodoListMiddlewareOptions): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>, undefined, any>;\nexport {};\n"],"mappings":";;;;cACqBC,kCAAAA;UAwBJU,yBAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6COC,kBAAAA,WAA6BD,4BAA4E,gBAAXX,CAAAA,CAAEM;SAC7GN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,SAASP,CAAAA,CAAEM;aACpBN,CAAAA,CAAEG;YACHH,CAAAA,CAAEI;cACFJ,CAAAA,CAAEK;;;;;;;YAONL,CAAAA,CAAEK"}
1
+ {"version":3,"file":"todoListMiddleware.d.cts","names":["z","TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT","stateSchema","ZodString","ZodEnum","ZodTypeAny","ZodObject","ZodArray","ZodDefault","TodoMiddlewareState","infer","TodoListMiddlewareOptions","todoListMiddleware","__types_js13","AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nexport declare const TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = \"## `write_todos`\\n\\nYou have access to the `write_todos` tool to help you manage and plan complex objectives. \\nUse this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.\\nThis tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.\\n\\nIt is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.\\nFor simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.\\nWriting todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.\\n\\n## Important To-Do List Usage Notes to Remember\\n- The `write_todos` tool should never be called multiple times in parallel.\\n- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.\";\ndeclare const stateSchema: z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>;\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport declare function todoListMiddleware(options?: TodoListMiddlewareOptions): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>, undefined, any>;\nexport {};\n"],"mappings":";;;;cACqBC,kCAAAA;UAwBJU,yBAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6COC,kBAAAA,WAA6BD,4BAA4E,gBAAXX,CAAAA,CAAEM;SAC7GN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,SAASP,CAAAA,CAAEM;aACpBN,CAAAA,CAAEG;YACHH,CAAAA,CAAEI;cACFJ,CAAAA,CAAEK;;;;;;;YAONL,CAAAA,CAAEK"}
@@ -1 +1 @@
1
- {"version":3,"file":"todoListMiddleware.d.ts","names":["z","TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT","stateSchema","ZodString","ZodEnum","ZodTypeAny","ZodObject","ZodArray","ZodDefault","TodoMiddlewareState","infer","TodoListMiddlewareOptions","todoListMiddleware","__types_js5","AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nexport declare const TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = \"## `write_todos`\\n\\nYou have access to the `write_todos` tool to help you manage and plan complex objectives. \\nUse this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.\\nThis tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.\\n\\nIt is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.\\nFor simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.\\nWriting todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.\\n\\n## Important To-Do List Usage Notes to Remember\\n- The `write_todos` tool should never be called multiple times in parallel.\\n- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.\";\ndeclare const stateSchema: z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>;\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport declare function todoListMiddleware(options?: TodoListMiddlewareOptions): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>, undefined, any>;\nexport {};\n"],"mappings":";;;;cACqBC,kCAAAA;UAwBJU,yBAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6COC,kBAAAA,WAA6BD,4BAA4E,gBAAXX,CAAAA,CAAEM;SAC7GN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,SAASP,CAAAA,CAAEM;aACpBN,CAAAA,CAAEG;YACHH,CAAAA,CAAEI;cACFJ,CAAAA,CAAEK;;;;;;;YAONL,CAAAA,CAAEK"}
1
+ {"version":3,"file":"todoListMiddleware.d.ts","names":["z","TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT","stateSchema","ZodString","ZodEnum","ZodTypeAny","ZodObject","ZodArray","ZodDefault","TodoMiddlewareState","infer","TodoListMiddlewareOptions","todoListMiddleware","__types_js3","AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nexport declare const TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = \"## `write_todos`\\n\\nYou have access to the `write_todos` tool to help you manage and plan complex objectives. \\nUse this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.\\nThis tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.\\n\\nIt is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.\\nFor simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.\\nWriting todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.\\n\\n## Important To-Do List Usage Notes to Remember\\n- The `write_todos` tool should never be called multiple times in parallel.\\n- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.\";\ndeclare const stateSchema: z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>;\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport declare function todoListMiddleware(options?: TodoListMiddlewareOptions): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>, undefined, any>;\nexport {};\n"],"mappings":";;;;cACqBC,kCAAAA;UAwBJU,yBAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6COC,kBAAAA,WAA6BD,4BAA4E,gBAAXX,CAAAA,CAAEM;SAC7GN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,SAASP,CAAAA,CAAEM;aACpBN,CAAAA,CAAEG;YACHH,CAAAA,CAAEI;cACFJ,CAAAA,CAAEK;;;;;;;YAONL,CAAAA,CAAEK"}
@@ -1 +1 @@
1
- {"version":3,"file":"toolCallLimit.d.cts","names":["z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","__types_js13","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, any>;\n"],"mappings":";;;;;;;;;AAQA;AA0BA;;AAI4BA,cA9BPE,0BAAAA,SAAmCC,KAAK,CA8B/BE;EAAS;;;EAKT,WAKAE,EAAAA,MAAAA;EAAS;;;EAWT,QAChBG,EAAAA,MAAAA;EAAU;AA1BoC;AAqC5D;EAA+B,WAAA,EAAA,MAAA,GAAA,SAAA;EAAA;;AAAuB;EAiF9BG,QAAAA,EAAAA,MAAAA,GAAAA,SAAuB;EAAA;;;EACc,QAAIN,EAAAA,MAAAA,GAAAA,SAAAA;EAAS,WAAlCO,CAAAA,WAAAA,EAAAA,MAAAA,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;;;;;AAClBd,cAxHDI,0BAwHGK,EAxHyBT,CAAAA,CAAEW,SAwH3BF,CAAAA;EAAU;;;EAGN,QAEFM,EAzHZf,CAAAA,CAAEM,WAyHUS,CAzHEf,CAAAA,CAAEK,SAyHJU,CAAAA;EAAM;;;AAPmF;eA7GlGf,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;YAKnBP,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;;;;;;;gBAWZP,CAAAA,CAAES,WAAWT,CAAAA,CAAEQ;YACrBR,CAAAA,CAAEU;;;;;;;;;;;KAWFE,mBAAAA,GAAsBX,4BAA4BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiFtCS,uBAAAA,UAAiCD,sBAAsE,gBAAXZ,CAAAA,CAAEW;uBAC7FX,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;oBAC3CP,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;YAClDP,CAAAA,CAAEU;uBACWK;oBACHA;;wBAEIA;qBACHA"}
1
+ {"version":3,"file":"toolCallLimit.d.cts","names":["z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","__types_js12","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, any>;\n"],"mappings":";;;;;;;;;AAQA;AA0BA;;AAI4BA,cA9BPE,0BAAAA,SAAmCC,KAAK,CA8B/BE;EAAS;;;E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 +1 @@
1
- {"version":3,"file":"toolCallLimit.d.ts","names":["z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","__types_js4","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, any>;\n"],"mappings":";;;;;;;;;AAQA;AA0BA;;AAI4BA,cA9BPE,0BAAAA,SAAmCC,KAAK,CA8B/BE;EAAS;;;EAKT,WAKAE,EAAAA,MAAAA;EAAS;;;EAWT,QAChBG,EAAAA,MAAAA;EAAU;AA1BoC;AAqC5D;EAA+B,WAAA,EAAA,MAAA,GAAA,SAAA;EAAA;;AAAuB;EAiF9BG,QAAAA,EAAAA,MAAAA,GAAAA,SAAuB;EAAA;;;EACc,QAAIN,EAAAA,MAAAA,GAAAA,SAAAA;EAAS,WAAlCO,CAAAA,WAAAA,EAAAA,MAAAA,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;;;;;AAClBd,cAxHDI,0BAwHGK,EAxHyBT,CAAAA,CAAEW,SAwH3BF,CAAAA;EAAU;;;EAGN,QAEFM,EAzHZf,CAAAA,CAAEM,WAyHUS,CAzHEf,CAAAA,CAAEK,SAyHJU,CAAAA;EAAM;;;AAPmF;eA7GlGf,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;YAKnBP,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;;;;;;;gBAWZP,CAAAA,CAAES,WAAWT,CAAAA,CAAEQ;YACrBR,CAAAA,CAAEU;;;;;;;;;;;KAWFE,mBAAAA,GAAsBX,4BAA4BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiFtCS,uBAAAA,UAAiCD,sBAAsE,gBAAXZ,CAAAA,CAAEW;uBAC7FX,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;oBAC3CP,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;YAClDP,CAAAA,CAAEU;uBACWK;oBACHA;;wBAEIA;qBACHA"}
1
+ {"version":3,"file":"toolCallLimit.d.ts","names":["z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","__types_js2","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, any>;\n"],"mappings":";;;;;;;;;AAQA;AA0BA;;AAI4BA,cA9BPE,0BAAAA,SAAmCC,KAAK,CA8B/BE;EAAS;;;EAKT,WAKAE,EAAAA,MAAAA;EAAS;;;EAWT,QAChBG,EAAAA,MAAAA;EAAU;AA1BoC;AAqC5D;EAA+B,WAAA,EAAA,MAAA,GAAA,SAAA;EAAA;;AAAuB;EAiF9BG,QAAAA,EAAAA,MAAAA,GAAAA,SAAuB;EAAA;;;EACc,QAAIN,EAAAA,MAAAA,GAAAA,SAAAA;EAAS,WAAlCO,CAAAA,WAAAA,EAAAA,MAAAA,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;;;;;AAClBd,cAxHDI,0BAwHGK,EAxHyBT,CAAAA,CAAEW,SAwH3BF,CAAAA;EAAU;;;EAGN,QAEFM,EAzHZf,CAAAA,CAAEM,WAyHUS,CAzHEf,CAAAA,CAAEK,SAyHJU,CAAAA;EAAM;;;AAPmF;eA7GlGf,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;YAKnBP,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;;;;;;;gBAWZP,CAAAA,CAAES,WAAWT,CAAAA,CAAEQ;YACrBR,CAAAA,CAAEU;;;;;;;;;;;KAWFE,mBAAAA,GAAsBX,4BAA4BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiFtCS,uBAAAA,UAAiCD,sBAAsE,gBAAXZ,CAAAA,CAAEW;uBAC7FX,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;oBAC3CP,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;YAClDP,CAAAA,CAAEU;uBACWK;oBACHA;;wBAEIA;qBACHA"}
@@ -0,0 +1,118 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ const require_chat_models_universal = require('../../chat_models/universal.cjs');
3
+ const require_middleware = require('../middleware.cjs');
4
+ const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
5
+
6
+ //#region src/agents/middleware/toolEmulator.ts
7
+ /**
8
+ * Middleware that emulates specified tools using an LLM instead of executing them.
9
+ *
10
+ * This middleware allows selective emulation of tools for testing purposes.
11
+ * By default (when `tools` is undefined), all tools are emulated. You can specify
12
+ * which tools to emulate by passing a list of tool names or tool instances.
13
+ *
14
+ * @param options - Configuration options for the middleware
15
+ * @param options.tools - List of tool names or tool instances to emulate. If undefined, all tools are emulated.
16
+ * @param options.model - Model to use for emulation. Defaults to "anthropic:claude-sonnet-4-5-20250929".
17
+ *
18
+ * @example Emulate all tools (default behavior)
19
+ * ```ts
20
+ * import { toolEmulatorMiddleware } from "@langchain/langchain/agents/middleware";
21
+ * import { createAgent } from "@langchain/langchain/agents";
22
+ *
23
+ * const middleware = toolEmulatorMiddleware();
24
+ *
25
+ * const agent = createAgent({
26
+ * model: "openai:gpt-4o",
27
+ * tools: [getWeather, getUserLocation, calculator],
28
+ * middleware: [middleware],
29
+ * });
30
+ * ```
31
+ *
32
+ * @example Emulate specific tools by name
33
+ * ```ts
34
+ * const middleware = toolEmulatorMiddleware({
35
+ * tools: ["get_weather", "get_user_location"]
36
+ * });
37
+ * ```
38
+ *
39
+ * @example Use a custom model for emulation
40
+ * ```ts
41
+ * const middleware = toolEmulatorMiddleware({
42
+ * tools: ["get_weather"],
43
+ * model: "anthropic:claude-sonnet-4-5-20250929"
44
+ * });
45
+ * ```
46
+ *
47
+ * @example Emulate specific tools by passing tool instances
48
+ * ```ts
49
+ * const middleware = toolEmulatorMiddleware({
50
+ * tools: [getWeather, getUserLocation]
51
+ * });
52
+ * ```
53
+ */
54
+ function toolEmulatorMiddleware(options = {}) {
55
+ let agentModel;
56
+ const { tools, model } = options;
57
+ /**
58
+ * Extract tool names from tools
59
+ */
60
+ const emulateAll = !tools || tools.length === 0;
61
+ const toolsToEmulate = /* @__PURE__ */ new Set();
62
+ if (!emulateAll && tools) for (const tool of tools) if (typeof tool === "string") toolsToEmulate.add(tool);
63
+ else {
64
+ const toolName = typeof tool.name === "string" ? tool.name : String(tool.name);
65
+ toolsToEmulate.add(toolName);
66
+ }
67
+ /**
68
+ * Initialize emulator model
69
+ * We'll initialize it lazily in wrapToolCall to handle async initChatModel
70
+ */
71
+ let emulatorModel;
72
+ const getEmulatorModel = async () => {
73
+ if (typeof model === "object") return model;
74
+ if (typeof model === "string") {
75
+ emulatorModel = emulatorModel ?? await require_chat_models_universal.initChatModel(model, { temperature: 1 }).catch((err) => {
76
+ console.error("Error initializing emulator model, using agent model:", err);
77
+ return agentModel;
78
+ });
79
+ return emulatorModel;
80
+ }
81
+ return agentModel;
82
+ };
83
+ return require_middleware.createMiddleware({
84
+ name: "ToolEmulatorMiddleware",
85
+ wrapModelCall: async (request, handler) => {
86
+ agentModel = request.model;
87
+ return handler(request);
88
+ },
89
+ wrapToolCall: async (request, handler) => {
90
+ const toolName = request.toolCall.name;
91
+ const shouldEmulate = emulateAll || toolsToEmulate.has(toolName);
92
+ if (!shouldEmulate) return handler(request);
93
+ const toolArgs = request.toolCall.args;
94
+ const toolDescription = request.tool.description || "No description available";
95
+ const toolArgsString = typeof toolArgs === "string" ? toolArgs : JSON.stringify(toolArgs);
96
+ const prompt = `You are emulating a tool call for testing purposes.
97
+
98
+ Tool: ${toolName}
99
+ Description: ${toolDescription}
100
+ Arguments: ${toolArgsString}
101
+
102
+ Generate a realistic response that this tool would return given these arguments.
103
+ Return ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`;
104
+ const emulator = await getEmulatorModel();
105
+ const response = await emulator.invoke([new __langchain_core_messages.HumanMessage(prompt)]);
106
+ const content = typeof response.content === "string" ? response.content : JSON.stringify(response.content);
107
+ return new __langchain_core_messages.ToolMessage({
108
+ content,
109
+ tool_call_id: request.toolCall.id ?? "",
110
+ name: toolName
111
+ });
112
+ }
113
+ });
114
+ }
115
+
116
+ //#endregion
117
+ exports.toolEmulatorMiddleware = toolEmulatorMiddleware;
118
+ //# sourceMappingURL=toolEmulator.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolEmulator.cjs","names":["options: ToolEmulatorOptions","agentModel: BaseChatModel | undefined","emulatorModel: BaseChatModel | undefined","initChatModel","createMiddleware","HumanMessage","ToolMessage"],"sources":["../../../src/agents/middleware/toolEmulator.ts"],"sourcesContent":["import { HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Options for configuring the Tool Emulator middleware.\n */\nexport interface ToolEmulatorOptions {\n /**\n * List of tool names (string) or tool instances to emulate.\n * - If `undefined` (default), ALL tools will be emulated.\n * - If empty array, no tools will be emulated.\n * - If array with tool names/instances, only those tools will be emulated.\n */\n tools?: (string | ClientTool | ServerTool)[];\n\n /**\n * Model to use for emulation.\n * - Can be a model identifier string (e.g., \"anthropic:claude-sonnet-4-5-20250929\")\n * - Can be a BaseChatModel instance\n * - Defaults to agent model\n */\n model?: string | BaseChatModel;\n}\n\n/**\n * Middleware that emulates specified tools using an LLM instead of executing them.\n *\n * This middleware allows selective emulation of tools for testing purposes.\n * By default (when `tools` is undefined), all tools are emulated. You can specify\n * which tools to emulate by passing a list of tool names or tool instances.\n *\n * @param options - Configuration options for the middleware\n * @param options.tools - List of tool names or tool instances to emulate. If undefined, all tools are emulated.\n * @param options.model - Model to use for emulation. Defaults to \"anthropic:claude-sonnet-4-5-20250929\".\n *\n * @example Emulate all tools (default behavior)\n * ```ts\n * import { toolEmulatorMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * const middleware = toolEmulatorMiddleware();\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather, getUserLocation, calculator],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example Emulate specific tools by name\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\", \"get_user_location\"]\n * });\n * ```\n *\n * @example Use a custom model for emulation\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\"],\n * model: \"anthropic:claude-sonnet-4-5-20250929\"\n * });\n * ```\n *\n * @example Emulate specific tools by passing tool instances\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [getWeather, getUserLocation]\n * });\n * ```\n */\nexport function toolEmulatorMiddleware(\n options: ToolEmulatorOptions = {}\n): ReturnType<typeof createMiddleware> {\n let agentModel: BaseChatModel | undefined;\n const { tools, model } = options;\n\n /**\n * Extract tool names from tools\n */\n const emulateAll = !tools || tools.length === 0;\n const toolsToEmulate = new Set<string>();\n\n if (!emulateAll && tools) {\n for (const tool of tools) {\n if (typeof tool === \"string\") {\n toolsToEmulate.add(tool);\n } else {\n // Assume tool instance with .name property\n const toolName =\n typeof tool.name === \"string\" ? tool.name : String(tool.name);\n toolsToEmulate.add(toolName);\n }\n }\n }\n\n /**\n * Initialize emulator model\n * We'll initialize it lazily in wrapToolCall to handle async initChatModel\n */\n let emulatorModel: BaseChatModel | undefined;\n const getEmulatorModel = async (): Promise<BaseChatModel> => {\n if (typeof model === \"object\") {\n return model;\n }\n if (typeof model === \"string\") {\n emulatorModel =\n emulatorModel ??\n (await initChatModel(model, { temperature: 1 }).catch((err) => {\n console.error(\n \"Error initializing emulator model, using agent model:\",\n err\n );\n return agentModel as BaseChatModel;\n }));\n return emulatorModel;\n }\n return agentModel as BaseChatModel;\n };\n\n return createMiddleware({\n name: \"ToolEmulatorMiddleware\",\n wrapModelCall: async (request, handler) => {\n agentModel = request.model as BaseChatModel;\n return handler(request);\n },\n wrapToolCall: async (request, handler) => {\n const toolName = request.toolCall.name;\n\n // Check if this tool should be emulated\n const shouldEmulate = emulateAll || toolsToEmulate.has(toolName);\n\n if (!shouldEmulate) {\n // Let it execute normally by calling the handler\n return handler(request);\n }\n\n // Extract tool information for emulation\n const toolArgs = request.toolCall.args;\n const toolDescription =\n request.tool.description || \"No description available\";\n\n // Build prompt for emulator LLM\n const toolArgsString =\n typeof toolArgs === \"string\" ? toolArgs : JSON.stringify(toolArgs);\n const prompt = `You are emulating a tool call for testing purposes.\n\nTool: ${toolName}\nDescription: ${toolDescription}\nArguments: ${toolArgsString}\n\nGenerate a realistic response that this tool would return given these arguments.\nReturn ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`;\n\n // Get emulated response from LLM\n const emulator = await getEmulatorModel();\n const response = await emulator.invoke([new HumanMessage(prompt)]);\n\n // Extract content from response\n const content =\n typeof response.content === \"string\"\n ? response.content\n : JSON.stringify(response.content);\n\n // Short-circuit: return emulated result without executing real tool\n return new ToolMessage({\n content,\n tool_call_id: request.toolCall.id ?? \"\",\n name: toolName,\n });\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,SAAgB,uBACdA,UAA+B,CAAE,GACI;CACrC,IAAIC;CACJ,MAAM,EAAE,OAAO,OAAO,GAAG;;;;CAKzB,MAAM,aAAa,CAAC,SAAS,MAAM,WAAW;CAC9C,MAAM,iCAAiB,IAAI;AAE3B,KAAI,CAAC,cAAc,MACjB,MAAK,MAAM,QAAQ,MACjB,KAAI,OAAO,SAAS,UAClB,eAAe,IAAI,KAAK;MACnB;EAEL,MAAM,WACJ,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO,OAAO,KAAK,KAAK;EAC/D,eAAe,IAAI,SAAS;CAC7B;;;;;CAQL,IAAIC;CACJ,MAAM,mBAAmB,YAAoC;AAC3D,MAAI,OAAO,UAAU,SACnB,QAAO;AAET,MAAI,OAAO,UAAU,UAAU;GAC7B,gBACE,iBACC,MAAMC,4CAAc,OAAO,EAAE,aAAa,EAAG,EAAC,CAAC,MAAM,CAAC,QAAQ;IAC7D,QAAQ,MACN,yDACA,IACD;AACD,WAAO;GACR,EAAC;AACJ,UAAO;EACR;AACD,SAAO;CACR;AAED,QAAOC,oCAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;GACzC,aAAa,QAAQ;AACrB,UAAO,QAAQ,QAAQ;EACxB;EACD,cAAc,OAAO,SAAS,YAAY;GACxC,MAAM,WAAW,QAAQ,SAAS;GAGlC,MAAM,gBAAgB,cAAc,eAAe,IAAI,SAAS;AAEhE,OAAI,CAAC,cAEH,QAAO,QAAQ,QAAQ;GAIzB,MAAM,WAAW,QAAQ,SAAS;GAClC,MAAM,kBACJ,QAAQ,KAAK,eAAe;GAG9B,MAAM,iBACJ,OAAO,aAAa,WAAW,WAAW,KAAK,UAAU,SAAS;GACpE,MAAM,SAAS,CAAC;;MAEhB,EAAE,SAAS;aACJ,EAAE,gBAAgB;WACpB,EAAE,eAAe;;;mGAGuE,CAAC;GAG9F,MAAM,WAAW,MAAM,kBAAkB;GACzC,MAAM,WAAW,MAAM,SAAS,OAAO,CAAC,IAAIC,uCAAa,OAAQ,EAAC;GAGlE,MAAM,UACJ,OAAO,SAAS,YAAY,WACxB,SAAS,UACT,KAAK,UAAU,SAAS,QAAQ;AAGtC,UAAO,IAAIC,sCAAY;IACrB;IACA,cAAc,QAAQ,SAAS,MAAM;IACrC,MAAM;GACP;EACF;CACF,EAAC;AACH"}
@@ -0,0 +1,76 @@
1
+ import { createMiddleware } from "../middleware.cjs";
2
+ import { BaseChatModel } from "@langchain/core/language_models/chat_models";
3
+ import { ClientTool, ServerTool } from "@langchain/core/tools";
4
+
5
+ //#region src/agents/middleware/toolEmulator.d.ts
6
+
7
+ /**
8
+ * Options for configuring the Tool Emulator middleware.
9
+ */
10
+ interface ToolEmulatorOptions {
11
+ /**
12
+ * List of tool names (string) or tool instances to emulate.
13
+ * - If `undefined` (default), ALL tools will be emulated.
14
+ * - If empty array, no tools will be emulated.
15
+ * - If array with tool names/instances, only those tools will be emulated.
16
+ */
17
+ tools?: (string | ClientTool | ServerTool)[];
18
+ /**
19
+ * Model to use for emulation.
20
+ * - Can be a model identifier string (e.g., "anthropic:claude-sonnet-4-5-20250929")
21
+ * - Can be a BaseChatModel instance
22
+ * - Defaults to agent model
23
+ */
24
+ model?: string | BaseChatModel;
25
+ }
26
+ /**
27
+ * Middleware that emulates specified tools using an LLM instead of executing them.
28
+ *
29
+ * This middleware allows selective emulation of tools for testing purposes.
30
+ * By default (when `tools` is undefined), all tools are emulated. You can specify
31
+ * which tools to emulate by passing a list of tool names or tool instances.
32
+ *
33
+ * @param options - Configuration options for the middleware
34
+ * @param options.tools - List of tool names or tool instances to emulate. If undefined, all tools are emulated.
35
+ * @param options.model - Model to use for emulation. Defaults to "anthropic:claude-sonnet-4-5-20250929".
36
+ *
37
+ * @example Emulate all tools (default behavior)
38
+ * ```ts
39
+ * import { toolEmulatorMiddleware } from "@langchain/langchain/agents/middleware";
40
+ * import { createAgent } from "@langchain/langchain/agents";
41
+ *
42
+ * const middleware = toolEmulatorMiddleware();
43
+ *
44
+ * const agent = createAgent({
45
+ * model: "openai:gpt-4o",
46
+ * tools: [getWeather, getUserLocation, calculator],
47
+ * middleware: [middleware],
48
+ * });
49
+ * ```
50
+ *
51
+ * @example Emulate specific tools by name
52
+ * ```ts
53
+ * const middleware = toolEmulatorMiddleware({
54
+ * tools: ["get_weather", "get_user_location"]
55
+ * });
56
+ * ```
57
+ *
58
+ * @example Use a custom model for emulation
59
+ * ```ts
60
+ * const middleware = toolEmulatorMiddleware({
61
+ * tools: ["get_weather"],
62
+ * model: "anthropic:claude-sonnet-4-5-20250929"
63
+ * });
64
+ * ```
65
+ *
66
+ * @example Emulate specific tools by passing tool instances
67
+ * ```ts
68
+ * const middleware = toolEmulatorMiddleware({
69
+ * tools: [getWeather, getUserLocation]
70
+ * });
71
+ * ```
72
+ */
73
+ declare function toolEmulatorMiddleware(options?: ToolEmulatorOptions): ReturnType<typeof createMiddleware>;
74
+ //#endregion
75
+ export { ToolEmulatorOptions, toolEmulatorMiddleware };
76
+ //# sourceMappingURL=toolEmulator.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolEmulator.d.cts","names":["BaseChatModel","ClientTool","ServerTool","createMiddleware","ToolEmulatorOptions","toolEmulatorMiddleware","ReturnType"],"sources":["../../../src/agents/middleware/toolEmulator.d.ts"],"sourcesContent":["import type { BaseChatModel } from \"@langchain/core/language_models/chat_models\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\nimport { createMiddleware } from \"../middleware.js\";\n/**\n * Options for configuring the Tool Emulator middleware.\n */\nexport interface ToolEmulatorOptions {\n /**\n * List of tool names (string) or tool instances to emulate.\n * - If `undefined` (default), ALL tools will be emulated.\n * - If empty array, no tools will be emulated.\n * - If array with tool names/instances, only those tools will be emulated.\n */\n tools?: (string | ClientTool | ServerTool)[];\n /**\n * Model to use for emulation.\n * - Can be a model identifier string (e.g., \"anthropic:claude-sonnet-4-5-20250929\")\n * - Can be a BaseChatModel instance\n * - Defaults to agent model\n */\n model?: string | BaseChatModel;\n}\n/**\n * Middleware that emulates specified tools using an LLM instead of executing them.\n *\n * This middleware allows selective emulation of tools for testing purposes.\n * By default (when `tools` is undefined), all tools are emulated. You can specify\n * which tools to emulate by passing a list of tool names or tool instances.\n *\n * @param options - Configuration options for the middleware\n * @param options.tools - List of tool names or tool instances to emulate. If undefined, all tools are emulated.\n * @param options.model - Model to use for emulation. Defaults to \"anthropic:claude-sonnet-4-5-20250929\".\n *\n * @example Emulate all tools (default behavior)\n * ```ts\n * import { toolEmulatorMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * const middleware = toolEmulatorMiddleware();\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [getWeather, getUserLocation, calculator],\n * middleware: [middleware],\n * });\n * ```\n *\n * @example Emulate specific tools by name\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\", \"get_user_location\"]\n * });\n * ```\n *\n * @example Use a custom model for emulation\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [\"get_weather\"],\n * model: \"anthropic:claude-sonnet-4-5-20250929\"\n * });\n * ```\n *\n * @example Emulate specific tools by passing tool instances\n * ```ts\n * const middleware = toolEmulatorMiddleware({\n * tools: [getWeather, getUserLocation]\n * });\n * ```\n */\nexport declare function toolEmulatorMiddleware(options?: ToolEmulatorOptions): ReturnType<typeof createMiddleware>;\n"],"mappings":";;;;;;;;AAMA;AAAoC,UAAnBI,mBAAAA,CAAmB;EAAA;;;AAcF;AAiDlC;;EAA8C,KAAWA,CAAAA,EAAAA,CAAAA,MAAAA,GAxDnCH,UAwDmCG,GAxDtBF,UAwDsBE,CAAAA,EAAAA;EAAmB;;AAAa;;;;mBAjDpEJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiDGK,sBAAAA,WAAiCD,sBAAsBE,kBAAkBH"}
@@ -0,0 +1,76 @@
1
+ import { createMiddleware } from "../middleware.js";
2
+ import { BaseChatModel } from "@langchain/core/language_models/chat_models";
3
+ import { ClientTool, ServerTool } from "@langchain/core/tools";
4
+
5
+ //#region src/agents/middleware/toolEmulator.d.ts
6
+
7
+ /**
8
+ * Options for configuring the Tool Emulator middleware.
9
+ */
10
+ interface ToolEmulatorOptions {
11
+ /**
12
+ * List of tool names (string) or tool instances to emulate.
13
+ * - If `undefined` (default), ALL tools will be emulated.
14
+ * - If empty array, no tools will be emulated.
15
+ * - If array with tool names/instances, only those tools will be emulated.
16
+ */
17
+ tools?: (string | ClientTool | ServerTool)[];
18
+ /**
19
+ * Model to use for emulation.
20
+ * - Can be a model identifier string (e.g., "anthropic:claude-sonnet-4-5-20250929")
21
+ * - Can be a BaseChatModel instance
22
+ * - Defaults to agent model
23
+ */
24
+ model?: string | BaseChatModel;
25
+ }
26
+ /**
27
+ * Middleware that emulates specified tools using an LLM instead of executing them.
28
+ *
29
+ * This middleware allows selective emulation of tools for testing purposes.
30
+ * By default (when `tools` is undefined), all tools are emulated. You can specify
31
+ * which tools to emulate by passing a list of tool names or tool instances.
32
+ *
33
+ * @param options - Configuration options for the middleware
34
+ * @param options.tools - List of tool names or tool instances to emulate. If undefined, all tools are emulated.
35
+ * @param options.model - Model to use for emulation. Defaults to "anthropic:claude-sonnet-4-5-20250929".
36
+ *
37
+ * @example Emulate all tools (default behavior)
38
+ * ```ts
39
+ * import { toolEmulatorMiddleware } from "@langchain/langchain/agents/middleware";
40
+ * import { createAgent } from "@langchain/langchain/agents";
41
+ *
42
+ * const middleware = toolEmulatorMiddleware();
43
+ *
44
+ * const agent = createAgent({
45
+ * model: "openai:gpt-4o",
46
+ * tools: [getWeather, getUserLocation, calculator],
47
+ * middleware: [middleware],
48
+ * });
49
+ * ```
50
+ *
51
+ * @example Emulate specific tools by name
52
+ * ```ts
53
+ * const middleware = toolEmulatorMiddleware({
54
+ * tools: ["get_weather", "get_user_location"]
55
+ * });
56
+ * ```
57
+ *
58
+ * @example Use a custom model for emulation
59
+ * ```ts
60
+ * const middleware = toolEmulatorMiddleware({
61
+ * tools: ["get_weather"],
62
+ * model: "anthropic:claude-sonnet-4-5-20250929"
63
+ * });
64
+ * ```
65
+ *
66
+ * @example Emulate specific tools by passing tool instances
67
+ * ```ts
68
+ * const middleware = toolEmulatorMiddleware({
69
+ * tools: [getWeather, getUserLocation]
70
+ * });
71
+ * ```
72
+ */
73
+ declare function toolEmulatorMiddleware(options?: ToolEmulatorOptions): ReturnType<typeof createMiddleware>;
74
+ //#endregion
75
+ export { ToolEmulatorOptions, toolEmulatorMiddleware };
76
+ //# sourceMappingURL=toolEmulator.d.ts.map