@librechat/agents 2.4.322 → 3.0.0-rc10

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 (279) 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 +15 -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 -213
  8. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  9. package/dist/cjs/graphs/MultiAgentGraph.cjs +507 -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 +422 -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 +137 -85
  41. package/dist/cjs/run.cjs.map +1 -1
  42. package/dist/cjs/stream.cjs +86 -52
  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 +16 -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 -215
  75. package/dist/esm/graphs/Graph.mjs.map +1 -1
  76. package/dist/esm/graphs/MultiAgentGraph.mjs +505 -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 +421 -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 +138 -87
  108. package/dist/esm/run.mjs.map +1 -1
  109. package/dist/esm/stream.mjs +88 -55
  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 +17 -7
  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 +47 -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 +82 -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/stream.d.ts +10 -3
  161. package/dist/types/tools/CodeExecutor.d.ts +2 -2
  162. package/dist/types/tools/ToolNode.d.ts +1 -1
  163. package/dist/types/tools/handlers.d.ts +17 -4
  164. package/dist/types/tools/search/anthropic.d.ts +16 -0
  165. package/dist/types/tools/search/firecrawl.d.ts +15 -0
  166. package/dist/types/tools/search/rerankers.d.ts +0 -1
  167. package/dist/types/tools/search/types.d.ts +30 -9
  168. package/dist/types/types/graph.d.ts +129 -15
  169. package/dist/types/types/llm.d.ts +25 -10
  170. package/dist/types/types/run.d.ts +50 -8
  171. package/dist/types/types/stream.d.ts +16 -2
  172. package/dist/types/types/tools.d.ts +1 -1
  173. package/dist/types/utils/events.d.ts +6 -0
  174. package/dist/types/utils/title.d.ts +2 -1
  175. package/dist/types/utils/tokens.d.ts +24 -0
  176. package/package.json +41 -17
  177. package/src/agents/AgentContext.ts +315 -0
  178. package/src/common/enum.ts +15 -5
  179. package/src/events.ts +24 -13
  180. package/src/graphs/Graph.ts +495 -313
  181. package/src/graphs/MultiAgentGraph.ts +598 -0
  182. package/src/graphs/index.ts +2 -1
  183. package/src/llm/anthropic/Jacob_Lee_Resume_2023.pdf +0 -0
  184. package/src/llm/anthropic/index.ts +78 -13
  185. package/src/llm/anthropic/llm.spec.ts +491 -115
  186. package/src/llm/anthropic/types.ts +39 -3
  187. package/src/llm/anthropic/utils/message_inputs.ts +67 -11
  188. package/src/llm/anthropic/utils/message_outputs.ts +21 -2
  189. package/src/llm/anthropic/utils/output_parsers.ts +25 -6
  190. package/src/llm/anthropic/utils/tools.ts +29 -0
  191. package/src/llm/google/index.ts +218 -0
  192. package/src/llm/google/types.ts +43 -0
  193. package/src/llm/google/utils/common.ts +646 -0
  194. package/src/llm/google/utils/tools.ts +160 -0
  195. package/src/llm/google/utils/zod_to_genai_parameters.ts +86 -0
  196. package/src/llm/ollama/index.ts +89 -0
  197. package/src/llm/ollama/utils.ts +193 -0
  198. package/src/llm/openai/index.ts +641 -14
  199. package/src/llm/openai/types.ts +24 -0
  200. package/src/llm/openai/utils/index.ts +912 -0
  201. package/src/llm/openai/utils/isReasoningModel.test.ts +90 -0
  202. package/src/llm/providers.ts +10 -9
  203. package/src/llm/text.ts +26 -7
  204. package/src/llm/vertexai/index.ts +360 -0
  205. package/src/messages/reducer.ts +80 -0
  206. package/src/run.ts +196 -116
  207. package/src/scripts/ant_web_search.ts +158 -0
  208. package/src/scripts/args.ts +12 -8
  209. package/src/scripts/cli4.ts +29 -21
  210. package/src/scripts/cli5.ts +29 -21
  211. package/src/scripts/code_exec.ts +54 -23
  212. package/src/scripts/code_exec_files.ts +48 -17
  213. package/src/scripts/code_exec_simple.ts +46 -27
  214. package/src/scripts/handoff-test.ts +135 -0
  215. package/src/scripts/image.ts +52 -20
  216. package/src/scripts/multi-agent-chain.ts +278 -0
  217. package/src/scripts/multi-agent-conditional.ts +220 -0
  218. package/src/scripts/multi-agent-document-review-chain.ts +197 -0
  219. package/src/scripts/multi-agent-hybrid-flow.ts +310 -0
  220. package/src/scripts/multi-agent-parallel.ts +341 -0
  221. package/src/scripts/multi-agent-sequence.ts +212 -0
  222. package/src/scripts/multi-agent-supervisor.ts +362 -0
  223. package/src/scripts/multi-agent-test.ts +186 -0
  224. package/src/scripts/search.ts +1 -9
  225. package/src/scripts/simple.ts +25 -10
  226. package/src/scripts/test-custom-prompt-key.ts +145 -0
  227. package/src/scripts/test-handoff-input.ts +170 -0
  228. package/src/scripts/test-multi-agent-list-handoff.ts +261 -0
  229. package/src/scripts/test-tools-before-handoff.ts +233 -0
  230. package/src/scripts/tools.ts +48 -18
  231. package/src/specs/anthropic.simple.test.ts +150 -34
  232. package/src/specs/azure.simple.test.ts +325 -0
  233. package/src/specs/openai.simple.test.ts +140 -33
  234. package/src/specs/openrouter.simple.test.ts +107 -0
  235. package/src/specs/prune.test.ts +4 -9
  236. package/src/specs/reasoning.test.ts +80 -44
  237. package/src/specs/token-memoization.test.ts +39 -0
  238. package/src/stream.test.ts +94 -0
  239. package/src/stream.ts +143 -61
  240. package/src/tools/ToolNode.ts +21 -7
  241. package/src/tools/handlers.ts +192 -18
  242. package/src/tools/search/anthropic.ts +51 -0
  243. package/src/tools/search/firecrawl.ts +69 -20
  244. package/src/tools/search/format.ts +6 -8
  245. package/src/tools/search/rerankers.ts +7 -40
  246. package/src/tools/search/search.ts +97 -16
  247. package/src/tools/search/tool.ts +5 -2
  248. package/src/tools/search/types.ts +30 -10
  249. package/src/tools/search/utils.ts +1 -1
  250. package/src/types/graph.ts +318 -103
  251. package/src/types/llm.ts +26 -12
  252. package/src/types/run.ts +56 -13
  253. package/src/types/stream.ts +22 -1
  254. package/src/types/tools.ts +16 -10
  255. package/src/utils/events.ts +32 -0
  256. package/src/utils/llmConfig.ts +19 -7
  257. package/src/utils/title.ts +104 -30
  258. package/src/utils/tokens.ts +69 -10
  259. package/dist/types/scripts/abort.d.ts +0 -1
  260. package/dist/types/scripts/args.d.ts +0 -6
  261. package/dist/types/scripts/caching.d.ts +0 -1
  262. package/dist/types/scripts/cli.d.ts +0 -1
  263. package/dist/types/scripts/cli2.d.ts +0 -1
  264. package/dist/types/scripts/cli3.d.ts +0 -1
  265. package/dist/types/scripts/cli4.d.ts +0 -1
  266. package/dist/types/scripts/cli5.d.ts +0 -1
  267. package/dist/types/scripts/code_exec.d.ts +0 -1
  268. package/dist/types/scripts/code_exec_files.d.ts +0 -1
  269. package/dist/types/scripts/code_exec_simple.d.ts +0 -1
  270. package/dist/types/scripts/content.d.ts +0 -1
  271. package/dist/types/scripts/empty_input.d.ts +0 -1
  272. package/dist/types/scripts/image.d.ts +0 -1
  273. package/dist/types/scripts/memory.d.ts +0 -1
  274. package/dist/types/scripts/search.d.ts +0 -1
  275. package/dist/types/scripts/simple.d.ts +0 -1
  276. package/dist/types/scripts/stream.d.ts +0 -1
  277. package/dist/types/scripts/thinking.d.ts +0 -1
  278. package/dist/types/scripts/tools.d.ts +0 -1
  279. package/dist/types/specs/spec.utils.d.ts +0 -1
@@ -0,0 +1,646 @@
1
+ import {
2
+ POSSIBLE_ROLES,
3
+ type Part,
4
+ type Content,
5
+ type TextPart,
6
+ type FileDataPart,
7
+ type InlineDataPart,
8
+ type FunctionCallPart,
9
+ type GenerateContentCandidate,
10
+ type EnhancedGenerateContentResponse,
11
+ type FunctionDeclaration as GenerativeAIFunctionDeclaration,
12
+ type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,
13
+ } from '@google/generative-ai';
14
+ import {
15
+ AIMessageChunk,
16
+ BaseMessage,
17
+ ChatMessage,
18
+ ToolMessage,
19
+ ToolMessageChunk,
20
+ MessageContent,
21
+ MessageContentComplex,
22
+ UsageMetadata,
23
+ isAIMessage,
24
+ isBaseMessage,
25
+ isToolMessage,
26
+ StandardContentBlockConverter,
27
+ parseBase64DataUrl,
28
+ convertToProviderContentBlock,
29
+ isDataContentBlock,
30
+ } from '@langchain/core/messages';
31
+ import { ChatGenerationChunk } from '@langchain/core/outputs';
32
+ import type { ChatGeneration } from '@langchain/core/outputs';
33
+ import { isLangChainTool } from '@langchain/core/utils/function_calling';
34
+ import { isOpenAITool } from '@langchain/core/language_models/base';
35
+ import { ToolCallChunk } from '@langchain/core/messages/tool';
36
+ import { v4 as uuidv4 } from 'uuid';
37
+ import {
38
+ jsonSchemaToGeminiParameters,
39
+ schemaToGenerativeAIParameters,
40
+ } from './zod_to_genai_parameters';
41
+ import { GoogleGenerativeAIToolType } from '../types';
42
+
43
+ export function getMessageAuthor(message: BaseMessage): string {
44
+ const type = message._getType();
45
+ if (ChatMessage.isInstance(message)) {
46
+ return message.role;
47
+ }
48
+ if (type === 'tool') {
49
+ return type;
50
+ }
51
+ return message.name ?? type;
52
+ }
53
+
54
+ /**
55
+ * Maps a message type to a Google Generative AI chat author.
56
+ * @param message The message to map.
57
+ * @param model The model to use for mapping.
58
+ * @returns The message type mapped to a Google Generative AI chat author.
59
+ */
60
+ export function convertAuthorToRole(
61
+ author: string
62
+ ): (typeof POSSIBLE_ROLES)[number] {
63
+ switch (author) {
64
+ /**
65
+ * Note: Gemini currently is not supporting system messages
66
+ * we will convert them to human messages and merge with following
67
+ * */
68
+ case 'supervisor':
69
+ case 'ai':
70
+ case 'model': // getMessageAuthor returns message.name. code ex.: return message.name ?? type;
71
+ return 'model';
72
+ case 'system':
73
+ return 'system';
74
+ case 'human':
75
+ return 'user';
76
+ case 'tool':
77
+ case 'function':
78
+ return 'function';
79
+ default:
80
+ throw new Error(`Unknown / unsupported author: ${author}`);
81
+ }
82
+ }
83
+
84
+ function messageContentMedia(content: MessageContentComplex): Part {
85
+ if ('mimeType' in content && 'data' in content) {
86
+ return {
87
+ inlineData: {
88
+ mimeType: content.mimeType,
89
+ data: content.data,
90
+ },
91
+ };
92
+ }
93
+ if ('mimeType' in content && 'fileUri' in content) {
94
+ return {
95
+ fileData: {
96
+ mimeType: content.mimeType,
97
+ fileUri: content.fileUri,
98
+ },
99
+ };
100
+ }
101
+
102
+ throw new Error('Invalid media content');
103
+ }
104
+
105
+ function inferToolNameFromPreviousMessages(
106
+ message: ToolMessage | ToolMessageChunk,
107
+ previousMessages: BaseMessage[]
108
+ ): string | undefined {
109
+ return previousMessages
110
+ .map((msg) => {
111
+ if (isAIMessage(msg)) {
112
+ return msg.tool_calls ?? [];
113
+ }
114
+ return [];
115
+ })
116
+ .flat()
117
+ .find((toolCall) => {
118
+ return toolCall.id === message.tool_call_id;
119
+ })?.name;
120
+ }
121
+
122
+ function _getStandardContentBlockConverter(
123
+ isMultimodalModel: boolean
124
+ ): StandardContentBlockConverter<{
125
+ text: TextPart;
126
+ image: FileDataPart | InlineDataPart;
127
+ audio: FileDataPart | InlineDataPart;
128
+ file: FileDataPart | InlineDataPart | TextPart;
129
+ }> {
130
+ const standardContentBlockConverter: StandardContentBlockConverter<{
131
+ text: TextPart;
132
+ image: FileDataPart | InlineDataPart;
133
+ audio: FileDataPart | InlineDataPart;
134
+ file: FileDataPart | InlineDataPart | TextPart;
135
+ }> = {
136
+ providerName: 'Google Gemini',
137
+
138
+ fromStandardTextBlock(block) {
139
+ return {
140
+ text: block.text,
141
+ };
142
+ },
143
+
144
+ fromStandardImageBlock(block): FileDataPart | InlineDataPart {
145
+ if (!isMultimodalModel) {
146
+ throw new Error('This model does not support images');
147
+ }
148
+ if (block.source_type === 'url') {
149
+ const data = parseBase64DataUrl({ dataUrl: block.url });
150
+ if (data) {
151
+ return {
152
+ inlineData: {
153
+ mimeType: data.mime_type,
154
+ data: data.data,
155
+ },
156
+ };
157
+ } else {
158
+ return {
159
+ fileData: {
160
+ mimeType: block.mime_type ?? '',
161
+ fileUri: block.url,
162
+ },
163
+ };
164
+ }
165
+ }
166
+
167
+ if (block.source_type === 'base64') {
168
+ return {
169
+ inlineData: {
170
+ mimeType: block.mime_type ?? '',
171
+ data: block.data,
172
+ },
173
+ };
174
+ }
175
+
176
+ throw new Error(`Unsupported source type: ${block.source_type}`);
177
+ },
178
+
179
+ fromStandardAudioBlock(block): FileDataPart | InlineDataPart {
180
+ if (!isMultimodalModel) {
181
+ throw new Error('This model does not support audio');
182
+ }
183
+ if (block.source_type === 'url') {
184
+ const data = parseBase64DataUrl({ dataUrl: block.url });
185
+ if (data) {
186
+ return {
187
+ inlineData: {
188
+ mimeType: data.mime_type,
189
+ data: data.data,
190
+ },
191
+ };
192
+ } else {
193
+ return {
194
+ fileData: {
195
+ mimeType: block.mime_type ?? '',
196
+ fileUri: block.url,
197
+ },
198
+ };
199
+ }
200
+ }
201
+
202
+ if (block.source_type === 'base64') {
203
+ return {
204
+ inlineData: {
205
+ mimeType: block.mime_type ?? '',
206
+ data: block.data,
207
+ },
208
+ };
209
+ }
210
+
211
+ throw new Error(`Unsupported source type: ${block.source_type}`);
212
+ },
213
+
214
+ fromStandardFileBlock(block): FileDataPart | InlineDataPart | TextPart {
215
+ if (!isMultimodalModel) {
216
+ throw new Error('This model does not support files');
217
+ }
218
+ if (block.source_type === 'text') {
219
+ return {
220
+ text: block.text,
221
+ };
222
+ }
223
+ if (block.source_type === 'url') {
224
+ const data = parseBase64DataUrl({ dataUrl: block.url });
225
+ if (data) {
226
+ return {
227
+ inlineData: {
228
+ mimeType: data.mime_type,
229
+ data: data.data,
230
+ },
231
+ };
232
+ } else {
233
+ return {
234
+ fileData: {
235
+ mimeType: block.mime_type ?? '',
236
+ fileUri: block.url,
237
+ },
238
+ };
239
+ }
240
+ }
241
+
242
+ if (block.source_type === 'base64') {
243
+ return {
244
+ inlineData: {
245
+ mimeType: block.mime_type ?? '',
246
+ data: block.data,
247
+ },
248
+ };
249
+ }
250
+ throw new Error(`Unsupported source type: ${block.source_type}`);
251
+ },
252
+ };
253
+ return standardContentBlockConverter;
254
+ }
255
+
256
+ function _convertLangChainContentToPart(
257
+ content: MessageContentComplex,
258
+ isMultimodalModel: boolean
259
+ ): Part | undefined {
260
+ if (isDataContentBlock(content)) {
261
+ return convertToProviderContentBlock(
262
+ content,
263
+ _getStandardContentBlockConverter(isMultimodalModel)
264
+ );
265
+ }
266
+
267
+ if (content.type === 'text') {
268
+ return { text: content.text };
269
+ } else if (content.type === 'executableCode') {
270
+ return { executableCode: content.executableCode };
271
+ } else if (content.type === 'codeExecutionResult') {
272
+ return { codeExecutionResult: content.codeExecutionResult };
273
+ } else if (content.type === 'image_url') {
274
+ if (!isMultimodalModel) {
275
+ throw new Error('This model does not support images');
276
+ }
277
+ let source: string;
278
+ if (typeof content.image_url === 'string') {
279
+ source = content.image_url;
280
+ } else if (
281
+ typeof content.image_url === 'object' &&
282
+ 'url' in content.image_url
283
+ ) {
284
+ source = content.image_url.url;
285
+ } else {
286
+ throw new Error('Please provide image as base64 encoded data URL');
287
+ }
288
+ const [dm, data] = source.split(',');
289
+ if (!dm.startsWith('data:')) {
290
+ throw new Error('Please provide image as base64 encoded data URL');
291
+ }
292
+
293
+ const [mimeType, encoding] = dm.replace(/^data:/, '').split(';');
294
+ if (encoding !== 'base64') {
295
+ throw new Error('Please provide image as base64 encoded data URL');
296
+ }
297
+
298
+ return {
299
+ inlineData: {
300
+ data,
301
+ mimeType,
302
+ },
303
+ };
304
+ } else if (content.type === 'media') {
305
+ return messageContentMedia(content);
306
+ } else if (content.type === 'tool_use') {
307
+ return {
308
+ functionCall: {
309
+ name: content.name,
310
+ args: content.input,
311
+ },
312
+ };
313
+ } else if (
314
+ content.type?.includes('/') === true &&
315
+ // Ensure it's a single slash.
316
+ content.type.split('/').length === 2 &&
317
+ 'data' in content &&
318
+ typeof content.data === 'string'
319
+ ) {
320
+ return {
321
+ inlineData: {
322
+ mimeType: content.type,
323
+ data: content.data,
324
+ },
325
+ };
326
+ } else if ('functionCall' in content) {
327
+ // No action needed here — function calls will be added later from message.tool_calls
328
+ return undefined;
329
+ } else {
330
+ if ('type' in content) {
331
+ throw new Error(`Unknown content type ${content.type}`);
332
+ } else {
333
+ throw new Error(`Unknown content ${JSON.stringify(content)}`);
334
+ }
335
+ }
336
+ }
337
+
338
+ export function convertMessageContentToParts(
339
+ message: BaseMessage,
340
+ isMultimodalModel: boolean,
341
+ previousMessages: BaseMessage[]
342
+ ): Part[] {
343
+ if (isToolMessage(message)) {
344
+ const messageName =
345
+ message.name ??
346
+ inferToolNameFromPreviousMessages(message, previousMessages);
347
+ if (messageName === undefined) {
348
+ throw new Error(
349
+ `Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${message.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`
350
+ );
351
+ }
352
+
353
+ const result = Array.isArray(message.content)
354
+ ? (message.content
355
+ .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))
356
+ .filter((p) => p !== undefined) as Part[])
357
+ : message.content;
358
+
359
+ if (message.status === 'error') {
360
+ return [
361
+ {
362
+ functionResponse: {
363
+ name: messageName,
364
+ // The API expects an object with an `error` field if the function call fails.
365
+ // `error` must be a valid object (not a string or array), so we wrap `message.content` here
366
+ response: { error: { details: result } },
367
+ },
368
+ },
369
+ ];
370
+ }
371
+
372
+ return [
373
+ {
374
+ functionResponse: {
375
+ name: messageName,
376
+ // again, can't have a string or array value for `response`, so we wrap it as an object here
377
+ response: { result },
378
+ },
379
+ },
380
+ ];
381
+ }
382
+
383
+ let functionCalls: FunctionCallPart[] = [];
384
+ const messageParts: Part[] = [];
385
+
386
+ if (typeof message.content === 'string' && message.content) {
387
+ messageParts.push({ text: message.content });
388
+ }
389
+
390
+ if (Array.isArray(message.content)) {
391
+ messageParts.push(
392
+ ...(message.content
393
+ .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))
394
+ .filter((p) => p !== undefined) as Part[])
395
+ );
396
+ }
397
+
398
+ if (isAIMessage(message) && message.tool_calls?.length != null) {
399
+ functionCalls = message.tool_calls.map((tc) => {
400
+ return {
401
+ functionCall: {
402
+ name: tc.name,
403
+ args: tc.args,
404
+ },
405
+ };
406
+ });
407
+ }
408
+
409
+ return [...messageParts, ...functionCalls];
410
+ }
411
+
412
+ export function convertBaseMessagesToContent(
413
+ messages: BaseMessage[],
414
+ isMultimodalModel: boolean,
415
+ convertSystemMessageToHumanContent: boolean = false
416
+ ): Content[] | undefined {
417
+ return messages.reduce<{
418
+ content: Content[] | undefined;
419
+ mergeWithPreviousContent: boolean;
420
+ }>(
421
+ (acc, message, index) => {
422
+ if (!isBaseMessage(message)) {
423
+ throw new Error('Unsupported message input');
424
+ }
425
+ const author = getMessageAuthor(message);
426
+ if (author === 'system' && index !== 0) {
427
+ throw new Error('System message should be the first one');
428
+ }
429
+ const role = convertAuthorToRole(author);
430
+
431
+ const prevContent = acc.content?.[acc.content.length];
432
+ if (
433
+ !acc.mergeWithPreviousContent &&
434
+ prevContent &&
435
+ prevContent.role === role
436
+ ) {
437
+ throw new Error(
438
+ 'Google Generative AI requires alternate messages between authors'
439
+ );
440
+ }
441
+
442
+ const parts = convertMessageContentToParts(
443
+ message,
444
+ isMultimodalModel,
445
+ messages.slice(0, index)
446
+ );
447
+
448
+ if (acc.mergeWithPreviousContent) {
449
+ const prevContent = acc.content?.[acc.content.length - 1];
450
+ if (!prevContent) {
451
+ throw new Error(
452
+ 'There was a problem parsing your system message. Please try a prompt without one.'
453
+ );
454
+ }
455
+ prevContent.parts.push(...parts);
456
+
457
+ return {
458
+ mergeWithPreviousContent: false,
459
+ content: acc.content,
460
+ };
461
+ }
462
+ let actualRole = role;
463
+ if (
464
+ actualRole === 'function' ||
465
+ (actualRole === 'system' && !convertSystemMessageToHumanContent)
466
+ ) {
467
+ // GenerativeAI API will throw an error if the role is not "user" or "model."
468
+ actualRole = 'user';
469
+ }
470
+ const content: Content = {
471
+ role: actualRole,
472
+ parts,
473
+ };
474
+ return {
475
+ mergeWithPreviousContent:
476
+ author === 'system' && !convertSystemMessageToHumanContent,
477
+ content: [...(acc.content ?? []), content],
478
+ };
479
+ },
480
+ { content: [], mergeWithPreviousContent: false }
481
+ ).content;
482
+ }
483
+
484
+ export function convertResponseContentToChatGenerationChunk(
485
+ response: EnhancedGenerateContentResponse,
486
+ extra: {
487
+ usageMetadata?: UsageMetadata | undefined;
488
+ index: number;
489
+ }
490
+ ): ChatGenerationChunk | null {
491
+ if (!response.candidates || response.candidates.length === 0) {
492
+ return null;
493
+ }
494
+ const functionCalls = response.functionCalls();
495
+ const [candidate] = response.candidates as [
496
+ Partial<GenerateContentCandidate> | undefined,
497
+ ];
498
+ const { content: candidateContent, ...generationInfo } = candidate ?? {};
499
+ let content: MessageContent | undefined;
500
+ // Checks if some parts do not have text. If false, it means that the content is a string.
501
+ const reasoningParts: string[] = [];
502
+ if (
503
+ candidateContent != null &&
504
+ Array.isArray(candidateContent.parts) &&
505
+ candidateContent.parts.every((p) => 'text' in p)
506
+ ) {
507
+ // content = candidateContent.parts.map((p) => p.text).join('');
508
+ const textParts: string[] = [];
509
+ for (const part of candidateContent.parts) {
510
+ if ('thought' in part && part.thought === true) {
511
+ reasoningParts.push(part.text ?? '');
512
+ continue;
513
+ }
514
+ textParts.push(part.text ?? '');
515
+ }
516
+ content = textParts.join('');
517
+ } else if (candidateContent && Array.isArray(candidateContent.parts)) {
518
+ content = candidateContent.parts.map((p) => {
519
+ if ('text' in p && 'thought' in p && p.thought === true) {
520
+ reasoningParts.push(p.text ?? '');
521
+ } else if ('text' in p) {
522
+ return {
523
+ type: 'text',
524
+ text: p.text,
525
+ };
526
+ } else if ('executableCode' in p) {
527
+ return {
528
+ type: 'executableCode',
529
+ executableCode: p.executableCode,
530
+ };
531
+ } else if ('codeExecutionResult' in p) {
532
+ return {
533
+ type: 'codeExecutionResult',
534
+ codeExecutionResult: p.codeExecutionResult,
535
+ };
536
+ }
537
+ return p;
538
+ });
539
+ } else {
540
+ // no content returned - likely due to abnormal stop reason, e.g. malformed function call
541
+ content = [];
542
+ }
543
+
544
+ let text = '';
545
+ if (typeof content === 'string' && content) {
546
+ text = content;
547
+ } else if (Array.isArray(content)) {
548
+ const block = content.find((b) => 'text' in b) as
549
+ | { text: string }
550
+ | undefined;
551
+ text = block?.text ?? '';
552
+ }
553
+
554
+ const toolCallChunks: ToolCallChunk[] = [];
555
+ if (functionCalls) {
556
+ toolCallChunks.push(
557
+ ...functionCalls.map((fc) => ({
558
+ ...fc,
559
+ args: JSON.stringify(fc.args),
560
+ // Un-commenting this causes LangChain to incorrectly merge tool calls together
561
+ // index: extra.index,
562
+ type: 'tool_call_chunk' as const,
563
+ id: 'id' in fc && typeof fc.id === 'string' ? fc.id : uuidv4(),
564
+ }))
565
+ );
566
+ }
567
+
568
+ const additional_kwargs: ChatGeneration['message']['additional_kwargs'] = {};
569
+ if (reasoningParts.length > 0) {
570
+ additional_kwargs.reasoning = reasoningParts.join('');
571
+ }
572
+
573
+ if (candidate?.groundingMetadata) {
574
+ additional_kwargs.groundingMetadata = candidate.groundingMetadata;
575
+ }
576
+
577
+ const isFinalChunk =
578
+ response.candidates[0]?.finishReason === 'STOP' ||
579
+ response.candidates[0]?.finishReason === 'MAX_TOKENS' ||
580
+ response.candidates[0]?.finishReason === 'SAFETY';
581
+
582
+ return new ChatGenerationChunk({
583
+ text,
584
+ message: new AIMessageChunk({
585
+ content: content,
586
+ name: !candidateContent ? undefined : candidateContent.role,
587
+ tool_call_chunks: toolCallChunks,
588
+ // Each chunk can have unique "generationInfo", and merging strategy is unclear,
589
+ // so leave blank for now.
590
+ additional_kwargs,
591
+ usage_metadata: isFinalChunk ? extra.usageMetadata : undefined,
592
+ }),
593
+ generationInfo,
594
+ });
595
+ }
596
+
597
+ export function convertToGenerativeAITools(
598
+ tools: GoogleGenerativeAIToolType[]
599
+ ): GoogleGenerativeAIFunctionDeclarationsTool[] {
600
+ if (
601
+ tools.every(
602
+ (tool) =>
603
+ 'functionDeclarations' in tool &&
604
+ Array.isArray(tool.functionDeclarations)
605
+ )
606
+ ) {
607
+ return tools as GoogleGenerativeAIFunctionDeclarationsTool[];
608
+ }
609
+ return [
610
+ {
611
+ functionDeclarations: tools.map(
612
+ (tool): GenerativeAIFunctionDeclaration => {
613
+ if (isLangChainTool(tool)) {
614
+ const jsonSchema = schemaToGenerativeAIParameters(tool.schema);
615
+ if (
616
+ jsonSchema.type === 'object' &&
617
+ 'properties' in jsonSchema &&
618
+ Object.keys(jsonSchema.properties).length === 0
619
+ ) {
620
+ return {
621
+ name: tool.name,
622
+ description: tool.description,
623
+ };
624
+ }
625
+ return {
626
+ name: tool.name,
627
+ description: tool.description,
628
+ parameters: jsonSchema,
629
+ };
630
+ }
631
+ if (isOpenAITool(tool)) {
632
+ return {
633
+ name: tool.function.name,
634
+ description:
635
+ tool.function.description ?? 'A function available to call.',
636
+ parameters: jsonSchemaToGeminiParameters(
637
+ tool.function.parameters
638
+ ),
639
+ };
640
+ }
641
+ return tool as unknown as GenerativeAIFunctionDeclaration;
642
+ }
643
+ ),
644
+ },
645
+ ];
646
+ }