@librechat/agents 2.4.322 → 3.0.0-rc1

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 (258) 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 +322 -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 +320 -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-test.d.ts +1 -0
  167. package/dist/types/stream.d.ts +10 -3
  168. package/dist/types/tools/CodeExecutor.d.ts +2 -2
  169. package/dist/types/tools/ToolNode.d.ts +1 -1
  170. package/dist/types/tools/handlers.d.ts +17 -4
  171. package/dist/types/tools/search/anthropic.d.ts +16 -0
  172. package/dist/types/tools/search/firecrawl.d.ts +15 -0
  173. package/dist/types/tools/search/rerankers.d.ts +0 -1
  174. package/dist/types/tools/search/types.d.ts +30 -9
  175. package/dist/types/types/graph.d.ts +95 -15
  176. package/dist/types/types/llm.d.ts +24 -10
  177. package/dist/types/types/run.d.ts +46 -8
  178. package/dist/types/types/stream.d.ts +16 -2
  179. package/dist/types/types/tools.d.ts +1 -1
  180. package/dist/types/utils/events.d.ts +6 -0
  181. package/dist/types/utils/title.d.ts +2 -1
  182. package/dist/types/utils/tokens.d.ts +24 -0
  183. package/package.json +33 -17
  184. package/src/agents/AgentContext.ts +315 -0
  185. package/src/common/enum.ts +14 -5
  186. package/src/events.ts +24 -13
  187. package/src/graphs/Graph.ts +495 -312
  188. package/src/graphs/MultiAgentGraph.ts +381 -0
  189. package/src/graphs/index.ts +2 -1
  190. package/src/llm/anthropic/Jacob_Lee_Resume_2023.pdf +0 -0
  191. package/src/llm/anthropic/index.ts +78 -13
  192. package/src/llm/anthropic/llm.spec.ts +491 -115
  193. package/src/llm/anthropic/types.ts +39 -3
  194. package/src/llm/anthropic/utils/message_inputs.ts +67 -11
  195. package/src/llm/anthropic/utils/message_outputs.ts +21 -2
  196. package/src/llm/anthropic/utils/output_parsers.ts +25 -6
  197. package/src/llm/anthropic/utils/tools.ts +29 -0
  198. package/src/llm/google/index.ts +218 -0
  199. package/src/llm/google/types.ts +43 -0
  200. package/src/llm/google/utils/common.ts +646 -0
  201. package/src/llm/google/utils/tools.ts +160 -0
  202. package/src/llm/google/utils/zod_to_genai_parameters.ts +86 -0
  203. package/src/llm/ollama/index.ts +89 -0
  204. package/src/llm/ollama/utils.ts +193 -0
  205. package/src/llm/openai/index.ts +600 -14
  206. package/src/llm/openai/types.ts +24 -0
  207. package/src/llm/openai/utils/index.ts +912 -0
  208. package/src/llm/openai/utils/isReasoningModel.test.ts +90 -0
  209. package/src/llm/providers.ts +10 -9
  210. package/src/llm/text.ts +26 -7
  211. package/src/llm/vertexai/index.ts +360 -0
  212. package/src/messages/reducer.ts +80 -0
  213. package/src/run.ts +181 -112
  214. package/src/scripts/ant_web_search.ts +158 -0
  215. package/src/scripts/args.ts +12 -8
  216. package/src/scripts/cli4.ts +29 -21
  217. package/src/scripts/cli5.ts +29 -21
  218. package/src/scripts/code_exec.ts +54 -23
  219. package/src/scripts/code_exec_files.ts +48 -17
  220. package/src/scripts/code_exec_simple.ts +46 -27
  221. package/src/scripts/handoff-test.ts +135 -0
  222. package/src/scripts/image.ts +52 -20
  223. package/src/scripts/multi-agent-conditional.ts +220 -0
  224. package/src/scripts/multi-agent-example-output.md +110 -0
  225. package/src/scripts/multi-agent-parallel.ts +337 -0
  226. package/src/scripts/multi-agent-sequence.ts +212 -0
  227. package/src/scripts/multi-agent-test.ts +186 -0
  228. package/src/scripts/search.ts +1 -9
  229. package/src/scripts/simple.ts +25 -10
  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 +139 -60
  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 +272 -103
  251. package/src/types/llm.ts +25 -12
  252. package/src/types/run.ts +51 -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
@@ -0,0 +1,160 @@
1
+ import {
2
+ Tool as GenerativeAITool,
3
+ ToolConfig,
4
+ FunctionCallingMode,
5
+ FunctionDeclaration,
6
+ FunctionDeclarationsTool,
7
+ FunctionDeclarationSchema,
8
+ } from '@google/generative-ai';
9
+ import { ToolChoice } from '@langchain/core/language_models/chat_models';
10
+ import { StructuredToolInterface } from '@langchain/core/tools';
11
+ import { isLangChainTool } from '@langchain/core/utils/function_calling';
12
+ import {
13
+ isOpenAITool,
14
+ ToolDefinition,
15
+ } from '@langchain/core/language_models/base';
16
+ import { convertToGenerativeAITools } from './common';
17
+ import { GoogleGenerativeAIToolType } from '../types';
18
+ import { removeAdditionalProperties } from './zod_to_genai_parameters';
19
+
20
+ export function convertToolsToGenAI(
21
+ tools: GoogleGenerativeAIToolType[],
22
+ extra?: {
23
+ toolChoice?: ToolChoice;
24
+ allowedFunctionNames?: string[];
25
+ }
26
+ ): {
27
+ tools: GenerativeAITool[];
28
+ toolConfig?: ToolConfig;
29
+ } {
30
+ // Extract function declaration processing to a separate function
31
+ const genAITools = processTools(tools);
32
+
33
+ // Simplify tool config creation
34
+ const toolConfig = createToolConfig(genAITools, extra);
35
+
36
+ return { tools: genAITools, toolConfig };
37
+ }
38
+
39
+ function processTools(tools: GoogleGenerativeAIToolType[]): GenerativeAITool[] {
40
+ let functionDeclarationTools: FunctionDeclaration[] = [];
41
+ const genAITools: GenerativeAITool[] = [];
42
+
43
+ tools.forEach((tool) => {
44
+ if (isLangChainTool(tool)) {
45
+ const [convertedTool] = convertToGenerativeAITools([
46
+ tool as StructuredToolInterface,
47
+ ]);
48
+ if (convertedTool.functionDeclarations) {
49
+ functionDeclarationTools.push(...convertedTool.functionDeclarations);
50
+ }
51
+ } else if (isOpenAITool(tool)) {
52
+ const { functionDeclarations } = convertOpenAIToolToGenAI(tool);
53
+ if (functionDeclarations) {
54
+ functionDeclarationTools.push(...functionDeclarations);
55
+ } else {
56
+ throw new Error(
57
+ 'Failed to convert OpenAI structured tool to GenerativeAI tool'
58
+ );
59
+ }
60
+ } else {
61
+ genAITools.push(tool as GenerativeAITool);
62
+ }
63
+ });
64
+
65
+ const genAIFunctionDeclaration = genAITools.find(
66
+ (t) => 'functionDeclarations' in t
67
+ );
68
+ if (genAIFunctionDeclaration) {
69
+ return genAITools.map((tool) => {
70
+ if (
71
+ functionDeclarationTools.length > 0 &&
72
+ 'functionDeclarations' in tool
73
+ ) {
74
+ const newTool = {
75
+ functionDeclarations: [
76
+ ...(tool.functionDeclarations || []),
77
+ ...functionDeclarationTools,
78
+ ],
79
+ };
80
+ // Clear the functionDeclarationTools array so it is not passed again
81
+ functionDeclarationTools = [];
82
+ return newTool;
83
+ }
84
+ return tool;
85
+ });
86
+ }
87
+
88
+ return [
89
+ ...genAITools,
90
+ ...(functionDeclarationTools.length > 0
91
+ ? [
92
+ {
93
+ functionDeclarations: functionDeclarationTools,
94
+ },
95
+ ]
96
+ : []),
97
+ ];
98
+ }
99
+
100
+ function convertOpenAIToolToGenAI(
101
+ tool: ToolDefinition
102
+ ): FunctionDeclarationsTool {
103
+ return {
104
+ functionDeclarations: [
105
+ {
106
+ name: tool.function.name,
107
+ description: tool.function.description,
108
+ parameters: removeAdditionalProperties(
109
+ tool.function.parameters
110
+ ) as FunctionDeclarationSchema,
111
+ },
112
+ ],
113
+ };
114
+ }
115
+
116
+ function createToolConfig(
117
+ genAITools: GenerativeAITool[],
118
+ extra?: {
119
+ toolChoice?: ToolChoice;
120
+ allowedFunctionNames?: string[];
121
+ }
122
+ ): ToolConfig | undefined {
123
+ if (!genAITools.length || !extra) return undefined;
124
+
125
+ const { toolChoice, allowedFunctionNames } = extra;
126
+
127
+ const modeMap: Record<string, FunctionCallingMode> = {
128
+ any: FunctionCallingMode.ANY,
129
+ auto: FunctionCallingMode.AUTO,
130
+ none: FunctionCallingMode.NONE,
131
+ };
132
+
133
+ if (
134
+ toolChoice != null &&
135
+ ['any', 'auto', 'none'].includes(toolChoice as string)
136
+ ) {
137
+ return {
138
+ functionCallingConfig: {
139
+ mode: modeMap[toolChoice as keyof typeof modeMap] ?? 'MODE_UNSPECIFIED',
140
+ allowedFunctionNames,
141
+ },
142
+ };
143
+ }
144
+
145
+ if (typeof toolChoice === 'string' || allowedFunctionNames) {
146
+ return {
147
+ functionCallingConfig: {
148
+ mode: FunctionCallingMode.ANY,
149
+ allowedFunctionNames: [
150
+ ...(allowedFunctionNames ?? []),
151
+ ...(toolChoice != null && typeof toolChoice === 'string'
152
+ ? [toolChoice]
153
+ : []),
154
+ ],
155
+ },
156
+ };
157
+ }
158
+
159
+ return undefined;
160
+ }
@@ -0,0 +1,86 @@
1
+ import {
2
+ type FunctionDeclarationSchema as GenerativeAIFunctionDeclarationSchema,
3
+ type SchemaType as FunctionDeclarationSchemaType,
4
+ } from '@google/generative-ai';
5
+ import {
6
+ InteropZodType,
7
+ isInteropZodSchema,
8
+ } from '@langchain/core/utils/types';
9
+ import {
10
+ type JsonSchema7Type,
11
+ toJsonSchema,
12
+ } from '@langchain/core/utils/json_schema';
13
+
14
+ export interface GenerativeAIJsonSchema extends Record<string, unknown> {
15
+ properties?: Record<string, GenerativeAIJsonSchema>;
16
+ type: FunctionDeclarationSchemaType;
17
+ }
18
+
19
+ export interface GenerativeAIJsonSchemaDirty extends GenerativeAIJsonSchema {
20
+ properties?: Record<string, GenerativeAIJsonSchemaDirty>;
21
+ additionalProperties?: boolean;
22
+ }
23
+
24
+ export function removeAdditionalProperties(
25
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
26
+ obj: Record<string, any>
27
+ ): GenerativeAIJsonSchema {
28
+ if (typeof obj === 'object' && obj !== null) {
29
+ const newObj = { ...obj };
30
+
31
+ if ('additionalProperties' in newObj) {
32
+ delete newObj.additionalProperties;
33
+ }
34
+ if ('$schema' in newObj) {
35
+ delete newObj.$schema;
36
+ }
37
+ if ('strict' in newObj) {
38
+ delete newObj.strict;
39
+ }
40
+
41
+ for (const key in newObj) {
42
+ if (key in newObj) {
43
+ if (Array.isArray(newObj[key])) {
44
+ newObj[key] = newObj[key].map(removeAdditionalProperties);
45
+ } else if (typeof newObj[key] === 'object' && newObj[key] !== null) {
46
+ newObj[key] = removeAdditionalProperties(newObj[key]);
47
+ }
48
+ }
49
+ }
50
+
51
+ return newObj as GenerativeAIJsonSchema;
52
+ }
53
+
54
+ return obj as GenerativeAIJsonSchema;
55
+ }
56
+
57
+ export function schemaToGenerativeAIParameters<
58
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
+ RunOutput extends Record<string, any> = Record<string, any>,
60
+ >(
61
+ schema: InteropZodType<RunOutput> | JsonSchema7Type
62
+ ): GenerativeAIFunctionDeclarationSchema {
63
+ // GenerativeAI doesn't accept either the $schema or additionalProperties
64
+ // attributes, so we need to explicitly remove them.
65
+ const jsonSchema = removeAdditionalProperties(
66
+ isInteropZodSchema(schema) ? toJsonSchema(schema) : schema
67
+ );
68
+ const { $schema: _s, ...rest } = jsonSchema;
69
+
70
+ return rest as GenerativeAIFunctionDeclarationSchema;
71
+ }
72
+
73
+ export function jsonSchemaToGeminiParameters(
74
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
75
+ schema: Record<string, any>
76
+ ): GenerativeAIFunctionDeclarationSchema {
77
+ // Gemini doesn't accept either the $schema or additionalProperties
78
+ // attributes, so we need to explicitly remove them.
79
+
80
+ const jsonSchema = removeAdditionalProperties(
81
+ schema as GenerativeAIJsonSchemaDirty
82
+ );
83
+ const { $schema: _s, ...rest } = jsonSchema;
84
+
85
+ return rest as GenerativeAIFunctionDeclarationSchema;
86
+ }
@@ -0,0 +1,89 @@
1
+ import { AIMessageChunk } from '@langchain/core/messages';
2
+ import { ChatGenerationChunk } from '@langchain/core/outputs';
3
+ import { ChatOllama as BaseChatOllama } from '@langchain/ollama';
4
+ import { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
5
+ import type {
6
+ ChatResponse as OllamaChatResponse,
7
+ Message as OllamaMessage,
8
+ } from 'ollama';
9
+ import type { UsageMetadata, BaseMessage } from '@langchain/core/messages';
10
+ import {
11
+ convertOllamaMessagesToLangChain,
12
+ convertToOllamaMessages,
13
+ } from './utils';
14
+
15
+ export class ChatOllama extends BaseChatOllama {
16
+ async *_streamResponseChunks(
17
+ messages: BaseMessage[],
18
+ options: this['ParsedCallOptions'],
19
+ runManager?: CallbackManagerForLLMRun
20
+ ): AsyncGenerator<ChatGenerationChunk> {
21
+ if (this.checkOrPullModel) {
22
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
23
+ // @ts-ignore
24
+ if (!((await this.checkModelExistsOnMachine(this.model)) as boolean)) {
25
+ await this.pull(this.model, {
26
+ logProgress: true,
27
+ });
28
+ }
29
+ }
30
+
31
+ const params = this.invocationParams(options);
32
+ // TODO: remove cast after SDK adds support for tool calls
33
+ const ollamaMessages = convertToOllamaMessages(messages) as OllamaMessage[];
34
+
35
+ const usageMetadata: UsageMetadata = {
36
+ input_tokens: 0,
37
+ output_tokens: 0,
38
+ total_tokens: 0,
39
+ };
40
+
41
+ const stream = await this.client.chat({
42
+ ...params,
43
+ messages: ollamaMessages,
44
+ stream: true,
45
+ });
46
+
47
+ let lastMetadata: Omit<OllamaChatResponse, 'message'> | undefined;
48
+
49
+ for await (const chunk of stream) {
50
+ if (options.signal?.aborted === true) {
51
+ this.client.abort();
52
+ }
53
+ const { message: responseMessage, ...rest } =
54
+ chunk as Partial<OllamaChatResponse>;
55
+ usageMetadata.input_tokens += rest.prompt_eval_count ?? 0;
56
+ usageMetadata.output_tokens += rest.eval_count ?? 0;
57
+ usageMetadata.total_tokens =
58
+ usageMetadata.input_tokens + usageMetadata.output_tokens;
59
+ lastMetadata = rest as Omit<OllamaChatResponse, 'message'>;
60
+ if (!responseMessage) {
61
+ continue;
62
+ }
63
+ const message = convertOllamaMessagesToLangChain(responseMessage);
64
+ const generationChunk = new ChatGenerationChunk({
65
+ text: responseMessage.content || '',
66
+ message,
67
+ });
68
+ yield generationChunk;
69
+ await runManager?.handleLLMNewToken(
70
+ responseMessage.content || '',
71
+ undefined,
72
+ undefined,
73
+ undefined,
74
+ undefined,
75
+ { chunk: generationChunk }
76
+ );
77
+ }
78
+
79
+ // Yield the `response_metadata` as the final chunk.
80
+ yield new ChatGenerationChunk({
81
+ text: '',
82
+ message: new AIMessageChunk({
83
+ content: '',
84
+ response_metadata: lastMetadata,
85
+ usage_metadata: usageMetadata,
86
+ }),
87
+ });
88
+ }
89
+ }
@@ -0,0 +1,193 @@
1
+ import {
2
+ AIMessage,
3
+ AIMessageChunk,
4
+ BaseMessage,
5
+ HumanMessage,
6
+ MessageContentText,
7
+ SystemMessage,
8
+ ToolMessage,
9
+ UsageMetadata,
10
+ } from '@langchain/core/messages';
11
+ import type {
12
+ Message as OllamaMessage,
13
+ ToolCall as OllamaToolCall,
14
+ } from 'ollama';
15
+ import { v4 as uuidv4 } from 'uuid';
16
+
17
+ export function convertOllamaMessagesToLangChain(
18
+ messages: OllamaMessage,
19
+ extra?: {
20
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
+ responseMetadata?: Record<string, any>;
22
+ usageMetadata?: UsageMetadata;
23
+ }
24
+ ): AIMessageChunk {
25
+ const additional_kwargs: BaseMessage['additional_kwargs'] = {};
26
+ if ('thinking' in messages) {
27
+ additional_kwargs.reasoning_content = messages.thinking as string;
28
+ }
29
+ return new AIMessageChunk({
30
+ content: messages.content || '',
31
+ tool_call_chunks: messages.tool_calls?.map((tc) => ({
32
+ name: tc.function.name,
33
+ args: JSON.stringify(tc.function.arguments),
34
+ type: 'tool_call_chunk',
35
+ index: 0,
36
+ id: uuidv4(),
37
+ })),
38
+ response_metadata: extra?.responseMetadata,
39
+ usage_metadata: extra?.usageMetadata,
40
+ additional_kwargs,
41
+ });
42
+ }
43
+
44
+ function extractBase64FromDataUrl(dataUrl: string): string {
45
+ const match = dataUrl.match(/^data:.*?;base64,(.*)$/);
46
+ return match ? match[1] : '';
47
+ }
48
+
49
+ function convertAMessagesToOllama(messages: AIMessage): OllamaMessage[] {
50
+ if (typeof messages.content === 'string') {
51
+ return [
52
+ {
53
+ role: 'assistant',
54
+ content: messages.content,
55
+ },
56
+ ];
57
+ }
58
+
59
+ const textFields = messages.content.filter(
60
+ (c) => c.type === 'text' && typeof c.text === 'string'
61
+ );
62
+ const textMessages = (textFields as MessageContentText[]).map((c) => ({
63
+ role: 'assistant',
64
+ content: c.text,
65
+ }));
66
+ let toolCallMsgs: OllamaMessage | undefined;
67
+
68
+ if (
69
+ messages.content.find((c) => c.type === 'tool_use') &&
70
+ messages.tool_calls?.length
71
+ ) {
72
+ // `tool_use` content types are accepted if the message has tool calls
73
+ const toolCalls: OllamaToolCall[] | undefined = messages.tool_calls.map(
74
+ (tc) => ({
75
+ id: tc.id,
76
+ type: 'function',
77
+ function: {
78
+ name: tc.name,
79
+ arguments: tc.args,
80
+ },
81
+ })
82
+ );
83
+
84
+ if (toolCalls) {
85
+ toolCallMsgs = {
86
+ role: 'assistant',
87
+ tool_calls: toolCalls,
88
+ content: '',
89
+ };
90
+ }
91
+ } else if (
92
+ messages.content.find((c) => c.type === 'tool_use') &&
93
+ !messages.tool_calls?.length
94
+ ) {
95
+ throw new Error(
96
+ '\'tool_use\' content type is not supported without tool calls.'
97
+ );
98
+ }
99
+
100
+ return [...textMessages, ...(toolCallMsgs ? [toolCallMsgs] : [])];
101
+ }
102
+
103
+ function convertHumanGenericMessagesToOllama(
104
+ message: HumanMessage
105
+ ): OllamaMessage[] {
106
+ if (typeof message.content === 'string') {
107
+ return [
108
+ {
109
+ role: 'user',
110
+ content: message.content,
111
+ },
112
+ ];
113
+ }
114
+ return message.content.map((c) => {
115
+ if (c.type === 'text') {
116
+ return {
117
+ role: 'user',
118
+ content: c.text,
119
+ };
120
+ } else if (c.type === 'image_url') {
121
+ if (typeof c.image_url === 'string') {
122
+ return {
123
+ role: 'user',
124
+ content: '',
125
+ images: [extractBase64FromDataUrl(c.image_url)],
126
+ };
127
+ } else if (c.image_url.url && typeof c.image_url.url === 'string') {
128
+ return {
129
+ role: 'user',
130
+ content: '',
131
+ images: [extractBase64FromDataUrl(c.image_url.url)],
132
+ };
133
+ }
134
+ }
135
+ throw new Error(`Unsupported content type: ${c.type}`);
136
+ });
137
+ }
138
+
139
+ function convertSystemMessageToOllama(message: SystemMessage): OllamaMessage[] {
140
+ if (typeof message.content === 'string') {
141
+ return [
142
+ {
143
+ role: 'system',
144
+ content: message.content,
145
+ },
146
+ ];
147
+ } else if (
148
+ message.content.every(
149
+ (c) => c.type === 'text' && typeof c.text === 'string'
150
+ )
151
+ ) {
152
+ return (message.content as MessageContentText[]).map((c) => ({
153
+ role: 'system',
154
+ content: c.text,
155
+ }));
156
+ } else {
157
+ throw new Error(
158
+ `Unsupported content type(s): ${message.content
159
+ .map((c) => c.type)
160
+ .join(', ')}`
161
+ );
162
+ }
163
+ }
164
+
165
+ function convertToolMessageToOllama(message: ToolMessage): OllamaMessage[] {
166
+ if (typeof message.content !== 'string') {
167
+ throw new Error('Non string tool message content is not supported');
168
+ }
169
+ return [
170
+ {
171
+ role: 'tool',
172
+ content: message.content,
173
+ },
174
+ ];
175
+ }
176
+
177
+ export function convertToOllamaMessages(
178
+ messages: BaseMessage[]
179
+ ): OllamaMessage[] {
180
+ return messages.flatMap((msg) => {
181
+ if (['human', 'generic'].includes(msg._getType())) {
182
+ return convertHumanGenericMessagesToOllama(msg);
183
+ } else if (msg._getType() === 'ai') {
184
+ return convertAMessagesToOllama(msg);
185
+ } else if (msg._getType() === 'system') {
186
+ return convertSystemMessageToOllama(msg);
187
+ } else if (msg._getType() === 'tool') {
188
+ return convertToolMessageToOllama(msg as ToolMessage);
189
+ } else {
190
+ throw new Error(`Unsupported message type: ${msg._getType()}`);
191
+ }
192
+ });
193
+ }