@mate-academy/llm-gateway 8.8.2 → 8.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (352) hide show
  1. package/dist/LLMError.d.ts +12 -0
  2. package/dist/LLMError.js +36 -0
  3. package/dist/LLMError.js.map +1 -0
  4. package/dist/LLMGateway.d.ts +30 -0
  5. package/dist/LLMGateway.js +56 -0
  6. package/dist/LLMGateway.js.map +1 -0
  7. package/dist/LLMGateway.typedefs.d.ts +5 -0
  8. package/dist/LLMGateway.typedefs.js +3 -0
  9. package/dist/LLMGateway.typedefs.js.map +1 -0
  10. package/dist/LLMService.constants.d.ts +26337 -0
  11. package/dist/LLMService.constants.js +35 -0
  12. package/dist/LLMService.constants.js.map +1 -0
  13. package/dist/LLMService.factory.d.ts +71 -0
  14. package/dist/LLMService.factory.js +102 -0
  15. package/dist/LLMService.factory.js.map +1 -0
  16. package/dist/LLMService.typedefs.d.ts +655 -0
  17. package/dist/LLMService.typedefs.js +72 -0
  18. package/dist/LLMService.typedefs.js.map +1 -0
  19. package/dist/advanced.d.ts +11 -0
  20. package/dist/advanced.js +32 -0
  21. package/dist/advanced.js.map +1 -0
  22. package/dist/client/LLMAgent.d.ts +76 -0
  23. package/dist/client/LLMAgent.js +36 -0
  24. package/dist/client/LLMAgent.js.map +1 -0
  25. package/dist/client/LLMClientEngine.d.ts +110 -0
  26. package/dist/client/LLMClientEngine.js +406 -0
  27. package/dist/client/LLMClientEngine.js.map +1 -0
  28. package/dist/client/agentRun.typedefs.d.ts +200 -0
  29. package/dist/client/agentRun.typedefs.js +25 -0
  30. package/dist/client/agentRun.typedefs.js.map +1 -0
  31. package/dist/client/agentRunner.d.ts +161 -0
  32. package/dist/client/agentRunner.js +517 -0
  33. package/dist/client/agentRunner.js.map +1 -0
  34. package/dist/client/codegen/fetchPromptRecords.d.ts +14 -0
  35. package/dist/client/codegen/fetchPromptRecords.js +90 -0
  36. package/dist/client/codegen/fetchPromptRecords.js.map +1 -0
  37. package/dist/client/codegen/generateSnapshot.d.ts +19 -0
  38. package/dist/client/codegen/generateSnapshot.js +28 -0
  39. package/dist/client/codegen/generateSnapshot.js.map +1 -0
  40. package/dist/client/codegen/index.d.ts +6 -0
  41. package/dist/client/codegen/index.js +23 -0
  42. package/dist/client/codegen/index.js.map +1 -0
  43. package/dist/client/codegen/promptCatalog.typedefs.d.ts +51 -0
  44. package/dist/client/codegen/promptCatalog.typedefs.js +3 -0
  45. package/dist/client/codegen/promptCatalog.typedefs.js.map +1 -0
  46. package/dist/client/codegen/promptName.d.ts +8 -0
  47. package/dist/client/codegen/promptName.js +21 -0
  48. package/dist/client/codegen/promptName.js.map +1 -0
  49. package/dist/client/codegen/renderSnapshot.constants.d.ts +7 -0
  50. package/dist/client/codegen/renderSnapshot.constants.js +16 -0
  51. package/dist/client/codegen/renderSnapshot.constants.js.map +1 -0
  52. package/dist/client/codegen/renderSnapshot.d.ts +9 -0
  53. package/dist/client/codegen/renderSnapshot.js +109 -0
  54. package/dist/client/codegen/renderSnapshot.js.map +1 -0
  55. package/dist/client/codegen/renderSnapshot.typedefs.d.ts +19 -0
  56. package/dist/client/codegen/renderSnapshot.typedefs.js +3 -0
  57. package/dist/client/codegen/renderSnapshot.typedefs.js.map +1 -0
  58. package/dist/client/coerceToolResult.d.ts +10 -0
  59. package/dist/client/coerceToolResult.js +38 -0
  60. package/dist/client/coerceToolResult.js.map +1 -0
  61. package/dist/client/createLLMClient.d.ts +10 -0
  62. package/dist/client/createLLMClient.js +47 -0
  63. package/dist/client/createLLMClient.js.map +1 -0
  64. package/dist/client/defineLLMPrompts.d.ts +34 -0
  65. package/dist/client/defineLLMPrompts.js +13 -0
  66. package/dist/client/defineLLMPrompts.js.map +1 -0
  67. package/dist/client/errors.d.ts +57 -0
  68. package/dist/client/errors.js +70 -0
  69. package/dist/client/errors.js.map +1 -0
  70. package/dist/client/index.d.ts +13 -0
  71. package/dist/client/index.js +30 -0
  72. package/dist/client/index.js.map +1 -0
  73. package/dist/client/llmClient.typedefs.d.ts +265 -0
  74. package/dist/client/llmClient.typedefs.js +11 -0
  75. package/dist/client/llmClient.typedefs.js.map +1 -0
  76. package/dist/client/llmConfig.schema.d.ts +53 -0
  77. package/dist/client/llmConfig.schema.js +49 -0
  78. package/dist/client/llmConfig.schema.js.map +1 -0
  79. package/dist/client/plainMessages.d.ts +12 -0
  80. package/dist/client/plainMessages.js +19 -0
  81. package/dist/client/plainMessages.js.map +1 -0
  82. package/dist/client/promptClientPort.typedefs.d.ts +60 -0
  83. package/dist/client/promptClientPort.typedefs.js +3 -0
  84. package/dist/client/promptClientPort.typedefs.js.map +1 -0
  85. package/dist/client/promptRegistry.runtime.d.ts +121 -0
  86. package/dist/client/promptRegistry.runtime.js +264 -0
  87. package/dist/client/promptRegistry.runtime.js.map +1 -0
  88. package/dist/client/promptSnapshot.typedefs.d.ts +55 -0
  89. package/dist/client/promptSnapshot.typedefs.js +3 -0
  90. package/dist/client/promptSnapshot.typedefs.js.map +1 -0
  91. package/dist/client/promptVariables.d.ts +7 -0
  92. package/dist/client/promptVariables.js +13 -0
  93. package/dist/client/promptVariables.js.map +1 -0
  94. package/dist/client/snapshotRuntime.d.ts +17 -0
  95. package/dist/client/snapshotRuntime.js +42 -0
  96. package/dist/client/snapshotRuntime.js.map +1 -0
  97. package/dist/client/snapshotRuntime.typedefs.d.ts +13 -0
  98. package/dist/client/snapshotRuntime.typedefs.js +3 -0
  99. package/dist/client/snapshotRuntime.typedefs.js.map +1 -0
  100. package/dist/client/validationGate.d.ts +24 -0
  101. package/dist/client/validationGate.js +54 -0
  102. package/dist/client/validationGate.js.map +1 -0
  103. package/dist/codegen.d.ts +6 -0
  104. package/dist/codegen.js +23 -0
  105. package/dist/codegen.js.map +1 -0
  106. package/dist/index.d.ts +10 -0
  107. package/dist/index.js +27 -0
  108. package/dist/index.js.map +1 -0
  109. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAI.constants.d.ts +873 -0
  110. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAI.constants.js +269 -0
  111. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAI.constants.js.map +1 -0
  112. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAI.entity.d.ts +24 -0
  113. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAI.entity.js +210 -0
  114. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAI.entity.js.map +1 -0
  115. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAI.typedefs.d.ts +22 -0
  116. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAI.typedefs.js +20 -0
  117. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAI.typedefs.js.map +1 -0
  118. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAIService.factory.d.ts +6 -0
  119. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAIService.factory.js +18 -0
  120. package/dist/providers/GoogleGenerativeAI/GoogleGenerativeAIService.factory.js.map +1 -0
  121. package/dist/providers/GoogleGenerativeAI/index.d.ts +5 -0
  122. package/dist/providers/GoogleGenerativeAI/index.js +22 -0
  123. package/dist/providers/GoogleGenerativeAI/index.js.map +1 -0
  124. package/dist/providers/GoogleGenerativeAI/schemas/GoogleSchemaAdapter.d.ts +12 -0
  125. package/dist/providers/GoogleGenerativeAI/schemas/GoogleSchemaAdapter.js +72 -0
  126. package/dist/providers/GoogleGenerativeAI/schemas/GoogleSchemaAdapter.js.map +1 -0
  127. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAIAssistance.service.d.ts +71 -0
  128. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAIAssistance.service.js +876 -0
  129. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAIAssistance.service.js.map +1 -0
  130. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAICompletion.service.d.ts +25 -0
  131. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAICompletion.service.js +216 -0
  132. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAICompletion.service.js.map +1 -0
  133. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAISpeechToText.service.d.ts +10 -0
  134. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAISpeechToText.service.js +136 -0
  135. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAISpeechToText.service.js.map +1 -0
  136. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAITextToSpeech.service.d.ts +11 -0
  137. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAITextToSpeech.service.js +97 -0
  138. package/dist/providers/GoogleGenerativeAI/services/GoogleGenerativeAITextToSpeech.service.js.map +1 -0
  139. package/dist/providers/GoogleGenerativeAI/services/index.d.ts +4 -0
  140. package/dist/providers/GoogleGenerativeAI/services/index.js +21 -0
  141. package/dist/providers/GoogleGenerativeAI/services/index.js.map +1 -0
  142. package/dist/providers/LLMAPI/LLMAPI.constants.d.ts +35874 -0
  143. package/dist/providers/LLMAPI/LLMAPI.constants.js +8663 -0
  144. package/dist/providers/LLMAPI/LLMAPI.constants.js.map +1 -0
  145. package/dist/providers/LLMAPI/LLMAPI.entity.d.ts +6 -0
  146. package/dist/providers/LLMAPI/LLMAPI.entity.js +48 -0
  147. package/dist/providers/LLMAPI/LLMAPI.entity.js.map +1 -0
  148. package/dist/providers/LLMAPI/LLMAPI.typedefs.d.ts +516 -0
  149. package/dist/providers/LLMAPI/LLMAPI.typedefs.js +564 -0
  150. package/dist/providers/LLMAPI/LLMAPI.typedefs.js.map +1 -0
  151. package/dist/providers/LLMAPI/LLMAPI.voices.d.ts +376 -0
  152. package/dist/providers/LLMAPI/LLMAPI.voices.js +739 -0
  153. package/dist/providers/LLMAPI/LLMAPI.voices.js.map +1 -0
  154. package/dist/providers/LLMAPI/LLMAPIService.factory.d.ts +6 -0
  155. package/dist/providers/LLMAPI/LLMAPIService.factory.js +19 -0
  156. package/dist/providers/LLMAPI/LLMAPIService.factory.js.map +1 -0
  157. package/dist/providers/LLMAPI/index.d.ts +7 -0
  158. package/dist/providers/LLMAPI/index.js +24 -0
  159. package/dist/providers/LLMAPI/index.js.map +1 -0
  160. package/dist/providers/LLMAPI/schemas/LLMAPISchemaAdapter.d.ts +3 -0
  161. package/dist/providers/LLMAPI/schemas/LLMAPISchemaAdapter.js +8 -0
  162. package/dist/providers/LLMAPI/schemas/LLMAPISchemaAdapter.js.map +1 -0
  163. package/dist/providers/LLMAPI/services/LLMAPIAssistance.service.d.ts +76 -0
  164. package/dist/providers/LLMAPI/services/LLMAPIAssistance.service.js +825 -0
  165. package/dist/providers/LLMAPI/services/LLMAPIAssistance.service.js.map +1 -0
  166. package/dist/providers/LLMAPI/services/LLMAPICompletion.service.d.ts +25 -0
  167. package/dist/providers/LLMAPI/services/LLMAPICompletion.service.js +177 -0
  168. package/dist/providers/LLMAPI/services/LLMAPICompletion.service.js.map +1 -0
  169. package/dist/providers/LLMAPI/services/LLMAPISpeechToText.service.d.ts +17 -0
  170. package/dist/providers/LLMAPI/services/LLMAPISpeechToText.service.js +34 -0
  171. package/dist/providers/LLMAPI/services/LLMAPISpeechToText.service.js.map +1 -0
  172. package/dist/providers/LLMAPI/services/LLMAPITextToSpeech.service.d.ts +20 -0
  173. package/dist/providers/LLMAPI/services/LLMAPITextToSpeech.service.js +36 -0
  174. package/dist/providers/LLMAPI/services/LLMAPITextToSpeech.service.js.map +1 -0
  175. package/dist/providers/LLMAPI/services/index.d.ts +4 -0
  176. package/dist/providers/LLMAPI/services/index.js +21 -0
  177. package/dist/providers/LLMAPI/services/index.js.map +1 -0
  178. package/dist/providers/LLMAPI/utilities/index.d.ts +4 -0
  179. package/dist/providers/LLMAPI/utilities/index.js +13 -0
  180. package/dist/providers/LLMAPI/utilities/index.js.map +1 -0
  181. package/dist/providers/LLMAPI/utilities/parseXmlToolCalls.d.ts +7 -0
  182. package/dist/providers/LLMAPI/utilities/parseXmlToolCalls.js +35 -0
  183. package/dist/providers/LLMAPI/utilities/parseXmlToolCalls.js.map +1 -0
  184. package/dist/providers/LLMAPI/utilities/stripThinkingTags.d.ts +1 -0
  185. package/dist/providers/LLMAPI/utilities/stripThinkingTags.js +7 -0
  186. package/dist/providers/LLMAPI/utilities/stripThinkingTags.js.map +1 -0
  187. package/dist/providers/LLMAPI/utilities/structuredOutput.d.ts +13 -0
  188. package/dist/providers/LLMAPI/utilities/structuredOutput.js +29 -0
  189. package/dist/providers/LLMAPI/utilities/structuredOutput.js.map +1 -0
  190. package/dist/providers/LLMAPI/utilities/validateStructuredResponse.d.ts +10 -0
  191. package/dist/providers/LLMAPI/utilities/validateStructuredResponse.js +21 -0
  192. package/dist/providers/LLMAPI/utilities/validateStructuredResponse.js.map +1 -0
  193. package/dist/providers/OpenAI/OpenAI.constants.d.ts +1664 -0
  194. package/dist/providers/OpenAI/OpenAI.constants.js +310 -0
  195. package/dist/providers/OpenAI/OpenAI.constants.js.map +1 -0
  196. package/dist/providers/OpenAI/OpenAI.entity.d.ts +15 -0
  197. package/dist/providers/OpenAI/OpenAI.entity.js +162 -0
  198. package/dist/providers/OpenAI/OpenAI.entity.js.map +1 -0
  199. package/dist/providers/OpenAI/OpenAI.typedefs.d.ts +61 -0
  200. package/dist/providers/OpenAI/OpenAI.typedefs.js +39 -0
  201. package/dist/providers/OpenAI/OpenAI.typedefs.js.map +1 -0
  202. package/dist/providers/OpenAI/OpenAIService.factory.d.ts +6 -0
  203. package/dist/providers/OpenAI/OpenAIService.factory.js +18 -0
  204. package/dist/providers/OpenAI/OpenAIService.factory.js.map +1 -0
  205. package/dist/providers/OpenAI/index.d.ts +5 -0
  206. package/dist/providers/OpenAI/index.js +22 -0
  207. package/dist/providers/OpenAI/index.js.map +1 -0
  208. package/dist/providers/OpenAI/schemas/OpenAISchemaAdapter.d.ts +14 -0
  209. package/dist/providers/OpenAI/schemas/OpenAISchemaAdapter.js +87 -0
  210. package/dist/providers/OpenAI/schemas/OpenAISchemaAdapter.js.map +1 -0
  211. package/dist/providers/OpenAI/services/OpenAIAssistance.service.d.ts +42 -0
  212. package/dist/providers/OpenAI/services/OpenAIAssistance.service.js +712 -0
  213. package/dist/providers/OpenAI/services/OpenAIAssistance.service.js.map +1 -0
  214. package/dist/providers/OpenAI/services/OpenAICompletion.service.d.ts +7 -0
  215. package/dist/providers/OpenAI/services/OpenAICompletion.service.js +12 -0
  216. package/dist/providers/OpenAI/services/OpenAICompletion.service.js.map +1 -0
  217. package/dist/providers/OpenAI/services/OpenAISpeechToText.service.d.ts +17 -0
  218. package/dist/providers/OpenAI/services/OpenAISpeechToText.service.js +40 -0
  219. package/dist/providers/OpenAI/services/OpenAISpeechToText.service.js.map +1 -0
  220. package/dist/providers/OpenAI/services/OpenAITextToSpeech.service.d.ts +13 -0
  221. package/dist/providers/OpenAI/services/OpenAITextToSpeech.service.js +32 -0
  222. package/dist/providers/OpenAI/services/OpenAITextToSpeech.service.js.map +1 -0
  223. package/dist/providers/OpenAI/services/buildFunctionCallOutput.d.ts +3 -0
  224. package/dist/providers/OpenAI/services/buildFunctionCallOutput.js +19 -0
  225. package/dist/providers/OpenAI/services/buildFunctionCallOutput.js.map +1 -0
  226. package/dist/providers/OpenAI/services/index.d.ts +4 -0
  227. package/dist/providers/OpenAI/services/index.js +21 -0
  228. package/dist/providers/OpenAI/services/index.js.map +1 -0
  229. package/dist/providers/OpenAICompatible/OpenAICompatibleCompletion.service.d.ts +30 -0
  230. package/dist/providers/OpenAICompatible/OpenAICompatibleCompletion.service.js +233 -0
  231. package/dist/providers/OpenAICompatible/OpenAICompatibleCompletion.service.js.map +1 -0
  232. package/dist/providers/OpenAICompatible/OpenAICompatibleSpeechToText.service.d.ts +22 -0
  233. package/dist/providers/OpenAICompatible/OpenAICompatibleSpeechToText.service.js +98 -0
  234. package/dist/providers/OpenAICompatible/OpenAICompatibleSpeechToText.service.js.map +1 -0
  235. package/dist/providers/OpenAICompatible/OpenAICompatibleTextToSpeech.service.d.ts +22 -0
  236. package/dist/providers/OpenAICompatible/OpenAICompatibleTextToSpeech.service.js +67 -0
  237. package/dist/providers/OpenAICompatible/OpenAICompatibleTextToSpeech.service.js.map +1 -0
  238. package/dist/providers/index.d.ts +3 -0
  239. package/dist/providers/index.js +20 -0
  240. package/dist/providers/index.js.map +1 -0
  241. package/dist/services/LLMAssistanceService.abstract.d.ts +39 -0
  242. package/dist/services/LLMAssistanceService.abstract.js +101 -0
  243. package/dist/services/LLMAssistanceService.abstract.js.map +1 -0
  244. package/dist/services/LLMBaseService.abstract.d.ts +161 -0
  245. package/dist/services/LLMBaseService.abstract.js +412 -0
  246. package/dist/services/LLMBaseService.abstract.js.map +1 -0
  247. package/dist/services/LLMCompletionService.abstract.d.ts +16 -0
  248. package/dist/services/LLMCompletionService.abstract.js +12 -0
  249. package/dist/services/LLMCompletionService.abstract.js.map +1 -0
  250. package/dist/services/LLMServicePurposeFactory.abstract.d.ts +12 -0
  251. package/dist/services/LLMServicePurposeFactory.abstract.js +7 -0
  252. package/dist/services/LLMServicePurposeFactory.abstract.js.map +1 -0
  253. package/dist/services/LLMSpeechToTextService.abstract.d.ts +8 -0
  254. package/dist/services/LLMSpeechToTextService.abstract.js +12 -0
  255. package/dist/services/LLMSpeechToTextService.abstract.js.map +1 -0
  256. package/dist/services/LLMTextToSpeechService.abstract.d.ts +8 -0
  257. package/dist/services/LLMTextToSpeechService.abstract.js +12 -0
  258. package/dist/services/LLMTextToSpeechService.abstract.js.map +1 -0
  259. package/dist/services/agentRounds/LLMAgentRounds.d.ts +32 -0
  260. package/dist/services/agentRounds/LLMAgentRounds.js +77 -0
  261. package/dist/services/agentRounds/LLMAgentRounds.js.map +1 -0
  262. package/dist/services/agentRounds/agentRounds.typedefs.d.ts +48 -0
  263. package/dist/services/agentRounds/agentRounds.typedefs.js +3 -0
  264. package/dist/services/agentRounds/agentRounds.typedefs.js.map +1 -0
  265. package/dist/services/agentRounds/index.d.ts +2 -0
  266. package/dist/services/agentRounds/index.js +19 -0
  267. package/dist/services/agentRounds/index.js.map +1 -0
  268. package/dist/services/chatState/CompletionsChatState.d.ts +35 -0
  269. package/dist/services/chatState/CompletionsChatState.js +118 -0
  270. package/dist/services/chatState/CompletionsChatState.js.map +1 -0
  271. package/dist/services/chatState/index.d.ts +1 -0
  272. package/dist/services/chatState/index.js +6 -0
  273. package/dist/services/chatState/index.js.map +1 -0
  274. package/dist/services/fileStorage/FileStorageToolExecutor.d.ts +15 -0
  275. package/dist/services/fileStorage/FileStorageToolExecutor.js +172 -0
  276. package/dist/services/fileStorage/FileStorageToolExecutor.js.map +1 -0
  277. package/dist/services/fileStorage/InMemoryFileStorage.d.ts +20 -0
  278. package/dist/services/fileStorage/InMemoryFileStorage.js +67 -0
  279. package/dist/services/fileStorage/InMemoryFileStorage.js.map +1 -0
  280. package/dist/services/fileStorage/fileStorageTools.d.ts +26 -0
  281. package/dist/services/fileStorage/fileStorageTools.js +68 -0
  282. package/dist/services/fileStorage/fileStorageTools.js.map +1 -0
  283. package/dist/services/fileStorage/index.d.ts +4 -0
  284. package/dist/services/fileStorage/index.js +11 -0
  285. package/dist/services/fileStorage/index.js.map +1 -0
  286. package/dist/services/index.d.ts +7 -0
  287. package/dist/services/index.js +24 -0
  288. package/dist/services/index.js.map +1 -0
  289. package/dist/utilities/calculateCosts.d.ts +4 -0
  290. package/dist/utilities/calculateCosts.js +56 -0
  291. package/dist/utilities/calculateCosts.js.map +1 -0
  292. package/dist/utilities/functional.utils.d.ts +1 -0
  293. package/dist/utilities/functional.utils.js +9 -0
  294. package/dist/utilities/functional.utils.js.map +1 -0
  295. package/dist/utilities/index.d.ts +9 -0
  296. package/dist/utilities/index.js +26 -0
  297. package/dist/utilities/index.js.map +1 -0
  298. package/dist/utilities/llmTracing/index.d.ts +3 -0
  299. package/dist/utilities/llmTracing/index.js +20 -0
  300. package/dist/utilities/llmTracing/index.js.map +1 -0
  301. package/dist/utilities/llmTracing/llmTracing.constants.d.ts +7 -0
  302. package/dist/utilities/llmTracing/llmTracing.constants.js +11 -0
  303. package/dist/utilities/llmTracing/llmTracing.constants.js.map +1 -0
  304. package/dist/utilities/llmTracing/llmTracing.typedefs.d.ts +137 -0
  305. package/dist/utilities/llmTracing/llmTracing.typedefs.js +3 -0
  306. package/dist/utilities/llmTracing/llmTracing.typedefs.js.map +1 -0
  307. package/dist/utilities/llmTracing/noopLLMTracing.d.ts +3 -0
  308. package/dist/utilities/llmTracing/noopLLMTracing.js +36 -0
  309. package/dist/utilities/llmTracing/noopLLMTracing.js.map +1 -0
  310. package/dist/utilities/logger/LLMLoggerInterface.d.ts +36 -0
  311. package/dist/utilities/logger/LLMLoggerInterface.js +3 -0
  312. package/dist/utilities/logger/LLMLoggerInterface.js.map +1 -0
  313. package/dist/utilities/logger/index.d.ts +1 -0
  314. package/dist/utilities/logger/index.js +18 -0
  315. package/dist/utilities/logger/index.js.map +1 -0
  316. package/dist/utilities/promptBuilder.d.ts +58 -0
  317. package/dist/utilities/promptBuilder.js +92 -0
  318. package/dist/utilities/promptBuilder.js.map +1 -0
  319. package/dist/utilities/reporter/LLMReporterInterface.d.ts +46 -0
  320. package/dist/utilities/reporter/LLMReporterInterface.js +3 -0
  321. package/dist/utilities/reporter/LLMReporterInterface.js.map +1 -0
  322. package/dist/utilities/reporter/index.d.ts +1 -0
  323. package/dist/utilities/reporter/index.js +18 -0
  324. package/dist/utilities/reporter/index.js.map +1 -0
  325. package/dist/utilities/schema/LLMSchema.d.ts +112 -0
  326. package/dist/utilities/schema/LLMSchema.js +223 -0
  327. package/dist/utilities/schema/LLMSchema.js.map +1 -0
  328. package/dist/utilities/schema/LLMSchema.typedefs.d.ts +55 -0
  329. package/dist/utilities/schema/LLMSchema.typedefs.js +3 -0
  330. package/dist/utilities/schema/LLMSchema.typedefs.js.map +1 -0
  331. package/dist/utilities/schema/SchemaAdapterRegistry.d.ts +26 -0
  332. package/dist/utilities/schema/SchemaAdapterRegistry.js +32 -0
  333. package/dist/utilities/schema/SchemaAdapterRegistry.js.map +1 -0
  334. package/dist/utilities/schema/index.d.ts +2 -0
  335. package/dist/utilities/schema/index.js +19 -0
  336. package/dist/utilities/schema/index.js.map +1 -0
  337. package/dist/utilities/serializeError.d.ts +9 -0
  338. package/dist/utilities/serializeError.js +69 -0
  339. package/dist/utilities/serializeError.js.map +1 -0
  340. package/dist/utilities/tokenizer.d.ts +4 -0
  341. package/dist/utilities/tokenizer.js +14 -0
  342. package/dist/utilities/tokenizer.js.map +1 -0
  343. package/dist/utilities/tools/LLMTool.d.ts +5 -0
  344. package/dist/utilities/tools/LLMTool.js +10 -0
  345. package/dist/utilities/tools/LLMTool.js.map +1 -0
  346. package/dist/utilities/tools/index.d.ts +2 -0
  347. package/dist/utilities/tools/index.js +8 -0
  348. package/dist/utilities/tools/index.js.map +1 -0
  349. package/dist/utilities/tools/normalizeToolResult.d.ts +15 -0
  350. package/dist/utilities/tools/normalizeToolResult.js +18 -0
  351. package/dist/utilities/tools/normalizeToolResult.js.map +1 -0
  352. package/package.json +1 -1
@@ -0,0 +1,876 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GoogleGenerativeAIAssistanceService = void 0;
4
+ const uuid_1 = require("uuid");
5
+ const genai_1 = require("@google/genai");
6
+ const LLMService_typedefs_1 = require("../../../LLMService.typedefs");
7
+ const serializeError_1 = require("../../../utilities/serializeError");
8
+ const tools_1 = require("../../../utilities/tools");
9
+ const services_1 = require("../../../services");
10
+ const GoogleGenerativeAI_typedefs_1 = require("../../../providers/GoogleGenerativeAI/GoogleGenerativeAI.typedefs");
11
+ const GoogleGenerativeAI_entity_1 = require("../../../providers/GoogleGenerativeAI/GoogleGenerativeAI.entity");
12
+ const GoogleGenerativeAI_constants_1 = require("../../../providers/GoogleGenerativeAI/GoogleGenerativeAI.constants");
13
+ const LLMService_constants_1 = require("../../../LLMService.constants");
14
+ class GoogleGenerativeAIAssistanceService extends services_1.LLMAssistanceService {
15
+ cachedContent = new Map();
16
+ chatSessions = new Map();
17
+ uploadedFiles = new Map();
18
+ uncachedFileStorages = new Map();
19
+ chatInstructions = new Map(); // chatId -> instructions
20
+ constructor(logger, reporter, options) {
21
+ super(LLMService_typedefs_1.LLMProviders.GoogleGenerativeAI, logger, reporter, options);
22
+ }
23
+ get instance() {
24
+ return this.getOrCreateInstance(() => new genai_1.GoogleGenAI(this.options ?? {}));
25
+ }
26
+ async uploadFile(fileOptions) {
27
+ const { path, mimeType, name, abortSignal, reporterContext, } = fileOptions;
28
+ const writeMetrics = this.reporter?.initWriter(reporterContext);
29
+ try {
30
+ const existingFile = await this.getFile(path);
31
+ if (existingFile) {
32
+ return existingFile;
33
+ }
34
+ abortSignal?.throwIfAborted();
35
+ const uploadResult = await this.instance.files.upload({
36
+ file: path,
37
+ config: {
38
+ mimeType,
39
+ displayName: name,
40
+ abortSignal,
41
+ },
42
+ });
43
+ abortSignal?.throwIfAborted();
44
+ if (!uploadResult.name) {
45
+ throw new Error('Upload result did not return a name');
46
+ }
47
+ if (!uploadResult.uri) {
48
+ throw new Error('Upload result did not return a uri');
49
+ }
50
+ if (uploadResult.error) {
51
+ throw uploadResult.error;
52
+ }
53
+ const uploadedFile = {
54
+ name,
55
+ mimeType,
56
+ fileId: uploadResult.name,
57
+ path: uploadResult.uri,
58
+ };
59
+ abortSignal?.throwIfAborted();
60
+ this.uploadedFiles.set(path, uploadedFile);
61
+ await this.writeSuccessMetrics({
62
+ method: this.getMethodName(this.uploadFile),
63
+ model: null,
64
+ usage: {},
65
+ writeMetrics,
66
+ });
67
+ return uploadedFile;
68
+ }
69
+ catch (error) {
70
+ await this.writeErrorMetrics({
71
+ method: this.getMethodName(this.uploadFile),
72
+ model: null,
73
+ isAborted: abortSignal?.aborted,
74
+ writeMetrics,
75
+ });
76
+ this.logRequestFailure({
77
+ method: this.getMethodName(this.uploadFile),
78
+ message: 'Error uploading file',
79
+ error,
80
+ isAborted: abortSignal?.aborted,
81
+ meta: { file: fileOptions },
82
+ });
83
+ return { error };
84
+ }
85
+ }
86
+ async getFile(path) {
87
+ return this.uploadedFiles.get(path) || null;
88
+ }
89
+ async deleteFile(fileId) {
90
+ this.uploadedFiles.delete(fileId);
91
+ await this.instance.files.delete({
92
+ name: fileId,
93
+ });
94
+ }
95
+ async createFileStorage(options) {
96
+ const { uploadedFiles, model, instructions, abortSignal, reporterContext, } = options;
97
+ const writeMetrics = this.reporter?.initWriter(reporterContext);
98
+ try {
99
+ abortSignal?.throwIfAborted();
100
+ const parts = GoogleGenerativeAI_entity_1.GoogleGenerativeAIEntity.getFileDataParts(uploadedFiles);
101
+ const countTokensFn = GoogleGenerativeAI_entity_1.GoogleGenerativeAIEntity
102
+ .getCountTokensFn(this.instance);
103
+ const tokenCount = await countTokensFn(parts, model);
104
+ abortSignal?.throwIfAborted();
105
+ if (tokenCount < GoogleGenerativeAI_constants_1.MIN_CACHE_CONTENT_LENGTH) {
106
+ /**
107
+ * Note: For small files that can't be cached, store them in uncachedFileStorages
108
+ * to be used directly in chat creation
109
+ */
110
+ const storageId = (0, uuid_1.v4)();
111
+ this.uncachedFileStorages.set(storageId, uploadedFiles);
112
+ this.logger
113
+ ?.child(this.getMethodName(this.createFileStorage))
114
+ .info('File storage created without caching (content too small)', {
115
+ storageId,
116
+ tokenCount,
117
+ minRequired: GoogleGenerativeAI_constants_1.MIN_CACHE_CONTENT_LENGTH,
118
+ });
119
+ abortSignal?.throwIfAborted();
120
+ await this.writeSuccessMetrics({
121
+ method: this.getMethodName(this.createFileStorage),
122
+ model,
123
+ usage: {},
124
+ writeMetrics,
125
+ });
126
+ return {
127
+ storageId,
128
+ };
129
+ }
130
+ const cacheResult = await this.instance.caches.create({
131
+ model: model.name,
132
+ config: {
133
+ contents: [
134
+ {
135
+ role: GoogleGenerativeAI_typedefs_1.GoogleGenerativeAIRoles.User,
136
+ parts,
137
+ },
138
+ ],
139
+ systemInstruction: instructions,
140
+ ttl: '1h',
141
+ abortSignal,
142
+ },
143
+ });
144
+ abortSignal?.throwIfAborted();
145
+ if (!cacheResult.name) {
146
+ throw new Error('Cache result did not return a name');
147
+ }
148
+ if (abortSignal?.aborted) {
149
+ throw new Error('File storage creation aborted');
150
+ }
151
+ abortSignal?.throwIfAborted();
152
+ this.cachedContent.set(cacheResult.name, cacheResult);
153
+ await this.writeSuccessMetrics({
154
+ method: this.getMethodName(this.createFileStorage),
155
+ model,
156
+ usage: {},
157
+ writeMetrics,
158
+ });
159
+ return {
160
+ storageId: cacheResult.name,
161
+ };
162
+ }
163
+ catch (error) {
164
+ await this.writeErrorMetrics({
165
+ method: this.getMethodName(this.createFileStorage),
166
+ model,
167
+ isAborted: abortSignal?.aborted,
168
+ writeMetrics,
169
+ });
170
+ this.logRequestFailure({
171
+ method: this.getMethodName(this.createFileStorage),
172
+ message: 'Error creating file storage',
173
+ error,
174
+ isAborted: abortSignal?.aborted,
175
+ meta: { uploadedFiles, model },
176
+ });
177
+ return { error };
178
+ }
179
+ }
180
+ async deleteFileStorage(fileStorageId) {
181
+ if (fileStorageId === '') {
182
+ return;
183
+ }
184
+ const cachedContent = this.cachedContent.get(fileStorageId);
185
+ if (cachedContent) {
186
+ this.cachedContent.delete(fileStorageId);
187
+ await this.instance.caches.delete({
188
+ name: fileStorageId,
189
+ });
190
+ }
191
+ this.uncachedFileStorages.delete(fileStorageId);
192
+ }
193
+ async createChat(options) {
194
+ const { storageId, model, instructions, history: providedHistory, abortSignal, reporterContext, } = options;
195
+ const writeMetrics = this.reporter?.initWriter(reporterContext);
196
+ try {
197
+ const cachedContent = storageId
198
+ ? this.cachedContent.get(storageId)
199
+ : undefined;
200
+ const uncachedFiles = storageId
201
+ ? this.uncachedFileStorages.get(storageId)
202
+ : undefined;
203
+ abortSignal?.throwIfAborted();
204
+ const history = providedHistory
205
+ ? await Promise.all(providedHistory.map((message) => (GoogleGenerativeAI_entity_1.GoogleGenerativeAIEntity.getContent(message, this.instance, this.logger))))
206
+ : [];
207
+ abortSignal?.throwIfAborted();
208
+ if (!cachedContent && uncachedFiles) {
209
+ const fileParts = GoogleGenerativeAI_entity_1.GoogleGenerativeAIEntity.getFileDataParts(uncachedFiles);
210
+ history.push({
211
+ role: GoogleGenerativeAI_typedefs_1.GoogleGenerativeAIRoles.User,
212
+ parts: fileParts,
213
+ });
214
+ }
215
+ const chatId = (0, uuid_1.v4)();
216
+ if (instructions) {
217
+ this.chatInstructions.set(chatId, instructions);
218
+ }
219
+ const chatSession = this.instance.chats.create({
220
+ model: model.name,
221
+ history,
222
+ config: {
223
+ systemInstruction: instructions,
224
+ temperature: model.config.temperature,
225
+ abortSignal,
226
+ ...(cachedContent && { cachedContent: cachedContent.name }),
227
+ },
228
+ });
229
+ abortSignal?.throwIfAborted();
230
+ this.chatSessions.set(chatId, chatSession);
231
+ await this.writeSuccessMetrics({
232
+ method: this.getMethodName(this.createChat),
233
+ model,
234
+ usage: {},
235
+ writeMetrics,
236
+ });
237
+ return Promise.resolve({ chatId });
238
+ }
239
+ catch (error) {
240
+ await this.writeErrorMetrics({
241
+ method: this.getMethodName(this.createChat),
242
+ model,
243
+ isAborted: abortSignal?.aborted,
244
+ writeMetrics,
245
+ });
246
+ this.logRequestFailure({
247
+ method: this.getMethodName(this.createChat),
248
+ message: 'Error creating chat',
249
+ error,
250
+ isAborted: abortSignal?.aborted,
251
+ meta: { options },
252
+ });
253
+ return Promise.resolve({ error });
254
+ }
255
+ }
256
+ deleteChat(chatId) {
257
+ this.chatSessions.delete(chatId);
258
+ this.chatInstructions.delete(chatId);
259
+ return Promise.resolve();
260
+ }
261
+ getStorageFileParts(storageId) {
262
+ if (!storageId) {
263
+ return [];
264
+ }
265
+ const uncachedFiles = this.uncachedFileStorages.get(storageId);
266
+ if (!uncachedFiles) {
267
+ return [];
268
+ }
269
+ return GoogleGenerativeAI_entity_1.GoogleGenerativeAIEntity.getFileDataParts(uncachedFiles);
270
+ }
271
+ async assistInChatText(options) {
272
+ const { model, reporterContext, abortSignal, traceContext, } = options;
273
+ const writeMetrics = this.reporter?.initWriter(reporterContext);
274
+ const method = this.getMethodName(this.assistInChatText);
275
+ const generationStartedAt = Date.now();
276
+ const rounds = this.openAgentRounds({
277
+ method,
278
+ model,
279
+ traceContext,
280
+ modelParameters: model.config,
281
+ });
282
+ try {
283
+ const { chatSession, messageParts, sendMessageConfig, } = await this.prepareChatMessage({
284
+ chatId: options.chatId,
285
+ message: options.message,
286
+ storageId: options.storageId,
287
+ tools: options.tools,
288
+ abortSignal,
289
+ });
290
+ const chatResponse = await rounds.run({
291
+ input: this.buildRoundConversation({
292
+ chatSession,
293
+ chatId: options.chatId,
294
+ outgoingParts: messageParts,
295
+ }),
296
+ call: () => chatSession.sendMessage({
297
+ message: messageParts,
298
+ config: sendMessageConfig,
299
+ }),
300
+ describeOutcome: this.buildRoundOutcome,
301
+ });
302
+ abortSignal?.throwIfAborted();
303
+ const toolLoopResult = await this.executeGoogleToolLoop({
304
+ chatSession,
305
+ chatId: options.chatId,
306
+ response: chatResponse,
307
+ tools: options.tools ?? [],
308
+ maxIterations: options.maxToolIterations
309
+ ?? LLMService_constants_1.DEFAULT_MAX_TOOL_ITERATIONS,
310
+ abortSignal,
311
+ config: sendMessageConfig,
312
+ multimodalToolResults: model.capabilities?.multimodalToolResults === true,
313
+ rounds,
314
+ onAssistantNarration: options.onAssistantNarration,
315
+ });
316
+ const responseText = toolLoopResult.response.text ?? '';
317
+ const { totalUsage } = toolLoopResult;
318
+ await this.writeSuccessMetrics({
319
+ method,
320
+ model,
321
+ usage: this.buildUsageMetrics(totalUsage),
322
+ writeMetrics,
323
+ });
324
+ return {
325
+ text: responseText,
326
+ toolIterationsUsed: toolLoopResult.toolIterationsUsed,
327
+ ...(toolLoopResult.toolIterationsExhausted && {
328
+ toolIterationsExhausted: true,
329
+ }),
330
+ stopReason: toolLoopResult.stopReason,
331
+ ...(toolLoopResult.terminalTool && {
332
+ terminalTool: toolLoopResult.terminalTool,
333
+ }),
334
+ };
335
+ }
336
+ catch (error) {
337
+ await this.writeErrorMetrics({
338
+ method,
339
+ model,
340
+ isAborted: abortSignal?.aborted,
341
+ writeMetrics,
342
+ error,
343
+ generationTrace: this.buildUnstartedRunTrace({
344
+ rounds,
345
+ method,
346
+ traceContext,
347
+ input: options.message,
348
+ modelParameters: model.config,
349
+ startedAt: generationStartedAt,
350
+ }),
351
+ });
352
+ this.logRequestFailure({
353
+ method,
354
+ message: 'Error assisting in chat',
355
+ error,
356
+ isAborted: abortSignal?.aborted,
357
+ meta: { options },
358
+ });
359
+ return { error };
360
+ }
361
+ }
362
+ async assistInChatStructured(options) {
363
+ const { model, abortSignal, schema, reporterContext, traceContext, } = options;
364
+ const writeMetrics = this.reporter?.initWriter(reporterContext);
365
+ const method = this.getMethodName(this.assistInChatStructured);
366
+ const generationStartedAt = Date.now();
367
+ const rounds = this.openAgentRounds({
368
+ method,
369
+ model,
370
+ traceContext,
371
+ modelParameters: model.config,
372
+ });
373
+ try {
374
+ const googleSchema = schema._toProviderSchema(LLMService_typedefs_1.LLMProviders.GoogleGenerativeAI);
375
+ const { chatSession, messageParts, sendMessageConfig, } = await this.prepareChatMessage({
376
+ chatId: options.chatId,
377
+ message: options.message,
378
+ storageId: options.storageId,
379
+ tools: options.tools,
380
+ abortSignal,
381
+ structuredConfig: {
382
+ ...(!options.tools?.length && {
383
+ responseMimeType: 'application/json',
384
+ }),
385
+ responseSchema: googleSchema,
386
+ },
387
+ });
388
+ const chatResponse = await rounds.run({
389
+ input: this.buildRoundConversation({
390
+ chatSession,
391
+ chatId: options.chatId,
392
+ outgoingParts: messageParts,
393
+ }),
394
+ call: () => chatSession.sendMessage({
395
+ message: messageParts,
396
+ config: sendMessageConfig,
397
+ }),
398
+ describeOutcome: this.buildRoundOutcome,
399
+ });
400
+ abortSignal?.throwIfAborted();
401
+ const toolLoopResult = await this.executeGoogleToolLoop({
402
+ chatSession,
403
+ chatId: options.chatId,
404
+ response: chatResponse,
405
+ tools: options.tools ?? [],
406
+ maxIterations: options.maxToolIterations
407
+ ?? LLMService_constants_1.DEFAULT_MAX_TOOL_ITERATIONS,
408
+ abortSignal,
409
+ config: sendMessageConfig,
410
+ multimodalToolResults: model.capabilities?.multimodalToolResults === true,
411
+ rounds,
412
+ onAssistantNarration: options.onAssistantNarration,
413
+ });
414
+ if (toolLoopResult.terminalTool) {
415
+ await this.writeSuccessMetrics({
416
+ method: this.getMethodName(this.assistInChatStructured),
417
+ model,
418
+ usage: this.buildUsageMetrics(toolLoopResult.totalUsage),
419
+ writeMetrics,
420
+ });
421
+ return {
422
+ text: toolLoopResult.response.text ?? '',
423
+ toolIterationsUsed: toolLoopResult.toolIterationsUsed,
424
+ stopReason: toolLoopResult.stopReason,
425
+ terminalTool: toolLoopResult.terminalTool,
426
+ };
427
+ }
428
+ let finalResponseText;
429
+ let totalUsage = toolLoopResult.totalUsage;
430
+ if (options.tools?.length) {
431
+ const structuredFollowUp = await this.sendStructuredFollowUp({
432
+ chatSession,
433
+ chatId: options.chatId,
434
+ googleSchema,
435
+ abortSignal,
436
+ rounds,
437
+ });
438
+ finalResponseText =
439
+ structuredFollowUp.text;
440
+ totalUsage =
441
+ this.combineUsage(totalUsage, structuredFollowUp.usage);
442
+ }
443
+ else {
444
+ finalResponseText =
445
+ toolLoopResult.response.text ?? '';
446
+ }
447
+ if (!finalResponseText) {
448
+ throw new Error('Empty response from Google'
449
+ + ' Generative AI Assistant');
450
+ }
451
+ try {
452
+ const parsed = JSON.parse(finalResponseText);
453
+ const validation = schema._parse(parsed);
454
+ await this.writeSuccessMetrics({
455
+ method,
456
+ model,
457
+ usage: this.buildUsageMetrics(totalUsage),
458
+ writeMetrics,
459
+ });
460
+ const structuredFollowUpRoundTrips = options.tools?.length ? 1 : 0;
461
+ return {
462
+ text: finalResponseText,
463
+ data: validation.data,
464
+ parseError: validation.error,
465
+ toolIterationsUsed: toolLoopResult.toolIterationsUsed
466
+ + structuredFollowUpRoundTrips,
467
+ ...(toolLoopResult.toolIterationsExhausted && {
468
+ toolIterationsExhausted: true,
469
+ }),
470
+ stopReason: toolLoopResult.stopReason,
471
+ };
472
+ }
473
+ catch (parseError) {
474
+ this.logger
475
+ ?.child(this.getMethodName(this.assistInChatStructured))
476
+ .warn('Failed to parse JSON response', {
477
+ content: finalResponseText,
478
+ parseError: parseError.message,
479
+ });
480
+ throw parseError;
481
+ }
482
+ }
483
+ catch (error) {
484
+ await this.writeErrorMetrics({
485
+ method,
486
+ model,
487
+ isAborted: abortSignal?.aborted,
488
+ writeMetrics,
489
+ error,
490
+ generationTrace: this.buildUnstartedRunTrace({
491
+ rounds,
492
+ method,
493
+ traceContext,
494
+ input: options.message,
495
+ modelParameters: model.config,
496
+ startedAt: generationStartedAt,
497
+ }),
498
+ });
499
+ this.logRequestFailure({
500
+ method,
501
+ message: 'Error assisting in chat with structured output',
502
+ error,
503
+ isAborted: abortSignal?.aborted,
504
+ meta: { options },
505
+ });
506
+ return {
507
+ text: '',
508
+ error,
509
+ parseError: 'Failed to get structured response'
510
+ + ' from Google Generative'
511
+ + ' AI Assistant',
512
+ };
513
+ }
514
+ }
515
+ async prepareChatMessage(options) {
516
+ const chatSession = this.chatSessions.get(options.chatId);
517
+ if (!chatSession) {
518
+ throw new Error('Chat session not found');
519
+ }
520
+ options.abortSignal?.throwIfAborted();
521
+ const messageContent = await GoogleGenerativeAI_entity_1.GoogleGenerativeAIEntity.getContent(options.message, this.instance, this.logger);
522
+ options.abortSignal?.throwIfAborted();
523
+ if (!messageContent.parts) {
524
+ throw new Error('No message parts available');
525
+ }
526
+ const storageFileParts = this.getStorageFileParts(options.storageId);
527
+ if (options.tools?.length) {
528
+ this.validateToolDefinitions(options.tools);
529
+ }
530
+ const googleTools = options.tools?.length
531
+ ? this.convertCustomToolsToGoogle(options.tools)
532
+ : undefined;
533
+ const sendMessageConfig = {
534
+ systemInstruction: this.chatInstructions.get(options.chatId),
535
+ abortSignal: options.abortSignal,
536
+ ...(googleTools && {
537
+ tools: googleTools,
538
+ }),
539
+ ...options.structuredConfig,
540
+ };
541
+ return {
542
+ chatSession,
543
+ messageParts: [
544
+ ...storageFileParts,
545
+ ...messageContent.parts,
546
+ ],
547
+ sendMessageConfig,
548
+ };
549
+ }
550
+ async sendStructuredFollowUp(params) {
551
+ const structuredConfig = {
552
+ systemInstruction: this.chatInstructions.get(params.chatId),
553
+ responseMimeType: 'application/json',
554
+ responseSchema: params.googleSchema,
555
+ abortSignal: params.abortSignal,
556
+ };
557
+ const followUpParts = [
558
+ {
559
+ text: 'Now respond with the structured'
560
+ + ' JSON output based on the'
561
+ + ' information gathered.',
562
+ },
563
+ ];
564
+ const structuredResponse = await params.rounds.run({
565
+ input: this.buildRoundConversation({
566
+ chatSession: params.chatSession,
567
+ chatId: params.chatId,
568
+ outgoingParts: followUpParts,
569
+ }),
570
+ call: () => params.chatSession.sendMessage({
571
+ message: followUpParts,
572
+ config: structuredConfig,
573
+ }),
574
+ describeOutcome: this.buildRoundOutcome,
575
+ });
576
+ return {
577
+ text: structuredResponse.text ?? '',
578
+ usage: this.extractUsageFromResponse(structuredResponse),
579
+ };
580
+ }
581
+ /**
582
+ * The conversation one round was sent with: the chat's system instruction,
583
+ * the history the SDK holds for the session, and the parts this round adds.
584
+ * Built before the request goes out so a round that throws traces the same
585
+ * transcript a successful one does.
586
+ */
587
+ buildRoundConversation(params) {
588
+ const instructions = this.chatInstructions.get(params.chatId);
589
+ return [
590
+ ...(instructions
591
+ ? [{
592
+ role: 'system',
593
+ parts: [{ text: instructions }],
594
+ }]
595
+ : []),
596
+ ...params.chatSession.getHistory(),
597
+ {
598
+ role: GoogleGenerativeAI_typedefs_1.GoogleGenerativeAIRoles.User,
599
+ parts: params.outgoingParts,
600
+ },
601
+ ];
602
+ }
603
+ /**
604
+ * One round's usage, mapped exactly as the run total is mapped for metrics,
605
+ * so the per-round generations add up to the single metrics point the run
606
+ * still writes.
607
+ */
608
+ buildUsageMetrics(usage) {
609
+ return {
610
+ inputTextTokens: usage.promptTokens - usage.cachedTokens,
611
+ inputCachedTextTokens: usage.cachedTokens,
612
+ outputTextTokens: usage.candidatesTokens,
613
+ };
614
+ }
615
+ buildRoundOutcome = (response) => ({
616
+ output: response.candidates?.[0]?.content,
617
+ usage: this.buildUsageMetrics(this.extractUsageFromResponse(response)),
618
+ });
619
+ extractUsageFromResponse(response) {
620
+ return {
621
+ promptTokens: response.usageMetadata
622
+ ?.promptTokenCount ?? 0,
623
+ cachedTokens: response.usageMetadata
624
+ ?.cachedContentTokenCount ?? 0,
625
+ candidatesTokens: response.usageMetadata
626
+ ?.candidatesTokenCount ?? 0,
627
+ };
628
+ }
629
+ combineUsage(first, second) {
630
+ return {
631
+ promptTokens: first.promptTokens
632
+ + second.promptTokens,
633
+ cachedTokens: first.cachedTokens
634
+ + second.cachedTokens,
635
+ candidatesTokens: first.candidatesTokens
636
+ + second.candidatesTokens,
637
+ };
638
+ }
639
+ convertCustomToolsToGoogle(tools) {
640
+ const functionDeclarations = tools.map((tool) => ({
641
+ name: tool.name,
642
+ description: tool.description,
643
+ parameters: tool.parameters._toProviderSchema(LLMService_typedefs_1.LLMProviders.GoogleGenerativeAI),
644
+ }));
645
+ return [{ functionDeclarations }];
646
+ }
647
+ async executeGoogleToolLoop(params) {
648
+ const { chatSession, chatId, tools, maxIterations, abortSignal, config, multimodalToolResults, rounds, onAssistantNarration, } = params;
649
+ let currentResponse = params.response;
650
+ const totalUsage = this.extractUsageFromResponse(currentResponse);
651
+ let toolIterationsUsed = 1;
652
+ let terminalTool;
653
+ for (let iteration = 0; iteration < maxIterations; iteration++) {
654
+ const functionCallParts = (currentResponse.candidates?.[0]
655
+ ?.content?.parts ?? []).filter((part) => part.functionCall?.name);
656
+ if (functionCallParts.length === 0) {
657
+ break;
658
+ }
659
+ if (onAssistantNarration) {
660
+ onAssistantNarration(this.extractVisibleToolRoundText(currentResponse));
661
+ }
662
+ abortSignal?.throwIfAborted();
663
+ const calls = functionCallParts.map((part) => ({
664
+ name: part.functionCall?.name ?? '',
665
+ args: (part.functionCall?.args ?? {}),
666
+ }));
667
+ const executedCalls = await this.executeGoogleFunctionCalls(calls, tools);
668
+ const terminalCall = executedCalls.find((executed) => executed.isTerminal);
669
+ if (terminalCall) {
670
+ abortSignal?.throwIfAborted();
671
+ terminalTool = {
672
+ name: terminalCall.name,
673
+ output: terminalCall.output,
674
+ };
675
+ break;
676
+ }
677
+ const functionResponseParts = await this.buildFunctionResponseParts(executedCalls, multimodalToolResults);
678
+ abortSignal?.throwIfAborted();
679
+ currentResponse = await rounds.run({
680
+ input: this.buildRoundConversation({
681
+ chatSession,
682
+ chatId,
683
+ outgoingParts: functionResponseParts,
684
+ }),
685
+ call: () => chatSession.sendMessage({
686
+ message: functionResponseParts,
687
+ config,
688
+ }),
689
+ describeOutcome: this.buildRoundOutcome,
690
+ });
691
+ toolIterationsUsed += 1;
692
+ const iterationUsage = this.extractUsageFromResponse(currentResponse);
693
+ totalUsage.promptTokens +=
694
+ iterationUsage.promptTokens;
695
+ totalUsage.cachedTokens +=
696
+ iterationUsage.cachedTokens;
697
+ totalUsage.candidatesTokens +=
698
+ iterationUsage.candidatesTokens;
699
+ }
700
+ const toolIterationsExhausted = !terminalTool && (currentResponse.candidates?.[0]
701
+ ?.content?.parts ?? []).some((part) => part.functionCall?.name);
702
+ if (toolIterationsExhausted) {
703
+ this.logger
704
+ ?.child(this.getMethodName(this.executeGoogleToolLoop))
705
+ .warn('Tool loop reached maxToolIterations', {
706
+ maxToolIterations: maxIterations,
707
+ toolIterationsUsed,
708
+ });
709
+ }
710
+ return {
711
+ response: currentResponse,
712
+ totalUsage,
713
+ toolIterationsUsed,
714
+ toolIterationsExhausted,
715
+ stopReason: this.resolveToolLoopStopReason({
716
+ terminalTool,
717
+ toolIterationsExhausted,
718
+ }),
719
+ terminalTool,
720
+ };
721
+ }
722
+ /**
723
+ * The visible assistant text a continuing tool-loop round produced, joined
724
+ * from the response's text parts. Thinking parts (`part.thought`) are
725
+ * excluded so only the visible narration channel is surfaced.
726
+ */
727
+ extractVisibleToolRoundText(response) {
728
+ return (response.candidates?.[0]?.content?.parts ?? [])
729
+ .filter((part) => typeof part.text === 'string' && part.thought !== true)
730
+ .map((part) => part.text)
731
+ .join('');
732
+ }
733
+ executeGoogleFunctionCalls(calls, tools) {
734
+ return Promise.all(calls.map((call) => this.executeSingleGoogleFunctionCall(call, tools)));
735
+ }
736
+ async buildFunctionResponseParts(executedCalls, multimodalToolResults) {
737
+ if (multimodalToolResults) {
738
+ return Promise.all(executedCalls.map((executedCall) => this.buildNativeFunctionResponsePart(executedCall)));
739
+ }
740
+ return this.buildAppendedFunctionResponseParts(executedCalls);
741
+ }
742
+ async executeSingleGoogleFunctionCall(call, tools) {
743
+ const matchingTool = tools.find((tool) => tool.name === call.name);
744
+ if (!matchingTool) {
745
+ const unknownToolMessage = `Error: Unknown tool "${call.name}"`;
746
+ return {
747
+ name: call.name,
748
+ result: {
749
+ content: unknownToolMessage,
750
+ images: [],
751
+ },
752
+ output: unknownToolMessage,
753
+ isTerminal: false,
754
+ };
755
+ }
756
+ const isTerminal = matchingTool.terminal === true;
757
+ try {
758
+ const rawResult = await this.getTracer().withToolObservation(`${this.serviceName}/tool:${call.name}`, call.args, () => Promise.resolve(matchingTool.execute(call.args)));
759
+ return {
760
+ name: call.name,
761
+ result: (0, tools_1.normalizeToolResult)(rawResult),
762
+ output: rawResult,
763
+ isTerminal,
764
+ };
765
+ }
766
+ catch (executionError) {
767
+ const message = executionError instanceof Error
768
+ ? executionError.message
769
+ : String(executionError);
770
+ this.logger
771
+ ?.child(this.getMethodName(this.executeSingleGoogleFunctionCall))
772
+ .error('Tool execution failed', {
773
+ toolName: call.name,
774
+ error: (0, serializeError_1.serializeError)(executionError),
775
+ });
776
+ const failureMessage = `Error: ${message}`;
777
+ return {
778
+ name: call.name,
779
+ result: {
780
+ content: failureMessage,
781
+ images: [],
782
+ },
783
+ output: failureMessage,
784
+ isTerminal,
785
+ };
786
+ }
787
+ }
788
+ /**
789
+ * Gemini 3 models accept image bytes inside `functionResponse.parts`. Each
790
+ * image blob carries a unique `displayName` the `response` payload then
791
+ * references via `{ $ref: displayName }`.
792
+ */
793
+ async buildNativeFunctionResponsePart(executedCall) {
794
+ const { name, result } = executedCall;
795
+ if (result.images.length === 0) {
796
+ return {
797
+ functionResponse: {
798
+ name,
799
+ response: { result: result.content },
800
+ },
801
+ };
802
+ }
803
+ const imageBlobs = await Promise.all(result.images.map((image, index) => this.fetchToolImageBlob(image, `${name}_image_${index + 1}`)));
804
+ return {
805
+ functionResponse: {
806
+ name,
807
+ response: {
808
+ result: result.content,
809
+ images: imageBlobs.map((blob) => ({
810
+ ...(blob.label && { label: blob.label }),
811
+ $ref: blob.displayName,
812
+ })),
813
+ },
814
+ parts: imageBlobs.map((blob) => ({
815
+ inlineData: {
816
+ mimeType: blob.mimeType,
817
+ data: blob.data,
818
+ displayName: blob.displayName,
819
+ },
820
+ })),
821
+ },
822
+ };
823
+ }
824
+ /**
825
+ * Gemini 2.5 models cannot carry images in a function response, so image
826
+ * bytes are appended as sibling user-content parts after every function
827
+ * response in the same message.
828
+ */
829
+ async buildAppendedFunctionResponseParts(executedCalls) {
830
+ const functionResponseParts = executedCalls.map(({ name, result }) => ({
831
+ functionResponse: {
832
+ name,
833
+ response: { result: result.content },
834
+ },
835
+ }));
836
+ const images = executedCalls.flatMap(({ result }) => result.images);
837
+ const imageParts = await Promise.all(images.map((image) => this.buildInlineImageParts(image)));
838
+ return [
839
+ ...functionResponseParts,
840
+ ...imageParts.flat(),
841
+ ];
842
+ }
843
+ async buildInlineImageParts(image) {
844
+ const blob = await this.fetchToolImageBlob(image);
845
+ const imagePart = {
846
+ inlineData: {
847
+ mimeType: blob.mimeType,
848
+ data: blob.data,
849
+ },
850
+ };
851
+ if (!blob.label) {
852
+ return [imagePart];
853
+ }
854
+ return [{ text: blob.label }, imagePart];
855
+ }
856
+ async fetchToolImageBlob(image, displayName) {
857
+ const response = await fetch(image.url);
858
+ if (!response.ok) {
859
+ throw new Error(`Failed to fetch tool image (${response.status}`
860
+ + ` ${response.statusText}): ${image.url}`);
861
+ }
862
+ const arrayBuffer = await response.arrayBuffer();
863
+ return {
864
+ mimeType: image.mimeType ?? 'image/png',
865
+ data: Buffer.from(arrayBuffer).toString('base64'),
866
+ displayName,
867
+ label: image.label,
868
+ };
869
+ }
870
+ async countTokens(messages, model) {
871
+ const countTokensFn = GoogleGenerativeAI_entity_1.GoogleGenerativeAIEntity.getCountTokensFn(this.instance);
872
+ return countTokensFn(messages, model);
873
+ }
874
+ }
875
+ exports.GoogleGenerativeAIAssistanceService = GoogleGenerativeAIAssistanceService;
876
+ //# sourceMappingURL=GoogleGenerativeAIAssistance.service.js.map