@smythos/sre 1.7.20 → 1.7.40
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/dist/index.js +114 -76
- package/dist/index.js.map +1 -1
- package/dist/types/Components/DataSourceIndexer.class.d.ts +4 -12
- package/dist/types/Components/GenAILLM.class.d.ts +5 -5
- package/dist/types/Components/index.d.ts +3 -3
- package/dist/types/index.d.ts +3 -3
- package/dist/types/subsystems/IO/VectorDB.service/connectors/MilvusVectorDB.class.d.ts +1 -0
- package/dist/types/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.d.ts +11 -4
- package/dist/types/subsystems/IO/VectorDB.service/embed/index.d.ts +5 -0
- package/dist/types/subsystems/LLMManager/ModelsProvider.service/connectors/JSONModelsProvider.class.d.ts +35 -0
- package/dist/types/subsystems/Security/Account.service/AccountConnector.d.ts +2 -2
- package/dist/types/subsystems/Security/Vault.service/connectors/SecretsManager.class.d.ts +2 -3
- package/dist/types/types/VectorDB.types.d.ts +4 -0
- package/dist/types/utils/string.utils.d.ts +1 -0
- package/package.json +3 -3
- package/src/Components/APIEndpoint.class.ts +1 -6
- package/src/Components/Component.class.ts +14 -1
- package/src/Components/DataSourceIndexer.class.ts +148 -34
- package/src/Components/GenAILLM.class.ts +21 -11
- package/src/Components/RAG/DataSourceCleaner.class.ts +178 -0
- package/src/Components/RAG/DataSourceComponent.class.ts +111 -0
- package/src/Components/RAG/DataSourceIndexer.class.ts +254 -0
- package/src/Components/{DataSourceLookup.class.ts → RAG/DataSourceLookup.class.ts} +92 -3
- package/src/Components/ServerlessCode.class.ts +1 -4
- package/src/Components/index.ts +3 -3
- package/src/helpers/S3Cache.helper.ts +2 -1
- package/src/index.ts +212 -212
- package/src/index.ts.bak +212 -212
- package/src/subsystems/IO/NKV.service/connectors/NKVRedis.class.ts +3 -1
- package/src/subsystems/IO/VectorDB.service/connectors/MilvusVectorDB.class.ts +145 -19
- package/src/subsystems/IO/VectorDB.service/connectors/PineconeVectorDB.class.ts +56 -22
- package/src/subsystems/IO/VectorDB.service/embed/GoogleEmbedding.ts +1 -0
- package/src/subsystems/IO/VectorDB.service/embed/OpenAIEmbedding.ts +2 -1
- package/src/subsystems/IO/VectorDB.service/embed/index.ts +18 -0
- package/src/subsystems/LLMManager/LLM.service/connectors/Anthropic.class.ts +35 -10
- package/src/subsystems/LLMManager/LLM.service/connectors/Bedrock.class.ts +12 -4
- package/src/subsystems/LLMManager/LLM.service/connectors/Echo.class.ts +4 -4
- package/src/subsystems/LLMManager/LLM.service/connectors/GoogleAI.class.ts +13 -4
- package/src/subsystems/LLMManager/LLM.service/connectors/Groq.class.ts +17 -5
- package/src/subsystems/LLMManager/LLM.service/connectors/Ollama.class.ts +18 -3
- package/src/subsystems/LLMManager/LLM.service/connectors/Perplexity.class.ts +14 -5
- package/src/subsystems/LLMManager/LLM.service/connectors/VertexAI.class.ts +6 -4
- package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/ChatCompletionsApiInterface.ts +5 -5
- package/src/subsystems/LLMManager/LLM.service/connectors/openai/apiInterfaces/ResponsesApiInterface.ts +8 -3
- package/src/subsystems/LLMManager/LLM.service/connectors/xAI.class.ts +9 -8
- package/src/subsystems/LLMManager/ModelsProvider.service/connectors/JSONModelsProvider.class.ts +92 -1
- package/src/subsystems/ObservabilityManager/Telemetry.service/connectors/OTel/OTel.class.ts +32 -6
- package/src/subsystems/Security/Account.service/AccountConnector.ts +3 -3
- package/src/subsystems/Security/Vault.service/connectors/SecretsManager.class.ts +8 -63
- package/src/types/VectorDB.types.ts +4 -0
- package/src/utils/array.utils.ts +11 -0
- package/src/utils/base64.utils.ts +1 -1
- package/src/utils/string.utils.ts +3 -192
- package/src/Components/DataSourceCleaner.class.ts +0 -92
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { IAgent as Agent } from '@sre/types/Agent.types';
|
|
2
|
+
import { Component } from '../Component.class';
|
|
3
|
+
import { TemplateString } from '@sre/helpers/TemplateString.helper';
|
|
4
|
+
import Joi from 'joi';
|
|
5
|
+
import { validateCharacterSet } from '../../utils';
|
|
6
|
+
import { ConnectorService } from '@sre/Core/ConnectorsService';
|
|
7
|
+
import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
|
|
8
|
+
|
|
9
|
+
import { DataSourceIndexer } from './DataSourceIndexer.class';
|
|
10
|
+
import { DataSourceComponent } from './DataSourceComponent.class';
|
|
11
|
+
import { VectorDBConnector } from '@sre/IO/VectorDB.service/VectorDBConnector';
|
|
12
|
+
|
|
13
|
+
export class DataSourceCleaner extends DataSourceComponent {
|
|
14
|
+
protected configSchema = Joi.object({
|
|
15
|
+
namespaceId: Joi.string().max(50).allow('').label('namespace'),
|
|
16
|
+
id: Joi.string().custom(validateCharacterSet, 'custom validation characterSet').allow('').label('source identifier'),
|
|
17
|
+
version: Joi.string().valid('v1', 'v2').default('v1'),
|
|
18
|
+
});
|
|
19
|
+
constructor() {
|
|
20
|
+
super();
|
|
21
|
+
}
|
|
22
|
+
init() {}
|
|
23
|
+
|
|
24
|
+
async process(input, config, agent: Agent) {
|
|
25
|
+
await super.process(input, config, agent);
|
|
26
|
+
if (!config.data.version || config.data.version === 'v1') {
|
|
27
|
+
return await this.processV1(input, config, agent);
|
|
28
|
+
} else if (config.data.version === 'v2') {
|
|
29
|
+
return await this.processV2(input, config, agent);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async processV1(input, config, agent: Agent) {
|
|
33
|
+
const teamId = agent.teamId;
|
|
34
|
+
const agentId = agent.id;
|
|
35
|
+
let debugOutput = agent.agentRuntime?.debug ? '== Source Indexer Log ==\n' : null;
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
const configSchema = this.validateConfigData(config.data);
|
|
39
|
+
if (configSchema.error) {
|
|
40
|
+
throw new Error(`Config data validation error: ${configSchema.error}\n EXITING...`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const outputs = {};
|
|
44
|
+
for (let con of config.outputs) {
|
|
45
|
+
if (con.default) continue;
|
|
46
|
+
outputs[con.name] = con?.description ? `<${con?.description}>` : '';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const inputSchema = this.validateInput(input);
|
|
50
|
+
if (inputSchema.error) {
|
|
51
|
+
throw new Error(`Input validation error: ${inputSchema.error}\n EXITING...`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// const namespaceId = configSchema.value.namespaceId.split('_')?.slice(1).join('_') || configSchema.value.namespaceId;
|
|
55
|
+
const namespaceId = /^c[a-z0-9]{24}.+$/.test(configSchema.value.namespaceId)
|
|
56
|
+
? configSchema.value.namespaceId.split('_').slice(1).join('_')
|
|
57
|
+
: configSchema.value.namespaceId;
|
|
58
|
+
|
|
59
|
+
let vectorDbConnector = ConnectorService.getVectorDBConnector();
|
|
60
|
+
|
|
61
|
+
let existingnamespace = await vectorDbConnector.requester(AccessCandidate.team(teamId)).namespaceExists(namespaceId);
|
|
62
|
+
if (!existingnamespace) {
|
|
63
|
+
throw new Error(`Namespace ${namespaceId} does not exist`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const providedId = TemplateString(config.data.id).parse(input).result;
|
|
67
|
+
const idRegex = /^[a-zA-Z0-9\-\_\.]+$/;
|
|
68
|
+
if (!idRegex.test(providedId)) {
|
|
69
|
+
throw new Error(`Invalid id. Accepted characters: 'a-z', 'A-Z', '0-9', '-', '_', '.'`);
|
|
70
|
+
}
|
|
71
|
+
debugOutput += `Searching for data source with id: ${providedId}\n`;
|
|
72
|
+
|
|
73
|
+
const dsId = DataSourceIndexer.normalizeDsId(providedId, teamId, namespaceId);
|
|
74
|
+
|
|
75
|
+
await vectorDbConnector.requester(AccessCandidate.team(teamId)).deleteDatasource(namespaceId, dsId);
|
|
76
|
+
|
|
77
|
+
debugOutput += `Deleted data source with id: ${providedId}\n`;
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
_debug: debugOutput,
|
|
81
|
+
Success: true,
|
|
82
|
+
// _error,
|
|
83
|
+
};
|
|
84
|
+
} catch (err: any) {
|
|
85
|
+
debugOutput += `Failed to delete data source: \n Error: ${err?.message}\n`;
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
_debug: debugOutput,
|
|
89
|
+
_error: err?.message || "Couldn't delete data source",
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async processV2(input, config, agent: Agent) {
|
|
95
|
+
const teamId = agent.teamId;
|
|
96
|
+
const agentId = agent.id;
|
|
97
|
+
let debugOutput = agent.agentRuntime?.debug ? '== Source Indexer Log ==\n' : null;
|
|
98
|
+
|
|
99
|
+
try {
|
|
100
|
+
const configSchema = this.validateConfigData(config.data);
|
|
101
|
+
if (configSchema.error) {
|
|
102
|
+
throw new Error(`Config data validation error: ${configSchema.error}\n EXITING...`);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const outputs = {};
|
|
106
|
+
for (let con of config.outputs) {
|
|
107
|
+
if (con.default) continue;
|
|
108
|
+
outputs[con.name] = con?.description ? `<${con?.description}>` : '';
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const inputSchema = this.validateInput(input);
|
|
112
|
+
if (inputSchema.error) {
|
|
113
|
+
throw new Error(`Input validation error: ${inputSchema.error}\n EXITING...`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// const namespaceId = configSchema.value.namespaceId.split('_')?.slice(1).join('_') || configSchema.value.namespaceId;
|
|
117
|
+
const namespaceLabel = /^c[a-z0-9]{24}.+$/.test(configSchema.value.namespaceId)
|
|
118
|
+
? configSchema.value.namespaceId.split('_').slice(1).join('_')
|
|
119
|
+
: configSchema.value.namespaceId;
|
|
120
|
+
const namespaceId = configSchema.value.namespaceId;
|
|
121
|
+
|
|
122
|
+
let vecDbConnector: VectorDBConnector = null;
|
|
123
|
+
try {
|
|
124
|
+
vecDbConnector = await this.resolveVectorDbConnector(namespaceId, teamId);
|
|
125
|
+
} catch (err: any) {
|
|
126
|
+
debugOutput += `Error: ${err?.message || "Couldn't get vector database connector"}\n\n`;
|
|
127
|
+
return {
|
|
128
|
+
_debug: debugOutput,
|
|
129
|
+
_error: err?.message || "Couldn't get vector database connector",
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// let existingnamespace = await vecDbConnector.requester(AccessCandidate.team(teamId)).namespaceExists(namespaceId);
|
|
134
|
+
// if (!existingnamespace) {
|
|
135
|
+
// throw new Error(`Namespace ${namespaceId} does not exist`);
|
|
136
|
+
// }
|
|
137
|
+
|
|
138
|
+
const providedId = TemplateString(config.data.id).parse(input).result;
|
|
139
|
+
const idRegex = /^[a-zA-Z0-9\-\_\.]+$/;
|
|
140
|
+
if (!idRegex.test(providedId)) {
|
|
141
|
+
throw new Error(`Invalid id. Accepted characters: 'a-z', 'A-Z', '0-9', '-', '_', '.'`);
|
|
142
|
+
}
|
|
143
|
+
debugOutput += `Searching for data source with id: ${providedId}\n`;
|
|
144
|
+
|
|
145
|
+
const dsId = DataSourceComponent.normalizeDsId(providedId, teamId, namespaceLabel);
|
|
146
|
+
|
|
147
|
+
await vecDbConnector.requester(AccessCandidate.team(teamId)).deleteDatasource(namespaceLabel, dsId);
|
|
148
|
+
|
|
149
|
+
debugOutput += `Deleted data source with id: ${providedId}\n`;
|
|
150
|
+
|
|
151
|
+
return {
|
|
152
|
+
_debug: debugOutput,
|
|
153
|
+
Success: true,
|
|
154
|
+
// _error,
|
|
155
|
+
};
|
|
156
|
+
} catch (err: any) {
|
|
157
|
+
debugOutput += `Failed to delete data source: \n Error: ${err?.message}\n`;
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
_debug: debugOutput,
|
|
161
|
+
_error: err?.message || "Couldn't delete data source",
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
validateInput(input: any) {
|
|
167
|
+
return Joi.object({}).unknown(true).validate(input);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
validateConfigData(data: any) {
|
|
171
|
+
return Joi.object({
|
|
172
|
+
namespaceId: Joi.string().required(),
|
|
173
|
+
id: Joi.string().optional().allow('').allow(null),
|
|
174
|
+
})
|
|
175
|
+
.unknown(true)
|
|
176
|
+
.validate(data);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Base class for the RAG components that handle the shared logic for the RAG components
|
|
2
|
+
import { EmbeddingsFactory } from '@sre/IO/VectorDB.service/embed';
|
|
3
|
+
import { Component } from '../Component.class';
|
|
4
|
+
import { ConnectorService } from '@sre/Core/ConnectorsService';
|
|
5
|
+
import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
|
|
6
|
+
import { getLLMCredentials } from '@sre/LLMManager/LLM.service/LLMCredentials.helper';
|
|
7
|
+
import { TEmbeddings } from '@sre/IO/VectorDB.service/embed/BaseEmbedding';
|
|
8
|
+
import { TemplateString } from '@sre/helpers/TemplateString.helper';
|
|
9
|
+
import { VectorDBConnector } from '@sre/IO/VectorDB.service/VectorDBConnector';
|
|
10
|
+
import { TLLMCredentials } from '@sre/types/LLM.types';
|
|
11
|
+
|
|
12
|
+
export type NsRecord = {
|
|
13
|
+
credentialId: string;
|
|
14
|
+
embeddings: { dimensions: string; modelId: string };
|
|
15
|
+
label: string;
|
|
16
|
+
createdAt: string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export enum TDataSourceCompErrorCodes {
|
|
20
|
+
NAMESPACE_NOT_FOUND = 1,
|
|
21
|
+
CREDENTIAL_NOT_FOUND = 2,
|
|
22
|
+
EMBEDDING_CONFIG_ERROR = 3,
|
|
23
|
+
}
|
|
24
|
+
export class DataSourceCompError extends Error {
|
|
25
|
+
public code: TDataSourceCompErrorCodes;
|
|
26
|
+
constructor(message: string, code: TDataSourceCompErrorCodes) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.name = 'DataSourceCompError';
|
|
29
|
+
this.code = code;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export class DataSourceComponent extends Component {
|
|
33
|
+
constructor() {
|
|
34
|
+
super();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
public async resolveVectorDbConnector(namespace: string | NsRecord, teamId: string): Promise<VectorDBConnector> {
|
|
38
|
+
// resolve the ns record, if not exist, throw an error (new in v2)
|
|
39
|
+
// then we also need to resolve the credentials
|
|
40
|
+
let namespaceRecord = namespace as NsRecord;
|
|
41
|
+
|
|
42
|
+
if (typeof namespace === 'string') {
|
|
43
|
+
// if it's a string, we need to get the namespace record from the NKV
|
|
44
|
+
const nkvConnector = ConnectorService.getNKVConnector();
|
|
45
|
+
const nkvClient = nkvConnector.requester(AccessCandidate.team(teamId));
|
|
46
|
+
const rawNsRecord = await nkvClient.get(`vectorDB:namespaces`, namespace);
|
|
47
|
+
|
|
48
|
+
if (!rawNsRecord) {
|
|
49
|
+
throw new DataSourceCompError(`Namespace ${namespace} does not exist`, TDataSourceCompErrorCodes.NAMESPACE_NOT_FOUND);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// const { credentialId, embeddings: embeddingsOptions } = JSON.parse(rawNsRecord.toString());
|
|
53
|
+
namespaceRecord = JSON.parse(rawNsRecord.toString()) as NsRecord;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const accountConnector = ConnectorService.getAccountConnector();
|
|
57
|
+
const accountClient = accountConnector.requester(AccessCandidate.team(teamId));
|
|
58
|
+
const rawCredRecord = await accountClient.getTeamSetting(namespaceRecord.credentialId, 'vector_db_creds');
|
|
59
|
+
if (!rawCredRecord) {
|
|
60
|
+
throw new DataSourceCompError(
|
|
61
|
+
`Credential ${namespaceRecord.credentialId} does not exist`,
|
|
62
|
+
TDataSourceCompErrorCodes.CREDENTIAL_NOT_FOUND
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
const credRecord = JSON.parse(rawCredRecord);
|
|
66
|
+
await Promise.all(
|
|
67
|
+
Object.keys(credRecord.credentials).map(async (key) => {
|
|
68
|
+
if (typeof credRecord.credentials[key] !== 'string') return;
|
|
69
|
+
credRecord.credentials[key] = await TemplateString(credRecord.credentials[key]).parseTeamKeysAsync(teamId).asyncResult;
|
|
70
|
+
})
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
const vecDbConnector = ConnectorService.getVectorDBConnector(credRecord.provider).instance({
|
|
74
|
+
credentials: credRecord.credentials,
|
|
75
|
+
embeddings: await this.buildEmbeddingConfig(namespaceRecord.embeddings, teamId),
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
return vecDbConnector;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
public async buildEmbeddingConfig(embedding: { dimensions: string; modelId: string }, teamId: string): Promise<TEmbeddings> {
|
|
82
|
+
// we need to take this and return a proper TEmbeddings object
|
|
83
|
+
|
|
84
|
+
const provider = EmbeddingsFactory.getProviderByModel(embedding.modelId as any);
|
|
85
|
+
|
|
86
|
+
// based on the provider, we should be able to retreive the correct credentials
|
|
87
|
+
const modelsProvider = ConnectorService.getModelsProviderConnector();
|
|
88
|
+
const modelProviderCandidate = modelsProvider.requester(AccessCandidate.team(teamId));
|
|
89
|
+
// const modelInfo = await modelProviderCandidate.getModelInfo(embedding.modelId);
|
|
90
|
+
|
|
91
|
+
const llmCreds = await getLLMCredentials(AccessCandidate.team(teamId), {
|
|
92
|
+
provider,
|
|
93
|
+
modelId: embedding.modelId,
|
|
94
|
+
credentials: [TLLMCredentials.Vault, TLLMCredentials.Internal],
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
return {
|
|
98
|
+
provider,
|
|
99
|
+
model: embedding.modelId,
|
|
100
|
+
credentials: llmCreds,
|
|
101
|
+
dimensions: parseInt(embedding.dimensions), // pass both for backwards compatibility
|
|
102
|
+
params: {
|
|
103
|
+
dimensions: parseInt(embedding.dimensions), // pass both for backwards compatibility
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
public static normalizeDsId(providedId: string, teamId: string, namespaceId: string) {
|
|
109
|
+
return `${teamId}::${namespaceId}::${providedId}`;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { IAgent as Agent } from '@sre/types/Agent.types';
|
|
2
|
+
import { DataSourceComponent } from './DataSourceComponent.class';
|
|
3
|
+
import Joi from 'joi';
|
|
4
|
+
import { validateCharacterSet } from '@sre/utils/validation.utils';
|
|
5
|
+
import { TemplateString } from '@sre/helpers/TemplateString.helper';
|
|
6
|
+
import { isUrl, detectURLSourceType } from '../../utils';
|
|
7
|
+
import { SmythFS } from '@sre/IO/Storage.service/SmythFS.class';
|
|
8
|
+
import { ConnectorService } from '@sre/Core/ConnectorsService';
|
|
9
|
+
|
|
10
|
+
import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
|
|
11
|
+
import { TEmbeddings } from '@sre/IO/VectorDB.service/embed/BaseEmbedding';
|
|
12
|
+
import { VectorDBConnector } from '@sre/IO/VectorDB.service/VectorDBConnector';
|
|
13
|
+
import { JSONContentHelper } from '@sre/helpers/JsonContent.helper';
|
|
14
|
+
|
|
15
|
+
export class DataSourceIndexer extends DataSourceComponent {
|
|
16
|
+
private MAX_ALLOWED_URLS_PER_INPUT = 20;
|
|
17
|
+
protected configSchema = Joi.object({
|
|
18
|
+
namespace: Joi.string().max(50).allow(''),
|
|
19
|
+
id: Joi.string().custom(validateCharacterSet, 'id custom validation').allow('').label('source identifier'),
|
|
20
|
+
name: Joi.string().max(50).allow('').label('label'),
|
|
21
|
+
metadata: Joi.string().allow(null).allow('').max(10000).label('metadata'),
|
|
22
|
+
chunkSize: Joi.number().optional(),
|
|
23
|
+
chunkOverlap: Joi.number().optional(),
|
|
24
|
+
version: Joi.string().valid('v1', 'v2').default('v1'),
|
|
25
|
+
});
|
|
26
|
+
constructor() {
|
|
27
|
+
super();
|
|
28
|
+
}
|
|
29
|
+
init() {}
|
|
30
|
+
async process(input, config, agent: Agent) {
|
|
31
|
+
await super.process(input, config, agent);
|
|
32
|
+
|
|
33
|
+
let response: any = null;
|
|
34
|
+
if (!config.data.version || config.data.version === 'v1') {
|
|
35
|
+
response = await this.processV1(input, config, agent);
|
|
36
|
+
} else if (config.data.version === 'v2') {
|
|
37
|
+
response = await this.processV2(input, config, agent);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return response;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
private async processV1(input, config, agent: Agent) {
|
|
44
|
+
const teamId = agent.teamId;
|
|
45
|
+
const agentId = agent.id;
|
|
46
|
+
let debugOutput = agent.agentRuntime?.debug ? '== Source Indexer Log ==\n' : null;
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
const _config = {
|
|
50
|
+
...config.data,
|
|
51
|
+
name: TemplateString(config.data.name).parse(input).result,
|
|
52
|
+
id: TemplateString(config.data.id).parse(input).result,
|
|
53
|
+
metadata: TemplateString(config.data.metadata).parse(input).result,
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const outputs = {};
|
|
57
|
+
for (let con of config.outputs) {
|
|
58
|
+
if (con.default) continue;
|
|
59
|
+
outputs[con.name] = con?.description ? `<${con?.description}>` : '';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const namespaceId = _config.namespace.split('_').slice(1).join('_') || _config.namespace;
|
|
63
|
+
debugOutput += `[Selected namespace id] \n${namespaceId}\n\n`;
|
|
64
|
+
|
|
65
|
+
const vectorDbConnector =
|
|
66
|
+
// (await vectorDBHelper.getTeamConnector(teamId)) ||
|
|
67
|
+
ConnectorService.getVectorDBConnector();
|
|
68
|
+
const nsExists = await vectorDbConnector.requester(AccessCandidate.team(teamId)).namespaceExists(namespaceId);
|
|
69
|
+
|
|
70
|
+
if (!nsExists) {
|
|
71
|
+
const newNs = await vectorDbConnector.requester(AccessCandidate.team(teamId)).createNamespace(namespaceId);
|
|
72
|
+
debugOutput += `[Created namespace] \n${newNs}\n\n`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const inputSchema = this.validateInput(input);
|
|
76
|
+
if (inputSchema.error) {
|
|
77
|
+
throw new Error(`Input validation error: ${inputSchema.error}\n EXITING...`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const providedId = _config.id;
|
|
81
|
+
// const isAutoId = _config.isAutoId;
|
|
82
|
+
const idRegex = /^[a-zA-Z0-9\-\_\.]+$/;
|
|
83
|
+
|
|
84
|
+
if (!providedId) {
|
|
85
|
+
// Assign a new ID if it's set to auto-generate or not provided
|
|
86
|
+
// _config.id = crypto.randomBytes(16).toString('hex');
|
|
87
|
+
throw new Error(`Id is required`);
|
|
88
|
+
} else if (!idRegex.test(providedId)) {
|
|
89
|
+
// Validate the provided ID if it's not auto-generated
|
|
90
|
+
throw new Error(`Invalid id. Accepted characters: 'a-z', 'A-Z', '0-9', '-', '_', '.'`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
let indexRes: any = null;
|
|
94
|
+
let parsedUrlArray: string[] | null = null;
|
|
95
|
+
const dsId = DataSourceIndexer.normalizeDsId(providedId, teamId, namespaceId);
|
|
96
|
+
|
|
97
|
+
if (isUrl(inputSchema.value.Source)) {
|
|
98
|
+
debugOutput += `STEP: Parsing input as url\n\n`;
|
|
99
|
+
throw new Error('URLs are not supported yet');
|
|
100
|
+
} else {
|
|
101
|
+
debugOutput += `STEP: Parsing input as text\n\n`;
|
|
102
|
+
indexRes = await this.addDSFromText({
|
|
103
|
+
teamId,
|
|
104
|
+
namespaceId: namespaceId,
|
|
105
|
+
text: inputSchema.value.Source,
|
|
106
|
+
name: _config.name || 'Untitled',
|
|
107
|
+
metadata: _config.metadata || null,
|
|
108
|
+
sourceId: dsId,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
debugOutput += `Created datasource successfully\n\n`;
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
_debug: debugOutput,
|
|
116
|
+
Success: {
|
|
117
|
+
result: indexRes?.data?.dataSource || true,
|
|
118
|
+
id: _config.id,
|
|
119
|
+
},
|
|
120
|
+
// _error,
|
|
121
|
+
};
|
|
122
|
+
} catch (err: any) {
|
|
123
|
+
debugOutput += `Error: ${err?.message || "Couldn't index data source"}\n\n`;
|
|
124
|
+
return {
|
|
125
|
+
_debug: debugOutput,
|
|
126
|
+
_error: err?.message || "Couldn't index data source",
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
private async processV2(input, config, agent: Agent) {
|
|
132
|
+
const teamId = agent.teamId;
|
|
133
|
+
const agentId = agent.id;
|
|
134
|
+
let debugOutput = agent.agentRuntime?.debug ? '== Source Indexer Log ==\n' : null;
|
|
135
|
+
|
|
136
|
+
try {
|
|
137
|
+
const _config = {
|
|
138
|
+
...config.data,
|
|
139
|
+
name: TemplateString(config.data.name).parse(input).result,
|
|
140
|
+
id: TemplateString(config.data.id).parse(input).result,
|
|
141
|
+
metadata: TemplateString(config.data.metadata).parse(input).result,
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const outputs = {};
|
|
145
|
+
for (let con of config.outputs) {
|
|
146
|
+
if (con.default) continue;
|
|
147
|
+
outputs[con.name] = con?.description ? `<${con?.description}>` : '';
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// we try to get the namespace without the prefix teamId, if not exist, we use the full namespace id
|
|
151
|
+
// const namespaceLabel = _config.namespace.split('_').slice(1).join('_') || _config.namespace;
|
|
152
|
+
const namespaceLabel = /^c[a-z0-9]{24}.+$/.test(_config.namespace) ? _config.namespace.split('_').slice(1).join('_') : _config.namespace;
|
|
153
|
+
const namespaceId = _config.namespace;
|
|
154
|
+
debugOutput += `[Selected namespace] \n${namespaceLabel}\n\n`;
|
|
155
|
+
|
|
156
|
+
let vecDbConnector: VectorDBConnector = null;
|
|
157
|
+
try {
|
|
158
|
+
vecDbConnector = await this.resolveVectorDbConnector(namespaceId, teamId);
|
|
159
|
+
} catch (err: any) {
|
|
160
|
+
debugOutput += `Error: ${err?.message || "Couldn't get vector database connector"}\n\n`;
|
|
161
|
+
return {
|
|
162
|
+
_debug: debugOutput,
|
|
163
|
+
_error: err?.message || "Couldn't get vector database connector",
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
const vecDbClient = vecDbConnector.requester(AccessCandidate.team(teamId));
|
|
167
|
+
|
|
168
|
+
const inputSchema = this.validateInput(input);
|
|
169
|
+
if (inputSchema.error) {
|
|
170
|
+
throw new Error(`Input validation error: ${inputSchema.error}\n EXITING...`);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const providedId = _config.id;
|
|
174
|
+
// const isAutoId = _config.isAutoId;
|
|
175
|
+
const idRegex = /^[a-zA-Z0-9\-\_\.]+$/;
|
|
176
|
+
|
|
177
|
+
if (!providedId) {
|
|
178
|
+
// Assign a new ID if it's set to auto-generate or not provided
|
|
179
|
+
// _config.id = crypto.randomBytes(16).toString('hex');
|
|
180
|
+
throw new Error(`Id is required`);
|
|
181
|
+
} else if (!idRegex.test(providedId)) {
|
|
182
|
+
// Validate the provided ID if it's not auto-generated
|
|
183
|
+
throw new Error(`Invalid id. Accepted characters: 'a-z', 'A-Z', '0-9', '-', '_', '.'`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const dsId = DataSourceIndexer.normalizeDsId(providedId, teamId, namespaceLabel);
|
|
187
|
+
|
|
188
|
+
// check if the datasource already exists
|
|
189
|
+
const dsExists = await vecDbClient.getDatasource(namespaceLabel, dsId);
|
|
190
|
+
if (dsExists) {
|
|
191
|
+
debugOutput += `Datasource already exists\n\n`;
|
|
192
|
+
return {
|
|
193
|
+
_debug: debugOutput,
|
|
194
|
+
_error: `Datasource already exists`,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
debugOutput += `STEP: Parsing input as text\n\n`;
|
|
199
|
+
|
|
200
|
+
const response = await vecDbClient.createDatasource(namespaceLabel, {
|
|
201
|
+
text: inputSchema.value.Source,
|
|
202
|
+
metadata: JSONContentHelper.create(_config.metadata).tryParse() || null,
|
|
203
|
+
id: dsId,
|
|
204
|
+
label: _config.name || 'Untitled',
|
|
205
|
+
chunkSize: _config.chunkSize ? parseInt(_config.chunkSize) : undefined,
|
|
206
|
+
chunkOverlap: _config.chunkOverlap ? parseInt(_config.chunkOverlap) : undefined,
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
debugOutput += `Created datasource successfully\n\n`;
|
|
210
|
+
|
|
211
|
+
return {
|
|
212
|
+
_debug: debugOutput,
|
|
213
|
+
Success: {
|
|
214
|
+
result: response || true,
|
|
215
|
+
id: _config.id,
|
|
216
|
+
},
|
|
217
|
+
// _error,
|
|
218
|
+
};
|
|
219
|
+
} catch (err: any) {
|
|
220
|
+
debugOutput += `Error: ${err?.message || "Couldn't index data source"}\n\n`;
|
|
221
|
+
return {
|
|
222
|
+
_debug: debugOutput,
|
|
223
|
+
_error: err?.message || "Couldn't index data source",
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
validateInput(input: any) {
|
|
229
|
+
return Joi.object({
|
|
230
|
+
Source: Joi.any().required(),
|
|
231
|
+
})
|
|
232
|
+
.unknown(true)
|
|
233
|
+
.validate(input);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private async addDSFromText({ teamId, sourceId, namespaceId, text, name, metadata }) {
|
|
237
|
+
let vectorDbConnector = ConnectorService.getVectorDBConnector();
|
|
238
|
+
// const isOnCustomStorage = await vectorDBHelper.isNamespaceOnCustomStorage(teamId, namespaceId);
|
|
239
|
+
// if (isOnCustomStorage) {
|
|
240
|
+
// const customTeamConnector = await vectorDBHelper.getTeamConnector(teamId);
|
|
241
|
+
// if (customTeamConnector) {
|
|
242
|
+
// vectorDbConnector = customTeamConnector;
|
|
243
|
+
// }
|
|
244
|
+
// }
|
|
245
|
+
const id = await vectorDbConnector.requester(AccessCandidate.team(teamId)).createDatasource(namespaceId, {
|
|
246
|
+
text,
|
|
247
|
+
metadata,
|
|
248
|
+
id: sourceId,
|
|
249
|
+
label: name,
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
return id;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import Joi from 'joi';
|
|
2
|
-
import { validateInteger } from '
|
|
2
|
+
import { validateInteger } from '../../utils';
|
|
3
3
|
import { jsonrepair } from 'jsonrepair';
|
|
4
4
|
import { TemplateString } from '@sre/helpers/TemplateString.helper';
|
|
5
5
|
import { JSONContent } from '@sre/helpers/JsonContent.helper';
|
|
6
6
|
import { ConnectorService } from '@sre/Core/ConnectorsService';
|
|
7
7
|
import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
|
|
8
8
|
import { IAgent as Agent } from '@sre/types/Agent.types';
|
|
9
|
-
import {
|
|
9
|
+
import { DataSourceComponent } from './DataSourceComponent.class';
|
|
10
10
|
|
|
11
11
|
// Note: LLMHelper renamed to LLMInference
|
|
12
12
|
class LLMInference {
|
|
@@ -15,7 +15,7 @@ class LLMInference {
|
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
export class DataSourceLookup extends
|
|
18
|
+
export class DataSourceLookup extends DataSourceComponent {
|
|
19
19
|
protected configSchema = Joi.object({
|
|
20
20
|
topK: Joi.alternatives([Joi.string(), Joi.number()]) // Value is now a number; keep string fallback for backward compatibility.
|
|
21
21
|
|
|
@@ -31,13 +31,22 @@ export class DataSourceLookup extends Component {
|
|
|
31
31
|
}),
|
|
32
32
|
scoreThreshold: Joi.number().optional().label('Score Threshold'),
|
|
33
33
|
includeScore: Joi.boolean().optional().label('Include Score'),
|
|
34
|
+
version: Joi.string().valid('v1', 'v2').default('v1'),
|
|
34
35
|
});
|
|
35
36
|
constructor() {
|
|
36
37
|
super();
|
|
37
38
|
}
|
|
38
39
|
init() {}
|
|
40
|
+
|
|
39
41
|
async process(input, config, agent: Agent) {
|
|
40
42
|
await super.process(input, config, agent);
|
|
43
|
+
if (!config.data.version || config.data.version === 'v1') {
|
|
44
|
+
return await this.processV1(input, config, agent);
|
|
45
|
+
} else if (config.data.version === 'v2') {
|
|
46
|
+
return await this.processV2(input, config, agent);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async processV1(input, config, agent: Agent) {
|
|
41
50
|
const componentId = config.id;
|
|
42
51
|
const component = agent.components[componentId];
|
|
43
52
|
const teamId = agent.teamId;
|
|
@@ -139,6 +148,86 @@ export class DataSourceLookup extends Component {
|
|
|
139
148
|
};
|
|
140
149
|
}
|
|
141
150
|
|
|
151
|
+
async processV2(input, config, agent: Agent) {
|
|
152
|
+
const teamId = agent.teamId;
|
|
153
|
+
let debugOutput = agent.agentRuntime?.debug ? '== Data Source Lookup Log ==\n' : null;
|
|
154
|
+
|
|
155
|
+
const outputs = {};
|
|
156
|
+
for (let con of config.outputs) {
|
|
157
|
+
if (con.default) continue;
|
|
158
|
+
outputs[con.name] = '';
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const namespaceLabel = /^c[a-z0-9]{24}.+$/.test(config.data.namespace)
|
|
162
|
+
? config.data.namespace.split('_').slice(1).join('_')
|
|
163
|
+
: config.data.namespace;
|
|
164
|
+
const namespaceId = config.data.namespace;
|
|
165
|
+
const model = config.data?.model || 'gpt-4o-mini';
|
|
166
|
+
const includeMetadata = config.data?.includeMetadata || false;
|
|
167
|
+
|
|
168
|
+
const scoreThreshold = config.data?.scoreThreshold || 0.001; // Use low score (0.001) to return most results for backward compatibility
|
|
169
|
+
const includeScore = config.data?.includeScore || false;
|
|
170
|
+
|
|
171
|
+
const _input = typeof input.Query === 'string' ? input.Query : JSON.stringify(input.Query);
|
|
172
|
+
|
|
173
|
+
const topK = Math.max(config.data?.topK || 50, 50);
|
|
174
|
+
|
|
175
|
+
// let vectorDbConnector = ConnectorService.getVectorDBConnector();
|
|
176
|
+
// let existingNs = await vectorDbConnector.requester(AccessCandidate.team(teamId)).namespaceExists(namespaceLabel);
|
|
177
|
+
|
|
178
|
+
const vecDbConnector = await this.resolveVectorDbConnector(namespaceId, teamId);
|
|
179
|
+
|
|
180
|
+
let results: string[] | { content: string; metadata: any; score?: number }[];
|
|
181
|
+
let _error;
|
|
182
|
+
try {
|
|
183
|
+
const response = await vecDbConnector
|
|
184
|
+
.requester(AccessCandidate.team(teamId))
|
|
185
|
+
.search(namespaceLabel, _input, { topK, includeMetadata: true });
|
|
186
|
+
|
|
187
|
+
results = response.slice(0, config.data.topK).map((result) => ({
|
|
188
|
+
content: result.text,
|
|
189
|
+
metadata: result.metadata,
|
|
190
|
+
score: result.score, // use a very low score to return
|
|
191
|
+
}));
|
|
192
|
+
|
|
193
|
+
results = results.filter((result) => result.score >= scoreThreshold);
|
|
194
|
+
|
|
195
|
+
// Transform results based on inclusion flags
|
|
196
|
+
results = results.map((result) => {
|
|
197
|
+
const transformedResult: any = {
|
|
198
|
+
content: result.content,
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
if (includeMetadata) {
|
|
202
|
+
// legacy user-specific metadata key [result.metadata?.metadata]
|
|
203
|
+
transformedResult.metadata = this.parseMetadata(result.metadata || result.metadata?.metadata);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (includeScore) {
|
|
207
|
+
transformedResult.score = result.score;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// If neither metadata nor score is included, return just the content string
|
|
211
|
+
return includeMetadata || includeScore ? transformedResult : result.content;
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
debugOutput += `[Results] \nLoaded ${results.length} results from namespace: ${namespaceLabel}\n\n`;
|
|
215
|
+
} catch (error) {
|
|
216
|
+
debugOutput += `Error: ${error instanceof Error ? error.message : error.toString()}\n\n`;
|
|
217
|
+
_error = error instanceof Error ? error.message : error.toString();
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const totalLength = JSON.stringify(results).length;
|
|
221
|
+
debugOutput += `[Total Length] \n${totalLength}\n\n`;
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
Results: results,
|
|
225
|
+
_error,
|
|
226
|
+
_debug: debugOutput,
|
|
227
|
+
//_debug: `Query: ${_input}. \nTotal Length = ${totalLength} \nResults: ${JSON.stringify(results)}`,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
142
231
|
// private async checkIfTeamOwnsNamespace(teamId: string, namespaceId: string, token: string) {
|
|
143
232
|
// try {
|
|
144
233
|
// const res = await SmythAPIHelper.fromAuth({ token }).mwSysAPI.get(`/vectors/namespaces/${namespaceId}`);
|