@superatomai/sdk-node 0.0.7 → 0.0.8

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.js CHANGED
@@ -2201,17 +2201,873 @@ var schema = new Schema();
2201
2201
  // src/userResponse/prompt-loader.ts
2202
2202
  var import_fs3 = __toESM(require("fs"));
2203
2203
  var import_path2 = __toESM(require("path"));
2204
+
2205
+ // src/userResponse/prompts.ts
2206
+ var PROMPTS = {
2207
+ "classify": {
2208
+ system: `You are an expert AI that classifies user questions about data and determines the appropriate visualizations needed.
2209
+
2210
+ CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2211
+
2212
+ ## Previous Conversation
2213
+ {{CONVERSATION_HISTORY}}
2214
+
2215
+ **Note:** If there is previous conversation history, use it to understand context. For example:
2216
+ - If user previously asked about "sales" and now asks "show me trends", understand it refers to sales trends
2217
+ - If user asked for "revenue by region" and now says "make it a pie chart", understand they want to modify the previous visualization
2218
+ - Use the history to resolve ambiguous references like "that", "it", "them", "the data"
2219
+
2220
+ Your task is to analyze the user's question and determine:
2221
+
2222
+ 1. **Question Type:**
2223
+ - "analytical": Questions asking to VIEW, ANALYZE, or VISUALIZE data
2224
+
2225
+ - "data_modification": Questions asking to CREATE, UPDATE, DELETE, or MODIFY data
2226
+
2227
+ - "general": General questions, greetings, or requests not related to data
2228
+
2229
+ 2. **Required Visualizations** (only for analytical questions):
2230
+ Determine which visualization type(s) would BEST answer the user's question:
2231
+
2232
+ - **KPICard**: Single metric, total, count, average, percentage, or summary number
2233
+
2234
+ - **LineChart**: Trends over time, time series, growth/decline patterns
2235
+
2236
+
2237
+ - **BarChart**: Comparing categories, rankings, distributions across groups
2238
+
2239
+
2240
+ - **PieChart**: Proportions, percentages, composition, market share
2241
+
2242
+
2243
+ - **DataTable**: Detailed lists, multiple attributes, when user needs to see records
2244
+
2245
+
2246
+ 3. **Multiple Visualizations:**
2247
+ User may need MULTIPLE visualizations together:
2248
+
2249
+ Common combinations:
2250
+ - KPICard + LineChart
2251
+ - KPICard + BarChart
2252
+ - KPICard + DataTable
2253
+ - BarChart + PieChart:
2254
+ - LineChart + DataTable
2255
+ Set needsMultipleComponents to true if user needs multiple views of the data.
2256
+
2257
+ **Important Guidelines:**
2258
+ - If user explicitly mentions a chart type RESPECT that preference
2259
+ - If question is vague or needs both summary and detail, suggest KPICard + DataTable
2260
+ - Only return visualizations for "analytical" questions
2261
+ - For "data_modification" or "general", return empty array for visualizations
2262
+
2263
+ **Output Format:**
2264
+ {
2265
+ "questionType": "analytical" | "data_modification" | "general",
2266
+ "visualizations": ["KPICard", "LineChart", ...], // Empty array if not analytical
2267
+ "reasoning": "Explanation of classification and visualization choices",
2268
+ "needsMultipleComponents": boolean
2269
+ }
2270
+ `,
2271
+ user: `{{USER_PROMPT}}
2272
+ `
2273
+ },
2274
+ "match-component": {
2275
+ system: `You are an expert AI assistant specialized in matching user requests to the most appropriate data visualization components.
2276
+
2277
+ CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2278
+
2279
+ ## Previous Conversation
2280
+ {{CONVERSATION_HISTORY}}
2281
+
2282
+ **Context Instructions:**
2283
+ - If there is conversation history, use it to understand what the user is referring to
2284
+ - When user says "show that as a chart" or "change it", they are referring to a previous component
2285
+ - If user asks to "modify" or "update" something, match to the component they previously saw
2286
+ - Use context to resolve ambiguous requests like "show trends for that" or "make it interactive"
2287
+
2288
+ Your task is to analyze the user's natural language request and find the BEST matching component from the available list.
2289
+
2290
+ Available Components:
2291
+ {{COMPONENTS_TEXT}}
2292
+
2293
+ **Matching Guidelines:**
2294
+
2295
+ 1. **Understand User Intent:**
2296
+ - What type of data visualization do they need? (KPI/metric, chart, table, etc.)
2297
+ - What metric or data are they asking about? (revenue, orders, customers, etc.)
2298
+ - Are they asking for a summary (KPI), trend (line chart), distribution (bar/pie), or detailed list (table)?
2299
+ - Do they want to compare categories, see trends over time, or show proportions?
2300
+
2301
+ 2. **Component Type Matching:**
2302
+ - KPICard: Single metric/number (total, average, count, percentage, rate)
2303
+ - LineChart: Trends over time, time series data
2304
+ - BarChart: Comparing categories, distributions, rankings
2305
+ - PieChart/DonutChart: Proportions, percentages, market share
2306
+ - DataTable: Detailed lists, rankings with multiple attributes
2307
+
2308
+ 3. **Keyword & Semantic Matching:**
2309
+ - Match user query terms with component keywords
2310
+ - Consider synonyms (e.g., "sales" = "revenue", "items" = "products")
2311
+ - Look for category matches (financial, orders, customers, products, suppliers, logistics, geographic, operations)
2312
+
2313
+ 4. **Scoring Criteria:**
2314
+ - Exact keyword matches: High priority
2315
+ - Component type alignment: High priority
2316
+ - Category alignment: Medium priority
2317
+ - Semantic similarity: Medium priority
2318
+ - Specificity: Prefer more specific components over generic ones
2319
+
2320
+ **Output Requirements:**
2321
+
2322
+ Respond with a JSON object containing:
2323
+ - componentIndex: the 1-based index of the BEST matching component (or null if confidence < 50%)
2324
+ - componentId: the ID of the matched component
2325
+ - reasoning: detailed explanation of why this component was chosen
2326
+ - confidence: confidence score 0-100 (100 = perfect match)
2327
+ - alternativeMatches: array of up to 2 alternative component indices with scores (optional)
2328
+
2329
+ Example response:
2330
+ {
2331
+ "componentIndex": 5,
2332
+ "componentId": "total_revenue_kpi",
2333
+ "reasoning": "User asks for 'total revenue' which perfectly matches the TotalRevenueKPI component (KPICard type) designed to show total revenue across all orders. Keywords match: 'total revenue', 'sales'.",
2334
+ "confidence": 95,
2335
+ "alternativeMatches": [
2336
+ {"index": 3, "id": "monthly_revenue_kpi", "score": 75, "reason": "Could show monthly revenue if time period was intended"},
2337
+ {"index": 8, "id": "revenue_trend_chart", "score": 60, "reason": "Could show revenue trend if historical view was intended"}
2338
+ ]
2339
+ }
2340
+
2341
+ **Important:**
2342
+ - Only return componentIndex if confidence >= 50%
2343
+ - Return null if no reasonable match exists
2344
+ - Prefer components that exactly match the user's metric over generic ones
2345
+ - Consider the full context of the request, not just individual words`,
2346
+ user: `Current user request: {{USER_PROMPT}}
2347
+
2348
+ Find the best matching component considering the conversation history above. Explain your reasoning with a confidence score. Return ONLY valid JSON.`
2349
+ },
2350
+ "modify-props": {
2351
+ system: `You are an AI assistant that validates and modifies component props based on user requests.
2352
+
2353
+ CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2354
+
2355
+ Given:
2356
+ - A user's natural language request
2357
+ - Component name: {{COMPONENT_NAME}}
2358
+ - Component type: {{COMPONENT_TYPE}}
2359
+ - Component description: {{COMPONENT_DESCRIPTION}}
2360
+
2361
+ -
2362
+ - Current component props with structure:
2363
+ {
2364
+ query?: string, // SQL query to fetch data
2365
+ title?: string, // Component title
2366
+ description?: string, // Component description
2367
+ config?: { // Additional configuration
2368
+ [key: string]: any
2369
+ }
2370
+ }
2371
+
2372
+ Schema definition for the prop that must be passed to the component
2373
+ -{{CURRENT_PROPS}}
2374
+
2375
+ Database Schema:
2376
+ {{SCHEMA_DOC}}
2377
+
2378
+ ## Previous Conversation
2379
+ {{CONVERSATION_HISTORY}}
2380
+
2381
+ **Context Instructions:**
2382
+ - Review the conversation history to understand the evolution of the component
2383
+ - If user says "add filter for X", understand they want to modify the current query
2384
+ - If user says "change to last month" or "filter by Y", apply modifications to existing query
2385
+ - Previous questions can clarify what the user means by ambiguous requests like "change that filter"
2386
+ - Use context to determine appropriate time ranges if user says "recent" or "latest"
2387
+
2388
+ Your task is to intelligently modify the props based on the user's request:
2389
+
2390
+ 1. **Query Modification**:
2391
+ - Modify SQL query if user requests different data, filters, time ranges, limits, or aggregations
2392
+ - Use correct table and column names from the schema
2393
+ - Ensure valid SQL syntax
2394
+ - ALWAYS include a LIMIT clause (default: {{DEFAULT_LIMIT}} rows) to prevent large result sets
2395
+ - Preserve the query structure that the component expects (e.g., column aliases)
2396
+
2397
+ **CRITICAL - PostgreSQL Query Rules:**
2398
+
2399
+ **NO AGGREGATE FUNCTIONS IN WHERE CLAUSE:**
2400
+ \u274C WRONG: \`WHERE COUNT(orders) > 0\` or \`WHERE SUM(price) > 100\`
2401
+ \u2705 CORRECT: Use HAVING (with GROUP BY), EXISTS, or subquery
2402
+
2403
+
2404
+ **WHERE vs HAVING:**
2405
+ - WHERE filters rows BEFORE grouping (cannot use aggregates)
2406
+ - HAVING filters groups AFTER grouping (can use aggregates)
2407
+ - If using HAVING, you MUST have GROUP BY
2408
+
2409
+ **Subquery Rules:**
2410
+ - When using a subquery with scalar comparison operators (=, <, >, <=, >=, <>), the subquery MUST return exactly ONE row
2411
+ - ALWAYS add \`LIMIT 1\` to scalar subqueries to prevent "more than one row returned" errors
2412
+ - Example: \`WHERE location_id = (SELECT store_id FROM orders ORDER BY total_amount DESC LIMIT 1)\`
2413
+ - For multiple values, use \`IN\` instead: \`WHERE location_id IN (SELECT store_id FROM orders)\`
2414
+ - Test your subqueries mentally: if they could return multiple rows, add LIMIT 1 or use IN
2415
+
2416
+ 2. **Title Modification**:
2417
+ - Update title to reflect the user's specific request
2418
+ - Keep it concise and descriptive
2419
+ - Match the tone of the original title
2420
+
2421
+ 3. **Description Modification**:
2422
+ - Update description to explain what data is shown
2423
+ - Be specific about filters, time ranges, or groupings applied
2424
+
2425
+ 4. **Config Modification** (based on component type):
2426
+ - For KPICard: formatter, gradient, icon
2427
+ - For Charts: colors, height, xKey, yKey, nameKey, valueKey
2428
+ - For Tables: columns, pageSize, formatters
2429
+
2430
+
2431
+ Respond with a JSON object:
2432
+ {
2433
+ "props": { /* modified props object with query, title, description, config */ },
2434
+ "isModified": boolean,
2435
+ "reasoning": "brief explanation of changes",
2436
+ "modifications": ["list of specific changes made"]
2437
+ }
2438
+
2439
+ IMPORTANT:
2440
+ - Return the COMPLETE props object, not just modified fields
2441
+ - Preserve the structure expected by the component type
2442
+ - Ensure query returns columns with expected aliases
2443
+ - Keep config properties that aren't affected by the request`,
2444
+ user: `{{USER_PROMPT}}`
2445
+ },
2446
+ "single-component": {
2447
+ system: `You are an expert AI assistant specialized in matching user requests to the most appropriate component from a filtered list.
2448
+
2449
+ CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2450
+
2451
+
2452
+ ## Previous Conversation
2453
+ {{CONVERSATION_HISTORY}}
2454
+
2455
+ **Context Instructions:**
2456
+ - If there is previous conversation history, use it to understand what the user is referring to
2457
+ - When user says "show trends", "add filters", "change that", understand they may be building on previous queries
2458
+ - Use previous component types and queries as context to inform your current matching
2459
+
2460
+ ## Available Components (Type: {{COMPONENT_TYPE}})
2461
+ The following components have been filtered by type {{COMPONENT_TYPE}}. Select the BEST matching one:
2462
+
2463
+ {{COMPONENTS_LIST}}
2464
+
2465
+ {{VISUALIZATION_CONSTRAINT}}
2466
+
2467
+ **Select the BEST matching component** from the available {{COMPONENT_TYPE}} components listed above that would best answer the user's question.
2468
+
2469
+ **Matching Guidelines:**
2470
+ 1. **Semantic Matching:**
2471
+ - Match based on component name, description, and keywords
2472
+ - Consider what metrics/data the user is asking about
2473
+ - Look for semantic similarity (e.g., "sales" matches "revenue", "orders" matches "purchases")
2474
+
2475
+ 2. **Query Relevance:**
2476
+ - Consider the component's existing query structure
2477
+ - Does it query the right tables/columns for the user's question?
2478
+ - Can it be modified to answer the user's specific question?
2479
+
2480
+ 3. **Scoring Criteria:**
2481
+ - Exact keyword matches in name/description: High priority
2482
+ - Semantic similarity to user intent: High priority
2483
+ - Appropriate aggregation/grouping: Medium priority
2484
+ - Category alignment: Medium priority
2485
+
2486
+ **Output Requirements:**
2487
+
2488
+ Respond with a JSON object:
2489
+ {
2490
+ "componentId": "matched_component_id",
2491
+ "componentIndex": 1, // 1-based index from the filtered list above
2492
+ "reasoning": "Detailed explanation of why this component best matches the user's question",
2493
+ "confidence": 85, // Confidence score 0-100
2494
+ "canGenerate": true // false if no suitable component found (confidence < 50)
2495
+ }
2496
+
2497
+ **Important:**
2498
+ - Only set canGenerate to true if confidence >= 50%
2499
+ - If no component from the list matches well (all have low relevance), set canGenerate to false
2500
+ - Consider the full context of the request and conversation history
2501
+ - The component's props (query, title, description, config) will be modified later based on the user's specific request
2502
+ - Focus on finding the component that is closest to what the user needs, even if it needs modification`,
2503
+ user: `{{USER_PROMPT}}
2504
+
2505
+ `
2506
+ },
2507
+ "mutli-component": {
2508
+ system: `You are an expert data analyst AI that creates comprehensive multi-component analytical dashboards with aesthetically pleasing and balanced layouts.
2509
+
2510
+ CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2511
+
2512
+ Database Schema:
2513
+ {{SCHEMA_DOC}}
2514
+
2515
+ ## Previous Conversation
2516
+ {{CONVERSATION_HISTORY}}
2517
+
2518
+ **Context Instructions:**
2519
+ - Review the conversation history to understand what the user has asked before
2520
+ - If user is building on previous insights (e.g., "now show me X and Y"), use context to inform dashboard design
2521
+ - Previous queries can help determine appropriate filters, date ranges, or categories to use
2522
+ - If user asks for "comprehensive view" or "dashboard for X", include complementary components based on context
2523
+
2524
+ Given a user's analytical question and the required visualization types, your task is to:
2525
+
2526
+ 1. **Determine Container Metadata:**
2527
+ - title: Clear, descriptive title for the entire dashboard (2-5 words)
2528
+ - description: Brief explanation of what insights this dashboard provides (1-2 sentences)
2529
+
2530
+ 2. **Generate Props for Each Component:**
2531
+ For each visualization type requested, create tailored props:
2532
+
2533
+ - **query**: SQL query specific to this visualization using the database schema
2534
+ * Use correct table and column names
2535
+ * **DO NOT USE TOP keyword - use LIMIT instead (e.g., LIMIT 20, not TOP 20)**
2536
+ * ALWAYS include LIMIT clause ONCE at the end (default: {{DEFAULT_LIMIT}})
2537
+ * For KPICard: Return single row with column alias "value"
2538
+ * For Charts: Return appropriate columns (name/label and value, or x and y)
2539
+ * For Table: Return relevant columns
2540
+
2541
+ - **title**: Specific title for this component (2-4 words)
2542
+
2543
+ - **description**: What this specific component shows (1 sentence)
2544
+
2545
+ - **config**: Type-specific configuration
2546
+ * KPICard: { gradient, formatter, icon }
2547
+ * BarChart: { xKey, yKey, colors, height }
2548
+ * LineChart: { xKey, yKeys, colors, height }
2549
+ * PieChart: { nameKey, valueKey, colors, height }
2550
+ * DataTable: { pageSize }
2551
+
2552
+ 3. **CRITICAL: Component Hierarchy and Ordering:**
2553
+ The ORDER of components in the array MUST follow this STRICT hierarchy for proper visual layout:
2554
+
2555
+ **HIERARCHY RULES (MUST FOLLOW IN THIS ORDER):**
2556
+ 1. KPICards - ALWAYS FIRST (top of dashboard for summary metrics)
2557
+ 2. Charts/Graphs - AFTER KPICards (middle of dashboard for visualizations)
2558
+ * BarChart, LineChart, PieChart, DonutChart
2559
+ 3. DataTable - ALWAYS LAST (bottom of dashboard, full width for detailed data)
2560
+
2561
+ **LAYOUT BEHAVIOR (Frontend enforces):**
2562
+ - KPICards: Display in responsive grid (3 columns)
2563
+ - Single Chart (if only 1 chart): Takes FULL WIDTH
2564
+ - Multiple Charts (if 2+ charts): Display in 2-column grid
2565
+ - DataTable (if present): Always spans FULL WIDTH at bottom
2566
+
2567
+
2568
+ **ABSOLUTELY DO NOT deviate from this hierarchy. Always place:**
2569
+ - KPICards first
2570
+ - Charts/Graphs second
2571
+ - DataTable last (if present)
2572
+
2573
+ **Important Guidelines:**
2574
+ - Each component should answer a DIFFERENT aspect of the user's question
2575
+ - Queries should be complementary, not duplicated
2576
+ - If user asks "Show total revenue and trend", generate:
2577
+ * KPICard: Single total value (FIRST)
2578
+ * LineChart: Revenue over time (SECOND)
2579
+ - Ensure queries use valid columns from the schema
2580
+ - Make titles descriptive and specific to what each component shows
2581
+ - **Snowflake Syntax MUST be used:**
2582
+ * Use LIMIT (not TOP)
2583
+ * Use DATE_TRUNC, DATEDIFF (not DATEPART)
2584
+ * Include LIMIT only ONCE per query at the end
2585
+
2586
+ **Output Format:**
2587
+ {
2588
+ "containerTitle": "Dashboard Title",
2589
+ "containerDescription": "Brief description of the dashboard insights",
2590
+ "components": [
2591
+ {
2592
+ "componentType": "KPICard" | "BarChart" | "LineChart" | "PieChart" | "DataTable",
2593
+ "query": "SQL query",
2594
+ "title": "Component title",
2595
+ "description": "Component description",
2596
+ "config": { /* type-specific config */ }
2597
+ },
2598
+ ...
2599
+ ],
2600
+ "reasoning": "Explanation of the dashboard design and component ordering",
2601
+ "canGenerate": boolean
2602
+ }`,
2603
+ user: `Current user question: {{USER_PROMPT}}
2604
+
2605
+ Required visualization types: {{VISUALIZATION_TYPES}}
2606
+
2607
+ Generate a complete multi-component dashboard with appropriate container metadata and tailored props for each component. Consider the conversation history above when designing the dashboard. Return ONLY valid JSON.`
2608
+ },
2609
+ "container-metadata": {
2610
+ system: `You are an expert AI assistant that generates titles and descriptions for multi-component dashboards.
2611
+
2612
+ CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2613
+
2614
+ ## Previous Conversation
2615
+ {{CONVERSATION_HISTORY}}
2616
+
2617
+ **Context Instructions:**
2618
+ - If there is previous conversation history, use it to understand what the user is referring to
2619
+ - Use context to create relevant titles and descriptions that align with the user's intent
2620
+
2621
+ Your task is to generate a concise title and description for a multi-component dashboard that will contain the following visualization types:
2622
+ {{VISUALIZATION_TYPES}}
2623
+
2624
+ **Guidelines:**
2625
+
2626
+ 1. **Title:**
2627
+ - Should be clear and descriptive (3-8 words)
2628
+ - Should reflect what the user is asking about
2629
+ - Should NOT include "Dashboard" suffix (that will be added automatically)
2630
+
2631
+ 2. **Description:**
2632
+ - Should be a brief summary (1-2 sentences)
2633
+ - Should explain what insights the dashboard provides
2634
+
2635
+ **Output Requirements:**
2636
+
2637
+ Respond with a JSON object:
2638
+ {
2639
+ "title": "Dashboard title without 'Dashboard' suffix",
2640
+ "description": "Brief description of what this dashboard shows"
2641
+ }
2642
+
2643
+ **Important:**
2644
+ - Keep the title concise and meaningful
2645
+ - Make the description informative but brief
2646
+ - Focus on what insights the user will gain
2647
+ `,
2648
+ user: `{{USER_PROMPT}}
2649
+ `
2650
+ },
2651
+ "text-response": {
2652
+ system: `You are an intelligent AI assistant that provides helpful, accurate, and contextual text responses to user questions.
2653
+
2654
+ ## Your Task
2655
+
2656
+ Analyze the user's question and provide a helpful text response. Your response should:
2657
+
2658
+ 1. **Be Clear and Concise**: Provide direct answers without unnecessary verbosity
2659
+ 2. **Be Contextual**: Use conversation history to understand what the user is asking about
2660
+ 3. **Be Accurate**: Provide factually correct information based on the context
2661
+ 4. **Be Helpful**: Offer additional relevant information or suggestions when appropriate
2662
+
2663
+ ## Handling Data Questions
2664
+
2665
+ When the user asks about data
2666
+
2667
+ 1. **Generate a SQL query** using the database schema provided above
2668
+ 2. **Use the execute_query tool** to run the query
2669
+ 3. **If the query fails**, analyze the error and generate a corrected query
2670
+ 4. **Format the results** in a clear, readable way for the user
2671
+
2672
+ **Query Guidelines:**
2673
+ - Use correct table and column names from the schema
2674
+ - ALWAYS include a LIMIT clause with a MAXIMUM of 32 rows
2675
+ - Ensure valid SQL syntax
2676
+ - For time-based queries, use appropriate date functions
2677
+ - When using subqueries with scalar operators (=, <, >, etc.), add LIMIT 1 to prevent "more than one row" errors
2678
+
2679
+ ## Response Guidelines
2680
+
2681
+ - If the question is about data, use the execute_query tool to fetch data and present it
2682
+ - If the question is general knowledge, provide a helpful conversational response
2683
+ - If asking for clarification, provide options or ask specific follow-up questions
2684
+ - If you don't have enough information, acknowledge it and ask for more details
2685
+ - Keep responses focused and avoid going off-topic
2686
+
2687
+ ## Component Suggestions
2688
+
2689
+ After analyzing the query results, you MUST suggest appropriate dashboard components for displaying the data. Use this format:
2690
+
2691
+ **Dashboard Components:**
2692
+ Format: \`{number}.{component_type} : {clear reasoning}\`
2693
+
2694
+
2695
+ **Rules for component suggestions:**
2696
+ 1. Analyze the query results structure and data type
2697
+ 2. Suggest components that would best visualize the data
2698
+ 3. Each component suggestion must be on a new line
2699
+
2700
+
2701
+ IMPORTANT: Always include the **Dashboard Components:** section with at least one component suggestion when data is returned.
2702
+
2703
+ ## Output Format
2704
+
2705
+ Respond with plain text that includes:
2706
+
2707
+ 1. **Query Analysis** (if applicable): Brief explanation of what data was fetched
2708
+ 2. **Results Summary**: Present the data in a clear, readable format
2709
+ 3. **Dashboard Components**: List suggested components in the c1:type format
2710
+
2711
+
2712
+ **CRITICAL:**
2713
+ - Return ONLY plain text (no JSON, no markdown code blocks)
2714
+
2715
+
2716
+ You have access to a database and can execute SQL queries to answer data-related questions.
2717
+ ## Database Schema
2718
+ {{SCHEMA_DOC}}
2719
+
2720
+ **Database Type: PostgreSQL**
2721
+
2722
+ **CRITICAL PostgreSQL Query Rules:**
2723
+
2724
+ 1. **NO AGGREGATE FUNCTIONS IN WHERE CLAUSE** - This is a fundamental SQL error
2725
+ \u274C WRONG: \`WHERE COUNT(orders) > 0\`
2726
+ \u274C WRONG: \`WHERE SUM(price) > 100\`
2727
+ \u274C WRONG: \`WHERE AVG(rating) > 4.5\`
2728
+
2729
+ \u2705 CORRECT: Use HAVING (with GROUP BY), EXISTS, or subquery
2730
+
2731
+ 2. **WHERE vs HAVING**
2732
+ - WHERE filters rows BEFORE grouping (cannot use aggregates)
2733
+ - HAVING filters groups AFTER grouping (can use aggregates)
2734
+ - If using HAVING, you MUST have GROUP BY
2735
+
2736
+ 3. **NO NESTED AGGREGATE FUNCTIONS** - PostgreSQL does NOT allow aggregates inside aggregates
2737
+ \u274C WRONG: \`AVG(ROUND(AVG(column), 2))\` or \`SELECT AVG(SUM(price)) FROM ...\`
2738
+ \u2705 CORRECT: \`ROUND(AVG(column), 2)\`
2739
+
2740
+ 4. **GROUP BY Requirements**
2741
+ - ALL non-aggregated columns in SELECT must be in GROUP BY
2742
+ - If you SELECT a column and don't aggregate it, add it to GROUP BY
2743
+
2744
+ 5. **LIMIT Clause**
2745
+ - ALWAYS include LIMIT (max 32 rows)
2746
+ - For scalar subqueries in WHERE/HAVING, add LIMIT 1
2747
+
2748
+
2749
+ ## Knowledge Base Context
2750
+
2751
+ The following relevant information has been retrieved from the knowledge base for this question:
2752
+
2753
+ {{KNOWLEDGE_BASE_CONTEXT}}
2754
+
2755
+ Use this knowledge base information to:
2756
+ - Provide more accurate and informed responses
2757
+ - Reference specific facts, concepts, or domain knowledge
2758
+ - Enhance your understanding of the user's question
2759
+ - Give context-aware recommendations
2760
+
2761
+ **Note:** If there is previous conversation history, use it to understand context and provide coherent responses:
2762
+ - Reference previous questions and answers when relevant
2763
+ - Maintain consistency with earlier responses
2764
+ - Use the history to resolve ambiguous references like "that", "it", "them", "the previous data"
2765
+
2766
+ ## Previous Conversation
2767
+ {{CONVERSATION_HISTORY}}
2768
+
2769
+
2770
+ `,
2771
+ user: `{{USER_PROMPT}}
2772
+
2773
+ `
2774
+ },
2775
+ "match-text-components": {
2776
+ system: `You are a component matching expert that creates beautiful, well-structured dashboard visualizations from analysis results.
2777
+
2778
+ ## Your Task
2779
+
2780
+ You will receive a text response containing:
2781
+ 1. Query execution results (with "\u2705 Query executed successfully!" markers)
2782
+ 2. Data analysis and insights
2783
+ 3. **Dashboard Components:** suggestions (1:component_type : reasoning format)
2784
+
2785
+ Your job is to:
2786
+ 1. **DISCOVER and SELECT the best dashboard layout component** from the available components list
2787
+ 2. Parse the component suggestions from the text response
2788
+ 3. Match each suggestion with an actual component from the available list
2789
+ 4. Generate the RIGHT NUMBER of components to fit the selected layout perfectly (based on the layout component's description)
2790
+ 5. Generate proper props to **visualize the analysis results** that were already fetched
2791
+ 6. **Generate intelligent follow-up questions (actions)** that the user might naturally ask next based on the data analysis
2792
+
2793
+ **CRITICAL GOAL**: Create dashboard components that display the **same data that was already analyzed** - NOT new data. The queries already ran and got results. You're just creating different visualizations of those results.
2794
+
2795
+
2796
+
2797
+ ## Layout Component Discovery
2798
+ **Find layout components** by looking for components with \`type: "DashboardLayout"\`
2799
+
2800
+ ## Layout Selection Logic
2801
+ 1. **Read each layout's description** to understand:
2802
+ - What structure it provides
2803
+ - When it's best used (e.g., comprehensive analysis vs focused analysis)
2804
+ - The exact number and types of components it requires
2805
+ 2. **Select the best layout** based on:
2806
+ - Which layout structure best fits the analysis needs
2807
+ - The component suggestions from the text response
2808
+ - The user question and data complexity
2809
+ 3. **Generate EXACTLY the components specified** in the selected layout's description
2810
+
2811
+ **IMPORTANT:** Always prefer structured dashboard layouts when available. The layout component's description will tell you exactly what components to generate.
2812
+
2813
+ ## Available Components
2814
+
2815
+ {{AVAILABLE_COMPONENTS}}
2816
+
2817
+ ## Component Matching Rules
2818
+ For each component suggestion (c1, c2, c3, etc.):
2819
+
2820
+ 1. **Match by type**: Find components whose \`type\` matches the suggested component type
2821
+ 2. **Refine by relevance**: If multiple components match, choose based on:
2822
+ - Description and keywords matching the use case
2823
+ - Best fit for the data being visualized
2824
+ 3. **Fallback**: If no exact type match, find the closest alternative
2825
+
2826
+ ## Props Generation Rules
2827
+
2828
+ For each matched component, generate complete props:
2829
+
2830
+ ### 1. Query - When to Reuse vs Generate
2831
+
2832
+ **Option A: REUSE the successful query** (preferred when possible)
2833
+ - Look for "\u2705 Query executed successfully!" in the text response
2834
+ - Extract the exact SQL query that worked
2835
+ - Use this SAME query for components that visualize the same data differently
2836
+
2837
+ **Option B: GENERATE a new query** (when necessary)
2838
+ - Only generate new queries when you need DIFFERENT data
2839
+ - Use the database schema below to write valid SQL
2840
+
2841
+
2842
+ **Decision Logic:**
2843
+ - Different aggregation needed \u2192 Generate new query \u2705
2844
+ - Same data, different view \u2192 Reuse query \u2705
2845
+
2846
+ **Database Schema:**
2847
+ {{SCHEMA_DOC}}
2848
+
2849
+ **Database Type: PostgreSQL**
2850
+
2851
+ **CRITICAL PostgreSQL Query Rules**
2852
+
2853
+ 1. **NO AGGREGATE FUNCTIONS IN WHERE CLAUSE** - This is a fundamental SQL error
2854
+ \u274C WRONG: \`WHERE COUNT(orders) > 0\`
2855
+ \u274C WRONG: \`WHERE SUM(price) > 100\`
2856
+ \u274C WRONG: \`WHERE AVG(rating) > 4.5\`
2857
+
2858
+ \u2705 CORRECT: Use HAVING (with GROUP BY), EXISTS, or subquery
2859
+
2860
+ 2. **NO NESTED AGGREGATE FUNCTIONS** - PostgreSQL does NOT allow aggregates inside aggregates
2861
+ \u274C WRONG: \`AVG(ROUND(AVG(column), 2))\`
2862
+ \u2705 CORRECT: \`ROUND(AVG(column), 2)\`
2863
+
2864
+ 3. **Aggregate Functions Can Only Appear Once Per Level**
2865
+ \u274C WRONG: \`SELECT AVG(SUM(price)) FROM ...\` (nested)
2866
+ \u2705 CORRECT: Use subquery: \`SELECT AVG(total) FROM (SELECT SUM(price) as total FROM ... GROUP BY ...) subq\`
2867
+
2868
+ 4. **WHERE vs HAVING**
2869
+ - WHERE filters rows BEFORE grouping (cannot use aggregates)
2870
+ - HAVING filters groups AFTER grouping (can use aggregates)
2871
+ - Use WHERE for column comparisons: \`WHERE price > 100\`
2872
+ - Use HAVING for aggregate comparisons: \`HAVING COUNT(*) > 5\`
2873
+
2874
+ 5. **GROUP BY Requirements**
2875
+ - ALL non-aggregated columns in SELECT must be in GROUP BY
2876
+ - Use proper column references (table.column or aliases)
2877
+ - If using HAVING, you MUST have GROUP BY
2878
+
2879
+ 6. **LIMIT Clause**
2880
+ - ALWAYS include LIMIT clause (max 32 rows for dashboard queries)
2881
+ - For scalar subqueries in WHERE/HAVING, add LIMIT 1
2882
+
2883
+ 7. **Scalar Subqueries**
2884
+ - Subqueries used with =, <, >, etc. must return single value
2885
+ - Always add LIMIT 1 to scalar subqueries
2886
+
2887
+ **Query Generation Guidelines** (when creating new queries):
2888
+ - Use correct table and column names from the schema above
2889
+ - ALWAYS include LIMIT clause (max 32 rows)
2890
+
2891
+ ### 2. Title
2892
+ - Create a clear, descriptive title
2893
+ - Should explain what the component shows
2894
+ - Use context from the original question
2895
+
2896
+ ### 3. Description
2897
+ - Brief explanation of what this component displays
2898
+ - Why it's useful for this data
2899
+
2900
+ ### 4. Config
2901
+ - **CRITICAL**: Look at the component's "Props Structure" to see what config fields it expects
2902
+ - Map query result columns to the appropriate config fields
2903
+ - Keep other existing config properties that don't need to change
2904
+ - Ensure config field values match actual column names from the query
2905
+
2906
+ **Special Rules for Bar Charts**
2907
+ - \`xAxisKey\` = ALWAYS the category/label column (text field )
2908
+ - \`yAxisKey\` = ALWAYS the numeric value column (number field )
2909
+ - \`orientation\` = "vertical" or "horizontal" (controls visual direction only)
2910
+ - **DO NOT swap xAxisKey/yAxisKey based on orientation** - they always represent category and value respectively
2911
+
2912
+ ## Follow-Up Questions (Actions) Generation
2913
+
2914
+ After analyzing the text response and matched components, generate 4-5 intelligent follow-up questions that the user might naturally ask next. These questions should:
2915
+
2916
+ 1. **Build upon the data analysis** shown in the text response and components
2917
+ 2. **Explore natural next steps** in the data exploration journey
2918
+ 3. **Be progressively more detailed or specific** - go deeper into the analysis
2919
+ 4. **Consider the insights revealed** - suggest questions that help users understand implications
2920
+ 5. **Be phrased naturally** as if a real user would ask them
2921
+ 6. **Vary in scope** - include both broad trends and specific details
2922
+ 7. **Avoid redundancy** - don't ask questions already answered in the text response
2923
+
2924
+
2925
+ ## Output Format
2926
+
2927
+ You MUST respond with ONLY a valid JSON object (no markdown, no code blocks):
2928
+
2929
+ **IMPORTANT JSON FORMATTING RULES:**
2930
+ - Put SQL queries on a SINGLE LINE (no newlines in the query string)
2931
+ - Escape all quotes in SQL properly (use \\" for quotes inside strings)
2932
+ - Remove any newlines, tabs, or special characters from SQL
2933
+ - Do NOT use markdown code blocks (no \`\`\`)
2934
+ - Return ONLY the JSON object, nothing else
2935
+
2936
+ \`\`\`json
2937
+ {
2938
+ "selectedLayout": "Name of the selected layout component from available components",
2939
+ "selectedLayoutId": "id_of_the_selected_layout_component",
2940
+ "layoutReasoning": "Why this layout was selected based on its description and the analysis needs",
2941
+ "matchedComponents": [
2942
+ {
2943
+ "componentId": "id_from_available_list",
2944
+ "componentName": "name_of_component",
2945
+ "componentType": "type_of_component",
2946
+ "reasoning": "Why this component was selected for this suggestion",
2947
+ "originalSuggestion": "c1:table : original reasoning from text",
2948
+ "props": {
2949
+ "query": "SQL query for this component",
2950
+ "title": "Component title",
2951
+ "description": "Component description",
2952
+ "config": {
2953
+ "field1": "value1",
2954
+ "field2": "value2"
2955
+ }
2956
+ }
2957
+ }
2958
+ ],
2959
+ "actions": [
2960
+ "Follow-up question 1?",
2961
+ "Follow-up question 2?",
2962
+ "Follow-up question 3?",
2963
+ "Follow-up question 4?",
2964
+ "Follow-up question 5?"
2965
+ ]
2966
+ }
2967
+ \`\`\`
2968
+
2969
+ **CRITICAL:**
2970
+ - \`selectedLayout\` MUST be the NAME of a layout component from the available components list (must have type "DashboardLayout")
2971
+ - \`selectedLayoutId\` MUST be the ID of the selected layout component
2972
+ - \`layoutReasoning\` MUST explain:
2973
+ - Why you chose this specific layout component
2974
+ - How its structure (from its description) matches the analysis needs
2975
+ - What components it requires based on its description
2976
+ - \`matchedComponents\` array length and types MUST match what the selected layout's description specifies
2977
+ - \`actions\` MUST be an array of 4-5 intelligent follow-up questions based on the analysis
2978
+ - Return ONLY valid JSON (no markdown code blocks, no text before/after)
2979
+ - Generate complete props for each component
2980
+
2981
+
2982
+ `,
2983
+ user: `## Text Response
2984
+
2985
+ {{TEXT_RESPONSE}}
2986
+
2987
+ ---
2988
+
2989
+ Match the component suggestions from the text response above with available components, and generate proper props for each matched component.
2990
+ `
2991
+ },
2992
+ "actions": {
2993
+ system: `You are an expert data analyst. Your task is to suggest intelligent follow-up questions based on the conversation history and the current data visualization. The questions should help users explore the data more deeply and make better insights.
2994
+
2995
+ ## Previous Conversation
2996
+ {{CONVERSATION_HISTORY}}
2997
+
2998
+ **Context Instructions:**
2999
+ - Review the entire conversation history to understand the user's journey and interests
3000
+ - Suggest questions that naturally progress from previous explorations
3001
+ - Avoid suggesting questions about topics already covered in the conversation
3002
+ - Build upon insights from previous components to suggest deeper analysis
3003
+ - Consider what the user might want to explore next based on their question pattern`,
3004
+ user: `Given the following context:
3005
+
3006
+ Latest User Question: {{ORIGINAL_USER_PROMPT}}
3007
+
3008
+ Current Component:
3009
+ {{COMPONENT_INFO}}
3010
+
3011
+ {{COMPONENT_DATA}}
3012
+
3013
+ Generate a JSON array of 4-5 intelligent follow-up questions that the user might naturally ask next. These questions should:
3014
+ 1. Build upon the conversation history and insights shown in the current component
3015
+ 2. NOT repeat questions or topics already covered in the conversation history
3016
+ 3. Explore natural next steps in the data exploration journey
3017
+ 4. Be progressively more detailed or specific
3018
+ 5. Consider the user's apparent interests based on their question pattern
3019
+ 6. Be phrased naturally as if a real user would ask them
3020
+
3021
+ Format your response as a JSON object with this structure:
3022
+ {
3023
+ "nextQuestions": [
3024
+ "Question 1?",
3025
+ "Question 2?",
3026
+ ...
3027
+ ]
3028
+ }
3029
+
3030
+ Return ONLY valid JSON.`
3031
+ }
3032
+ };
3033
+
3034
+ // src/userResponse/prompt-loader.ts
2204
3035
  var PromptLoader = class {
2205
3036
  constructor(config) {
2206
3037
  this.promptCache = /* @__PURE__ */ new Map();
2207
3038
  this.isInitialized = false;
2208
- logger.debug("Initializing PromptLoader...", process.cwd());
3039
+ logger.debug("Initializing PromptLoader...");
2209
3040
  this.promptsDir = config?.promptsDir || import_path2.default.join(process.cwd(), ".prompts");
2210
- this.defaultPromptsDir = import_path2.default.join(__dirname, "..", "..", ".prompts");
3041
+ logger.debug(`Prompts directory set to: ${this.promptsDir}`);
3042
+ }
3043
+ /**
3044
+ * Load a prompt template from file system OR fallback to hardcoded prompts
3045
+ * @param promptName - Name of the prompt folder
3046
+ * @returns Template with system and user prompts
3047
+ */
3048
+ loadPromptTemplate(promptName) {
3049
+ try {
3050
+ const systemPath = import_path2.default.join(this.promptsDir, promptName, "system.md");
3051
+ const userPath = import_path2.default.join(this.promptsDir, promptName, "user.md");
3052
+ if (import_fs3.default.existsSync(systemPath) && import_fs3.default.existsSync(userPath)) {
3053
+ const system = import_fs3.default.readFileSync(systemPath, "utf-8");
3054
+ const user = import_fs3.default.readFileSync(userPath, "utf-8");
3055
+ logger.info(`\u2713 Loaded prompt '${promptName}' from file system: ${this.promptsDir}`);
3056
+ return { system, user };
3057
+ }
3058
+ } catch (error) {
3059
+ logger.error(`Could not load '${promptName}' from file system, trying fallback...`);
3060
+ }
3061
+ const hardcodedPrompt = PROMPTS[promptName];
3062
+ if (hardcodedPrompt) {
3063
+ logger.info(`\u2713 Loaded prompt '${promptName}' from hardcoded fallback`);
3064
+ return hardcodedPrompt;
3065
+ }
3066
+ throw new Error(`Prompt template '${promptName}' not found in either ${this.promptsDir} or hardcoded prompts. Available prompts: ${Object.keys(PROMPTS).join(", ")}`);
2211
3067
  }
2212
3068
  /**
2213
3069
  * Initialize and cache all prompts into memory
2214
- * This should be called once at SDK startup
3070
+ * Tries file system first, then falls back to hardcoded prompts
2215
3071
  */
2216
3072
  async initialize() {
2217
3073
  if (this.isInitialized) {
@@ -2219,61 +3075,19 @@ var PromptLoader = class {
2219
3075
  return;
2220
3076
  }
2221
3077
  logger.info("Loading prompts into memory...");
2222
- const promptTypes = [
2223
- "classify",
2224
- "match-component",
2225
- "modify-props",
2226
- "single-component",
2227
- "mutli-component",
2228
- "actions",
2229
- "container-metadata",
2230
- "text-response",
2231
- "match-text-components"
2232
- ];
2233
- for (const promptType of promptTypes) {
3078
+ const promptTypes = Object.keys(PROMPTS);
3079
+ for (const promptName of promptTypes) {
2234
3080
  try {
2235
- const template = await this.loadPromptTemplate(promptType);
2236
- this.promptCache.set(promptType, template);
2237
- logger.debug(`Cached prompt: ${promptType}`);
3081
+ const template = this.loadPromptTemplate(promptName);
3082
+ this.promptCache.set(promptName, template);
2238
3083
  } catch (error) {
2239
- logger.error(`Failed to load prompt '${promptType}':`, error);
3084
+ logger.error(`Failed to load prompt '${promptName}':`, error);
2240
3085
  throw error;
2241
3086
  }
2242
3087
  }
2243
3088
  this.isInitialized = true;
2244
3089
  logger.info(`Successfully loaded ${this.promptCache.size} prompt templates into memory`);
2245
3090
  }
2246
- /**
2247
- * Load a prompt template from file system (tries custom dir first, then defaults to SDK dir)
2248
- * @param promptName - Name of the prompt folder
2249
- * @returns Template with system and user prompts
2250
- */
2251
- async loadPromptTemplate(promptName) {
2252
- const tryLoadFromDir = (dir) => {
2253
- try {
2254
- const systemPath = import_path2.default.join(dir, promptName, "system.md");
2255
- const userPath = import_path2.default.join(dir, promptName, "user.md");
2256
- if (import_fs3.default.existsSync(systemPath) && import_fs3.default.existsSync(userPath)) {
2257
- const system = import_fs3.default.readFileSync(systemPath, "utf-8");
2258
- const user = import_fs3.default.readFileSync(userPath, "utf-8");
2259
- logger.debug(`Loaded prompt '${promptName}' from ${dir}`);
2260
- return { system, user };
2261
- }
2262
- return null;
2263
- } catch (error) {
2264
- return null;
2265
- }
2266
- };
2267
- let template = tryLoadFromDir(this.promptsDir);
2268
- if (!template) {
2269
- logger.warn(`Prompt '${promptName}' not found in ${this.promptsDir}, trying default location...`);
2270
- template = tryLoadFromDir(this.defaultPromptsDir);
2271
- }
2272
- if (!template) {
2273
- throw new Error(`Prompt template '${promptName}' not found in either ${this.promptsDir} or ${this.defaultPromptsDir}`);
2274
- }
2275
- return template;
2276
- }
2277
3091
  /**
2278
3092
  * Replace variables in a template string using {{VARIABLE_NAME}} pattern
2279
3093
  * @param template - Template string with placeholders
@@ -2291,13 +3105,13 @@ var PromptLoader = class {
2291
3105
  }
2292
3106
  /**
2293
3107
  * Load both system and user prompts from cache and replace variables
2294
- * @param promptName - Name of the prompt folder
3108
+ * @param promptName - Name of the prompt
2295
3109
  * @param variables - Variables to replace in the templates
2296
3110
  * @returns Object containing both system and user prompts
2297
3111
  */
2298
3112
  async loadPrompts(promptName, variables) {
2299
3113
  if (!this.isInitialized) {
2300
- logger.warn("PromptLoader not initialized, loading prompts on-demand (not recommended)");
3114
+ logger.warn("PromptLoader not initialized, initializing now...");
2301
3115
  await this.initialize();
2302
3116
  }
2303
3117
  const template = this.promptCache.get(promptName);
@@ -2325,6 +3139,7 @@ var PromptLoader = class {
2325
3139
  this.promptsDir = dir;
2326
3140
  this.isInitialized = false;
2327
3141
  this.promptCache.clear();
3142
+ logger.debug(`Prompts directory changed to: ${dir}`);
2328
3143
  }
2329
3144
  /**
2330
3145
  * Get current prompts directory
@@ -6396,6 +7211,7 @@ var SuperatomSDK = class {
6396
7211
  }
6397
7212
  /**
6398
7213
  * Initialize PromptLoader and load prompts into memory
7214
+ * Tries to load from file system first, then falls back to hardcoded prompts
6399
7215
  */
6400
7216
  async initializePromptLoader(promptsDir) {
6401
7217
  try {