@smythos/sre 1.5.1 → 1.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/LICENSE +18 -0
  2. package/dist/index.js +22329 -4
  3. package/dist/index.js.map +1 -1
  4. package/dist/types/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.d.ts +2 -2
  5. package/dist/types/subsystems/IO/VectorDB.service/embed/BaseEmbedding.d.ts +11 -7
  6. package/dist/types/types/VectorDB.types.d.ts +13 -11
  7. package/package.json +102 -127
  8. package/src/Components/APICall/APICall.class.ts +155 -0
  9. package/src/Components/APICall/AccessTokenManager.ts +130 -0
  10. package/src/Components/APICall/ArrayBufferResponse.helper.ts +58 -0
  11. package/src/Components/APICall/OAuth.helper.ts +294 -0
  12. package/src/Components/APICall/mimeTypeCategories.ts +46 -0
  13. package/src/Components/APICall/parseData.ts +167 -0
  14. package/src/Components/APICall/parseHeaders.ts +41 -0
  15. package/src/Components/APICall/parseProxy.ts +68 -0
  16. package/src/Components/APICall/parseUrl.ts +91 -0
  17. package/src/Components/APIEndpoint.class.ts +234 -0
  18. package/src/Components/APIOutput.class.ts +58 -0
  19. package/src/Components/AgentPlugin.class.ts +102 -0
  20. package/src/Components/Async.class.ts +155 -0
  21. package/src/Components/Await.class.ts +90 -0
  22. package/src/Components/Classifier.class.ts +158 -0
  23. package/src/Components/Component.class.ts +94 -0
  24. package/src/Components/ComponentHost.class.ts +38 -0
  25. package/src/Components/DataSourceCleaner.class.ts +92 -0
  26. package/src/Components/DataSourceIndexer.class.ts +181 -0
  27. package/src/Components/DataSourceLookup.class.ts +141 -0
  28. package/src/Components/FEncDec.class.ts +29 -0
  29. package/src/Components/FHash.class.ts +33 -0
  30. package/src/Components/FSign.class.ts +80 -0
  31. package/src/Components/FSleep.class.ts +25 -0
  32. package/src/Components/FTimestamp.class.ts +25 -0
  33. package/src/Components/FileStore.class.ts +75 -0
  34. package/src/Components/ForEach.class.ts +97 -0
  35. package/src/Components/GPTPlugin.class.ts +70 -0
  36. package/src/Components/GenAILLM.class.ts +395 -0
  37. package/src/Components/HuggingFace.class.ts +314 -0
  38. package/src/Components/Image/imageSettings.config.ts +70 -0
  39. package/src/Components/ImageGenerator.class.ts +407 -0
  40. package/src/Components/JSONFilter.class.ts +54 -0
  41. package/src/Components/LLMAssistant.class.ts +213 -0
  42. package/src/Components/LogicAND.class.ts +28 -0
  43. package/src/Components/LogicAtLeast.class.ts +85 -0
  44. package/src/Components/LogicAtMost.class.ts +86 -0
  45. package/src/Components/LogicOR.class.ts +29 -0
  46. package/src/Components/LogicXOR.class.ts +34 -0
  47. package/src/Components/MCPClient.class.ts +112 -0
  48. package/src/Components/PromptGenerator.class.ts +122 -0
  49. package/src/Components/ScrapflyWebScrape.class.ts +159 -0
  50. package/src/Components/TavilyWebSearch.class.ts +98 -0
  51. package/src/Components/index.ts +77 -0
  52. package/src/Core/AgentProcess.helper.ts +240 -0
  53. package/src/Core/Connector.class.ts +123 -0
  54. package/src/Core/ConnectorsService.ts +192 -0
  55. package/src/Core/DummyConnector.ts +49 -0
  56. package/src/Core/HookService.ts +105 -0
  57. package/src/Core/SmythRuntime.class.ts +292 -0
  58. package/src/Core/SystemEvents.ts +15 -0
  59. package/src/Core/boot.ts +55 -0
  60. package/src/config.ts +15 -0
  61. package/src/constants.ts +125 -0
  62. package/src/data/hugging-face.params.json +580 -0
  63. package/src/helpers/BinaryInput.helper.ts +324 -0
  64. package/src/helpers/Conversation.helper.ts +1094 -0
  65. package/src/helpers/JsonContent.helper.ts +97 -0
  66. package/src/helpers/LocalCache.helper.ts +97 -0
  67. package/src/helpers/Log.helper.ts +234 -0
  68. package/src/helpers/OpenApiParser.helper.ts +150 -0
  69. package/src/helpers/S3Cache.helper.ts +129 -0
  70. package/src/helpers/SmythURI.helper.ts +5 -0
  71. package/src/helpers/TemplateString.helper.ts +243 -0
  72. package/src/helpers/TypeChecker.helper.ts +329 -0
  73. package/src/index.ts +179 -0
  74. package/src/index.ts.bak +179 -0
  75. package/src/subsystems/AgentManager/Agent.class.ts +1108 -0
  76. package/src/subsystems/AgentManager/Agent.helper.ts +3 -0
  77. package/src/subsystems/AgentManager/AgentData.service/AgentDataConnector.ts +230 -0
  78. package/src/subsystems/AgentManager/AgentData.service/connectors/CLIAgentDataConnector.class.ts +66 -0
  79. package/src/subsystems/AgentManager/AgentData.service/connectors/LocalAgentDataConnector.class.ts +142 -0
  80. package/src/subsystems/AgentManager/AgentData.service/connectors/NullAgentData.class.ts +39 -0
  81. package/src/subsystems/AgentManager/AgentData.service/index.ts +18 -0
  82. package/src/subsystems/AgentManager/AgentLogger.class.ts +297 -0
  83. package/src/subsystems/AgentManager/AgentRequest.class.ts +51 -0
  84. package/src/subsystems/AgentManager/AgentRuntime.class.ts +559 -0
  85. package/src/subsystems/AgentManager/AgentSSE.class.ts +101 -0
  86. package/src/subsystems/AgentManager/AgentSettings.class.ts +52 -0
  87. package/src/subsystems/AgentManager/Component.service/ComponentConnector.ts +32 -0
  88. package/src/subsystems/AgentManager/Component.service/connectors/LocalComponentConnector.class.ts +59 -0
  89. package/src/subsystems/AgentManager/Component.service/index.ts +11 -0
  90. package/src/subsystems/AgentManager/EmbodimentSettings.class.ts +47 -0
  91. package/src/subsystems/AgentManager/ForkedAgent.class.ts +153 -0
  92. package/src/subsystems/AgentManager/OSResourceMonitor.ts +77 -0
  93. package/src/subsystems/ComputeManager/Code.service/CodeConnector.ts +99 -0
  94. package/src/subsystems/ComputeManager/Code.service/connectors/AWSLambdaCode.class.ts +63 -0
  95. package/src/subsystems/ComputeManager/Code.service/index.ts +11 -0
  96. package/src/subsystems/IO/CLI.service/CLIConnector.ts +47 -0
  97. package/src/subsystems/IO/CLI.service/index.ts +9 -0
  98. package/src/subsystems/IO/Log.service/LogConnector.ts +32 -0
  99. package/src/subsystems/IO/Log.service/connectors/ConsoleLog.class.ts +28 -0
  100. package/src/subsystems/IO/Log.service/index.ts +13 -0
  101. package/src/subsystems/IO/NKV.service/NKVConnector.ts +41 -0
  102. package/src/subsystems/IO/NKV.service/connectors/NKVRAM.class.ts +204 -0
  103. package/src/subsystems/IO/NKV.service/connectors/NKVRedis.class.ts +182 -0
  104. package/src/subsystems/IO/NKV.service/index.ts +12 -0
  105. package/src/subsystems/IO/Router.service/RouterConnector.ts +21 -0
  106. package/src/subsystems/IO/Router.service/connectors/ExpressRouter.class.ts +48 -0
  107. package/src/subsystems/IO/Router.service/connectors/NullRouter.class.ts +40 -0
  108. package/src/subsystems/IO/Router.service/index.ts +11 -0
  109. package/src/subsystems/IO/Storage.service/SmythFS.class.ts +472 -0
  110. package/src/subsystems/IO/Storage.service/StorageConnector.ts +66 -0
  111. package/src/subsystems/IO/Storage.service/connectors/LocalStorage.class.ts +305 -0
  112. package/src/subsystems/IO/Storage.service/connectors/S3Storage.class.ts +418 -0
  113. package/src/subsystems/IO/Storage.service/index.ts +13 -0
  114. package/src/subsystems/IO/VectorDB.service/VectorDBConnector.ts +108 -0
  115. package/src/subsystems/IO/VectorDB.service/connectors/MilvusVectorDB.class.ts +454 -0
  116. package/src/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.ts +384 -0
  117. package/src/subsystems/IO/VectorDB.service/connectors/RAMVecrtorDB.class.ts +421 -0
  118. package/src/subsystems/IO/VectorDB.service/embed/BaseEmbedding.ts +107 -0
  119. package/src/subsystems/IO/VectorDB.service/embed/OpenAIEmbedding.ts +109 -0
  120. package/src/subsystems/IO/VectorDB.service/embed/index.ts +21 -0
  121. package/src/subsystems/IO/VectorDB.service/index.ts +14 -0
  122. package/src/subsystems/LLMManager/LLM.helper.ts +221 -0
  123. package/src/subsystems/LLMManager/LLM.inference.ts +335 -0
  124. package/src/subsystems/LLMManager/LLM.service/LLMConnector.ts +375 -0
  125. package/src/subsystems/LLMManager/LLM.service/LLMCredentials.helper.ts +145 -0
  126. package/src/subsystems/LLMManager/LLM.service/connectors/Anthropic.class.ts +632 -0
  127. package/src/subsystems/LLMManager/LLM.service/connectors/Bedrock.class.ts +405 -0
  128. package/src/subsystems/LLMManager/LLM.service/connectors/Echo.class.ts +81 -0
  129. package/src/subsystems/LLMManager/LLM.service/connectors/GoogleAI.class.ts +689 -0
  130. package/src/subsystems/LLMManager/LLM.service/connectors/Groq.class.ts +257 -0
  131. package/src/subsystems/LLMManager/LLM.service/connectors/OpenAI.class.ts +848 -0
  132. package/src/subsystems/LLMManager/LLM.service/connectors/Perplexity.class.ts +255 -0
  133. package/src/subsystems/LLMManager/LLM.service/connectors/VertexAI.class.ts +193 -0
  134. package/src/subsystems/LLMManager/LLM.service/index.ts +43 -0
  135. package/src/subsystems/LLMManager/ModelsProvider.service/ModelsProviderConnector.ts +281 -0
  136. package/src/subsystems/LLMManager/ModelsProvider.service/connectors/SmythModelsProvider.class.ts +229 -0
  137. package/src/subsystems/LLMManager/ModelsProvider.service/index.ts +11 -0
  138. package/src/subsystems/LLMManager/custom-models.ts +854 -0
  139. package/src/subsystems/LLMManager/models.ts +2539 -0
  140. package/src/subsystems/LLMManager/paramMappings.ts +69 -0
  141. package/src/subsystems/MemoryManager/Cache.service/CacheConnector.ts +86 -0
  142. package/src/subsystems/MemoryManager/Cache.service/connectors/LocalStorageCache.class.ts +297 -0
  143. package/src/subsystems/MemoryManager/Cache.service/connectors/RAMCache.class.ts +201 -0
  144. package/src/subsystems/MemoryManager/Cache.service/connectors/RedisCache.class.ts +252 -0
  145. package/src/subsystems/MemoryManager/Cache.service/connectors/S3Cache.class.ts +373 -0
  146. package/src/subsystems/MemoryManager/Cache.service/index.ts +15 -0
  147. package/src/subsystems/MemoryManager/LLMCache.ts +72 -0
  148. package/src/subsystems/MemoryManager/LLMContext.ts +125 -0
  149. package/src/subsystems/MemoryManager/RuntimeContext.ts +249 -0
  150. package/src/subsystems/Security/AccessControl/ACL.class.ts +208 -0
  151. package/src/subsystems/Security/AccessControl/AccessCandidate.class.ts +76 -0
  152. package/src/subsystems/Security/AccessControl/AccessRequest.class.ts +52 -0
  153. package/src/subsystems/Security/Account.service/AccountConnector.ts +41 -0
  154. package/src/subsystems/Security/Account.service/connectors/AWSAccount.class.ts +76 -0
  155. package/src/subsystems/Security/Account.service/connectors/DummyAccount.class.ts +130 -0
  156. package/src/subsystems/Security/Account.service/connectors/JSONFileAccount.class.ts +159 -0
  157. package/src/subsystems/Security/Account.service/index.ts +14 -0
  158. package/src/subsystems/Security/Credentials.helper.ts +62 -0
  159. package/src/subsystems/Security/ManagedVault.service/ManagedVaultConnector.ts +34 -0
  160. package/src/subsystems/Security/ManagedVault.service/connectors/NullManagedVault.class.ts +57 -0
  161. package/src/subsystems/Security/ManagedVault.service/connectors/SecretManagerManagedVault.ts +154 -0
  162. package/src/subsystems/Security/ManagedVault.service/index.ts +12 -0
  163. package/src/subsystems/Security/SecureConnector.class.ts +110 -0
  164. package/src/subsystems/Security/Vault.service/Vault.helper.ts +30 -0
  165. package/src/subsystems/Security/Vault.service/VaultConnector.ts +26 -0
  166. package/src/subsystems/Security/Vault.service/connectors/HashicorpVault.class.ts +46 -0
  167. package/src/subsystems/Security/Vault.service/connectors/JSONFileVault.class.ts +166 -0
  168. package/src/subsystems/Security/Vault.service/connectors/NullVault.class.ts +54 -0
  169. package/src/subsystems/Security/Vault.service/connectors/SecretsManager.class.ts +140 -0
  170. package/src/subsystems/Security/Vault.service/index.ts +12 -0
  171. package/src/types/ACL.types.ts +104 -0
  172. package/src/types/AWS.types.ts +9 -0
  173. package/src/types/Agent.types.ts +61 -0
  174. package/src/types/AgentLogger.types.ts +17 -0
  175. package/src/types/Cache.types.ts +1 -0
  176. package/src/types/Common.types.ts +3 -0
  177. package/src/types/LLM.types.ts +419 -0
  178. package/src/types/Redis.types.ts +8 -0
  179. package/src/types/SRE.types.ts +64 -0
  180. package/src/types/Security.types.ts +18 -0
  181. package/src/types/Storage.types.ts +5 -0
  182. package/src/types/VectorDB.types.ts +86 -0
  183. package/src/utils/base64.utils.ts +275 -0
  184. package/src/utils/cli.utils.ts +68 -0
  185. package/src/utils/data.utils.ts +263 -0
  186. package/src/utils/date-time.utils.ts +22 -0
  187. package/src/utils/general.utils.ts +238 -0
  188. package/src/utils/index.ts +12 -0
  189. package/src/utils/numbers.utils.ts +13 -0
  190. package/src/utils/oauth.utils.ts +35 -0
  191. package/src/utils/string.utils.ts +414 -0
  192. package/src/utils/url.utils.ts +19 -0
  193. package/src/utils/validation.utils.ts +74 -0
@@ -0,0 +1,395 @@
1
+ import Joi from 'joi';
2
+ import { IAgent as Agent } from '@sre/types/Agent.types';
3
+ import { LLMInference } from '@sre/LLMManager/LLM.inference';
4
+ import { TemplateString } from '@sre/helpers/TemplateString.helper';
5
+ import { SUPPORTED_MIME_TYPES_MAP } from '@sre/constants';
6
+ import { getMimeType } from '@sre/utils/data.utils';
7
+ import { Component } from './Component.class';
8
+ import { formatDataForDebug } from '@sre/utils/data.utils';
9
+ import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
10
+
11
+ //TODO : better handling of context window exceeding max length
12
+
13
+ export class GenAILLM extends Component {
14
+ protected schema = {
15
+ name: 'GenAILLM',
16
+ description: 'Use this component to generate a responses from an LLM',
17
+ settings: {
18
+ model: {
19
+ type: 'string',
20
+ max: 200,
21
+ required: true,
22
+ },
23
+ prompt: {
24
+ type: 'string',
25
+ max: 8_000_000,
26
+ label: 'Prompt',
27
+ },
28
+ temperature: {
29
+ type: 'number',
30
+ min: 0,
31
+ max: 5,
32
+ label: 'Temperature',
33
+ },
34
+ maxTokens: {
35
+ type: 'number',
36
+ min: 1,
37
+ label: 'Maximum Tokens',
38
+ },
39
+ maxThinkingTokens: {
40
+ type: 'number',
41
+ min: 1,
42
+ label: 'Maximum Thinking Tokens',
43
+ },
44
+ stopSequences: {
45
+ type: 'string',
46
+ max: 400,
47
+ label: 'Stop Sequences',
48
+ allowEmpty: true,
49
+ },
50
+ topP: {
51
+ type: 'number',
52
+ min: 0,
53
+ max: 1,
54
+ label: 'Top P',
55
+ },
56
+ topK: {
57
+ type: 'number',
58
+ min: 0,
59
+ max: 500,
60
+ label: 'Top K',
61
+ },
62
+ frequencyPenalty: {
63
+ type: 'number',
64
+ min: 0,
65
+ max: 2,
66
+ label: 'Frequency Penalty',
67
+ },
68
+ presencePenalty: {
69
+ type: 'number',
70
+ min: 0,
71
+ max: 2,
72
+ label: 'Presence Penalty',
73
+ },
74
+ responseFormat: {
75
+ type: 'string',
76
+ valid: ['json', 'text'],
77
+ label: 'Response Format',
78
+ },
79
+ passthrough: {
80
+ type: 'boolean',
81
+ description: 'If true, the LLM response will be returned as is by the agent',
82
+ label: 'Passthrough',
83
+ },
84
+ useSystemPrompt: {
85
+ type: 'boolean',
86
+ description: 'If true, the component will use parent agent system prompt',
87
+ label: 'Use System Prompt',
88
+ },
89
+ useContextWindow: {
90
+ type: 'boolean',
91
+ description: 'If true, the component will use parent agent context window',
92
+ label: 'Use Context Window',
93
+ },
94
+ maxContextWindowLength: {
95
+ type: 'number',
96
+ min: 0,
97
+ description: 'The maximum number of messages to use from this component context window (if useContextWindow is true)',
98
+ label: 'Maximum Context Window Length',
99
+ },
100
+ },
101
+ inputs: {
102
+ Input: {
103
+ type: 'Any',
104
+ description: 'An input that you can pass to the LLM',
105
+ },
106
+ Attachment: {
107
+ type: 'Binary',
108
+ description: 'An attachment that you can pass to the LLM',
109
+ optional: true,
110
+ },
111
+ },
112
+ outputs: {
113
+ Reply: {
114
+ default: true,
115
+ },
116
+ },
117
+ };
118
+ protected configSchema = Joi.object({
119
+ model: Joi.string().max(200).required(),
120
+ prompt: Joi.string().required().max(8_000_000).label('Prompt'), // 2M tokens is around 8M characters
121
+ temperature: Joi.number().min(0).max(5).label('Temperature'), // max temperature is 2 for OpenAI and togetherAI but 5 for cohere
122
+ maxTokens: Joi.number().min(1).label('Maximum Tokens'),
123
+ stopSequences: Joi.string().allow('').max(400).label('Stop Sequences'),
124
+ topP: Joi.number().min(0).max(1).label('Top P'),
125
+ topK: Joi.number().min(0).max(500).label('Top K'), // max top_k is 100 for togetherAI but 500 for cohere
126
+ frequencyPenalty: Joi.number().min(0).max(2).label('Frequency Penalty'),
127
+ presencePenalty: Joi.number().min(0).max(2).label('Presence Penalty'),
128
+ responseFormat: Joi.string().valid('json', 'text').optional().label('Response Format'),
129
+ passthrough: Joi.boolean().optional().label('Passthrough'),
130
+ useSystemPrompt: Joi.boolean().optional().label('Use System Prompt'),
131
+ useContextWindow: Joi.boolean().optional().label('Use Context Window'),
132
+ maxContextWindowLength: Joi.number().optional().min(0).label('Maximum Context Window Length'),
133
+
134
+ // #region Search
135
+ useWebSearch: Joi.boolean().optional().label('Use Search'),
136
+ webSearchContextSize: Joi.string().valid('high', 'medium', 'low').optional().label('Search Content Size'),
137
+ webSearchCity: Joi.string().max(100).optional().allow('').label('Search City'),
138
+ webSearchCountry: Joi.string().max(100).optional().allow('').label('Search Country'),
139
+ webSearchRegion: Joi.string().max(100).optional().allow('').label('Search Region'),
140
+ webSearchTimezone: Joi.string().max(100).optional().allow('').label('Search Timezone'),
141
+ // #endregion
142
+
143
+ useReasoning: Joi.boolean().optional().label('Use Reasoning'),
144
+ maxThinkingTokens: Joi.number().min(1).label('Maximum Thinking Tokens'),
145
+ });
146
+ constructor() {
147
+ super();
148
+ }
149
+ init() {}
150
+ async process(input, config, agent: Agent) {
151
+ await super.process(input, config, agent);
152
+
153
+ //let debugLog = agent.agentRuntime?.debug ? [] : undefined;
154
+ const logger = this.createComponentLogger(agent, config);
155
+
156
+ try {
157
+ logger.debug(`=== GenAILLM Log ===`);
158
+ let teamId = agent?.teamId;
159
+
160
+ const passThrough: boolean = config.data.passthrough || false;
161
+ const useContextWindow: boolean = config.data.useContextWindow || false;
162
+ const useSystemPrompt: boolean = config.data.useSystemPrompt || false;
163
+ const useWebSearch: boolean = config.data.useWebSearch || false;
164
+ const maxTokens: number = parseInt(config.data.maxTokens) || 1024;
165
+ const maxContextWindowLength: number = parseInt(config.data.maxContextWindowLength) || 1024;
166
+ const model: string = config.data.model || 'echo';
167
+ const llmInference: LLMInference = await LLMInference.getInstance(model, AccessCandidate.agent(agent.id));
168
+
169
+ // if the llm is undefined, then it means we removed the model from our system
170
+ if (!llmInference.connector) {
171
+ return {
172
+ _error: `The model '${model}' is not available. Please try a different one.`,
173
+ _debug: logger.output,
174
+ };
175
+ }
176
+
177
+ //const team = AccessCandidate.team(teamId);
178
+ //const llmRegistry = isStandardLLM ? LLMRegistry : await CustomLLMRegistry.getInstance(team);
179
+ const modelId = await agent.modelsProvider.getModelId(model);
180
+
181
+ logger.debug(` Model : ${modelId || model}`);
182
+
183
+ let prompt: any = TemplateString(config.data.prompt).parse(input).result;
184
+
185
+ let files: any[] = parseFiles(input, config);
186
+ let isMultimodalRequest = false;
187
+ const provider = await agent.modelsProvider.getProvider(model);
188
+ const isEcho = provider === 'Echo';
189
+
190
+ // Ignore files for Echo model
191
+ if (files?.length > 0 && !isEcho) {
192
+ // TODO: simplify the valid files checking logic
193
+ const supportedFileTypes = SUPPORTED_MIME_TYPES_MAP?.[provider] || {};
194
+ const modelInfo = await agent.modelsProvider.getModelInfo(model);
195
+ const features = modelInfo?.features || [];
196
+ const fileTypes = new Set(); // Set to avoid duplicates
197
+
198
+ const validFiles = await Promise.all(
199
+ files.map(async (file) => {
200
+ const mimeType = file?.mimetype || (await getMimeType(file));
201
+ const [requestFeature = ''] =
202
+ Object.entries(supportedFileTypes).find(([key, value]) => (value as string[]).includes(mimeType)) || [];
203
+
204
+ if (mimeType) {
205
+ fileTypes.add(mimeType);
206
+ }
207
+
208
+ return features?.includes(requestFeature) ? file : null;
209
+ })
210
+ );
211
+
212
+ files = validFiles.filter(Boolean);
213
+
214
+ if (files.length === 0) {
215
+ return {
216
+ _error: `Model does not support ${fileTypes?.size > 0 ? Array.from(fileTypes).join(', ') : 'File(s)'}`,
217
+ _debug: logger.output,
218
+ };
219
+ }
220
+
221
+ isMultimodalRequest = true;
222
+ }
223
+
224
+ logger.debug(` Prompt\n`, prompt, '\n');
225
+
226
+ if (!isEcho) {
227
+ logger.debug(' Files\n', await Promise.all(files.map((file) => formatDataForDebug(file))));
228
+ }
229
+
230
+ // default to json response format
231
+ config.data.responseFormat = config.data?.responseFormat || 'json';
232
+
233
+ // request to LLM
234
+ let response: any;
235
+
236
+ const _prompt = llmInference.connector.enhancePrompt(prompt, config);
237
+ let messages = [];
238
+
239
+ let systemPrompt = '';
240
+ if (useSystemPrompt) {
241
+ //first we try to grab the system prompt from llmCache (in case of a ConversationHelper implementing dynamic system prompt)
242
+ const cachedPrompt = await agent.agentRuntime.llmCache.get('systemPrompt', 'text');
243
+ //if not found, we can read the system prompt from agent data.
244
+ systemPrompt = cachedPrompt || agent.data?.behavior || '';
245
+
246
+ if (systemPrompt) {
247
+ logger.debug(' Using Agent System Prompt\n', systemPrompt);
248
+ }
249
+ if (systemPrompt) {
250
+ messages = [{ role: 'system', content: systemPrompt }];
251
+ }
252
+ }
253
+
254
+ if (useContextWindow) {
255
+ const cachedMessages = await agent.agentRuntime.llmCache.get('messages', 'json');
256
+ try {
257
+ const messagesJSON = typeof cachedMessages === 'string' ? JSON.parse(cachedMessages) : cachedMessages;
258
+ //const contextWindow = messagesJSON.filter((message) => message.role !== 'user');
259
+
260
+ const convMessages = await llmInference.getContextWindow(systemPrompt, messagesJSON, maxContextWindowLength, maxTokens);
261
+
262
+ if (convMessages.length > 0) {
263
+ logger.debug(` Using Agent Context Window : ${convMessages.length - 1} messages will be used`);
264
+ }
265
+
266
+ messages = [...convMessages];
267
+ //messages.push(...contextWindowJSON);
268
+ } catch (error) {
269
+ logger.warn('Error on parsing context window: ', error);
270
+ console.warn(cachedMessages);
271
+ }
272
+ }
273
+
274
+ if (messages[messages.length - 1]?.role == 'user') {
275
+ messages[messages.length - 1].content = _prompt;
276
+ } else {
277
+ messages.push({ role: 'user', content: _prompt });
278
+ }
279
+ let finishReason = 'stop';
280
+ const contentPromise = new Promise(async (resolve, reject) => {
281
+ let _content = '';
282
+ let eventEmitter;
283
+
284
+ eventEmitter = await llmInference
285
+ .promptStream({
286
+ contextWindow: messages,
287
+ files,
288
+ params: {
289
+ ...config.data,
290
+ agentId: agent.id,
291
+ },
292
+ })
293
+ .catch((error) => {
294
+ console.error('Error on promptStream: ', error);
295
+ reject(error);
296
+ });
297
+
298
+ eventEmitter.on('content', (content) => {
299
+ if (passThrough) {
300
+ if (typeof agent.callback === 'function') {
301
+ agent.callback({ content });
302
+ }
303
+ agent.sse.send('llm/passthrough/content', content.replace(/\n/g, '\\n'));
304
+ }
305
+ _content += content;
306
+ });
307
+
308
+ eventEmitter.on('thinking', (thinking) => {
309
+ if (passThrough) {
310
+ if (typeof agent.callback === 'function') {
311
+ agent.callback({ thinking });
312
+ }
313
+ agent.sse.send('llm/passthrough/thinking', thinking.replace(/\n/g, '\\n'));
314
+ }
315
+ });
316
+ eventEmitter.on('end', () => {
317
+ if (passThrough) {
318
+ if (typeof agent.callback === 'function') {
319
+ agent.callback({ content: '\n' });
320
+ }
321
+ agent.sse.send('llm/passthrough/content', '\\n');
322
+ }
323
+ resolve(_content);
324
+ });
325
+ eventEmitter.on('interrupted', (reason) => {
326
+ finishReason = reason || 'stop';
327
+ });
328
+
329
+ eventEmitter.on('error', (error) => {
330
+ reject(error);
331
+ });
332
+ });
333
+ response = await contentPromise.catch((error) => {
334
+ return { error: error.message || error };
335
+ });
336
+ // // If the model stopped before completing the response, this is usually due to output token limit reached.
337
+ if (finishReason !== 'stop') {
338
+ return {
339
+ Reply: response,
340
+ _error: 'The model stopped before completing the response, this is usually due to output token limit reached.',
341
+ _debug: logger.output,
342
+ };
343
+ }
344
+
345
+ // in case we have the response but it's empty string, undefined or null
346
+ if (!response) {
347
+ return { _error: ' LLM Error = Empty Response!', _debug: logger.output };
348
+ }
349
+
350
+ if (response?.error) {
351
+ const error = response?.error + ' ' + (response?.details || '');
352
+ logger.error(` LLM Error=`, error);
353
+
354
+ return { Output: response?.data, _error: error, _debug: logger.output };
355
+ }
356
+
357
+ const Reply = llmInference.connector.postProcess(response);
358
+ if (Reply.error) {
359
+ logger.error(` LLM Error=`, Reply.error);
360
+ return { _error: Reply.error, _debug: logger.output };
361
+ }
362
+
363
+ logger.debug(' Reply \n', Reply);
364
+
365
+ const result = { Reply };
366
+
367
+ result['_debug'] = logger.output;
368
+
369
+ return result;
370
+ } catch (error) {
371
+ return { _error: error.message, _debug: logger.output };
372
+ }
373
+ }
374
+ }
375
+
376
+ function parseFiles(input: any, config: any) {
377
+ const mediaTypes = ['Image', 'Audio', 'Video', 'Binary'];
378
+
379
+ // Parse media inputs from config
380
+ const inputFiles =
381
+ config.inputs
382
+ ?.filter((_input) => mediaTypes.includes(_input.type))
383
+ ?.flatMap((_input) => {
384
+ const value = input[_input.name];
385
+
386
+ if (Array.isArray(value)) {
387
+ return value.map((item) => TemplateString(item).parseRaw(input).result);
388
+ } else {
389
+ return TemplateString(value).parseRaw(input).result;
390
+ }
391
+ })
392
+ ?.filter((file) => file) || [];
393
+
394
+ return inputFiles;
395
+ }