@librechat/agents 2.4.322 → 3.0.0-rc2

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 (266) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +218 -0
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -0
  3. package/dist/cjs/common/enum.cjs +14 -5
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/events.cjs +10 -6
  6. package/dist/cjs/events.cjs.map +1 -1
  7. package/dist/cjs/graphs/Graph.cjs +309 -212
  8. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  9. package/dist/cjs/graphs/MultiAgentGraph.cjs +422 -0
  10. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -0
  11. package/dist/cjs/llm/anthropic/index.cjs +54 -9
  12. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  13. package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
  14. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +52 -6
  15. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  16. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +22 -2
  17. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
  18. package/dist/cjs/llm/anthropic/utils/tools.cjs +29 -0
  19. package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -0
  20. package/dist/cjs/llm/google/index.cjs +144 -0
  21. package/dist/cjs/llm/google/index.cjs.map +1 -0
  22. package/dist/cjs/llm/google/utils/common.cjs +477 -0
  23. package/dist/cjs/llm/google/utils/common.cjs.map +1 -0
  24. package/dist/cjs/llm/ollama/index.cjs +67 -0
  25. package/dist/cjs/llm/ollama/index.cjs.map +1 -0
  26. package/dist/cjs/llm/ollama/utils.cjs +158 -0
  27. package/dist/cjs/llm/ollama/utils.cjs.map +1 -0
  28. package/dist/cjs/llm/openai/index.cjs +389 -3
  29. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  30. package/dist/cjs/llm/openai/utils/index.cjs +672 -0
  31. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -0
  32. package/dist/cjs/llm/providers.cjs +15 -15
  33. package/dist/cjs/llm/providers.cjs.map +1 -1
  34. package/dist/cjs/llm/text.cjs +14 -3
  35. package/dist/cjs/llm/text.cjs.map +1 -1
  36. package/dist/cjs/llm/vertexai/index.cjs +330 -0
  37. package/dist/cjs/llm/vertexai/index.cjs.map +1 -0
  38. package/dist/cjs/main.cjs +11 -0
  39. package/dist/cjs/main.cjs.map +1 -1
  40. package/dist/cjs/run.cjs +120 -81
  41. package/dist/cjs/run.cjs.map +1 -1
  42. package/dist/cjs/stream.cjs +85 -51
  43. package/dist/cjs/stream.cjs.map +1 -1
  44. package/dist/cjs/tools/ToolNode.cjs +10 -4
  45. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  46. package/dist/cjs/tools/handlers.cjs +119 -13
  47. package/dist/cjs/tools/handlers.cjs.map +1 -1
  48. package/dist/cjs/tools/search/anthropic.cjs +40 -0
  49. package/dist/cjs/tools/search/anthropic.cjs.map +1 -0
  50. package/dist/cjs/tools/search/firecrawl.cjs +55 -9
  51. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  52. package/dist/cjs/tools/search/format.cjs +6 -6
  53. package/dist/cjs/tools/search/format.cjs.map +1 -1
  54. package/dist/cjs/tools/search/rerankers.cjs +7 -29
  55. package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
  56. package/dist/cjs/tools/search/search.cjs +86 -16
  57. package/dist/cjs/tools/search/search.cjs.map +1 -1
  58. package/dist/cjs/tools/search/tool.cjs +4 -2
  59. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  60. package/dist/cjs/tools/search/utils.cjs +1 -1
  61. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  62. package/dist/cjs/utils/events.cjs +31 -0
  63. package/dist/cjs/utils/events.cjs.map +1 -0
  64. package/dist/cjs/utils/title.cjs +57 -21
  65. package/dist/cjs/utils/title.cjs.map +1 -1
  66. package/dist/cjs/utils/tokens.cjs +54 -7
  67. package/dist/cjs/utils/tokens.cjs.map +1 -1
  68. package/dist/esm/agents/AgentContext.mjs +216 -0
  69. package/dist/esm/agents/AgentContext.mjs.map +1 -0
  70. package/dist/esm/common/enum.mjs +15 -6
  71. package/dist/esm/common/enum.mjs.map +1 -1
  72. package/dist/esm/events.mjs +10 -6
  73. package/dist/esm/events.mjs.map +1 -1
  74. package/dist/esm/graphs/Graph.mjs +311 -214
  75. package/dist/esm/graphs/Graph.mjs.map +1 -1
  76. package/dist/esm/graphs/MultiAgentGraph.mjs +420 -0
  77. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -0
  78. package/dist/esm/llm/anthropic/index.mjs +54 -9
  79. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  80. package/dist/esm/llm/anthropic/types.mjs.map +1 -1
  81. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +52 -6
  82. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  83. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +22 -2
  84. package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
  85. package/dist/esm/llm/anthropic/utils/tools.mjs +27 -0
  86. package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -0
  87. package/dist/esm/llm/google/index.mjs +142 -0
  88. package/dist/esm/llm/google/index.mjs.map +1 -0
  89. package/dist/esm/llm/google/utils/common.mjs +471 -0
  90. package/dist/esm/llm/google/utils/common.mjs.map +1 -0
  91. package/dist/esm/llm/ollama/index.mjs +65 -0
  92. package/dist/esm/llm/ollama/index.mjs.map +1 -0
  93. package/dist/esm/llm/ollama/utils.mjs +155 -0
  94. package/dist/esm/llm/ollama/utils.mjs.map +1 -0
  95. package/dist/esm/llm/openai/index.mjs +388 -4
  96. package/dist/esm/llm/openai/index.mjs.map +1 -1
  97. package/dist/esm/llm/openai/utils/index.mjs +666 -0
  98. package/dist/esm/llm/openai/utils/index.mjs.map +1 -0
  99. package/dist/esm/llm/providers.mjs +5 -5
  100. package/dist/esm/llm/providers.mjs.map +1 -1
  101. package/dist/esm/llm/text.mjs +14 -3
  102. package/dist/esm/llm/text.mjs.map +1 -1
  103. package/dist/esm/llm/vertexai/index.mjs +328 -0
  104. package/dist/esm/llm/vertexai/index.mjs.map +1 -0
  105. package/dist/esm/main.mjs +6 -5
  106. package/dist/esm/main.mjs.map +1 -1
  107. package/dist/esm/run.mjs +121 -83
  108. package/dist/esm/run.mjs.map +1 -1
  109. package/dist/esm/stream.mjs +87 -54
  110. package/dist/esm/stream.mjs.map +1 -1
  111. package/dist/esm/tools/ToolNode.mjs +10 -4
  112. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  113. package/dist/esm/tools/handlers.mjs +119 -15
  114. package/dist/esm/tools/handlers.mjs.map +1 -1
  115. package/dist/esm/tools/search/anthropic.mjs +37 -0
  116. package/dist/esm/tools/search/anthropic.mjs.map +1 -0
  117. package/dist/esm/tools/search/firecrawl.mjs +55 -9
  118. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  119. package/dist/esm/tools/search/format.mjs +7 -7
  120. package/dist/esm/tools/search/format.mjs.map +1 -1
  121. package/dist/esm/tools/search/rerankers.mjs +7 -29
  122. package/dist/esm/tools/search/rerankers.mjs.map +1 -1
  123. package/dist/esm/tools/search/search.mjs +86 -16
  124. package/dist/esm/tools/search/search.mjs.map +1 -1
  125. package/dist/esm/tools/search/tool.mjs +4 -2
  126. package/dist/esm/tools/search/tool.mjs.map +1 -1
  127. package/dist/esm/tools/search/utils.mjs +1 -1
  128. package/dist/esm/tools/search/utils.mjs.map +1 -1
  129. package/dist/esm/utils/events.mjs +29 -0
  130. package/dist/esm/utils/events.mjs.map +1 -0
  131. package/dist/esm/utils/title.mjs +57 -22
  132. package/dist/esm/utils/title.mjs.map +1 -1
  133. package/dist/esm/utils/tokens.mjs +54 -8
  134. package/dist/esm/utils/tokens.mjs.map +1 -1
  135. package/dist/types/agents/AgentContext.d.ts +91 -0
  136. package/dist/types/common/enum.d.ts +15 -6
  137. package/dist/types/events.d.ts +5 -4
  138. package/dist/types/graphs/Graph.d.ts +64 -67
  139. package/dist/types/graphs/MultiAgentGraph.d.ts +37 -0
  140. package/dist/types/graphs/index.d.ts +1 -0
  141. package/dist/types/llm/anthropic/index.d.ts +11 -0
  142. package/dist/types/llm/anthropic/types.d.ts +9 -3
  143. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -1
  144. package/dist/types/llm/anthropic/utils/output_parsers.d.ts +4 -4
  145. package/dist/types/llm/anthropic/utils/tools.d.ts +3 -0
  146. package/dist/types/llm/google/index.d.ts +13 -0
  147. package/dist/types/llm/google/types.d.ts +32 -0
  148. package/dist/types/llm/google/utils/common.d.ts +19 -0
  149. package/dist/types/llm/google/utils/tools.d.ts +10 -0
  150. package/dist/types/llm/google/utils/zod_to_genai_parameters.d.ts +14 -0
  151. package/dist/types/llm/ollama/index.d.ts +7 -0
  152. package/dist/types/llm/ollama/utils.d.ts +7 -0
  153. package/dist/types/llm/openai/index.d.ts +72 -3
  154. package/dist/types/llm/openai/types.d.ts +10 -0
  155. package/dist/types/llm/openai/utils/index.d.ts +20 -0
  156. package/dist/types/llm/text.d.ts +1 -1
  157. package/dist/types/llm/vertexai/index.d.ts +293 -0
  158. package/dist/types/messages/reducer.d.ts +9 -0
  159. package/dist/types/run.d.ts +19 -12
  160. package/dist/types/scripts/ant_web_search.d.ts +1 -0
  161. package/dist/types/scripts/args.d.ts +2 -1
  162. package/dist/types/scripts/handoff-test.d.ts +1 -0
  163. package/dist/types/scripts/multi-agent-conditional.d.ts +1 -0
  164. package/dist/types/scripts/multi-agent-parallel.d.ts +1 -0
  165. package/dist/types/scripts/multi-agent-sequence.d.ts +1 -0
  166. package/dist/types/scripts/multi-agent-supervisor.d.ts +1 -0
  167. package/dist/types/scripts/multi-agent-test.d.ts +1 -0
  168. package/dist/types/scripts/test-custom-prompt-key.d.ts +2 -0
  169. package/dist/types/scripts/test-handoff-input.d.ts +2 -0
  170. package/dist/types/scripts/test-multi-agent-list-handoff.d.ts +2 -0
  171. package/dist/types/stream.d.ts +10 -3
  172. package/dist/types/tools/CodeExecutor.d.ts +2 -2
  173. package/dist/types/tools/ToolNode.d.ts +1 -1
  174. package/dist/types/tools/handlers.d.ts +17 -4
  175. package/dist/types/tools/search/anthropic.d.ts +16 -0
  176. package/dist/types/tools/search/firecrawl.d.ts +15 -0
  177. package/dist/types/tools/search/rerankers.d.ts +0 -1
  178. package/dist/types/tools/search/types.d.ts +30 -9
  179. package/dist/types/types/graph.d.ts +129 -15
  180. package/dist/types/types/llm.d.ts +24 -10
  181. package/dist/types/types/run.d.ts +46 -8
  182. package/dist/types/types/stream.d.ts +16 -2
  183. package/dist/types/types/tools.d.ts +1 -1
  184. package/dist/types/utils/events.d.ts +6 -0
  185. package/dist/types/utils/title.d.ts +2 -1
  186. package/dist/types/utils/tokens.d.ts +24 -0
  187. package/package.json +37 -17
  188. package/src/agents/AgentContext.ts +315 -0
  189. package/src/common/enum.ts +14 -5
  190. package/src/events.ts +24 -13
  191. package/src/graphs/Graph.ts +495 -312
  192. package/src/graphs/MultiAgentGraph.ts +498 -0
  193. package/src/graphs/index.ts +2 -1
  194. package/src/llm/anthropic/Jacob_Lee_Resume_2023.pdf +0 -0
  195. package/src/llm/anthropic/index.ts +78 -13
  196. package/src/llm/anthropic/llm.spec.ts +491 -115
  197. package/src/llm/anthropic/types.ts +39 -3
  198. package/src/llm/anthropic/utils/message_inputs.ts +67 -11
  199. package/src/llm/anthropic/utils/message_outputs.ts +21 -2
  200. package/src/llm/anthropic/utils/output_parsers.ts +25 -6
  201. package/src/llm/anthropic/utils/tools.ts +29 -0
  202. package/src/llm/google/index.ts +218 -0
  203. package/src/llm/google/types.ts +43 -0
  204. package/src/llm/google/utils/common.ts +646 -0
  205. package/src/llm/google/utils/tools.ts +160 -0
  206. package/src/llm/google/utils/zod_to_genai_parameters.ts +86 -0
  207. package/src/llm/ollama/index.ts +89 -0
  208. package/src/llm/ollama/utils.ts +193 -0
  209. package/src/llm/openai/index.ts +600 -14
  210. package/src/llm/openai/types.ts +24 -0
  211. package/src/llm/openai/utils/index.ts +912 -0
  212. package/src/llm/openai/utils/isReasoningModel.test.ts +90 -0
  213. package/src/llm/providers.ts +10 -9
  214. package/src/llm/text.ts +26 -7
  215. package/src/llm/vertexai/index.ts +360 -0
  216. package/src/messages/reducer.ts +80 -0
  217. package/src/run.ts +181 -112
  218. package/src/scripts/ant_web_search.ts +158 -0
  219. package/src/scripts/args.ts +12 -8
  220. package/src/scripts/cli4.ts +29 -21
  221. package/src/scripts/cli5.ts +29 -21
  222. package/src/scripts/code_exec.ts +54 -23
  223. package/src/scripts/code_exec_files.ts +48 -17
  224. package/src/scripts/code_exec_simple.ts +46 -27
  225. package/src/scripts/handoff-test.ts +135 -0
  226. package/src/scripts/image.ts +52 -20
  227. package/src/scripts/multi-agent-conditional.ts +220 -0
  228. package/src/scripts/multi-agent-example-output.md +110 -0
  229. package/src/scripts/multi-agent-parallel.ts +341 -0
  230. package/src/scripts/multi-agent-sequence.ts +212 -0
  231. package/src/scripts/multi-agent-supervisor.ts +361 -0
  232. package/src/scripts/multi-agent-test.ts +186 -0
  233. package/src/scripts/search.ts +1 -9
  234. package/src/scripts/simple.ts +25 -10
  235. package/src/scripts/test-custom-prompt-key.ts +145 -0
  236. package/src/scripts/test-handoff-input.ts +110 -0
  237. package/src/scripts/test-multi-agent-list-handoff.ts +258 -0
  238. package/src/scripts/tools.ts +48 -18
  239. package/src/specs/anthropic.simple.test.ts +150 -34
  240. package/src/specs/azure.simple.test.ts +325 -0
  241. package/src/specs/openai.simple.test.ts +140 -33
  242. package/src/specs/openrouter.simple.test.ts +107 -0
  243. package/src/specs/prune.test.ts +4 -9
  244. package/src/specs/reasoning.test.ts +80 -44
  245. package/src/specs/token-memoization.test.ts +39 -0
  246. package/src/stream.test.ts +94 -0
  247. package/src/stream.ts +139 -60
  248. package/src/tools/ToolNode.ts +21 -7
  249. package/src/tools/handlers.ts +192 -18
  250. package/src/tools/search/anthropic.ts +51 -0
  251. package/src/tools/search/firecrawl.ts +69 -20
  252. package/src/tools/search/format.ts +6 -8
  253. package/src/tools/search/rerankers.ts +7 -40
  254. package/src/tools/search/search.ts +97 -16
  255. package/src/tools/search/tool.ts +5 -2
  256. package/src/tools/search/types.ts +30 -10
  257. package/src/tools/search/utils.ts +1 -1
  258. package/src/types/graph.ts +315 -103
  259. package/src/types/llm.ts +25 -12
  260. package/src/types/run.ts +51 -13
  261. package/src/types/stream.ts +22 -1
  262. package/src/types/tools.ts +16 -10
  263. package/src/utils/events.ts +32 -0
  264. package/src/utils/llmConfig.ts +19 -7
  265. package/src/utils/title.ts +104 -30
  266. package/src/utils/tokens.ts +69 -10
@@ -0,0 +1,90 @@
1
+ import { isReasoningModel } from './index';
2
+
3
+ describe('isReasoningModel', () => {
4
+ describe('should return true for reasoning models', () => {
5
+ test('basic o-series models', () => {
6
+ expect(isReasoningModel('o1')).toBe(true);
7
+ expect(isReasoningModel('o2')).toBe(true);
8
+ expect(isReasoningModel('o9')).toBe(true);
9
+ expect(isReasoningModel('o1-preview')).toBe(true);
10
+ expect(isReasoningModel('o1-mini')).toBe(true);
11
+ });
12
+
13
+ test('gpt-5+ models', () => {
14
+ expect(isReasoningModel('gpt-5')).toBe(true);
15
+ expect(isReasoningModel('gpt-6')).toBe(true);
16
+ expect(isReasoningModel('gpt-7')).toBe(true);
17
+ expect(isReasoningModel('gpt-8')).toBe(true);
18
+ expect(isReasoningModel('gpt-9')).toBe(true);
19
+ });
20
+
21
+ test('with provider prefixes', () => {
22
+ expect(isReasoningModel('azure/o1')).toBe(true);
23
+ expect(isReasoningModel('azure/gpt-5')).toBe(true);
24
+ expect(isReasoningModel('openai/o1')).toBe(true);
25
+ expect(isReasoningModel('openai/gpt-5')).toBe(true);
26
+ });
27
+
28
+ test('with custom prefixes', () => {
29
+ expect(isReasoningModel('custom-provider/o1')).toBe(true);
30
+ expect(isReasoningModel('my-deployment/gpt-5')).toBe(true);
31
+ expect(isReasoningModel('company/azure/gpt-5')).toBe(true);
32
+ });
33
+
34
+ test('case insensitive', () => {
35
+ expect(isReasoningModel('O1')).toBe(true);
36
+ expect(isReasoningModel('GPT-5')).toBe(true);
37
+ expect(isReasoningModel('gPt-6')).toBe(true);
38
+ expect(isReasoningModel('Azure/O1')).toBe(true);
39
+ });
40
+ });
41
+
42
+ describe('should return false for non-reasoning models', () => {
43
+ test('older GPT models', () => {
44
+ expect(isReasoningModel('gpt-3.5-turbo')).toBe(false);
45
+ expect(isReasoningModel('gpt-4')).toBe(false);
46
+ expect(isReasoningModel('gpt-4-turbo')).toBe(false);
47
+ expect(isReasoningModel('gpt-4o')).toBe(false);
48
+ expect(isReasoningModel('gpt-4o-mini')).toBe(false);
49
+ });
50
+
51
+ test('other model families', () => {
52
+ expect(isReasoningModel('claude-3')).toBe(false);
53
+ expect(isReasoningModel('claude-3-opus')).toBe(false);
54
+ expect(isReasoningModel('llama-2')).toBe(false);
55
+ expect(isReasoningModel('gemini-pro')).toBe(false);
56
+ });
57
+
58
+ test('partial matches that should not match', () => {
59
+ expect(isReasoningModel('proto1')).toBe(false);
60
+ expect(isReasoningModel('version-o1')).toBe(true);
61
+ expect(isReasoningModel('gpt-40')).toBe(false);
62
+ expect(isReasoningModel('gpt-3.5')).toBe(false);
63
+ });
64
+
65
+ test('empty, null, and undefined', () => {
66
+ expect(isReasoningModel('')).toBe(false);
67
+ expect(isReasoningModel()).toBe(false);
68
+ expect(isReasoningModel(undefined)).toBe(false);
69
+ });
70
+ });
71
+
72
+ describe('edge cases', () => {
73
+ test('with special characters', () => {
74
+ expect(isReasoningModel('deployment_o1_model')).toBe(false);
75
+ expect(isReasoningModel('gpt-5-deployment')).toBe(true);
76
+ expect(isReasoningModel('o1@latest')).toBe(true);
77
+ expect(isReasoningModel('gpt-5.0')).toBe(true);
78
+ });
79
+
80
+ test('word boundary behavior', () => {
81
+ // These should match because o1 and gpt-5 are whole words
82
+ expect(isReasoningModel('use-o1-model')).toBe(true);
83
+ expect(isReasoningModel('model-gpt-5-latest')).toBe(true);
84
+
85
+ // These should not match because o1/gpt-5 are not whole words
86
+ expect(isReasoningModel('proto1model')).toBe(false);
87
+ expect(isReasoningModel('supergpt-50')).toBe(false);
88
+ });
89
+ });
90
+ });
@@ -1,24 +1,25 @@
1
1
  // src/llm/providers.ts
2
- import { ChatOllama } from '@langchain/ollama';
3
2
  import { ChatMistralAI } from '@langchain/mistralai';
4
3
  import { ChatBedrockConverse } from '@langchain/aws';
5
4
  // import { ChatAnthropic } from '@langchain/anthropic';
6
- import { ChatVertexAI } from '@langchain/google-vertexai';
7
- import { ChatGoogleGenerativeAI } from '@langchain/google-genai';
5
+ // import { ChatVertexAI } from '@langchain/google-vertexai';
8
6
  import { BedrockChat } from '@langchain/community/chat_models/bedrock/web';
9
7
  import type {
10
8
  ChatModelConstructorMap,
11
9
  ProviderOptionsMap,
12
10
  ChatModelMap,
13
11
  } from '@/types';
14
- import { CustomAnthropic } from '@/llm/anthropic';
15
- import { ChatOpenRouter } from '@/llm/openrouter';
16
12
  import {
17
- ChatXAI,
18
- ChatOpenAI,
19
- ChatDeepSeek,
20
13
  AzureChatOpenAI,
14
+ ChatDeepSeek,
15
+ ChatOpenAI,
16
+ ChatXAI,
21
17
  } from '@/llm/openai';
18
+ import { CustomChatGoogleGenerativeAI } from '@/llm/google';
19
+ import { CustomAnthropic } from '@/llm/anthropic';
20
+ import { ChatOpenRouter } from '@/llm/openrouter';
21
+ import { ChatVertexAI } from '@/llm/vertexai';
22
+ import { ChatOllama } from '@/llm/ollama';
22
23
  import { Providers } from '@/common';
23
24
 
24
25
  export const llmProviders: Partial<ChatModelConstructorMap> = {
@@ -35,7 +36,7 @@ export const llmProviders: Partial<ChatModelConstructorMap> = {
35
36
  [Providers.BEDROCK_LEGACY]: BedrockChat,
36
37
  [Providers.BEDROCK]: ChatBedrockConverse,
37
38
  // [Providers.ANTHROPIC]: ChatAnthropic,
38
- [Providers.GOOGLE]: ChatGoogleGenerativeAI,
39
+ [Providers.GOOGLE]: CustomChatGoogleGenerativeAI,
39
40
  };
40
41
 
41
42
  export const manualToolStreamProviders = new Set<Providers | string>([
package/src/llm/text.ts CHANGED
@@ -1,4 +1,3 @@
1
-
2
1
  export interface TextStreamOptions {
3
2
  minChunkSize?: number;
4
3
  maxChunkSize?: number;
@@ -30,7 +29,15 @@ export class TextStream {
30
29
  return Math.floor(Math.random() * (max - min)) + min;
31
30
  }
32
31
 
33
- private static readonly BOUNDARIES = new Set([' ', '.', ',', '!', '?', ';', ':']);
32
+ private static readonly BOUNDARIES = new Set([
33
+ ' ',
34
+ '.',
35
+ ',',
36
+ '!',
37
+ '?',
38
+ ';',
39
+ ':',
40
+ ]);
34
41
 
35
42
  private findFirstWordBoundary(text: string, minSize: number): number {
36
43
  if (minSize >= text.length) return text.length;
@@ -49,11 +56,17 @@ export class TextStream {
49
56
  return text.length; // If no boundary found, return entire remaining text
50
57
  }
51
58
 
52
- async *generateText(progressCallback?: ProgressCallback): AsyncGenerator<string, void, unknown> {
59
+ async *generateText(
60
+ signal?: AbortSignal,
61
+ progressCallback?: ProgressCallback
62
+ ): AsyncGenerator<string, void, unknown> {
53
63
  const { delay, minChunkSize, maxChunkSize } = this;
54
64
 
55
65
  while (this.currentIndex < this.text.length) {
56
- await new Promise(resolve => setTimeout(resolve, delay));
66
+ if (signal?.aborted === true) {
67
+ break;
68
+ }
69
+ await new Promise((resolve) => setTimeout(resolve, delay));
57
70
 
58
71
  const remainingText = this.text.slice(this.currentIndex);
59
72
  let chunkSize: number;
@@ -62,14 +75,20 @@ export class TextStream {
62
75
  chunkSize = this.findFirstWordBoundary(remainingText, minChunkSize);
63
76
  } else {
64
77
  const remainingChars = remainingText.length;
65
- chunkSize = Math.min(this.randomInt(minChunkSize, maxChunkSize + 1), remainingChars);
78
+ chunkSize = Math.min(
79
+ this.randomInt(minChunkSize, maxChunkSize + 1),
80
+ remainingChars
81
+ );
66
82
  }
67
83
 
68
- const chunk = this.text.slice(this.currentIndex, this.currentIndex + chunkSize);
84
+ const chunk = this.text.slice(
85
+ this.currentIndex,
86
+ this.currentIndex + chunkSize
87
+ );
69
88
  progressCallback?.(chunk);
70
89
 
71
90
  yield chunk;
72
91
  this.currentIndex += chunkSize;
73
92
  }
74
93
  }
75
- }
94
+ }
@@ -0,0 +1,360 @@
1
+ import { ChatGoogle } from '@langchain/google-gauth';
2
+ import { ChatConnection } from '@langchain/google-common';
3
+ import type {
4
+ GeminiRequest,
5
+ GoogleAIModelRequestParams,
6
+ GoogleAbstractedClient,
7
+ } from '@langchain/google-common';
8
+ import type { BaseMessage } from '@langchain/core/messages';
9
+ import type { VertexAIClientOptions } from '@/types';
10
+
11
+ class CustomChatConnection extends ChatConnection<VertexAIClientOptions> {
12
+ async formatData(
13
+ input: BaseMessage[],
14
+ parameters: GoogleAIModelRequestParams
15
+ ): Promise<unknown> {
16
+ const formattedData = (await super.formatData(
17
+ input,
18
+ parameters
19
+ )) as GeminiRequest;
20
+ if (
21
+ formattedData.generationConfig?.thinkingConfig?.thinkingBudget === -1 &&
22
+ formattedData.generationConfig.thinkingConfig.includeThoughts === false
23
+ ) {
24
+ formattedData.generationConfig.thinkingConfig.includeThoughts = true;
25
+ }
26
+ return formattedData;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Integration with Google Vertex AI chat models.
32
+ *
33
+ * Setup:
34
+ * Install `@langchain/google-vertexai` and set your stringified
35
+ * Vertex AI credentials as an environment variable named `GOOGLE_APPLICATION_CREDENTIALS`.
36
+ *
37
+ * ```bash
38
+ * npm install @langchain/google-vertexai
39
+ * export GOOGLE_APPLICATION_CREDENTIALS="path/to/credentials"
40
+ * ```
41
+ *
42
+ * ## [Constructor args](https://api.js.langchain.com/classes/_langchain_google_vertexai.index.ChatVertexAI.html#constructor.new_ChatVertexAI)
43
+ *
44
+ * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_common_types.GoogleAIBaseLanguageModelCallOptions.html)
45
+ *
46
+ * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
47
+ * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:
48
+ *
49
+ * ```typescript
50
+ * // When calling `.withConfig`, call options should be passed via the first argument
51
+ * const llmWithArgsBound = llm.withConfig({
52
+ * stop: ["\n"],
53
+ * tools: [...],
54
+ * });
55
+ *
56
+ * // When calling `.bindTools`, call options should be passed via the second argument
57
+ * const llmWithTools = llm.bindTools(
58
+ * [...],
59
+ * {
60
+ * tool_choice: "auto",
61
+ * }
62
+ * );
63
+ * ```
64
+ *
65
+ * ## Examples
66
+ *
67
+ * <details open>
68
+ * <summary><strong>Instantiate</strong></summary>
69
+ *
70
+ * ```typescript
71
+ * import { ChatVertexAI } from '@langchain/google-vertexai';
72
+ *
73
+ * const llm = new ChatVertexAI({
74
+ * model: "gemini-1.5-pro",
75
+ * temperature: 0,
76
+ * // other params...
77
+ * });
78
+ * ```
79
+ * </details>
80
+ *
81
+ * <br />
82
+ *
83
+ * <details>
84
+ * <summary><strong>Invoking</strong></summary>
85
+ *
86
+ * ```typescript
87
+ * const input = `Translate "I love programming" into French.`;
88
+ *
89
+ * // Models also accept a list of chat messages or a formatted prompt
90
+ * const result = await llm.invoke(input);
91
+ * console.log(result);
92
+ * ```
93
+ *
94
+ * ```txt
95
+ * AIMessageChunk {
96
+ * "content": "\"J'adore programmer\" \n\nHere's why this is the best translation:\n\n* **J'adore** means \"I love\" and conveys a strong passion.\n* **Programmer** is the French verb for \"to program.\"\n\nThis translation is natural and idiomatic in French. \n",
97
+ * "additional_kwargs": {},
98
+ * "response_metadata": {},
99
+ * "tool_calls": [],
100
+ * "tool_call_chunks": [],
101
+ * "invalid_tool_calls": [],
102
+ * "usage_metadata": {
103
+ * "input_tokens": 9,
104
+ * "output_tokens": 63,
105
+ * "total_tokens": 72
106
+ * }
107
+ * }
108
+ * ```
109
+ * </details>
110
+ *
111
+ * <br />
112
+ *
113
+ * <details>
114
+ * <summary><strong>Streaming Chunks</strong></summary>
115
+ *
116
+ * ```typescript
117
+ * for await (const chunk of await llm.stream(input)) {
118
+ * console.log(chunk);
119
+ * }
120
+ * ```
121
+ *
122
+ * ```txt
123
+ * AIMessageChunk {
124
+ * "content": "\"",
125
+ * "additional_kwargs": {},
126
+ * "response_metadata": {},
127
+ * "tool_calls": [],
128
+ * "tool_call_chunks": [],
129
+ * "invalid_tool_calls": []
130
+ * }
131
+ * AIMessageChunk {
132
+ * "content": "J'adore programmer\" \n",
133
+ * "additional_kwargs": {},
134
+ * "response_metadata": {},
135
+ * "tool_calls": [],
136
+ * "tool_call_chunks": [],
137
+ * "invalid_tool_calls": []
138
+ * }
139
+ * AIMessageChunk {
140
+ * "content": "",
141
+ * "additional_kwargs": {},
142
+ * "response_metadata": {},
143
+ * "tool_calls": [],
144
+ * "tool_call_chunks": [],
145
+ * "invalid_tool_calls": []
146
+ * }
147
+ * AIMessageChunk {
148
+ * "content": "",
149
+ * "additional_kwargs": {},
150
+ * "response_metadata": {
151
+ * "finishReason": "stop"
152
+ * },
153
+ * "tool_calls": [],
154
+ * "tool_call_chunks": [],
155
+ * "invalid_tool_calls": [],
156
+ * "usage_metadata": {
157
+ * "input_tokens": 9,
158
+ * "output_tokens": 8,
159
+ * "total_tokens": 17
160
+ * }
161
+ * }
162
+ * ```
163
+ * </details>
164
+ *
165
+ * <br />
166
+ *
167
+ * <details>
168
+ * <summary><strong>Aggregate Streamed Chunks</strong></summary>
169
+ *
170
+ * ```typescript
171
+ * import { AIMessageChunk } from '@langchain/core/messages';
172
+ * import { concat } from '@langchain/core/utils/stream';
173
+ *
174
+ * const stream = await llm.stream(input);
175
+ * let full: AIMessageChunk | undefined;
176
+ * for await (const chunk of stream) {
177
+ * full = !full ? chunk : concat(full, chunk);
178
+ * }
179
+ * console.log(full);
180
+ * ```
181
+ *
182
+ * ```txt
183
+ * AIMessageChunk {
184
+ * "content": "\"J'adore programmer\" \n",
185
+ * "additional_kwargs": {},
186
+ * "response_metadata": {
187
+ * "finishReason": "stop"
188
+ * },
189
+ * "tool_calls": [],
190
+ * "tool_call_chunks": [],
191
+ * "invalid_tool_calls": [],
192
+ * "usage_metadata": {
193
+ * "input_tokens": 9,
194
+ * "output_tokens": 8,
195
+ * "total_tokens": 17
196
+ * }
197
+ * }
198
+ * ```
199
+ * </details>
200
+ *
201
+ * <br />
202
+ *
203
+ * <details>
204
+ * <summary><strong>Bind tools</strong></summary>
205
+ *
206
+ * ```typescript
207
+ * import { z } from 'zod';
208
+ *
209
+ * const GetWeather = {
210
+ * name: "GetWeather",
211
+ * description: "Get the current weather in a given location",
212
+ * schema: z.object({
213
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
214
+ * }),
215
+ * }
216
+ *
217
+ * const GetPopulation = {
218
+ * name: "GetPopulation",
219
+ * description: "Get the current population in a given location",
220
+ * schema: z.object({
221
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
222
+ * }),
223
+ * }
224
+ *
225
+ * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);
226
+ * const aiMsg = await llmWithTools.invoke(
227
+ * "Which city is hotter today and which is bigger: LA or NY?"
228
+ * );
229
+ * console.log(aiMsg.tool_calls);
230
+ * ```
231
+ *
232
+ * ```txt
233
+ * [
234
+ * {
235
+ * name: 'GetPopulation',
236
+ * args: { location: 'New York City, NY' },
237
+ * id: '33c1c1f47e2f492799c77d2800a43912',
238
+ * type: 'tool_call'
239
+ * }
240
+ * ]
241
+ * ```
242
+ * </details>
243
+ *
244
+ * <br />
245
+ *
246
+ * <details>
247
+ * <summary><strong>Structured Output</strong></summary>
248
+ *
249
+ * ```typescript
250
+ * import { z } from 'zod';
251
+ *
252
+ * const Joke = z.object({
253
+ * setup: z.string().describe("The setup of the joke"),
254
+ * punchline: z.string().describe("The punchline to the joke"),
255
+ * rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
256
+ * }).describe('Joke to tell user.');
257
+ *
258
+ * const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" });
259
+ * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
260
+ * console.log(jokeResult);
261
+ * ```
262
+ *
263
+ * ```txt
264
+ * {
265
+ * setup: 'What do you call a cat that loves to bowl?',
266
+ * punchline: 'An alley cat!'
267
+ * }
268
+ * ```
269
+ * </details>
270
+ *
271
+ * <br />
272
+ *
273
+ * <details>
274
+ * <summary><strong>Usage Metadata</strong></summary>
275
+ *
276
+ * ```typescript
277
+ * const aiMsgForMetadata = await llm.invoke(input);
278
+ * console.log(aiMsgForMetadata.usage_metadata);
279
+ * ```
280
+ *
281
+ * ```txt
282
+ * { input_tokens: 9, output_tokens: 8, total_tokens: 17 }
283
+ * ```
284
+ * </details>
285
+ *
286
+ * <br />
287
+ *
288
+ * <details>
289
+ * <summary><strong>Stream Usage Metadata</strong></summary>
290
+ *
291
+ * ```typescript
292
+ * const streamForMetadata = await llm.stream(
293
+ * input,
294
+ * {
295
+ * streamUsage: true
296
+ * }
297
+ * );
298
+ * let fullForMetadata: AIMessageChunk | undefined;
299
+ * for await (const chunk of streamForMetadata) {
300
+ * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);
301
+ * }
302
+ * console.log(fullForMetadata?.usage_metadata);
303
+ * ```
304
+ *
305
+ * ```txt
306
+ * { input_tokens: 9, output_tokens: 8, total_tokens: 17 }
307
+ * ```
308
+ * </details>
309
+ *
310
+ * <br />
311
+ */
312
+ export class ChatVertexAI extends ChatGoogle {
313
+ lc_namespace = ['langchain', 'chat_models', 'vertexai'];
314
+ dynamicThinkingBudget = false;
315
+
316
+ static lc_name(): 'ChatVertexAI' {
317
+ return 'ChatVertexAI';
318
+ }
319
+
320
+ constructor(fields?: VertexAIClientOptions) {
321
+ let dynamicThinkingBudget = false;
322
+ if (fields?.thinkingBudget === -1) {
323
+ dynamicThinkingBudget = true;
324
+ fields.thinkingBudget = 1;
325
+ }
326
+ super({
327
+ ...fields,
328
+ platformType: 'gcp',
329
+ });
330
+ this.dynamicThinkingBudget = dynamicThinkingBudget;
331
+ }
332
+ invocationParams(
333
+ options?: this['ParsedCallOptions'] | undefined
334
+ ): GoogleAIModelRequestParams {
335
+ const params = super.invocationParams(options);
336
+ if (this.dynamicThinkingBudget) {
337
+ params.maxReasoningTokens = -1;
338
+ }
339
+ return params;
340
+ }
341
+
342
+ buildConnection(
343
+ fields: VertexAIClientOptions,
344
+ client: GoogleAbstractedClient
345
+ ): void {
346
+ this.connection = new CustomChatConnection(
347
+ { ...fields, ...this },
348
+ this.caller,
349
+ client,
350
+ false
351
+ );
352
+
353
+ this.streamedConnection = new CustomChatConnection(
354
+ { ...fields, ...this },
355
+ this.caller,
356
+ client,
357
+ true
358
+ );
359
+ }
360
+ }
@@ -0,0 +1,80 @@
1
+ import {
2
+ BaseMessage,
3
+ BaseMessageLike,
4
+ coerceMessageLikeToMessage,
5
+ } from '@langchain/core/messages';
6
+ import { v4 } from 'uuid';
7
+
8
+ export const REMOVE_ALL_MESSAGES = '__remove_all__';
9
+
10
+ export type Messages =
11
+ | Array<BaseMessage | BaseMessageLike>
12
+ | BaseMessage
13
+ | BaseMessageLike;
14
+
15
+ /**
16
+ * Prebuilt reducer that combines returned messages.
17
+ * Can handle standard messages and special modifiers like {@link RemoveMessage}
18
+ * instances.
19
+ */
20
+ export function messagesStateReducer(
21
+ left: Messages,
22
+ right: Messages
23
+ ): BaseMessage[] {
24
+ const leftArray = Array.isArray(left) ? left : [left];
25
+ const rightArray = Array.isArray(right) ? right : [right];
26
+ // coerce to message
27
+ const leftMessages = (leftArray as BaseMessageLike[]).map(
28
+ coerceMessageLikeToMessage
29
+ );
30
+ const rightMessages = (rightArray as BaseMessageLike[]).map(
31
+ coerceMessageLikeToMessage
32
+ );
33
+ // assign missing ids
34
+ for (const m of leftMessages) {
35
+ if (m.id === null || m.id === undefined) {
36
+ m.id = v4();
37
+ m.lc_kwargs.id = m.id;
38
+ }
39
+ }
40
+
41
+ let removeAllIdx: number | undefined;
42
+ for (let i = 0; i < rightMessages.length; i += 1) {
43
+ const m = rightMessages[i];
44
+ if (m.id === null || m.id === undefined) {
45
+ m.id = v4();
46
+ m.lc_kwargs.id = m.id;
47
+ }
48
+
49
+ if (m.getType() === 'remove' && m.id === REMOVE_ALL_MESSAGES) {
50
+ removeAllIdx = i;
51
+ }
52
+ }
53
+
54
+ if (removeAllIdx != null) return rightMessages.slice(removeAllIdx + 1);
55
+
56
+ // merge
57
+ const merged = [...leftMessages];
58
+ const mergedById = new Map(merged.map((m, i) => [m.id, i]));
59
+ const idsToRemove = new Set();
60
+ for (const m of rightMessages) {
61
+ const existingIdx = mergedById.get(m.id);
62
+ if (existingIdx !== undefined) {
63
+ if (m.getType() === 'remove') {
64
+ idsToRemove.add(m.id);
65
+ } else {
66
+ idsToRemove.delete(m.id);
67
+ merged[existingIdx] = m;
68
+ }
69
+ } else {
70
+ if (m.getType() === 'remove') {
71
+ throw new Error(
72
+ `Attempting to delete a message with an ID that doesn't exist ('${m.id}')`
73
+ );
74
+ }
75
+ mergedById.set(m.id, merged.length);
76
+ merged.push(m);
77
+ }
78
+ }
79
+ return merged.filter((m) => !idsToRemove.has(m.id));
80
+ }