@superatomai/sdk-node 0.0.6 → 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
@@ -434,6 +434,7 @@ var require_main = __commonJS({
434
434
  // src/userResponse/utils.ts
435
435
  var utils_exports = {};
436
436
  __export(utils_exports, {
437
+ convertQuestionsToActions: () => convertQuestionsToActions,
437
438
  convertTopToLimit: () => convertTopToLimit,
438
439
  ensureQueryLimit: () => ensureQueryLimit,
439
440
  fixScalarSubqueries: () => fixScalarSubqueries,
@@ -535,6 +536,14 @@ function fixScalarSubqueries(query) {
535
536
  }
536
537
  return modifiedQuery;
537
538
  }
539
+ function convertQuestionsToActions(questions) {
540
+ return questions.map((question, index) => ({
541
+ id: `action_${index}_${Date.now()}`,
542
+ name: question,
543
+ type: "next_question",
544
+ question
545
+ }));
546
+ }
538
547
  function getJsonSizeInBytes(obj) {
539
548
  const jsonString = JSON.stringify(obj);
540
549
  return Buffer.byteLength(jsonString, "utf8");
@@ -855,7 +864,8 @@ var ComponentPropsSchema = import_zod3.z.object({
855
864
  query: import_zod3.z.string().optional(),
856
865
  title: import_zod3.z.string().optional(),
857
866
  description: import_zod3.z.string().optional(),
858
- config: import_zod3.z.record(import_zod3.z.unknown()).optional()
867
+ config: import_zod3.z.record(import_zod3.z.unknown()).optional(),
868
+ actions: import_zod3.z.array(import_zod3.z.any()).optional()
859
869
  });
860
870
  var ComponentSchema = import_zod3.z.object({
861
871
  id: import_zod3.z.string(),
@@ -1238,6 +1248,12 @@ var UIBlock = class {
1238
1248
  throw error;
1239
1249
  }
1240
1250
  }
1251
+ /**
1252
+ * Set or replace all actions
1253
+ */
1254
+ setActions(actions) {
1255
+ this.actions = actions;
1256
+ }
1241
1257
  /**
1242
1258
  * Add a single action (only if actions are resolved)
1243
1259
  */
@@ -2185,17 +2201,873 @@ var schema = new Schema();
2185
2201
  // src/userResponse/prompt-loader.ts
2186
2202
  var import_fs3 = __toESM(require("fs"));
2187
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
2188
3035
  var PromptLoader = class {
2189
3036
  constructor(config) {
2190
3037
  this.promptCache = /* @__PURE__ */ new Map();
2191
3038
  this.isInitialized = false;
2192
- logger.debug("Initializing PromptLoader...", process.cwd());
3039
+ logger.debug("Initializing PromptLoader...");
2193
3040
  this.promptsDir = config?.promptsDir || import_path2.default.join(process.cwd(), ".prompts");
2194
- 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(", ")}`);
2195
3067
  }
2196
3068
  /**
2197
3069
  * Initialize and cache all prompts into memory
2198
- * This should be called once at SDK startup
3070
+ * Tries file system first, then falls back to hardcoded prompts
2199
3071
  */
2200
3072
  async initialize() {
2201
3073
  if (this.isInitialized) {
@@ -2203,61 +3075,19 @@ var PromptLoader = class {
2203
3075
  return;
2204
3076
  }
2205
3077
  logger.info("Loading prompts into memory...");
2206
- const promptTypes = [
2207
- "classify",
2208
- "match-component",
2209
- "modify-props",
2210
- "single-component",
2211
- "mutli-component",
2212
- "actions",
2213
- "container-metadata",
2214
- "text-response",
2215
- "match-text-components"
2216
- ];
2217
- for (const promptType of promptTypes) {
3078
+ const promptTypes = Object.keys(PROMPTS);
3079
+ for (const promptName of promptTypes) {
2218
3080
  try {
2219
- const template = await this.loadPromptTemplate(promptType);
2220
- this.promptCache.set(promptType, template);
2221
- logger.debug(`Cached prompt: ${promptType}`);
3081
+ const template = this.loadPromptTemplate(promptName);
3082
+ this.promptCache.set(promptName, template);
2222
3083
  } catch (error) {
2223
- logger.error(`Failed to load prompt '${promptType}':`, error);
3084
+ logger.error(`Failed to load prompt '${promptName}':`, error);
2224
3085
  throw error;
2225
3086
  }
2226
3087
  }
2227
3088
  this.isInitialized = true;
2228
3089
  logger.info(`Successfully loaded ${this.promptCache.size} prompt templates into memory`);
2229
3090
  }
2230
- /**
2231
- * Load a prompt template from file system (tries custom dir first, then defaults to SDK dir)
2232
- * @param promptName - Name of the prompt folder
2233
- * @returns Template with system and user prompts
2234
- */
2235
- async loadPromptTemplate(promptName) {
2236
- const tryLoadFromDir = (dir) => {
2237
- try {
2238
- const systemPath = import_path2.default.join(dir, promptName, "system.md");
2239
- const userPath = import_path2.default.join(dir, promptName, "user.md");
2240
- if (import_fs3.default.existsSync(systemPath) && import_fs3.default.existsSync(userPath)) {
2241
- const system = import_fs3.default.readFileSync(systemPath, "utf-8");
2242
- const user = import_fs3.default.readFileSync(userPath, "utf-8");
2243
- logger.debug(`Loaded prompt '${promptName}' from ${dir}`);
2244
- return { system, user };
2245
- }
2246
- return null;
2247
- } catch (error) {
2248
- return null;
2249
- }
2250
- };
2251
- let template = tryLoadFromDir(this.promptsDir);
2252
- if (!template) {
2253
- logger.warn(`Prompt '${promptName}' not found in ${this.promptsDir}, trying default location...`);
2254
- template = tryLoadFromDir(this.defaultPromptsDir);
2255
- }
2256
- if (!template) {
2257
- throw new Error(`Prompt template '${promptName}' not found in either ${this.promptsDir} or ${this.defaultPromptsDir}`);
2258
- }
2259
- return template;
2260
- }
2261
3091
  /**
2262
3092
  * Replace variables in a template string using {{VARIABLE_NAME}} pattern
2263
3093
  * @param template - Template string with placeholders
@@ -2275,13 +3105,13 @@ var PromptLoader = class {
2275
3105
  }
2276
3106
  /**
2277
3107
  * Load both system and user prompts from cache and replace variables
2278
- * @param promptName - Name of the prompt folder
3108
+ * @param promptName - Name of the prompt
2279
3109
  * @param variables - Variables to replace in the templates
2280
3110
  * @returns Object containing both system and user prompts
2281
3111
  */
2282
3112
  async loadPrompts(promptName, variables) {
2283
3113
  if (!this.isInitialized) {
2284
- logger.warn("PromptLoader not initialized, loading prompts on-demand (not recommended)");
3114
+ logger.warn("PromptLoader not initialized, initializing now...");
2285
3115
  await this.initialize();
2286
3116
  }
2287
3117
  const template = this.promptCache.get(promptName);
@@ -2309,6 +3139,7 @@ var PromptLoader = class {
2309
3139
  this.promptsDir = dir;
2310
3140
  this.isInitialized = false;
2311
3141
  this.promptCache.clear();
3142
+ logger.debug(`Prompts directory changed to: ${dir}`);
2312
3143
  }
2313
3144
  /**
2314
3145
  * Get current prompts directory
@@ -2600,6 +3431,42 @@ var LLM = class {
2600
3431
  }
2601
3432
  };
2602
3433
 
3434
+ // src/userResponse/knowledge-base.ts
3435
+ var getKnowledgeBase = async ({
3436
+ prompt,
3437
+ collections,
3438
+ topK = 1
3439
+ }) => {
3440
+ try {
3441
+ if (!collections || !collections["knowledge-base"] || !collections["knowledge-base"]["query"]) {
3442
+ logger.info("[KnowledgeBase] knowledge-base.query collection not registered, skipping");
3443
+ return "";
3444
+ }
3445
+ logger.info(`[KnowledgeBase] Querying knowledge base for: "${prompt.substring(0, 50)}..."`);
3446
+ const result = await collections["knowledge-base"]["query"]({
3447
+ prompt,
3448
+ topK
3449
+ });
3450
+ if (!result || !result.content) {
3451
+ logger.error("[KnowledgeBase] No knowledge base results returned");
3452
+ return "";
3453
+ }
3454
+ logger.info(`[KnowledgeBase] Retrieved knowledge base context (${result.content.length} chars)`);
3455
+ if (result.metadata?.sources && result.metadata.sources.length > 0) {
3456
+ logger.debug(`[KnowledgeBase] Sources: ${result.metadata.sources.map((s) => s.title).join(", ")}`);
3457
+ }
3458
+ return result.content;
3459
+ } catch (error) {
3460
+ const errorMsg = error instanceof Error ? error.message : String(error);
3461
+ logger.warn(`[KnowledgeBase] Error querying knowledge base: ${errorMsg}`);
3462
+ return "";
3463
+ }
3464
+ };
3465
+ var KB = {
3466
+ getKnowledgeBase
3467
+ };
3468
+ var knowledge_base_default = KB;
3469
+
2603
3470
  // src/userResponse/base-llm.ts
2604
3471
  var BaseLLM = class {
2605
3472
  constructor(config) {
@@ -3139,13 +4006,14 @@ var BaseLLM = class {
3139
4006
  }
3140
4007
  }
3141
4008
  /**
3142
- * Match components from text response suggestions
4009
+ * Match components from text response suggestions and generate follow-up questions
3143
4010
  * Takes a text response with component suggestions (c1:type format) and matches with available components
4011
+ * Also generates intelligent follow-up questions (actions) based on the analysis
3144
4012
  * @param textResponse - The text response containing component suggestions
3145
4013
  * @param components - List of available components
3146
4014
  * @param apiKey - Optional API key
3147
4015
  * @param logCollector - Optional log collector
3148
- * @returns Object containing matched components, selected layout, and reasoning
4016
+ * @returns Object containing matched components, selected layout, reasoning, and follow-up actions
3149
4017
  */
3150
4018
  async matchComponentsFromTextResponse(textResponse, components, apiKey, logCollector) {
3151
4019
  try {
@@ -3187,7 +4055,6 @@ var BaseLLM = class {
3187
4055
  // Don't parse as JSON yet, get raw response
3188
4056
  );
3189
4057
  logger.debug(`[${this.getProviderName()}] Raw component matching response length: ${rawResponse?.length || 0}`);
3190
- logger.file(`[${this.getProviderName()}] Component matching raw response:`, rawResponse);
3191
4058
  let result;
3192
4059
  try {
3193
4060
  let cleanedResponse = rawResponse || "";
@@ -3230,7 +4097,8 @@ var BaseLLM = class {
3230
4097
  selectedLayout: "MultiComponentContainer",
3231
4098
  selectedLayoutId: "",
3232
4099
  selectedLayoutComponent: null,
3233
- layoutReasoning: "No layout selected"
4100
+ layoutReasoning: "No layout selected",
4101
+ actions: []
3234
4102
  };
3235
4103
  }
3236
4104
  }
@@ -3238,6 +4106,8 @@ var BaseLLM = class {
3238
4106
  const selectedLayout = result.selectedLayout || "MultiComponentContainer";
3239
4107
  const selectedLayoutId = result.selectedLayoutId || "";
3240
4108
  const layoutReasoning = result.layoutReasoning || "No layout reasoning provided";
4109
+ const rawActions = result.actions || [];
4110
+ const actions = convertQuestionsToActions(rawActions);
3241
4111
  let selectedLayoutComponent = null;
3242
4112
  if (selectedLayoutId) {
3243
4113
  selectedLayoutComponent = components.find((c) => c.id === selectedLayoutId) || null;
@@ -3248,6 +4118,7 @@ var BaseLLM = class {
3248
4118
  logger.info(`[${this.getProviderName()}] Matched ${matchedComponents.length} components from text response`);
3249
4119
  logger.info(`[${this.getProviderName()}] Selected layout: ${selectedLayout} (ID: ${selectedLayoutId})`);
3250
4120
  logger.info(`[${this.getProviderName()}] Layout reasoning: ${layoutReasoning}`);
4121
+ logger.info(`[${this.getProviderName()}] Generated ${actions.length} follow-up actions`);
3251
4122
  if (matchedComponents.length > 0) {
3252
4123
  logCollector?.info(`Matched ${matchedComponents.length} components for visualization using ${selectedLayout}`);
3253
4124
  logCollector?.info(`Layout reasoning: ${layoutReasoning}`);
@@ -3262,6 +4133,12 @@ var BaseLLM = class {
3262
4133
  }
3263
4134
  });
3264
4135
  }
4136
+ if (actions.length > 0) {
4137
+ logCollector?.info(`Generated ${actions.length} follow-up questions`);
4138
+ actions.forEach((action, idx) => {
4139
+ logCollector?.info(` ${idx + 1}. ${action.name}`);
4140
+ });
4141
+ }
3265
4142
  const finalComponents = matchedComponents.map((mc) => {
3266
4143
  const originalComponent = components.find((c) => c.id === mc.componentId);
3267
4144
  if (!originalComponent) {
@@ -3281,7 +4158,8 @@ var BaseLLM = class {
3281
4158
  selectedLayout,
3282
4159
  selectedLayoutId,
3283
4160
  selectedLayoutComponent,
3284
- layoutReasoning
4161
+ layoutReasoning,
4162
+ actions
3285
4163
  };
3286
4164
  } catch (error) {
3287
4165
  const errorMsg = error instanceof Error ? error.message : String(error);
@@ -3293,7 +4171,8 @@ var BaseLLM = class {
3293
4171
  selectedLayout: "MultiComponentContainer",
3294
4172
  selectedLayoutId: "",
3295
4173
  selectedLayoutComponent: null,
3296
- layoutReasoning: "Error occurred during component matching"
4174
+ layoutReasoning: "Error occurred during component matching",
4175
+ actions: []
3297
4176
  };
3298
4177
  }
3299
4178
  }
@@ -3312,10 +4191,17 @@ var BaseLLM = class {
3312
4191
  logger.debug(`[${this.getProviderName()}] User prompt: "${userPrompt.substring(0, 50)}..."`);
3313
4192
  try {
3314
4193
  const schemaDoc = schema.generateSchemaDocumentation();
4194
+ const knowledgeBaseContext = await knowledge_base_default.getKnowledgeBase({
4195
+ prompt: userPrompt,
4196
+ collections,
4197
+ topK: 1
4198
+ });
4199
+ logger.file("\n=============================\nknowledge base context:", knowledgeBaseContext);
3315
4200
  const prompts = await promptLoader.loadPrompts("text-response", {
3316
4201
  USER_PROMPT: userPrompt,
3317
4202
  CONVERSATION_HISTORY: conversationHistory || "No previous conversation",
3318
- SCHEMA_DOC: schemaDoc
4203
+ SCHEMA_DOC: schemaDoc,
4204
+ KNOWLEDGE_BASE_CONTEXT: knowledgeBaseContext || "No additional knowledge base context available."
3319
4205
  });
3320
4206
  logger.file("\n=============================\nsystem prompt:", prompts.system);
3321
4207
  logger.file("\n=============================\nuser prompt:", prompts.user);
@@ -3516,6 +4402,7 @@ ${errorMsg}
3516
4402
  text: textResponse,
3517
4403
  // Include the streamed text showing all attempts
3518
4404
  matchedComponents: [],
4405
+ actions: [],
3519
4406
  method: `${this.getProviderName()}-text-response-max-attempts`
3520
4407
  }
3521
4408
  };
@@ -3531,6 +4418,7 @@ ${errorMsg}
3531
4418
  let matchedComponents = [];
3532
4419
  let selectedLayoutComponent = null;
3533
4420
  let layoutReasoning = "No layout selected";
4421
+ let actions = [];
3534
4422
  if (components && components.length > 0) {
3535
4423
  logger.info(`[${this.getProviderName()}] Matching components from text response...`);
3536
4424
  const matchResult = await this.matchComponentsFromTextResponse(
@@ -3542,6 +4430,7 @@ ${errorMsg}
3542
4430
  matchedComponents = matchResult.components;
3543
4431
  selectedLayoutComponent = matchResult.selectedLayoutComponent;
3544
4432
  layoutReasoning = matchResult.layoutReasoning;
4433
+ actions = matchResult.actions;
3545
4434
  }
3546
4435
  let container_componet = null;
3547
4436
  if (matchedComponents.length > 0) {
@@ -3555,11 +4444,12 @@ ${errorMsg}
3555
4444
  config: {
3556
4445
  ...selectedLayoutComponent.props?.config || {},
3557
4446
  components: matchedComponents
3558
- }
4447
+ },
4448
+ actions
3559
4449
  }
3560
4450
  };
3561
- logger.info(`[${this.getProviderName()}] Created ${selectedLayoutComponent.name} (${selectedLayoutComponent.type}) container with ${matchedComponents.length} components`);
3562
- logCollector?.info(`Created ${selectedLayoutComponent.name} with ${matchedComponents.length} components: ${layoutReasoning}`);
4451
+ logger.info(`[${this.getProviderName()}] Created ${selectedLayoutComponent.name} (${selectedLayoutComponent.type}) container with ${matchedComponents.length} components and ${actions.length} actions`);
4452
+ logCollector?.info(`Created ${selectedLayoutComponent.name} with ${matchedComponents.length} components and ${actions.length} actions: ${layoutReasoning}`);
3563
4453
  } else {
3564
4454
  container_componet = {
3565
4455
  id: `multi_container_${Date.now()}`,
@@ -3571,11 +4461,12 @@ ${errorMsg}
3571
4461
  props: {
3572
4462
  config: {
3573
4463
  components: matchedComponents
3574
- }
4464
+ },
4465
+ actions
3575
4466
  }
3576
4467
  };
3577
- logger.info(`[${this.getProviderName()}] Created fallback MultiComponentContainer with ${matchedComponents.length} components`);
3578
- logCollector?.info(`Created MultiComponentContainer with ${matchedComponents.length} components: ${layoutReasoning}`);
4468
+ logger.info(`[${this.getProviderName()}] Created fallback MultiComponentContainer with ${matchedComponents.length} components and ${actions.length} actions`);
4469
+ logCollector?.info(`Created MultiComponentContainer with ${matchedComponents.length} components and ${actions.length} actions: ${layoutReasoning}`);
3579
4470
  }
3580
4471
  }
3581
4472
  return {
@@ -3585,6 +4476,7 @@ ${errorMsg}
3585
4476
  matchedComponents,
3586
4477
  component: container_componet,
3587
4478
  layoutReasoning,
4479
+ actions,
3588
4480
  method: `${this.getProviderName()}-text-response`
3589
4481
  },
3590
4482
  errors: []
@@ -3600,6 +4492,7 @@ ${errorMsg}
3600
4492
  data: {
3601
4493
  text: "I apologize, but I encountered an error while processing your question. Please try rephrasing or ask something else.",
3602
4494
  matchedComponents: [],
4495
+ actions: [],
3603
4496
  method: `${this.getProviderName()}-text-response-error`
3604
4497
  }
3605
4498
  };
@@ -4350,6 +5243,7 @@ var get_user_request = async (data, components, sendMessage, anthropicApiKey, gr
4350
5243
  }
4351
5244
  let component = null;
4352
5245
  let textResponse = null;
5246
+ let actions = [];
4353
5247
  if (userResponse.data) {
4354
5248
  if (typeof userResponse.data === "object") {
4355
5249
  if ("component" in userResponse.data) {
@@ -4358,6 +5252,9 @@ var get_user_request = async (data, components, sendMessage, anthropicApiKey, gr
4358
5252
  if ("textResponse" in userResponse.data) {
4359
5253
  textResponse = userResponse.data.text;
4360
5254
  }
5255
+ if ("actions" in userResponse.data) {
5256
+ actions = userResponse.data.actions || [];
5257
+ }
4361
5258
  }
4362
5259
  }
4363
5260
  const finalTextResponse = responseMode === "text" && accumulatedStreamResponse ? accumulatedStreamResponse : textResponse;
@@ -4368,11 +5265,15 @@ var get_user_request = async (data, components, sendMessage, anthropicApiKey, gr
4368
5265
  component,
4369
5266
  // generatedComponentMetadata: full component object (ComponentSchema)
4370
5267
  [],
4371
- // actions: empty initially
5268
+ // actions: empty initially, will be set below
4372
5269
  uiBlockId,
4373
5270
  finalTextResponse
4374
5271
  // textResponse: FULL streaming response including all intermediate messages
4375
5272
  );
5273
+ if (actions.length > 0) {
5274
+ uiBlock.setActions(actions);
5275
+ logger.info(`Stored ${actions.length} actions in UIBlock: ${uiBlockId}`);
5276
+ }
4376
5277
  thread.addUIBlock(uiBlock);
4377
5278
  logger.info(`Created UIBlock: ${uiBlockId} in Thread: ${threadId}`);
4378
5279
  return {
@@ -4610,7 +5511,6 @@ async function handleActionsRequest(data, sendMessage, anthropicApiKey, groqApiK
4610
5511
  const uiBlockId = SA_RUNTIME.uiBlockId;
4611
5512
  const threadId = SA_RUNTIME.threadId;
4612
5513
  logger.debug(`[ACTIONS_REQ ${id}] SA_RUNTIME validated - threadId: ${threadId}, uiBlockId: ${uiBlockId}`);
4613
- logger.debug(`[ACTIONS_REQ ${id}] Retrieving thread: ${threadId}`);
4614
5514
  const threadManager = ThreadManager.getInstance();
4615
5515
  const thread = threadManager.getThread(threadId);
4616
5516
  if (!thread) {
@@ -6311,6 +7211,7 @@ var SuperatomSDK = class {
6311
7211
  }
6312
7212
  /**
6313
7213
  * Initialize PromptLoader and load prompts into memory
7214
+ * Tries to load from file system first, then falls back to hardcoded prompts
6314
7215
  */
6315
7216
  async initializePromptLoader(promptsDir) {
6316
7217
  try {