@superatomai/sdk-node 0.0.39 → 0.0.41

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.d.mts CHANGED
@@ -615,6 +615,68 @@ declare const IncomingMessageSchema: z.ZodObject<{
615
615
  payload?: unknown;
616
616
  }>;
617
617
  type IncomingMessage = z.infer<typeof IncomingMessageSchema>;
618
+ declare const ComponentSchema: z.ZodObject<{
619
+ id: z.ZodString;
620
+ name: z.ZodString;
621
+ displayName: z.ZodOptional<z.ZodString>;
622
+ isDisplayComp: z.ZodOptional<z.ZodBoolean>;
623
+ type: z.ZodString;
624
+ description: z.ZodString;
625
+ props: z.ZodObject<{
626
+ query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>;
627
+ title: z.ZodOptional<z.ZodString>;
628
+ description: z.ZodOptional<z.ZodString>;
629
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
630
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
631
+ }, "strip", z.ZodTypeAny, {
632
+ description?: string | undefined;
633
+ query?: string | {} | undefined;
634
+ title?: string | undefined;
635
+ config?: Record<string, unknown> | undefined;
636
+ actions?: any[] | undefined;
637
+ }, {
638
+ description?: string | undefined;
639
+ query?: string | {} | undefined;
640
+ title?: string | undefined;
641
+ config?: Record<string, unknown> | undefined;
642
+ actions?: any[] | undefined;
643
+ }>;
644
+ category: z.ZodOptional<z.ZodString>;
645
+ keywords: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
646
+ }, "strip", z.ZodTypeAny, {
647
+ id: string;
648
+ type: string;
649
+ name: string;
650
+ description: string;
651
+ props: {
652
+ description?: string | undefined;
653
+ query?: string | {} | undefined;
654
+ title?: string | undefined;
655
+ config?: Record<string, unknown> | undefined;
656
+ actions?: any[] | undefined;
657
+ };
658
+ displayName?: string | undefined;
659
+ isDisplayComp?: boolean | undefined;
660
+ category?: string | undefined;
661
+ keywords?: string[] | undefined;
662
+ }, {
663
+ id: string;
664
+ type: string;
665
+ name: string;
666
+ description: string;
667
+ props: {
668
+ description?: string | undefined;
669
+ query?: string | {} | undefined;
670
+ title?: string | undefined;
671
+ config?: Record<string, unknown> | undefined;
672
+ actions?: any[] | undefined;
673
+ };
674
+ displayName?: string | undefined;
675
+ isDisplayComp?: boolean | undefined;
676
+ category?: string | undefined;
677
+ keywords?: string[] | undefined;
678
+ }>;
679
+ type Component = z.infer<typeof ComponentSchema>;
618
680
  declare const ToolSchema: z.ZodObject<{
619
681
  id: z.ZodString;
620
682
  name: z.ZodString;
@@ -640,6 +702,13 @@ type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Prom
640
702
  type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
641
703
 
642
704
  type DatabaseType = 'postgresql' | 'mssql' | 'snowflake' | 'mysql';
705
+ /**
706
+ * Model strategy for controlling which models are used for different tasks
707
+ * - 'best': Use the best model (e.g., Sonnet) for all tasks - highest quality, higher cost
708
+ * - 'fast': Use the fast model (e.g., Haiku) for all tasks - lower quality, lower cost
709
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
710
+ */
711
+ type ModelStrategy = 'best' | 'fast' | 'balanced';
643
712
  interface SuperatomSDKConfig {
644
713
  url?: string;
645
714
  apiKey?: string;
@@ -655,6 +724,13 @@ interface SuperatomSDKConfig {
655
724
  OPENAI_API_KEY?: string;
656
725
  LLM_PROVIDERS?: LLMProvider[];
657
726
  logLevel?: LogLevel;
727
+ /**
728
+ * Model selection strategy for LLM API calls:
729
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
730
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
731
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
732
+ */
733
+ modelStrategy?: ModelStrategy;
658
734
  }
659
735
 
660
736
  declare const KbNodesQueryFiltersSchema: z.ZodObject<{
@@ -785,6 +861,11 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
785
861
  } | undefined;
786
862
  }>;
787
863
  type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
864
+ interface T_RESPONSE {
865
+ success: boolean;
866
+ data?: any;
867
+ errors: string[];
868
+ }
788
869
 
789
870
  /**
790
871
  * UserManager class to handle CRUD operations on users with file persistence
@@ -1548,6 +1629,120 @@ declare const CONTEXT_CONFIG: {
1548
1629
  MAX_CONVERSATION_CONTEXT_BLOCKS: number;
1549
1630
  };
1550
1631
 
1632
+ /**
1633
+ * LLM Usage Logger - Tracks token usage, costs, and timing for all LLM API calls
1634
+ */
1635
+ interface LLMUsageEntry {
1636
+ timestamp: string;
1637
+ requestId: string;
1638
+ provider: string;
1639
+ model: string;
1640
+ method: string;
1641
+ inputTokens: number;
1642
+ outputTokens: number;
1643
+ cacheReadTokens?: number;
1644
+ cacheWriteTokens?: number;
1645
+ totalTokens: number;
1646
+ costUSD: number;
1647
+ durationMs: number;
1648
+ toolCalls?: number;
1649
+ success: boolean;
1650
+ error?: string;
1651
+ }
1652
+ declare class LLMUsageLogger {
1653
+ private logStream;
1654
+ private logPath;
1655
+ private enabled;
1656
+ private sessionStats;
1657
+ constructor();
1658
+ private initLogStream;
1659
+ private writeHeader;
1660
+ /**
1661
+ * Calculate cost based on token usage and model
1662
+ */
1663
+ calculateCost(model: string, inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): number;
1664
+ /**
1665
+ * Log an LLM API call
1666
+ */
1667
+ log(entry: LLMUsageEntry): void;
1668
+ /**
1669
+ * Log session summary (call at end of request)
1670
+ */
1671
+ logSessionSummary(requestContext?: string): void;
1672
+ /**
1673
+ * Reset session stats (call at start of new user request)
1674
+ */
1675
+ resetSession(): void;
1676
+ /**
1677
+ * Reset the log file for a new request (clears previous logs)
1678
+ * Call this at the start of each USER_PROMPT_REQ
1679
+ */
1680
+ resetLogFile(requestContext?: string): void;
1681
+ /**
1682
+ * Get current session stats
1683
+ */
1684
+ getSessionStats(): {
1685
+ totalCalls: number;
1686
+ totalInputTokens: number;
1687
+ totalOutputTokens: number;
1688
+ totalCacheReadTokens: number;
1689
+ totalCacheWriteTokens: number;
1690
+ totalCostUSD: number;
1691
+ totalDurationMs: number;
1692
+ };
1693
+ /**
1694
+ * Generate a unique request ID
1695
+ */
1696
+ generateRequestId(): string;
1697
+ }
1698
+ declare const llmUsageLogger: LLMUsageLogger;
1699
+
1700
+ /**
1701
+ * User Prompt Error Logger - Captures detailed errors for USER_PROMPT_REQ
1702
+ * Logs full error details including raw strings for parse failures
1703
+ */
1704
+ declare class UserPromptErrorLogger {
1705
+ private logStream;
1706
+ private logPath;
1707
+ private enabled;
1708
+ private hasErrors;
1709
+ constructor();
1710
+ /**
1711
+ * Reset the error log file for a new request
1712
+ */
1713
+ resetLogFile(requestContext?: string): void;
1714
+ /**
1715
+ * Log a JSON parse error with the raw string that failed
1716
+ */
1717
+ logJsonParseError(context: string, rawString: string, error: Error): void;
1718
+ /**
1719
+ * Log a general error with full details
1720
+ */
1721
+ logError(context: string, error: Error | string, additionalData?: Record<string, any>): void;
1722
+ /**
1723
+ * Log a SQL query error with the full query
1724
+ */
1725
+ logSqlError(query: string, error: Error | string, params?: any[]): void;
1726
+ /**
1727
+ * Log an LLM API error
1728
+ */
1729
+ logLlmError(provider: string, model: string, method: string, error: Error | string, requestData?: any): void;
1730
+ /**
1731
+ * Log tool execution error
1732
+ */
1733
+ logToolError(toolName: string, toolInput: any, error: Error | string): void;
1734
+ /**
1735
+ * Write final summary if there were errors
1736
+ */
1737
+ writeSummary(): void;
1738
+ /**
1739
+ * Check if any errors were logged
1740
+ */
1741
+ hadErrors(): boolean;
1742
+ private write;
1743
+ }
1744
+ declare const userPromptErrorLogger: UserPromptErrorLogger;
1745
+
1551
1746
  /**
1552
1747
  * BM25L Reranker for hybrid semantic search
1553
1748
  *
@@ -1676,6 +1871,216 @@ declare function rerankConversationResults<T extends {
1676
1871
  bm25Score: number;
1677
1872
  }>;
1678
1873
 
1874
+ /**
1875
+ * Task types for model selection
1876
+ * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
1877
+ * - 'simple': Classification, action generation (uses fast model in balanced mode)
1878
+ */
1879
+ type TaskType = 'complex' | 'simple';
1880
+ interface BaseLLMConfig {
1881
+ model?: string;
1882
+ fastModel?: string;
1883
+ defaultLimit?: number;
1884
+ apiKey?: string;
1885
+ /**
1886
+ * Model selection strategy:
1887
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
1888
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
1889
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
1890
+ */
1891
+ modelStrategy?: ModelStrategy;
1892
+ }
1893
+ /**
1894
+ * BaseLLM abstract class for AI-powered component generation and matching
1895
+ * Provides common functionality for all LLM providers
1896
+ */
1897
+ declare abstract class BaseLLM {
1898
+ protected model: string;
1899
+ protected fastModel: string;
1900
+ protected defaultLimit: number;
1901
+ protected apiKey?: string;
1902
+ protected modelStrategy: ModelStrategy;
1903
+ constructor(config?: BaseLLMConfig);
1904
+ /**
1905
+ * Get the appropriate model based on task type and model strategy
1906
+ * @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
1907
+ * @returns The model string to use for this task
1908
+ */
1909
+ protected getModelForTask(taskType: TaskType): string;
1910
+ /**
1911
+ * Set the model strategy at runtime
1912
+ * @param strategy - 'best', 'fast', or 'balanced'
1913
+ */
1914
+ setModelStrategy(strategy: ModelStrategy): void;
1915
+ /**
1916
+ * Get the current model strategy
1917
+ * @returns The current model strategy
1918
+ */
1919
+ getModelStrategy(): ModelStrategy;
1920
+ /**
1921
+ * Get the default model for this provider (used for complex tasks like text generation)
1922
+ */
1923
+ protected abstract getDefaultModel(): string;
1924
+ /**
1925
+ * Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
1926
+ * Should return a cheaper/faster model like Haiku for Anthropic
1927
+ */
1928
+ protected abstract getDefaultFastModel(): string;
1929
+ /**
1930
+ * Get the default API key from environment
1931
+ */
1932
+ protected abstract getDefaultApiKey(): string | undefined;
1933
+ /**
1934
+ * Get the provider name (for logging)
1935
+ */
1936
+ protected abstract getProviderName(): string;
1937
+ /**
1938
+ * Get the API key (from instance, parameter, or environment)
1939
+ */
1940
+ protected getApiKey(apiKey?: string): string | undefined;
1941
+ /**
1942
+ * Check if a component contains a Form (data_modification component)
1943
+ * Forms have hardcoded defaultValues that become stale when cached
1944
+ * This checks both single Form components and Forms inside MultiComponentContainer
1945
+ */
1946
+ protected containsFormComponent(component: any): boolean;
1947
+ /**
1948
+ * Match components from text response suggestions and generate follow-up questions
1949
+ * Takes a text response with component suggestions (c1:type format) and matches with available components
1950
+ * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
1951
+ * All components are placed in a default MultiComponentContainer layout
1952
+ * @param analysisContent - The text response containing component suggestions
1953
+ * @param components - List of available components
1954
+ * @param apiKey - Optional API key
1955
+ * @param logCollector - Optional log collector
1956
+ * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
1957
+ * @returns Object containing matched components, layout title/description, and follow-up actions
1958
+ */
1959
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], apiKey?: string, logCollector?: any, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[]): Promise<{
1960
+ components: Component[];
1961
+ layoutTitle: string;
1962
+ layoutDescription: string;
1963
+ actions: Action[];
1964
+ }>;
1965
+ /**
1966
+ * Classify user question into category and detect external tools needed
1967
+ * Determines if question is for data analysis, requires external tools, or needs text response
1968
+ */
1969
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, logCollector?: any, conversationHistory?: string, externalTools?: any[]): Promise<{
1970
+ category: 'data_analysis' | 'data_modification' | 'general';
1971
+ externalTools: Array<{
1972
+ type: string;
1973
+ name: string;
1974
+ description: string;
1975
+ parameters: Record<string, any>;
1976
+ }>;
1977
+ dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
1978
+ reasoning: string;
1979
+ confidence: number;
1980
+ }>;
1981
+ /**
1982
+ * Adapt UI block parameters based on current user question
1983
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
1984
+ */
1985
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, logCollector?: any): Promise<{
1986
+ success: boolean;
1987
+ adaptedComponent?: Component;
1988
+ parametersChanged?: Array<{
1989
+ field: string;
1990
+ reason: string;
1991
+ }>;
1992
+ explanation: string;
1993
+ }>;
1994
+ /**
1995
+ * Generate text-based response for user question
1996
+ * This provides conversational text responses instead of component generation
1997
+ * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
1998
+ * After generating text response, if components are provided, matches suggested components
1999
+ * @param streamCallback - Optional callback function to receive text chunks as they stream
2000
+ * @param collections - Collection registry for executing database queries via database.execute
2001
+ * @param components - Optional list of available components for matching suggestions
2002
+ * @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called
2003
+ * @param category - Question category ('data_analysis' | 'data_modification' | 'general'). For data_modification, answer component streaming is skipped. For general, component generation is skipped entirely.
2004
+ */
2005
+ generateTextResponse(userPrompt: string, apiKey?: string, logCollector?: any, conversationHistory?: string, streamCallback?: (chunk: string) => void, collections?: any, components?: Component[], externalTools?: any[], category?: 'data_analysis' | 'data_modification' | 'general'): Promise<T_RESPONSE>;
2006
+ /**
2007
+ * Main orchestration function with semantic search and multi-step classification
2008
+ * NEW FLOW (Recommended):
2009
+ * 1. Semantic search: Check previous conversations (>60% match)
2010
+ * - If match found → Adapt UI block parameters and return
2011
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
2012
+ * 3. Route appropriately based on category and response mode
2013
+ *
2014
+ * @param responseMode - 'component' for component generation (default), 'text' for text responses
2015
+ * @param streamCallback - Optional callback function to receive text chunks as they stream (only for text mode)
2016
+ * @param collections - Collection registry for executing database queries (required for text mode)
2017
+ * @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called (only for text mode)
2018
+ */
2019
+ handleUserRequest(userPrompt: string, components: Component[], apiKey?: string, logCollector?: any, conversationHistory?: string, responseMode?: 'component' | 'text', streamCallback?: (chunk: string) => void, collections?: any, externalTools?: any[], userId?: string): Promise<T_RESPONSE>;
2020
+ /**
2021
+ * Generate next questions that the user might ask based on the original prompt and generated component
2022
+ * This helps provide intelligent suggestions for follow-up queries
2023
+ * For general/conversational questions without components, pass textResponse instead
2024
+ */
2025
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, logCollector?: any, conversationHistory?: string, textResponse?: string): Promise<string[]>;
2026
+ }
2027
+
2028
+ interface AnthropicLLMConfig extends BaseLLMConfig {
2029
+ }
2030
+ /**
2031
+ * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
2032
+ */
2033
+ declare class AnthropicLLM extends BaseLLM {
2034
+ constructor(config?: AnthropicLLMConfig);
2035
+ protected getDefaultModel(): string;
2036
+ protected getDefaultFastModel(): string;
2037
+ protected getDefaultApiKey(): string | undefined;
2038
+ protected getProviderName(): string;
2039
+ }
2040
+ declare const anthropicLLM: AnthropicLLM;
2041
+
2042
+ interface GroqLLMConfig extends BaseLLMConfig {
2043
+ }
2044
+ /**
2045
+ * GroqLLM class for handling AI-powered component generation and matching using Groq
2046
+ */
2047
+ declare class GroqLLM extends BaseLLM {
2048
+ constructor(config?: GroqLLMConfig);
2049
+ protected getDefaultModel(): string;
2050
+ protected getDefaultFastModel(): string;
2051
+ protected getDefaultApiKey(): string | undefined;
2052
+ protected getProviderName(): string;
2053
+ }
2054
+ declare const groqLLM: GroqLLM;
2055
+
2056
+ interface GeminiLLMConfig extends BaseLLMConfig {
2057
+ }
2058
+ /**
2059
+ * GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
2060
+ */
2061
+ declare class GeminiLLM extends BaseLLM {
2062
+ constructor(config?: GeminiLLMConfig);
2063
+ protected getDefaultModel(): string;
2064
+ protected getDefaultFastModel(): string;
2065
+ protected getDefaultApiKey(): string | undefined;
2066
+ protected getProviderName(): string;
2067
+ }
2068
+ declare const geminiLLM: GeminiLLM;
2069
+
2070
+ interface OpenAILLMConfig extends BaseLLMConfig {
2071
+ }
2072
+ /**
2073
+ * OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
2074
+ */
2075
+ declare class OpenAILLM extends BaseLLM {
2076
+ constructor(config?: OpenAILLMConfig);
2077
+ protected getDefaultModel(): string;
2078
+ protected getDefaultFastModel(): string;
2079
+ protected getDefaultApiKey(): string | undefined;
2080
+ protected getProviderName(): string;
2081
+ }
2082
+ declare const openaiLLM: OpenAILLM;
2083
+
1679
2084
  declare const SDK_VERSION = "0.0.8";
1680
2085
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
1681
2086
  declare class SuperatomSDK {
@@ -1700,6 +2105,7 @@ declare class SuperatomSDK {
1700
2105
  private openaiApiKey;
1701
2106
  private llmProviders;
1702
2107
  private databaseType;
2108
+ private modelStrategy;
1703
2109
  private userManager;
1704
2110
  private dashboardManager;
1705
2111
  private reportManager;
@@ -1796,6 +2202,20 @@ declare class SuperatomSDK {
1796
2202
  * Get the stored tools
1797
2203
  */
1798
2204
  getTools(): Tool$1[];
2205
+ /**
2206
+ * Apply model strategy to all LLM provider singletons
2207
+ * @param strategy - 'best', 'fast', or 'balanced'
2208
+ */
2209
+ private applyModelStrategy;
2210
+ /**
2211
+ * Set model strategy at runtime
2212
+ * @param strategy - 'best', 'fast', or 'balanced'
2213
+ */
2214
+ setModelStrategy(strategy: ModelStrategy): void;
2215
+ /**
2216
+ * Get current model strategy
2217
+ */
2218
+ getModelStrategy(): ModelStrategy;
1799
2219
  }
1800
2220
 
1801
- export { type Action, BM25L, type BM25LOptions, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LogLevel, type Message, type RerankedResult, SDK_VERSION, STORAGE_CONFIG, SuperatomSDK, type SuperatomSDKConfig, Thread, ThreadManager, type Tool$1 as Tool, UIBlock, UILogCollector, type User, UserManager, type UsersData, hybridRerank, logger, rerankChromaResults, rerankConversationResults };
2221
+ export { type Action, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, type Message, type ModelStrategy, type RerankedResult, SDK_VERSION, STORAGE_CONFIG, SuperatomSDK, type SuperatomSDKConfig, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, UIBlock, UILogCollector, type User, UserManager, type UsersData, anthropicLLM, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, openaiLLM, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };