langchain 1.0.3 → 1.0.4

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 (372) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/agents/ReactAgent.cjs.map +1 -1
  3. package/dist/agents/ReactAgent.js.map +1 -1
  4. package/dist/agents/annotation.cjs +6 -4
  5. package/dist/agents/annotation.cjs.map +1 -1
  6. package/dist/agents/annotation.js +7 -5
  7. package/dist/agents/annotation.js.map +1 -1
  8. package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
  9. package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
  10. package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
  11. package/dist/agents/middleware/hitl.d.cts.map +1 -1
  12. package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
  13. package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
  14. package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
  15. package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
  16. package/dist/agents/middleware/promptCaching.d.cts.map +1 -1
  17. package/dist/agents/middleware/promptCaching.d.ts.map +1 -1
  18. package/dist/agents/middleware/summarization.cjs +272 -52
  19. package/dist/agents/middleware/summarization.cjs.map +1 -1
  20. package/dist/agents/middleware/summarization.d.cts +325 -30
  21. package/dist/agents/middleware/summarization.d.cts.map +1 -1
  22. package/dist/agents/middleware/summarization.d.ts +320 -25
  23. package/dist/agents/middleware/summarization.d.ts.map +1 -1
  24. package/dist/agents/middleware/summarization.js +274 -54
  25. package/dist/agents/middleware/summarization.js.map +1 -1
  26. package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
  27. package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
  28. package/dist/agents/middleware/toolCallLimit.cjs +36 -27
  29. package/dist/agents/middleware/toolCallLimit.cjs.map +1 -1
  30. package/dist/agents/middleware/toolCallLimit.d.cts +3 -1
  31. package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
  32. package/dist/agents/middleware/toolCallLimit.d.ts +3 -1
  33. package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
  34. package/dist/agents/middleware/toolCallLimit.js +36 -27
  35. package/dist/agents/middleware/toolCallLimit.js.map +1 -1
  36. package/dist/agents/middleware/types.d.cts.map +1 -1
  37. package/dist/agents/middleware/types.d.ts.map +1 -1
  38. package/dist/agents/middleware/utils.d.cts.map +1 -1
  39. package/dist/agents/middleware/utils.d.ts.map +1 -1
  40. package/dist/agents/nodes/AgentNode.cjs +0 -4
  41. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  42. package/dist/agents/nodes/AgentNode.js +1 -5
  43. package/dist/agents/nodes/AgentNode.js.map +1 -1
  44. package/dist/agents/responses.cjs +0 -1
  45. package/dist/agents/responses.js +1 -1
  46. package/dist/index.cjs.map +1 -1
  47. package/dist/index.d.cts +2 -2
  48. package/dist/index.d.ts +2 -2
  49. package/dist/index.js.map +1 -1
  50. package/package.json +6 -6
  51. package/dist/agents/middleware/callLimit.cjs +0 -130
  52. package/dist/agents/middleware/callLimit.cjs.map +0 -1
  53. package/dist/agents/middleware/callLimit.d.cts +0 -119
  54. package/dist/agents/middleware/callLimit.d.cts.map +0 -1
  55. package/dist/agents/middleware/callLimit.d.ts +0 -119
  56. package/dist/agents/middleware/callLimit.d.ts.map +0 -1
  57. package/dist/agents/middleware/callLimit.js +0 -129
  58. package/dist/agents/middleware/callLimit.js.map +0 -1
  59. package/dist/agents/middleware/index.d.cts +0 -15
  60. package/dist/agents/middleware/index.d.ts +0 -14
  61. package/dist/agents/tools.d.cts +0 -9
  62. package/dist/agents/tools.d.cts.map +0 -1
  63. package/dist/agents/tools.d.ts +0 -9
  64. package/dist/agents/tools.d.ts.map +0 -1
  65. package/dist/embeddings/cache_backed.cjs +0 -140
  66. package/dist/embeddings/cache_backed.cjs.map +0 -1
  67. package/dist/embeddings/cache_backed.d.cts +0 -107
  68. package/dist/embeddings/cache_backed.d.cts.map +0 -1
  69. package/dist/embeddings/cache_backed.d.ts +0 -107
  70. package/dist/embeddings/cache_backed.d.ts.map +0 -1
  71. package/dist/embeddings/cache_backed.js +0 -134
  72. package/dist/embeddings/cache_backed.js.map +0 -1
  73. package/dist/embeddings/fake.cjs +0 -22
  74. package/dist/embeddings/fake.cjs.map +0 -1
  75. package/dist/embeddings/fake.d.cts +0 -1
  76. package/dist/embeddings/fake.d.ts +0 -1
  77. package/dist/embeddings/fake.js +0 -12
  78. package/dist/embeddings/fake.js.map +0 -1
  79. package/dist/node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.cjs +0 -248
  80. package/dist/node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.cjs.map +0 -1
  81. package/dist/node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js +0 -244
  82. package/dist/node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js.map +0 -1
  83. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.cjs +0 -3096
  84. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.cjs.map +0 -1
  85. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.js +0 -3095
  86. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/client.js.map +0 -1
  87. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/env.cjs +0 -12
  88. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/env.cjs.map +0 -1
  89. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/env.js +0 -12
  90. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/env.js.map +0 -1
  91. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/constants.cjs +0 -71
  92. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/constants.cjs.map +0 -1
  93. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/constants.js +0 -38
  94. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/constants.js.map +0 -1
  95. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/translator.cjs +0 -221
  96. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/translator.cjs.map +0 -1
  97. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/translator.js +0 -221
  98. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/experimental/otel/translator.js.map +0 -1
  99. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/index.cjs +0 -11
  100. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/index.cjs.map +0 -1
  101. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/index.js +0 -11
  102. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/index.js.map +0 -1
  103. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.cjs +0 -703
  104. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.cjs.map +0 -1
  105. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.js +0 -702
  106. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/run_trees.js.map +0 -1
  107. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/constants.cjs +0 -7
  108. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/constants.cjs.map +0 -1
  109. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/constants.js +0 -6
  110. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/constants.js.map +0 -1
  111. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/fetch.cjs +0 -29
  112. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/fetch.cjs.map +0 -1
  113. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/fetch.js +0 -28
  114. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/fetch.js.map +0 -1
  115. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/otel.cjs +0 -115
  116. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/otel.cjs.map +0 -1
  117. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/otel.js +0 -113
  118. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/singletons/otel.js.map +0 -1
  119. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/_uuid.cjs +0 -14
  120. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/_uuid.cjs.map +0 -1
  121. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/_uuid.js +0 -13
  122. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/_uuid.js.map +0 -1
  123. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/async_caller.cjs +0 -95
  124. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/async_caller.cjs.map +0 -1
  125. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/async_caller.js +0 -95
  126. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/async_caller.js.map +0 -1
  127. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.cjs +0 -136
  128. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.cjs.map +0 -1
  129. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.js +0 -131
  130. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/env.js.map +0 -1
  131. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.cjs +0 -102
  132. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.cjs.map +0 -1
  133. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.js +0 -99
  134. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/error.js.map +0 -1
  135. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/fast-safe-stringify/index.cjs +0 -140
  136. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/fast-safe-stringify/index.cjs.map +0 -1
  137. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/fast-safe-stringify/index.js +0 -140
  138. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/fast-safe-stringify/index.js.map +0 -1
  139. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/messages.cjs +0 -18
  140. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/messages.cjs.map +0 -1
  141. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/messages.js +0 -16
  142. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/messages.js.map +0 -1
  143. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/project.cjs +0 -10
  144. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/project.cjs.map +0 -1
  145. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/project.js +0 -10
  146. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/project.js.map +0 -1
  147. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/prompts.cjs +0 -30
  148. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/prompts.cjs.map +0 -1
  149. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/prompts.js +0 -30
  150. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/prompts.js.map +0 -1
  151. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/warn.cjs +0 -13
  152. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/warn.cjs.map +0 -1
  153. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/warn.js +0 -12
  154. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/dist/utils/warn.js.map +0 -1
  155. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/index.cjs +0 -6
  156. package/dist/node_modules/.pnpm/langsmith@0.3.74_@opentelemetry_api@1.9.0_openai@5.12.2_ws@8.18.3_bufferutil@4.0.9_utf-8-validate@6.0.5__zod@3.25.76_/node_modules/langsmith/index.js +0 -6
  157. package/dist/node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.cjs +0 -27
  158. package/dist/node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.cjs.map +0 -1
  159. package/dist/node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js +0 -23
  160. package/dist/node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js.map +0 -1
  161. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.cjs +0 -267
  162. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.cjs.map +0 -1
  163. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.js +0 -263
  164. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/index.js.map +0 -1
  165. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.cjs +0 -32
  166. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.cjs.map +0 -1
  167. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.js +0 -28
  168. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/lower-bound.js.map +0 -1
  169. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.cjs +0 -49
  170. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.cjs.map +0 -1
  171. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.js +0 -45
  172. package/dist/node_modules/.pnpm/p-queue@6.6.2/node_modules/p-queue/dist/priority-queue.js.map +0 -1
  173. package/dist/node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.cjs +0 -83
  174. package/dist/node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.cjs.map +0 -1
  175. package/dist/node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.js +0 -79
  176. package/dist/node_modules/.pnpm/p-retry@4.6.2/node_modules/p-retry/index.js.map +0 -1
  177. package/dist/node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.cjs +0 -52
  178. package/dist/node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.cjs.map +0 -1
  179. package/dist/node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js +0 -48
  180. package/dist/node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js.map +0 -1
  181. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.cjs +0 -16
  182. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.cjs.map +0 -1
  183. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js +0 -13
  184. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js.map +0 -1
  185. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.cjs +0 -77
  186. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.cjs.map +0 -1
  187. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js +0 -74
  188. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js.map +0 -1
  189. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.cjs +0 -115
  190. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.cjs.map +0 -1
  191. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js +0 -112
  192. package/dist/node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js.map +0 -1
  193. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.cjs +0 -90
  194. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.cjs.map +0 -1
  195. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js +0 -86
  196. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/comparator.js.map +0 -1
  197. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.cjs +0 -294
  198. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.cjs.map +0 -1
  199. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js +0 -290
  200. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/range.js.map +0 -1
  201. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.cjs +0 -191
  202. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.cjs.map +0 -1
  203. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js +0 -187
  204. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/classes/semver.js.map +0 -1
  205. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.cjs +0 -24
  206. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.cjs.map +0 -1
  207. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js +0 -20
  208. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/clean.js.map +0 -1
  209. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.cjs +0 -51
  210. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.cjs.map +0 -1
  211. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js +0 -47
  212. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/cmp.js.map +0 -1
  213. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.cjs +0 -48
  214. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.cjs.map +0 -1
  215. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js +0 -44
  216. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/coerce.js.map +0 -1
  217. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.cjs +0 -25
  218. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.cjs.map +0 -1
  219. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js +0 -21
  220. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-build.js.map +0 -1
  221. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.cjs +0 -21
  222. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.cjs.map +0 -1
  223. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js +0 -17
  224. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare-loose.js.map +0 -1
  225. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.cjs +0 -21
  226. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.cjs.map +0 -1
  227. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js +0 -17
  228. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/compare.js.map +0 -1
  229. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.cjs +0 -43
  230. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.cjs.map +0 -1
  231. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js +0 -39
  232. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/diff.js.map +0 -1
  233. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.cjs +0 -21
  234. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.cjs.map +0 -1
  235. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js +0 -17
  236. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/eq.js.map +0 -1
  237. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.cjs +0 -21
  238. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.cjs.map +0 -1
  239. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js +0 -17
  240. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gt.js.map +0 -1
  241. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.cjs +0 -21
  242. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.cjs.map +0 -1
  243. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js +0 -17
  244. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/gte.js.map +0 -1
  245. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.cjs +0 -32
  246. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.cjs.map +0 -1
  247. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js +0 -28
  248. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/inc.js.map +0 -1
  249. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.cjs +0 -21
  250. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.cjs.map +0 -1
  251. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js +0 -17
  252. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lt.js.map +0 -1
  253. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.cjs +0 -21
  254. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.cjs.map +0 -1
  255. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js +0 -17
  256. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/lte.js.map +0 -1
  257. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.cjs +0 -21
  258. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.cjs.map +0 -1
  259. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js +0 -17
  260. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/major.js.map +0 -1
  261. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.cjs +0 -21
  262. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.cjs.map +0 -1
  263. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js +0 -17
  264. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/minor.js.map +0 -1
  265. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.cjs +0 -21
  266. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.cjs.map +0 -1
  267. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js +0 -17
  268. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/neq.js.map +0 -1
  269. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.cjs +0 -29
  270. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.cjs.map +0 -1
  271. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js +0 -25
  272. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/parse.js.map +0 -1
  273. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.cjs +0 -21
  274. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.cjs.map +0 -1
  275. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js +0 -17
  276. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/patch.js.map +0 -1
  277. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.cjs +0 -24
  278. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.cjs.map +0 -1
  279. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js +0 -20
  280. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/prerelease.js.map +0 -1
  281. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.cjs +0 -21
  282. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.cjs.map +0 -1
  283. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js +0 -17
  284. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rcompare.js.map +0 -1
  285. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.cjs +0 -21
  286. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.cjs.map +0 -1
  287. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js +0 -17
  288. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/rsort.js.map +0 -1
  289. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.cjs +0 -28
  290. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.cjs.map +0 -1
  291. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js +0 -24
  292. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/satisfies.js.map +0 -1
  293. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.cjs +0 -21
  294. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.cjs.map +0 -1
  295. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js +0 -17
  296. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/sort.js.map +0 -1
  297. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.cjs +0 -24
  298. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.cjs.map +0 -1
  299. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js +0 -20
  300. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/functions/valid.js.map +0 -1
  301. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.cjs +0 -146
  302. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.cjs.map +0 -1
  303. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js +0 -142
  304. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/index.js.map +0 -1
  305. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.cjs +0 -41
  306. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.cjs.map +0 -1
  307. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js +0 -37
  308. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/constants.js.map +0 -1
  309. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.cjs +0 -19
  310. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.cjs.map +0 -1
  311. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js +0 -15
  312. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/debug.js.map +0 -1
  313. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.cjs +0 -32
  314. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.cjs.map +0 -1
  315. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js +0 -28
  316. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/identifiers.js.map +0 -1
  317. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.cjs +0 -47
  318. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.cjs.map +0 -1
  319. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js +0 -43
  320. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/lrucache.js.map +0 -1
  321. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.cjs +0 -25
  322. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.cjs.map +0 -1
  323. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js +0 -21
  324. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/parse-options.js.map +0 -1
  325. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.cjs +0 -94
  326. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.cjs.map +0 -1
  327. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js +0 -90
  328. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/internal/re.js.map +0 -1
  329. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.cjs +0 -21
  330. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.cjs.map +0 -1
  331. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js +0 -17
  332. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/gtr.js.map +0 -1
  333. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.cjs +0 -25
  334. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.cjs.map +0 -1
  335. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js +0 -21
  336. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/intersects.js.map +0 -1
  337. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.cjs +0 -21
  338. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.cjs.map +0 -1
  339. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js +0 -17
  340. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/ltr.js.map +0 -1
  341. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.cjs +0 -41
  342. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.cjs.map +0 -1
  343. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js +0 -37
  344. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/max-satisfying.js.map +0 -1
  345. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.cjs +0 -41
  346. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.cjs.map +0 -1
  347. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js +0 -37
  348. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-satisfying.js.map +0 -1
  349. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.cjs +0 -55
  350. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.cjs.map +0 -1
  351. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js +0 -51
  352. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/min-version.js.map +0 -1
  353. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.cjs +0 -74
  354. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.cjs.map +0 -1
  355. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js +0 -70
  356. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/outside.js.map +0 -1
  357. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.cjs +0 -48
  358. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.cjs.map +0 -1
  359. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js +0 -44
  360. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/simplify.js.map +0 -1
  361. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.cjs +0 -112
  362. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.cjs.map +0 -1
  363. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js +0 -108
  364. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/subset.js.map +0 -1
  365. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.cjs +0 -21
  366. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.cjs.map +0 -1
  367. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js +0 -17
  368. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/to-comparators.js.map +0 -1
  369. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.cjs +0 -27
  370. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.cjs.map +0 -1
  371. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js +0 -23
  372. package/dist/node_modules/.pnpm/semver@7.7.2/node_modules/semver/ranges/valid.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"AgentNode.cjs","names":["RunnableCallable","options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","model: string | LanguageModelLike","transformResponseFormat","ProviderStrategy","ToolStrategy","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","ToolMessage","#invokeModel","Command","#areMoreStepsNeeded","AIMessage","initChatModel","options: {\n lastMessage?: string;\n }","#deriveModel","request: ModelRequest","validateLLMHasNoBoundTools","#getResponseFormat","#bindTools","#getModelInputState","mergeAbortSignals","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>>","request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","runtime: Runtime<unknown>","requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","req: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","isClientTool","initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n unknown\n >","response: AIMessage","toolCalls: ToolCall[]","responseFormat: ToolResponseFormat","MultipleStructuredOutputsError","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","hasToolCalls","model: LanguageModelLike","preparedOptions: ModelRequest | undefined","structuredResponseFormat: ResponseFormat | undefined","options: Partial<BaseChatModelCallOptions>","hasSupportForJsonSchemaOutput","bindTools","getPromptRunnable","withAgentName"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseMessage, AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n interopParse,\n interopZodObjectPartial,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { PreHookAnnotation } from \"../annotation.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n isClientTool,\n} from \"../utils.js\";\nimport { mergeAbortSignals } from \"../nodes/utils.js\";\nimport { CreateAgentParams } from \"../types.js\";\nimport type { InternalAgentState, Runtime } from \"../runtime.js\";\nimport type {\n AgentMiddleware,\n AnyAnnotationRoot,\n WrapModelCallHandler,\n} from \"../middleware/types.js\";\nimport type { ModelRequest } from \"./types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n hasSupportForJsonSchemaOutput,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\n/**\n * Wrap the base handler with middleware wrapModelCall hooks\n * Middleware are composed so the first middleware is the outermost wrapper\n * Example: [auth, retry, cache] means auth wraps retry wraps cache wraps baseHandler\n */\ntype InternalModelResponse<StructuredResponseFormat> =\n | AIMessage\n | ResponseHandlerResult<StructuredResponseFormat>;\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema>,\n | \"model\"\n | \"systemPrompt\"\n | \"includeAgentName\"\n | \"name\"\n | \"responseFormat\"\n | \"middleware\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n wrapModelCallHookMiddleware?: [\n AgentMiddleware,\n () => Record<string, unknown>\n ][];\n}\n\ninterface NativeResponseFormat {\n type: \"native\";\n strategy: ProviderStrategy;\n}\n\ninterface ToolResponseFormat {\n type: \"tool\";\n tools: Record<string, ToolStrategy>;\n}\n\ntype ResponseFormat = NativeResponseFormat | ToolResponseFormat;\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n | (\n | { messages: BaseMessage[] }\n | { structuredResponse: StructuredResponseFormat }\n )\n | Command\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) => this.#run(input, config as RunnableConfig),\n });\n\n this.#options = options;\n }\n\n /**\n * Returns response format primtivies based on given model and response format provided by the user.\n *\n * If the the user selects a tool output:\n * - return a record of tools to extract structured output from the model's response\n *\n * if the the user selects a native schema output or if the model supports JSON schema output:\n * - return a provider strategy to extract structured output from the model's response\n *\n * @param model - The model to get the response format for.\n * @returns The response format.\n */\n #getResponseFormat(\n model: string | LanguageModelLike\n ): ResponseFormat | undefined {\n if (!this.#options.responseFormat) {\n return undefined;\n }\n\n const strategies = transformResponseFormat(\n this.#options.responseFormat,\n undefined,\n model\n );\n\n /**\n * we either define a list of provider strategies or a list of tool strategies\n */\n const isProviderStrategy = strategies.every(\n (format) => format instanceof ProviderStrategy\n );\n\n /**\n * Populate a list of structured tool info.\n */\n if (!isProviderStrategy) {\n return {\n type: \"tool\",\n tools: (\n strategies.filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>),\n };\n }\n\n return {\n type: \"native\",\n /**\n * there can only be one provider strategy\n */\n strategy: strategies[0] as ProviderStrategy,\n };\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel() {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n if (this.#options.model) {\n return this.#options.model;\n }\n\n throw new Error(\"No model option was provided, either via `model` option.\");\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel();\n const lgConfig = config as LangGraphRunnableConfig;\n\n /**\n * Create the base handler that performs the actual model invocation\n */\n const baseHandler = async (\n request: ModelRequest\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> => {\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(request.model);\n\n const structuredResponseFormat = this.#getResponseFormat(request.model);\n const modelWithTools = await this.#bindTools(\n request.model,\n request,\n structuredResponseFormat\n );\n\n let modelInput = this.#getModelInputState(state);\n modelInput = { ...modelInput, messages: request.messages };\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = { ...config, signal };\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (structuredResponseFormat?.type === \"native\") {\n const structuredResponse =\n structuredResponseFormat.strategy.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n\n return response;\n }\n\n if (!structuredResponseFormat || !response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in structuredResponseFormat.tools\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(\n response,\n toolCalls,\n structuredResponseFormat\n );\n }\n\n const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n structuredResponseFormat,\n toolMessageContent ?? options.lastMessage\n );\n };\n\n const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? [];\n let wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>> = baseHandler;\n\n /**\n * Build composed handler from last to first so first middleware becomes outermost\n */\n for (let i = wrapperMiddleware.length - 1; i >= 0; i--) {\n const [middleware, getMiddlewareState] = wrapperMiddleware[i];\n if (middleware.wrapModelCall) {\n const innerHandler = wrappedHandler;\n const currentMiddleware = middleware;\n const currentGetState = getMiddlewareState;\n\n wrappedHandler = async (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Merge context with default context of middleware\n */\n const context = currentMiddleware.contextSchema\n ? interopParse(\n currentMiddleware.contextSchema,\n lgConfig?.context || {}\n )\n : lgConfig?.context;\n\n /**\n * Create runtime\n */\n const runtime: Runtime<unknown> = Object.freeze({\n context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n });\n\n /**\n * Create the request with state and runtime\n */\n const requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n > = {\n ...request,\n state: {\n ...(middleware.stateSchema\n ? interopParse(\n interopZodObjectPartial(middleware.stateSchema),\n state\n )\n : {}),\n ...currentGetState(),\n messages: state.messages,\n } as InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n runtime,\n };\n\n /**\n * Create handler that validates tools and calls the inner handler\n */\n const handlerWithValidation = async (\n req: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Verify that the user didn't add any new tools.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const modifiedTools = req.tools ?? [];\n const newTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n !this.#options.toolClasses.some((t) => t.name === tool.name)\n );\n if (newTools.length > 0) {\n throw new Error(\n `You have added a new tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${newTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n /**\n * Verify that user has not added or modified a tool with the same name.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const invalidTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n this.#options.toolClasses.every((t) => t !== tool)\n );\n if (invalidTools.length > 0) {\n throw new Error(\n `You have modified a tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${invalidTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n return innerHandler(req);\n };\n\n // Call middleware's wrapModelCall with the validation handler\n if (!currentMiddleware.wrapModelCall) {\n return handlerWithValidation(requestWithStateAndRuntime);\n }\n\n try {\n const middlewareResponse = await currentMiddleware.wrapModelCall(\n requestWithStateAndRuntime,\n handlerWithValidation as WrapModelCallHandler\n );\n\n /**\n * Validate that this specific middleware returned a valid AIMessage\n */\n if (!AIMessage.isInstance(middlewareResponse)) {\n throw new Error(\n `Invalid response from \"wrapModelCall\" in middleware \"${\n currentMiddleware.name\n }\": expected AIMessage, got ${typeof middlewareResponse}`\n );\n }\n\n return middlewareResponse;\n } catch (error) {\n // Add middleware context to error if not already added\n if (\n error instanceof Error &&\n !error.message.includes(`middleware \"${currentMiddleware.name}\"`)\n ) {\n error.message = `Error in middleware \"${currentMiddleware.name}\": ${error.message}`;\n }\n throw error;\n }\n };\n }\n }\n\n /**\n * Execute the wrapped handler with the initial request\n */\n const initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n unknown\n > = {\n model,\n systemPrompt: this.#options.systemPrompt,\n messages: state.messages,\n tools: this.#options.toolClasses,\n state,\n runtime: Object.freeze({\n context: lgConfig?.context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n }) as Runtime<unknown>,\n };\n\n return wrappedHandler(initialRequest);\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[],\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0],\n responseFormat\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = responseFormat.tools[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new ToolMessage({\n tool_call_id: toolCall.id ?? \"\",\n content: JSON.stringify(structuredResponse),\n name: toolCall.name,\n }),\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall,\n responseFormat\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(responseFormat.tools).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages.at(-1))))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions: ModelRequest | undefined,\n structuredResponseFormat: ResponseFormat | undefined\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(\n structuredResponseFormat && \"tools\" in structuredResponseFormat\n ? structuredResponseFormat.tools\n : {}\n );\n\n /**\n * Use tools from preparedOptions if provided, otherwise use default tools\n */\n const allTools = [\n ...(preparedOptions?.tools ?? this.#options.toolClasses),\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ];\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (structuredResponseFormat?.type === \"native\") {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: structuredResponseFormat.strategy.schema?.name ?? \"extract\",\n description: getSchemaDescription(\n structuredResponseFormat.strategy.schema\n ),\n schema: structuredResponseFormat.strategy.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: structuredResponseFormat.strategy.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n ...(preparedOptions?.modelSettings ?? {}),\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(\n preparedOptions?.systemPrompt ?? this.#options.systemPrompt\n ).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n\n getState(): {\n messages: BaseMessage[];\n } {\n const state = super.getState();\n const origState = state && !(state instanceof Command) ? state : {};\n\n return {\n messages: [],\n ...origState,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAiGA,IAAa,YAAb,cAMUA,0CAOR;CACA;CAEA,YACEC,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WAAW,KAAKC,KAAK,OAAO,OAAyB;EACpE,EAAC;EAEF,KAAKC,WAAW;CACjB;;;;;;;;;;;;;CAcD,mBACEC,OAC4B;AAC5B,MAAI,CAAC,KAAKD,SAAS,eACjB,QAAO;EAGT,MAAM,aAAaE,0CACjB,KAAKF,SAAS,gBACd,QACA,MACD;;;;EAKD,MAAM,qBAAqB,WAAW,MACpC,CAAC,WAAW,kBAAkBG,mCAC/B;;;;AAKD,MAAI,CAAC,mBACH,QAAO;GACL,MAAM;GACN,OACE,WAAW,OACT,CAAC,WAAW,kBAAkBC,+BAC/B,CACD,OAAO,CAAC,KAAK,WAAW;IACxB,IAAI,OAAO,QAAQ;AACnB,WAAO;GACR,GAAE,CAAE,EAAiC;EACvC;AAGH,SAAO;GACL,MAAM;GAIN,UAAU,WAAW;EACtB;CACF;CAED,MAAML,KACJM,OAEAC,QACA;;;;;EAKA,MAAM,cAAc,MAAM,SAAS,GAAG,GAAG;AACzC,MACE,eACAC,sCAAY,WAAW,YAAY,IACnC,YAAY,QACZ,KAAKP,SAAS,mBAAmB,IAAI,YAAY,KAAK;;;;AAKtD,SAAO,EAAE,UAAU,CAAE,EAAE;EAGzB,MAAM,WAAW,MAAM,KAAKQ,aAAa,OAAO,OAAO;;;;AAKvD,MAAI,wBAAwB,SAC1B,QAAO;GACL,UAAU,CAAC,GAAG,MAAM,UAAU,GAAI,SAAS,YAAY,CAAE,CAAE;GAC3D,oBAAoB,SAAS;EAC9B;;;;AAMH,M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;IAC1C,QAAQ;GACT;GAED,OAAO,OAAO,SAAS;IACrB,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,cAAe;KACjC,QAAQ,yBAAyB,SAAS;IAC3C;IACD,QAAQ;GACT,EAAC;EACH;;;;EAKD,MAAM,iBAAiB,MAAMC,wBAAU,OAAO,UAAU;GACtD,GAAG;GACH,GAAI,iBAAiB,iBAAiB,CAAE;GACxC,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgBC,gCACpB,iBAAiB,gBAAgB,KAAK9C,SAAS,aAChD,CAAC,KACA,KAAKA,SAAS,qBAAqB,WAC/B+C,oCAAc,gBAAgB,KAAK/C,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;CAED,WAEE;EACA,MAAM,QAAQ,MAAM,UAAU;EAC9B,MAAM,YAAY,SAAS,EAAE,iBAAiBS,iCAAW,QAAQ,CAAE;AAEnE,SAAO;GACL,UAAU,CAAE;GACZ,GAAG;EACJ;CACF;AACF"}
1
+ {"version":3,"file":"AgentNode.cjs","names":["RunnableCallable","options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","model: string | LanguageModelLike","transformResponseFormat","ProviderStrategy","ToolStrategy","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","ToolMessage","#invokeModel","Command","#areMoreStepsNeeded","AIMessage","initChatModel","options: {\n lastMessage?: string;\n }","#deriveModel","request: ModelRequest","validateLLMHasNoBoundTools","#getResponseFormat","#bindTools","#getModelInputState","mergeAbortSignals","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>>","request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","runtime: Runtime<unknown>","requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","req: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","isClientTool","initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n unknown\n >","response: AIMessage","toolCalls: ToolCall[]","responseFormat: ToolResponseFormat","MultipleStructuredOutputsError","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","hasToolCalls","model: LanguageModelLike","preparedOptions: ModelRequest | undefined","structuredResponseFormat: ResponseFormat | undefined","options: Partial<BaseChatModelCallOptions>","bindTools","getPromptRunnable","withAgentName"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseMessage, AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n interopParse,\n interopZodObjectPartial,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { PreHookAnnotation } from \"../annotation.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n isClientTool,\n} from \"../utils.js\";\nimport { mergeAbortSignals } from \"../nodes/utils.js\";\nimport { CreateAgentParams } from \"../types.js\";\nimport type { InternalAgentState, Runtime } from \"../runtime.js\";\nimport type {\n AgentMiddleware,\n AnyAnnotationRoot,\n WrapModelCallHandler,\n} from \"../middleware/types.js\";\nimport type { ModelRequest } from \"./types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\n/**\n * Wrap the base handler with middleware wrapModelCall hooks\n * Middleware are composed so the first middleware is the outermost wrapper\n * Example: [auth, retry, cache] means auth wraps retry wraps cache wraps baseHandler\n */\ntype InternalModelResponse<StructuredResponseFormat> =\n | AIMessage\n | ResponseHandlerResult<StructuredResponseFormat>;\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema>,\n | \"model\"\n | \"systemPrompt\"\n | \"includeAgentName\"\n | \"name\"\n | \"responseFormat\"\n | \"middleware\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n wrapModelCallHookMiddleware?: [\n AgentMiddleware,\n () => Record<string, unknown>\n ][];\n}\n\ninterface NativeResponseFormat {\n type: \"native\";\n strategy: ProviderStrategy;\n}\n\ninterface ToolResponseFormat {\n type: \"tool\";\n tools: Record<string, ToolStrategy>;\n}\n\ntype ResponseFormat = NativeResponseFormat | ToolResponseFormat;\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n | (\n | { messages: BaseMessage[] }\n | { structuredResponse: StructuredResponseFormat }\n )\n | Command\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) => this.#run(input, config as RunnableConfig),\n });\n\n this.#options = options;\n }\n\n /**\n * Returns response format primtivies based on given model and response format provided by the user.\n *\n * If the the user selects a tool output:\n * - return a record of tools to extract structured output from the model's response\n *\n * if the the user selects a native schema output or if the model supports JSON schema output:\n * - return a provider strategy to extract structured output from the model's response\n *\n * @param model - The model to get the response format for.\n * @returns The response format.\n */\n #getResponseFormat(\n model: string | LanguageModelLike\n ): ResponseFormat | undefined {\n if (!this.#options.responseFormat) {\n return undefined;\n }\n\n const strategies = transformResponseFormat(\n this.#options.responseFormat,\n undefined,\n model\n );\n\n /**\n * we either define a list of provider strategies or a list of tool strategies\n */\n const isProviderStrategy = strategies.every(\n (format) => format instanceof ProviderStrategy\n );\n\n /**\n * Populate a list of structured tool info.\n */\n if (!isProviderStrategy) {\n return {\n type: \"tool\",\n tools: (\n strategies.filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>),\n };\n }\n\n return {\n type: \"native\",\n /**\n * there can only be one provider strategy\n */\n strategy: strategies[0] as ProviderStrategy,\n };\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel() {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n if (this.#options.model) {\n return this.#options.model;\n }\n\n throw new Error(\"No model option was provided, either via `model` option.\");\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel();\n const lgConfig = config as LangGraphRunnableConfig;\n\n /**\n * Create the base handler that performs the actual model invocation\n */\n const baseHandler = async (\n request: ModelRequest\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> => {\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(request.model);\n\n const structuredResponseFormat = this.#getResponseFormat(request.model);\n const modelWithTools = await this.#bindTools(\n request.model,\n request,\n structuredResponseFormat\n );\n\n let modelInput = this.#getModelInputState(state);\n modelInput = { ...modelInput, messages: request.messages };\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = { ...config, signal };\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (structuredResponseFormat?.type === \"native\") {\n const structuredResponse =\n structuredResponseFormat.strategy.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n\n return response;\n }\n\n if (!structuredResponseFormat || !response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in structuredResponseFormat.tools\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(\n response,\n toolCalls,\n structuredResponseFormat\n );\n }\n\n const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n structuredResponseFormat,\n toolMessageContent ?? options.lastMessage\n );\n };\n\n const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? [];\n let wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>> = baseHandler;\n\n /**\n * Build composed handler from last to first so first middleware becomes outermost\n */\n for (let i = wrapperMiddleware.length - 1; i >= 0; i--) {\n const [middleware, getMiddlewareState] = wrapperMiddleware[i];\n if (middleware.wrapModelCall) {\n const innerHandler = wrappedHandler;\n const currentMiddleware = middleware;\n const currentGetState = getMiddlewareState;\n\n wrappedHandler = async (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Merge context with default context of middleware\n */\n const context = currentMiddleware.contextSchema\n ? interopParse(\n currentMiddleware.contextSchema,\n lgConfig?.context || {}\n )\n : lgConfig?.context;\n\n /**\n * Create runtime\n */\n const runtime: Runtime<unknown> = Object.freeze({\n context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n });\n\n /**\n * Create the request with state and runtime\n */\n const requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n > = {\n ...request,\n state: {\n ...(middleware.stateSchema\n ? interopParse(\n interopZodObjectPartial(middleware.stateSchema),\n state\n )\n : {}),\n ...currentGetState(),\n messages: state.messages,\n } as InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n runtime,\n };\n\n /**\n * Create handler that validates tools and calls the inner handler\n */\n const handlerWithValidation = async (\n req: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Verify that the user didn't add any new tools.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const modifiedTools = req.tools ?? [];\n const newTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n !this.#options.toolClasses.some((t) => t.name === tool.name)\n );\n if (newTools.length > 0) {\n throw new Error(\n `You have added a new tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${newTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n /**\n * Verify that user has not added or modified a tool with the same name.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const invalidTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n this.#options.toolClasses.every((t) => t !== tool)\n );\n if (invalidTools.length > 0) {\n throw new Error(\n `You have modified a tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${invalidTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n return innerHandler(req);\n };\n\n // Call middleware's wrapModelCall with the validation handler\n if (!currentMiddleware.wrapModelCall) {\n return handlerWithValidation(requestWithStateAndRuntime);\n }\n\n try {\n const middlewareResponse = await currentMiddleware.wrapModelCall(\n requestWithStateAndRuntime,\n handlerWithValidation as WrapModelCallHandler\n );\n\n /**\n * Validate that this specific middleware returned a valid AIMessage\n */\n if (!AIMessage.isInstance(middlewareResponse)) {\n throw new Error(\n `Invalid response from \"wrapModelCall\" in middleware \"${\n currentMiddleware.name\n }\": expected AIMessage, got ${typeof middlewareResponse}`\n );\n }\n\n return middlewareResponse;\n } catch (error) {\n // Add middleware context to error if not already added\n if (\n error instanceof Error &&\n !error.message.includes(`middleware \"${currentMiddleware.name}\"`)\n ) {\n error.message = `Error in middleware \"${currentMiddleware.name}\": ${error.message}`;\n }\n throw error;\n }\n };\n }\n }\n\n /**\n * Execute the wrapped handler with the initial request\n */\n const initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n unknown\n > = {\n model,\n systemPrompt: this.#options.systemPrompt,\n messages: state.messages,\n tools: this.#options.toolClasses,\n state,\n runtime: Object.freeze({\n context: lgConfig?.context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n }) as Runtime<unknown>,\n };\n\n return wrappedHandler(initialRequest);\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[],\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0],\n responseFormat\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = responseFormat.tools[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new ToolMessage({\n tool_call_id: toolCall.id ?? \"\",\n content: JSON.stringify(structuredResponse),\n name: toolCall.name,\n }),\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall,\n responseFormat\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(responseFormat.tools).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages.at(-1))))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions: ModelRequest | undefined,\n structuredResponseFormat: ResponseFormat | undefined\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(\n structuredResponseFormat && \"tools\" in structuredResponseFormat\n ? structuredResponseFormat.tools\n : {}\n );\n\n /**\n * Use tools from preparedOptions if provided, otherwise use default tools\n */\n const allTools = [\n ...(preparedOptions?.tools ?? this.#options.toolClasses),\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ];\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (structuredResponseFormat?.type === \"native\") {\n const jsonSchemaParams = {\n name: structuredResponseFormat.strategy.schema?.name ?? \"extract\",\n description: getSchemaDescription(\n structuredResponseFormat.strategy.schema\n ),\n schema: structuredResponseFormat.strategy.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: structuredResponseFormat.strategy.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n ...(preparedOptions?.modelSettings ?? {}),\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(\n preparedOptions?.systemPrompt ?? this.#options.systemPrompt\n ).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n\n getState(): {\n messages: BaseMessage[];\n } {\n const state = super.getState();\n const origState = state && !(state instanceof Command) ? state : {};\n\n return {\n messages: [],\n ...origState,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgGA,IAAa,YAAb,cAMUA,0CAOR;CACA;CAEA,YACEC,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WAAW,KAAKC,KAAK,OAAO,OAAyB;EACpE,EAAC;EAEF,KAAKC,WAAW;CACjB;;;;;;;;;;;;;CAcD,mBACEC,OAC4B;AAC5B,MAAI,CAAC,KAAKD,SAAS,eACjB,QAAO;EA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UAAU;EAC9B,MAAM,YAAY,SAAS,EAAE,iBAAiBS,iCAAW,QAAQ,CAAE;AAEnE,SAAO;GACL,UAAU,CAAE;GACZ,GAAG;EACJ;CACF;AACF"}
@@ -4,7 +4,7 @@ import { bindTools, getPromptRunnable, hasToolCalls, isClientTool, validateLLMHa
4
4
  import { RunnableCallable } from "../RunnableCallable.js";
5
5
  import { mergeAbortSignals } from "./utils.js";
6
6
  import { withAgentName } from "../withAgentName.js";
7
- import { ProviderStrategy, ToolStrategy, hasSupportForJsonSchemaOutput, transformResponseFormat } from "../responses.js";
7
+ import { ProviderStrategy, ToolStrategy, transformResponseFormat } from "../responses.js";
8
8
  import { AIMessage, ToolMessage } from "@langchain/core/messages";
9
9
  import { Command } from "@langchain/langgraph";
10
10
  import { getSchemaDescription, interopParse, interopZodObjectPartial } from "@langchain/core/utils/types";
@@ -353,10 +353,6 @@ var AgentNode = class extends RunnableCallable {
353
353
  * check if the user requests a native schema output
354
354
  */
355
355
  if (structuredResponseFormat?.type === "native") {
356
- /**
357
- * if the model does not support JSON schema output, throw an error
358
- */
359
- if (!hasSupportForJsonSchemaOutput(model)) throw new Error("Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.");
360
356
  const jsonSchemaParams = {
361
357
  name: structuredResponseFormat.strategy.schema?.name ?? "extract",
362
358
  description: getSchemaDescription(structuredResponseFormat.strategy.schema),
@@ -1 +1 @@
1
- {"version":3,"file":"AgentNode.js","names":["options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","model: string | LanguageModelLike","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","#invokeModel","#areMoreStepsNeeded","options: {\n lastMessage?: string;\n }","#deriveModel","request: ModelRequest","#getResponseFormat","#bindTools","#getModelInputState","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>>","request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","runtime: Runtime<unknown>","requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","req: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n unknown\n >","response: AIMessage","toolCalls: ToolCall[]","responseFormat: ToolResponseFormat","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","model: LanguageModelLike","preparedOptions: ModelRequest | undefined","structuredResponseFormat: ResponseFormat | undefined","options: Partial<BaseChatModelCallOptions>"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseMessage, AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n interopParse,\n interopZodObjectPartial,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { PreHookAnnotation } from \"../annotation.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n isClientTool,\n} from \"../utils.js\";\nimport { mergeAbortSignals } from \"../nodes/utils.js\";\nimport { CreateAgentParams } from \"../types.js\";\nimport type { InternalAgentState, Runtime } from \"../runtime.js\";\nimport type {\n AgentMiddleware,\n AnyAnnotationRoot,\n WrapModelCallHandler,\n} from \"../middleware/types.js\";\nimport type { ModelRequest } from \"./types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n hasSupportForJsonSchemaOutput,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\n/**\n * Wrap the base handler with middleware wrapModelCall hooks\n * Middleware are composed so the first middleware is the outermost wrapper\n * Example: [auth, retry, cache] means auth wraps retry wraps cache wraps baseHandler\n */\ntype InternalModelResponse<StructuredResponseFormat> =\n | AIMessage\n | ResponseHandlerResult<StructuredResponseFormat>;\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema>,\n | \"model\"\n | \"systemPrompt\"\n | \"includeAgentName\"\n | \"name\"\n | \"responseFormat\"\n | \"middleware\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n wrapModelCallHookMiddleware?: [\n AgentMiddleware,\n () => Record<string, unknown>\n ][];\n}\n\ninterface NativeResponseFormat {\n type: \"native\";\n strategy: ProviderStrategy;\n}\n\ninterface ToolResponseFormat {\n type: \"tool\";\n tools: Record<string, ToolStrategy>;\n}\n\ntype ResponseFormat = NativeResponseFormat | ToolResponseFormat;\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n | (\n | { messages: BaseMessage[] }\n | { structuredResponse: StructuredResponseFormat }\n )\n | Command\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) => this.#run(input, config as RunnableConfig),\n });\n\n this.#options = options;\n }\n\n /**\n * Returns response format primtivies based on given model and response format provided by the user.\n *\n * If the the user selects a tool output:\n * - return a record of tools to extract structured output from the model's response\n *\n * if the the user selects a native schema output or if the model supports JSON schema output:\n * - return a provider strategy to extract structured output from the model's response\n *\n * @param model - The model to get the response format for.\n * @returns The response format.\n */\n #getResponseFormat(\n model: string | LanguageModelLike\n ): ResponseFormat | undefined {\n if (!this.#options.responseFormat) {\n return undefined;\n }\n\n const strategies = transformResponseFormat(\n this.#options.responseFormat,\n undefined,\n model\n );\n\n /**\n * we either define a list of provider strategies or a list of tool strategies\n */\n const isProviderStrategy = strategies.every(\n (format) => format instanceof ProviderStrategy\n );\n\n /**\n * Populate a list of structured tool info.\n */\n if (!isProviderStrategy) {\n return {\n type: \"tool\",\n tools: (\n strategies.filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>),\n };\n }\n\n return {\n type: \"native\",\n /**\n * there can only be one provider strategy\n */\n strategy: strategies[0] as ProviderStrategy,\n };\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel() {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n if (this.#options.model) {\n return this.#options.model;\n }\n\n throw new Error(\"No model option was provided, either via `model` option.\");\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel();\n const lgConfig = config as LangGraphRunnableConfig;\n\n /**\n * Create the base handler that performs the actual model invocation\n */\n const baseHandler = async (\n request: ModelRequest\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> => {\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(request.model);\n\n const structuredResponseFormat = this.#getResponseFormat(request.model);\n const modelWithTools = await this.#bindTools(\n request.model,\n request,\n structuredResponseFormat\n );\n\n let modelInput = this.#getModelInputState(state);\n modelInput = { ...modelInput, messages: request.messages };\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = { ...config, signal };\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (structuredResponseFormat?.type === \"native\") {\n const structuredResponse =\n structuredResponseFormat.strategy.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n\n return response;\n }\n\n if (!structuredResponseFormat || !response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in structuredResponseFormat.tools\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(\n response,\n toolCalls,\n structuredResponseFormat\n );\n }\n\n const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n structuredResponseFormat,\n toolMessageContent ?? options.lastMessage\n );\n };\n\n const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? [];\n let wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>> = baseHandler;\n\n /**\n * Build composed handler from last to first so first middleware becomes outermost\n */\n for (let i = wrapperMiddleware.length - 1; i >= 0; i--) {\n const [middleware, getMiddlewareState] = wrapperMiddleware[i];\n if (middleware.wrapModelCall) {\n const innerHandler = wrappedHandler;\n const currentMiddleware = middleware;\n const currentGetState = getMiddlewareState;\n\n wrappedHandler = async (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Merge context with default context of middleware\n */\n const context = currentMiddleware.contextSchema\n ? interopParse(\n currentMiddleware.contextSchema,\n lgConfig?.context || {}\n )\n : lgConfig?.context;\n\n /**\n * Create runtime\n */\n const runtime: Runtime<unknown> = Object.freeze({\n context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n });\n\n /**\n * Create the request with state and runtime\n */\n const requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n > = {\n ...request,\n state: {\n ...(middleware.stateSchema\n ? interopParse(\n interopZodObjectPartial(middleware.stateSchema),\n state\n )\n : {}),\n ...currentGetState(),\n messages: state.messages,\n } as InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n runtime,\n };\n\n /**\n * Create handler that validates tools and calls the inner handler\n */\n const handlerWithValidation = async (\n req: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Verify that the user didn't add any new tools.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const modifiedTools = req.tools ?? [];\n const newTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n !this.#options.toolClasses.some((t) => t.name === tool.name)\n );\n if (newTools.length > 0) {\n throw new Error(\n `You have added a new tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${newTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n /**\n * Verify that user has not added or modified a tool with the same name.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const invalidTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n this.#options.toolClasses.every((t) => t !== tool)\n );\n if (invalidTools.length > 0) {\n throw new Error(\n `You have modified a tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${invalidTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n return innerHandler(req);\n };\n\n // Call middleware's wrapModelCall with the validation handler\n if (!currentMiddleware.wrapModelCall) {\n return handlerWithValidation(requestWithStateAndRuntime);\n }\n\n try {\n const middlewareResponse = await currentMiddleware.wrapModelCall(\n requestWithStateAndRuntime,\n handlerWithValidation as WrapModelCallHandler\n );\n\n /**\n * Validate that this specific middleware returned a valid AIMessage\n */\n if (!AIMessage.isInstance(middlewareResponse)) {\n throw new Error(\n `Invalid response from \"wrapModelCall\" in middleware \"${\n currentMiddleware.name\n }\": expected AIMessage, got ${typeof middlewareResponse}`\n );\n }\n\n return middlewareResponse;\n } catch (error) {\n // Add middleware context to error if not already added\n if (\n error instanceof Error &&\n !error.message.includes(`middleware \"${currentMiddleware.name}\"`)\n ) {\n error.message = `Error in middleware \"${currentMiddleware.name}\": ${error.message}`;\n }\n throw error;\n }\n };\n }\n }\n\n /**\n * Execute the wrapped handler with the initial request\n */\n const initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n unknown\n > = {\n model,\n systemPrompt: this.#options.systemPrompt,\n messages: state.messages,\n tools: this.#options.toolClasses,\n state,\n runtime: Object.freeze({\n context: lgConfig?.context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n }) as Runtime<unknown>,\n };\n\n return wrappedHandler(initialRequest);\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[],\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0],\n responseFormat\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = responseFormat.tools[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new ToolMessage({\n tool_call_id: toolCall.id ?? \"\",\n content: JSON.stringify(structuredResponse),\n name: toolCall.name,\n }),\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall,\n responseFormat\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(responseFormat.tools).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages.at(-1))))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions: ModelRequest | undefined,\n structuredResponseFormat: ResponseFormat | undefined\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(\n structuredResponseFormat && \"tools\" in structuredResponseFormat\n ? structuredResponseFormat.tools\n : {}\n );\n\n /**\n * Use tools from preparedOptions if provided, otherwise use default tools\n */\n const allTools = [\n ...(preparedOptions?.tools ?? this.#options.toolClasses),\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ];\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (structuredResponseFormat?.type === \"native\") {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: structuredResponseFormat.strategy.schema?.name ?? \"extract\",\n description: getSchemaDescription(\n structuredResponseFormat.strategy.schema\n ),\n schema: structuredResponseFormat.strategy.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: structuredResponseFormat.strategy.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n ...(preparedOptions?.modelSettings ?? {}),\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(\n preparedOptions?.systemPrompt ?? this.#options.systemPrompt\n ).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n\n getState(): {\n messages: BaseMessage[];\n } {\n const state = super.getState();\n const origState = state && !(state instanceof Command) ? state : {};\n\n return {\n messages: [],\n ...origState,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;AAiGA,IAAa,YAAb,cAMU,iBAOR;CACA;CAEA,YACEA,SACA;EACA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Aa;EACd,EAAC;;;;EAKF,MAAM,gBAAgB,kBACpB,iBAAiB,gBAAgB,KAAKA,SAAS,aAChD,CAAC,KACA,KAAKA,SAAS,qBAAqB,WAC/B,cAAc,gBAAgB,KAAKA,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;CAED,WAEE;EACA,MAAM,QAAQ,MAAM,UAAU;EAC9B,MAAM,YAAY,SAAS,EAAE,iBAAiB,WAAW,QAAQ,CAAE;AAEnE,SAAO;GACL,UAAU,CAAE;GACZ,GAAG;EACJ;CACF;AACF"}
1
+ {"version":3,"file":"AgentNode.js","names":["options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","model: string | LanguageModelLike","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","#invokeModel","#areMoreStepsNeeded","options: {\n lastMessage?: string;\n }","#deriveModel","request: ModelRequest","#getResponseFormat","#bindTools","#getModelInputState","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>>","request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","runtime: Runtime<unknown>","requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","req: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >","initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n unknown\n >","response: AIMessage","toolCalls: ToolCall[]","responseFormat: ToolResponseFormat","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","response: BaseMessage","model: LanguageModelLike","preparedOptions: ModelRequest | undefined","structuredResponseFormat: ResponseFormat | undefined","options: Partial<BaseChatModelCallOptions>"],"sources":["../../../src/agents/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport { BaseMessage, AIMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n interopParse,\n interopZodObjectPartial,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../errors.js\";\nimport { RunnableCallable } from \"../RunnableCallable.js\";\nimport { PreHookAnnotation } from \"../annotation.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n isClientTool,\n} from \"../utils.js\";\nimport { mergeAbortSignals } from \"../nodes/utils.js\";\nimport { CreateAgentParams } from \"../types.js\";\nimport type { InternalAgentState, Runtime } from \"../runtime.js\";\nimport type {\n AgentMiddleware,\n AnyAnnotationRoot,\n WrapModelCallHandler,\n} from \"../middleware/types.js\";\nimport type { ModelRequest } from \"./types.js\";\nimport { withAgentName } from \"../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../responses.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\n/**\n * Wrap the base handler with middleware wrapModelCall hooks\n * Middleware are composed so the first middleware is the outermost wrapper\n * Example: [auth, retry, cache] means auth wraps retry wraps cache wraps baseHandler\n */\ntype InternalModelResponse<StructuredResponseFormat> =\n | AIMessage\n | ResponseHandlerResult<StructuredResponseFormat>;\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, StateSchema, ContextSchema>,\n | \"model\"\n | \"systemPrompt\"\n | \"includeAgentName\"\n | \"name\"\n | \"responseFormat\"\n | \"middleware\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n wrapModelCallHookMiddleware?: [\n AgentMiddleware,\n () => Record<string, unknown>\n ][];\n}\n\ninterface NativeResponseFormat {\n type: \"native\";\n strategy: ProviderStrategy;\n}\n\ninterface ToolResponseFormat {\n type: \"tool\";\n tools: Record<string, ToolStrategy>;\n}\n\ntype ResponseFormat = NativeResponseFormat | ToolResponseFormat;\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n | (\n | { messages: BaseMessage[] }\n | { structuredResponse: StructuredResponseFormat }\n )\n | Command\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) => this.#run(input, config as RunnableConfig),\n });\n\n this.#options = options;\n }\n\n /**\n * Returns response format primtivies based on given model and response format provided by the user.\n *\n * If the the user selects a tool output:\n * - return a record of tools to extract structured output from the model's response\n *\n * if the the user selects a native schema output or if the model supports JSON schema output:\n * - return a provider strategy to extract structured output from the model's response\n *\n * @param model - The model to get the response format for.\n * @returns The response format.\n */\n #getResponseFormat(\n model: string | LanguageModelLike\n ): ResponseFormat | undefined {\n if (!this.#options.responseFormat) {\n return undefined;\n }\n\n const strategies = transformResponseFormat(\n this.#options.responseFormat,\n undefined,\n model\n );\n\n /**\n * we either define a list of provider strategies or a list of tool strategies\n */\n const isProviderStrategy = strategies.every(\n (format) => format instanceof ProviderStrategy\n );\n\n /**\n * Populate a list of structured tool info.\n */\n if (!isProviderStrategy) {\n return {\n type: \"tool\",\n tools: (\n strategies.filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>),\n };\n }\n\n return {\n type: \"native\",\n /**\n * there can only be one provider strategy\n */\n strategy: strategies[0] as ProviderStrategy,\n };\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n ToolMessage.isInstance(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage({\n content: \"Sorry, need more steps to process this request.\",\n name: this.name,\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel() {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n if (this.#options.model) {\n return this.#options.model;\n }\n\n throw new Error(\"No model option was provided, either via `model` option.\");\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel();\n const lgConfig = config as LangGraphRunnableConfig;\n\n /**\n * Create the base handler that performs the actual model invocation\n */\n const baseHandler = async (\n request: ModelRequest\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> => {\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(request.model);\n\n const structuredResponseFormat = this.#getResponseFormat(request.model);\n const modelWithTools = await this.#bindTools(\n request.model,\n request,\n structuredResponseFormat\n );\n\n let modelInput = this.#getModelInputState(state);\n modelInput = { ...modelInput, messages: request.messages };\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = { ...config, signal };\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (structuredResponseFormat?.type === \"native\") {\n const structuredResponse =\n structuredResponseFormat.strategy.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n\n return response;\n }\n\n if (!structuredResponseFormat || !response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in structuredResponseFormat.tools\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(\n response,\n toolCalls,\n structuredResponseFormat\n );\n }\n\n const toolStrategy = structuredResponseFormat.tools[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n structuredResponseFormat,\n toolMessageContent ?? options.lastMessage\n );\n };\n\n const wrapperMiddleware = this.#options.wrapModelCallHookMiddleware ?? [];\n let wrappedHandler: (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ) => Promise<InternalModelResponse<StructuredResponseFormat>> = baseHandler;\n\n /**\n * Build composed handler from last to first so first middleware becomes outermost\n */\n for (let i = wrapperMiddleware.length - 1; i >= 0; i--) {\n const [middleware, getMiddlewareState] = wrapperMiddleware[i];\n if (middleware.wrapModelCall) {\n const innerHandler = wrappedHandler;\n const currentMiddleware = middleware;\n const currentGetState = getMiddlewareState;\n\n wrappedHandler = async (\n request: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Merge context with default context of middleware\n */\n const context = currentMiddleware.contextSchema\n ? interopParse(\n currentMiddleware.contextSchema,\n lgConfig?.context || {}\n )\n : lgConfig?.context;\n\n /**\n * Create runtime\n */\n const runtime: Runtime<unknown> = Object.freeze({\n context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n });\n\n /**\n * Create the request with state and runtime\n */\n const requestWithStateAndRuntime: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n > = {\n ...request,\n state: {\n ...(middleware.stateSchema\n ? interopParse(\n interopZodObjectPartial(middleware.stateSchema),\n state\n )\n : {}),\n ...currentGetState(),\n messages: state.messages,\n } as InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n runtime,\n };\n\n /**\n * Create handler that validates tools and calls the inner handler\n */\n const handlerWithValidation = async (\n req: ModelRequest<\n InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n unknown\n >\n ): Promise<InternalModelResponse<StructuredResponseFormat>> => {\n /**\n * Verify that the user didn't add any new tools.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const modifiedTools = req.tools ?? [];\n const newTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n !this.#options.toolClasses.some((t) => t.name === tool.name)\n );\n if (newTools.length > 0) {\n throw new Error(\n `You have added a new tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${newTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n /**\n * Verify that user has not added or modified a tool with the same name.\n * We can't allow this as the ToolNode is already initiated with given tools.\n */\n const invalidTools = modifiedTools.filter(\n (tool) =>\n isClientTool(tool) &&\n this.#options.toolClasses.every((t) => t !== tool)\n );\n if (invalidTools.length > 0) {\n throw new Error(\n `You have modified a tool in \"wrapModelCall\" hook of middleware \"${\n currentMiddleware.name\n }\": ${invalidTools\n .map((tool) => tool.name)\n .join(\", \")}. This is not supported.`\n );\n }\n\n return innerHandler(req);\n };\n\n // Call middleware's wrapModelCall with the validation handler\n if (!currentMiddleware.wrapModelCall) {\n return handlerWithValidation(requestWithStateAndRuntime);\n }\n\n try {\n const middlewareResponse = await currentMiddleware.wrapModelCall(\n requestWithStateAndRuntime,\n handlerWithValidation as WrapModelCallHandler\n );\n\n /**\n * Validate that this specific middleware returned a valid AIMessage\n */\n if (!AIMessage.isInstance(middlewareResponse)) {\n throw new Error(\n `Invalid response from \"wrapModelCall\" in middleware \"${\n currentMiddleware.name\n }\": expected AIMessage, got ${typeof middlewareResponse}`\n );\n }\n\n return middlewareResponse;\n } catch (error) {\n // Add middleware context to error if not already added\n if (\n error instanceof Error &&\n !error.message.includes(`middleware \"${currentMiddleware.name}\"`)\n ) {\n error.message = `Error in middleware \"${currentMiddleware.name}\": ${error.message}`;\n }\n throw error;\n }\n };\n }\n }\n\n /**\n * Execute the wrapped handler with the initial request\n */\n const initialRequest: ModelRequest<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n unknown\n > = {\n model,\n systemPrompt: this.#options.systemPrompt,\n messages: state.messages,\n tools: this.#options.toolClasses,\n state,\n runtime: Object.freeze({\n context: lgConfig?.context,\n writer: lgConfig.writer,\n interrupt: lgConfig.interrupt,\n signal: lgConfig.signal,\n }) as Runtime<unknown>,\n };\n\n return wrappedHandler(initialRequest);\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[],\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0],\n responseFormat\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = responseFormat.tools[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new ToolMessage({\n tool_call_id: toolCall.id ?? \"\",\n content: JSON.stringify(structuredResponse),\n name: toolCall.name,\n }),\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall,\n responseFormat\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall,\n responseFormat: ToolResponseFormat\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(responseFormat.tools).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n AIMessage.isInstance(response) &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages.at(-1))))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions: ModelRequest | undefined,\n structuredResponseFormat: ResponseFormat | undefined\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions> = {};\n const structuredTools = Object.values(\n structuredResponseFormat && \"tools\" in structuredResponseFormat\n ? structuredResponseFormat.tools\n : {}\n );\n\n /**\n * Use tools from preparedOptions if provided, otherwise use default tools\n */\n const allTools = [\n ...(preparedOptions?.tools ?? this.#options.toolClasses),\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ];\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (structuredResponseFormat?.type === \"native\") {\n const jsonSchemaParams = {\n name: structuredResponseFormat.strategy.schema?.name ?? \"extract\",\n description: getSchemaDescription(\n structuredResponseFormat.strategy.schema\n ),\n schema: structuredResponseFormat.strategy.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: structuredResponseFormat.strategy.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n ...(preparedOptions?.modelSettings ?? {}),\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(\n preparedOptions?.systemPrompt ?? this.#options.systemPrompt\n ).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n\n getState(): {\n messages: BaseMessage[];\n } {\n const state = super.getState();\n const origState = state && !(state instanceof Command) ? state : {};\n\n return {\n messages: [],\n ...origState,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;AAgGA,IAAa,YAAb,cAMU,iBAOR;CACA;CAEA,YACEA,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WAAW,KAAKC,KAAK,OAAO,OAAyB;EACpE,EAAC;EAEF,KAAKC,WAAW;CACjB;;;;;;;;;;;;;CAcD,mBACEC,OAC4B;AAC5B,MAAI,CAAC,KAAKD,SAAS,eACjB,QAAO;EAGT,MAAM,aAAa,wBACjB,KAAKA,SAAS,gBACd,QACA,MACD;;;;EAKD,MAAM,qBAAqB,WAAW,MACpC,CAAC,WAAW,kBAAkB,iBAC/B;;;;AAKD,MAAI,CAAC,mBACH,QAAO;GACL,MAAM;GACN,OACE,WAAW,OACT,CAAC,WAAW,kBAAkB,aAC/B,CACD,OAAO,CAAC,KAAK,WAAW;IACxB,IAAI,OAAO,QAAQ;AACnB,WAAO;GACR,GAAE,CAAE,EAAiC;EACvC;AAGH,SAAO;GACL,MAAM;GAIN,UAAU,WAAW;EACtB;CACF;CAED,MAAMD,KACJG,OAEAC,QACA;;;;;EAKA,MAAM,cAAc,MAAM,SAAS,GAAG,GAAG;AACzC,MACE,eACA,YAAY,WAAW,YAAY,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,eAChB,gBAAgB,SAAS,IAAI,QAAQ;;;;AAKxC,MAAI,0BAA0B,SAAS,UAAU;GAC/C,MAAM,mBAAmB;IACvB,MAAM,yBAAyB,SAAS,QAAQ,QAAQ;IACxD,aAAa,qBACX,yBAAyB,SAAS,OACnC;IACD,QAAQ,yBAAyB,SAAS;IAC1C,QAAQ;GACT;GAED,OAAO,OAAO,SAAS;IACrB,iBAAiB;KACf,MAAM;KACN,aAAa;IACd;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,cAAe;KACjC,QAAQ,yBAAyB,SAAS;IAC3C;IACD,QAAQ;GACT,EAAC;EACH;;;;EAKD,MAAM,iBAAiB,MAAM,UAAU,OAAO,UAAU;GACtD,GAAG;GACH,GAAI,iBAAiB,iBAAiB,CAAE;GACxC,aAAa;EACd,EAAC;;;;EAKF,MAAM,gBAAgB,kBACpB,iBAAiB,gBAAgB,KAAKA,SAAS,aAChD,CAAC,KACA,KAAKA,SAAS,qBAAqB,WAC/B,cAAc,gBAAgB,KAAKA,SAAS,iBAAiB,GAC7D,eACL;AAED,SAAO;CACR;CAED,WAEE;EACA,MAAM,QAAQ,MAAM,UAAU;EAC9B,MAAM,YAAY,SAAS,EAAE,iBAAiB,WAAW,QAAQ,CAAE;AAEnE,SAAO;GACL,UAAU,CAAE;GACZ,GAAG;EACJ;CACF;AACF"}
@@ -201,7 +201,6 @@ function hasSupportForJsonSchemaOutput(model) {
201
201
  //#endregion
202
202
  exports.ProviderStrategy = ProviderStrategy;
203
203
  exports.ToolStrategy = ToolStrategy;
204
- exports.hasSupportForJsonSchemaOutput = hasSupportForJsonSchemaOutput;
205
204
  exports.providerStrategy = providerStrategy;
206
205
  exports.toolStrategy = toolStrategy;
207
206
  exports.transformResponseFormat = transformResponseFormat;
@@ -198,5 +198,5 @@ function hasSupportForJsonSchemaOutput(model) {
198
198
  }
199
199
 
200
200
  //#endregion
201
- export { ProviderStrategy, ToolStrategy, hasSupportForJsonSchemaOutput, providerStrategy, toolStrategy, transformResponseFormat };
201
+ export { ProviderStrategy, ToolStrategy, providerStrategy, toolStrategy, transformResponseFormat };
202
202
  //# sourceMappingURL=responses.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * LangChain Messages\n */\nexport {\n BaseMessage,\n BaseMessageChunk,\n AIMessage,\n AIMessageChunk,\n SystemMessage,\n SystemMessageChunk,\n HumanMessage,\n HumanMessageChunk,\n ToolMessage,\n ToolMessageChunk,\n type ContentBlock,\n filterMessages,\n trimMessages,\n} from \"@langchain/core/messages\";\n\n/**\n * Universal Chat Model\n */\nexport { initChatModel } from \"./chat_models/universal.js\";\n\n/**\n * LangChain Tools\n */\nexport {\n tool,\n Tool,\n DynamicTool,\n StructuredTool,\n DynamicStructuredTool,\n} from \"@langchain/core/tools\";\n\n/**\n * LangChain Agents\n */\nexport * from \"./agents/index.js\";\n\n/**\n * `createAgent` pre-built middleware\n */\nexport * from \"./agents/middleware/index.js\";\n\n/**\n * LangChain Stores\n */\nexport { InMemoryStore } from \"@langchain/core/stores\";\n\n/**\n * LangChain Documents\n */\nexport { type DocumentInput, Document } from \"@langchain/core/documents\";\n"],"mappings":""}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * LangChain Messages\n */\nexport {\n BaseMessage,\n BaseMessageChunk,\n AIMessage,\n AIMessageChunk,\n SystemMessage,\n SystemMessageChunk,\n HumanMessage,\n HumanMessageChunk,\n ToolMessage,\n ToolMessageChunk,\n type ContentBlock,\n filterMessages,\n trimMessages,\n} from \"@langchain/core/messages\";\n\n/**\n * Universal Chat Model\n */\nexport { initChatModel } from \"./chat_models/universal.js\";\n\n/**\n * LangChain Tools\n */\nexport {\n tool,\n Tool,\n type ToolRuntime,\n DynamicTool,\n StructuredTool,\n DynamicStructuredTool,\n} from \"@langchain/core/tools\";\n\n/**\n * LangChain Agents\n */\nexport * from \"./agents/index.js\";\n\n/**\n * `createAgent` pre-built middleware\n */\nexport * from \"./agents/middleware/index.js\";\n\n/**\n * LangChain Stores\n */\nexport { InMemoryStore } from \"@langchain/core/stores\";\n\n/**\n * LangChain Documents\n */\nexport { type DocumentInput, Document } from \"@langchain/core/documents\";\n"],"mappings":""}
package/dist/index.d.cts CHANGED
@@ -23,7 +23,7 @@ import { modelFallbackMiddleware } from "./agents/middleware/modelFallback.cjs";
23
23
  import { ToolRetryMiddlewareConfig, toolRetryMiddleware } from "./agents/middleware/toolRetry.cjs";
24
24
  import { countTokensApproximately } from "./agents/middleware/utils.cjs";
25
25
  import { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ContentBlock, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, filterMessages, trimMessages } from "@langchain/core/messages";
26
- import { DynamicStructuredTool, DynamicTool, StructuredTool, Tool, tool } from "@langchain/core/tools";
26
+ import { DynamicStructuredTool, DynamicTool, StructuredTool, Tool, ToolRuntime, tool } from "@langchain/core/tools";
27
27
  import { InMemoryStore } from "@langchain/core/stores";
28
28
  import { Document, DocumentInput } from "@langchain/core/documents";
29
- export { AIMessage, AIMessageChunk, Action, ActionRequest, AgentMiddleware, ApproveDecision, BaseMessage, BaseMessageChunk, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, ModelCallLimitMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, PIIRedactionMiddlewareConfig, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RejectDecision, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, ToolStrategy, UserInput, WithStateGraphNodes, WrapToolCallHook, anthropicPromptCachingMiddleware, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, dynamicSystemPromptMiddleware, filterMessages, humanInTheLoopMiddleware, initChatModel, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, piiRedactionMiddleware, providerStrategy, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
29
+ export { AIMessage, AIMessageChunk, Action, ActionRequest, AgentMiddleware, ApproveDecision, BaseMessage, BaseMessageChunk, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, ModelCallLimitMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, PIIRedactionMiddlewareConfig, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RejectDecision, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, UserInput, WithStateGraphNodes, WrapToolCallHook, anthropicPromptCachingMiddleware, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, dynamicSystemPromptMiddleware, filterMessages, humanInTheLoopMiddleware, initChatModel, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, piiRedactionMiddleware, providerStrategy, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
package/dist/index.d.ts CHANGED
@@ -23,7 +23,7 @@ import { modelFallbackMiddleware } from "./agents/middleware/modelFallback.js";
23
23
  import { ToolRetryMiddlewareConfig, toolRetryMiddleware } from "./agents/middleware/toolRetry.js";
24
24
  import { countTokensApproximately } from "./agents/middleware/utils.js";
25
25
  import { AIMessage, AIMessageChunk, BaseMessage, BaseMessageChunk, ContentBlock, HumanMessage, HumanMessageChunk, SystemMessage, SystemMessageChunk, ToolMessage, ToolMessageChunk, filterMessages, trimMessages } from "@langchain/core/messages";
26
- import { DynamicStructuredTool, DynamicTool, StructuredTool, Tool, tool } from "@langchain/core/tools";
26
+ import { DynamicStructuredTool, DynamicTool, StructuredTool, Tool, ToolRuntime, tool } from "@langchain/core/tools";
27
27
  import { InMemoryStore } from "@langchain/core/stores";
28
28
  import { Document, DocumentInput } from "@langchain/core/documents";
29
- export { AIMessage, AIMessageChunk, Action, ActionRequest, AgentMiddleware, ApproveDecision, BaseMessage, BaseMessageChunk, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, ModelCallLimitMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, PIIRedactionMiddlewareConfig, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RejectDecision, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, ToolStrategy, UserInput, WithStateGraphNodes, WrapToolCallHook, anthropicPromptCachingMiddleware, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, dynamicSystemPromptMiddleware, filterMessages, humanInTheLoopMiddleware, initChatModel, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, piiRedactionMiddleware, providerStrategy, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
29
+ export { AIMessage, AIMessageChunk, Action, ActionRequest, AgentMiddleware, ApproveDecision, BaseMessage, BaseMessageChunk, BuiltInState, ClearToolUsesEdit, ClearToolUsesEditConfig, type ContentBlock, ContextEdit, ContextEditingMiddlewareConfig, CreateAgentParams, Decision, DecisionType, DescriptionFactory, Document, type DocumentInput, DynamicStructuredTool, DynamicSystemPromptMiddlewareConfig, DynamicTool, EditDecision, ExecutedToolCall, ExtractZodArrayTypes, FakeToolCallingModel, HITLRequest, HITLResponse, HumanInTheLoopMiddlewareConfig, HumanMessage, HumanMessageChunk, InMemoryStore, Interrupt, InterruptOnConfig, JumpTo, JumpToTarget, LLMToolSelectorConfig, ModelCallLimitMiddlewareConfig, MultipleStructuredOutputsError, MultipleToolsBoundError, N, PIIRedactionMiddlewareConfig, PromptCachingMiddlewareConfig, ProviderStrategy, ReactAgent, RejectDecision, ResponseFormat, ResponseFormatUndefined, ReviewConfig, Runtime, StructuredOutputParsingError, StructuredTool, SummarizationMiddlewareConfig, SystemMessage, SystemMessageChunk, TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, TodoListMiddlewareOptions, TokenCounter, Tool, ToolCall, ToolCallHandler, ToolCallLimitConfig, ToolCallLimitExceededError, ToolCallRequest, ToolInvocationError, ToolMessage, ToolMessageChunk, ToolResult, ToolRetryMiddlewareConfig, type ToolRuntime, ToolStrategy, UserInput, WithStateGraphNodes, WrapToolCallHook, anthropicPromptCachingMiddleware, contextEditingMiddleware, countTokensApproximately, createAgent, createMiddleware, dynamicSystemPromptMiddleware, filterMessages, humanInTheLoopMiddleware, initChatModel, llmToolSelectorMiddleware, modelCallLimitMiddleware, modelFallbackMiddleware, piiRedactionMiddleware, providerStrategy, summarizationMiddleware, todoListMiddleware, tool, toolCallLimitMiddleware, toolRetryMiddleware, toolStrategy, trimMessages };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * LangChain Messages\n */\nexport {\n BaseMessage,\n BaseMessageChunk,\n AIMessage,\n AIMessageChunk,\n SystemMessage,\n SystemMessageChunk,\n HumanMessage,\n HumanMessageChunk,\n ToolMessage,\n ToolMessageChunk,\n type ContentBlock,\n filterMessages,\n trimMessages,\n} from \"@langchain/core/messages\";\n\n/**\n * Universal Chat Model\n */\nexport { initChatModel } from \"./chat_models/universal.js\";\n\n/**\n * LangChain Tools\n */\nexport {\n tool,\n Tool,\n DynamicTool,\n StructuredTool,\n DynamicStructuredTool,\n} from \"@langchain/core/tools\";\n\n/**\n * LangChain Agents\n */\nexport * from \"./agents/index.js\";\n\n/**\n * `createAgent` pre-built middleware\n */\nexport * from \"./agents/middleware/index.js\";\n\n/**\n * LangChain Stores\n */\nexport { InMemoryStore } from \"@langchain/core/stores\";\n\n/**\n * LangChain Documents\n */\nexport { type DocumentInput, Document } from \"@langchain/core/documents\";\n"],"mappings":""}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * LangChain Messages\n */\nexport {\n BaseMessage,\n BaseMessageChunk,\n AIMessage,\n AIMessageChunk,\n SystemMessage,\n SystemMessageChunk,\n HumanMessage,\n HumanMessageChunk,\n ToolMessage,\n ToolMessageChunk,\n type ContentBlock,\n filterMessages,\n trimMessages,\n} from \"@langchain/core/messages\";\n\n/**\n * Universal Chat Model\n */\nexport { initChatModel } from \"./chat_models/universal.js\";\n\n/**\n * LangChain Tools\n */\nexport {\n tool,\n Tool,\n type ToolRuntime,\n DynamicTool,\n StructuredTool,\n DynamicStructuredTool,\n} from \"@langchain/core/tools\";\n\n/**\n * LangChain Agents\n */\nexport * from \"./agents/index.js\";\n\n/**\n * `createAgent` pre-built middleware\n */\nexport * from \"./agents/middleware/index.js\";\n\n/**\n * LangChain Stores\n */\nexport { InMemoryStore } from \"@langchain/core/stores\";\n\n/**\n * LangChain Documents\n */\nexport { type DocumentInput, Document } from \"@langchain/core/documents\";\n"],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "langchain",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "description": "Typescript bindings for langchain",
5
5
  "author": "LangChain",
6
6
  "license": "MIT",
@@ -36,15 +36,15 @@
36
36
  "reflect-metadata": "^0.2.2",
37
37
  "rimraf": "^5.0.1",
38
38
  "rollup": "^3.19.1",
39
- "typeorm": "^0.3.20",
39
+ "typeorm": "^0.3.26",
40
40
  "typescript": "~5.8.3",
41
41
  "vitest": "^3.2.4",
42
42
  "yaml": "^2.8.1",
43
- "@langchain/core": "1.0.3",
44
- "@langchain/cohere": "1.0.0",
45
43
  "@langchain/anthropic": "1.0.0",
46
- "@langchain/openai": "1.0.0",
47
- "@langchain/eslint": "0.1.0"
44
+ "@langchain/eslint": "0.1.0",
45
+ "@langchain/cohere": "1.0.0",
46
+ "@langchain/core": "1.0.4",
47
+ "@langchain/openai": "1.1.0"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "@langchain/core": "^1.0.3"
@@ -1,130 +0,0 @@
1
- const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
- const require_middleware = require('../middleware.cjs');
3
- const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
4
- const zod_v3 = require_rolldown_runtime.__toESM(require("zod/v3"));
5
-
6
- //#region src/agents/middleware/callLimit.ts
7
- const DEFAULT_EXIT_BEHAVIOR = "end";
8
- const contextSchema = zod_v3.z.object({
9
- threadLimit: zod_v3.z.number().optional(),
10
- runLimit: zod_v3.z.number().optional(),
11
- exitBehavior: zod_v3.z.enum(["throw", "end"]).optional()
12
- });
13
- /**
14
- * Error thrown when the model call limit is exceeded.
15
- *
16
- * @param threadLimit - The maximum number of model calls allowed per thread.
17
- * @param runLimit - The maximum number of model calls allowed per run.
18
- * @param threadCount - The number of model calls made at the thread level.
19
- * @param runCount - The number of model calls made at the run level.
20
- */
21
- var ModelCallLimitMiddlewareError = class extends Error {
22
- constructor({ threadLimit, runLimit, threadCount, runCount }) {
23
- const exceededHint = [];
24
- if (typeof threadLimit === "number" && typeof threadCount === "number") exceededHint.push(`thread level call limit reached with ${threadCount} model calls`);
25
- if (typeof runLimit === "number" && typeof runCount === "number") exceededHint.push(`run level call limit reached with ${runCount} model calls`);
26
- super(`Model call limits exceeded${exceededHint.length > 0 ? `: ${exceededHint.join(", ")}` : ""}`);
27
- this.name = "ModelCallLimitMiddlewareError";
28
- }
29
- };
30
- /**
31
- * Creates a middleware to limit the number of model calls at both thread and run levels.
32
- *
33
- * This middleware helps prevent excessive model API calls by enforcing limits on how many
34
- * times the model can be invoked. It supports two types of limits:
35
- *
36
- * - **Thread-level limit**: Restricts the total number of model calls across an entire conversation thread
37
- * - **Run-level limit**: Restricts the number of model calls within a single agent run/invocation
38
- *
39
- * ## How It Works
40
- *
41
- * The middleware intercepts model requests before they are sent and checks the current call counts
42
- * against the configured limits. If either limit is exceeded, it throws a `ModelCallLimitMiddlewareError`
43
- * to stop execution and prevent further API calls.
44
- *
45
- * ## Use Cases
46
- *
47
- * - **Cost Control**: Prevent runaway costs from excessive model calls in production
48
- * - **Testing**: Ensure agents don't make too many calls during development/testing
49
- * - **Safety**: Limit potential infinite loops or recursive agent behaviors
50
- * - **Rate Limiting**: Enforce organizational policies on model usage per conversation
51
- *
52
- * @param middlewareOptions - Configuration options for the call limits
53
- * @param middlewareOptions.threadLimit - Maximum number of model calls allowed per thread (optional)
54
- * @param middlewareOptions.runLimit - Maximum number of model calls allowed per run (optional)
55
- *
56
- * @returns A middleware instance that can be passed to `createAgent`
57
- *
58
- * @throws {ModelCallLimitMiddlewareError} When either the thread or run limit is exceeded
59
- *
60
- * @example
61
- * ```typescript
62
- * import { createAgent, modelCallLimitMiddleware } from "langchain";
63
- *
64
- * // Limit to 10 calls per thread and 3 calls per run
65
- * const agent = createAgent({
66
- * model: "openai:gpt-4o-mini",
67
- * tools: [myTool],
68
- * middleware: [
69
- * modelCallLimitMiddleware({
70
- * threadLimit: 10,
71
- * runLimit: 3
72
- * })
73
- * ]
74
- * });
75
- * ```
76
- *
77
- * @example
78
- * ```typescript
79
- * // Limits can also be configured at runtime via context
80
- * const result = await agent.invoke(
81
- * { messages: ["Hello"] },
82
- * {
83
- * configurable: {
84
- * threadLimit: 5 // Override the default limit for this run
85
- * }
86
- * }
87
- * );
88
- * ```
89
- */
90
- function modelCallLimitMiddleware(middlewareOptions) {
91
- return require_middleware.createMiddleware({
92
- name: "ModelCallLimitMiddleware",
93
- contextSchema,
94
- beforeModel: {
95
- canJumpTo: ["end"],
96
- hook: (state, runtime) => {
97
- const exitBehavior = runtime.context.exitBehavior ?? middlewareOptions?.exitBehavior ?? DEFAULT_EXIT_BEHAVIOR;
98
- const threadLimit = runtime.context.threadLimit ?? middlewareOptions?.threadLimit;
99
- const runLimit = runtime.context.runLimit ?? middlewareOptions?.runLimit;
100
- if (typeof threadLimit === "number" && threadLimit <= runtime.threadLevelCallCount) {
101
- const error = new ModelCallLimitMiddlewareError({
102
- threadLimit,
103
- threadCount: runtime.threadLevelCallCount
104
- });
105
- if (exitBehavior === "end") return {
106
- jumpTo: "end",
107
- messages: [new __langchain_core_messages.AIMessage(error.message)]
108
- };
109
- throw error;
110
- }
111
- if (typeof runLimit === "number" && runLimit <= runtime.runModelCallCount) {
112
- const error = new ModelCallLimitMiddlewareError({
113
- runLimit,
114
- runCount: runtime.runModelCallCount
115
- });
116
- if (exitBehavior === "end") return {
117
- jumpTo: "end",
118
- messages: [new __langchain_core_messages.AIMessage(error.message)]
119
- };
120
- throw error;
121
- }
122
- return state;
123
- }
124
- }
125
- });
126
- }
127
-
128
- //#endregion
129
- exports.modelCallLimitMiddleware = modelCallLimitMiddleware;
130
- //# sourceMappingURL=callLimit.cjs.map