@juspay/neurolink 8.3.0 → 8.4.1
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.md +12 -0
- package/README.md +1 -0
- package/dist/adapters/providerImageAdapter.d.ts +1 -1
- package/dist/adapters/providerImageAdapter.js +62 -0
- package/dist/agent/directTools.d.ts +0 -72
- package/dist/agent/directTools.js +3 -74
- package/dist/cli/commands/config.d.ts +18 -18
- package/dist/cli/factories/commandFactory.js +1 -0
- package/dist/constants/enums.d.ts +1 -0
- package/dist/constants/enums.js +3 -1
- package/dist/constants/tokens.d.ts +3 -0
- package/dist/constants/tokens.js +3 -0
- package/dist/core/baseProvider.d.ts +56 -53
- package/dist/core/baseProvider.js +107 -1095
- package/dist/core/constants.d.ts +3 -0
- package/dist/core/constants.js +6 -3
- package/dist/core/modelConfiguration.js +10 -0
- package/dist/core/modules/GenerationHandler.d.ts +63 -0
- package/dist/core/modules/GenerationHandler.js +230 -0
- package/dist/core/modules/MessageBuilder.d.ts +39 -0
- package/dist/core/modules/MessageBuilder.js +179 -0
- package/dist/core/modules/StreamHandler.d.ts +52 -0
- package/dist/core/modules/StreamHandler.js +103 -0
- package/dist/core/modules/TelemetryHandler.d.ts +64 -0
- package/dist/core/modules/TelemetryHandler.js +170 -0
- package/dist/core/modules/ToolsManager.d.ts +98 -0
- package/dist/core/modules/ToolsManager.js +521 -0
- package/dist/core/modules/Utilities.d.ts +88 -0
- package/dist/core/modules/Utilities.js +329 -0
- package/dist/factories/providerRegistry.js +1 -1
- package/dist/lib/adapters/providerImageAdapter.d.ts +1 -1
- package/dist/lib/adapters/providerImageAdapter.js +62 -0
- package/dist/lib/agent/directTools.d.ts +0 -72
- package/dist/lib/agent/directTools.js +3 -74
- package/dist/lib/constants/enums.d.ts +1 -0
- package/dist/lib/constants/enums.js +3 -1
- package/dist/lib/constants/tokens.d.ts +3 -0
- package/dist/lib/constants/tokens.js +3 -0
- package/dist/lib/core/baseProvider.d.ts +56 -53
- package/dist/lib/core/baseProvider.js +107 -1095
- package/dist/lib/core/constants.d.ts +3 -0
- package/dist/lib/core/constants.js +6 -3
- package/dist/lib/core/modelConfiguration.js +10 -0
- package/dist/lib/core/modules/GenerationHandler.d.ts +63 -0
- package/dist/lib/core/modules/GenerationHandler.js +231 -0
- package/dist/lib/core/modules/MessageBuilder.d.ts +39 -0
- package/dist/lib/core/modules/MessageBuilder.js +180 -0
- package/dist/lib/core/modules/StreamHandler.d.ts +52 -0
- package/dist/lib/core/modules/StreamHandler.js +104 -0
- package/dist/lib/core/modules/TelemetryHandler.d.ts +64 -0
- package/dist/lib/core/modules/TelemetryHandler.js +171 -0
- package/dist/lib/core/modules/ToolsManager.d.ts +98 -0
- package/dist/lib/core/modules/ToolsManager.js +522 -0
- package/dist/lib/core/modules/Utilities.d.ts +88 -0
- package/dist/lib/core/modules/Utilities.js +330 -0
- package/dist/lib/factories/providerRegistry.js +1 -1
- package/dist/lib/mcp/servers/agent/directToolsServer.js +0 -1
- package/dist/lib/memory/mem0Initializer.d.ts +32 -1
- package/dist/lib/memory/mem0Initializer.js +55 -2
- package/dist/lib/models/modelRegistry.js +44 -0
- package/dist/lib/neurolink.d.ts +1 -1
- package/dist/lib/neurolink.js +43 -10
- package/dist/lib/providers/amazonBedrock.js +59 -10
- package/dist/lib/providers/anthropic.js +2 -30
- package/dist/lib/providers/azureOpenai.js +2 -24
- package/dist/lib/providers/googleAiStudio.js +2 -24
- package/dist/lib/providers/googleVertex.js +2 -45
- package/dist/lib/providers/huggingFace.js +3 -31
- package/dist/lib/providers/litellm.d.ts +1 -1
- package/dist/lib/providers/litellm.js +110 -44
- package/dist/lib/providers/mistral.js +5 -32
- package/dist/lib/providers/ollama.d.ts +1 -0
- package/dist/lib/providers/ollama.js +476 -129
- package/dist/lib/providers/openAI.js +2 -28
- package/dist/lib/providers/openaiCompatible.js +3 -31
- package/dist/lib/types/content.d.ts +16 -113
- package/dist/lib/types/content.js +16 -2
- package/dist/lib/types/conversation.d.ts +3 -17
- package/dist/lib/types/generateTypes.d.ts +2 -2
- package/dist/lib/types/index.d.ts +2 -0
- package/dist/lib/types/index.js +2 -0
- package/dist/lib/types/multimodal.d.ts +282 -0
- package/dist/lib/types/multimodal.js +101 -0
- package/dist/lib/types/streamTypes.d.ts +2 -2
- package/dist/lib/utils/imageProcessor.d.ts +1 -1
- package/dist/lib/utils/messageBuilder.js +25 -2
- package/dist/lib/utils/multimodalOptionsBuilder.d.ts +1 -1
- package/dist/lib/utils/pdfProcessor.d.ts +9 -0
- package/dist/lib/utils/pdfProcessor.js +67 -9
- package/dist/mcp/servers/agent/directToolsServer.js +0 -1
- package/dist/memory/mem0Initializer.d.ts +32 -1
- package/dist/memory/mem0Initializer.js +55 -2
- package/dist/models/modelRegistry.js +44 -0
- package/dist/neurolink.d.ts +1 -1
- package/dist/neurolink.js +43 -10
- package/dist/providers/amazonBedrock.js +59 -10
- package/dist/providers/anthropic.js +2 -30
- package/dist/providers/azureOpenai.js +2 -24
- package/dist/providers/googleAiStudio.js +2 -24
- package/dist/providers/googleVertex.js +2 -45
- package/dist/providers/huggingFace.js +3 -31
- package/dist/providers/litellm.d.ts +1 -1
- package/dist/providers/litellm.js +110 -44
- package/dist/providers/mistral.js +5 -32
- package/dist/providers/ollama.d.ts +1 -0
- package/dist/providers/ollama.js +476 -129
- package/dist/providers/openAI.js +2 -28
- package/dist/providers/openaiCompatible.js +3 -31
- package/dist/types/content.d.ts +16 -113
- package/dist/types/content.js +16 -2
- package/dist/types/conversation.d.ts +3 -17
- package/dist/types/generateTypes.d.ts +2 -2
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.js +2 -0
- package/dist/types/multimodal.d.ts +282 -0
- package/dist/types/multimodal.js +100 -0
- package/dist/types/streamTypes.d.ts +2 -2
- package/dist/utils/imageProcessor.d.ts +1 -1
- package/dist/utils/messageBuilder.js +25 -2
- package/dist/utils/multimodalOptionsBuilder.d.ts +1 -1
- package/dist/utils/pdfProcessor.d.ts +9 -0
- package/dist/utils/pdfProcessor.js +67 -9
- package/package.json +5 -2
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stream Handler Module
|
|
3
|
+
*
|
|
4
|
+
* Handles streaming-related validation, result creation, and analytics.
|
|
5
|
+
* Extracted from BaseProvider to follow Single Responsibility Principle.
|
|
6
|
+
*
|
|
7
|
+
* Responsibilities:
|
|
8
|
+
* - Stream options validation
|
|
9
|
+
* - Text stream creation
|
|
10
|
+
* - Stream result formatting
|
|
11
|
+
* - Stream analytics creation
|
|
12
|
+
*
|
|
13
|
+
* @module core/modules/StreamHandler
|
|
14
|
+
*/
|
|
15
|
+
import { logger } from "../../utils/logger.js";
|
|
16
|
+
import { validateStreamOptions as validateStreamOpts, ValidationError, createValidationSummary, } from "../../utils/parameterValidation.js";
|
|
17
|
+
import { STEP_LIMITS } from "../constants.js";
|
|
18
|
+
import { createAnalytics } from "../analytics.js";
|
|
19
|
+
import { nanoid } from "nanoid";
|
|
20
|
+
/**
|
|
21
|
+
* StreamHandler class - Handles streaming operations for AI providers
|
|
22
|
+
*/
|
|
23
|
+
export class StreamHandler {
|
|
24
|
+
providerName;
|
|
25
|
+
modelName;
|
|
26
|
+
constructor(providerName, modelName) {
|
|
27
|
+
this.providerName = providerName;
|
|
28
|
+
this.modelName = modelName;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Validate stream options - consolidates validation from 7/10 providers
|
|
32
|
+
*/
|
|
33
|
+
validateStreamOptions(options) {
|
|
34
|
+
const validation = validateStreamOpts(options);
|
|
35
|
+
if (!validation.isValid) {
|
|
36
|
+
const summary = createValidationSummary(validation);
|
|
37
|
+
throw new ValidationError(`Stream options validation failed: ${summary}`, "options", "VALIDATION_FAILED", validation.suggestions);
|
|
38
|
+
}
|
|
39
|
+
// Log warnings if any
|
|
40
|
+
if (validation.warnings.length > 0) {
|
|
41
|
+
logger.warn("Stream options validation warnings:", validation.warnings);
|
|
42
|
+
}
|
|
43
|
+
// Additional BaseProvider-specific validation
|
|
44
|
+
if (options.maxSteps !== undefined) {
|
|
45
|
+
if (options.maxSteps < STEP_LIMITS.min ||
|
|
46
|
+
options.maxSteps > STEP_LIMITS.max) {
|
|
47
|
+
throw new ValidationError(`maxSteps must be between ${STEP_LIMITS.min} and ${STEP_LIMITS.max}`, "maxSteps", "OUT_OF_RANGE", [
|
|
48
|
+
`Use a value between ${STEP_LIMITS.min} and ${STEP_LIMITS.max} for optimal performance`,
|
|
49
|
+
]);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Create text stream transformation - consolidates identical logic from 7/10 providers
|
|
55
|
+
*/
|
|
56
|
+
createTextStream(result) {
|
|
57
|
+
return (async function* () {
|
|
58
|
+
for await (const chunk of result.textStream) {
|
|
59
|
+
yield { content: chunk };
|
|
60
|
+
}
|
|
61
|
+
})();
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Create standardized stream result - consolidates result structure
|
|
65
|
+
*/
|
|
66
|
+
createStreamResult(stream, additionalProps = {}) {
|
|
67
|
+
return {
|
|
68
|
+
stream,
|
|
69
|
+
provider: this.providerName,
|
|
70
|
+
model: this.modelName,
|
|
71
|
+
...additionalProps,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Create stream analytics - consolidates analytics from 4/10 providers
|
|
76
|
+
*/
|
|
77
|
+
async createStreamAnalytics(result, startTime, options) {
|
|
78
|
+
try {
|
|
79
|
+
const analytics = createAnalytics(this.providerName, this.modelName, result, Date.now() - startTime, {
|
|
80
|
+
requestId: `${this.providerName}-stream-${nanoid()}`,
|
|
81
|
+
streamingMode: true,
|
|
82
|
+
...options.context,
|
|
83
|
+
});
|
|
84
|
+
return analytics;
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
logger.warn(`Analytics creation failed for ${this.providerName}:`, error);
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Validate streaming-only options (called before executeStream)
|
|
93
|
+
* Simpler validation for options object structure
|
|
94
|
+
*/
|
|
95
|
+
validateStreamOptionsOnly(options) {
|
|
96
|
+
if (!options.input) {
|
|
97
|
+
throw new ValidationError("Stream options must include input", "input", "MISSING_REQUIRED", ["Provide options.input with text content"]);
|
|
98
|
+
}
|
|
99
|
+
if (!options.input.text && !options.input.images?.length) {
|
|
100
|
+
throw new ValidationError("Stream input must include either text or images", "input", "MISSING_REQUIRED", ["Provide options.input.text or options.input.images"]);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telemetry Handler Module
|
|
3
|
+
*
|
|
4
|
+
* Handles analytics, evaluation, performance metrics, and telemetry configuration.
|
|
5
|
+
* Extracted from BaseProvider to follow Single Responsibility Principle.
|
|
6
|
+
*
|
|
7
|
+
* Responsibilities:
|
|
8
|
+
* - Analytics creation and tracking
|
|
9
|
+
* - Evaluation generation
|
|
10
|
+
* - Performance metrics recording
|
|
11
|
+
* - Cost calculation
|
|
12
|
+
* - Telemetry configuration
|
|
13
|
+
*
|
|
14
|
+
* @module core/modules/TelemetryHandler
|
|
15
|
+
*/
|
|
16
|
+
import type { AIProviderName, EnhancedGenerateResult, TextGenerationOptions, AnalyticsData } from "../../types/index.js";
|
|
17
|
+
import type { EvaluationData } from "../../types/index.js";
|
|
18
|
+
import type { StreamOptions } from "../../types/streamTypes.js";
|
|
19
|
+
import type { NeuroLink } from "../../neurolink.js";
|
|
20
|
+
/**
|
|
21
|
+
* TelemetryHandler class - Handles analytics and telemetry for AI providers
|
|
22
|
+
*/
|
|
23
|
+
export declare class TelemetryHandler {
|
|
24
|
+
private readonly providerName;
|
|
25
|
+
private readonly modelName;
|
|
26
|
+
private readonly neurolink?;
|
|
27
|
+
constructor(providerName: AIProviderName, modelName: string, neurolink?: NeuroLink | undefined);
|
|
28
|
+
/**
|
|
29
|
+
* Create analytics for a generation result
|
|
30
|
+
*/
|
|
31
|
+
createAnalytics(result: EnhancedGenerateResult, responseTime: number, context?: Record<string, unknown>): Promise<AnalyticsData>;
|
|
32
|
+
/**
|
|
33
|
+
* Create evaluation for a generation result
|
|
34
|
+
*/
|
|
35
|
+
createEvaluation(result: EnhancedGenerateResult, options: TextGenerationOptions): Promise<EvaluationData>;
|
|
36
|
+
/**
|
|
37
|
+
* Record performance metrics for a generation
|
|
38
|
+
*/
|
|
39
|
+
recordPerformanceMetrics(usage: {
|
|
40
|
+
promptTokens: number;
|
|
41
|
+
completionTokens: number;
|
|
42
|
+
totalTokens: number;
|
|
43
|
+
} | undefined, responseTime: number): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Calculate actual cost based on token usage and provider configuration
|
|
46
|
+
*/
|
|
47
|
+
calculateActualCost(usage: {
|
|
48
|
+
promptTokens?: number;
|
|
49
|
+
completionTokens?: number;
|
|
50
|
+
totalTokens?: number;
|
|
51
|
+
}): Promise<number>;
|
|
52
|
+
/**
|
|
53
|
+
* Get telemetry configuration for streaming/generation
|
|
54
|
+
*/
|
|
55
|
+
getStreamTelemetryConfig(options: StreamOptions | TextGenerationOptions, operationType?: "stream" | "generate"): {
|
|
56
|
+
isEnabled: boolean;
|
|
57
|
+
functionId?: string;
|
|
58
|
+
metadata?: Record<string, string | number | boolean>;
|
|
59
|
+
} | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* Handle tool execution storage if available
|
|
62
|
+
*/
|
|
63
|
+
handleToolExecutionStorage(toolCalls: unknown[], toolResults: unknown[], options: TextGenerationOptions | StreamOptions, currentTime: Date): Promise<void>;
|
|
64
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Telemetry Handler Module
|
|
3
|
+
*
|
|
4
|
+
* Handles analytics, evaluation, performance metrics, and telemetry configuration.
|
|
5
|
+
* Extracted from BaseProvider to follow Single Responsibility Principle.
|
|
6
|
+
*
|
|
7
|
+
* Responsibilities:
|
|
8
|
+
* - Analytics creation and tracking
|
|
9
|
+
* - Evaluation generation
|
|
10
|
+
* - Performance metrics recording
|
|
11
|
+
* - Cost calculation
|
|
12
|
+
* - Telemetry configuration
|
|
13
|
+
*
|
|
14
|
+
* @module core/modules/TelemetryHandler
|
|
15
|
+
*/
|
|
16
|
+
import { logger } from "../../utils/logger.js";
|
|
17
|
+
import { nanoid } from "nanoid";
|
|
18
|
+
import { modelConfig } from "../modelConfiguration.js";
|
|
19
|
+
import { recordProviderPerformanceFromMetrics, getPerformanceOptimizedProvider, } from "../evaluationProviders.js";
|
|
20
|
+
/**
|
|
21
|
+
* TelemetryHandler class - Handles analytics and telemetry for AI providers
|
|
22
|
+
*/
|
|
23
|
+
export class TelemetryHandler {
|
|
24
|
+
providerName;
|
|
25
|
+
modelName;
|
|
26
|
+
neurolink;
|
|
27
|
+
constructor(providerName, modelName, neurolink) {
|
|
28
|
+
this.providerName = providerName;
|
|
29
|
+
this.modelName = modelName;
|
|
30
|
+
this.neurolink = neurolink;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Create analytics for a generation result
|
|
34
|
+
*/
|
|
35
|
+
async createAnalytics(result, responseTime, context) {
|
|
36
|
+
const { createAnalytics } = await import("../analytics.js");
|
|
37
|
+
return createAnalytics(this.providerName, this.modelName, result, responseTime, context);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Create evaluation for a generation result
|
|
41
|
+
*/
|
|
42
|
+
async createEvaluation(result, options) {
|
|
43
|
+
const { evaluateResponse } = await import("../evaluation.js");
|
|
44
|
+
const context = {
|
|
45
|
+
userQuery: options.prompt || options.input?.text || "Generated response",
|
|
46
|
+
aiResponse: result.content,
|
|
47
|
+
context: options.context,
|
|
48
|
+
primaryDomain: options.evaluationDomain,
|
|
49
|
+
assistantRole: "AI assistant",
|
|
50
|
+
conversationHistory: options.conversationHistory?.map((msg) => ({
|
|
51
|
+
role: msg.role,
|
|
52
|
+
content: msg.content,
|
|
53
|
+
})),
|
|
54
|
+
toolUsage: options.toolUsageContext
|
|
55
|
+
? [
|
|
56
|
+
{
|
|
57
|
+
toolName: options.toolUsageContext,
|
|
58
|
+
input: {},
|
|
59
|
+
output: {},
|
|
60
|
+
executionTime: 0,
|
|
61
|
+
},
|
|
62
|
+
]
|
|
63
|
+
: undefined,
|
|
64
|
+
expectedOutcome: options.expectedOutcome,
|
|
65
|
+
evaluationCriteria: options.evaluationCriteria,
|
|
66
|
+
};
|
|
67
|
+
const evaluation = await evaluateResponse(context);
|
|
68
|
+
return evaluation;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Record performance metrics for a generation
|
|
72
|
+
*/
|
|
73
|
+
async recordPerformanceMetrics(usage, responseTime) {
|
|
74
|
+
try {
|
|
75
|
+
const actualCost = await this.calculateActualCost(usage || { promptTokens: 0, completionTokens: 0, totalTokens: 0 });
|
|
76
|
+
recordProviderPerformanceFromMetrics(this.providerName, {
|
|
77
|
+
responseTime,
|
|
78
|
+
tokensGenerated: usage?.totalTokens || 0,
|
|
79
|
+
cost: actualCost,
|
|
80
|
+
success: true,
|
|
81
|
+
});
|
|
82
|
+
const optimizedProvider = getPerformanceOptimizedProvider("speed");
|
|
83
|
+
logger.debug(`🚀 Performance recorded for ${this.providerName}:`, {
|
|
84
|
+
responseTime: `${responseTime}ms`,
|
|
85
|
+
tokens: usage?.totalTokens || 0,
|
|
86
|
+
estimatedCost: `$${actualCost.toFixed(6)}`,
|
|
87
|
+
recommendedSpeedProvider: optimizedProvider?.provider || "none",
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
catch (perfError) {
|
|
91
|
+
logger.warn("⚠️ Performance recording failed:", perfError);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Calculate actual cost based on token usage and provider configuration
|
|
96
|
+
*/
|
|
97
|
+
async calculateActualCost(usage) {
|
|
98
|
+
try {
|
|
99
|
+
const costInfo = modelConfig.getCostInfo(this.providerName, this.modelName);
|
|
100
|
+
if (!costInfo) {
|
|
101
|
+
return 0; // No cost info available
|
|
102
|
+
}
|
|
103
|
+
const promptTokens = usage?.promptTokens || 0;
|
|
104
|
+
const completionTokens = usage?.completionTokens || 0;
|
|
105
|
+
// Calculate cost per 1K tokens
|
|
106
|
+
const inputCost = (promptTokens / 1000) * costInfo.input;
|
|
107
|
+
const outputCost = (completionTokens / 1000) * costInfo.output;
|
|
108
|
+
return inputCost + outputCost;
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
logger.debug(`Cost calculation failed for ${this.providerName}:`, error);
|
|
112
|
+
return 0; // Fallback to 0 on any error
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Get telemetry configuration for streaming/generation
|
|
117
|
+
*/
|
|
118
|
+
getStreamTelemetryConfig(options, operationType = "stream") {
|
|
119
|
+
// Check if telemetry is enabled via NeuroLink observability config
|
|
120
|
+
if (!this.neurolink?.isTelemetryEnabled()) {
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
const functionId = `${this.providerName}-${operationType}-${nanoid()}`;
|
|
124
|
+
const metadata = {
|
|
125
|
+
provider: this.providerName,
|
|
126
|
+
model: this.modelName,
|
|
127
|
+
toolsEnabled: !options.disableTools,
|
|
128
|
+
neurolink: true,
|
|
129
|
+
};
|
|
130
|
+
// Add sessionId if available
|
|
131
|
+
if ("sessionId" in options && options.sessionId) {
|
|
132
|
+
const sessionId = options.sessionId;
|
|
133
|
+
if (typeof sessionId === "string" ||
|
|
134
|
+
typeof sessionId === "number" ||
|
|
135
|
+
typeof sessionId === "boolean") {
|
|
136
|
+
metadata.sessionId = sessionId;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
isEnabled: true,
|
|
141
|
+
functionId,
|
|
142
|
+
metadata,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Handle tool execution storage if available
|
|
147
|
+
*/
|
|
148
|
+
async handleToolExecutionStorage(toolCalls, toolResults, options, currentTime) {
|
|
149
|
+
// Check if tools are not empty
|
|
150
|
+
const hasToolData = (toolCalls && toolCalls.length > 0) ||
|
|
151
|
+
(toolResults && toolResults.length > 0);
|
|
152
|
+
// Check if NeuroLink instance is available and has tool execution storage
|
|
153
|
+
const hasStorageAvailable = this.neurolink?.isToolExecutionStorageAvailable();
|
|
154
|
+
// Early return if storage is not available or no tool data
|
|
155
|
+
if (!hasStorageAvailable || !hasToolData || !this.neurolink) {
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
const sessionId = options.context?.sessionId ||
|
|
159
|
+
options.sessionId ||
|
|
160
|
+
`session-${nanoid()}`;
|
|
161
|
+
const userId = options.context?.userId ||
|
|
162
|
+
options.userId;
|
|
163
|
+
try {
|
|
164
|
+
await this.neurolink.storeToolExecutions(sessionId, userId, toolCalls, toolResults, currentTime);
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
logger.warn("Failed to store tool executions:", error);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tools Manager Module
|
|
3
|
+
*
|
|
4
|
+
* Handles all tool registration, discovery, and execution for AI providers.
|
|
5
|
+
* Extracted from BaseProvider to follow Single Responsibility Principle.
|
|
6
|
+
*
|
|
7
|
+
* Responsibilities:
|
|
8
|
+
* - Tool registration (direct, custom, MCP, external MCP)
|
|
9
|
+
* - Tool discovery and aggregation
|
|
10
|
+
* - Tool creation from definitions and schemas
|
|
11
|
+
* - Tool executor setup
|
|
12
|
+
* - Session context management for MCP tools
|
|
13
|
+
* - Event emission wrapping for tool execution
|
|
14
|
+
*
|
|
15
|
+
* @module core/modules/ToolsManager
|
|
16
|
+
*/
|
|
17
|
+
import type { Tool } from "ai";
|
|
18
|
+
import { z } from "zod";
|
|
19
|
+
import type { AIProviderName } from "../../types/index.js";
|
|
20
|
+
import type { NeuroLink } from "../../neurolink.js";
|
|
21
|
+
/**
|
|
22
|
+
* Utility functions interface for ToolsManager
|
|
23
|
+
*/
|
|
24
|
+
export interface ToolUtilities {
|
|
25
|
+
isZodSchema?: (schema: unknown) => boolean;
|
|
26
|
+
convertToolResult?: (result: unknown) => Promise<unknown>;
|
|
27
|
+
createPermissiveZodSchema?: () => z.ZodSchema;
|
|
28
|
+
fixSchemaForOpenAIStrictMode?: (schema: Record<string, unknown>) => Record<string, unknown>;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* ToolsManager class - Handles all tool management operations
|
|
32
|
+
*/
|
|
33
|
+
export declare class ToolsManager {
|
|
34
|
+
private readonly providerName;
|
|
35
|
+
private readonly directTools;
|
|
36
|
+
private readonly neurolink?;
|
|
37
|
+
private readonly utilities?;
|
|
38
|
+
protected mcpTools?: Record<string, Tool>;
|
|
39
|
+
protected customTools?: Map<string, unknown>;
|
|
40
|
+
protected toolExecutor?: (toolName: string, params: unknown) => Promise<unknown>;
|
|
41
|
+
protected sessionId?: string;
|
|
42
|
+
protected userId?: string;
|
|
43
|
+
constructor(providerName: AIProviderName, directTools: Record<string, unknown>, neurolink?: NeuroLink | undefined, utilities?: ToolUtilities | undefined);
|
|
44
|
+
/**
|
|
45
|
+
* Set session context for MCP tools
|
|
46
|
+
*/
|
|
47
|
+
setSessionContext(sessionId?: string, userId?: string): void;
|
|
48
|
+
/**
|
|
49
|
+
* Set up tool executor for a provider to enable actual tool execution
|
|
50
|
+
* @param sdk - The NeuroLinkSDK instance for tool execution
|
|
51
|
+
* @param functionTag - Function name for logging
|
|
52
|
+
*/
|
|
53
|
+
setupToolExecutor(sdk: {
|
|
54
|
+
customTools: Map<string, unknown>;
|
|
55
|
+
executeTool: (toolName: string, params: unknown) => Promise<unknown>;
|
|
56
|
+
}, functionTag: string): void;
|
|
57
|
+
/**
|
|
58
|
+
* Get all available tools - direct tools are ALWAYS available
|
|
59
|
+
* MCP tools are added when available (without blocking)
|
|
60
|
+
*/
|
|
61
|
+
getAllTools(): Promise<Record<string, Tool>>;
|
|
62
|
+
/**
|
|
63
|
+
* Get direct tools (built-in agent tools)
|
|
64
|
+
*/
|
|
65
|
+
getDirectTools(): Record<string, unknown>;
|
|
66
|
+
/**
|
|
67
|
+
* Get MCP tools
|
|
68
|
+
*/
|
|
69
|
+
getMCPTools(): Record<string, Tool> | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* Get custom tools
|
|
72
|
+
*/
|
|
73
|
+
getCustomTools(): Map<string, unknown> | undefined;
|
|
74
|
+
/**
|
|
75
|
+
* Process direct tools with event emission wrapping
|
|
76
|
+
*/
|
|
77
|
+
private processDirectTools;
|
|
78
|
+
/**
|
|
79
|
+
* Process custom tools from setupToolExecutor
|
|
80
|
+
*/
|
|
81
|
+
private processCustomTools;
|
|
82
|
+
/**
|
|
83
|
+
* Process MCP tools integration
|
|
84
|
+
*/
|
|
85
|
+
private processMCPTools;
|
|
86
|
+
/**
|
|
87
|
+
* Process external MCP tools
|
|
88
|
+
*/
|
|
89
|
+
private processExternalMCPTools;
|
|
90
|
+
/**
|
|
91
|
+
* Create a custom tool from tool definition
|
|
92
|
+
*/
|
|
93
|
+
private createCustomToolFromDefinition;
|
|
94
|
+
/**
|
|
95
|
+
* Create an external MCP tool
|
|
96
|
+
*/
|
|
97
|
+
private createExternalMCPTool;
|
|
98
|
+
}
|