@superatomai/sdk-node 0.0.4 → 0.0.6

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/README.md CHANGED
@@ -5,13 +5,17 @@ A TypeScript/Node.js SDK for building AI-powered data applications with Superato
5
5
  ## Features
6
6
 
7
7
  - **WebSocket Communication** - Real-time bidirectional messaging with automatic reconnection
8
+ - **AI-Powered Component Generation** - Automatically generate dashboard components and visualizations from user questions
9
+ - **Intelligent Text Responses** - LLM-powered conversational responses with SQL query execution and retry logic
10
+ - **Component Matching & Classification** - Smart component selection based on question type and visualization needs
8
11
  - **Collection Handlers** - Register custom data operation handlers (CRUD, queries, mutations)
9
12
  - **User Management** - Built-in authentication and user storage with file-based persistence
10
13
  - **Dashboard & Report Management** - Create and manage dashboards and reports with DSL-based rendering
11
- - **LLM Integration** - Unified interface for Anthropic Claude and Groq models with streaming support
14
+ - **Multi-Provider LLM Integration** - Unified interface for Anthropic Claude and Groq models with automatic fallback
12
15
  - **Thread & UI Block Management** - Organize conversations and UI components with automatic cleanup
13
- - **Log Collection** - Capture and send runtime logs to the UI
14
- - **Prompt Loader** - Load custom prompts from the file system
16
+ - **Log Collection** - Capture and send runtime logs to the UI with configurable log levels
17
+ - **Prompt Loader** - Load and cache custom prompts from the file system with template variable support
18
+ - **Database Schema Management** - Automatic schema documentation generation for LLM context
15
19
  - **Cleanup Service** - Automatic memory management and old data removal
16
20
  - **TypeScript First** - Full type safety with comprehensive type definitions
17
21
 
@@ -79,6 +83,7 @@ interface SuperatomSDKConfig {
79
83
  ANTHROPIC_API_KEY?: string; // Optional: Anthropic API key for LLM
80
84
  GROQ_API_KEY?: string; // Optional: Groq API key for LLM
81
85
  LLM_PROVIDERS?: LLMProvider[]; // Optional: Custom LLM providers
86
+ logLevel?: LogLevel; // Optional: Log level (errors, warnings, info, verbose) (default: 'info')
82
87
  }
83
88
  ```
84
89
 
@@ -87,6 +92,7 @@ interface SuperatomSDKConfig {
87
92
  - `SA_WEBSOCKET_URL` - WebSocket URL (default: `wss://ws.superatom.ai/websocket`)
88
93
  - `ANTHROPIC_API_KEY` - Anthropic API key for Claude models
89
94
  - `GROQ_API_KEY` - Groq API key for open-source models
95
+ - `SUPERATOM_LOG_LEVEL` - Log level for SDK logging (errors, warnings, info, verbose) (default: 'info')
90
96
 
91
97
  ## Core Features
92
98
 
@@ -329,7 +335,216 @@ const jsonResult = await LLM.stream(
329
335
  - With provider: `anthropic/model-name` or `groq/model-name`
330
336
  - Without provider: Defaults to Anthropic
331
337
 
332
- ### 7. Thread & UI Block Management
338
+ ### 7. AI-Powered User Response System
339
+
340
+ The SDK includes a powerful AI system for generating intelligent responses to user questions with two modes: **component generation** and **text responses**.
341
+
342
+ #### Component Generation Mode
343
+
344
+ Automatically match and generate dashboard components based on user questions:
345
+
346
+ ```typescript
347
+ import { get_user_response } from '@superatomai/sdk-node/userResponse';
348
+
349
+ const components = [
350
+ { id: 'sales-chart', name: 'SalesChart', type: 'BarChart', /* ... */ },
351
+ { id: 'kpi-card', name: 'RevenueKPI', type: 'KPICard', /* ... */ },
352
+ // ... more components
353
+ ];
354
+
355
+ const result = await get_user_response(
356
+ 'Show me sales by region',
357
+ components,
358
+ anthropicApiKey,
359
+ groqApiKey,
360
+ ['anthropic', 'groq'], // Provider fallback order
361
+ logCollector,
362
+ conversationHistory,
363
+ 'component' // Component generation mode
364
+ );
365
+
366
+ if (result.success) {
367
+ console.log('Generated component:', result.data.component);
368
+ console.log('Reasoning:', result.data.reasoning);
369
+ }
370
+ ```
371
+
372
+ **Features:**
373
+ - **Question Classification** - Automatically determines question type (analytical, data_modification, general)
374
+ - **Visualization Type Detection** - Identifies required visualization types (charts, tables, KPIs)
375
+ - **Multi-Component Dashboards** - Generates multiple components for comprehensive analysis
376
+ - **Props Modification** - Intelligently modifies component props including SQL queries
377
+ - **SQL Query Validation** - Ensures queries have proper LIMIT clauses and fixes scalar subqueries
378
+
379
+ #### Text Response Mode
380
+
381
+ Generate conversational text responses with SQL query execution:
382
+
383
+ ```typescript
384
+ const result = await get_user_response(
385
+ 'What were the top 5 selling products last month?',
386
+ components,
387
+ anthropicApiKey,
388
+ groqApiKey,
389
+ ['anthropic', 'groq'],
390
+ logCollector,
391
+ conversationHistory,
392
+ 'text', // Text response mode
393
+ (chunk) => {
394
+ // Stream text chunks in real-time
395
+ process.stdout.write(chunk);
396
+ },
397
+ collections // Required for query execution
398
+ );
399
+
400
+ if (result.success) {
401
+ console.log('Text response:', result.data.text);
402
+ console.log('Matched components:', result.data.matchedComponents);
403
+ console.log('Container component:', result.data.component);
404
+ }
405
+ ```
406
+
407
+ **Features:**
408
+ - **SQL Query Execution** - Automatically generates and executes SQL queries via tool calling
409
+ - **Automatic Retry Logic** - Up to 6 retry attempts with query correction on errors
410
+ - **Streaming Responses** - Real-time text streaming with query execution status updates
411
+ - **Component Suggestions** - Parses component suggestions from text and matches with available components
412
+ - **Layout Discovery** - Automatically selects appropriate dashboard layouts based on component metadata
413
+ - **Performance Tracking** - Measures and logs total time taken for request processing
414
+
415
+ #### Using BaseLLM Classes Directly
416
+
417
+ For more control, use the BaseLLM implementations directly:
418
+
419
+ ```typescript
420
+ import { anthropicLLM, groqLLM } from '@superatomai/sdk-node/userResponse';
421
+
422
+ // Classify user question
423
+ const classification = await anthropicLLM.classifyUserQuestion(
424
+ 'Show me sales trends',
425
+ apiKey,
426
+ logCollector,
427
+ conversationHistory
428
+ );
429
+
430
+ console.log('Question type:', classification.questionType);
431
+ console.log('Visualizations needed:', classification.visualizations);
432
+
433
+ // Generate analytical component
434
+ const result = await anthropicLLM.generateAnalyticalComponent(
435
+ 'Show me sales by region',
436
+ components,
437
+ 'BarChart', // Preferred visualization type
438
+ apiKey,
439
+ logCollector,
440
+ conversationHistory
441
+ );
442
+
443
+ // Match existing component
444
+ const matchResult = await anthropicLLM.matchComponent(
445
+ 'Update the sales dashboard',
446
+ components,
447
+ apiKey,
448
+ logCollector,
449
+ conversationHistory
450
+ );
451
+
452
+ // Generate next questions
453
+ const nextQuestions = await anthropicLLM.generateNextQuestions(
454
+ originalPrompt,
455
+ generatedComponent,
456
+ componentData,
457
+ apiKey,
458
+ logCollector,
459
+ conversationHistory
460
+ );
461
+ ```
462
+
463
+ **BaseLLM Methods:**
464
+ - `handleUserRequest()` - Main orchestration method (supports both component and text modes)
465
+ - `classifyUserQuestion()` - Classify question type and identify visualizations
466
+ - `generateAnalyticalComponent()` - Generate single analytical component
467
+ - `generateMultipleAnalyticalComponents()` - Generate multiple components in parallel
468
+ - `matchComponent()` - Match and modify existing component
469
+ - `validateAndModifyProps()` - Validate and modify component props
470
+ - `generateTextResponse()` - Generate text with tool calling support
471
+ - `matchComponentsFromTextResponse()` - Match components from text suggestions
472
+ - `generateNextQuestions()` - Generate follow-up question suggestions
473
+
474
+ ### 8. Prompt Loader System
475
+
476
+ The SDK includes a sophisticated prompt loading system with caching and template variable support:
477
+
478
+ ```typescript
479
+ import { promptLoader } from '@superatomai/sdk-node/userResponse';
480
+
481
+ // Initialize with custom directory (default: .prompts)
482
+ const sdk = new SuperatomSDK({
483
+ apiKey: 'your-api-key',
484
+ projectId: 'your-project-id',
485
+ promptsDir: './my-custom-prompts',
486
+ });
487
+
488
+ // Prompts are automatically loaded and cached on initialization
489
+ // Access prompt cache size
490
+ const cacheSize = promptLoader.getCacheSize();
491
+ console.log(`Loaded ${cacheSize} prompts`);
492
+
493
+ // Load specific prompts with variables
494
+ const prompts = await promptLoader.loadPrompts('classify', {
495
+ USER_PROMPT: userQuestion,
496
+ CONVERSATION_HISTORY: history || 'No previous conversation'
497
+ });
498
+
499
+ console.log('System prompt:', prompts.system);
500
+ console.log('User prompt:', prompts.user);
501
+ ```
502
+
503
+ **Prompt Directory Structure:**
504
+ ```
505
+ .prompts/
506
+ ├── classify/
507
+ │ ├── system.md # System prompt for classification
508
+ │ └── user.md # User prompt template
509
+ ├── match-component/
510
+ │ ├── system.md
511
+ │ └── user.md
512
+ ├── modify-props/
513
+ │ ├── system.md
514
+ │ └── user.md
515
+ ├── text-response/
516
+ │ ├── system.md
517
+ │ └── user.md
518
+ └── match-text-components/
519
+ ├── system.md
520
+ └── user.md
521
+ ```
522
+
523
+ **Template Variables:**
524
+ Variables in prompts are replaced using the `{{VARIABLE_NAME}}` syntax:
525
+
526
+ ```markdown
527
+ # system.md
528
+ You are analyzing this question: {{USER_PROMPT}}
529
+
530
+ Previous conversation:
531
+ {{CONVERSATION_HISTORY}}
532
+
533
+ Available components:
534
+ {{AVAILABLE_COMPONENTS}}
535
+ ```
536
+
537
+ **Built-in Prompt Types:**
538
+ - `classify` - Question classification and visualization type detection
539
+ - `match-component` - Component matching and selection
540
+ - `modify-props` - Props validation and modification
541
+ - `single-component` - Single analytical component generation
542
+ - `text-response` - Text response with tool calling
543
+ - `match-text-components` - Component matching from text suggestions
544
+ - `container-metadata` - Container title and description generation
545
+ - `actions` - Next question generation
546
+
547
+ ### 9. Thread & UI Block Management
333
548
 
334
549
  Organize conversations and UI components:
335
550
 
@@ -379,45 +594,92 @@ threadManager.deleteThread(thread.getId());
379
594
  - `form` - Interactive forms
380
595
  - Custom types as needed
381
596
 
382
- ### 8. Log Collection
597
+ ### 10. Logging System
383
598
 
384
- Capture and send logs to the UI:
599
+ The SDK includes a comprehensive logging system with environment-based log levels for both terminal and UI log collection.
385
600
 
386
- ```typescript
387
- import { UILogCollector } from '@superatomai/sdk-node';
601
+ #### Log Levels
602
+
603
+ The SDK supports hierarchical log levels:
388
604
 
389
- const collector = new UILogCollector();
605
+ - **`errors`** - Only error logs are shown
606
+ - **`warnings`** - Warning and error logs are shown
607
+ - **`info`** - Info, warning, and error logs are shown (default)
608
+ - **`verbose`** - All logs including debug messages are shown
390
609
 
391
- // Start collecting logs
392
- collector.start();
610
+ #### Configuring Log Level
393
611
 
394
- // Logs are automatically captured
395
- console.log('This will be captured');
396
- console.error('Error messages too');
612
+ You can set the log level in three ways:
613
+
614
+ **1. Via environment variable (recommended for deployment):**
615
+
616
+ ```bash
617
+ export SUPERATOM_LOG_LEVEL=verbose
618
+ node your-app.js
619
+ ```
620
+
621
+ **2. Via SDK configuration (overrides environment variable):**
622
+
623
+ ```typescript
624
+ import { SuperatomSDK } from '@superatomai/sdk-node';
397
625
 
398
- // Add custom logs
399
- collector.addLog({
400
- level: 'info',
401
- message: 'Processing data...',
402
- type: 'explanation',
403
- data: { progress: 50 },
626
+ const sdk = new SuperatomSDK({
627
+ apiKey: 'your-api-key',
628
+ projectId: 'your-project-id',
629
+ logLevel: 'verbose', // errors | warnings | info | verbose
404
630
  });
631
+ ```
405
632
 
406
- // Get captured logs
407
- const logs = collector.getLogs();
633
+ **3. Programmatically at runtime:**
634
+
635
+ ```typescript
636
+ import { logger } from '@superatomai/sdk-node';
637
+
638
+ // Change log level at runtime
639
+ logger.setLogLevel('verbose');
408
640
 
409
- // Send logs to UI (via SDK)
410
- const message = collector.createMessage('uiblock-123');
411
- sdk.send(message);
641
+ // Get current log level
642
+ const currentLevel = logger.getLogLevel(); // returns 'verbose'
643
+ ```
412
644
 
413
- // Stop collecting
414
- collector.stop();
645
+ #### Using the Logger
415
646
 
416
- // Clear logs
417
- collector.clear();
647
+ ```typescript
648
+ import { logger } from '@superatomai/sdk-node';
649
+
650
+ // These will be filtered based on the configured log level
651
+ logger.error('Critical error occurred'); // Shown at all levels
652
+ logger.warn('Something might be wrong'); // Hidden when level is 'errors'
653
+ logger.info('Processing completed'); // Hidden when level is 'errors' or 'warnings'
654
+ logger.debug('Detailed debug information'); // Only shown when level is 'verbose'
418
655
  ```
419
656
 
420
- ### 9. Cleanup Service
657
+ #### UI Log Collection
658
+
659
+ The `UILogCollector` also respects the log level configuration. Logs are sent to the frontend and displayed in the terminal based on the configured level.
660
+
661
+ ```typescript
662
+ import { UILogCollector } from '@superatomai/sdk-node';
663
+
664
+ const collector = new UILogCollector(
665
+ clientId,
666
+ (msg) => sdk.send(msg),
667
+ 'uiblock-123'
668
+ );
669
+
670
+ // These logs are filtered based on log level before being sent to UI
671
+ collector.error('Error message'); // Always sent
672
+ collector.warn('Warning message'); // Sent unless level is 'errors'
673
+ collector.info('Info message'); // Sent unless level is 'errors' or 'warnings'
674
+ collector.debug('Debug message'); // Only sent when level is 'verbose'
675
+
676
+ // Get all collected logs
677
+ const logs = collector.getLogs();
678
+ ```
679
+
680
+ **Note:** The log level affects both terminal output and UI log collection, ensuring consistent logging behavior across your application.
681
+
682
+ ### 11. Cleanup Service
421
683
 
422
684
  Automatic memory management for threads and UI blocks:
423
685
 
@@ -458,31 +720,6 @@ STORAGE_CONFIG.UIBLOCK_RETENTION_DAYS = 14;
458
720
  STORAGE_CONFIG.MAX_COMPONENT_DATA_SIZE = 200 * 1024;
459
721
  ```
460
722
 
461
- ### 10. Prompt Loader
462
-
463
- Load custom prompts from the file system:
464
-
465
- ```typescript
466
- // Prompts are automatically loaded from .prompts/ directory
467
- // Or specify custom directory in config:
468
- const sdk = new SuperatomSDK({
469
- apiKey: 'your-api-key',
470
- projectId: 'your-project-id',
471
- promptsDir: './my-prompts',
472
- });
473
-
474
- // Prompts are loaded and cached on initialization
475
- // They can be accessed by handlers internally
476
- ```
477
-
478
- **Prompt File Structure:**
479
- ```
480
- .prompts/
481
- ├── system.txt # System prompts
482
- ├── user-greeting.txt # User greeting prompts
483
- └── analysis.txt # Analysis prompts
484
- ```
485
-
486
723
  ## API Reference
487
724
 
488
725
  ### SuperatomSDK
@@ -629,9 +866,35 @@ import type {
629
866
  IncomingMessage,
630
867
  SuperatomSDKConfig,
631
868
  CollectionHandler,
869
+ CollectionOperation,
632
870
  User,
633
- DSLRendererProps,
871
+ UsersData,
872
+ Component,
873
+ T_RESPONSE,
874
+ LLMProvider,
875
+ LogLevel,
876
+ CapturedLog,
877
+ Action,
634
878
  } from '@superatomai/sdk-node';
879
+
880
+ // Import LLM and utility classes
881
+ import {
882
+ LLM,
883
+ UserManager,
884
+ UILogCollector,
885
+ Thread,
886
+ UIBlock,
887
+ ThreadManager,
888
+ CleanupService,
889
+ logger,
890
+ } from '@superatomai/sdk-node';
891
+
892
+ // Import user response utilities
893
+ import {
894
+ get_user_response,
895
+ anthropicLLM,
896
+ groqLLM,
897
+ } from '@superatomai/sdk-node/userResponse';
635
898
  ```
636
899
 
637
900
  ## Examples
@@ -640,9 +903,13 @@ Check out the [examples](./examples) directory for complete examples:
640
903
  - Basic WebSocket communication
641
904
  - Data collection handlers
642
905
  - User authentication flow
643
- - LLM integration
906
+ - LLM integration with streaming
907
+ - AI-powered component generation
908
+ - Text response with query execution
909
+ - Component matching and classification
644
910
  - Thread management
645
911
  - Dashboard creation
912
+ - Prompt customization
646
913
 
647
914
  ## Development
648
915