@smythos/sre 1.6.8 → 1.6.10

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 (239) hide show
  1. package/CHANGELOG +111 -111
  2. package/LICENSE +18 -18
  3. package/README.md +135 -135
  4. package/dist/bundle-analysis-lazy.html +4949 -0
  5. package/dist/bundle-analysis.html +4949 -0
  6. package/dist/index.js +2 -2
  7. package/dist/index.js.map +1 -1
  8. package/dist/types/Components/Triggers/Gmail.trigger.d.ts +58 -0
  9. package/dist/types/Components/Triggers/GmailTrigger.class.d.ts +44 -0
  10. package/dist/types/Components/Triggers/Trigger.class.d.ts +21 -0
  11. package/dist/types/Components/Triggers/WhatsApp.trigger.d.ts +22 -0
  12. package/dist/types/helpers/AIPerformanceAnalyzer.helper.d.ts +45 -0
  13. package/dist/types/helpers/AIPerformanceCollector.helper.d.ts +111 -0
  14. package/dist/types/subsystems/IO/Storage.service/connectors/AzureBlobStorage.class.d.ts +211 -0
  15. package/dist/types/subsystems/IO/VectorDB.service/connectors/WeaviateVectorDB.class.d.ts +187 -0
  16. package/dist/types/subsystems/PerformanceManager/Performance.service/PerformanceConnector.d.ts +102 -0
  17. package/dist/types/subsystems/PerformanceManager/Performance.service/connectors/LocalPerformanceConnector.class.d.ts +100 -0
  18. package/dist/types/subsystems/PerformanceManager/Performance.service/index.d.ts +22 -0
  19. package/dist/types/subsystems/Security/Credentials/Credentials.class.d.ts +2 -0
  20. package/dist/types/subsystems/Security/Credentials/ManagedOAuth2Credentials.class.d.ts +18 -0
  21. package/dist/types/subsystems/Security/Credentials/OAuth2Credentials.class.d.ts +14 -0
  22. package/dist/types/types/Performance.types.d.ts +468 -0
  23. package/dist/types/utils/package-manager.utils.d.ts +26 -0
  24. package/package.json +1 -1
  25. package/src/Components/APICall/APICall.class.ts +161 -161
  26. package/src/Components/APICall/AccessTokenManager.ts +166 -166
  27. package/src/Components/APICall/ArrayBufferResponse.helper.ts +58 -58
  28. package/src/Components/APICall/OAuth.helper.ts +447 -447
  29. package/src/Components/APICall/mimeTypeCategories.ts +46 -46
  30. package/src/Components/APICall/parseData.ts +167 -167
  31. package/src/Components/APICall/parseHeaders.ts +41 -41
  32. package/src/Components/APICall/parseProxy.ts +68 -68
  33. package/src/Components/APICall/parseUrl.ts +91 -91
  34. package/src/Components/APIEndpoint.class.ts +234 -234
  35. package/src/Components/APIOutput.class.ts +58 -58
  36. package/src/Components/AgentPlugin.class.ts +102 -102
  37. package/src/Components/Async.class.ts +155 -155
  38. package/src/Components/Await.class.ts +90 -90
  39. package/src/Components/Classifier.class.ts +158 -158
  40. package/src/Components/Component.class.ts +147 -147
  41. package/src/Components/ComponentHost.class.ts +38 -38
  42. package/src/Components/DataSourceCleaner.class.ts +92 -92
  43. package/src/Components/DataSourceIndexer.class.ts +181 -181
  44. package/src/Components/DataSourceLookup.class.ts +161 -161
  45. package/src/Components/ECMASandbox.class.ts +72 -72
  46. package/src/Components/FEncDec.class.ts +29 -29
  47. package/src/Components/FHash.class.ts +33 -33
  48. package/src/Components/FSign.class.ts +80 -80
  49. package/src/Components/FSleep.class.ts +25 -25
  50. package/src/Components/FTimestamp.class.ts +66 -66
  51. package/src/Components/FileStore.class.ts +78 -78
  52. package/src/Components/ForEach.class.ts +97 -97
  53. package/src/Components/GPTPlugin.class.ts +70 -70
  54. package/src/Components/GenAILLM.class.ts +586 -586
  55. package/src/Components/HuggingFace.class.ts +313 -313
  56. package/src/Components/Image/imageSettings.config.ts +70 -70
  57. package/src/Components/ImageGenerator.class.ts +483 -483
  58. package/src/Components/JSONFilter.class.ts +54 -54
  59. package/src/Components/LLMAssistant.class.ts +213 -213
  60. package/src/Components/LogicAND.class.ts +28 -28
  61. package/src/Components/LogicAtLeast.class.ts +85 -85
  62. package/src/Components/LogicAtMost.class.ts +86 -86
  63. package/src/Components/LogicOR.class.ts +29 -29
  64. package/src/Components/LogicXOR.class.ts +34 -34
  65. package/src/Components/MCPClient.class.ts +137 -137
  66. package/src/Components/MemoryDeleteKeyVal.class.ts +70 -70
  67. package/src/Components/MemoryReadKeyVal.class.ts +67 -67
  68. package/src/Components/MemoryWriteKeyVal.class.ts +62 -62
  69. package/src/Components/MemoryWriteObject.class.ts +97 -97
  70. package/src/Components/MultimodalLLM.class.ts +128 -128
  71. package/src/Components/OpenAPI.class.ts +72 -72
  72. package/src/Components/PromptGenerator.class.ts +122 -122
  73. package/src/Components/ScrapflyWebScrape.class.ts +183 -183
  74. package/src/Components/ServerlessCode.class.ts +123 -123
  75. package/src/Components/TavilyWebSearch.class.ts +103 -103
  76. package/src/Components/VisionLLM.class.ts +104 -104
  77. package/src/Components/ZapierAction.class.ts +127 -127
  78. package/src/Components/index.ts +97 -97
  79. package/src/Core/AgentProcess.helper.ts +240 -240
  80. package/src/Core/Connector.class.ts +123 -123
  81. package/src/Core/ConnectorsService.ts +197 -197
  82. package/src/Core/DummyConnector.ts +49 -49
  83. package/src/Core/HookService.ts +105 -105
  84. package/src/Core/SmythRuntime.class.ts +241 -241
  85. package/src/Core/SystemEvents.ts +16 -16
  86. package/src/Core/boot.ts +56 -56
  87. package/src/config.ts +15 -15
  88. package/src/constants.ts +126 -126
  89. package/src/data/hugging-face.params.json +579 -579
  90. package/src/helpers/AWSLambdaCode.helper.ts +624 -624
  91. package/src/helpers/BinaryInput.helper.ts +331 -331
  92. package/src/helpers/Conversation.helper.ts +1157 -1157
  93. package/src/helpers/ECMASandbox.helper.ts +64 -64
  94. package/src/helpers/JsonContent.helper.ts +97 -97
  95. package/src/helpers/LocalCache.helper.ts +97 -97
  96. package/src/helpers/Log.helper.ts +274 -274
  97. package/src/helpers/OpenApiParser.helper.ts +150 -150
  98. package/src/helpers/S3Cache.helper.ts +147 -147
  99. package/src/helpers/SmythURI.helper.ts +5 -5
  100. package/src/helpers/Sysconfig.helper.ts +95 -95
  101. package/src/helpers/TemplateString.helper.ts +243 -243
  102. package/src/helpers/TypeChecker.helper.ts +329 -329
  103. package/src/index.ts +3 -3
  104. package/src/index.ts.bak +3 -3
  105. package/src/subsystems/AgentManager/Agent.class.ts +1114 -1114
  106. package/src/subsystems/AgentManager/Agent.helper.ts +3 -3
  107. package/src/subsystems/AgentManager/AgentData.service/AgentDataConnector.ts +230 -230
  108. package/src/subsystems/AgentManager/AgentData.service/connectors/CLIAgentDataConnector.class.ts +66 -66
  109. package/src/subsystems/AgentManager/AgentData.service/connectors/LocalAgentDataConnector.class.ts +145 -145
  110. package/src/subsystems/AgentManager/AgentData.service/connectors/NullAgentData.class.ts +39 -39
  111. package/src/subsystems/AgentManager/AgentData.service/index.ts +18 -18
  112. package/src/subsystems/AgentManager/AgentLogger.class.ts +301 -301
  113. package/src/subsystems/AgentManager/AgentRequest.class.ts +51 -51
  114. package/src/subsystems/AgentManager/AgentRuntime.class.ts +557 -557
  115. package/src/subsystems/AgentManager/AgentSSE.class.ts +101 -101
  116. package/src/subsystems/AgentManager/AgentSettings.class.ts +52 -52
  117. package/src/subsystems/AgentManager/Component.service/ComponentConnector.ts +32 -32
  118. package/src/subsystems/AgentManager/Component.service/connectors/LocalComponentConnector.class.ts +60 -60
  119. package/src/subsystems/AgentManager/Component.service/index.ts +11 -11
  120. package/src/subsystems/AgentManager/EmbodimentSettings.class.ts +47 -47
  121. package/src/subsystems/AgentManager/ForkedAgent.class.ts +154 -154
  122. package/src/subsystems/AgentManager/OSResourceMonitor.ts +77 -77
  123. package/src/subsystems/ComputeManager/Code.service/CodeConnector.ts +98 -98
  124. package/src/subsystems/ComputeManager/Code.service/connectors/AWSLambdaCode.class.ts +171 -171
  125. package/src/subsystems/ComputeManager/Code.service/connectors/ECMASandbox.class.ts +131 -131
  126. package/src/subsystems/ComputeManager/Code.service/index.ts +13 -13
  127. package/src/subsystems/IO/CLI.service/CLIConnector.ts +47 -47
  128. package/src/subsystems/IO/CLI.service/index.ts +9 -9
  129. package/src/subsystems/IO/Log.service/LogConnector.ts +32 -32
  130. package/src/subsystems/IO/Log.service/connectors/ConsoleLog.class.ts +28 -28
  131. package/src/subsystems/IO/Log.service/index.ts +13 -13
  132. package/src/subsystems/IO/NKV.service/NKVConnector.ts +43 -43
  133. package/src/subsystems/IO/NKV.service/connectors/NKVLocalStorage.class.ts +234 -234
  134. package/src/subsystems/IO/NKV.service/connectors/NKVRAM.class.ts +204 -204
  135. package/src/subsystems/IO/NKV.service/connectors/NKVRedis.class.ts +182 -182
  136. package/src/subsystems/IO/NKV.service/index.ts +14 -14
  137. package/src/subsystems/IO/Router.service/RouterConnector.ts +21 -21
  138. package/src/subsystems/IO/Router.service/connectors/ExpressRouter.class.ts +48 -48
  139. package/src/subsystems/IO/Router.service/connectors/NullRouter.class.ts +40 -40
  140. package/src/subsystems/IO/Router.service/index.ts +11 -11
  141. package/src/subsystems/IO/Storage.service/SmythFS.class.ts +488 -488
  142. package/src/subsystems/IO/Storage.service/StorageConnector.ts +66 -66
  143. package/src/subsystems/IO/Storage.service/connectors/LocalStorage.class.ts +327 -327
  144. package/src/subsystems/IO/Storage.service/connectors/S3Storage.class.ts +482 -482
  145. package/src/subsystems/IO/Storage.service/index.ts +13 -13
  146. package/src/subsystems/IO/VectorDB.service/VectorDBConnector.ts +108 -108
  147. package/src/subsystems/IO/VectorDB.service/connectors/MilvusVectorDB.class.ts +465 -465
  148. package/src/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.ts +387 -387
  149. package/src/subsystems/IO/VectorDB.service/connectors/RAMVecrtorDB.class.ts +408 -408
  150. package/src/subsystems/IO/VectorDB.service/embed/BaseEmbedding.ts +107 -107
  151. package/src/subsystems/IO/VectorDB.service/embed/GoogleEmbedding.ts +118 -118
  152. package/src/subsystems/IO/VectorDB.service/embed/OpenAIEmbedding.ts +109 -109
  153. package/src/subsystems/IO/VectorDB.service/embed/index.ts +26 -26
  154. package/src/subsystems/IO/VectorDB.service/index.ts +14 -14
  155. package/src/subsystems/LLMManager/LLM.helper.ts +251 -251
  156. package/src/subsystems/LLMManager/LLM.inference.ts +345 -345
  157. package/src/subsystems/LLMManager/LLM.service/LLMConnector.ts +492 -492
  158. package/src/subsystems/LLMManager/LLM.service/LLMCredentials.helper.ts +171 -171
  159. package/src/subsystems/LLMManager/LLM.service/connectors/Anthropic.class.ts +666 -666
  160. package/src/subsystems/LLMManager/LLM.service/connectors/Bedrock.class.ts +407 -407
  161. package/src/subsystems/LLMManager/LLM.service/connectors/Echo.class.ts +92 -92
  162. package/src/subsystems/LLMManager/LLM.service/connectors/GoogleAI.class.ts +983 -983
  163. package/src/subsystems/LLMManager/LLM.service/connectors/Groq.class.ts +319 -319
  164. package/src/subsystems/LLMManager/LLM.service/connectors/Ollama.class.ts +361 -361
  165. package/src/subsystems/LLMManager/LLM.service/connectors/Perplexity.class.ts +257 -257
  166. package/src/subsystems/LLMManager/LLM.service/connectors/VertexAI.class.ts +430 -430
  167. package/src/subsystems/LLMManager/LLM.service/connectors/openai/OpenAIConnector.class.ts +503 -503
  168. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/ChatCompletionsApiInterface.ts +524 -524
  169. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/OpenAIApiInterface.ts +100 -100
  170. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/OpenAIApiInterfaceFactory.ts +81 -81
  171. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/ResponsesApiInterface.ts +1145 -1145
  172. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/constants.ts +13 -13
  173. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/index.ts +4 -4
  174. package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/utils.ts +11 -11
  175. package/src/subsystems/LLMManager/LLM.service/connectors/openai/types.ts +32 -32
  176. package/src/subsystems/LLMManager/LLM.service/connectors/xAI.class.ts +478 -478
  177. package/src/subsystems/LLMManager/LLM.service/index.ts +47 -47
  178. package/src/subsystems/LLMManager/ModelsProvider.service/ModelsProviderConnector.ts +303 -303
  179. package/src/subsystems/LLMManager/ModelsProvider.service/connectors/JSONModelsProvider.class.ts +280 -271
  180. package/src/subsystems/LLMManager/ModelsProvider.service/index.ts +11 -11
  181. package/src/subsystems/LLMManager/custom-models.ts +854 -854
  182. package/src/subsystems/LLMManager/models.ts +2540 -2540
  183. package/src/subsystems/LLMManager/paramMappings.ts +69 -69
  184. package/src/subsystems/MemoryManager/Cache.service/CacheConnector.ts +86 -86
  185. package/src/subsystems/MemoryManager/Cache.service/connectors/LocalStorageCache.class.ts +297 -297
  186. package/src/subsystems/MemoryManager/Cache.service/connectors/RAMCache.class.ts +214 -214
  187. package/src/subsystems/MemoryManager/Cache.service/connectors/RedisCache.class.ts +252 -252
  188. package/src/subsystems/MemoryManager/Cache.service/connectors/S3Cache.class.ts +373 -373
  189. package/src/subsystems/MemoryManager/Cache.service/index.ts +15 -15
  190. package/src/subsystems/MemoryManager/LLMCache.ts +72 -72
  191. package/src/subsystems/MemoryManager/LLMContext.ts +124 -124
  192. package/src/subsystems/MemoryManager/LLMMemory.service/LLMMemoryConnector.ts +26 -26
  193. package/src/subsystems/MemoryManager/RuntimeContext.ts +277 -277
  194. package/src/subsystems/Security/AccessControl/ACL.class.ts +208 -208
  195. package/src/subsystems/Security/AccessControl/AccessCandidate.class.ts +82 -82
  196. package/src/subsystems/Security/AccessControl/AccessRequest.class.ts +52 -52
  197. package/src/subsystems/Security/Account.service/AccountConnector.ts +44 -44
  198. package/src/subsystems/Security/Account.service/connectors/DummyAccount.class.ts +130 -130
  199. package/src/subsystems/Security/Account.service/connectors/JSONFileAccount.class.ts +170 -170
  200. package/src/subsystems/Security/Account.service/connectors/MySQLAccount.class.ts +76 -76
  201. package/src/subsystems/Security/Account.service/index.ts +14 -14
  202. package/src/subsystems/Security/Credentials.helper.ts +62 -62
  203. package/src/subsystems/Security/ManagedVault.service/ManagedVaultConnector.ts +38 -38
  204. package/src/subsystems/Security/ManagedVault.service/connectors/NullManagedVault.class.ts +53 -53
  205. package/src/subsystems/Security/ManagedVault.service/connectors/SecretManagerManagedVault.ts +154 -154
  206. package/src/subsystems/Security/ManagedVault.service/index.ts +12 -12
  207. package/src/subsystems/Security/SecureConnector.class.ts +110 -110
  208. package/src/subsystems/Security/Vault.service/Vault.helper.ts +30 -30
  209. package/src/subsystems/Security/Vault.service/VaultConnector.ts +29 -29
  210. package/src/subsystems/Security/Vault.service/connectors/HashicorpVault.class.ts +46 -46
  211. package/src/subsystems/Security/Vault.service/connectors/JSONFileVault.class.ts +221 -221
  212. package/src/subsystems/Security/Vault.service/connectors/NullVault.class.ts +54 -54
  213. package/src/subsystems/Security/Vault.service/connectors/SecretsManager.class.ts +140 -140
  214. package/src/subsystems/Security/Vault.service/index.ts +12 -12
  215. package/src/types/ACL.types.ts +104 -104
  216. package/src/types/AWS.types.ts +10 -10
  217. package/src/types/Agent.types.ts +61 -61
  218. package/src/types/AgentLogger.types.ts +17 -17
  219. package/src/types/Cache.types.ts +1 -1
  220. package/src/types/Common.types.ts +2 -2
  221. package/src/types/LLM.types.ts +520 -520
  222. package/src/types/Redis.types.ts +8 -8
  223. package/src/types/SRE.types.ts +64 -64
  224. package/src/types/Security.types.ts +14 -14
  225. package/src/types/Storage.types.ts +5 -5
  226. package/src/types/VectorDB.types.ts +86 -86
  227. package/src/utils/base64.utils.ts +275 -275
  228. package/src/utils/cli.utils.ts +68 -68
  229. package/src/utils/data.utils.ts +322 -322
  230. package/src/utils/date-time.utils.ts +22 -22
  231. package/src/utils/general.utils.ts +238 -238
  232. package/src/utils/index.ts +12 -12
  233. package/src/utils/lazy-client.ts +261 -261
  234. package/src/utils/numbers.utils.ts +13 -13
  235. package/src/utils/oauth.utils.ts +35 -35
  236. package/src/utils/string.utils.ts +414 -414
  237. package/src/utils/url.utils.ts +19 -19
  238. package/src/utils/validation.utils.ts +74 -74
  239. package/dist/types/subsystems/LLMManager/ModelsProvider.service/connectors/SmythModelsProvider.class.d.ts +0 -39
@@ -1,1157 +1,1157 @@
1
- import { AgentProcess } from '@sre/Core/AgentProcess.helper';
2
- import { ConnectorService } from '@sre/Core/ConnectorsService';
3
- import { Logger } from '@sre/helpers/Log.helper';
4
- import { LLMInference } from '@sre/LLMManager/LLM.inference';
5
- import { LLMContext } from '@sre/MemoryManager/LLMContext';
6
- import { TAgentProcessParams } from '@sre/types/Agent.types';
7
- import { ILLMContextStore, TLLMEvent, TLLMModel, ToolData } from '@sre/types/LLM.types';
8
- import { isUrl } from '@sre/utils/data.utils';
9
- import { processWithConcurrencyLimit, uid } from '@sre/utils/general.utils';
10
- import axios, { AxiosRequestConfig } from 'axios';
11
- import EventEmitter from 'events';
12
- import { JSONContent } from './JsonContent.helper';
13
- import { OpenAPIParser } from './OpenApiParser.helper';
14
- import { Match, TemplateString } from './TemplateString.helper';
15
- import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
16
- import { EventSource, FetchLike } from 'eventsource';
17
- import { hookAsyncWithContext } from '@sre/Core/HookService';
18
- import { randomUUID } from 'crypto';
19
- import * as acorn from 'acorn';
20
-
21
- const console = Logger('ConversationHelper');
22
- type FunctionDeclaration = {
23
- name: string;
24
- description: string;
25
- properties: Record<string, any>;
26
- requiredFields: string[];
27
- };
28
- type ToolParams = {
29
- type: string;
30
- endpoint: string;
31
- args: Record<string, any>;
32
- method: string;
33
- baseUrl: string;
34
- headers?: Record<string, string>;
35
- agentCallback?: (data: any) => void;
36
- };
37
-
38
- //TODO: handle authentication
39
- export class Conversation extends EventEmitter {
40
- private _agentId: string = '';
41
- private _systemPrompt;
42
- private userDefinedSystemPrompt: string = '';
43
- public toolChoice: string = 'auto';
44
- public get systemPrompt() {
45
- return this._systemPrompt;
46
- }
47
- public set systemPrompt(systemPrompt) {
48
- this._systemPrompt = systemPrompt;
49
- if (this._context) this._context.systemPrompt = systemPrompt;
50
- }
51
- public assistantName;
52
-
53
- private _reqMethods;
54
- private _toolsConfig;
55
- private _toolStatusMap: Record<string, string> = {};
56
- private _endpoints;
57
- private _baseUrl;
58
-
59
- private _status = '';
60
- private _currentWaitPromise;
61
-
62
- private _llmContextStore: ILLMContextStore;
63
- private _context: LLMContext;
64
-
65
- private _maxContextSize = 1024 * 128;
66
- private _maxOutputTokens = 1024 * 8;
67
- private _teamId: string = undefined;
68
- private _agentVersion: string = undefined;
69
- public agentData: any;
70
-
71
- public get context() {
72
- return this._context;
73
- }
74
-
75
- private _lastError;
76
- private _spec;
77
- private _customToolsDeclarations: FunctionDeclaration[] = [];
78
- private _customToolsHandlers: Record<string, (args: Record<string, any>) => Promise<any>> = {};
79
- public stop = false;
80
- public set spec(specSource) {
81
- this.ready.then(() => {
82
- this._status = '';
83
- this.loadSpecFromSource(specSource).then(async (spec) => {
84
- if (!spec) {
85
- this._status = 'error';
86
- this.emit('error', 'Invalid OpenAPI specification data format');
87
- throw new Error('Invalid OpenAPI specification data format');
88
- }
89
- this._spec = spec;
90
-
91
- // teamId is required to load custom LLMs, we must assign it before updateModel()
92
- await this.assignTeamIdFromAgentId(this._agentId);
93
-
94
- await this.updateModel(this._model);
95
- this._status = 'ready';
96
- });
97
- });
98
- }
99
-
100
- public set model(model: string | TLLMModel) {
101
- this.ready.then(async () => {
102
- this._status = '';
103
- await this.updateModel(model);
104
- this._status = 'ready';
105
- });
106
- }
107
- public get model() {
108
- return this._model;
109
- }
110
-
111
- constructor(
112
- private _model: string | TLLMModel,
113
- private _specSource?: string | Record<string, any>,
114
- private _settings?: {
115
- maxContextSize?: number;
116
- maxOutputTokens?: number;
117
- systemPrompt?: string;
118
- toolChoice?: string;
119
- store?: ILLMContextStore;
120
- experimentalCache?: boolean;
121
- toolsStrategy?: (toolsConfig) => any;
122
- agentId?: string;
123
- agentVersion?: string;
124
- baseUrl?: string;
125
- }
126
- ) {
127
- //TODO: handle loading previous session (messages)
128
- super();
129
-
130
- //this event listener avoids unhandled errors that can cause crashes
131
- this.on('error', (error) => {
132
- this._lastError = error;
133
- console.warn('Conversation Error: ', error?.message);
134
- });
135
- this._maxContextSize =
136
- _settings?.maxContextSize || (this._model as TLLMModel).tokens || (this._model as TLLMModel).keyOptions?.tokens || this._maxContextSize;
137
- this._maxOutputTokens =
138
- _settings?.maxOutputTokens ||
139
- (this._model as TLLMModel).completionTokens ||
140
- (this._model as TLLMModel).keyOptions?.completionTokens ||
141
- this._maxOutputTokens;
142
-
143
- if (_settings?.systemPrompt) {
144
- this.userDefinedSystemPrompt = _settings.systemPrompt;
145
- }
146
- if (_settings?.toolChoice) {
147
- this.toolChoice = _settings.toolChoice;
148
- }
149
-
150
- if (_settings?.store) {
151
- this._llmContextStore = _settings.store;
152
- }
153
-
154
- this._baseUrl = _settings?.baseUrl;
155
-
156
- this._agentVersion = _settings?.agentVersion;
157
-
158
- (async () => {
159
- if (_specSource) {
160
- this.loadSpecFromSource(_specSource)
161
- .then(async (spec) => {
162
- if (!spec) {
163
- this._status = 'error';
164
- this.emit('error', 'Unable to parse OpenAPI specifications');
165
- throw new Error('Invalid OpenAPI specification data format');
166
- }
167
- this._spec = spec;
168
-
169
- if (!this._agentId && _settings?.agentId) this._agentId = _settings.agentId;
170
- if (!this._agentId) this._agentId = 'FAKE-AGENT-ID'; //We use a fake agent ID to avoid ACL check errors
171
-
172
- // teamId is required to load custom LLMs, we must assign it before updateModel()
173
- await this.assignTeamIdFromAgentId(this._agentId);
174
-
175
- await this.updateModel(this._model);
176
-
177
- this._status = 'ready';
178
- })
179
- .catch((error) => {
180
- this._status = 'error';
181
- this.emit('error', error);
182
- });
183
- } else {
184
- await this.updateModel(this._model);
185
- this._status = 'ready';
186
- }
187
- })();
188
- }
189
-
190
- public get ready() {
191
- if (this._currentWaitPromise) return this._currentWaitPromise;
192
- this._currentWaitPromise = new Promise((resolve, reject) => {
193
- if (this._status) {
194
- return resolve(this._status);
195
- }
196
-
197
- const maxWaitTime = 30000;
198
- let waitTime = 0;
199
- const interval = 100;
200
-
201
- const wait = setInterval(() => {
202
- if (this._status) {
203
- clearInterval(wait);
204
- return resolve(this._status);
205
- } else {
206
- waitTime += interval;
207
- if (waitTime >= maxWaitTime) {
208
- clearInterval(wait);
209
- return reject('Timeout: Failed to prepare data');
210
- }
211
- }
212
- }, interval);
213
- });
214
-
215
- return this._currentWaitPromise;
216
- }
217
-
218
- //TODO : handle attachments
219
- @hookAsyncWithContext('Conversation.prompt', async (instance: Conversation) => {
220
- await instance.ready;
221
-
222
- return {
223
- teamId: instance._teamId,
224
- agentId: instance._agentId,
225
- model: instance._model,
226
- };
227
- })
228
- public async prompt(message?: string | any, toolHeaders = {}, concurrentToolCalls = 4, abortSignal?: AbortSignal) {
229
- // if an error occured while streaming, we need to propagate it so for this, we register a one time error listener
230
- let error = null;
231
- const errListener = (err) => (error = err);
232
- this.once('error', errListener);
233
- const result = await this.streamPrompt(message, toolHeaders, concurrentToolCalls, abortSignal);
234
-
235
- // if an error event occured, throw the error
236
- if (error) {
237
- throw error;
238
- }
239
-
240
- this.removeListener('error', errListener);
241
- return result;
242
- }
243
-
244
- //TODO : handle attachments
245
- @hookAsyncWithContext('Conversation.streamPrompt', async (instance: Conversation) => {
246
- await instance.ready;
247
-
248
- return {
249
- teamId: instance._teamId,
250
- agentId: instance._agentId,
251
- model: instance._model,
252
- };
253
- })
254
- public async streamPrompt(message?: string | any, toolHeaders = {}, concurrentToolCalls = 4, abortSignal?: AbortSignal) {
255
- let options = typeof message === 'object' ? message : { message };
256
- message = options?.message;
257
- const files = options?.files;
258
-
259
- if (message) {
260
- //initial call, reset stop flag
261
-
262
- this.stop = false;
263
- }
264
- if (this.stop) {
265
- this.emit('interrupted', 'interrupted');
266
- this.emit('end');
267
- return;
268
- }
269
- await this.ready;
270
-
271
- // Add an abort handler
272
- if (abortSignal) {
273
- abortSignal.addEventListener('abort', () => {
274
- //this.emit('error', { name: 'AbortError', message: 'Request aborted by user!' });
275
- this.emit('aborted', 'Aborted by user!');
276
- //const error = new Error('Request aborted by user!');
277
- //error.name = 'AbortError';
278
- //throw error;
279
- });
280
- }
281
-
282
- const passThroughtContinueMessage = 'Continue with the next tool call if there are any, or just inform the user that you are done';
283
- //let promises = [];
284
- let _content = '';
285
- const reqMethods = this._reqMethods;
286
- const toolsConfig = this._toolsConfig;
287
- const endpoints = this._endpoints;
288
- const baseUrl = this._baseUrl;
289
- const message_id = 'msg_' + randomUUID();
290
- const isDebugSession = toolHeaders['X-DEBUG'];
291
-
292
- /* ==================== STEP ENTRY ==================== */
293
- // console.debug('Request to LLM with the given model, messages and functions properties.', {
294
- // model: this.model,
295
- // message,
296
- // toolsConfig,
297
- // });
298
- /* ==================== STEP ENTRY ==================== */
299
- const llmInference: LLMInference = await LLMInference.getInstance(this.model, AccessCandidate.team(this._teamId));
300
-
301
- if (message) this._context.addUserMessage(message, message_id);
302
-
303
- const contextWindow = await this._context.getContextWindow(this._maxContextSize, this._maxOutputTokens);
304
-
305
- let maxTokens = this._maxOutputTokens;
306
- if (typeof this.model === 'object' && this.model?.params?.maxTokens) {
307
- maxTokens = this.model.params.maxTokens;
308
- }
309
-
310
- const eventEmitter: any = await llmInference
311
- .promptStream({
312
- contextWindow,
313
- files,
314
- params: {
315
- model: this.model,
316
- toolsConfig: this._settings?.toolsStrategy ? this._settings.toolsStrategy(toolsConfig) : toolsConfig,
317
- maxTokens,
318
- cache: this._settings?.experimentalCache,
319
- agentId: this._agentId,
320
- abortSignal,
321
- },
322
- })
323
- .catch((error) => {
324
- console.error('Error on promptStream: ', error);
325
- this.emit(TLLMEvent.Error, error);
326
- });
327
-
328
- // remove listeners from llm event emitter to stop receiving stream data
329
- if (abortSignal) {
330
- abortSignal.addEventListener('abort', () => {
331
- eventEmitter.removeAllListeners();
332
- });
333
- }
334
- if (!eventEmitter || eventEmitter.error) {
335
- throw new Error('[LLM Request Error]');
336
- }
337
-
338
- if (message) this.emit('start');
339
- eventEmitter.on('data', (data) => {
340
- if (this.stop) return;
341
- this.emit('data', data);
342
- });
343
-
344
- eventEmitter.on(TLLMEvent.Thinking, (thinking) => {
345
- if (this.stop) return;
346
- this.emit(TLLMEvent.Thinking, thinking);
347
- });
348
-
349
- eventEmitter.on(TLLMEvent.Data, (data) => {
350
- if (this.stop) return;
351
- this.emit(TLLMEvent.Data, data);
352
- });
353
-
354
- eventEmitter.on(TLLMEvent.Content, (content) => {
355
- if (this.stop) return;
356
- // if (toolHeaders['x-passthrough']) {
357
- // console.log('Passthrough skiped content ', content);
358
- // return;
359
- // }
360
- //const lastMessage = this._context?.messages?.[this._context?.messages?.length - 1];
361
- //const skip = lastMessage?.__smyth_data__?.internal;
362
-
363
- //skip if the content is the last generated message after a passthrough content
364
- // if (skip) {
365
- // let s = true;
366
- // }
367
- _content += content;
368
- this.emit(TLLMEvent.Content, content);
369
- });
370
-
371
- let finishReason = 'stop';
372
-
373
- let toolsPromise = new Promise((resolve, reject) => {
374
- let hasTools = false;
375
- let hasError = false;
376
- let passThroughContent = '';
377
-
378
- eventEmitter.on(TLLMEvent.Error, (error) => {
379
- hasError = true;
380
- reject(error);
381
- });
382
-
383
- eventEmitter.on(TLLMEvent.ToolInfo, async (toolsData, thinkingBlocks = []) => {
384
- if (this.stop) return;
385
- hasTools = true;
386
- let llmMessage: any = {
387
- role: 'assistant',
388
- content: _content,
389
- tool_calls: [],
390
- };
391
-
392
- if (thinkingBlocks?.length > 0) {
393
- this.emit(
394
- 'thoughtProcess',
395
- thinkingBlocks
396
- .filter((block) => block.type === 'thinking')
397
- .map((block) => block.thinking || '')
398
- .join('\n')
399
- );
400
-
401
- llmMessage.thinkingBlocks = thinkingBlocks;
402
- }
403
-
404
- llmMessage.tool_calls = toolsData.map((tool) => {
405
- return {
406
- id: tool.id,
407
- type: tool.type,
408
- function: {
409
- name: tool.name,
410
- arguments: tool.arguments,
411
- },
412
- };
413
- });
414
-
415
- //if (llmMessage.tool_calls?.length <= 0) return;
416
-
417
- this.emit(TLLMEvent.ToolInfo, toolsData);
418
-
419
- //initialize the agent callback logic
420
- const _agentCallback = (data) => {
421
- if (this.stop) return;
422
- //if (typeof data !== 'string') return;
423
- let content = '';
424
- let thinking = '';
425
- if (typeof data === 'object') {
426
- if (data.content) {
427
- content = data.content;
428
-
429
- passThroughContent += content;
430
- eventEmitter.emit(TLLMEvent.Content, content);
431
- }
432
- if (data.thinking) {
433
- thinking = data.thinking;
434
- eventEmitter.emit(TLLMEvent.Thinking, thinking);
435
- }
436
- return;
437
- }
438
- if (typeof data === 'string') {
439
- passThroughContent += data;
440
- eventEmitter.emit(TLLMEvent.Content, data);
441
- }
442
-
443
- //passThroughContent += data;
444
- //this is currently used to handle agent callbacks when running local agents
445
- //this.emit('agentCallback', data);
446
-
447
- //this.emit('content', data);
448
- //this.emit('content', data);
449
- //eventEmitter.emit('content', data);
450
- };
451
-
452
- const toolProcessingTasks = toolsData.map(
453
- (tool: { index: number; name: string; type: string; arguments: Record<string, any> }) => async () => {
454
- const endpoint = endpoints?.get(tool?.name) || tool?.name;
455
- // Sometimes we have object response from the LLM such as Anthropic
456
-
457
- let args = typeof tool?.arguments === 'string' ? JSONContent(tool?.arguments).tryParse() || {} : tool?.arguments;
458
-
459
- if (args?.error) {
460
- throw new Error('[Tool] Arguments Parsing Error\n' + JSON.stringify({ message: args?.error }));
461
- }
462
-
463
- //await beforeFunctionCall(llmMessage, toolsData[tool.index]);
464
- // TODO [Forhad]: Make sure toolsData[tool.index] and tool do the same thing
465
- this.emit('beforeToolCall', { tool, args }, llmMessage); //deprecated
466
-
467
- const status = tool.name ? this._toolStatusMap?.[tool.name] : undefined;
468
- this.emit(TLLMEvent.ToolCall, { tool, status, _llmRequest: llmMessage });
469
-
470
- const toolArgs = {
471
- type: tool?.type,
472
- method: reqMethods?.get(tool?.name),
473
- endpoint,
474
- args,
475
- baseUrl,
476
- headers: toolHeaders,
477
- agentCallback: _agentCallback,
478
- };
479
-
480
- let { data: functionResponse, error } = await this.useTool(toolArgs, abortSignal);
481
-
482
- if (error) {
483
- functionResponse = typeof error === 'object' && typeof error !== null ? JSON.stringify(error) : error;
484
- }
485
-
486
- const result = functionResponse;
487
-
488
- functionResponse =
489
- typeof functionResponse === 'object' && typeof functionResponse !== null
490
- ? JSON.stringify(functionResponse)
491
- : functionResponse;
492
-
493
- //await afterFunctionCall(functionResponse, toolsData[tool.index]);
494
- this.emit('afterToolCall', { tool, args }, functionResponse); // Deprecated
495
- this.emit(TLLMEvent.ToolResult, { tool, result });
496
-
497
- return { ...tool, result: functionResponse };
498
- }
499
- );
500
-
501
- const processedToolsData = await processWithConcurrencyLimit<ToolData>(toolProcessingTasks, concurrentToolCalls);
502
-
503
- //if (!passThroughContent) {
504
-
505
- if (!passThroughContent) {
506
- this._context.addToolMessage(llmMessage, processedToolsData, message_id);
507
- //delete toolHeaders['x-passthrough'];
508
- } else {
509
- //this._context.addAssistantMessage(passThroughContent, message_id);
510
-
511
- //llmMessage.content += '\n' + passThroughContent;
512
- this._context.addToolMessage(llmMessage, processedToolsData, message_id, { passThrough: true });
513
-
514
- //this._context.addAssistantMessage(passThroughContent, message_id, { passthrough: true });
515
- //this should not be stored in the persistent conversation store
516
- //it's just a workaround to avoid generating more content after passthrough content
517
- //this._context.addUserMessage(passThroughtContinueMessage, message_id, { internal: true });
518
- //toolHeaders['x-passthrough'] = 'true';
519
- }
520
-
521
- this.streamPrompt(null, toolHeaders, concurrentToolCalls, abortSignal).then(resolve).catch(reject);
522
-
523
- //} else {
524
- //TODO : add passthrough content to the context window ??
525
-
526
- //if passThroughContent is not empty, it means that the current agent streamed content through components
527
- //resolve(passThroughContent);
528
- //}
529
- //const result = await resolve(await this.streamPrompt(null, toolHeaders, concurrentToolCalls));
530
- //console.log('Result after tool call: ', result);
531
- });
532
-
533
- eventEmitter.on(TLLMEvent.End, async (toolsData, usage_data, _finishReason) => {
534
- if (_finishReason) finishReason = _finishReason;
535
- if (usage_data) {
536
- //FIXME : normalize the usage data format
537
- this.emit(TLLMEvent.Usage, usage_data);
538
- }
539
- if (hasError) return;
540
-
541
- if (!hasTools || passThroughContent) {
542
- //console.log(' ===> resolved content no tool', _content);
543
- //this._context.push({ role: 'assistant', content: _content });
544
- const lastMessage = this._context?.messages?.[this._context?.messages?.length - 1];
545
- let metadata;
546
- if (lastMessage?.content?.includes(passThroughtContinueMessage) && lastMessage?.__smyth_data__?.internal) {
547
- metadata = { internal: true };
548
- }
549
- this._context.addAssistantMessage(_content, message_id, metadata);
550
- resolve(''); //the content were already emitted through 'content' event
551
- }
552
- });
553
- });
554
-
555
- const toolsContent = await toolsPromise.catch((error) => {
556
- console.error('Error in toolsPromise: ', error);
557
- //this.emit('error', error);
558
- this.emit(TLLMEvent.Error, error);
559
- return '';
560
- });
561
- _content += toolsContent;
562
- //let content = JSONContent(_content).tryParse();
563
-
564
- // let streamPromise = new Promise((resolve, reject) => {
565
- // eventEmitter.on('end', async () => {
566
- // if (toolsPromise) await toolsPromise;
567
-
568
- // let content = JSONContent(_content).tryParse();
569
- // resolve({ content });
570
- // });
571
- // });
572
-
573
- // promises.push(streamPromise);
574
-
575
- //await Promise.all(promises);
576
- //return content;
577
-
578
- if (message) {
579
- //console.log('main content', content);
580
- //this._context.push({ role: 'assistant', content: content });
581
-
582
- if (finishReason !== 'stop') {
583
- this.emit(TLLMEvent.Interrupted, finishReason);
584
- }
585
- this.emit(TLLMEvent.End);
586
- } else {
587
- //console.log('tool content', content);
588
- }
589
-
590
- return _content;
591
- }
592
-
593
- private resolveToolEndpoint(baseUrl: string, method: string, endpoint: string, params: Record<string, any>): string {
594
- //handle query params
595
- let templateParams = {};
596
- if (params) {
597
- const parameters = this._spec?.paths?.[endpoint]?.[method.toLowerCase()]?.parameters || [];
598
- for (let p of parameters) {
599
- if (p.in === 'path') {
600
- templateParams[p.name] = params[p.name] || '';
601
- delete params[p.name];
602
- }
603
- }
604
- }
605
- const parsedEndpoint = TemplateString(endpoint).parse(templateParams, Match.singleCurly).clean().result;
606
-
607
- // Create a new URL object using the base URL and endpoint
608
- const url = new URL(parsedEndpoint, baseUrl);
609
-
610
- // Iterate over the params object and append each key/value pair to the URL search parameters
611
- Object.keys(params).forEach((key) => {
612
- url.searchParams.append(key, params[key]);
613
- });
614
-
615
- // Return the full URL as a string
616
- return url.toString();
617
- }
618
-
619
- private async useTool(
620
- params: ToolParams,
621
- abortSignal?: AbortSignal
622
- ): Promise<{
623
- data: any;
624
- error;
625
- }> {
626
- if (this.stop) {
627
- return { data: null, error: 'Conversation Interrupted' };
628
- }
629
-
630
- const { type, endpoint, args, method, baseUrl, headers = {}, agentCallback } = params;
631
-
632
- if (type === 'function') {
633
- const toolHandler = this._customToolsHandlers[endpoint];
634
- if (toolHandler) {
635
- try {
636
- const result = await toolHandler(args);
637
- return { data: result, error: null };
638
- } catch (error) {
639
- return { data: null, error: error?.message || 'Custom tool handler failed' };
640
- }
641
- }
642
- try {
643
- const url = this.resolveToolEndpoint(baseUrl, method, endpoint, method == 'get' ? args : {});
644
-
645
- const reqConfig: AxiosRequestConfig = {
646
- method,
647
- url,
648
- headers: {
649
- ...headers,
650
- },
651
- signal: abortSignal,
652
- };
653
-
654
- if (method !== 'get') {
655
- if (Object.keys(args).length) {
656
- reqConfig.data = args;
657
- }
658
- //(reqConfig.headers as Record<string, unknown>)['Content-Type'] = 'application/json';
659
- reqConfig.headers['Content-Type'] = 'application/json';
660
- }
661
-
662
- console.debug('Calling tool: ', reqConfig);
663
-
664
- reqConfig.headers['X-CACHE-ID'] = this._context?.llmCache?.id;
665
-
666
- /*
667
- * Objective for the following conditions:
668
- * - In case it is not a debug call and there is no monitor id, then we need to run the agent locally to reduce latency
669
- * - but if it a debug call, we need to forward req to sre-builder-debugger since it holds the debug promises
670
- * - or if there is a monitor id, we need to forward req to sre-builder-debugger since it holds the monitor SSE connections.
671
- * - a remote call is often needed for file parsing be default agent we inject, it should not be loaded locally.
672
- * So the objecive is mainly reducing latency when possible
673
- */
674
- //TODO : implement a timeout for the tool call
675
- const requiresRemoteCall =
676
- reqConfig.headers['X-DEBUG'] !== undefined ||
677
- reqConfig.headers['X-MONITOR-ID'] !== undefined ||
678
- reqConfig.headers['X-AGENT-REMOTE-CALL'] !== undefined;
679
- if (
680
- reqConfig.url.includes('localhost') ||
681
- (reqConfig.headers['X-AGENT-ID'] && !requiresRemoteCall)
682
- //empty string is accepted
683
-
684
- // || reqConfig.url.includes('localagent') //* commented to allow debugging live sessions as the req needs to reach sre-builder-debugger
685
- ) {
686
- console.log('RUNNING AGENT LOCALLY');
687
- let agentProcess;
688
- if (this.agentData === this._specSource) {
689
- //the agent was loaded from data
690
- agentProcess = AgentProcess.load(this.agentData, this._agentVersion);
691
- } else {
692
- //the agent was loaded from a spec
693
- agentProcess = AgentProcess.load(
694
- reqConfig.headers['X-AGENT-ID'] || this._agentId,
695
- reqConfig.headers['X-AGENT-VERSION'] || this._agentVersion
696
- );
697
- }
698
- //if it's a local agent, invoke it directly
699
-
700
- const response = await agentProcess.run(reqConfig as TAgentProcessParams, agentCallback);
701
- return { data: response.data, error: null };
702
- } else {
703
- console.log('RUNNING AGENT REMOTELY');
704
- let eventSource;
705
-
706
- // if debug mode is on OR the user attached a monitor to the call, then we need to attach a monitor to the agent call
707
- if ((reqConfig.headers['X-DEBUG'] && reqConfig.headers['X-AGENT-ID']) || reqConfig.headers['X-MONITOR-ID']) {
708
- console.log('ATTACHING MONITOR TO REMOTE AGENT CALL');
709
- const monitUrl = reqConfig.url.split('/api')[0] + '/agent/' + reqConfig.headers['X-AGENT-ID'] + '/monitor';
710
-
711
- // Create custom fetch implementation that includes our headers
712
- const customFetch: FetchLike = (url, init) => {
713
- return fetch(url, {
714
- ...init,
715
- headers: {
716
- ...(init?.headers || {}),
717
- ...Object.fromEntries(Object.entries(reqConfig.headers).map(([k, v]) => [k, String(v)])),
718
- },
719
- });
720
- };
721
-
722
- const eventSource = new EventSource(monitUrl, {
723
- fetch: customFetch,
724
- });
725
- let monitorId = '';
726
-
727
- eventSource.addEventListener('init', (event) => {
728
- monitorId = event.data;
729
- console.log('monitorId', monitorId);
730
- if (reqConfig.headers['X-MONITOR-ID']) {
731
- // an external monitor was sent, so we do not override it
732
- reqConfig.headers['X-MONITOR-ID'] = `${reqConfig.headers['X-MONITOR-ID']},${monitorId}`;
733
- } else {
734
- reqConfig.headers['X-MONITOR-ID'] = monitorId;
735
- }
736
- });
737
- eventSource.addEventListener('llm/passthrough/content', (event: any) => {
738
- if (params.agentCallback) params.agentCallback({ content: event.data.replace(/\\n/g, '\n') });
739
- });
740
- eventSource.addEventListener('llm/passthrough/thinking', (event: any) => {
741
- if (params.agentCallback) params.agentCallback({ thinking: event.data.replace(/\\n/g, '\n') });
742
- });
743
-
744
- await new Promise((resolve) => {
745
- let maxTime = 5 * 1000; //5 seconds
746
- let itv = setInterval(() => {
747
- if (monitorId || maxTime <= 0) {
748
- clearInterval(itv);
749
- resolve(true);
750
- }
751
- maxTime -= 100;
752
- }, 100);
753
- });
754
- }
755
-
756
- //if it's a remote agent, call the API via HTTP
757
- const response = await axios.request(reqConfig);
758
-
759
- if (eventSource) {
760
- eventSource.close();
761
- console.log('eventSource closed');
762
- }
763
- return { data: response.data, error: null };
764
- }
765
- } catch (error: any) {
766
- console.warn('Failed to call Tool: ', baseUrl, endpoint);
767
- console.warn(' ====>', error);
768
- return { data: null, error: error?.response?.data || error?.message };
769
- }
770
- }
771
-
772
- return { data: null, error: `'${type}' tool type not supported at the moment` };
773
- }
774
-
775
- public async addTool(tool: {
776
- name: string;
777
- description: string;
778
- arguments?: Record<string, any> | string[];
779
- handler: (args: Record<string, any>) => Promise<any>;
780
- inputs?: any[];
781
- }) {
782
- if (!tool.arguments) {
783
- //if no arguments are provided, we need to extract them from the function
784
- const toolFunction = tool.handler as Function;
785
- const openApiArgs = this.extractArgsAsOpenAPI(toolFunction);
786
- const _arguments: any = {};
787
- for (let arg of openApiArgs) {
788
- _arguments[arg.name] = arg.schema;
789
- if (tool.inputs && arg.schema.properties) {
790
- const required = [];
791
- for (let prop in arg.schema.properties) {
792
- const input = tool.inputs?.find((i) => i.name === prop);
793
- if (!arg.schema.properties[prop].description) {
794
- arg.schema.properties[prop].description = input?.description;
795
- }
796
- if (!input?.optional) {
797
- required.push(prop);
798
- }
799
- }
800
- if (required.length) {
801
- arg.schema.required = required;
802
- }
803
- }
804
- }
805
-
806
- tool.arguments = _arguments;
807
- tool.handler = async (argsObj: any) => {
808
- const args = Object.values(argsObj);
809
- const result = await toolFunction(...args);
810
- return result;
811
- };
812
- }
813
-
814
- const requiredFields = Object.values(tool.arguments)
815
- .map((arg) => (arg.required ? arg.name : null))
816
- .filter((arg) => arg);
817
-
818
- const properties = {};
819
- for (let entry in tool.arguments) {
820
- properties[entry] = {
821
- type: tool.arguments[entry].type || 'string',
822
- properties: tool.arguments[entry].properties,
823
- description: tool.arguments[entry].description,
824
- ...(tool.arguments[entry].type === 'array' ? { items: { type: tool.arguments[entry].items?.type || 'string' } } : {}),
825
- };
826
- }
827
- const toolDefinition = {
828
- name: tool.name,
829
- description: tool.description,
830
- properties,
831
- requiredFields,
832
- };
833
- this._customToolsDeclarations.push(toolDefinition);
834
- this._customToolsHandlers[tool.name] = tool.handler;
835
-
836
- //deduplicate tools
837
-
838
- const llmInference: LLMInference = await LLMInference.getInstance(this.model, AccessCandidate.team(this._teamId));
839
- this._customToolsDeclarations = this._customToolsDeclarations.filter(
840
- (tool, index, self) => self.findIndex((t) => t.name === tool.name) === index
841
- );
842
- const toolsConfig: any = llmInference.connector.formatToolsConfig({
843
- type: 'function',
844
- toolDefinitions: this._customToolsDeclarations,
845
- toolChoice: this.toolChoice,
846
- });
847
-
848
- //if (this._toolsConfig) this._toolsConfig.tools.push(...toolsConfig?.tools);
849
- //else this._toolsConfig = toolsConfig;
850
-
851
- this._toolsConfig = toolsConfig;
852
- }
853
- /**
854
- * updates LLM model, if spec is available, it will update the tools config
855
- * @param model
856
- */
857
- // TODO [Forhad]: For now updateModel does not required await, but when we will have tools implementation in custom model then we need to await for it
858
- private async updateModel(model: string | TLLMModel) {
859
- try {
860
- this._model = model;
861
-
862
- if (this._spec) {
863
- this._reqMethods = OpenAPIParser.mapReqMethods(this._spec?.paths);
864
- this._endpoints = OpenAPIParser.mapEndpoints(this._spec?.paths);
865
- this._baseUrl = this._spec?.servers?.[0].url;
866
-
867
- const functionDeclarations = this.getFunctionDeclarations(this._spec);
868
- //functionDeclarations.push(...this._customToolsDeclarations);
869
- this._customToolsDeclarations.push(...functionDeclarations);
870
- const llmInference: LLMInference = await LLMInference.getInstance(this._model, AccessCandidate.team(this._teamId));
871
- if (!llmInference.connector) {
872
- this.emit('error', 'No connector found for model: ' + this._model);
873
- return;
874
- }
875
- this._customToolsDeclarations = this._customToolsDeclarations.filter(
876
- (tool, index, self) => self.findIndex((t) => t.name === tool.name) === index
877
- );
878
- this._toolsConfig = llmInference.connector.formatToolsConfig({
879
- type: 'function',
880
- toolDefinitions: this._customToolsDeclarations,
881
- toolChoice: this.toolChoice,
882
- });
883
-
884
- let messages = [];
885
- if (this._context) messages = this._context.messages; // preserve messages
886
-
887
- this._context = new LLMContext(llmInference, this.systemPrompt, this._llmContextStore);
888
- } else {
889
- this._toolsConfig = null;
890
- this._reqMethods = null;
891
- this._endpoints = null;
892
- this._baseUrl = null;
893
- }
894
- } catch (error) {
895
- this.emit('error', error);
896
- }
897
- }
898
-
899
- /**
900
- * this function is used to patch the spec with missing fields that are required for the tool to work
901
- * @param spec
902
- */
903
- private patchSpec(spec: Record<string, any>) {
904
- const paths = spec?.paths;
905
- for (const path in paths) {
906
- const pathData = paths[path];
907
-
908
- // it's possible we have multiple methods for a single path
909
- for (const key in pathData) {
910
- const data = pathData[key];
911
- if (!data?.operationId) {
912
- //normalize path and use it as operationId
913
- data.operationId = path.replace(/\//g, '_').replace(/{|}/g, '').replace(/\./g, '_');
914
- }
915
- }
916
- }
917
- return spec;
918
- }
919
- /**
920
- * Loads OpenAPI specification from source
921
- * @param specSource
922
- * @returns
923
- */
924
- private async loadSpecFromSource(specSource: string | Record<string, any>) {
925
- if (typeof specSource === 'object') {
926
- //is this a valid OpenAPI spec?
927
- if (OpenAPIParser.isValidOpenAPI(specSource)) {
928
- this.systemPrompt = specSource?.info?.description || '';
929
- return this.patchSpec(specSource);
930
- }
931
- //is this a valid agent data?
932
- if (typeof specSource?.behavior === 'string' && specSource?.components && specSource?.connections) {
933
- this.agentData = specSource; //agent loaded from data directly
934
- this._agentId = specSource.id;
935
- return await this.loadSpecFromAgent(specSource);
936
- }
937
-
938
- return null;
939
- }
940
-
941
- if (typeof specSource === 'string') {
942
- //is this an openAPI url?
943
- if (isUrl(specSource as string)) {
944
- const spec = await OpenAPIParser.getJsonFromUrl(specSource as string);
945
-
946
- if (spec.info?.description) this.systemPrompt = spec.info.description;
947
-
948
- // we always overwrite system prompt with user defined one
949
- if (this.userDefinedSystemPrompt) this.systemPrompt = this.userDefinedSystemPrompt;
950
-
951
- if (spec.info?.title) this.assistantName = spec.info.title;
952
-
953
- const specUrl = new URL(specSource as string);
954
- const defaultBaseUrl = specUrl.origin;
955
-
956
- if (!spec?.servers) spec.servers = [{ url: defaultBaseUrl }];
957
- if (spec.servers?.length == 0) spec.servers = [{ url: defaultBaseUrl }];
958
-
959
- if (this.assistantName) {
960
- this.systemPrompt = `Assistant Name : ${this.assistantName}\n\n${this.systemPrompt}`;
961
- }
962
-
963
- //this._agentId = specUrl.hostname; //just set an agent ID in order to identify the agent in SRE //FIXME: maybe this requires a better solution
964
- return this.patchSpec(spec);
965
- }
966
- //is this an agentId ?
967
- const agentDataConnector = ConnectorService.getAgentDataConnector();
968
- const agentId = specSource as string;
969
- this._agentId = agentId;
970
-
971
- if (this._agentVersion === undefined) {
972
- const isDeployed = await agentDataConnector.isDeployed(agentId);
973
- this._agentVersion = isDeployed ? 'latest' : '';
974
- }
975
-
976
- this.agentData = await agentDataConnector.getAgentData(agentId, this._agentVersion).catch((error) => null);
977
- if (!this.agentData) return null;
978
-
979
- const spec = await this.loadSpecFromAgent(this.agentData);
980
- return spec;
981
- }
982
- }
983
- private async loadSpecFromAgent(agentData: Record<string, any>) {
984
- //handle the case where agentData object contains the agent schema directly
985
- //agents retrieved from the database have a wrapping object with agent name and version number
986
- //local agent might include the agent data directly
987
- if (agentData?.components) {
988
- agentData = { name: agentData?.name, data: agentData, version: '1.0.0' };
989
- }
990
-
991
- const agentDataConnector = ConnectorService.getAgentDataConnector();
992
- this.systemPrompt = agentData?.data?.behavior || this.systemPrompt;
993
-
994
- // we always overwrite system prompt with user defined one
995
- if (this.userDefinedSystemPrompt) this.systemPrompt = this.userDefinedSystemPrompt;
996
-
997
- this.assistantName = agentData?.data?.name || agentData?.data?.templateInfo?.name || this.assistantName;
998
- if (this.assistantName) {
999
- this.systemPrompt = `Assistant Name : ${this.assistantName}\n\n${this.systemPrompt}`;
1000
- }
1001
-
1002
- this._toolStatusMap = agentData?.data?.components
1003
- ?.filter((component) => component.name === 'APIEndpoint')
1004
- .reduce((map, component) => {
1005
- if (component?.data?.endpoint) {
1006
- map[component.data.endpoint] =
1007
- component?.data?.status_message || `Calling ${component?.data?.endpointLabel || component.data.endpoint}`;
1008
- }
1009
- return map;
1010
- }, {});
1011
-
1012
- let baseUrl = this._baseUrl || 'http://localhost/';
1013
- if (baseUrl && !baseUrl.endsWith('/')) {
1014
- baseUrl += '/';
1015
- }
1016
-
1017
- const spec = await agentDataConnector.getOpenAPIJSON(agentData, baseUrl, this._agentVersion, true).catch((error) => null);
1018
- return this.patchSpec(spec);
1019
- }
1020
-
1021
- /**
1022
- * Extracts function declarations from OpenAPI specification
1023
- * @param spec
1024
- * @returns
1025
- */
1026
- private getFunctionDeclarations(spec): FunctionDeclaration[] {
1027
- const paths = spec?.paths;
1028
- const reqMethods = OpenAPIParser.mapReqMethods(paths);
1029
-
1030
- let declarations: FunctionDeclaration[] = [];
1031
-
1032
- for (const path in paths) {
1033
- const pathData = paths[path];
1034
-
1035
- // it's possible we have multiple methods for a single path
1036
- for (const key in pathData) {
1037
- const data = pathData[key];
1038
-
1039
- if (!data?.operationId) continue;
1040
-
1041
- const method = reqMethods.get(data?.operationId) || 'get';
1042
-
1043
- let properties = {};
1044
- let requiredFields: string[] = [];
1045
-
1046
- if (method.toLowerCase() === 'get') {
1047
- const params = data?.parameters || [];
1048
- for (const prop of params) {
1049
- properties[prop.name] = {
1050
- ...prop.schema,
1051
- description: prop.description,
1052
- };
1053
-
1054
- if (prop.required === true) {
1055
- requiredFields.push(prop?.name || '');
1056
- }
1057
- }
1058
- } else {
1059
- properties = data?.requestBody?.content?.['application/json']?.schema?.properties;
1060
- requiredFields = data?.requestBody?.content?.['application/json']?.schema?.required;
1061
-
1062
- // Open AI doesn't support 'required' to be boolean inside property
1063
- for (const prop in properties) {
1064
- delete properties[prop]?.required;
1065
- }
1066
- }
1067
-
1068
- if (!properties) properties = {};
1069
- if (!requiredFields) requiredFields = [];
1070
-
1071
- const declaration = {
1072
- name: data?.operationId,
1073
- description: data?.description || data?.summary || '',
1074
- properties,
1075
- requiredFields,
1076
- };
1077
- declarations.push(declaration);
1078
- }
1079
- }
1080
-
1081
- return declarations;
1082
- }
1083
-
1084
- private async assignTeamIdFromAgentId(agentId: string) {
1085
- if (agentId) {
1086
- const accountConnector = ConnectorService.getAccountConnector();
1087
- const teamId = await accountConnector.getCandidateTeam(AccessCandidate.agent(agentId))?.catch(() => '');
1088
- this._teamId = teamId || '';
1089
- }
1090
- }
1091
-
1092
- private extractArgsAsOpenAPI(fn) {
1093
- const ast = acorn.parse(`(${fn.toString()})`, { ecmaVersion: 'latest' });
1094
- const params = (ast.body[0] as any).expression.params;
1095
-
1096
- let counter = 0;
1097
- function handleParam(param) {
1098
- if (param.type === 'Identifier') {
1099
- return {
1100
- name: param.name,
1101
- in: 'query',
1102
- required: true,
1103
- schema: { type: 'string', name: param.name, required: true },
1104
- };
1105
- }
1106
-
1107
- if (param.type === 'AssignmentPattern' && param.left.type === 'Identifier') {
1108
- return {
1109
- name: param.left.name,
1110
- in: 'query',
1111
- required: false,
1112
- schema: { type: 'string', name: param.left.name, required: false },
1113
- };
1114
- }
1115
-
1116
- if (param.type === 'RestElement' && param.argument.type === 'Identifier') {
1117
- return {
1118
- name: param.argument.name,
1119
- in: 'query',
1120
- required: false,
1121
- schema: { type: 'array', items: { type: 'string' } },
1122
- };
1123
- }
1124
-
1125
- if (param.type === 'ObjectPattern') {
1126
- // For destructured objects, output as a single parameter with nested fields
1127
- const name = `object___${counter++}`;
1128
- return {
1129
- name,
1130
- in: 'query',
1131
- required: true,
1132
- schema: {
1133
- type: 'object',
1134
- required: true,
1135
- name,
1136
- properties: Object.fromEntries(
1137
- param.properties.map((prop) => {
1138
- const keyName = prop.key.name || '[unknown]';
1139
- return [keyName, { type: 'string' }]; // default to string
1140
- })
1141
- ),
1142
- },
1143
- };
1144
- }
1145
-
1146
- const name = `unknown___${counter++}`;
1147
- return {
1148
- name,
1149
- in: 'query',
1150
- required: true,
1151
- schema: { type: 'string', name, required: true },
1152
- };
1153
- }
1154
-
1155
- return params.map(handleParam);
1156
- }
1157
- }
1
+ import { AgentProcess } from '@sre/Core/AgentProcess.helper';
2
+ import { ConnectorService } from '@sre/Core/ConnectorsService';
3
+ import { Logger } from '@sre/helpers/Log.helper';
4
+ import { LLMInference } from '@sre/LLMManager/LLM.inference';
5
+ import { LLMContext } from '@sre/MemoryManager/LLMContext';
6
+ import { TAgentProcessParams } from '@sre/types/Agent.types';
7
+ import { ILLMContextStore, TLLMEvent, TLLMModel, ToolData } from '@sre/types/LLM.types';
8
+ import { isUrl } from '@sre/utils/data.utils';
9
+ import { processWithConcurrencyLimit, uid } from '@sre/utils/general.utils';
10
+ import axios, { AxiosRequestConfig } from 'axios';
11
+ import EventEmitter from 'events';
12
+ import { JSONContent } from './JsonContent.helper';
13
+ import { OpenAPIParser } from './OpenApiParser.helper';
14
+ import { Match, TemplateString } from './TemplateString.helper';
15
+ import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
16
+ import { EventSource, FetchLike } from 'eventsource';
17
+ import { hookAsyncWithContext } from '@sre/Core/HookService';
18
+ import { randomUUID } from 'crypto';
19
+ import * as acorn from 'acorn';
20
+
21
+ const console = Logger('ConversationHelper');
22
+ type FunctionDeclaration = {
23
+ name: string;
24
+ description: string;
25
+ properties: Record<string, any>;
26
+ requiredFields: string[];
27
+ };
28
+ type ToolParams = {
29
+ type: string;
30
+ endpoint: string;
31
+ args: Record<string, any>;
32
+ method: string;
33
+ baseUrl: string;
34
+ headers?: Record<string, string>;
35
+ agentCallback?: (data: any) => void;
36
+ };
37
+
38
+ //TODO: handle authentication
39
+ export class Conversation extends EventEmitter {
40
+ private _agentId: string = '';
41
+ private _systemPrompt;
42
+ private userDefinedSystemPrompt: string = '';
43
+ public toolChoice: string = 'auto';
44
+ public get systemPrompt() {
45
+ return this._systemPrompt;
46
+ }
47
+ public set systemPrompt(systemPrompt) {
48
+ this._systemPrompt = systemPrompt;
49
+ if (this._context) this._context.systemPrompt = systemPrompt;
50
+ }
51
+ public assistantName;
52
+
53
+ private _reqMethods;
54
+ private _toolsConfig;
55
+ private _toolStatusMap: Record<string, string> = {};
56
+ private _endpoints;
57
+ private _baseUrl;
58
+
59
+ private _status = '';
60
+ private _currentWaitPromise;
61
+
62
+ private _llmContextStore: ILLMContextStore;
63
+ private _context: LLMContext;
64
+
65
+ private _maxContextSize = 1024 * 128;
66
+ private _maxOutputTokens = 1024 * 8;
67
+ private _teamId: string = undefined;
68
+ private _agentVersion: string = undefined;
69
+ public agentData: any;
70
+
71
+ public get context() {
72
+ return this._context;
73
+ }
74
+
75
+ private _lastError;
76
+ private _spec;
77
+ private _customToolsDeclarations: FunctionDeclaration[] = [];
78
+ private _customToolsHandlers: Record<string, (args: Record<string, any>) => Promise<any>> = {};
79
+ public stop = false;
80
+ public set spec(specSource) {
81
+ this.ready.then(() => {
82
+ this._status = '';
83
+ this.loadSpecFromSource(specSource).then(async (spec) => {
84
+ if (!spec) {
85
+ this._status = 'error';
86
+ this.emit('error', 'Invalid OpenAPI specification data format');
87
+ throw new Error('Invalid OpenAPI specification data format');
88
+ }
89
+ this._spec = spec;
90
+
91
+ // teamId is required to load custom LLMs, we must assign it before updateModel()
92
+ await this.assignTeamIdFromAgentId(this._agentId);
93
+
94
+ await this.updateModel(this._model);
95
+ this._status = 'ready';
96
+ });
97
+ });
98
+ }
99
+
100
+ public set model(model: string | TLLMModel) {
101
+ this.ready.then(async () => {
102
+ this._status = '';
103
+ await this.updateModel(model);
104
+ this._status = 'ready';
105
+ });
106
+ }
107
+ public get model() {
108
+ return this._model;
109
+ }
110
+
111
+ constructor(
112
+ private _model: string | TLLMModel,
113
+ private _specSource?: string | Record<string, any>,
114
+ private _settings?: {
115
+ maxContextSize?: number;
116
+ maxOutputTokens?: number;
117
+ systemPrompt?: string;
118
+ toolChoice?: string;
119
+ store?: ILLMContextStore;
120
+ experimentalCache?: boolean;
121
+ toolsStrategy?: (toolsConfig) => any;
122
+ agentId?: string;
123
+ agentVersion?: string;
124
+ baseUrl?: string;
125
+ }
126
+ ) {
127
+ //TODO: handle loading previous session (messages)
128
+ super();
129
+
130
+ //this event listener avoids unhandled errors that can cause crashes
131
+ this.on('error', (error) => {
132
+ this._lastError = error;
133
+ console.warn('Conversation Error: ', error?.message);
134
+ });
135
+ this._maxContextSize =
136
+ _settings?.maxContextSize || (this._model as TLLMModel).tokens || (this._model as TLLMModel).keyOptions?.tokens || this._maxContextSize;
137
+ this._maxOutputTokens =
138
+ _settings?.maxOutputTokens ||
139
+ (this._model as TLLMModel).completionTokens ||
140
+ (this._model as TLLMModel).keyOptions?.completionTokens ||
141
+ this._maxOutputTokens;
142
+
143
+ if (_settings?.systemPrompt) {
144
+ this.userDefinedSystemPrompt = _settings.systemPrompt;
145
+ }
146
+ if (_settings?.toolChoice) {
147
+ this.toolChoice = _settings.toolChoice;
148
+ }
149
+
150
+ if (_settings?.store) {
151
+ this._llmContextStore = _settings.store;
152
+ }
153
+
154
+ this._baseUrl = _settings?.baseUrl;
155
+
156
+ this._agentVersion = _settings?.agentVersion;
157
+
158
+ (async () => {
159
+ if (_specSource) {
160
+ this.loadSpecFromSource(_specSource)
161
+ .then(async (spec) => {
162
+ if (!spec) {
163
+ this._status = 'error';
164
+ this.emit('error', 'Unable to parse OpenAPI specifications');
165
+ throw new Error('Invalid OpenAPI specification data format');
166
+ }
167
+ this._spec = spec;
168
+
169
+ if (!this._agentId && _settings?.agentId) this._agentId = _settings.agentId;
170
+ if (!this._agentId) this._agentId = 'FAKE-AGENT-ID'; //We use a fake agent ID to avoid ACL check errors
171
+
172
+ // teamId is required to load custom LLMs, we must assign it before updateModel()
173
+ await this.assignTeamIdFromAgentId(this._agentId);
174
+
175
+ await this.updateModel(this._model);
176
+
177
+ this._status = 'ready';
178
+ })
179
+ .catch((error) => {
180
+ this._status = 'error';
181
+ this.emit('error', error);
182
+ });
183
+ } else {
184
+ await this.updateModel(this._model);
185
+ this._status = 'ready';
186
+ }
187
+ })();
188
+ }
189
+
190
+ public get ready() {
191
+ if (this._currentWaitPromise) return this._currentWaitPromise;
192
+ this._currentWaitPromise = new Promise((resolve, reject) => {
193
+ if (this._status) {
194
+ return resolve(this._status);
195
+ }
196
+
197
+ const maxWaitTime = 30000;
198
+ let waitTime = 0;
199
+ const interval = 100;
200
+
201
+ const wait = setInterval(() => {
202
+ if (this._status) {
203
+ clearInterval(wait);
204
+ return resolve(this._status);
205
+ } else {
206
+ waitTime += interval;
207
+ if (waitTime >= maxWaitTime) {
208
+ clearInterval(wait);
209
+ return reject('Timeout: Failed to prepare data');
210
+ }
211
+ }
212
+ }, interval);
213
+ });
214
+
215
+ return this._currentWaitPromise;
216
+ }
217
+
218
+ //TODO : handle attachments
219
+ @hookAsyncWithContext('Conversation.prompt', async (instance: Conversation) => {
220
+ await instance.ready;
221
+
222
+ return {
223
+ teamId: instance._teamId,
224
+ agentId: instance._agentId,
225
+ model: instance._model,
226
+ };
227
+ })
228
+ public async prompt(message?: string | any, toolHeaders = {}, concurrentToolCalls = 4, abortSignal?: AbortSignal) {
229
+ // if an error occured while streaming, we need to propagate it so for this, we register a one time error listener
230
+ let error = null;
231
+ const errListener = (err) => (error = err);
232
+ this.once('error', errListener);
233
+ const result = await this.streamPrompt(message, toolHeaders, concurrentToolCalls, abortSignal);
234
+
235
+ // if an error event occured, throw the error
236
+ if (error) {
237
+ throw error;
238
+ }
239
+
240
+ this.removeListener('error', errListener);
241
+ return result;
242
+ }
243
+
244
+ //TODO : handle attachments
245
+ @hookAsyncWithContext('Conversation.streamPrompt', async (instance: Conversation) => {
246
+ await instance.ready;
247
+
248
+ return {
249
+ teamId: instance._teamId,
250
+ agentId: instance._agentId,
251
+ model: instance._model,
252
+ };
253
+ })
254
+ public async streamPrompt(message?: string | any, toolHeaders = {}, concurrentToolCalls = 4, abortSignal?: AbortSignal) {
255
+ let options = typeof message === 'object' ? message : { message };
256
+ message = options?.message;
257
+ const files = options?.files;
258
+
259
+ if (message) {
260
+ //initial call, reset stop flag
261
+
262
+ this.stop = false;
263
+ }
264
+ if (this.stop) {
265
+ this.emit('interrupted', 'interrupted');
266
+ this.emit('end');
267
+ return;
268
+ }
269
+ await this.ready;
270
+
271
+ // Add an abort handler
272
+ if (abortSignal) {
273
+ abortSignal.addEventListener('abort', () => {
274
+ //this.emit('error', { name: 'AbortError', message: 'Request aborted by user!' });
275
+ this.emit('aborted', 'Aborted by user!');
276
+ //const error = new Error('Request aborted by user!');
277
+ //error.name = 'AbortError';
278
+ //throw error;
279
+ });
280
+ }
281
+
282
+ const passThroughtContinueMessage = 'Continue with the next tool call if there are any, or just inform the user that you are done';
283
+ //let promises = [];
284
+ let _content = '';
285
+ const reqMethods = this._reqMethods;
286
+ const toolsConfig = this._toolsConfig;
287
+ const endpoints = this._endpoints;
288
+ const baseUrl = this._baseUrl;
289
+ const message_id = 'msg_' + randomUUID();
290
+ const isDebugSession = toolHeaders['X-DEBUG'];
291
+
292
+ /* ==================== STEP ENTRY ==================== */
293
+ // console.debug('Request to LLM with the given model, messages and functions properties.', {
294
+ // model: this.model,
295
+ // message,
296
+ // toolsConfig,
297
+ // });
298
+ /* ==================== STEP ENTRY ==================== */
299
+ const llmInference: LLMInference = await LLMInference.getInstance(this.model, AccessCandidate.team(this._teamId));
300
+
301
+ if (message) this._context.addUserMessage(message, message_id);
302
+
303
+ const contextWindow = await this._context.getContextWindow(this._maxContextSize, this._maxOutputTokens);
304
+
305
+ let maxTokens = this._maxOutputTokens;
306
+ if (typeof this.model === 'object' && this.model?.params?.maxTokens) {
307
+ maxTokens = this.model.params.maxTokens;
308
+ }
309
+
310
+ const eventEmitter: any = await llmInference
311
+ .promptStream({
312
+ contextWindow,
313
+ files,
314
+ params: {
315
+ model: this.model,
316
+ toolsConfig: this._settings?.toolsStrategy ? this._settings.toolsStrategy(toolsConfig) : toolsConfig,
317
+ maxTokens,
318
+ cache: this._settings?.experimentalCache,
319
+ agentId: this._agentId,
320
+ abortSignal,
321
+ },
322
+ })
323
+ .catch((error) => {
324
+ console.error('Error on promptStream: ', error);
325
+ this.emit(TLLMEvent.Error, error);
326
+ });
327
+
328
+ // remove listeners from llm event emitter to stop receiving stream data
329
+ if (abortSignal) {
330
+ abortSignal.addEventListener('abort', () => {
331
+ eventEmitter.removeAllListeners();
332
+ });
333
+ }
334
+ if (!eventEmitter || eventEmitter.error) {
335
+ throw new Error('[LLM Request Error]');
336
+ }
337
+
338
+ if (message) this.emit('start');
339
+ eventEmitter.on('data', (data) => {
340
+ if (this.stop) return;
341
+ this.emit('data', data);
342
+ });
343
+
344
+ eventEmitter.on(TLLMEvent.Thinking, (thinking) => {
345
+ if (this.stop) return;
346
+ this.emit(TLLMEvent.Thinking, thinking);
347
+ });
348
+
349
+ eventEmitter.on(TLLMEvent.Data, (data) => {
350
+ if (this.stop) return;
351
+ this.emit(TLLMEvent.Data, data);
352
+ });
353
+
354
+ eventEmitter.on(TLLMEvent.Content, (content) => {
355
+ if (this.stop) return;
356
+ // if (toolHeaders['x-passthrough']) {
357
+ // console.log('Passthrough skiped content ', content);
358
+ // return;
359
+ // }
360
+ //const lastMessage = this._context?.messages?.[this._context?.messages?.length - 1];
361
+ //const skip = lastMessage?.__smyth_data__?.internal;
362
+
363
+ //skip if the content is the last generated message after a passthrough content
364
+ // if (skip) {
365
+ // let s = true;
366
+ // }
367
+ _content += content;
368
+ this.emit(TLLMEvent.Content, content);
369
+ });
370
+
371
+ let finishReason = 'stop';
372
+
373
+ let toolsPromise = new Promise((resolve, reject) => {
374
+ let hasTools = false;
375
+ let hasError = false;
376
+ let passThroughContent = '';
377
+
378
+ eventEmitter.on(TLLMEvent.Error, (error) => {
379
+ hasError = true;
380
+ reject(error);
381
+ });
382
+
383
+ eventEmitter.on(TLLMEvent.ToolInfo, async (toolsData, thinkingBlocks = []) => {
384
+ if (this.stop) return;
385
+ hasTools = true;
386
+ let llmMessage: any = {
387
+ role: 'assistant',
388
+ content: _content,
389
+ tool_calls: [],
390
+ };
391
+
392
+ if (thinkingBlocks?.length > 0) {
393
+ this.emit(
394
+ 'thoughtProcess',
395
+ thinkingBlocks
396
+ .filter((block) => block.type === 'thinking')
397
+ .map((block) => block.thinking || '')
398
+ .join('\n')
399
+ );
400
+
401
+ llmMessage.thinkingBlocks = thinkingBlocks;
402
+ }
403
+
404
+ llmMessage.tool_calls = toolsData.map((tool) => {
405
+ return {
406
+ id: tool.id,
407
+ type: tool.type,
408
+ function: {
409
+ name: tool.name,
410
+ arguments: tool.arguments,
411
+ },
412
+ };
413
+ });
414
+
415
+ //if (llmMessage.tool_calls?.length <= 0) return;
416
+
417
+ this.emit(TLLMEvent.ToolInfo, toolsData);
418
+
419
+ //initialize the agent callback logic
420
+ const _agentCallback = (data) => {
421
+ if (this.stop) return;
422
+ //if (typeof data !== 'string') return;
423
+ let content = '';
424
+ let thinking = '';
425
+ if (typeof data === 'object') {
426
+ if (data.content) {
427
+ content = data.content;
428
+
429
+ passThroughContent += content;
430
+ eventEmitter.emit(TLLMEvent.Content, content);
431
+ }
432
+ if (data.thinking) {
433
+ thinking = data.thinking;
434
+ eventEmitter.emit(TLLMEvent.Thinking, thinking);
435
+ }
436
+ return;
437
+ }
438
+ if (typeof data === 'string') {
439
+ passThroughContent += data;
440
+ eventEmitter.emit(TLLMEvent.Content, data);
441
+ }
442
+
443
+ //passThroughContent += data;
444
+ //this is currently used to handle agent callbacks when running local agents
445
+ //this.emit('agentCallback', data);
446
+
447
+ //this.emit('content', data);
448
+ //this.emit('content', data);
449
+ //eventEmitter.emit('content', data);
450
+ };
451
+
452
+ const toolProcessingTasks = toolsData.map(
453
+ (tool: { index: number; name: string; type: string; arguments: Record<string, any> }) => async () => {
454
+ const endpoint = endpoints?.get(tool?.name) || tool?.name;
455
+ // Sometimes we have object response from the LLM such as Anthropic
456
+
457
+ let args = typeof tool?.arguments === 'string' ? JSONContent(tool?.arguments).tryParse() || {} : tool?.arguments;
458
+
459
+ if (args?.error) {
460
+ throw new Error('[Tool] Arguments Parsing Error\n' + JSON.stringify({ message: args?.error }));
461
+ }
462
+
463
+ //await beforeFunctionCall(llmMessage, toolsData[tool.index]);
464
+ // TODO [Forhad]: Make sure toolsData[tool.index] and tool do the same thing
465
+ this.emit('beforeToolCall', { tool, args }, llmMessage); //deprecated
466
+
467
+ const status = tool.name ? this._toolStatusMap?.[tool.name] : undefined;
468
+ this.emit(TLLMEvent.ToolCall, { tool, status, _llmRequest: llmMessage });
469
+
470
+ const toolArgs = {
471
+ type: tool?.type,
472
+ method: reqMethods?.get(tool?.name),
473
+ endpoint,
474
+ args,
475
+ baseUrl,
476
+ headers: toolHeaders,
477
+ agentCallback: _agentCallback,
478
+ };
479
+
480
+ let { data: functionResponse, error } = await this.useTool(toolArgs, abortSignal);
481
+
482
+ if (error) {
483
+ functionResponse = typeof error === 'object' && typeof error !== null ? JSON.stringify(error) : error;
484
+ }
485
+
486
+ const result = functionResponse;
487
+
488
+ functionResponse =
489
+ typeof functionResponse === 'object' && typeof functionResponse !== null
490
+ ? JSON.stringify(functionResponse)
491
+ : functionResponse;
492
+
493
+ //await afterFunctionCall(functionResponse, toolsData[tool.index]);
494
+ this.emit('afterToolCall', { tool, args }, functionResponse); // Deprecated
495
+ this.emit(TLLMEvent.ToolResult, { tool, result });
496
+
497
+ return { ...tool, result: functionResponse };
498
+ }
499
+ );
500
+
501
+ const processedToolsData = await processWithConcurrencyLimit<ToolData>(toolProcessingTasks, concurrentToolCalls);
502
+
503
+ //if (!passThroughContent) {
504
+
505
+ if (!passThroughContent) {
506
+ this._context.addToolMessage(llmMessage, processedToolsData, message_id);
507
+ //delete toolHeaders['x-passthrough'];
508
+ } else {
509
+ //this._context.addAssistantMessage(passThroughContent, message_id);
510
+
511
+ //llmMessage.content += '\n' + passThroughContent;
512
+ this._context.addToolMessage(llmMessage, processedToolsData, message_id, { passThrough: true });
513
+
514
+ //this._context.addAssistantMessage(passThroughContent, message_id, { passthrough: true });
515
+ //this should not be stored in the persistent conversation store
516
+ //it's just a workaround to avoid generating more content after passthrough content
517
+ //this._context.addUserMessage(passThroughtContinueMessage, message_id, { internal: true });
518
+ //toolHeaders['x-passthrough'] = 'true';
519
+ }
520
+
521
+ this.streamPrompt(null, toolHeaders, concurrentToolCalls, abortSignal).then(resolve).catch(reject);
522
+
523
+ //} else {
524
+ //TODO : add passthrough content to the context window ??
525
+
526
+ //if passThroughContent is not empty, it means that the current agent streamed content through components
527
+ //resolve(passThroughContent);
528
+ //}
529
+ //const result = await resolve(await this.streamPrompt(null, toolHeaders, concurrentToolCalls));
530
+ //console.log('Result after tool call: ', result);
531
+ });
532
+
533
+ eventEmitter.on(TLLMEvent.End, async (toolsData, usage_data, _finishReason) => {
534
+ if (_finishReason) finishReason = _finishReason;
535
+ if (usage_data) {
536
+ //FIXME : normalize the usage data format
537
+ this.emit(TLLMEvent.Usage, usage_data);
538
+ }
539
+ if (hasError) return;
540
+
541
+ if (!hasTools || passThroughContent) {
542
+ //console.log(' ===> resolved content no tool', _content);
543
+ //this._context.push({ role: 'assistant', content: _content });
544
+ const lastMessage = this._context?.messages?.[this._context?.messages?.length - 1];
545
+ let metadata;
546
+ if (lastMessage?.content?.includes(passThroughtContinueMessage) && lastMessage?.__smyth_data__?.internal) {
547
+ metadata = { internal: true };
548
+ }
549
+ this._context.addAssistantMessage(_content, message_id, metadata);
550
+ resolve(''); //the content were already emitted through 'content' event
551
+ }
552
+ });
553
+ });
554
+
555
+ const toolsContent = await toolsPromise.catch((error) => {
556
+ console.error('Error in toolsPromise: ', error);
557
+ //this.emit('error', error);
558
+ this.emit(TLLMEvent.Error, error);
559
+ return '';
560
+ });
561
+ _content += toolsContent;
562
+ //let content = JSONContent(_content).tryParse();
563
+
564
+ // let streamPromise = new Promise((resolve, reject) => {
565
+ // eventEmitter.on('end', async () => {
566
+ // if (toolsPromise) await toolsPromise;
567
+
568
+ // let content = JSONContent(_content).tryParse();
569
+ // resolve({ content });
570
+ // });
571
+ // });
572
+
573
+ // promises.push(streamPromise);
574
+
575
+ //await Promise.all(promises);
576
+ //return content;
577
+
578
+ if (message) {
579
+ //console.log('main content', content);
580
+ //this._context.push({ role: 'assistant', content: content });
581
+
582
+ if (finishReason !== 'stop') {
583
+ this.emit(TLLMEvent.Interrupted, finishReason);
584
+ }
585
+ this.emit(TLLMEvent.End);
586
+ } else {
587
+ //console.log('tool content', content);
588
+ }
589
+
590
+ return _content;
591
+ }
592
+
593
+ private resolveToolEndpoint(baseUrl: string, method: string, endpoint: string, params: Record<string, any>): string {
594
+ //handle query params
595
+ let templateParams = {};
596
+ if (params) {
597
+ const parameters = this._spec?.paths?.[endpoint]?.[method.toLowerCase()]?.parameters || [];
598
+ for (let p of parameters) {
599
+ if (p.in === 'path') {
600
+ templateParams[p.name] = params[p.name] || '';
601
+ delete params[p.name];
602
+ }
603
+ }
604
+ }
605
+ const parsedEndpoint = TemplateString(endpoint).parse(templateParams, Match.singleCurly).clean().result;
606
+
607
+ // Create a new URL object using the base URL and endpoint
608
+ const url = new URL(parsedEndpoint, baseUrl);
609
+
610
+ // Iterate over the params object and append each key/value pair to the URL search parameters
611
+ Object.keys(params).forEach((key) => {
612
+ url.searchParams.append(key, params[key]);
613
+ });
614
+
615
+ // Return the full URL as a string
616
+ return url.toString();
617
+ }
618
+
619
+ private async useTool(
620
+ params: ToolParams,
621
+ abortSignal?: AbortSignal
622
+ ): Promise<{
623
+ data: any;
624
+ error;
625
+ }> {
626
+ if (this.stop) {
627
+ return { data: null, error: 'Conversation Interrupted' };
628
+ }
629
+
630
+ const { type, endpoint, args, method, baseUrl, headers = {}, agentCallback } = params;
631
+
632
+ if (type === 'function') {
633
+ const toolHandler = this._customToolsHandlers[endpoint];
634
+ if (toolHandler) {
635
+ try {
636
+ const result = await toolHandler(args);
637
+ return { data: result, error: null };
638
+ } catch (error) {
639
+ return { data: null, error: error?.message || 'Custom tool handler failed' };
640
+ }
641
+ }
642
+ try {
643
+ const url = this.resolveToolEndpoint(baseUrl, method, endpoint, method == 'get' ? args : {});
644
+
645
+ const reqConfig: AxiosRequestConfig = {
646
+ method,
647
+ url,
648
+ headers: {
649
+ ...headers,
650
+ },
651
+ signal: abortSignal,
652
+ };
653
+
654
+ if (method !== 'get') {
655
+ if (Object.keys(args).length) {
656
+ reqConfig.data = args;
657
+ }
658
+ //(reqConfig.headers as Record<string, unknown>)['Content-Type'] = 'application/json';
659
+ reqConfig.headers['Content-Type'] = 'application/json';
660
+ }
661
+
662
+ console.debug('Calling tool: ', reqConfig);
663
+
664
+ reqConfig.headers['X-CACHE-ID'] = this._context?.llmCache?.id;
665
+
666
+ /*
667
+ * Objective for the following conditions:
668
+ * - In case it is not a debug call and there is no monitor id, then we need to run the agent locally to reduce latency
669
+ * - but if it a debug call, we need to forward req to sre-builder-debugger since it holds the debug promises
670
+ * - or if there is a monitor id, we need to forward req to sre-builder-debugger since it holds the monitor SSE connections.
671
+ * - a remote call is often needed for file parsing be default agent we inject, it should not be loaded locally.
672
+ * So the objecive is mainly reducing latency when possible
673
+ */
674
+ //TODO : implement a timeout for the tool call
675
+ const requiresRemoteCall =
676
+ reqConfig.headers['X-DEBUG'] !== undefined ||
677
+ reqConfig.headers['X-MONITOR-ID'] !== undefined ||
678
+ reqConfig.headers['X-AGENT-REMOTE-CALL'] !== undefined;
679
+ if (
680
+ reqConfig.url.includes('localhost') ||
681
+ (reqConfig.headers['X-AGENT-ID'] && !requiresRemoteCall)
682
+ //empty string is accepted
683
+
684
+ // || reqConfig.url.includes('localagent') //* commented to allow debugging live sessions as the req needs to reach sre-builder-debugger
685
+ ) {
686
+ console.log('RUNNING AGENT LOCALLY');
687
+ let agentProcess;
688
+ if (this.agentData === this._specSource) {
689
+ //the agent was loaded from data
690
+ agentProcess = AgentProcess.load(this.agentData, this._agentVersion);
691
+ } else {
692
+ //the agent was loaded from a spec
693
+ agentProcess = AgentProcess.load(
694
+ reqConfig.headers['X-AGENT-ID'] || this._agentId,
695
+ reqConfig.headers['X-AGENT-VERSION'] || this._agentVersion
696
+ );
697
+ }
698
+ //if it's a local agent, invoke it directly
699
+
700
+ const response = await agentProcess.run(reqConfig as TAgentProcessParams, agentCallback);
701
+ return { data: response.data, error: null };
702
+ } else {
703
+ console.log('RUNNING AGENT REMOTELY');
704
+ let eventSource;
705
+
706
+ // if debug mode is on OR the user attached a monitor to the call, then we need to attach a monitor to the agent call
707
+ if ((reqConfig.headers['X-DEBUG'] && reqConfig.headers['X-AGENT-ID']) || reqConfig.headers['X-MONITOR-ID']) {
708
+ console.log('ATTACHING MONITOR TO REMOTE AGENT CALL');
709
+ const monitUrl = reqConfig.url.split('/api')[0] + '/agent/' + reqConfig.headers['X-AGENT-ID'] + '/monitor';
710
+
711
+ // Create custom fetch implementation that includes our headers
712
+ const customFetch: FetchLike = (url, init) => {
713
+ return fetch(url, {
714
+ ...init,
715
+ headers: {
716
+ ...(init?.headers || {}),
717
+ ...Object.fromEntries(Object.entries(reqConfig.headers).map(([k, v]) => [k, String(v)])),
718
+ },
719
+ });
720
+ };
721
+
722
+ const eventSource = new EventSource(monitUrl, {
723
+ fetch: customFetch,
724
+ });
725
+ let monitorId = '';
726
+
727
+ eventSource.addEventListener('init', (event) => {
728
+ monitorId = event.data;
729
+ console.log('monitorId', monitorId);
730
+ if (reqConfig.headers['X-MONITOR-ID']) {
731
+ // an external monitor was sent, so we do not override it
732
+ reqConfig.headers['X-MONITOR-ID'] = `${reqConfig.headers['X-MONITOR-ID']},${monitorId}`;
733
+ } else {
734
+ reqConfig.headers['X-MONITOR-ID'] = monitorId;
735
+ }
736
+ });
737
+ eventSource.addEventListener('llm/passthrough/content', (event: any) => {
738
+ if (params.agentCallback) params.agentCallback({ content: event.data.replace(/\\n/g, '\n') });
739
+ });
740
+ eventSource.addEventListener('llm/passthrough/thinking', (event: any) => {
741
+ if (params.agentCallback) params.agentCallback({ thinking: event.data.replace(/\\n/g, '\n') });
742
+ });
743
+
744
+ await new Promise((resolve) => {
745
+ let maxTime = 5 * 1000; //5 seconds
746
+ let itv = setInterval(() => {
747
+ if (monitorId || maxTime <= 0) {
748
+ clearInterval(itv);
749
+ resolve(true);
750
+ }
751
+ maxTime -= 100;
752
+ }, 100);
753
+ });
754
+ }
755
+
756
+ //if it's a remote agent, call the API via HTTP
757
+ const response = await axios.request(reqConfig);
758
+
759
+ if (eventSource) {
760
+ eventSource.close();
761
+ console.log('eventSource closed');
762
+ }
763
+ return { data: response.data, error: null };
764
+ }
765
+ } catch (error: any) {
766
+ console.warn('Failed to call Tool: ', baseUrl, endpoint);
767
+ console.warn(' ====>', error);
768
+ return { data: null, error: error?.response?.data || error?.message };
769
+ }
770
+ }
771
+
772
+ return { data: null, error: `'${type}' tool type not supported at the moment` };
773
+ }
774
+
775
+ public async addTool(tool: {
776
+ name: string;
777
+ description: string;
778
+ arguments?: Record<string, any> | string[];
779
+ handler: (args: Record<string, any>) => Promise<any>;
780
+ inputs?: any[];
781
+ }) {
782
+ if (!tool.arguments) {
783
+ //if no arguments are provided, we need to extract them from the function
784
+ const toolFunction = tool.handler as Function;
785
+ const openApiArgs = this.extractArgsAsOpenAPI(toolFunction);
786
+ const _arguments: any = {};
787
+ for (let arg of openApiArgs) {
788
+ _arguments[arg.name] = arg.schema;
789
+ if (tool.inputs && arg.schema.properties) {
790
+ const required = [];
791
+ for (let prop in arg.schema.properties) {
792
+ const input = tool.inputs?.find((i) => i.name === prop);
793
+ if (!arg.schema.properties[prop].description) {
794
+ arg.schema.properties[prop].description = input?.description;
795
+ }
796
+ if (!input?.optional) {
797
+ required.push(prop);
798
+ }
799
+ }
800
+ if (required.length) {
801
+ arg.schema.required = required;
802
+ }
803
+ }
804
+ }
805
+
806
+ tool.arguments = _arguments;
807
+ tool.handler = async (argsObj: any) => {
808
+ const args = Object.values(argsObj);
809
+ const result = await toolFunction(...args);
810
+ return result;
811
+ };
812
+ }
813
+
814
+ const requiredFields = Object.values(tool.arguments)
815
+ .map((arg) => (arg.required ? arg.name : null))
816
+ .filter((arg) => arg);
817
+
818
+ const properties = {};
819
+ for (let entry in tool.arguments) {
820
+ properties[entry] = {
821
+ type: tool.arguments[entry].type || 'string',
822
+ properties: tool.arguments[entry].properties,
823
+ description: tool.arguments[entry].description,
824
+ ...(tool.arguments[entry].type === 'array' ? { items: { type: tool.arguments[entry].items?.type || 'string' } } : {}),
825
+ };
826
+ }
827
+ const toolDefinition = {
828
+ name: tool.name,
829
+ description: tool.description,
830
+ properties,
831
+ requiredFields,
832
+ };
833
+ this._customToolsDeclarations.push(toolDefinition);
834
+ this._customToolsHandlers[tool.name] = tool.handler;
835
+
836
+ //deduplicate tools
837
+
838
+ const llmInference: LLMInference = await LLMInference.getInstance(this.model, AccessCandidate.team(this._teamId));
839
+ this._customToolsDeclarations = this._customToolsDeclarations.filter(
840
+ (tool, index, self) => self.findIndex((t) => t.name === tool.name) === index
841
+ );
842
+ const toolsConfig: any = llmInference.connector.formatToolsConfig({
843
+ type: 'function',
844
+ toolDefinitions: this._customToolsDeclarations,
845
+ toolChoice: this.toolChoice,
846
+ });
847
+
848
+ //if (this._toolsConfig) this._toolsConfig.tools.push(...toolsConfig?.tools);
849
+ //else this._toolsConfig = toolsConfig;
850
+
851
+ this._toolsConfig = toolsConfig;
852
+ }
853
+ /**
854
+ * updates LLM model, if spec is available, it will update the tools config
855
+ * @param model
856
+ */
857
+ // TODO [Forhad]: For now updateModel does not required await, but when we will have tools implementation in custom model then we need to await for it
858
+ private async updateModel(model: string | TLLMModel) {
859
+ try {
860
+ this._model = model;
861
+
862
+ if (this._spec) {
863
+ this._reqMethods = OpenAPIParser.mapReqMethods(this._spec?.paths);
864
+ this._endpoints = OpenAPIParser.mapEndpoints(this._spec?.paths);
865
+ this._baseUrl = this._spec?.servers?.[0].url;
866
+
867
+ const functionDeclarations = this.getFunctionDeclarations(this._spec);
868
+ //functionDeclarations.push(...this._customToolsDeclarations);
869
+ this._customToolsDeclarations.push(...functionDeclarations);
870
+ const llmInference: LLMInference = await LLMInference.getInstance(this._model, AccessCandidate.team(this._teamId));
871
+ if (!llmInference.connector) {
872
+ this.emit('error', 'No connector found for model: ' + this._model);
873
+ return;
874
+ }
875
+ this._customToolsDeclarations = this._customToolsDeclarations.filter(
876
+ (tool, index, self) => self.findIndex((t) => t.name === tool.name) === index
877
+ );
878
+ this._toolsConfig = llmInference.connector.formatToolsConfig({
879
+ type: 'function',
880
+ toolDefinitions: this._customToolsDeclarations,
881
+ toolChoice: this.toolChoice,
882
+ });
883
+
884
+ let messages = [];
885
+ if (this._context) messages = this._context.messages; // preserve messages
886
+
887
+ this._context = new LLMContext(llmInference, this.systemPrompt, this._llmContextStore);
888
+ } else {
889
+ this._toolsConfig = null;
890
+ this._reqMethods = null;
891
+ this._endpoints = null;
892
+ this._baseUrl = null;
893
+ }
894
+ } catch (error) {
895
+ this.emit('error', error);
896
+ }
897
+ }
898
+
899
+ /**
900
+ * this function is used to patch the spec with missing fields that are required for the tool to work
901
+ * @param spec
902
+ */
903
+ private patchSpec(spec: Record<string, any>) {
904
+ const paths = spec?.paths;
905
+ for (const path in paths) {
906
+ const pathData = paths[path];
907
+
908
+ // it's possible we have multiple methods for a single path
909
+ for (const key in pathData) {
910
+ const data = pathData[key];
911
+ if (!data?.operationId) {
912
+ //normalize path and use it as operationId
913
+ data.operationId = path.replace(/\//g, '_').replace(/{|}/g, '').replace(/\./g, '_');
914
+ }
915
+ }
916
+ }
917
+ return spec;
918
+ }
919
+ /**
920
+ * Loads OpenAPI specification from source
921
+ * @param specSource
922
+ * @returns
923
+ */
924
+ private async loadSpecFromSource(specSource: string | Record<string, any>) {
925
+ if (typeof specSource === 'object') {
926
+ //is this a valid OpenAPI spec?
927
+ if (OpenAPIParser.isValidOpenAPI(specSource)) {
928
+ this.systemPrompt = specSource?.info?.description || '';
929
+ return this.patchSpec(specSource);
930
+ }
931
+ //is this a valid agent data?
932
+ if (typeof specSource?.behavior === 'string' && specSource?.components && specSource?.connections) {
933
+ this.agentData = specSource; //agent loaded from data directly
934
+ this._agentId = specSource.id;
935
+ return await this.loadSpecFromAgent(specSource);
936
+ }
937
+
938
+ return null;
939
+ }
940
+
941
+ if (typeof specSource === 'string') {
942
+ //is this an openAPI url?
943
+ if (isUrl(specSource as string)) {
944
+ const spec = await OpenAPIParser.getJsonFromUrl(specSource as string);
945
+
946
+ if (spec.info?.description) this.systemPrompt = spec.info.description;
947
+
948
+ // we always overwrite system prompt with user defined one
949
+ if (this.userDefinedSystemPrompt) this.systemPrompt = this.userDefinedSystemPrompt;
950
+
951
+ if (spec.info?.title) this.assistantName = spec.info.title;
952
+
953
+ const specUrl = new URL(specSource as string);
954
+ const defaultBaseUrl = specUrl.origin;
955
+
956
+ if (!spec?.servers) spec.servers = [{ url: defaultBaseUrl }];
957
+ if (spec.servers?.length == 0) spec.servers = [{ url: defaultBaseUrl }];
958
+
959
+ if (this.assistantName) {
960
+ this.systemPrompt = `Assistant Name : ${this.assistantName}\n\n${this.systemPrompt}`;
961
+ }
962
+
963
+ //this._agentId = specUrl.hostname; //just set an agent ID in order to identify the agent in SRE //FIXME: maybe this requires a better solution
964
+ return this.patchSpec(spec);
965
+ }
966
+ //is this an agentId ?
967
+ const agentDataConnector = ConnectorService.getAgentDataConnector();
968
+ const agentId = specSource as string;
969
+ this._agentId = agentId;
970
+
971
+ if (this._agentVersion === undefined) {
972
+ const isDeployed = await agentDataConnector.isDeployed(agentId);
973
+ this._agentVersion = isDeployed ? 'latest' : '';
974
+ }
975
+
976
+ this.agentData = await agentDataConnector.getAgentData(agentId, this._agentVersion).catch((error) => null);
977
+ if (!this.agentData) return null;
978
+
979
+ const spec = await this.loadSpecFromAgent(this.agentData);
980
+ return spec;
981
+ }
982
+ }
983
+ private async loadSpecFromAgent(agentData: Record<string, any>) {
984
+ //handle the case where agentData object contains the agent schema directly
985
+ //agents retrieved from the database have a wrapping object with agent name and version number
986
+ //local agent might include the agent data directly
987
+ if (agentData?.components) {
988
+ agentData = { name: agentData?.name, data: agentData, version: '1.0.0' };
989
+ }
990
+
991
+ const agentDataConnector = ConnectorService.getAgentDataConnector();
992
+ this.systemPrompt = agentData?.data?.behavior || this.systemPrompt;
993
+
994
+ // we always overwrite system prompt with user defined one
995
+ if (this.userDefinedSystemPrompt) this.systemPrompt = this.userDefinedSystemPrompt;
996
+
997
+ this.assistantName = agentData?.data?.name || agentData?.data?.templateInfo?.name || this.assistantName;
998
+ if (this.assistantName) {
999
+ this.systemPrompt = `Assistant Name : ${this.assistantName}\n\n${this.systemPrompt}`;
1000
+ }
1001
+
1002
+ this._toolStatusMap = agentData?.data?.components
1003
+ ?.filter((component) => component.name === 'APIEndpoint')
1004
+ .reduce((map, component) => {
1005
+ if (component?.data?.endpoint) {
1006
+ map[component.data.endpoint] =
1007
+ component?.data?.status_message || `Calling ${component?.data?.endpointLabel || component.data.endpoint}`;
1008
+ }
1009
+ return map;
1010
+ }, {});
1011
+
1012
+ let baseUrl = this._baseUrl || 'http://localhost/';
1013
+ if (baseUrl && !baseUrl.endsWith('/')) {
1014
+ baseUrl += '/';
1015
+ }
1016
+
1017
+ const spec = await agentDataConnector.getOpenAPIJSON(agentData, baseUrl, this._agentVersion, true).catch((error) => null);
1018
+ return this.patchSpec(spec);
1019
+ }
1020
+
1021
+ /**
1022
+ * Extracts function declarations from OpenAPI specification
1023
+ * @param spec
1024
+ * @returns
1025
+ */
1026
+ private getFunctionDeclarations(spec): FunctionDeclaration[] {
1027
+ const paths = spec?.paths;
1028
+ const reqMethods = OpenAPIParser.mapReqMethods(paths);
1029
+
1030
+ let declarations: FunctionDeclaration[] = [];
1031
+
1032
+ for (const path in paths) {
1033
+ const pathData = paths[path];
1034
+
1035
+ // it's possible we have multiple methods for a single path
1036
+ for (const key in pathData) {
1037
+ const data = pathData[key];
1038
+
1039
+ if (!data?.operationId) continue;
1040
+
1041
+ const method = reqMethods.get(data?.operationId) || 'get';
1042
+
1043
+ let properties = {};
1044
+ let requiredFields: string[] = [];
1045
+
1046
+ if (method.toLowerCase() === 'get') {
1047
+ const params = data?.parameters || [];
1048
+ for (const prop of params) {
1049
+ properties[prop.name] = {
1050
+ ...prop.schema,
1051
+ description: prop.description,
1052
+ };
1053
+
1054
+ if (prop.required === true) {
1055
+ requiredFields.push(prop?.name || '');
1056
+ }
1057
+ }
1058
+ } else {
1059
+ properties = data?.requestBody?.content?.['application/json']?.schema?.properties;
1060
+ requiredFields = data?.requestBody?.content?.['application/json']?.schema?.required;
1061
+
1062
+ // Open AI doesn't support 'required' to be boolean inside property
1063
+ for (const prop in properties) {
1064
+ delete properties[prop]?.required;
1065
+ }
1066
+ }
1067
+
1068
+ if (!properties) properties = {};
1069
+ if (!requiredFields) requiredFields = [];
1070
+
1071
+ const declaration = {
1072
+ name: data?.operationId,
1073
+ description: data?.description || data?.summary || '',
1074
+ properties,
1075
+ requiredFields,
1076
+ };
1077
+ declarations.push(declaration);
1078
+ }
1079
+ }
1080
+
1081
+ return declarations;
1082
+ }
1083
+
1084
+ private async assignTeamIdFromAgentId(agentId: string) {
1085
+ if (agentId) {
1086
+ const accountConnector = ConnectorService.getAccountConnector();
1087
+ const teamId = await accountConnector.getCandidateTeam(AccessCandidate.agent(agentId))?.catch(() => '');
1088
+ this._teamId = teamId || '';
1089
+ }
1090
+ }
1091
+
1092
+ private extractArgsAsOpenAPI(fn) {
1093
+ const ast = acorn.parse(`(${fn.toString()})`, { ecmaVersion: 'latest' });
1094
+ const params = (ast.body[0] as any).expression.params;
1095
+
1096
+ let counter = 0;
1097
+ function handleParam(param) {
1098
+ if (param.type === 'Identifier') {
1099
+ return {
1100
+ name: param.name,
1101
+ in: 'query',
1102
+ required: true,
1103
+ schema: { type: 'string', name: param.name, required: true },
1104
+ };
1105
+ }
1106
+
1107
+ if (param.type === 'AssignmentPattern' && param.left.type === 'Identifier') {
1108
+ return {
1109
+ name: param.left.name,
1110
+ in: 'query',
1111
+ required: false,
1112
+ schema: { type: 'string', name: param.left.name, required: false },
1113
+ };
1114
+ }
1115
+
1116
+ if (param.type === 'RestElement' && param.argument.type === 'Identifier') {
1117
+ return {
1118
+ name: param.argument.name,
1119
+ in: 'query',
1120
+ required: false,
1121
+ schema: { type: 'array', items: { type: 'string' } },
1122
+ };
1123
+ }
1124
+
1125
+ if (param.type === 'ObjectPattern') {
1126
+ // For destructured objects, output as a single parameter with nested fields
1127
+ const name = `object___${counter++}`;
1128
+ return {
1129
+ name,
1130
+ in: 'query',
1131
+ required: true,
1132
+ schema: {
1133
+ type: 'object',
1134
+ required: true,
1135
+ name,
1136
+ properties: Object.fromEntries(
1137
+ param.properties.map((prop) => {
1138
+ const keyName = prop.key.name || '[unknown]';
1139
+ return [keyName, { type: 'string' }]; // default to string
1140
+ })
1141
+ ),
1142
+ },
1143
+ };
1144
+ }
1145
+
1146
+ const name = `unknown___${counter++}`;
1147
+ return {
1148
+ name,
1149
+ in: 'query',
1150
+ required: true,
1151
+ schema: { type: 'string', name, required: true },
1152
+ };
1153
+ }
1154
+
1155
+ return params.map(handleParam);
1156
+ }
1157
+ }