@juspay/neurolink 1.2.3 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { GoogleVertexAI, AmazonBedrock, OpenAI } from '../providers/index.js';
1
+ import { GoogleVertexAI, AmazonBedrock, OpenAI, AnthropicProvider, AzureOpenAIProvider } from '../providers/index.js';
2
2
  import { getBestProvider } from '../utils/providerUtils.js';
3
3
  const componentIdentifier = 'aiProviderFactory';
4
4
  /**
@@ -34,8 +34,16 @@ export class AIProviderFactory {
34
34
  case 'gpt':
35
35
  provider = new OpenAI(modelName);
36
36
  break;
37
+ case 'anthropic':
38
+ case 'claude':
39
+ provider = new AnthropicProvider();
40
+ break;
41
+ case 'azure':
42
+ case 'azure-openai':
43
+ provider = new AzureOpenAIProvider();
44
+ break;
37
45
  default:
38
- throw new Error(`Unknown provider: ${providerName}. Supported providers: vertex, bedrock, openai`);
46
+ throw new Error(`Unknown provider: ${providerName}. Supported providers: vertex, bedrock, openai, anthropic, azure`);
39
47
  }
40
48
  console.log(`[${functionTag}] Provider creation succeeded`, {
41
49
  providerName,
@@ -6,7 +6,9 @@ import type { StreamTextResult, ToolSet, Schema, GenerateTextResult } from 'ai';
6
6
  export declare enum AIProviderName {
7
7
  BEDROCK = "bedrock",
8
8
  OPENAI = "openai",
9
- VERTEX = "vertex"
9
+ VERTEX = "vertex",
10
+ ANTHROPIC = "anthropic",
11
+ AZURE = "azure"
10
12
  }
11
13
  /**
12
14
  * Supported Models for Amazon Bedrock
@@ -6,6 +6,8 @@ export var AIProviderName;
6
6
  AIProviderName["BEDROCK"] = "bedrock";
7
7
  AIProviderName["OPENAI"] = "openai";
8
8
  AIProviderName["VERTEX"] = "vertex";
9
+ AIProviderName["ANTHROPIC"] = "anthropic";
10
+ AIProviderName["AZURE"] = "azure";
9
11
  })(AIProviderName || (AIProviderName = {}));
10
12
  /**
11
13
  * Supported Models for Amazon Bedrock
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ import { AIProviderFactory } from './core/factory.js';
10
10
  export { AIProviderFactory };
11
11
  export type { AIProvider, AIProviderName, ProviderConfig, StreamingOptions, ProviderAttempt, SupportedModelName } from './core/types.js';
12
12
  export { BedrockModels, OpenAIModels, VertexModels, DEFAULT_PROVIDER_CONFIGS } from './core/types.js';
13
- export { GoogleVertexAI, AmazonBedrock, OpenAI } from './providers/index.js';
13
+ export { GoogleVertexAI, AmazonBedrock, OpenAI, AnthropicProvider, AzureOpenAIProvider } from './providers/index.js';
14
14
  export type { ProviderName } from './providers/index.js';
15
15
  export { PROVIDERS, AVAILABLE_PROVIDERS } from './providers/index.js';
16
16
  export { getBestProvider, getAvailableProviders, isValidProvider } from './utils/providerUtils.js';
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ export { AIProviderFactory };
12
12
  // Model enums
13
13
  export { BedrockModels, OpenAIModels, VertexModels, DEFAULT_PROVIDER_CONFIGS } from './core/types.js';
14
14
  // Provider exports
15
- export { GoogleVertexAI, AmazonBedrock, OpenAI } from './providers/index.js';
15
+ export { GoogleVertexAI, AmazonBedrock, OpenAI, AnthropicProvider, AzureOpenAIProvider } from './providers/index.js';
16
16
  export { PROVIDERS, AVAILABLE_PROVIDERS } from './providers/index.js';
17
17
  // Utility exports
18
18
  export { getBestProvider, getAvailableProviders, isValidProvider } from './utils/providerUtils.js';
@@ -7,7 +7,7 @@
7
7
  import type { AIProviderName } from './core/types.js';
8
8
  export interface TextGenerationOptions {
9
9
  prompt: string;
10
- provider?: 'openai' | 'bedrock' | 'vertex' | 'auto';
10
+ provider?: 'openai' | 'bedrock' | 'vertex' | 'anthropic' | 'azure' | 'auto';
11
11
  temperature?: number;
12
12
  maxTokens?: number;
13
13
  systemPrompt?: string;
@@ -15,7 +15,7 @@ export interface TextGenerationOptions {
15
15
  }
16
16
  export interface StreamTextOptions {
17
17
  prompt: string;
18
- provider?: 'openai' | 'bedrock' | 'vertex' | 'auto';
18
+ provider?: 'openai' | 'bedrock' | 'vertex' | 'anthropic' | 'azure' | 'auto';
19
19
  temperature?: number;
20
20
  maxTokens?: number;
21
21
  systemPrompt?: string;
package/dist/neurolink.js CHANGED
@@ -34,7 +34,7 @@ export class NeuroLink {
34
34
  }
35
35
  const responseTime = Date.now() - startTime;
36
36
  return {
37
- content: result.text,
37
+ content: result.content || result.text || '',
38
38
  provider: providerName,
39
39
  usage: result.usage,
40
40
  responseTime
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Anthropic AI Provider (Direct API)
3
+ *
4
+ * Direct integration with Anthropic's Claude models via their native API.
5
+ * Supports Claude 3.5 Sonnet, Claude 3.5 Haiku, and Claude 3 Opus.
6
+ */
7
+ import type { AIProvider, TextGenerationOptions, StreamTextOptions } from '../core/types.js';
8
+ import { AIProviderName } from '../core/types.js';
9
+ export declare class AnthropicProvider implements AIProvider {
10
+ readonly name: AIProviderName;
11
+ private apiKey;
12
+ private baseURL;
13
+ private defaultModel;
14
+ constructor();
15
+ private getApiKey;
16
+ private getModel;
17
+ private makeRequest;
18
+ generateText(optionsOrPrompt: TextGenerationOptions | string, schema?: any): Promise<any>;
19
+ streamText(optionsOrPrompt: StreamTextOptions | string, schema?: any): Promise<any>;
20
+ private createAsyncIterable;
21
+ generateTextStream(optionsOrPrompt: StreamTextOptions | string): AsyncGenerator<any, void, unknown>;
22
+ testConnection(): Promise<{
23
+ success: boolean;
24
+ error?: string;
25
+ responseTime?: number;
26
+ }>;
27
+ isConfigured(): boolean;
28
+ getRequiredConfig(): string[];
29
+ getOptionalConfig(): string[];
30
+ getModels(): string[];
31
+ supportsStreaming(): boolean;
32
+ supportsSchema(): boolean;
33
+ getCapabilities(): string[];
34
+ }
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Anthropic AI Provider (Direct API)
3
+ *
4
+ * Direct integration with Anthropic's Claude models via their native API.
5
+ * Supports Claude 3.5 Sonnet, Claude 3.5 Haiku, and Claude 3 Opus.
6
+ */
7
+ import { AIProviderName } from '../core/types.js';
8
+ export class AnthropicProvider {
9
+ name = AIProviderName.ANTHROPIC;
10
+ apiKey;
11
+ baseURL;
12
+ defaultModel;
13
+ constructor() {
14
+ this.apiKey = this.getApiKey();
15
+ this.baseURL = process.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com';
16
+ this.defaultModel = process.env.ANTHROPIC_MODEL || 'claude-3-5-sonnet-20241022';
17
+ console.log(`[AnthropicProvider] Initialized with model: ${this.defaultModel}`);
18
+ }
19
+ getApiKey() {
20
+ const apiKey = process.env.ANTHROPIC_API_KEY;
21
+ if (!apiKey) {
22
+ throw new Error('ANTHROPIC_API_KEY environment variable is required');
23
+ }
24
+ return apiKey;
25
+ }
26
+ getModel() {
27
+ return this.defaultModel;
28
+ }
29
+ async makeRequest(endpoint, body, stream = false) {
30
+ const url = `${this.baseURL}/v1/${endpoint}`;
31
+ const headers = {
32
+ 'Content-Type': 'application/json',
33
+ 'x-api-key': this.apiKey,
34
+ 'anthropic-version': '2023-06-01',
35
+ 'anthropic-dangerous-direct-browser-access': 'true' // Required for browser usage
36
+ };
37
+ console.log(`[AnthropicProvider.makeRequest] ${stream ? 'Streaming' : 'Non-streaming'} request to ${url}`);
38
+ console.log(`[AnthropicProvider.makeRequest] Model: ${body.model}, Max tokens: ${body.max_tokens}`);
39
+ const response = await fetch(url, {
40
+ method: 'POST',
41
+ headers,
42
+ body: JSON.stringify(body)
43
+ });
44
+ if (!response.ok) {
45
+ const errorText = await response.text();
46
+ console.error(`[AnthropicProvider.makeRequest] API error ${response.status}: ${errorText}`);
47
+ throw new Error(`Anthropic API error ${response.status}: ${errorText}`);
48
+ }
49
+ return response;
50
+ }
51
+ async generateText(optionsOrPrompt, schema) {
52
+ console.log('[AnthropicProvider.generateText] Starting text generation');
53
+ // Parse parameters with backward compatibility
54
+ const options = typeof optionsOrPrompt === 'string'
55
+ ? { prompt: optionsOrPrompt }
56
+ : optionsOrPrompt;
57
+ const { prompt, temperature = 0.7, maxTokens = 500, systemPrompt = 'You are Claude, an AI assistant created by Anthropic. You are helpful, harmless, and honest.' } = options;
58
+ console.log(`[AnthropicProvider.generateText] Prompt: "${prompt.substring(0, 100)}...", Temperature: ${temperature}, Max tokens: ${maxTokens}`);
59
+ const requestBody = {
60
+ model: this.getModel(),
61
+ max_tokens: maxTokens,
62
+ messages: [
63
+ {
64
+ role: 'user',
65
+ content: prompt
66
+ }
67
+ ],
68
+ temperature,
69
+ system: systemPrompt
70
+ };
71
+ try {
72
+ const response = await this.makeRequest('messages', requestBody);
73
+ const data = await response.json();
74
+ console.log(`[AnthropicProvider.generateText] Success. Generated ${data.usage.output_tokens} tokens`);
75
+ const content = data.content.map(block => block.text).join('');
76
+ return {
77
+ content,
78
+ provider: this.name,
79
+ model: data.model,
80
+ usage: {
81
+ promptTokens: data.usage.input_tokens,
82
+ completionTokens: data.usage.output_tokens,
83
+ totalTokens: data.usage.input_tokens + data.usage.output_tokens
84
+ },
85
+ finishReason: data.stop_reason
86
+ };
87
+ }
88
+ catch (error) {
89
+ console.error('[AnthropicProvider.generateText] Error:', error);
90
+ throw error;
91
+ }
92
+ }
93
+ async streamText(optionsOrPrompt, schema) {
94
+ console.log('[AnthropicProvider.streamText] Starting text streaming');
95
+ // Parse parameters with backward compatibility
96
+ const options = typeof optionsOrPrompt === 'string'
97
+ ? { prompt: optionsOrPrompt }
98
+ : optionsOrPrompt;
99
+ const { prompt, temperature = 0.7, maxTokens = 500, systemPrompt = 'You are Claude, an AI assistant created by Anthropic. You are helpful, harmless, and honest.' } = options;
100
+ console.log(`[AnthropicProvider.streamText] Streaming prompt: "${prompt.substring(0, 100)}..."`);
101
+ const requestBody = {
102
+ model: this.getModel(),
103
+ max_tokens: maxTokens,
104
+ messages: [
105
+ {
106
+ role: 'user',
107
+ content: prompt
108
+ }
109
+ ],
110
+ temperature,
111
+ system: systemPrompt,
112
+ stream: true
113
+ };
114
+ try {
115
+ const response = await this.makeRequest('messages', requestBody, true);
116
+ if (!response.body) {
117
+ throw new Error('No response body received');
118
+ }
119
+ // Return a StreamTextResult-like object
120
+ return {
121
+ textStream: this.createAsyncIterable(response.body),
122
+ text: '',
123
+ usage: { promptTokens: 0, completionTokens: 0, totalTokens: 0 },
124
+ finishReason: 'end_turn'
125
+ };
126
+ }
127
+ catch (error) {
128
+ console.error('[AnthropicProvider.streamText] Error:', error);
129
+ throw error;
130
+ }
131
+ }
132
+ async *createAsyncIterable(body) {
133
+ const reader = body.getReader();
134
+ const decoder = new TextDecoder();
135
+ let buffer = '';
136
+ try {
137
+ while (true) {
138
+ const { done, value } = await reader.read();
139
+ if (done)
140
+ break;
141
+ buffer += decoder.decode(value, { stream: true });
142
+ const lines = buffer.split('\n');
143
+ buffer = lines.pop() || '';
144
+ for (const line of lines) {
145
+ if (line.trim() === '')
146
+ continue;
147
+ if (line.startsWith('data: ')) {
148
+ const data = line.slice(6);
149
+ if (data.trim() === '[DONE]')
150
+ continue;
151
+ try {
152
+ const chunk = JSON.parse(data);
153
+ // Extract text content from different chunk types
154
+ if (chunk.type === 'content_block_delta' && chunk.delta?.text) {
155
+ yield chunk.delta.text;
156
+ }
157
+ }
158
+ catch (parseError) {
159
+ console.warn('[AnthropicProvider.createAsyncIterable] Failed to parse chunk:', parseError);
160
+ continue;
161
+ }
162
+ }
163
+ }
164
+ }
165
+ }
166
+ finally {
167
+ reader.releaseLock();
168
+ }
169
+ }
170
+ async *generateTextStream(optionsOrPrompt) {
171
+ console.log('[AnthropicProvider.generateTextStream] Starting text streaming');
172
+ // Parse parameters with backward compatibility
173
+ const options = typeof optionsOrPrompt === 'string'
174
+ ? { prompt: optionsOrPrompt }
175
+ : optionsOrPrompt;
176
+ const { prompt, temperature = 0.7, maxTokens = 500, systemPrompt = 'You are Claude, an AI assistant created by Anthropic. You are helpful, harmless, and honest.' } = options;
177
+ console.log(`[AnthropicProvider.generateTextStream] Streaming prompt: "${prompt.substring(0, 100)}..."`);
178
+ const requestBody = {
179
+ model: this.getModel(),
180
+ max_tokens: maxTokens,
181
+ messages: [
182
+ {
183
+ role: 'user',
184
+ content: prompt
185
+ }
186
+ ],
187
+ temperature,
188
+ system: systemPrompt,
189
+ stream: true
190
+ };
191
+ try {
192
+ const response = await this.makeRequest('messages', requestBody, true);
193
+ if (!response.body) {
194
+ throw new Error('No response body received');
195
+ }
196
+ const reader = response.body.getReader();
197
+ const decoder = new TextDecoder();
198
+ let buffer = '';
199
+ try {
200
+ while (true) {
201
+ const { done, value } = await reader.read();
202
+ if (done)
203
+ break;
204
+ buffer += decoder.decode(value, { stream: true });
205
+ const lines = buffer.split('\n');
206
+ buffer = lines.pop() || '';
207
+ for (const line of lines) {
208
+ if (line.trim() === '')
209
+ continue;
210
+ if (line.startsWith('data: ')) {
211
+ const data = line.slice(6);
212
+ if (data.trim() === '[DONE]')
213
+ continue;
214
+ try {
215
+ const chunk = JSON.parse(data);
216
+ // Extract text content from different chunk types
217
+ if (chunk.type === 'content_block_delta' && chunk.delta?.text) {
218
+ yield {
219
+ content: chunk.delta.text,
220
+ provider: this.name,
221
+ model: this.getModel()
222
+ };
223
+ }
224
+ }
225
+ catch (parseError) {
226
+ console.warn('[AnthropicProvider.generateTextStream] Failed to parse chunk:', parseError);
227
+ continue;
228
+ }
229
+ }
230
+ }
231
+ }
232
+ }
233
+ finally {
234
+ reader.releaseLock();
235
+ }
236
+ console.log('[AnthropicProvider.generateTextStream] Streaming completed');
237
+ }
238
+ catch (error) {
239
+ console.error('[AnthropicProvider.generateTextStream] Error:', error);
240
+ throw error;
241
+ }
242
+ }
243
+ async testConnection() {
244
+ console.log('[AnthropicProvider.testConnection] Testing connection to Anthropic API');
245
+ const startTime = Date.now();
246
+ try {
247
+ await this.generateText({
248
+ prompt: 'Hello',
249
+ maxTokens: 5
250
+ });
251
+ const responseTime = Date.now() - startTime;
252
+ console.log(`[AnthropicProvider.testConnection] Connection test successful (${responseTime}ms)`);
253
+ return {
254
+ success: true,
255
+ responseTime
256
+ };
257
+ }
258
+ catch (error) {
259
+ const responseTime = Date.now() - startTime;
260
+ console.error(`[AnthropicProvider.testConnection] Connection test failed (${responseTime}ms):`, error);
261
+ return {
262
+ success: false,
263
+ error: error instanceof Error ? error.message : 'Unknown error',
264
+ responseTime
265
+ };
266
+ }
267
+ }
268
+ isConfigured() {
269
+ try {
270
+ this.getApiKey();
271
+ return true;
272
+ }
273
+ catch {
274
+ return false;
275
+ }
276
+ }
277
+ getRequiredConfig() {
278
+ return ['ANTHROPIC_API_KEY'];
279
+ }
280
+ getOptionalConfig() {
281
+ return ['ANTHROPIC_MODEL', 'ANTHROPIC_BASE_URL'];
282
+ }
283
+ getModels() {
284
+ return [
285
+ 'claude-3-5-sonnet-20241022',
286
+ 'claude-3-5-haiku-20241022',
287
+ 'claude-3-opus-20240229',
288
+ 'claude-3-sonnet-20240229',
289
+ 'claude-3-haiku-20240307'
290
+ ];
291
+ }
292
+ supportsStreaming() {
293
+ return true;
294
+ }
295
+ supportsSchema() {
296
+ return false; // Anthropic doesn't have native JSON schema support like OpenAI
297
+ }
298
+ getCapabilities() {
299
+ return [
300
+ 'text-generation',
301
+ 'streaming',
302
+ 'conversation',
303
+ 'system-prompts',
304
+ 'long-context' // Claude models support up to 200k tokens
305
+ ];
306
+ }
307
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Azure OpenAI Provider
3
+ *
4
+ * Enterprise-grade OpenAI integration through Microsoft Azure.
5
+ * Supports all OpenAI models with enhanced security and compliance.
6
+ */
7
+ import type { AIProvider, TextGenerationOptions, StreamTextOptions } from '../core/types.js';
8
+ import { AIProviderName } from '../core/types.js';
9
+ export declare class AzureOpenAIProvider implements AIProvider {
10
+ readonly name: AIProviderName;
11
+ private apiKey;
12
+ private endpoint;
13
+ private deploymentId;
14
+ private apiVersion;
15
+ constructor();
16
+ private getApiKey;
17
+ private getEndpoint;
18
+ private getDeploymentId;
19
+ private getApiUrl;
20
+ private makeRequest;
21
+ generateText(optionsOrPrompt: TextGenerationOptions | string, schema?: any): Promise<any>;
22
+ streamText(optionsOrPrompt: StreamTextOptions | string, schema?: any): Promise<any>;
23
+ private createAsyncIterable;
24
+ generateTextStream(optionsOrPrompt: StreamTextOptions | string): AsyncGenerator<any, void, unknown>;
25
+ testConnection(): Promise<{
26
+ success: boolean;
27
+ error?: string;
28
+ responseTime?: number;
29
+ }>;
30
+ isConfigured(): boolean;
31
+ getRequiredConfig(): string[];
32
+ getOptionalConfig(): string[];
33
+ getModels(): string[];
34
+ supportsStreaming(): boolean;
35
+ supportsSchema(): boolean;
36
+ getCapabilities(): string[];
37
+ }