@juspay/neurolink 7.6.1 → 7.7.0

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 (136) hide show
  1. package/CHANGELOG.md +9 -4
  2. package/README.md +78 -3
  3. package/dist/cli/commands/config.d.ts +275 -3
  4. package/dist/cli/commands/config.js +121 -0
  5. package/dist/cli/commands/mcp.js +77 -28
  6. package/dist/cli/factories/commandFactory.js +359 -6
  7. package/dist/core/analytics.js +7 -27
  8. package/dist/core/baseProvider.js +43 -4
  9. package/dist/core/constants.d.ts +46 -0
  10. package/dist/core/constants.js +47 -0
  11. package/dist/core/dynamicModels.d.ts +16 -4
  12. package/dist/core/dynamicModels.js +130 -26
  13. package/dist/core/evaluation.js +5 -1
  14. package/dist/core/evaluationProviders.d.ts +6 -2
  15. package/dist/core/evaluationProviders.js +41 -125
  16. package/dist/core/factory.d.ts +5 -0
  17. package/dist/core/factory.js +62 -50
  18. package/dist/core/modelConfiguration.d.ts +246 -0
  19. package/dist/core/modelConfiguration.js +775 -0
  20. package/dist/core/types.d.ts +22 -3
  21. package/dist/core/types.js +5 -1
  22. package/dist/factories/providerRegistry.js +3 -3
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/lib/core/analytics.js +7 -27
  26. package/dist/lib/core/baseProvider.js +43 -4
  27. package/dist/lib/core/constants.d.ts +46 -0
  28. package/dist/lib/core/constants.js +47 -0
  29. package/dist/lib/core/dynamicModels.d.ts +16 -4
  30. package/dist/lib/core/dynamicModels.js +130 -26
  31. package/dist/lib/core/evaluation.js +5 -1
  32. package/dist/lib/core/evaluationProviders.d.ts +6 -2
  33. package/dist/lib/core/evaluationProviders.js +41 -125
  34. package/dist/lib/core/factory.d.ts +5 -0
  35. package/dist/lib/core/factory.js +63 -50
  36. package/dist/lib/core/modelConfiguration.d.ts +246 -0
  37. package/dist/lib/core/modelConfiguration.js +775 -0
  38. package/dist/lib/core/types.d.ts +22 -3
  39. package/dist/lib/core/types.js +5 -1
  40. package/dist/lib/factories/providerRegistry.js +3 -3
  41. package/dist/lib/index.d.ts +1 -1
  42. package/dist/lib/index.js +1 -1
  43. package/dist/lib/mcp/factory.d.ts +5 -5
  44. package/dist/lib/mcp/factory.js +2 -2
  45. package/dist/lib/mcp/servers/utilities/utilityServer.d.ts +1 -1
  46. package/dist/lib/mcp/servers/utilities/utilityServer.js +1 -1
  47. package/dist/lib/mcp/toolRegistry.js +2 -2
  48. package/dist/lib/neurolink.d.ts +168 -12
  49. package/dist/lib/neurolink.js +685 -123
  50. package/dist/lib/providers/anthropic.js +52 -2
  51. package/dist/lib/providers/googleAiStudio.js +4 -0
  52. package/dist/lib/providers/googleVertex.d.ts +75 -9
  53. package/dist/lib/providers/googleVertex.js +365 -46
  54. package/dist/lib/providers/huggingFace.d.ts +52 -11
  55. package/dist/lib/providers/huggingFace.js +180 -42
  56. package/dist/lib/providers/litellm.d.ts +9 -9
  57. package/dist/lib/providers/litellm.js +103 -16
  58. package/dist/lib/providers/ollama.d.ts +52 -17
  59. package/dist/lib/providers/ollama.js +276 -68
  60. package/dist/lib/sdk/toolRegistration.d.ts +42 -0
  61. package/dist/lib/sdk/toolRegistration.js +269 -27
  62. package/dist/lib/telemetry/telemetryService.d.ts +6 -0
  63. package/dist/lib/telemetry/telemetryService.js +38 -3
  64. package/dist/lib/types/contextTypes.d.ts +75 -11
  65. package/dist/lib/types/contextTypes.js +227 -1
  66. package/dist/lib/types/domainTypes.d.ts +62 -0
  67. package/dist/lib/types/domainTypes.js +5 -0
  68. package/dist/lib/types/generateTypes.d.ts +52 -0
  69. package/dist/lib/types/index.d.ts +1 -0
  70. package/dist/lib/types/mcpTypes.d.ts +1 -1
  71. package/dist/lib/types/mcpTypes.js +1 -1
  72. package/dist/lib/types/streamTypes.d.ts +14 -0
  73. package/dist/lib/types/universalProviderOptions.d.ts +1 -1
  74. package/dist/lib/utils/errorHandling.d.ts +142 -0
  75. package/dist/lib/utils/errorHandling.js +316 -0
  76. package/dist/lib/utils/factoryProcessing.d.ts +74 -0
  77. package/dist/lib/utils/factoryProcessing.js +588 -0
  78. package/dist/lib/utils/optionsConversion.d.ts +54 -0
  79. package/dist/lib/utils/optionsConversion.js +126 -0
  80. package/dist/lib/utils/optionsUtils.d.ts +246 -0
  81. package/dist/lib/utils/optionsUtils.js +960 -0
  82. package/dist/lib/utils/providerHealth.d.ts +107 -0
  83. package/dist/lib/utils/providerHealth.js +507 -0
  84. package/dist/lib/utils/providerUtils.d.ts +17 -0
  85. package/dist/lib/utils/providerUtils.js +271 -16
  86. package/dist/lib/utils/timeout.js +1 -1
  87. package/dist/lib/utils/tokenLimits.d.ts +33 -0
  88. package/dist/lib/utils/tokenLimits.js +118 -0
  89. package/dist/mcp/factory.d.ts +5 -5
  90. package/dist/mcp/factory.js +2 -2
  91. package/dist/mcp/servers/utilities/utilityServer.d.ts +1 -1
  92. package/dist/mcp/servers/utilities/utilityServer.js +1 -1
  93. package/dist/mcp/toolRegistry.js +2 -2
  94. package/dist/neurolink.d.ts +168 -12
  95. package/dist/neurolink.js +685 -123
  96. package/dist/providers/anthropic.js +52 -2
  97. package/dist/providers/googleAiStudio.js +4 -0
  98. package/dist/providers/googleVertex.d.ts +75 -9
  99. package/dist/providers/googleVertex.js +365 -46
  100. package/dist/providers/huggingFace.d.ts +52 -11
  101. package/dist/providers/huggingFace.js +181 -43
  102. package/dist/providers/litellm.d.ts +9 -9
  103. package/dist/providers/litellm.js +103 -16
  104. package/dist/providers/ollama.d.ts +52 -17
  105. package/dist/providers/ollama.js +276 -68
  106. package/dist/sdk/toolRegistration.d.ts +42 -0
  107. package/dist/sdk/toolRegistration.js +269 -27
  108. package/dist/telemetry/telemetryService.d.ts +6 -0
  109. package/dist/telemetry/telemetryService.js +38 -3
  110. package/dist/types/contextTypes.d.ts +75 -11
  111. package/dist/types/contextTypes.js +227 -2
  112. package/dist/types/domainTypes.d.ts +62 -0
  113. package/dist/types/domainTypes.js +5 -0
  114. package/dist/types/generateTypes.d.ts +52 -0
  115. package/dist/types/index.d.ts +1 -0
  116. package/dist/types/mcpTypes.d.ts +1 -1
  117. package/dist/types/mcpTypes.js +1 -1
  118. package/dist/types/streamTypes.d.ts +14 -0
  119. package/dist/types/universalProviderOptions.d.ts +1 -1
  120. package/dist/types/universalProviderOptions.js +0 -1
  121. package/dist/utils/errorHandling.d.ts +142 -0
  122. package/dist/utils/errorHandling.js +316 -0
  123. package/dist/utils/factoryProcessing.d.ts +74 -0
  124. package/dist/utils/factoryProcessing.js +588 -0
  125. package/dist/utils/optionsConversion.d.ts +54 -0
  126. package/dist/utils/optionsConversion.js +126 -0
  127. package/dist/utils/optionsUtils.d.ts +246 -0
  128. package/dist/utils/optionsUtils.js +960 -0
  129. package/dist/utils/providerHealth.d.ts +107 -0
  130. package/dist/utils/providerHealth.js +507 -0
  131. package/dist/utils/providerUtils.d.ts +17 -0
  132. package/dist/utils/providerUtils.js +271 -16
  133. package/dist/utils/timeout.js +1 -1
  134. package/dist/utils/tokenLimits.d.ts +33 -0
  135. package/dist/utils/tokenLimits.js +118 -0
  136. package/package.json +2 -2
@@ -45,19 +45,41 @@ export class AnthropicProvider extends BaseProvider {
45
45
  }
46
46
  handleProviderError(error) {
47
47
  if (error instanceof TimeoutError) {
48
- return new Error(`Anthropic request timed out: ${error.message}`);
48
+ return new Error(`Anthropic request timed out after ${error.timeout}ms: ${error.message}`);
49
49
  }
50
50
  const errorRecord = error;
51
+ // Handle API key errors
51
52
  if ((typeof errorRecord?.message === "string" &&
52
53
  errorRecord.message.includes("API_KEY_INVALID")) ||
53
54
  (typeof errorRecord?.message === "string" &&
54
55
  errorRecord.message.includes("Invalid API key"))) {
55
56
  return new Error("Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable.");
56
57
  }
58
+ // Handle rate limiting errors
57
59
  if (typeof errorRecord?.message === "string" &&
58
- errorRecord.message.includes("rate limit")) {
60
+ (errorRecord.message.includes("rate limit") ||
61
+ errorRecord.message.includes("too_many_requests") ||
62
+ errorRecord.message.includes("429"))) {
59
63
  return new Error("Anthropic rate limit exceeded. Please try again later.");
60
64
  }
65
+ // Handle connection errors
66
+ if (typeof errorRecord?.message === "string" &&
67
+ (errorRecord.message.includes("ECONNRESET") ||
68
+ errorRecord.message.includes("ENOTFOUND") ||
69
+ errorRecord.message.includes("ECONNREFUSED") ||
70
+ errorRecord.message.includes("network") ||
71
+ errorRecord.message.includes("connection"))) {
72
+ return new Error("Anthropic API connection error. Please check your internet connection and try again.");
73
+ }
74
+ // Handle server errors
75
+ if (typeof errorRecord?.message === "string" &&
76
+ (errorRecord.message.includes("500") ||
77
+ errorRecord.message.includes("502") ||
78
+ errorRecord.message.includes("503") ||
79
+ errorRecord.message.includes("504") ||
80
+ errorRecord.message.includes("server error"))) {
81
+ return new Error("Anthropic API server error. Please try again in a few moments.");
82
+ }
61
83
  const message = typeof errorRecord?.message === "string"
62
84
  ? errorRecord.message
63
85
  : "Unknown error";
@@ -76,12 +98,23 @@ export class AnthropicProvider extends BaseProvider {
76
98
  const timeout = this.getTimeout(options);
77
99
  const timeoutController = createTimeoutController(timeout, this.providerName, "stream");
78
100
  try {
101
+ // ✅ Get tools for streaming (same as generate method)
102
+ const shouldUseTools = !options.disableTools && this.supportsTools();
103
+ const tools = shouldUseTools ? await this.getAllTools() : {};
104
+ // 🔧 CRITICAL FIX: Vercel AI SDK streamText() hangs with tools and maxSteps > 1
105
+ // For stream-focused SDK, we need reliable streaming, so avoid the hanging case
106
+ if (shouldUseTools && Object.keys(tools).length > 0) {
107
+ throw new Error("Vercel AI SDK streamText() limitation with tools - falling back to synthetic streaming");
108
+ }
79
109
  const result = await streamText({
80
110
  model: this.model,
81
111
  prompt: options.input.text,
82
112
  system: options.systemPrompt || undefined,
83
113
  temperature: options.temperature,
84
114
  maxTokens: options.maxTokens || DEFAULT_MAX_TOKENS,
115
+ tools: {}, // 🔧 Force empty tools for real streaming to avoid hanging
116
+ maxSteps: 1, // 🔧 Force single step for real streaming
117
+ toolChoice: "none", // 🔧 Force no tools for real streaming
85
118
  abortSignal: timeoutController?.controller.signal,
86
119
  });
87
120
  timeoutController?.cleanup();
@@ -91,10 +124,27 @@ export class AnthropicProvider extends BaseProvider {
91
124
  yield { content: chunk };
92
125
  }
93
126
  };
127
+ // ✅ Note: Vercel AI SDK's streamText() method limitations with tools
128
+ // The streamText() function doesn't provide the same tool result access as generateText()
129
+ // For full tool support, the BaseProvider will fall back to synthetic streaming when needed
130
+ const toolCalls = [];
131
+ const toolResults = [];
132
+ const usage = await result.usage;
133
+ const finishReason = await result.finishReason;
94
134
  return {
95
135
  stream: transformedStream(),
96
136
  provider: this.providerName,
97
137
  model: this.modelName,
138
+ toolCalls, // ✅ Include tool calls in stream result
139
+ toolResults, // ✅ Include tool results in stream result
140
+ usage: usage
141
+ ? {
142
+ inputTokens: usage.promptTokens || 0,
143
+ outputTokens: usage.completionTokens || 0,
144
+ totalTokens: usage.totalTokens || 0,
145
+ }
146
+ : undefined,
147
+ finishReason: finishReason || undefined,
98
148
  };
99
149
  }
100
150
  catch (error) {
@@ -65,6 +65,10 @@ export class GoogleAIStudioProvider extends BaseProvider {
65
65
  this.validateStreamOptions(options);
66
66
  const startTime = Date.now();
67
67
  const apiKey = this.getApiKey();
68
+ // Ensure environment variable is set for @ai-sdk/google
69
+ if (!process.env.GOOGLE_GENERATIVE_AI_API_KEY) {
70
+ process.env.GOOGLE_GENERATIVE_AI_API_KEY = apiKey;
71
+ }
68
72
  const google = createGoogleGenerativeAI({ apiKey });
69
73
  const model = google(this.modelName);
70
74
  const timeout = this.getTimeout(options);
@@ -1,37 +1,66 @@
1
1
  import type { ZodType, ZodTypeDef } from "zod";
2
- import { type Schema, type LanguageModelV1 } from "ai";
2
+ import { type Schema, type LanguageModelV1, type LanguageModel } from "ai";
3
3
  import type { AIProviderName } from "../core/types.js";
4
4
  import type { StreamOptions, StreamResult } from "../types/streamTypes.js";
5
5
  import { BaseProvider } from "../core/baseProvider.js";
6
6
  /**
7
7
  * Google Vertex AI Provider v2 - BaseProvider Implementation
8
8
  *
9
- * PHASE 3.5: Simple BaseProvider wrap around existing @ai-sdk/google-vertex implementation
10
- *
11
9
  * Features:
12
10
  * - Extends BaseProvider for shared functionality
13
11
  * - Preserves existing Google Cloud authentication
14
12
  * - Maintains Anthropic model support via dynamic imports
15
- * - Uses pre-initialized Vertex instance for efficiency
13
+ * - Fresh model creation for each request
16
14
  * - Enhanced error handling with setup guidance
15
+ * - Tool registration and context management
17
16
  */
18
17
  export declare class GoogleVertexProvider extends BaseProvider {
19
- private vertex;
20
- private model;
21
18
  private projectId;
22
19
  private location;
23
- private cachedAnthropicModel;
20
+ private registeredTools;
21
+ private toolContext;
22
+ private static modelConfigCache;
23
+ private static modelConfigCacheTime;
24
+ private static readonly CACHE_DURATION;
25
+ private static readonly MAX_CACHE_SIZE;
26
+ private static maxTokensCache;
27
+ private static maxTokensCacheTime;
24
28
  constructor(modelName?: string, sdk?: unknown);
25
29
  protected getProviderName(): AIProviderName;
26
30
  protected getDefaultModel(): string;
27
31
  /**
28
32
  * Returns the Vercel AI SDK model instance for Google Vertex
29
- * Handles both Google and Anthropic models
33
+ * Creates fresh model instances for each request
34
+ */
35
+ protected getAISDKModel(): Promise<LanguageModel>;
36
+ /**
37
+ * Gets the appropriate model instance (Google or Anthropic)
38
+ * Creates fresh instances for each request to ensure proper authentication
30
39
  */
31
- protected getAISDKModel(): Promise<LanguageModelV1>;
40
+ private getModel;
32
41
  protected executeStream(options: StreamOptions, analysisSchema?: ZodType<unknown, ZodTypeDef, unknown> | Schema<unknown>): Promise<StreamResult>;
33
42
  protected handleProviderError(error: unknown): Error;
34
43
  private validateStreamOptions;
44
+ /**
45
+ * Memory-safe cache management for model configurations
46
+ * Implements LRU eviction to prevent memory leaks in long-running processes
47
+ */
48
+ private static evictLRUCacheEntries;
49
+ /**
50
+ * Access and refresh cache entry (moves to end for LRU)
51
+ */
52
+ private static accessCacheEntry;
53
+ /**
54
+ * Memory-safe cached check for whether maxTokens should be set for the given model
55
+ * Optimized for streaming performance with LRU eviction to prevent memory leaks
56
+ */
57
+ private shouldSetMaxTokensCached;
58
+ /**
59
+ * Memory-safe check if model has maxTokens issues using configuration-based approach
60
+ * This replaces hardcoded model-specific logic with configurable behavior
61
+ * Includes LRU caching to avoid repeated configuration lookups during streaming
62
+ */
63
+ private modelHasMaxTokensIssues;
35
64
  /**
36
65
  * Check if Anthropic models are available
37
66
  * @returns Promise<boolean> indicating if Anthropic support is available
@@ -39,9 +68,46 @@ export declare class GoogleVertexProvider extends BaseProvider {
39
68
  hasAnthropicSupport(): Promise<boolean>;
40
69
  /**
41
70
  * Create an Anthropic model instance if available
71
+ * Uses fresh vertex settings for each request
42
72
  * @param modelName Anthropic model name (e.g., 'claude-3-sonnet@20240229')
43
73
  * @returns LanguageModelV1 instance or null if not available
44
74
  */
45
75
  createAnthropicModel(modelName: string): Promise<LanguageModelV1 | null>;
76
+ /**
77
+ * Register a tool with the AI provider
78
+ * @param name The name of the tool
79
+ * @param schema The Zod schema defining the tool's parameters
80
+ * @param description A description of what the tool does
81
+ * @param handler The function to execute when the tool is called
82
+ */
83
+ registerTool(name: string, schema: ZodType<unknown>, description: string, handler: (params: Record<string, unknown>) => Promise<unknown>): void;
84
+ /**
85
+ * Set the context for tool execution
86
+ * @param context The context to use for tool execution
87
+ */
88
+ setToolContext(context: Record<string, unknown>): void;
89
+ /**
90
+ * Get the current tool execution context
91
+ * @returns The current tool execution context
92
+ */
93
+ getToolContext(): Record<string, unknown>;
94
+ /**
95
+ * Clear all static caches - useful for testing and memory cleanup
96
+ * Public method to allow external cache management
97
+ */
98
+ static clearCaches(): void;
99
+ /**
100
+ * Get cache statistics for monitoring and debugging
101
+ */
102
+ static getCacheStats(): {
103
+ modelConfigCacheSize: number;
104
+ maxTokensCacheSize: number;
105
+ maxCacheSize: number;
106
+ cacheAge: {
107
+ modelConfig: number;
108
+ maxTokens: number;
109
+ };
110
+ };
46
111
  }
47
112
  export default GoogleVertexProvider;
113
+ export { GoogleVertexProvider as GoogleVertexAI };