@smythos/sre 1.5.0 → 1.5.2
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.
- package/CHANGELOG +62 -0
- package/LICENSE +18 -0
- package/package.json +127 -115
- package/src/Components/APICall/APICall.class.ts +155 -0
- package/src/Components/APICall/AccessTokenManager.ts +130 -0
- package/src/Components/APICall/ArrayBufferResponse.helper.ts +58 -0
- package/src/Components/APICall/OAuth.helper.ts +294 -0
- package/src/Components/APICall/mimeTypeCategories.ts +46 -0
- package/src/Components/APICall/parseData.ts +167 -0
- package/src/Components/APICall/parseHeaders.ts +41 -0
- package/src/Components/APICall/parseProxy.ts +68 -0
- package/src/Components/APICall/parseUrl.ts +91 -0
- package/src/Components/APIEndpoint.class.ts +234 -0
- package/src/Components/APIOutput.class.ts +58 -0
- package/src/Components/AgentPlugin.class.ts +102 -0
- package/src/Components/Async.class.ts +155 -0
- package/src/Components/Await.class.ts +90 -0
- package/src/Components/Classifier.class.ts +158 -0
- package/src/Components/Component.class.ts +94 -0
- package/src/Components/ComponentHost.class.ts +38 -0
- package/src/Components/DataSourceCleaner.class.ts +92 -0
- package/src/Components/DataSourceIndexer.class.ts +181 -0
- package/src/Components/DataSourceLookup.class.ts +141 -0
- package/src/Components/FEncDec.class.ts +29 -0
- package/src/Components/FHash.class.ts +33 -0
- package/src/Components/FSign.class.ts +80 -0
- package/src/Components/FSleep.class.ts +25 -0
- package/src/Components/FTimestamp.class.ts +25 -0
- package/src/Components/FileStore.class.ts +75 -0
- package/src/Components/ForEach.class.ts +97 -0
- package/src/Components/GPTPlugin.class.ts +70 -0
- package/src/Components/GenAILLM.class.ts +395 -0
- package/src/Components/HuggingFace.class.ts +314 -0
- package/src/Components/Image/imageSettings.config.ts +70 -0
- package/src/Components/ImageGenerator.class.ts +407 -0
- package/src/Components/JSONFilter.class.ts +54 -0
- package/src/Components/LLMAssistant.class.ts +213 -0
- package/src/Components/LogicAND.class.ts +28 -0
- package/src/Components/LogicAtLeast.class.ts +85 -0
- package/src/Components/LogicAtMost.class.ts +86 -0
- package/src/Components/LogicOR.class.ts +29 -0
- package/src/Components/LogicXOR.class.ts +34 -0
- package/src/Components/MCPClient.class.ts +112 -0
- package/src/Components/PromptGenerator.class.ts +122 -0
- package/src/Components/ScrapflyWebScrape.class.ts +159 -0
- package/src/Components/TavilyWebSearch.class.ts +98 -0
- package/src/Components/index.ts +77 -0
- package/src/Core/AgentProcess.helper.ts +240 -0
- package/src/Core/Connector.class.ts +123 -0
- package/src/Core/ConnectorsService.ts +192 -0
- package/src/Core/DummyConnector.ts +49 -0
- package/src/Core/HookService.ts +105 -0
- package/src/Core/SmythRuntime.class.ts +292 -0
- package/src/Core/SystemEvents.ts +15 -0
- package/src/Core/boot.ts +55 -0
- package/src/config.ts +15 -0
- package/src/constants.ts +125 -0
- package/src/data/hugging-face.params.json +580 -0
- package/src/helpers/BinaryInput.helper.ts +324 -0
- package/src/helpers/Conversation.helper.ts +1094 -0
- package/src/helpers/JsonContent.helper.ts +97 -0
- package/src/helpers/LocalCache.helper.ts +97 -0
- package/src/helpers/Log.helper.ts +234 -0
- package/src/helpers/OpenApiParser.helper.ts +150 -0
- package/src/helpers/S3Cache.helper.ts +129 -0
- package/src/helpers/SmythURI.helper.ts +5 -0
- package/src/helpers/TemplateString.helper.ts +243 -0
- package/src/helpers/TypeChecker.helper.ts +329 -0
- package/src/index.ts +179 -0
- package/src/index.ts.bak +179 -0
- package/src/subsystems/AgentManager/Agent.class.ts +1108 -0
- package/src/subsystems/AgentManager/Agent.helper.ts +3 -0
- package/src/subsystems/AgentManager/AgentData.service/AgentDataConnector.ts +230 -0
- package/src/subsystems/AgentManager/AgentData.service/connectors/CLIAgentDataConnector.class.ts +66 -0
- package/src/subsystems/AgentManager/AgentData.service/connectors/LocalAgentDataConnector.class.ts +142 -0
- package/src/subsystems/AgentManager/AgentData.service/connectors/NullAgentData.class.ts +39 -0
- package/src/subsystems/AgentManager/AgentData.service/index.ts +18 -0
- package/src/subsystems/AgentManager/AgentLogger.class.ts +297 -0
- package/src/subsystems/AgentManager/AgentRequest.class.ts +51 -0
- package/src/subsystems/AgentManager/AgentRuntime.class.ts +559 -0
- package/src/subsystems/AgentManager/AgentSSE.class.ts +101 -0
- package/src/subsystems/AgentManager/AgentSettings.class.ts +52 -0
- package/src/subsystems/AgentManager/Component.service/ComponentConnector.ts +32 -0
- package/src/subsystems/AgentManager/Component.service/connectors/LocalComponentConnector.class.ts +59 -0
- package/src/subsystems/AgentManager/Component.service/index.ts +11 -0
- package/src/subsystems/AgentManager/EmbodimentSettings.class.ts +47 -0
- package/src/subsystems/AgentManager/ForkedAgent.class.ts +153 -0
- package/src/subsystems/AgentManager/OSResourceMonitor.ts +77 -0
- package/src/subsystems/ComputeManager/Code.service/CodeConnector.ts +99 -0
- package/src/subsystems/ComputeManager/Code.service/connectors/AWSLambdaCode.class.ts +63 -0
- package/src/subsystems/ComputeManager/Code.service/index.ts +11 -0
- package/src/subsystems/IO/CLI.service/CLIConnector.ts +47 -0
- package/src/subsystems/IO/CLI.service/index.ts +9 -0
- package/src/subsystems/IO/Log.service/LogConnector.ts +32 -0
- package/src/subsystems/IO/Log.service/connectors/ConsoleLog.class.ts +28 -0
- package/src/subsystems/IO/Log.service/index.ts +13 -0
- package/src/subsystems/IO/NKV.service/NKVConnector.ts +41 -0
- package/src/subsystems/IO/NKV.service/connectors/NKVRAM.class.ts +204 -0
- package/src/subsystems/IO/NKV.service/connectors/NKVRedis.class.ts +182 -0
- package/src/subsystems/IO/NKV.service/index.ts +12 -0
- package/src/subsystems/IO/Router.service/RouterConnector.ts +21 -0
- package/src/subsystems/IO/Router.service/connectors/ExpressRouter.class.ts +48 -0
- package/src/subsystems/IO/Router.service/connectors/NullRouter.class.ts +40 -0
- package/src/subsystems/IO/Router.service/index.ts +11 -0
- package/src/subsystems/IO/Storage.service/SmythFS.class.ts +472 -0
- package/src/subsystems/IO/Storage.service/StorageConnector.ts +66 -0
- package/src/subsystems/IO/Storage.service/connectors/LocalStorage.class.ts +305 -0
- package/src/subsystems/IO/Storage.service/connectors/S3Storage.class.ts +418 -0
- package/src/subsystems/IO/Storage.service/index.ts +13 -0
- package/src/subsystems/IO/VectorDB.service/VectorDBConnector.ts +108 -0
- package/src/subsystems/IO/VectorDB.service/connectors/MilvusVectorDB.class.ts +450 -0
- package/src/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.ts +373 -0
- package/src/subsystems/IO/VectorDB.service/connectors/RAMVecrtorDB.class.ts +420 -0
- package/src/subsystems/IO/VectorDB.service/embed/BaseEmbedding.ts +106 -0
- package/src/subsystems/IO/VectorDB.service/embed/OpenAIEmbedding.ts +109 -0
- package/src/subsystems/IO/VectorDB.service/embed/index.ts +21 -0
- package/src/subsystems/IO/VectorDB.service/index.ts +14 -0
- package/src/subsystems/LLMManager/LLM.helper.ts +221 -0
- package/src/subsystems/LLMManager/LLM.inference.ts +335 -0
- package/src/subsystems/LLMManager/LLM.service/LLMConnector.ts +374 -0
- package/src/subsystems/LLMManager/LLM.service/LLMCredentials.helper.ts +145 -0
- package/src/subsystems/LLMManager/LLM.service/connectors/Anthropic.class.ts +632 -0
- package/src/subsystems/LLMManager/LLM.service/connectors/Bedrock.class.ts +405 -0
- package/src/subsystems/LLMManager/LLM.service/connectors/Echo.class.ts +81 -0
- package/src/subsystems/LLMManager/LLM.service/connectors/GoogleAI.class.ts +689 -0
- package/src/subsystems/LLMManager/LLM.service/connectors/Groq.class.ts +257 -0
- package/src/subsystems/LLMManager/LLM.service/connectors/OpenAI.class.ts +848 -0
- package/src/subsystems/LLMManager/LLM.service/connectors/Perplexity.class.ts +255 -0
- package/src/subsystems/LLMManager/LLM.service/connectors/VertexAI.class.ts +193 -0
- package/src/subsystems/LLMManager/LLM.service/index.ts +43 -0
- package/src/subsystems/LLMManager/ModelsProvider.service/ModelsProviderConnector.ts +281 -0
- package/src/subsystems/LLMManager/ModelsProvider.service/connectors/SmythModelsProvider.class.ts +229 -0
- package/src/subsystems/LLMManager/ModelsProvider.service/index.ts +11 -0
- package/src/subsystems/LLMManager/custom-models.ts +854 -0
- package/src/subsystems/LLMManager/models.ts +2539 -0
- package/src/subsystems/LLMManager/paramMappings.ts +69 -0
- package/src/subsystems/MemoryManager/Cache.service/CacheConnector.ts +86 -0
- package/src/subsystems/MemoryManager/Cache.service/connectors/LocalStorageCache.class.ts +297 -0
- package/src/subsystems/MemoryManager/Cache.service/connectors/RAMCache.class.ts +201 -0
- package/src/subsystems/MemoryManager/Cache.service/connectors/RedisCache.class.ts +252 -0
- package/src/subsystems/MemoryManager/Cache.service/connectors/S3Cache.class.ts +373 -0
- package/src/subsystems/MemoryManager/Cache.service/index.ts +15 -0
- package/src/subsystems/MemoryManager/LLMCache.ts +72 -0
- package/src/subsystems/MemoryManager/LLMContext.ts +125 -0
- package/src/subsystems/MemoryManager/RuntimeContext.ts +249 -0
- package/src/subsystems/Security/AccessControl/ACL.class.ts +208 -0
- package/src/subsystems/Security/AccessControl/AccessCandidate.class.ts +76 -0
- package/src/subsystems/Security/AccessControl/AccessRequest.class.ts +52 -0
- package/src/subsystems/Security/Account.service/AccountConnector.ts +41 -0
- package/src/subsystems/Security/Account.service/connectors/AWSAccount.class.ts +76 -0
- package/src/subsystems/Security/Account.service/connectors/DummyAccount.class.ts +130 -0
- package/src/subsystems/Security/Account.service/connectors/JSONFileAccount.class.ts +159 -0
- package/src/subsystems/Security/Account.service/index.ts +14 -0
- package/src/subsystems/Security/Credentials.helper.ts +62 -0
- package/src/subsystems/Security/ManagedVault.service/ManagedVaultConnector.ts +34 -0
- package/src/subsystems/Security/ManagedVault.service/connectors/NullManagedVault.class.ts +57 -0
- package/src/subsystems/Security/ManagedVault.service/connectors/SecretManagerManagedVault.ts +154 -0
- package/src/subsystems/Security/ManagedVault.service/index.ts +12 -0
- package/src/subsystems/Security/SecureConnector.class.ts +110 -0
- package/src/subsystems/Security/Vault.service/Vault.helper.ts +30 -0
- package/src/subsystems/Security/Vault.service/VaultConnector.ts +26 -0
- package/src/subsystems/Security/Vault.service/connectors/HashicorpVault.class.ts +46 -0
- package/src/subsystems/Security/Vault.service/connectors/JSONFileVault.class.ts +166 -0
- package/src/subsystems/Security/Vault.service/connectors/NullVault.class.ts +54 -0
- package/src/subsystems/Security/Vault.service/connectors/SecretsManager.class.ts +140 -0
- package/src/subsystems/Security/Vault.service/index.ts +12 -0
- package/src/types/ACL.types.ts +104 -0
- package/src/types/AWS.types.ts +9 -0
- package/src/types/Agent.types.ts +61 -0
- package/src/types/AgentLogger.types.ts +17 -0
- package/src/types/Cache.types.ts +1 -0
- package/src/types/Common.types.ts +3 -0
- package/src/types/LLM.types.ts +419 -0
- package/src/types/Redis.types.ts +8 -0
- package/src/types/SRE.types.ts +64 -0
- package/src/types/Security.types.ts +18 -0
- package/src/types/Storage.types.ts +5 -0
- package/src/types/VectorDB.types.ts +78 -0
- package/src/utils/base64.utils.ts +275 -0
- package/src/utils/cli.utils.ts +68 -0
- package/src/utils/data.utils.ts +263 -0
- package/src/utils/date-time.utils.ts +22 -0
- package/src/utils/general.utils.ts +238 -0
- package/src/utils/index.ts +12 -0
- package/src/utils/numbers.utils.ts +13 -0
- package/src/utils/oauth.utils.ts +35 -0
- package/src/utils/string.utils.ts +414 -0
- package/src/utils/url.utils.ts +19 -0
- package/src/utils/validation.utils.ts +74 -0
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BedrockRuntimeClient,
|
|
3
|
+
ConverseCommand,
|
|
4
|
+
ConverseCommandInput,
|
|
5
|
+
ConverseStreamCommand,
|
|
6
|
+
ConverseStreamCommandOutput,
|
|
7
|
+
TokenUsage,
|
|
8
|
+
ConverseCommandOutput,
|
|
9
|
+
} from '@aws-sdk/client-bedrock-runtime';
|
|
10
|
+
import EventEmitter from 'events';
|
|
11
|
+
|
|
12
|
+
import { BUILT_IN_MODEL_PREFIX } from '@sre/constants';
|
|
13
|
+
import {
|
|
14
|
+
TLLMParams,
|
|
15
|
+
ToolData,
|
|
16
|
+
TLLMMessageBlock,
|
|
17
|
+
TLLMToolResultMessageBlock,
|
|
18
|
+
TLLMMessageRole,
|
|
19
|
+
APIKeySource,
|
|
20
|
+
TLLMEvent,
|
|
21
|
+
BedrockCredentials,
|
|
22
|
+
ILLMRequestFuncParams,
|
|
23
|
+
TLLMChatResponse,
|
|
24
|
+
TLLMConnectorParams,
|
|
25
|
+
ILLMRequestContext,
|
|
26
|
+
TCustomLLMModel,
|
|
27
|
+
} from '@sre/types/LLM.types';
|
|
28
|
+
import { LLMHelper } from '@sre/LLMManager/LLM.helper';
|
|
29
|
+
import { isJSONString } from '@sre/utils/general.utils';
|
|
30
|
+
|
|
31
|
+
import { LLMConnector } from '../LLMConnector';
|
|
32
|
+
import { JSONContent } from '@sre/helpers/JsonContent.helper';
|
|
33
|
+
import { SystemEvents } from '@sre/Core/SystemEvents';
|
|
34
|
+
|
|
35
|
+
// TODO [Forhad]: Need to adjust some type definitions
|
|
36
|
+
|
|
37
|
+
export class BedrockConnector extends LLMConnector {
|
|
38
|
+
public name = 'LLM:Bedrock';
|
|
39
|
+
|
|
40
|
+
private async getClient(params: ILLMRequestContext): Promise<BedrockRuntimeClient> {
|
|
41
|
+
const credentials = params.credentials as BedrockCredentials;
|
|
42
|
+
const region = (params.modelInfo as TCustomLLMModel).settings.region;
|
|
43
|
+
|
|
44
|
+
if (!(Object.keys(credentials).length >= 2)) throw new Error('Access key ID and secret access key are required for Bedrock');
|
|
45
|
+
|
|
46
|
+
return new BedrockRuntimeClient({
|
|
47
|
+
region: region,
|
|
48
|
+
credentials,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
protected async request({ acRequest, body, context }: ILLMRequestFuncParams): Promise<TLLMChatResponse> {
|
|
53
|
+
try {
|
|
54
|
+
const bedrock = await this.getClient(context);
|
|
55
|
+
const command = new ConverseCommand(body);
|
|
56
|
+
const response: ConverseCommandOutput = await bedrock.send(command);
|
|
57
|
+
|
|
58
|
+
const usage = response.usage;
|
|
59
|
+
this.reportUsage(usage as any, {
|
|
60
|
+
modelEntryName: context.modelEntryName,
|
|
61
|
+
keySource: context.isUserKey ? APIKeySource.User : APIKeySource.Smyth,
|
|
62
|
+
agentId: context.agentId,
|
|
63
|
+
teamId: context.teamId,
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const message = response.output?.message;
|
|
67
|
+
const finishReason = response.stopReason;
|
|
68
|
+
|
|
69
|
+
let toolsData: ToolData[] = [];
|
|
70
|
+
let useTool = false;
|
|
71
|
+
|
|
72
|
+
if (finishReason === 'tool_use') {
|
|
73
|
+
const toolUseBlocks = message?.content?.filter((block) => block?.toolUse) || [];
|
|
74
|
+
|
|
75
|
+
toolsData = toolUseBlocks.map((block, index) => ({
|
|
76
|
+
index,
|
|
77
|
+
id: block.toolUse?.toolUseId as string,
|
|
78
|
+
type: 'function', // We call API only when the tool type is 'function' in src/helpers/Conversation.helper.ts`. Even though Claude returns the type as 'tool_use', it should be interpreted as 'function'.,
|
|
79
|
+
name: _deserializeToolName(block.toolUse?.name as string),
|
|
80
|
+
arguments: block.toolUse?.input as Record<string, any>,
|
|
81
|
+
role: 'tool',
|
|
82
|
+
}));
|
|
83
|
+
useTool = true;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
content: Array.isArray(message?.content) ? message?.content?.[0]?.text || '' : message?.content || '',
|
|
88
|
+
finishReason,
|
|
89
|
+
useTool,
|
|
90
|
+
toolsData,
|
|
91
|
+
message: message as any,
|
|
92
|
+
usage,
|
|
93
|
+
};
|
|
94
|
+
} catch (error: any) {
|
|
95
|
+
throw error?.error || error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
protected async streamRequest({ acRequest, body, context }: ILLMRequestFuncParams): Promise<EventEmitter> {
|
|
100
|
+
const emitter = new EventEmitter();
|
|
101
|
+
|
|
102
|
+
try {
|
|
103
|
+
const bedrock = await this.getClient(context);
|
|
104
|
+
const command = new ConverseStreamCommand(body);
|
|
105
|
+
const response: ConverseStreamCommandOutput = await bedrock.send(command);
|
|
106
|
+
const stream = response.stream;
|
|
107
|
+
|
|
108
|
+
if (stream) {
|
|
109
|
+
(async () => {
|
|
110
|
+
let currentMessage = {
|
|
111
|
+
role: '',
|
|
112
|
+
content: '',
|
|
113
|
+
toolCalls: [] as any[],
|
|
114
|
+
currentToolCall: null as any,
|
|
115
|
+
currentToolInput: '' as string,
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
for await (const chunk of stream) {
|
|
119
|
+
// Handle message start
|
|
120
|
+
if (chunk.messageStart) {
|
|
121
|
+
currentMessage.role = chunk.messageStart.role || '';
|
|
122
|
+
emitter.emit('data', { role: currentMessage.role });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Handle content deltas
|
|
126
|
+
if (chunk.contentBlockDelta?.delta?.text) {
|
|
127
|
+
currentMessage.content += chunk.contentBlockDelta.delta.text;
|
|
128
|
+
emitter.emit('data', chunk.contentBlockDelta.delta.text);
|
|
129
|
+
emitter.emit('content', chunk.contentBlockDelta.delta.text, currentMessage.role);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Handle tool use start
|
|
133
|
+
if (chunk.contentBlockStart?.start?.toolUse) {
|
|
134
|
+
const toolUse = chunk.contentBlockStart.start.toolUse;
|
|
135
|
+
if (toolUse.toolUseId && toolUse.name) {
|
|
136
|
+
currentMessage.currentToolCall = {
|
|
137
|
+
index: currentMessage.toolCalls.length,
|
|
138
|
+
id: toolUse.toolUseId,
|
|
139
|
+
type: 'function',
|
|
140
|
+
name: _deserializeToolName(toolUse.name),
|
|
141
|
+
arguments: '',
|
|
142
|
+
role: 'tool',
|
|
143
|
+
};
|
|
144
|
+
currentMessage.currentToolInput = '';
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Handle tool use input deltas
|
|
149
|
+
if (chunk.contentBlockDelta?.delta?.toolUse?.input && currentMessage.currentToolCall) {
|
|
150
|
+
currentMessage.currentToolInput += chunk.contentBlockDelta.delta.toolUse.input;
|
|
151
|
+
currentMessage.currentToolCall.arguments = currentMessage.currentToolInput;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Handle tool use block completion
|
|
155
|
+
if (chunk.contentBlockStop && currentMessage.currentToolCall) {
|
|
156
|
+
// Parse JSON arguments if possible
|
|
157
|
+
if (
|
|
158
|
+
typeof currentMessage.currentToolCall.arguments === 'string' &&
|
|
159
|
+
isJSONString(currentMessage.currentToolCall.arguments)
|
|
160
|
+
) {
|
|
161
|
+
currentMessage.currentToolCall.arguments = JSON.parse(currentMessage.currentToolCall.arguments);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
currentMessage.toolCalls.push(currentMessage.currentToolCall);
|
|
165
|
+
currentMessage.currentToolCall = null;
|
|
166
|
+
currentMessage.currentToolInput = '';
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Handle message completion
|
|
170
|
+
if (chunk.messageStop) {
|
|
171
|
+
if (currentMessage.toolCalls.length > 0) {
|
|
172
|
+
emitter.emit(TLLMEvent.ToolInfo, currentMessage.toolCalls);
|
|
173
|
+
}
|
|
174
|
+
emitter.emit(TLLMEvent.End, currentMessage.toolCalls);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (chunk?.metadata?.usage) {
|
|
178
|
+
const usage = chunk.metadata.usage;
|
|
179
|
+
this.reportUsage(usage as any, {
|
|
180
|
+
modelEntryName: context.modelEntryName,
|
|
181
|
+
keySource: context.isUserKey ? APIKeySource.User : APIKeySource.Smyth,
|
|
182
|
+
agentId: context.agentId,
|
|
183
|
+
teamId: context.teamId,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
})();
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return emitter;
|
|
191
|
+
} catch (error: unknown) {
|
|
192
|
+
const typedError = error as Error;
|
|
193
|
+
emitter.emit(TLLMEvent.Error, typedError?.['error'] || typedError);
|
|
194
|
+
return emitter;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
protected async webSearchRequest({ acRequest, body, context }: ILLMRequestFuncParams): Promise<EventEmitter> {
|
|
199
|
+
throw new Error('Web search is not supported for Bedrock');
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
protected async reqBodyAdapter(params: TLLMParams): Promise<ConverseCommandInput> {
|
|
203
|
+
const customModelInfo = params.modelInfo;
|
|
204
|
+
|
|
205
|
+
let systemPrompt;
|
|
206
|
+
let messages = params?.messages || [];
|
|
207
|
+
|
|
208
|
+
const { systemMessage, otherMessages } = LLMHelper.separateSystemMessages(messages);
|
|
209
|
+
|
|
210
|
+
if ('content' in systemMessage) {
|
|
211
|
+
systemPrompt = typeof systemMessage?.content === 'string' ? [{ text: systemMessage?.content }] : systemMessage?.content;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
messages = otherMessages;
|
|
215
|
+
|
|
216
|
+
const body: ConverseCommandInput = {
|
|
217
|
+
modelId: customModelInfo.settings?.customModel || customModelInfo.settings?.foundationModel,
|
|
218
|
+
messages,
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
if (systemPrompt) {
|
|
222
|
+
body.system = systemPrompt;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
if (params?.toolsConfig?.tools?.length > 0) {
|
|
226
|
+
body.toolConfig = {
|
|
227
|
+
tools: params?.toolsConfig?.tools as any,
|
|
228
|
+
...(params?.toolsConfig?.tool_choice && { toolChoice: params?.toolsConfig?.tool_choice as any }),
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return body;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
protected reportUsage(
|
|
236
|
+
usage: TokenUsage & { cacheReadInputTokenCount: number; cacheWriteInputTokenCount: number },
|
|
237
|
+
metadata: { modelEntryName: string; keySource: APIKeySource; agentId: string; teamId: string }
|
|
238
|
+
) {
|
|
239
|
+
// SmythOS (built-in) models have a prefix, so we need to remove it to get the model name
|
|
240
|
+
const modelName = metadata.modelEntryName.replace(BUILT_IN_MODEL_PREFIX, '');
|
|
241
|
+
|
|
242
|
+
const usageData = {
|
|
243
|
+
sourceId: `llm:${modelName}`,
|
|
244
|
+
input_tokens: usage.inputTokens,
|
|
245
|
+
output_tokens: usage.outputTokens,
|
|
246
|
+
input_tokens_cache_write: usage.cacheWriteInputTokenCount || 0,
|
|
247
|
+
input_tokens_cache_read: usage.cacheReadInputTokenCount || 0,
|
|
248
|
+
keySource: metadata.keySource,
|
|
249
|
+
agentId: metadata.agentId,
|
|
250
|
+
teamId: metadata.teamId,
|
|
251
|
+
};
|
|
252
|
+
SystemEvents.emit('USAGE:LLM', usageData);
|
|
253
|
+
|
|
254
|
+
return usageData;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
public formatToolsConfig({ type = 'function', toolDefinitions, toolChoice = 'auto' }) {
|
|
258
|
+
let tools: any[] = [];
|
|
259
|
+
|
|
260
|
+
if (type === 'function') {
|
|
261
|
+
tools = toolDefinitions.map((tool) => {
|
|
262
|
+
const { name, description, properties, requiredFields } = tool;
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
toolSpec: {
|
|
266
|
+
name: _serializeToolName(name),
|
|
267
|
+
description,
|
|
268
|
+
inputSchema: {
|
|
269
|
+
json: {
|
|
270
|
+
type: 'object',
|
|
271
|
+
properties,
|
|
272
|
+
required: requiredFields,
|
|
273
|
+
},
|
|
274
|
+
},
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return tools?.length > 0 ? { tools, toolChoice: toolChoice || 'auto' } : {};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
public transformToolMessageBlocks({
|
|
284
|
+
messageBlock,
|
|
285
|
+
toolsData,
|
|
286
|
+
}: {
|
|
287
|
+
messageBlock: TLLMMessageBlock;
|
|
288
|
+
toolsData: ToolData[];
|
|
289
|
+
}): TLLMToolResultMessageBlock[] {
|
|
290
|
+
const messageBlocks: any[] = [];
|
|
291
|
+
|
|
292
|
+
if (messageBlock) {
|
|
293
|
+
const content: any[] = []; // TODO: set proper type for content
|
|
294
|
+
|
|
295
|
+
if (typeof messageBlock.content === 'string') {
|
|
296
|
+
content.push({ text: messageBlock.content });
|
|
297
|
+
} else if (Array.isArray(messageBlock.content)) {
|
|
298
|
+
content.push(...messageBlock.content);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (messageBlock.tool_calls?.length) {
|
|
302
|
+
messageBlock.tool_calls.forEach((toolCall: Record<string, any>) => {
|
|
303
|
+
const args = toolCall?.function?.arguments;
|
|
304
|
+
content.push({
|
|
305
|
+
toolUse: {
|
|
306
|
+
toolUseId: toolCall.id,
|
|
307
|
+
name: _serializeToolName(toolCall?.function?.name),
|
|
308
|
+
input: typeof args === 'string' ? JSONContent(args || '{}').tryParse() : args || {},
|
|
309
|
+
},
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
messageBlocks.push({
|
|
315
|
+
role: messageBlock?.role,
|
|
316
|
+
content,
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Add tool results as user message
|
|
321
|
+
if (toolsData?.length) {
|
|
322
|
+
const toolResultsContent = toolsData
|
|
323
|
+
.filter((tool) => tool.id && (tool.result || tool.error))
|
|
324
|
+
.map((tool) => {
|
|
325
|
+
let content;
|
|
326
|
+
|
|
327
|
+
// * Note: We also have two other types of results: image and document. - https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseStreamCommand/
|
|
328
|
+
if (typeof tool?.result === 'string') {
|
|
329
|
+
content = [{ text: tool.result as string }];
|
|
330
|
+
} else if (typeof tool?.result === 'object') {
|
|
331
|
+
content = [{ json: tool.result }];
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
return {
|
|
335
|
+
toolResult: {
|
|
336
|
+
toolUseId: tool.id,
|
|
337
|
+
content: content,
|
|
338
|
+
...(tool.error && { status: 'error' }),
|
|
339
|
+
},
|
|
340
|
+
};
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
if (toolResultsContent.length > 0) {
|
|
344
|
+
messageBlocks.push({
|
|
345
|
+
role: TLLMMessageRole.User,
|
|
346
|
+
content: toolResultsContent,
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return messageBlocks;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
public getConsistentMessages(messages: TLLMMessageBlock[]): TLLMMessageBlock[] {
|
|
355
|
+
const _messages = LLMHelper.removeDuplicateUserMessages(messages);
|
|
356
|
+
|
|
357
|
+
return _messages.map((message) => {
|
|
358
|
+
let textBlock = [];
|
|
359
|
+
|
|
360
|
+
if (message?.parts) {
|
|
361
|
+
// empty text causes error in Bedrock, so we add a placeholder
|
|
362
|
+
textBlock = message.parts.map((part) => {
|
|
363
|
+
if ('text' in part) {
|
|
364
|
+
return { ...part, text: part.text || '...' };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
return { ...part };
|
|
368
|
+
});
|
|
369
|
+
} else if (message?.content) {
|
|
370
|
+
textBlock = Array.isArray(message.content)
|
|
371
|
+
? message.content.map((part) => {
|
|
372
|
+
if ('text' in part) {
|
|
373
|
+
return { ...part, text: part.text || '...' };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
return { ...part };
|
|
377
|
+
})
|
|
378
|
+
: [{ text: (message?.content as string) || '...' }]; // empty text causes error in Bedrock, so we add a placeholder
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
return {
|
|
382
|
+
role: message.role,
|
|
383
|
+
content: textBlock,
|
|
384
|
+
};
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Serializes a name by converting dashes to double underscores for Bedrock compatibility
|
|
391
|
+
* @param name - The original name containing dashes
|
|
392
|
+
* @returns The serialized name with dashes replaced by double underscores
|
|
393
|
+
*/
|
|
394
|
+
function _serializeToolName(name: string): string {
|
|
395
|
+
return name?.replace(/-/g, '__');
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Deserializes a Bedrock Tool name by converting double underscores back to dashes
|
|
400
|
+
* @param name - The serialized name containing double underscores
|
|
401
|
+
* @returns The deserialized name with double underscores replaced by dashes
|
|
402
|
+
*/
|
|
403
|
+
function _deserializeToolName(name: string): string {
|
|
404
|
+
return name?.replace(/__/g, '-');
|
|
405
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { JSONContent } from '@sre/helpers/JsonContent.helper';
|
|
2
|
+
import { LLMConnector } from '../LLMConnector';
|
|
3
|
+
import EventEmitter from 'events';
|
|
4
|
+
import { APIKeySource, ILLMRequestFuncParams, TLLMChatResponse, TLLMConnectorParams, TLLMParams } from '@sre/types/LLM.types';
|
|
5
|
+
|
|
6
|
+
export class EchoConnector extends LLMConnector {
|
|
7
|
+
public name = 'LLM:Echo';
|
|
8
|
+
|
|
9
|
+
protected async request({ acRequest, body, context }: ILLMRequestFuncParams): Promise<TLLMChatResponse> {
|
|
10
|
+
const content = body?.messages?.[0]?.content; // As Echo model only used in PromptGenerator so we can assume the first message is the user message to echo
|
|
11
|
+
return {
|
|
12
|
+
content,
|
|
13
|
+
finishReason: 'stop',
|
|
14
|
+
useTool: false,
|
|
15
|
+
toolsData: [],
|
|
16
|
+
message: { content, role: 'assistant' },
|
|
17
|
+
usage: {},
|
|
18
|
+
} as TLLMChatResponse;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
protected async streamRequest({ acRequest, body, context }: ILLMRequestFuncParams): Promise<EventEmitter> {
|
|
22
|
+
const emitter = new EventEmitter();
|
|
23
|
+
let content = '';
|
|
24
|
+
|
|
25
|
+
if (Array.isArray(body?.messages)) {
|
|
26
|
+
content = body?.messages?.filter((m) => m.role === 'user').pop()?.content;
|
|
27
|
+
}
|
|
28
|
+
//params?.messages?.[0]?.content;
|
|
29
|
+
|
|
30
|
+
// Process stream asynchronously as we need to return emitter immediately
|
|
31
|
+
(async () => {
|
|
32
|
+
// Simulate streaming by splitting content into chunks
|
|
33
|
+
const chunks = content.split(' ');
|
|
34
|
+
|
|
35
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
36
|
+
// Simulate network delay
|
|
37
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
38
|
+
|
|
39
|
+
const isLastChunk = i === chunks.length - 1;
|
|
40
|
+
// Add space between chunks except for the last one to avoid trailing space in file URLs
|
|
41
|
+
const delta = { content: chunks[i] + (isLastChunk ? '' : ' ') };
|
|
42
|
+
emitter.emit('data', delta);
|
|
43
|
+
emitter.emit('content', delta.content);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Emit end event after all chunks are processed
|
|
47
|
+
setTimeout(() => {
|
|
48
|
+
emitter.emit('end', [], []); // Empty arrays for toolsData and usage_data
|
|
49
|
+
}, 100);
|
|
50
|
+
})();
|
|
51
|
+
|
|
52
|
+
return emitter;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
protected async webSearchRequest({ acRequest, body, context }: ILLMRequestFuncParams): Promise<EventEmitter> {
|
|
56
|
+
throw new Error('Web search is not supported for Echo');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
protected async reqBodyAdapter(params: TLLMParams): Promise<any> {
|
|
60
|
+
return params;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
public enhancePrompt(prompt: string, config: any) {
|
|
64
|
+
//Echo model does not require enhancements, because we are just echoing the prompt as is.
|
|
65
|
+
return prompt;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
public postProcess(response: any) {
|
|
69
|
+
try {
|
|
70
|
+
const result = JSONContent(response).tryFullParse();
|
|
71
|
+
if (result?.error) {
|
|
72
|
+
return response;
|
|
73
|
+
}
|
|
74
|
+
return result;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
return response;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
protected reportUsage(usage: any, metadata: { modelEntryName: string; keySource: APIKeySource; agentId: string; teamId: string }) {}
|
|
81
|
+
}
|