@superatomai/sdk-node 0.0.13 → 0.0.15

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
@@ -562,6 +562,25 @@ var ReportsRequestMessageSchema = import_zod3.z.object({
562
562
  type: import_zod3.z.literal("REPORTS"),
563
563
  payload: ReportsRequestPayloadSchema
564
564
  });
565
+ var UIBlockSchema = import_zod3.z.object({
566
+ id: import_zod3.z.string().optional(),
567
+ userQuestion: import_zod3.z.string().optional(),
568
+ text: import_zod3.z.string().optional(),
569
+ textResponse: import_zod3.z.string().optional(),
570
+ component: ComponentSchema.optional(),
571
+ // Legacy field
572
+ generatedComponentMetadata: ComponentSchema.optional(),
573
+ // Actual field used by UIBlock class
574
+ componentData: import_zod3.z.record(import_zod3.z.any()).optional(),
575
+ actions: import_zod3.z.array(import_zod3.z.any()).optional(),
576
+ isFetchingActions: import_zod3.z.boolean().optional(),
577
+ createdAt: import_zod3.z.string().optional(),
578
+ metadata: import_zod3.z.object({
579
+ timestamp: import_zod3.z.number().optional(),
580
+ userPrompt: import_zod3.z.string().optional(),
581
+ similarity: import_zod3.z.number().optional()
582
+ }).optional()
583
+ });
565
584
  var BookmarkDataSchema = import_zod3.z.object({
566
585
  id: import_zod3.z.number().optional(),
567
586
  uiblock: import_zod3.z.any(),
@@ -570,9 +589,11 @@ var BookmarkDataSchema = import_zod3.z.object({
570
589
  updated_at: import_zod3.z.string().optional()
571
590
  });
572
591
  var BookmarksRequestPayloadSchema = import_zod3.z.object({
573
- operation: import_zod3.z.enum(["create", "update", "delete", "getAll", "getOne"]),
592
+ operation: import_zod3.z.enum(["create", "update", "delete", "getAll", "getOne", "getByUser", "getByThread"]),
574
593
  data: import_zod3.z.object({
575
594
  id: import_zod3.z.number().optional(),
595
+ userId: import_zod3.z.number().optional(),
596
+ threadId: import_zod3.z.string().optional(),
576
597
  uiblock: import_zod3.z.any().optional()
577
598
  }).optional()
578
599
  });
@@ -1400,7 +1421,7 @@ async function cleanupUserStorage() {
1400
1421
  }
1401
1422
 
1402
1423
  // src/auth/validator.ts
1403
- function validateUser(credentials) {
1424
+ async function validateUser(credentials, collections) {
1404
1425
  const { username, email, password } = credentials;
1405
1426
  const identifier = username || email;
1406
1427
  logger.debug("[validateUser] Starting user validation");
@@ -1412,7 +1433,39 @@ function validateUser(credentials) {
1412
1433
  error: "Username or email and password are required"
1413
1434
  };
1414
1435
  }
1415
- logger.debug(`[validateUser] Looking up user by identifier: ${identifier}`);
1436
+ if (collections && collections["users"] && collections["users"]["authenticate"]) {
1437
+ logger.debug(`[validateUser] Attempting database authentication for: ${identifier}`);
1438
+ try {
1439
+ const dbResult = await collections["users"]["authenticate"]({
1440
+ identifier,
1441
+ password
1442
+ });
1443
+ logger.info("[validateUser] Database authentication attempt completed", dbResult);
1444
+ if (dbResult && dbResult.success && dbResult.data) {
1445
+ logger.info(`[validateUser] \u2713 User authenticated via database: ${dbResult.data.username}`);
1446
+ return {
1447
+ success: true,
1448
+ data: dbResult.data.username,
1449
+ username: dbResult.data.username,
1450
+ userId: dbResult.data.id
1451
+ };
1452
+ } else {
1453
+ logger.debug(`[validateUser] Database auth failed for ${identifier}: ${dbResult?.error || "Invalid credentials"}`);
1454
+ if (dbResult && dbResult.error === "Invalid credentials") {
1455
+ return {
1456
+ success: false,
1457
+ error: "Invalid credentials"
1458
+ };
1459
+ }
1460
+ }
1461
+ } catch (error) {
1462
+ const errorMsg = error instanceof Error ? error.message : String(error);
1463
+ logger.debug(`[validateUser] Database lookup error: ${errorMsg}, falling back to file storage`);
1464
+ }
1465
+ } else {
1466
+ logger.debug("[validateUser] No users collection available, using file storage only");
1467
+ }
1468
+ logger.info(`[validateUser] Attempting file-based validation for: ${identifier}`);
1416
1469
  const user = findUserByUsernameOrEmail(identifier);
1417
1470
  if (!user) {
1418
1471
  logger.warn(`[validateUser] Validation failed: User not found - ${identifier}`);
@@ -1421,7 +1474,7 @@ function validateUser(credentials) {
1421
1474
  error: "Invalid username or email"
1422
1475
  };
1423
1476
  }
1424
- logger.debug(`[validateUser] User found: ${user.username}, verifying password`);
1477
+ logger.debug(`[validateUser] User found in file storage: ${user.username}, verifying password`);
1425
1478
  const hashedPassword = hashPassword(user.password);
1426
1479
  if (hashedPassword !== password) {
1427
1480
  logger.warn(`[validateUser] Validation failed: Invalid password for user - ${user.username}`);
@@ -1431,19 +1484,18 @@ function validateUser(credentials) {
1431
1484
  error: "Invalid password"
1432
1485
  };
1433
1486
  }
1434
- logger.info(`[validateUser] \u2713 User validated successfully: ${user.username}`);
1435
- logger.debug(`[validateUser] Returning user data for: ${user.username}`);
1487
+ logger.info(`[validateUser] \u2713 User validated via file storage: ${user.username}`);
1436
1488
  return {
1437
1489
  success: true,
1438
1490
  data: user.username,
1439
1491
  username: user.username
1440
1492
  };
1441
1493
  }
1442
- function authenticateAndStoreWsId(credentials, wsId) {
1494
+ async function authenticateAndStoreWsId(credentials, wsId, collections) {
1443
1495
  const identifier = credentials.username || credentials.email;
1444
1496
  logger.debug("[authenticateAndStoreWsId] Starting authentication and WebSocket ID storage");
1445
1497
  logger.debug("[authenticateAndStoreWsId] Validating user credentials");
1446
- const validationResult = validateUser(credentials);
1498
+ const validationResult = await validateUser(credentials, collections);
1447
1499
  if (!validationResult.success) {
1448
1500
  logger.warn(`[authenticateAndStoreWsId] User validation failed for: ${identifier}`);
1449
1501
  return validationResult;
@@ -1455,7 +1507,7 @@ function authenticateAndStoreWsId(credentials, wsId) {
1455
1507
  logger.debug(`[authenticateAndStoreWsId] WebSocket ID ${wsId} associated with user ${username}`);
1456
1508
  return validationResult;
1457
1509
  }
1458
- function verifyAuthToken(authToken) {
1510
+ async function verifyAuthToken(authToken, collections) {
1459
1511
  try {
1460
1512
  logger.debug("[verifyAuthToken] Starting token verification");
1461
1513
  logger.debug("[verifyAuthToken] Decoding base64 token");
@@ -1465,7 +1517,7 @@ function verifyAuthToken(authToken) {
1465
1517
  logger.debug("[verifyAuthToken] Token decoded and parsed successfully");
1466
1518
  logger.debug(`[verifyAuthToken] Token contains username: ${credentials.username ? "\u2713" : "\u2717"}`);
1467
1519
  logger.debug("[verifyAuthToken] Validating credentials from token");
1468
- const result = validateUser(credentials);
1520
+ const result = await validateUser(credentials, collections);
1469
1521
  if (result.success) {
1470
1522
  logger.info(`[verifyAuthToken] \u2713 Token verified successfully for user: ${credentials.username || "unknown"}`);
1471
1523
  } else {
@@ -1484,7 +1536,7 @@ function verifyAuthToken(authToken) {
1484
1536
  }
1485
1537
 
1486
1538
  // src/handlers/auth-login-requests.ts
1487
- async function handleAuthLoginRequest(data, sendMessage) {
1539
+ async function handleAuthLoginRequest(data, collections, sendMessage) {
1488
1540
  try {
1489
1541
  logger.debug("[AUTH_LOGIN_REQ] Parsing incoming auth login request");
1490
1542
  const authRequest = AuthLoginRequestMessageSchema.parse(data);
@@ -1543,12 +1595,12 @@ async function handleAuthLoginRequest(data, sendMessage) {
1543
1595
  }, sendMessage, wsId);
1544
1596
  return;
1545
1597
  }
1546
- logger.info(`[AUTH_LOGIN_REQ ${id}] Credentials validated, authenticating user: ${identifier}`);
1547
- logger.debug(`[AUTH_LOGIN_REQ ${id}] WebSocket ID: ${wsId}`);
1598
+ logger.info(`[AUTH_LOGIN_REQ ${id}] Credentials validated, authenticating user: ${identifier} username: ${username} email: ${email} password: ${password}`);
1548
1599
  logger.debug(`[AUTH_LOGIN_REQ ${id}] Calling authenticateAndStoreWsId for user: ${identifier}`);
1549
- const authResult = authenticateAndStoreWsId(
1600
+ const authResult = await authenticateAndStoreWsId(
1550
1601
  { username, email, password },
1551
- wsId
1602
+ wsId,
1603
+ collections
1552
1604
  );
1553
1605
  logger.info(`[AUTH_LOGIN_REQ ${id}] Authentication result for ${identifier}: ${authResult.success ? "success" : "failed"}`);
1554
1606
  if (!authResult.success) {
@@ -1600,7 +1652,7 @@ function sendDataResponse2(id, res, sendMessage, clientId) {
1600
1652
  }
1601
1653
 
1602
1654
  // src/handlers/auth-verify-request.ts
1603
- async function handleAuthVerifyRequest(data, sendMessage) {
1655
+ async function handleAuthVerifyRequest(data, collections, sendMessage) {
1604
1656
  try {
1605
1657
  logger.debug("[AUTH_VERIFY_REQ] Parsing incoming auth verify request");
1606
1658
  const authRequest = AuthVerifyRequestMessageSchema.parse(data);
@@ -1630,7 +1682,7 @@ async function handleAuthVerifyRequest(data, sendMessage) {
1630
1682
  logger.debug(`[AUTH_VERIFY_REQ ${id}] WebSocket ID: ${wsId}`);
1631
1683
  logger.debug(`[AUTH_VERIFY_REQ ${id}] Calling verifyAuthToken`);
1632
1684
  const startTime = Date.now();
1633
- const authResult = verifyAuthToken(token);
1685
+ const authResult = await verifyAuthToken(token, collections);
1634
1686
  const verificationTime = Date.now() - startTime;
1635
1687
  logger.info(`[AUTH_VERIFY_REQ ${id}] Token verification completed in ${verificationTime}ms - ${authResult.success ? "valid" : "invalid"}`);
1636
1688
  if (!authResult.success) {
@@ -1829,489 +1881,126 @@ var import_path2 = __toESM(require("path"));
1829
1881
 
1830
1882
  // src/userResponse/prompts.ts
1831
1883
  var PROMPTS = {
1832
- "classify": {
1833
- system: `You are an expert AI that classifies user questions about data and determines the appropriate visualizations needed.
1834
-
1835
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
1836
-
1837
- ## Previous Conversation
1838
- {{CONVERSATION_HISTORY}}
1839
-
1840
- **Note:** If there is previous conversation history, use it to understand context. For example:
1841
- - If user previously asked about "sales" and now asks "show me trends", understand it refers to sales trends
1842
- - If user asked for "revenue by region" and now says "make it a pie chart", understand they want to modify the previous visualization
1843
- - Use the history to resolve ambiguous references like "that", "it", "them", "the data"
1844
-
1845
- Your task is to analyze the user's question and determine:
1846
-
1847
- 1. **Question Type:**
1848
- - "analytical": Questions asking to VIEW, ANALYZE, or VISUALIZE data
1849
-
1850
- - "data_modification": Questions asking to CREATE, UPDATE, DELETE, or MODIFY data
1851
-
1852
- - "general": General questions, greetings, or requests not related to data
1853
-
1854
- 2. **Required Visualizations** (only for analytical questions):
1855
- Determine which visualization type(s) would BEST answer the user's question:
1856
-
1857
- - **KPICard**: Single metric, total, count, average, percentage, or summary number
1858
-
1859
- - **LineChart**: Trends over time, time series, growth/decline patterns
1860
-
1861
-
1862
- - **BarChart**: Comparing categories, rankings, distributions across groups
1863
-
1864
-
1865
- - **PieChart**: Proportions, percentages, composition, market share
1866
-
1867
-
1868
- - **DataTable**: Detailed lists, multiple attributes, when user needs to see records
1869
-
1870
-
1871
- 3. **Multiple Visualizations:**
1872
- User may need MULTIPLE visualizations together:
1873
-
1874
- Common combinations:
1875
- - KPICard + LineChart
1876
- - KPICard + BarChart
1877
- - KPICard + DataTable
1878
- - BarChart + PieChart:
1879
- - LineChart + DataTable
1880
- Set needsMultipleComponents to true if user needs multiple views of the data.
1884
+ "text-response": {
1885
+ system: `You are an intelligent AI assistant that provides helpful, accurate, and contextual text responses to user questions. You have access to a database and can execute SQL queries and external tools to answer user requests.
1881
1886
 
1882
- **Important Guidelines:**
1883
- - If user explicitly mentions a chart type RESPECT that preference
1884
- - If question is vague or needs both summary and detail, suggest KPICard + DataTable
1885
- - Only return visualizations for "analytical" questions
1886
- - For "data_modification" or "general", return empty array for visualizations
1887
+ ## Your Task
1887
1888
 
1888
- **Output Format:**
1889
- {
1890
- "questionType": "analytical" | "data_modification" | "general",
1891
- "visualizations": ["KPICard", "LineChart", ...], // Empty array if not analytical
1892
- "reasoning": "Explanation of classification and visualization choices",
1893
- "needsMultipleComponents": boolean
1894
- }
1895
- `,
1896
- user: `{{USER_PROMPT}}
1897
- `
1898
- },
1899
- "match-component": {
1900
- system: `You are an expert AI assistant specialized in matching user requests to the most appropriate data visualization components.
1889
+ Analyze the user's question and provide a helpful text response. Your response should:
1901
1890
 
1902
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
1891
+ 1. **Be Clear and Concise**: Provide direct answers without unnecessary verbosity
1892
+ 2. **Be Contextual**: Use conversation history to understand what the user is asking about
1893
+ 3. **Be Accurate**: Provide factually correct information based on the context
1894
+ 4. **Be Helpful**: Offer additional relevant information or suggestions when appropriate
1903
1895
 
1904
- ## Previous Conversation
1905
- {{CONVERSATION_HISTORY}}
1896
+ ## Available Tools
1906
1897
 
1907
- **Context Instructions:**
1908
- - If there is conversation history, use it to understand what the user is referring to
1909
- - When user says "show that as a chart" or "change it", they are referring to a previous component
1910
- - If user asks to "modify" or "update" something, match to the component they previously saw
1911
- - Use context to resolve ambiguous requests like "show trends for that" or "make it interactive"
1912
-
1913
- Your task is to analyze the user's natural language request and find the BEST matching component from the available list.
1914
-
1915
- Available Components:
1916
- {{COMPONENTS_TEXT}}
1917
-
1918
- **Matching Guidelines:**
1919
-
1920
- 1. **Understand User Intent:**
1921
- - What type of data visualization do they need? (KPI/metric, chart, table, etc.)
1922
- - What metric or data are they asking about? (revenue, orders, customers, etc.)
1923
- - Are they asking for a summary (KPI), trend (line chart), distribution (bar/pie), or detailed list (table)?
1924
- - Do they want to compare categories, see trends over time, or show proportions?
1925
-
1926
- 2. **Component Type Matching:**
1927
- - KPICard: Single metric/number (total, average, count, percentage, rate)
1928
- - LineChart: Trends over time, time series data
1929
- - BarChart: Comparing categories, distributions, rankings
1930
- - PieChart/DonutChart: Proportions, percentages, market share
1931
- - DataTable: Detailed lists, rankings with multiple attributes
1932
-
1933
- 3. **Keyword & Semantic Matching:**
1934
- - Match user query terms with component keywords
1935
- - Consider synonyms (e.g., "sales" = "revenue", "items" = "products")
1936
- - Look for category matches (financial, orders, customers, products, suppliers, logistics, geographic, operations)
1937
-
1938
- 4. **Scoring Criteria:**
1939
- - Exact keyword matches: High priority
1940
- - Component type alignment: High priority
1941
- - Category alignment: Medium priority
1942
- - Semantic similarity: Medium priority
1943
- - Specificity: Prefer more specific components over generic ones
1944
-
1945
- **Output Requirements:**
1946
-
1947
- Respond with a JSON object containing:
1948
- - componentIndex: the 1-based index of the BEST matching component (or null if confidence < 50%)
1949
- - componentId: the ID of the matched component
1950
- - reasoning: detailed explanation of why this component was chosen
1951
- - confidence: confidence score 0-100 (100 = perfect match)
1952
- - alternativeMatches: array of up to 2 alternative component indices with scores (optional)
1953
-
1954
- Example response:
1955
- {
1956
- "componentIndex": 5,
1957
- "componentId": "total_revenue_kpi",
1958
- "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'.",
1959
- "confidence": 95,
1960
- "alternativeMatches": [
1961
- {"index": 3, "id": "monthly_revenue_kpi", "score": 75, "reason": "Could show monthly revenue if time period was intended"},
1962
- {"index": 8, "id": "revenue_trend_chart", "score": 60, "reason": "Could show revenue trend if historical view was intended"}
1963
- ]
1964
- }
1898
+ The following external tools are available for this request (if applicable):
1965
1899
 
1966
- **Important:**
1967
- - Only return componentIndex if confidence >= 50%
1968
- - Return null if no reasonable match exists
1969
- - Prefer components that exactly match the user's metric over generic ones
1970
- - Consider the full context of the request, not just individual words`,
1971
- user: `Current user request: {{USER_PROMPT}}
1900
+ {{AVAILABLE_EXTERNAL_TOOLS}}
1972
1901
 
1973
- Find the best matching component considering the conversation history above. Explain your reasoning with a confidence score. Return ONLY valid JSON.`
1974
- },
1975
- "modify-props": {
1976
- system: `You are an AI assistant that validates and modifies component props based on user requests.
1902
+ When a tool is needed to complete the user's request:
1903
+ 1. **Analyze the request** to determine which tool(s) are needed
1904
+ 2. **Extract parameters** from the user's question that the tool requires
1905
+ 3. **Execute the tool** by calling it with the extracted parameters
1906
+ 4. **Present the results** in your response in a clear, user-friendly format
1907
+ 5. **Combine with other data** if the user's request requires both database queries and external tool results
1977
1908
 
1978
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
1909
+ ## Handling Data Questions
1979
1910
 
1980
- Given:
1981
- - A user's natural language request
1982
- - Component name: {{COMPONENT_NAME}}
1983
- - Component type: {{COMPONENT_TYPE}}
1984
- - Component description: {{COMPONENT_DESCRIPTION}}
1911
+ When the user asks about data
1985
1912
 
1986
- -
1987
- - Current component props with structure:
1988
- {
1989
- query?: string, // SQL query to fetch data
1990
- title?: string, // Component title
1991
- description?: string, // Component description
1992
- config?: { // Additional configuration
1993
- [key: string]: any
1994
- }
1995
- }
1913
+ 1. **Generate a SQL query** using the database schema provided above
1914
+ 2. **Use the execute_query tool** to run the query
1915
+ 3. **If the query fails**, analyze the error and generate a corrected query
1916
+ 4. **Format the results** in a clear, readable way for the user
1996
1917
 
1997
- Schema definition for the prop that must be passed to the component
1998
- -{{CURRENT_PROPS}}
1918
+ **Query Guidelines:**
1919
+ - Use correct table and column names from the schema
1920
+ - ALWAYS include a LIMIT clause with a MAXIMUM of 32 rows
1921
+ - Ensure valid SQL syntax
1922
+ - For time-based queries, use appropriate date functions
1923
+ - When using subqueries with scalar operators (=, <, >, etc.), add LIMIT 1 to prevent "more than one row" errors
1999
1924
 
2000
- Database Schema:
1925
+ ## Database Schema
2001
1926
  {{SCHEMA_DOC}}
2002
1927
 
2003
- ## Previous Conversation
2004
- {{CONVERSATION_HISTORY}}
2005
-
2006
- **Context Instructions:**
2007
- - Review the conversation history to understand the evolution of the component
2008
- - If user says "add filter for X", understand they want to modify the current query
2009
- - If user says "change to last month" or "filter by Y", apply modifications to existing query
2010
- - Previous questions can clarify what the user means by ambiguous requests like "change that filter"
2011
- - Use context to determine appropriate time ranges if user says "recent" or "latest"
2012
-
2013
- Your task is to intelligently modify the props based on the user's request:
1928
+ **Database Type: PostgreSQL**
2014
1929
 
2015
- 1. **Query Modification**:
2016
- - Modify SQL query if user requests different data, filters, time ranges, limits, or aggregations
2017
- - Use correct table and column names from the schema
2018
- - Ensure valid SQL syntax
2019
- - ALWAYS include a LIMIT clause (default: {{DEFAULT_LIMIT}} rows) to prevent large result sets
2020
- - Preserve the query structure that the component expects (e.g., column aliases)
1930
+ **CRITICAL PostgreSQL Query Rules:**
2021
1931
 
2022
- **CRITICAL - PostgreSQL Query Rules:**
1932
+ 1. **NO AGGREGATE FUNCTIONS IN WHERE CLAUSE** - This is a fundamental SQL error
1933
+ \u274C WRONG: \`WHERE COUNT(orders) > 0\`
1934
+ \u274C WRONG: \`WHERE SUM(price) > 100\`
1935
+ \u274C WRONG: \`WHERE AVG(rating) > 4.5\`
1936
+ \u274C WRONG: \`WHERE FLOOR(AVG(rating)) = 4\` (aggregate inside any function is still not allowed)
1937
+ \u274C WRONG: \`WHERE ROUND(SUM(price), 2) > 100\`
2023
1938
 
2024
- **NO AGGREGATE FUNCTIONS IN WHERE CLAUSE:**
2025
- \u274C WRONG: \`WHERE COUNT(orders) > 0\` or \`WHERE SUM(price) > 100\`
2026
1939
  \u2705 CORRECT: Use HAVING (with GROUP BY), EXISTS, or subquery
1940
+ \u2705 CORRECT: Move aggregate logic to HAVING: \`GROUP BY ... HAVING FLOOR(AVG(rating)) = 4\`
1941
+ \u2705 CORRECT: Use subquery for filtering: \`WHERE product_id IN (SELECT product_id FROM ... GROUP BY ... HAVING AVG(rating) >= 4)\`
2027
1942
 
2028
-
2029
- **WHERE vs HAVING:**
1943
+ 2. **WHERE vs HAVING**
2030
1944
  - WHERE filters rows BEFORE grouping (cannot use aggregates)
2031
1945
  - HAVING filters groups AFTER grouping (can use aggregates)
2032
1946
  - If using HAVING, you MUST have GROUP BY
2033
1947
 
2034
- **Subquery Rules:**
2035
- - When using a subquery with scalar comparison operators (=, <, >, <=, >=, <>), the subquery MUST return exactly ONE row
2036
- - ALWAYS add \`LIMIT 1\` to scalar subqueries to prevent "more than one row returned" errors
2037
- - Example: \`WHERE location_id = (SELECT store_id FROM orders ORDER BY total_amount DESC LIMIT 1)\`
2038
- - For multiple values, use \`IN\` instead: \`WHERE location_id IN (SELECT store_id FROM orders)\`
2039
- - Test your subqueries mentally: if they could return multiple rows, add LIMIT 1 or use IN
2040
-
2041
- 2. **Title Modification**:
2042
- - Update title to reflect the user's specific request
2043
- - Keep it concise and descriptive
2044
- - Match the tone of the original title
2045
-
2046
- 3. **Description Modification**:
2047
- - Update description to explain what data is shown
2048
- - Be specific about filters, time ranges, or groupings applied
2049
-
2050
- 4. **Config Modification** (based on component type):
2051
- - For KPICard: formatter, gradient, icon
2052
- - For Charts: colors, height, xKey, yKey, nameKey, valueKey
2053
- - For Tables: columns, pageSize, formatters
2054
-
2055
-
2056
- Respond with a JSON object:
2057
- {
2058
- "props": { /* modified props object with query, title, description, config */ },
2059
- "isModified": boolean,
2060
- "reasoning": "brief explanation of changes",
2061
- "modifications": ["list of specific changes made"]
2062
- }
2063
-
2064
- IMPORTANT:
2065
- - Return the COMPLETE props object, not just modified fields
2066
- - Preserve the structure expected by the component type
2067
- - Ensure query returns columns with expected aliases
2068
- - Keep config properties that aren't affected by the request`,
2069
- user: `{{USER_PROMPT}}`
2070
- },
2071
- "single-component": {
2072
- system: `You are an expert AI assistant specialized in matching user requests to the most appropriate component from a filtered list.
2073
-
2074
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2075
-
2076
-
2077
- ## Previous Conversation
2078
- {{CONVERSATION_HISTORY}}
2079
-
2080
- **Context Instructions:**
2081
- - If there is previous conversation history, use it to understand what the user is referring to
2082
- - When user says "show trends", "add filters", "change that", understand they may be building on previous queries
2083
- - Use previous component types and queries as context to inform your current matching
2084
-
2085
- ## Available Components (Type: {{COMPONENT_TYPE}})
2086
- The following components have been filtered by type {{COMPONENT_TYPE}}. Select the BEST matching one:
2087
-
2088
- {{COMPONENTS_LIST}}
2089
-
2090
- {{VISUALIZATION_CONSTRAINT}}
2091
-
2092
- **Select the BEST matching component** from the available {{COMPONENT_TYPE}} components listed above that would best answer the user's question.
2093
-
2094
- **Matching Guidelines:**
2095
- 1. **Semantic Matching:**
2096
- - Match based on component name, description, and keywords
2097
- - Consider what metrics/data the user is asking about
2098
- - Look for semantic similarity (e.g., "sales" matches "revenue", "orders" matches "purchases")
2099
-
2100
- 2. **Query Relevance:**
2101
- - Consider the component's existing query structure
2102
- - Does it query the right tables/columns for the user's question?
2103
- - Can it be modified to answer the user's specific question?
2104
-
2105
- 3. **Scoring Criteria:**
2106
- - Exact keyword matches in name/description: High priority
2107
- - Semantic similarity to user intent: High priority
2108
- - Appropriate aggregation/grouping: Medium priority
2109
- - Category alignment: Medium priority
2110
-
2111
- **Output Requirements:**
2112
-
2113
- Respond with a JSON object:
2114
- {
2115
- "componentId": "matched_component_id",
2116
- "componentIndex": 1, // 1-based index from the filtered list above
2117
- "reasoning": "Detailed explanation of why this component best matches the user's question",
2118
- "confidence": 85, // Confidence score 0-100
2119
- "canGenerate": true // false if no suitable component found (confidence < 50)
2120
- }
2121
-
2122
- **Important:**
2123
- - Only set canGenerate to true if confidence >= 50%
2124
- - If no component from the list matches well (all have low relevance), set canGenerate to false
2125
- - Consider the full context of the request and conversation history
2126
- - The component's props (query, title, description, config) will be modified later based on the user's specific request
2127
- - Focus on finding the component that is closest to what the user needs, even if it needs modification`,
2128
- user: `{{USER_PROMPT}}
2129
-
2130
- `
2131
- },
2132
- "mutli-component": {
2133
- system: `You are an expert data analyst AI that creates comprehensive multi-component analytical dashboards with aesthetically pleasing and balanced layouts.
2134
-
2135
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2136
-
2137
- Database Schema:
2138
- {{SCHEMA_DOC}}
2139
-
2140
- ## Previous Conversation
2141
- {{CONVERSATION_HISTORY}}
2142
-
2143
- **Context Instructions:**
2144
- - Review the conversation history to understand what the user has asked before
2145
- - If user is building on previous insights (e.g., "now show me X and Y"), use context to inform dashboard design
2146
- - Previous queries can help determine appropriate filters, date ranges, or categories to use
2147
- - If user asks for "comprehensive view" or "dashboard for X", include complementary components based on context
2148
-
2149
- Given a user's analytical question and the required visualization types, your task is to:
2150
-
2151
- 1. **Determine Container Metadata:**
2152
- - title: Clear, descriptive title for the entire dashboard (2-5 words)
2153
- - description: Brief explanation of what insights this dashboard provides (1-2 sentences)
2154
-
2155
- 2. **Generate Props for Each Component:**
2156
- For each visualization type requested, create tailored props:
2157
-
2158
- - **query**: SQL query specific to this visualization using the database schema
2159
- * Use correct table and column names
2160
- * **DO NOT USE TOP keyword - use LIMIT instead (e.g., LIMIT 20, not TOP 20)**
2161
- * ALWAYS include LIMIT clause ONCE at the end (default: {{DEFAULT_LIMIT}})
2162
- * For KPICard: Return single row with column alias "value"
2163
- * For Charts: Return appropriate columns (name/label and value, or x and y)
2164
- * For Table: Return relevant columns
2165
-
2166
- - **title**: Specific title for this component (2-4 words)
2167
-
2168
- - **description**: What this specific component shows (1 sentence)
2169
-
2170
- - **config**: Type-specific configuration
2171
- * KPICard: { gradient, formatter, icon }
2172
- * BarChart: { xKey, yKey, colors, height }
2173
- * LineChart: { xKey, yKeys, colors, height }
2174
- * PieChart: { nameKey, valueKey, colors, height }
2175
- * DataTable: { pageSize }
2176
-
2177
- 3. **CRITICAL: Component Hierarchy and Ordering:**
2178
- The ORDER of components in the array MUST follow this STRICT hierarchy for proper visual layout:
2179
-
2180
- **HIERARCHY RULES (MUST FOLLOW IN THIS ORDER):**
2181
- 1. KPICards - ALWAYS FIRST (top of dashboard for summary metrics)
2182
- 2. Charts/Graphs - AFTER KPICards (middle of dashboard for visualizations)
2183
- * BarChart, LineChart, PieChart, DonutChart
2184
- 3. DataTable - ALWAYS LAST (bottom of dashboard, full width for detailed data)
2185
-
2186
- **LAYOUT BEHAVIOR (Frontend enforces):**
2187
- - KPICards: Display in responsive grid (3 columns)
2188
- - Single Chart (if only 1 chart): Takes FULL WIDTH
2189
- - Multiple Charts (if 2+ charts): Display in 2-column grid
2190
- - DataTable (if present): Always spans FULL WIDTH at bottom
2191
-
2192
-
2193
- **ABSOLUTELY DO NOT deviate from this hierarchy. Always place:**
2194
- - KPICards first
2195
- - Charts/Graphs second
2196
- - DataTable last (if present)
2197
-
2198
- **Important Guidelines:**
2199
- - Each component should answer a DIFFERENT aspect of the user's question
2200
- - Queries should be complementary, not duplicated
2201
- - If user asks "Show total revenue and trend", generate:
2202
- * KPICard: Single total value (FIRST)
2203
- * LineChart: Revenue over time (SECOND)
2204
- - Ensure queries use valid columns from the schema
2205
- - Make titles descriptive and specific to what each component shows
2206
- - **Snowflake Syntax MUST be used:**
2207
- * Use LIMIT (not TOP)
2208
- * Use DATE_TRUNC, DATEDIFF (not DATEPART)
2209
- * Include LIMIT only ONCE per query at the end
2210
-
2211
- **Output Format:**
2212
- {
2213
- "containerTitle": "Dashboard Title",
2214
- "containerDescription": "Brief description of the dashboard insights",
2215
- "components": [
2216
- {
2217
- "componentType": "KPICard" | "BarChart" | "LineChart" | "PieChart" | "DataTable",
2218
- "query": "SQL query",
2219
- "title": "Component title",
2220
- "description": "Component description",
2221
- "config": { /* type-specific config */ }
2222
- },
2223
- ...
2224
- ],
2225
- "reasoning": "Explanation of the dashboard design and component ordering",
2226
- "canGenerate": boolean
2227
- }`,
2228
- user: `Current user question: {{USER_PROMPT}}
2229
-
2230
- Required visualization types: {{VISUALIZATION_TYPES}}
2231
-
2232
- 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.`
2233
- },
2234
- "container-metadata": {
2235
- system: `You are an expert AI assistant that generates titles and descriptions for multi-component dashboards.
2236
-
2237
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2238
-
2239
- ## Previous Conversation
2240
- {{CONVERSATION_HISTORY}}
2241
-
2242
- **Context Instructions:**
2243
- - If there is previous conversation history, use it to understand what the user is referring to
2244
- - Use context to create relevant titles and descriptions that align with the user's intent
2245
-
2246
- Your task is to generate a concise title and description for a multi-component dashboard that will contain the following visualization types:
2247
- {{VISUALIZATION_TYPES}}
2248
-
2249
- **Guidelines:**
2250
-
2251
- 1. **Title:**
2252
- - Should be clear and descriptive (3-8 words)
2253
- - Should reflect what the user is asking about
2254
- - Should NOT include "Dashboard" suffix (that will be added automatically)
2255
-
2256
- 2. **Description:**
2257
- - Should be a brief summary (1-2 sentences)
2258
- - Should explain what insights the dashboard provides
2259
-
2260
- **Output Requirements:**
2261
-
2262
- Respond with a JSON object:
2263
- {
2264
- "title": "Dashboard title without 'Dashboard' suffix",
2265
- "description": "Brief description of what this dashboard shows"
2266
- }
2267
-
2268
- **Important:**
2269
- - Keep the title concise and meaningful
2270
- - Make the description informative but brief
2271
- - Focus on what insights the user will gain
2272
- `,
2273
- user: `{{USER_PROMPT}}
2274
- `
2275
- },
2276
- "text-response": {
2277
- system: `You are an intelligent AI assistant that provides helpful, accurate, and contextual text responses to user questions.
2278
-
2279
- ## Your Task
2280
-
2281
- Analyze the user's question and provide a helpful text response. Your response should:
1948
+ 3. **NO NESTED AGGREGATE FUNCTIONS** - PostgreSQL does NOT allow aggregates inside aggregates
1949
+ \u274C WRONG: \`AVG(ROUND(AVG(column), 2))\` or \`SELECT AVG(SUM(price)) FROM ...\`
1950
+ \u2705 CORRECT: \`ROUND(AVG(column), 2)\`
2282
1951
 
2283
- 1. **Be Clear and Concise**: Provide direct answers without unnecessary verbosity
2284
- 2. **Be Contextual**: Use conversation history to understand what the user is asking about
2285
- 3. **Be Accurate**: Provide factually correct information based on the context
2286
- 4. **Be Helpful**: Offer additional relevant information or suggestions when appropriate
1952
+ 4. **GROUP BY Requirements**
1953
+ - ALL non-aggregated columns in SELECT must be in GROUP BY
1954
+ - If you SELECT a column and don't aggregate it, add it to GROUP BY
2287
1955
 
2288
- ## Handling Data Questions
1956
+ 5. **LIMIT Clause**
1957
+ - ALWAYS include LIMIT (max 32 rows)
1958
+ - For scalar subqueries in WHERE/HAVING, add LIMIT 1
2289
1959
 
2290
- When the user asks about data
1960
+ 6. **String Escaping** - PostgreSQL uses double single-quotes, NOT backslash
1961
+ \u274C WRONG: \`'Children\\'s furniture'\`
1962
+ \u2705 CORRECT: \`'Children''s furniture'\`
2291
1963
 
2292
- 1. **Generate a SQL query** using the database schema provided above
2293
- 2. **Use the execute_query tool** to run the query
2294
- 3. **If the query fails**, analyze the error and generate a corrected query
2295
- 4. **Format the results** in a clear, readable way for the user
1964
+ 7. **Always Use Table Aliases for Column References** - Prevent ambiguous column errors
1965
+ \u274C WRONG: \`SELECT product_id FROM products p JOIN product_variants pv ON p.product_id = pv.product_id\`
1966
+ \u2705 CORRECT: \`SELECT p.product_id FROM products p JOIN product_variants pv ON p.product_id = pv.product_id\`
1967
+ - Always prefix columns with table alias (e.g., \`p.product_id\`, \`c.name\`)
1968
+ - Especially critical in subqueries and joins where multiple tables share column names
2296
1969
 
2297
- **Query Guidelines:**
2298
- - Use correct table and column names from the schema
2299
- - ALWAYS include a LIMIT clause with a MAXIMUM of 32 rows
2300
- - Ensure valid SQL syntax
2301
- - For time-based queries, use appropriate date functions
2302
- - When using subqueries with scalar operators (=, <, >, etc.), add LIMIT 1 to prevent "more than one row" errors
2303
1970
 
2304
1971
  ## Response Guidelines
2305
1972
 
2306
- - If the question is about data, use the execute_query tool to fetch data and present it
1973
+ - If the question is about viewing data, use the execute_query tool to fetch data and present it
1974
+ - If the question is about creating/updating/deleting data:
1975
+ 1. Acknowledge that the system supports this via forms
1976
+ 2. **CRITICAL:** Use the database schema to determine which fields are required based on \`nullable\` property
1977
+ 3. **CRITICAL:** If the form will have select fields for foreign keys, you MUST fetch the options data using execute_query
1978
+ 4. **CRITICAL FOR UPDATE/DELETE OPERATIONS:** If it's an update/edit/modify/delete question:
1979
+ - **NEVER update ID/primary key columns** (e.g., order_id, customer_id, product_id) - these are immutable identifiers
1980
+ - You MUST first fetch the CURRENT values of the record using a SELECT query
1981
+ - Identify the record (from user's question - e.g., "update order 123" or "delete order 123" means order_id = 123)
1982
+ - Execute: \`SELECT * FROM table_name WHERE id = <value> LIMIT 1\`
1983
+ - Present the current values in your response (e.g., "Current order status: Pending, payment method: Credit Card")
1984
+ - For DELETE: These values will be shown in a disabled form as confirmation before deletion
1985
+ - For UPDATE: These values will populate as default values for editing
1986
+ 5. Present the options data in your response (e.g., "Available categories: Furniture (id: 1), Kitchen (id: 2), Decor (id: 3)")
1987
+ 6. The form component will be generated automatically using this data
2307
1988
  - If the question is general knowledge, provide a helpful conversational response
2308
1989
  - If asking for clarification, provide options or ask specific follow-up questions
2309
1990
  - If you don't have enough information, acknowledge it and ask for more details
2310
1991
  - Keep responses focused and avoid going off-topic
2311
1992
 
1993
+ **Example for data modification with foreign keys:**
1994
+ User: "I want to create a new product"
1995
+ You should:
1996
+ 1. Execute query: \`SELECT category_id, name FROM categories LIMIT 32\`
1997
+ 2. Execute query: \`SELECT store_id, name FROM stores LIMIT 32\`
1998
+ 3. Present: "I can help you create a new product. Available categories: Furniture (id: 1), Kitchen (id: 2)... Available stores: Store A (id: 10), Store B (id: 20)..."
1999
+ 4. Suggest Form component
2000
+
2312
2001
  ## Component Suggestions
2313
2002
 
2314
- After analyzing the query results, you MUST suggest appropriate dashboard components for displaying the data. Use this format:
2003
+ After analyzing the user's question, you MUST suggest appropriate dashboard components. Use this format:
2315
2004
 
2316
2005
  <DashboardComponents>
2317
2006
  **Dashboard Components:**
@@ -2319,12 +2008,22 @@ Format: \`{number}.{component_type} : {clear reasoning}\`
2319
2008
 
2320
2009
 
2321
2010
  **Rules for component suggestions:**
2322
- 1. Analyze the query results structure and data type
2323
- 2. Suggest components that would best visualize the data
2324
- 3. Each component suggestion must be on a new line
2011
+ 1. If a conclusive answer can be provided based on user question, suggest that as the first component.
2012
+ 2. ALways suggest context/supporting components that will give the user more information and allow them to explore further.
2013
+ 3. If the question includes a time range, also explore time-based components for past time ranges.
2014
+ 4. **For data viewing/analysis questions**: Suggest visualization components (KPICard, BarChart, LineChart, PieChart, DataTable, etc.).
2015
+ 5. **For data modification questions** (create/add/update/delete):
2016
+ - Always suggest 1-2 context components first to provide relevant information (prefer KPICard for showing key metrics)
2017
+ - Then suggest \`Form\` component for the actual modification
2018
+ - Example: "1.KPICard : Show current order total and status" then "2.Form : To update order details"
2019
+ 6. Analyze the query results structure and data type
2020
+ 7. Each component suggestion must be on a new line
2325
2021
  </DashboardComponents>
2326
2022
 
2327
- IMPORTANT: Always wrap component suggestions with <DashboardComponents> tags and include at least one component suggestion when data is returned.
2023
+ IMPORTANT:
2024
+ - Always wrap component suggestions with <DashboardComponents> tags
2025
+ - For data viewing: Include at least one component suggestion when data is returned
2026
+ - For data modifications: Always suggest 1-2 context components before Form (e.g., "1.KPICard : Show current order value" then "2.Form : To update order status")
2328
2027
 
2329
2028
  ## Output Format
2330
2029
 
@@ -2339,37 +2038,22 @@ Respond with plain text that includes:
2339
2038
  - Return ONLY plain text (no JSON, no markdown code blocks)
2340
2039
 
2341
2040
 
2342
- You have access to a database and can execute SQL queries to answer data-related questions.
2343
- ## Database Schema
2344
- {{SCHEMA_DOC}}
2345
-
2346
- **Database Type: PostgreSQL**
2041
+ You have access to a database and can execute SQL queries to answer data-related questions. For data modifications, the system provides form-based interfaces.
2347
2042
 
2348
- **CRITICAL PostgreSQL Query Rules:**
2349
-
2350
- 1. **NO AGGREGATE FUNCTIONS IN WHERE CLAUSE** - This is a fundamental SQL error
2351
- \u274C WRONG: \`WHERE COUNT(orders) > 0\`
2352
- \u274C WRONG: \`WHERE SUM(price) > 100\`
2353
- \u274C WRONG: \`WHERE AVG(rating) > 4.5\`
2354
2043
 
2355
- \u2705 CORRECT: Use HAVING (with GROUP BY), EXISTS, or subquery
2044
+ ## External Tool Results
2356
2045
 
2357
- 2. **WHERE vs HAVING**
2358
- - WHERE filters rows BEFORE grouping (cannot use aggregates)
2359
- - HAVING filters groups AFTER grouping (can use aggregates)
2360
- - If using HAVING, you MUST have GROUP BY
2046
+ The following external tools were executed for this request (if applicable):
2361
2047
 
2362
- 3. **NO NESTED AGGREGATE FUNCTIONS** - PostgreSQL does NOT allow aggregates inside aggregates
2363
- \u274C WRONG: \`AVG(ROUND(AVG(column), 2))\` or \`SELECT AVG(SUM(price)) FROM ...\`
2364
- \u2705 CORRECT: \`ROUND(AVG(column), 2)\`
2048
+ {{EXTERNAL_TOOL_CONTEXT}}
2365
2049
 
2366
- 4. **GROUP BY Requirements**
2367
- - ALL non-aggregated columns in SELECT must be in GROUP BY
2368
- - If you SELECT a column and don't aggregate it, add it to GROUP BY
2050
+ Use this external tool data to:
2051
+ - Provide information from external sources (emails, calendar, etc.)
2052
+ - Present the data in a user-friendly format
2053
+ - Combine external data with database queries when relevant
2054
+ - Reference specific results in your response
2369
2055
 
2370
- 5. **LIMIT Clause**
2371
- - ALWAYS include LIMIT (max 32 rows)
2372
- - For scalar subqueries in WHERE/HAVING, add LIMIT 1
2056
+ **Note:** If external tools were not needed, this section will indicate "No external tools were used for this request."
2373
2057
 
2374
2058
 
2375
2059
  ## Knowledge Base Context
@@ -2392,10 +2076,8 @@ Use this knowledge base information to:
2392
2076
  ## Previous Conversation
2393
2077
  {{CONVERSATION_HISTORY}}
2394
2078
 
2395
-
2396
2079
  `,
2397
2080
  user: `{{USER_PROMPT}}
2398
-
2399
2081
  `
2400
2082
  },
2401
2083
  "match-text-components": {
@@ -2409,11 +2091,21 @@ You will receive a text response containing:
2409
2091
  3. **Dashboard Components:** suggestions (1:component_type : reasoning format)
2410
2092
 
2411
2093
  Your job is to:
2412
- 1. **Parse the component suggestions** from the text response (format: 1:component_type : reasoning)
2413
- 2. **Match each suggestion with an actual component** from the available list
2414
- 3. **Generate proper props** for each matched component to **visualize the analysis results** that were already fetched
2415
- 4. **Generate title and description** for the dashboard container
2416
- 5. **Generate intelligent follow-up questions (actions)** that the user might naturally ask next based on the data analysis
2094
+ 1. **FIRST: Generate a direct answer component** (if the user question can be answered with a single visualization)
2095
+ - Determine the BEST visualization type (KPICard, BarChart, DataTable, PieChart, LineChart, etc.) to directly answer the user's question
2096
+ - Select the matching component from the available components list
2097
+ - Generate complete props for this component (query, title, description, config)
2098
+ - This component will be placed in the \`answerComponent\` field
2099
+ - This component will be streamed to the frontend IMMEDIATELY for instant user feedback
2100
+ - **CRITICAL**: Generate this FIRST in your JSON response
2101
+
2102
+ 2. **THEN: Parse ALL dashboard component suggestions** from the text response (format: 1:component_type : reasoning)
2103
+ 3. **Match EACH suggestion with an actual component** from the available list
2104
+ 4. **CRITICAL**: \`matchedComponents\` must include **ALL** dashboard components suggested in the text, INCLUDING the component you used as \`answerComponent\`
2105
+ - The answerComponent is shown first for quick feedback, but the full dashboard shows everything
2106
+ 5. **Generate proper props** for each matched component to **visualize the analysis results** that were already fetched
2107
+ 6. **Generate title and description** for the dashboard container
2108
+ 7. **Generate intelligent follow-up questions (actions)** that the user might naturally ask next based on the data analysis
2417
2109
 
2418
2110
  **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.
2419
2111
 
@@ -2448,7 +2140,8 @@ For each matched component, generate complete props:
2448
2140
 
2449
2141
  **Option B: GENERATE a new query** (when necessary)
2450
2142
  - Only generate new queries when you need DIFFERENT data
2451
- - Use the database schema below to write valid SQL
2143
+ - For SELECT queries: Use the database schema below to write valid SQL
2144
+ - For mutations (INSERT/UPDATE/DELETE): Only if matching a Form component, generate mutation query with $fieldName placeholders
2452
2145
 
2453
2146
 
2454
2147
  **Decision Logic:**
@@ -2466,8 +2159,12 @@ For each matched component, generate complete props:
2466
2159
  \u274C WRONG: \`WHERE COUNT(orders) > 0\`
2467
2160
  \u274C WRONG: \`WHERE SUM(price) > 100\`
2468
2161
  \u274C WRONG: \`WHERE AVG(rating) > 4.5\`
2162
+ \u274C WRONG: \`WHERE FLOOR(AVG(rating)) = 4\` (aggregate inside any function is still not allowed)
2163
+ \u274C WRONG: \`WHERE ROUND(SUM(price), 2) > 100\`
2469
2164
 
2470
2165
  \u2705 CORRECT: Use HAVING (with GROUP BY), EXISTS, or subquery
2166
+ \u2705 CORRECT: Move aggregate logic to HAVING: \`GROUP BY ... HAVING FLOOR(AVG(rating)) = 4\`
2167
+ \u2705 CORRECT: Use subquery for filtering: \`WHERE product_id IN (SELECT product_id FROM ... GROUP BY ... HAVING AVG(rating) >= 4)\`
2471
2168
 
2472
2169
  2. **NO NESTED AGGREGATE FUNCTIONS** - PostgreSQL does NOT allow aggregates inside aggregates
2473
2170
  \u274C WRONG: \`AVG(ROUND(AVG(column), 2))\`
@@ -2496,6 +2193,16 @@ For each matched component, generate complete props:
2496
2193
  - Subqueries used with =, <, >, etc. must return single value
2497
2194
  - Always add LIMIT 1 to scalar subqueries
2498
2195
 
2196
+ 8. **String Escaping** - PostgreSQL uses double single-quotes, NOT backslash
2197
+ \u274C WRONG: \`'Children\\'s furniture'\`
2198
+ \u2705 CORRECT: \`'Children''s furniture'\`
2199
+
2200
+ 9. **Always Use Table Aliases for Column References** - Prevent ambiguous column errors
2201
+ \u274C WRONG: \`SELECT product_id FROM products p JOIN product_variants pv ON p.product_id = pv.product_id\`
2202
+ \u2705 CORRECT: \`SELECT p.product_id FROM products p JOIN product_variants pv ON p.product_id = pv.product_id\`
2203
+ - Always prefix columns with table alias (e.g., \`p.product_id\`, \`c.name\`)
2204
+ - Especially critical in subqueries and joins where multiple tables share column names
2205
+
2499
2206
  **Query Generation Guidelines** (when creating new queries):
2500
2207
  - Use correct table and column names from the schema above
2501
2208
  - ALWAYS include LIMIT clause (max 32 rows)
@@ -2509,7 +2216,7 @@ For each matched component, generate complete props:
2509
2216
  - Brief explanation of what this component displays
2510
2217
  - Why it's useful for this data
2511
2218
 
2512
- ### 4. Config
2219
+ ### 4. Config (for visualization components)
2513
2220
  - **CRITICAL**: Look at the component's "Props Structure" to see what config fields it expects
2514
2221
  - Map query result columns to the appropriate config fields
2515
2222
  - Keep other existing config properties that don't need to change
@@ -2521,20 +2228,130 @@ For each matched component, generate complete props:
2521
2228
  - \`orientation\` = "vertical" or "horizontal" (controls visual direction only)
2522
2229
  - **DO NOT swap xAxisKey/yAxisKey based on orientation** - they always represent category and value respectively
2523
2230
 
2524
- ## Follow-Up Questions (Actions) Generation
2525
-
2526
- 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:
2527
-
2528
- 1. **Build upon the data analysis** shown in the text response and components
2529
- 2. **Explore natural next steps** in the data exploration journey
2530
- 3. **Be progressively more detailed or specific** - go deeper into the analysis
2531
- 4. **Consider the insights revealed** - suggest questions that help users understand implications
2532
- 5. **Be phrased naturally** as if a real user would ask them
2533
- 6. **Vary in scope** - include both broad trends and specific details
2534
- 7. **Avoid redundancy** - don't ask questions already answered in the text response
2231
+ ### 5. Additional Props (match according to component type)
2232
+ - **CRITICAL**: Look at the matched component's "Props Structure" in the available components list
2233
+ - Generate props that match EXACTLY what the component expects
2535
2234
 
2235
+ **For Form components (type: "Form"):**
2536
2236
 
2537
- ## Output Format
2237
+ Props structure:
2238
+ - **query**: \`{ sql: "INSERT/UPDATE/DELETE query with $fieldName placeholders", params: [] }\`
2239
+ - **For UPDATE queries**: Check the database schema - if the table has an \`updated_at\` or \`last_updated\` column, always include it in the SET clause with \`CURRENT_TIMESTAMP\` (e.g., \`UPDATE table_name SET field = $field, updated_at = CURRENT_TIMESTAMP WHERE id = value\`)
2240
+ - **title**: "Update Order 5000", "Create New Product", or "Delete Order 5000"
2241
+ - **description**: What the form does
2242
+ - **submitButtonText**: Button text (default: "Submit"). For delete: "Delete", "Confirm Delete"
2243
+ - **submitButtonColor**: "primary" (blue) or "danger" (red). Use "danger" for DELETE operations
2244
+ - **successMessage**: Success message (default: "Form submitted successfully!"). For delete: "Record deleted successfully!"
2245
+ - **disableFields**: Set \`true\` for DELETE operations to show current values but prevent editing
2246
+ - **fields**: Array of field objects (structure below)
2247
+
2248
+ **Field object:**
2249
+ \`\`\`json
2250
+ {
2251
+ "name": "field_name", // Matches $field_name in SQL query
2252
+ "description": "Field Label",
2253
+ "type": "text|number|email|date|select|multiselect|checkbox|textarea",
2254
+ "required": true, // Set based on schema: nullable=false \u2192 required=true, nullable=true \u2192 required=false
2255
+ "defaultValue": "current_value", // For UPDATE: extract from text response
2256
+ "placeholder": "hint text",
2257
+ "options": [...], // For select/multiselect
2258
+ "validation": {
2259
+ "minLength": { "value": 5, "message": "..." },
2260
+ "maxLength": { "value": 100, "message": "..." },
2261
+ "min": { "value": 18, "message": "..." },
2262
+ "max": { "value": 120, "message": "..." },
2263
+ "pattern": { "value": "regex", "message": "..." }
2264
+ }
2265
+ }
2266
+ \`\`\`
2267
+
2268
+ **CRITICAL - Set required based on database schema:**
2269
+ - Check the column's \`nullable\` property in the database schema
2270
+ - If \`nullable: false\` \u2192 set \`required: true\` (field is mandatory)
2271
+ - If \`nullable: true\` \u2192 set \`required: false\` (field is optional)
2272
+ - Never set fields as required if the schema allows NULL
2273
+
2274
+ **Default Values for UPDATE:**
2275
+ - **NEVER include ID/primary key fields in UPDATE forms** (e.g., order_id, customer_id, product_id) - these cannot be changed
2276
+ - Detect UPDATE by checking if SQL contains "UPDATE" keyword
2277
+ - Extract current values from text response (look for "Current values:" or SELECT results)
2278
+ - Set \`defaultValue\` for each field with the extracted current value
2279
+
2280
+ **CRITICAL - Single field with current value pre-selected:**
2281
+ For UPDATE operations, use ONE field with defaultValue set to current value (not two separate fields).
2282
+
2283
+ \u2705 CORRECT - Single field, current value pre-selected:
2284
+ \`\`\`json
2285
+ {
2286
+ "name": "category_id",
2287
+ "type": "select",
2288
+ "defaultValue": 5,
2289
+ "options": [{"id": 1, "name": "Kitchen"}, {"id": 5, "name": "Furniture"}, {"id": 7, "name": "Decor"}]
2290
+ }
2291
+ \`\`\`
2292
+ User sees dropdown with "Furniture" selected, can change to any other category.
2293
+
2294
+ \u274C WRONG - Two separate fields:
2295
+ \`\`\`json
2296
+ [
2297
+ {"name": "current_category", "type": "text", "defaultValue": "Furniture", "disabled": true},
2298
+ {"name": "new_category", "type": "select", "options": [...]}
2299
+ ]
2300
+ \`\`\`
2301
+
2302
+ **Options Format:**
2303
+ - **Enum/status fields** (non-foreign keys): String array \`["Pending", "Shipped", "Delivered"]\`
2304
+ - **Foreign keys** (reference tables): Object array \`[{"id": 1, "name": "Furniture"}, {"id": 2, "name": "Kitchen"}]\`
2305
+ - Extract from text response queries and match format to field type
2306
+
2307
+ **Example UPDATE form field:**
2308
+ \`\`\`json
2309
+ {
2310
+ "name": "status",
2311
+ "description": "Order Status",
2312
+ "type": "select",
2313
+ "required": true,
2314
+ "defaultValue": "Pending", // Current value from database
2315
+ "options": ["Pending", "Processing", "Shipped", "Delivered"]
2316
+ }
2317
+ \`\`\`
2318
+
2319
+ **Example DELETE form props:**
2320
+ \`\`\`json
2321
+ {
2322
+ "query": { "sql": "DELETE FROM orders WHERE order_id = 123", "params": [] },
2323
+ "title": "Delete Order 123",
2324
+ "description": "Are you sure you want to delete this order?",
2325
+ "submitButtonText": "Confirm Delete",
2326
+ "submitButtonColor": "danger",
2327
+ "successMessage": "Order deleted successfully!",
2328
+ "disableFields": true,
2329
+ "fields": [
2330
+ { "name": "order_id", "description": "Order ID", "type": "text", "defaultValue": "123" },
2331
+ { "name": "status", "description": "Status", "type": "text", "defaultValue": "Pending" }
2332
+ ]
2333
+ }
2334
+ \`\`\`
2335
+
2336
+ **For visualization components (Charts, Tables, KPIs):**
2337
+ - **query**: String (SQL SELECT query)
2338
+ - **title**, **description**, **config**: As per component's props structure
2339
+ - Do NOT include fields array
2340
+
2341
+ ## Follow-Up Questions (Actions) Generation
2342
+
2343
+ 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:
2344
+
2345
+ 1. **Build upon the data analysis** shown in the text response and components
2346
+ 2. **Explore natural next steps** in the data exploration journey
2347
+ 3. **Be progressively more detailed or specific** - go deeper into the analysis
2348
+ 4. **Consider the insights revealed** - suggest questions that help users understand implications
2349
+ 5. **Be phrased naturally** as if a real user would ask them
2350
+ 6. **Vary in scope** - include both broad trends and specific details
2351
+ 7. **Avoid redundancy** - don't ask questions already answered in the text response
2352
+
2353
+
2354
+ ## Output Format
2538
2355
 
2539
2356
  You MUST respond with ONLY a valid JSON object (no markdown, no code blocks):
2540
2357
 
@@ -2545,8 +2362,25 @@ You MUST respond with ONLY a valid JSON object (no markdown, no code blocks):
2545
2362
  - Do NOT use markdown code blocks (no \`\`\`)
2546
2363
  - Return ONLY the JSON object, nothing else
2547
2364
 
2365
+ **Example 1: With answer component** (when user question can be answered with single visualization)
2548
2366
  \`\`\`json
2549
2367
  {
2368
+ "hasAnswerComponent": true,
2369
+ "answerComponent": {
2370
+ "componentId": "id_from_available_list",
2371
+ "componentName": "name_of_component",
2372
+ "componentType": "type_of_component (can be KPICard, BarChart, LineChart, PieChart, DataTable, etc.)",
2373
+ "reasoning": "Why this visualization type best answers the user's question",
2374
+ "props": {
2375
+ "query": "SQL query for this component",
2376
+ "title": "Component title that directly answers the user's question",
2377
+ "description": "Component description",
2378
+ "config": {
2379
+ "field1": "value1",
2380
+ "field2": "value2"
2381
+ }
2382
+ }
2383
+ },
2550
2384
  "layoutTitle": "Clear, concise title for the overall dashboard/layout (5-10 words)",
2551
2385
  "layoutDescription": "Brief description of what the dashboard shows and its purpose (1-2 sentences)",
2552
2386
  "matchedComponents": [
@@ -2554,7 +2388,7 @@ You MUST respond with ONLY a valid JSON object (no markdown, no code blocks):
2554
2388
  "componentId": "id_from_available_list",
2555
2389
  "componentName": "name_of_component",
2556
2390
  "componentType": "type_of_component",
2557
- "reasoning": "Why this component was selected for this suggestion",
2391
+ "reasoning": "Why this component was selected for the dashboard",
2558
2392
  "originalSuggestion": "c1:table : original reasoning from text",
2559
2393
  "props": {
2560
2394
  "query": "SQL query for this component",
@@ -2577,21 +2411,65 @@ You MUST respond with ONLY a valid JSON object (no markdown, no code blocks):
2577
2411
  }
2578
2412
  \`\`\`
2579
2413
 
2414
+ **Example 2: Without answer component** (when user question needs multiple visualizations or dashboard)
2415
+ \`\`\`json
2416
+ {
2417
+ "hasAnswerComponent": false,
2418
+ "answerComponent": null,
2419
+ "layoutTitle": "Clear, concise title for the overall dashboard/layout (5-10 words)",
2420
+ "layoutDescription": "Brief description of what the dashboard shows and its purpose (1-2 sentences)",
2421
+ "matchedComponents": [
2422
+ {
2423
+ "componentId": "id_from_available_list",
2424
+ "componentName": "name_of_component",
2425
+ "componentType": "type_of_component",
2426
+ "reasoning": "Why this component was selected for the dashboard",
2427
+ "originalSuggestion": "c1:chart : original reasoning from text",
2428
+ "props": {
2429
+ "query": "SQL query for this component",
2430
+ "title": "Component title",
2431
+ "description": "Component description",
2432
+ "config": {
2433
+ "field1": "value1",
2434
+ "field2": "value2"
2435
+ }
2436
+ }
2437
+ }
2438
+ ],
2439
+ "actions": [
2440
+ "Follow-up question 1?",
2441
+ "Follow-up question 2?",
2442
+ "Follow-up question 3?",
2443
+ "Follow-up question 4?",
2444
+ "Follow-up question 5?"
2445
+ ]
2446
+ }
2447
+ \`\`\`
2448
+
2580
2449
  **CRITICAL:**
2581
- - \`matchedComponents\` MUST include ALL components suggested in the text response
2450
+ - **\`hasAnswerComponent\` determines if an answer component exists**
2451
+ - Set to \`true\` if the user question can be answered with a single visualization
2452
+ - Set to \`false\` if the user question can not be answered with single visualisation and needs multiple visualizations or a dashboard overview
2453
+ - **If \`hasAnswerComponent\` is \`true\`:**
2454
+ - \`answerComponent\` MUST be generated FIRST in the JSON before \`layoutTitle\`
2455
+ - Generate complete props (query, title, description, config)
2456
+ - **If \`hasAnswerComponent\` is \`false\`:**
2457
+ - Set \`answerComponent\` to \`null\`
2458
+ - **\`matchedComponents\` MUST include ALL dashboard components from the text analysis**
2459
+ - **CRITICAL**: Even if you used a component as \`answerComponent\`, you MUST STILL include it in \`matchedComponents\`
2460
+ - The count of matchedComponents should EQUAL the count of dashboard suggestions in the text (e.g., if text has 4 suggestions, matchedComponents should have 4 items)
2461
+ - Do NOT skip the answerComponent from matchedComponents
2462
+ - \`matchedComponents\` come from the dashboard component suggestions in the text response
2582
2463
  - \`layoutTitle\` MUST be a clear, concise title (5-10 words) that summarizes what the entire dashboard shows
2583
- - Examples: "Sales Performance Overview", "Customer Metrics Analysis", "Product Category Breakdown"
2584
2464
  - \`layoutDescription\` MUST be a brief description (1-2 sentences) explaining the purpose and scope of the dashboard
2585
2465
  - Should describe what insights the dashboard provides and what data it shows
2586
2466
  - \`actions\` MUST be an array of 4-5 intelligent follow-up questions based on the analysis
2587
2467
  - Return ONLY valid JSON (no markdown code blocks, no text before/after)
2588
- - Generate complete props for each component including query, title, description, and config
2589
-
2590
-
2468
+ - Generate complete props for each component
2591
2469
  `,
2592
- user: `## Text Response
2470
+ user: `## Analysis Content
2593
2471
 
2594
- {{TEXT_RESPONSE}}
2472
+ {{ANALYSIS_CONTENT}}
2595
2473
 
2596
2474
  ---
2597
2475
 
@@ -2638,70 +2516,269 @@ Format your response as a JSON object with this structure:
2638
2516
 
2639
2517
  Return ONLY valid JSON.`
2640
2518
  },
2641
- "execute-tools": {
2642
- system: `You are an expert AI assistant that executes external tools to fetch data from external services.
2519
+ "category-classification": {
2520
+ system: `You are an expert AI that categorizes user questions into specific action categories and identifies required tools/resources.
2643
2521
 
2644
- You have access to external tools that can retrieve information like emails, calendar events, and other external data. When the user requests this information, you should call the appropriate tools.
2522
+ CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2645
2523
 
2646
2524
  ## Available External Tools
2525
+
2647
2526
  {{AVAILABLE_TOOLS}}
2648
2527
 
2649
- ## Your Task
2528
+ ---
2650
2529
 
2651
- Analyze the user's request and:
2652
-
2653
- 1. **Determine if external tools are needed**
2654
- - Examples that NEED external tools:
2655
- - "Show me my emails" \u2192 needs email tool
2656
- - "Get my last 5 Gmail messages" \u2192 needs Gmail tool
2657
- - "Check my Outlook inbox" \u2192 needs Outlook tool
2658
-
2659
- - Examples that DON'T need external tools:
2660
- - "What is the total sales?" \u2192 database query (handled elsewhere)
2661
- - "Show me revenue trends" \u2192 internal data analysis
2662
- - "Hello" \u2192 general conversation
2663
-
2664
- 2. **Call the appropriate tools**
2665
- - Use the tool calling mechanism to execute external tools
2666
- - Extract parameters from the user's request
2667
- - Use sensible defaults when parameters aren't specified:
2668
- - For email limit: default to 10
2669
- - For email address: use "me" for the authenticated user if not specified
2670
-
2671
- 3. **Handle errors and retry**
2672
- - If a tool call fails, analyze the error message
2673
- - Retry with corrected parameters if possible
2674
- - You have up to 3 attempts per tool
2675
-
2676
- ## Important Guidelines
2677
-
2678
- - **Only call external tools when necessary** - Don't call tools for database queries or general conversation
2679
- - **Choose the right tool** - For email requests, select Gmail vs Outlook based on:
2680
- - Explicit mention (e.g., "Gmail", "Outlook")
2681
- - Email domain (e.g., @gmail.com \u2192 Gmail, @company.com \u2192 Outlook)
2682
- - **Extract parameters carefully** - Use the user's exact values when provided
2683
- - **If no tools are needed** - Simply respond that no external tools are required for this request
2684
-
2685
- ## Examples
2686
-
2687
- **Example 1 - Gmail Request:**
2688
- User: "Show me my last 5 Gmail messages"
2689
- Action: Call get-gmail-mails tool with parameters: { email: "me", limit: 5 }
2690
-
2691
- **Example 2 - Outlook Request:**
2692
- User: "Get emails from john.doe@company.com"
2693
- Action: Call get-outlook-mails tool with parameters: { email: "john.doe@company.com", limit: 10 }
2694
-
2695
- **Example 3 - No Tools Needed:**
2696
- User: "What is the total sales?"
2697
- Response: This is a database query, not an external tool request. No external tools are needed.
2698
-
2699
- **Example 4 - Error Retry:**
2700
- Tool call fails with: "Invalid email parameter"
2701
- Action: Analyze error, correct the parameter, and retry the tool call
2702
- `,
2703
- user: `{{USER_PROMPT}}
2704
- `
2530
+ Your task is to analyze the user's question and determine:
2531
+
2532
+ 1. **Question Category:**
2533
+ - "data_analysis": Questions about analyzing, querying, reading, or visualizing data from the database (SELECT operations)
2534
+ - "data_modification": Questions about creating, updating, deleting, or modifying data in the database (INSERT, UPDATE, DELETE operations)
2535
+
2536
+ 2. **External Tools Required** (for both categories):
2537
+ From the available tools listed above, identify which ones are needed to support the user's request:
2538
+ - Match the tool names/descriptions to what the user is asking for
2539
+ - Extract specific parameters mentioned in the user's question
2540
+
2541
+ 3. **Tool Parameters** (if tools are identified):
2542
+ Extract specific parameters the user mentioned:
2543
+ - For each identified tool, extract relevant parameters (email, recipient, content, etc.)
2544
+ - Only include parameters the user explicitly or implicitly mentioned
2545
+
2546
+ **Important Guidelines:**
2547
+ - If user mentions any of the available external tools \u2192 identify those tools and extract their parameters
2548
+ - If user asks to "send", "schedule", "create event", "message" \u2192 check if available tools match
2549
+ - If user asks to "show", "analyze", "compare", "calculate" data \u2192 "data_analysis"
2550
+ - If user asks to modify/create/update/delete data \u2192 "data_modification"
2551
+ - Always identify tools from the available tools list (not from generic descriptions)
2552
+ - Be precise in identifying tool types and required parameters
2553
+ - Only include tools that are explicitly mentioned or clearly needed
2554
+
2555
+ **Output Format:**
2556
+ \`\`\`json
2557
+ {
2558
+ "category": "data_analysis" | "data_modification",
2559
+ "reasoning": "Brief explanation of why this category was chosen",
2560
+ "externalTools": [
2561
+ {
2562
+ "type": "tool_id_from_available_tools",
2563
+ "name": "Tool Display Name",
2564
+ "description": "What this tool will do",
2565
+ "parameters": {
2566
+ "param1": "extracted value",
2567
+ "param2": "extracted value"
2568
+ }
2569
+ }
2570
+ ],
2571
+ "dataAnalysisType": "visualization" | "calculation" | "comparison" | "trend" | null,
2572
+ "confidence": 0-100
2573
+ }
2574
+ \`\`\`
2575
+
2576
+
2577
+ ## Previous Conversation
2578
+ {{CONVERSATION_HISTORY}}`,
2579
+ user: `{{USER_PROMPT}}`
2580
+ },
2581
+ "adapt-ui-block-params": {
2582
+ system: `You are an expert AI that adapts and modifies UI block component parameters based on the user's current question.
2583
+
2584
+ CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2585
+
2586
+ ## Database Schema Reference
2587
+
2588
+ {{SCHEMA_DOC}}
2589
+
2590
+ Use this schema to understand available tables, columns, and relationships when modifying SQL queries. Ensure all table and column names you use in adapted queries are valid according to this schema.
2591
+
2592
+ ## Context
2593
+ You are given:
2594
+ 1. A previous UI Block response (with component and its props) that matched the user's current question with >90% semantic similarity
2595
+ 2. The user's current question
2596
+ 3. The component that needs parameter adaptation
2597
+
2598
+ Your task is to:
2599
+ 1. **Analyze the difference** between the original question (from the matched UIBlock) and the current user question
2600
+ 2. **Identify what parameters need to change** in the component props to answer the current question
2601
+ 3. **Modify the props** to match the current request while keeping the same component type(s)
2602
+ 4. **Preserve component structure** - only change props, not the components themselves
2603
+
2604
+ ## Component Structure Handling
2605
+
2606
+ ### For Single Components:
2607
+ - Modify props directly (config, actions, query, filters, etc.)
2608
+
2609
+ ### For MultiComponentContainer:
2610
+ The component will have structure:
2611
+ \`\`\`json
2612
+ {
2613
+ "type": "Container",
2614
+ "name": "MultiComponentContainer",
2615
+ "props": {
2616
+ "config": {
2617
+ "components": [...], // Array of nested components - ADAPT EACH ONE
2618
+ "title": "...", // Container title - UPDATE based on new question
2619
+ "description": "..." // Container description - UPDATE based on new question
2620
+ },
2621
+ "actions": [...] // ADAPT actions if needed
2622
+ }
2623
+ }
2624
+ \`\`\`
2625
+
2626
+ When adapting MultiComponentContainer:
2627
+ - Update the container-level \`title\` and \`description\` to reflect the new user question
2628
+ - For each component in \`config.components\`:
2629
+ - Identify what data it shows and how the new question changes what's needed
2630
+ - Adapt its query parameters (WHERE clauses, LIMIT, ORDER BY, filters, date ranges)
2631
+ - Update its title/description to match the new context
2632
+ - Update its config settings (colors, sorting, grouping, metrics)
2633
+ - Update \`actions\` if the new question requires different actions
2634
+
2635
+ ## Important Guidelines:
2636
+ - Keep the same component type (don't change KPICard to LineChart)
2637
+ - Keep the same number of components in the container
2638
+ - For each nested component, update:
2639
+ - Query WHERE clauses, LIMIT, ORDER BY, filters, date ranges, metrics
2640
+ - Title and description to reflect the new question
2641
+ - Config settings like colors, sorting, grouping if needed
2642
+ - Maintain each component's core purpose while answering the new question
2643
+ - If query modification is needed, ensure all table/column names remain valid
2644
+ - CRITICAL: Ensure JSON is valid and complete for all nested structures
2645
+
2646
+
2647
+ ## Output Format:
2648
+
2649
+ ### For Single Component:
2650
+ \`\`\`json
2651
+ {
2652
+ "success": true,
2653
+ "adaptedComponent": {
2654
+ "id": "original_component_id",
2655
+ "name": "component_name",
2656
+ "type": "component_type",
2657
+ "description": "updated_description",
2658
+ "props": {
2659
+ "config": { },
2660
+ "actions": [],
2661
+ }
2662
+ },
2663
+ "parametersChanged": [
2664
+ {
2665
+ "field": "query",
2666
+ "reason": "Added Q4 date filter"
2667
+ },
2668
+ {
2669
+ "field": "title",
2670
+ "reason": "Updated to reflect Q4 focus"
2671
+ }
2672
+ ],
2673
+ "explanation": "How the component was adapted to answer the new question"
2674
+ }
2675
+ \`\`\`
2676
+
2677
+ ### For MultiComponentContainer:
2678
+ \`\`\`json
2679
+ {
2680
+ "success": true,
2681
+ "adaptedComponent": {
2682
+ "id": "original_container_id",
2683
+ "name": "MultiComponentContainer",
2684
+ "type": "Container",
2685
+ "description": "updated_container_description",
2686
+ "props": {
2687
+ "config": {
2688
+ "title": "Updated dashboard title based on new question",
2689
+ "description": "Updated description reflecting new question context",
2690
+ "components": [
2691
+ {
2692
+ "id": "component_1_id",
2693
+ "name": "component_1_name",
2694
+ "type": "component_1_type",
2695
+ "description": "updated description for this specific component",
2696
+ "props": {
2697
+ "query": "Modified SQL query with updated WHERE/LIMIT/ORDER BY",
2698
+ "config": { "metric": "updated_metric", "filters": {...} }
2699
+ }
2700
+ },
2701
+ {
2702
+ "id": "component_2_id",
2703
+ "name": "component_2_name",
2704
+ "type": "component_2_type",
2705
+ "description": "updated description for this component",
2706
+ "props": {
2707
+ "query": "Modified SQL query for this component",
2708
+ "config": { "metric": "updated_metric", "filters": {...} }
2709
+ }
2710
+ }
2711
+ ]
2712
+ },
2713
+ "actions": []
2714
+ }
2715
+ },
2716
+ "parametersChanged": [
2717
+ {
2718
+ "field": "container.title",
2719
+ "reason": "Updated to reflect new dashboard focus"
2720
+ },
2721
+ {
2722
+ "field": "components[0].query",
2723
+ "reason": "Modified WHERE clause for new metrics"
2724
+ },
2725
+ {
2726
+ "field": "components[1].config.metric",
2727
+ "reason": "Changed metric from X to Y based on new question"
2728
+ }
2729
+ ],
2730
+ "explanation": "Detailed explanation of how each component was adapted"
2731
+ }
2732
+ \`\`\`
2733
+
2734
+ If adaptation is not possible or would fundamentally change the component:
2735
+ \`\`\`json
2736
+ {
2737
+ "success": false,
2738
+ "reason": "Cannot adapt component - the new question requires a different visualization type",
2739
+ "explanation": "The original component shows KPI cards but the new question needs a trend chart"
2740
+ }
2741
+ \`\`\``,
2742
+ user: `## Previous Matched UIBlock
2743
+
2744
+ **Original Question:** {{ORIGINAL_USER_PROMPT}}
2745
+
2746
+ **Matched UIBlock Component:**
2747
+ \`\`\`json
2748
+ {{MATCHED_UI_BLOCK_COMPONENT}}
2749
+ \`\`\`
2750
+
2751
+ **Component Properties:**
2752
+ \`\`\`json
2753
+ {{COMPONENT_PROPS}}
2754
+ \`\`\`
2755
+
2756
+ ## Current User Question
2757
+ {{CURRENT_USER_PROMPT}}
2758
+
2759
+ ---
2760
+
2761
+ ## Adaptation Instructions
2762
+
2763
+ 1. **Analyze the difference** between the original question and the current question
2764
+ 2. **Identify what data needs to change**:
2765
+ - For single components: adapt the query/config/actions
2766
+ - For MultiComponentContainer: adapt the container title/description AND each nested component's parameters
2767
+
2768
+ 3. **Modify the parameters**:
2769
+ - **Container level** (if MultiComponentContainer):
2770
+ - Update \`title\` and \`description\` to reflect the new user question
2771
+ - Update \`actions\` if needed
2772
+
2773
+ - **For each component** (single or nested in container):
2774
+ - Identify what it shows (sales, revenue, inventory, etc.)
2775
+ - Adapt SQL queries: modify WHERE clauses, LIMIT, ORDER BY, filters, date ranges
2776
+ - Update component title and description
2777
+ - Update config settings (metrics, colors, sorting, grouping)
2778
+
2779
+ 4. **Preserve structure**: Keep the same number and type of components
2780
+
2781
+ 5. **Return complete JSON** with all adapted properties for all components`
2705
2782
  }
2706
2783
  };
2707
2784
 
@@ -2779,9 +2856,10 @@ var PromptLoader = class {
2779
2856
  }
2780
2857
  /**
2781
2858
  * Load both system and user prompts from cache and replace variables
2859
+ * Supports prompt caching by splitting static and dynamic content
2782
2860
  * @param promptName - Name of the prompt
2783
2861
  * @param variables - Variables to replace in the templates
2784
- * @returns Object containing both system and user prompts
2862
+ * @returns Object containing both system and user prompts (system can be string or array for caching)
2785
2863
  */
2786
2864
  async loadPrompts(promptName, variables) {
2787
2865
  if (!this.isInitialized) {
@@ -2792,6 +2870,26 @@ var PromptLoader = class {
2792
2870
  if (!template) {
2793
2871
  throw new Error(`Prompt template '${promptName}' not found in cache. Available prompts: ${Array.from(this.promptCache.keys()).join(", ")}`);
2794
2872
  }
2873
+ const contextMarker = "---\n\n## CONTEXT";
2874
+ if (template.system.includes(contextMarker)) {
2875
+ const [staticPart, contextPart] = template.system.split(contextMarker);
2876
+ logger.debug(`\u2713 Prompt caching enabled for '${promptName}' (static: ${staticPart.length} chars, context: ${contextPart.length} chars)`);
2877
+ const processedContext = this.replaceVariables(contextMarker + contextPart, variables);
2878
+ return {
2879
+ system: [
2880
+ {
2881
+ type: "text",
2882
+ text: staticPart.trim(),
2883
+ cache_control: { type: "ephemeral" }
2884
+ },
2885
+ {
2886
+ type: "text",
2887
+ text: processedContext.trim()
2888
+ }
2889
+ ],
2890
+ user: this.replaceVariables(template.user, variables)
2891
+ };
2892
+ }
2795
2893
  return {
2796
2894
  system: this.replaceVariables(template.system, variables),
2797
2895
  user: this.replaceVariables(template.user, variables)
@@ -2878,6 +2976,75 @@ var LLM = class {
2878
2976
  // ============================================================
2879
2977
  // PRIVATE HELPER METHODS
2880
2978
  // ============================================================
2979
+ /**
2980
+ * Normalize system prompt to Anthropic format
2981
+ * Converts string to array format if needed
2982
+ * @param sys - System prompt (string or array of blocks)
2983
+ * @returns Normalized system prompt for Anthropic API
2984
+ */
2985
+ static _normalizeSystemPrompt(sys) {
2986
+ if (typeof sys === "string") {
2987
+ return sys;
2988
+ }
2989
+ return sys;
2990
+ }
2991
+ /**
2992
+ * Log cache usage metrics from Anthropic API response
2993
+ * Shows cache hits, costs, and savings
2994
+ */
2995
+ static _logCacheUsage(usage) {
2996
+ if (!usage) return;
2997
+ const inputTokens = usage.input_tokens || 0;
2998
+ const cacheCreationTokens = usage.cache_creation_input_tokens || 0;
2999
+ const cacheReadTokens = usage.cache_read_input_tokens || 0;
3000
+ const outputTokens = usage.output_tokens || 0;
3001
+ const INPUT_PRICE = 0.8;
3002
+ const OUTPUT_PRICE = 4;
3003
+ const CACHE_WRITE_PRICE = 1;
3004
+ const CACHE_READ_PRICE = 0.08;
3005
+ const regularInputCost = inputTokens / 1e6 * INPUT_PRICE;
3006
+ const cacheWriteCost = cacheCreationTokens / 1e6 * CACHE_WRITE_PRICE;
3007
+ const cacheReadCost = cacheReadTokens / 1e6 * CACHE_READ_PRICE;
3008
+ const outputCost = outputTokens / 1e6 * OUTPUT_PRICE;
3009
+ const totalCost = regularInputCost + cacheWriteCost + cacheReadCost + outputCost;
3010
+ const totalInputTokens = inputTokens + cacheCreationTokens + cacheReadTokens;
3011
+ const costWithoutCache = totalInputTokens / 1e6 * INPUT_PRICE + outputCost;
3012
+ const savings = costWithoutCache - totalCost;
3013
+ const savingsPercent = costWithoutCache > 0 ? savings / costWithoutCache * 100 : 0;
3014
+ console.log("\n\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
3015
+ console.log("\u{1F4B0} PROMPT CACHING METRICS");
3016
+ console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
3017
+ console.log("\n\u{1F4CA} Token Usage:");
3018
+ console.log(` Input (regular): ${inputTokens.toLocaleString()} tokens`);
3019
+ if (cacheCreationTokens > 0) {
3020
+ console.log(` Cache write: ${cacheCreationTokens.toLocaleString()} tokens (first request)`);
3021
+ }
3022
+ if (cacheReadTokens > 0) {
3023
+ console.log(` Cache read: ${cacheReadTokens.toLocaleString()} tokens \u26A1 HIT!`);
3024
+ }
3025
+ console.log(` Output: ${outputTokens.toLocaleString()} tokens`);
3026
+ console.log(` Total input: ${totalInputTokens.toLocaleString()} tokens`);
3027
+ console.log("\n\u{1F4B5} Cost Breakdown:");
3028
+ console.log(` Input (regular): $${regularInputCost.toFixed(6)}`);
3029
+ if (cacheCreationTokens > 0) {
3030
+ console.log(` Cache write: $${cacheWriteCost.toFixed(6)}`);
3031
+ }
3032
+ if (cacheReadTokens > 0) {
3033
+ console.log(` Cache read: $${cacheReadCost.toFixed(6)} (90% off!)`);
3034
+ }
3035
+ console.log(` Output: $${outputCost.toFixed(6)}`);
3036
+ console.log(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
3037
+ console.log(` Total cost: $${totalCost.toFixed(6)}`);
3038
+ if (cacheReadTokens > 0) {
3039
+ console.log(`
3040
+ \u{1F48E} Savings: $${savings.toFixed(6)} (${savingsPercent.toFixed(1)}% off)`);
3041
+ console.log(` Without cache: $${costWithoutCache.toFixed(6)}`);
3042
+ } else if (cacheCreationTokens > 0) {
3043
+ console.log(`
3044
+ \u23F1\uFE0F Cache created - next request will be ~90% cheaper!`);
3045
+ }
3046
+ console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n");
3047
+ }
2881
3048
  /**
2882
3049
  * Parse model string to extract provider and model name
2883
3050
  * @param modelString - Format: "provider/model-name" or just "model-name"
@@ -2912,7 +3079,7 @@ var LLM = class {
2912
3079
  model: modelName,
2913
3080
  max_tokens: options.maxTokens || 1e3,
2914
3081
  temperature: options.temperature,
2915
- system: messages.sys,
3082
+ system: this._normalizeSystemPrompt(messages.sys),
2916
3083
  messages: [{
2917
3084
  role: "user",
2918
3085
  content: messages.user
@@ -2930,7 +3097,7 @@ var LLM = class {
2930
3097
  model: modelName,
2931
3098
  max_tokens: options.maxTokens || 1e3,
2932
3099
  temperature: options.temperature,
2933
- system: messages.sys,
3100
+ system: this._normalizeSystemPrompt(messages.sys),
2934
3101
  messages: [{
2935
3102
  role: "user",
2936
3103
  content: messages.user
@@ -2938,6 +3105,7 @@ var LLM = class {
2938
3105
  stream: true
2939
3106
  });
2940
3107
  let fullText = "";
3108
+ let usage = null;
2941
3109
  for await (const chunk of stream) {
2942
3110
  if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
2943
3111
  const text = chunk.delta.text;
@@ -2945,8 +3113,12 @@ var LLM = class {
2945
3113
  if (options.partial) {
2946
3114
  options.partial(text);
2947
3115
  }
3116
+ } else if (chunk.type === "message_delta" && chunk.usage) {
3117
+ usage = chunk.usage;
2948
3118
  }
2949
3119
  }
3120
+ if (usage) {
3121
+ }
2950
3122
  if (json) {
2951
3123
  return this._parseJSON(fullText);
2952
3124
  }
@@ -2969,7 +3141,7 @@ var LLM = class {
2969
3141
  model: modelName,
2970
3142
  max_tokens: options.maxTokens || 4e3,
2971
3143
  temperature: options.temperature,
2972
- system: messages.sys,
3144
+ system: this._normalizeSystemPrompt(messages.sys),
2973
3145
  messages: conversationMessages,
2974
3146
  tools,
2975
3147
  stream: true
@@ -2979,6 +3151,7 @@ var LLM = class {
2979
3151
  const contentBlocks = [];
2980
3152
  let currentTextBlock = "";
2981
3153
  let currentToolUse = null;
3154
+ let usage = null;
2982
3155
  for await (const chunk of stream) {
2983
3156
  if (chunk.type === "message_start") {
2984
3157
  contentBlocks.length = 0;
@@ -3029,11 +3202,16 @@ var LLM = class {
3029
3202
  }
3030
3203
  if (chunk.type === "message_delta") {
3031
3204
  stopReason = chunk.delta.stop_reason || stopReason;
3205
+ if (chunk.usage) {
3206
+ usage = chunk.usage;
3207
+ }
3032
3208
  }
3033
3209
  if (chunk.type === "message_stop") {
3034
3210
  break;
3035
3211
  }
3036
3212
  }
3213
+ if (usage) {
3214
+ }
3037
3215
  if (stopReason === "end_turn") {
3038
3216
  break;
3039
3217
  }
@@ -3205,6 +3383,57 @@ var KB = {
3205
3383
  };
3206
3384
  var knowledge_base_default = KB;
3207
3385
 
3386
+ // src/userResponse/conversation-search.ts
3387
+ var searchConversations = async ({
3388
+ userPrompt,
3389
+ collections,
3390
+ userId,
3391
+ similarityThreshold = 0.6
3392
+ }) => {
3393
+ try {
3394
+ if (!collections || !collections["conversation-history"] || !collections["conversation-history"]["search"]) {
3395
+ logger.info("[ConversationSearch] conversation-history.search collection not registered, skipping");
3396
+ return null;
3397
+ }
3398
+ logger.info(`[ConversationSearch] Searching conversations for: "${userPrompt.substring(0, 50)}..."`);
3399
+ logger.info(`[ConversationSearch] Using similarity threshold: ${(similarityThreshold * 100).toFixed(0)}%`);
3400
+ const result = await collections["conversation-history"]["search"]({
3401
+ userPrompt,
3402
+ userId,
3403
+ threshold: similarityThreshold
3404
+ });
3405
+ if (!result) {
3406
+ logger.info("[ConversationSearch] No matching conversations found");
3407
+ return null;
3408
+ }
3409
+ if (!result.uiBlock) {
3410
+ logger.error("[ConversationSearch] No UI block in conversation search result");
3411
+ return null;
3412
+ }
3413
+ const similarity = result.similarity || 0;
3414
+ logger.info(`[ConversationSearch] Best match similarity: ${(similarity * 100).toFixed(2)}%`);
3415
+ if (similarity < similarityThreshold) {
3416
+ logger.info(
3417
+ `[ConversationSearch] Best match has similarity ${(similarity * 100).toFixed(2)}% but below threshold ${(similarityThreshold * 100).toFixed(2)}%`
3418
+ );
3419
+ return null;
3420
+ }
3421
+ logger.info(
3422
+ `[ConversationSearch] Found matching conversation with similarity ${(similarity * 100).toFixed(2)}%`
3423
+ );
3424
+ logger.debug(`[ConversationSearch] Matched prompt: "${result.metadata?.userPrompt?.substring(0, 50)}..."`);
3425
+ return result;
3426
+ } catch (error) {
3427
+ const errorMsg = error instanceof Error ? error.message : String(error);
3428
+ logger.warn(`[ConversationSearch] Error searching conversations: ${errorMsg}`);
3429
+ return null;
3430
+ }
3431
+ };
3432
+ var ConversationSearch = {
3433
+ searchConversations
3434
+ };
3435
+ var conversation_search_default = ConversationSearch;
3436
+
3208
3437
  // src/userResponse/base-llm.ts
3209
3438
  var BaseLLM = class {
3210
3439
  constructor(config) {
@@ -3219,564 +3448,39 @@ var BaseLLM = class {
3219
3448
  return apiKey || this.apiKey || this.getDefaultApiKey();
3220
3449
  }
3221
3450
  /**
3222
- * Classify user question to determine the type and required visualizations
3451
+ * Match components from text response suggestions and generate follow-up questions
3452
+ * Takes a text response with component suggestions (c1:type format) and matches with available components
3453
+ * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
3454
+ * All components are placed in a default MultiComponentContainer layout
3455
+ * @param analysisContent - The text response containing component suggestions
3456
+ * @param components - List of available components
3457
+ * @param apiKey - Optional API key
3458
+ * @param logCollector - Optional log collector
3459
+ * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
3460
+ * @returns Object containing matched components, layout title/description, and follow-up actions
3223
3461
  */
3224
- async classifyUserQuestion(userPrompt, apiKey, logCollector, conversationHistory) {
3462
+ async matchComponentsFromAnalysis(analysisContent, components, apiKey, logCollector, componentStreamCallback) {
3225
3463
  try {
3226
- const prompts = await promptLoader.loadPrompts("classify", {
3227
- USER_PROMPT: userPrompt,
3228
- CONVERSATION_HISTORY: conversationHistory || "No previous conversation"
3229
- });
3230
- const result = await LLM.stream(
3231
- {
3232
- sys: prompts.system,
3233
- user: prompts.user
3234
- },
3235
- {
3236
- model: this.model,
3237
- maxTokens: 800,
3238
- temperature: 0.2,
3239
- apiKey: this.getApiKey(apiKey)
3240
- },
3241
- true
3242
- // Parse as JSON
3243
- );
3244
- logCollector?.logExplanation(
3245
- "User question classified",
3246
- result.reasoning || "No reasoning provided",
3247
- {
3248
- questionType: result.questionType || "general",
3249
- visualizations: result.visualizations || [],
3250
- needsMultipleComponents: result.needsMultipleComponents || false
3251
- }
3252
- );
3253
- return {
3254
- questionType: result.questionType || "general",
3255
- visualizations: result.visualizations || [],
3256
- reasoning: result.reasoning || "No reasoning provided",
3257
- needsMultipleComponents: result.needsMultipleComponents || false
3258
- };
3259
- } catch (error) {
3260
- const errorMsg = error instanceof Error ? error.message : String(error);
3261
- logger.error(`[${this.getProviderName()}] Error classifying user question: ${errorMsg}`);
3262
- logger.debug(`[${this.getProviderName()}] Classification error details:`, error);
3263
- throw error;
3264
- }
3265
- }
3266
- /**
3267
- * Enhanced function that validates and modifies the entire props object based on user request
3268
- * This includes query, title, description, and config properties
3269
- */
3270
- async validateAndModifyProps(userPrompt, originalProps, componentName, componentType, componentDescription, apiKey, logCollector, conversationHistory) {
3271
- const schemaDoc = schema.generateSchemaDocumentation();
3272
- try {
3273
- const prompts = await promptLoader.loadPrompts("modify-props", {
3274
- COMPONENT_NAME: componentName,
3275
- COMPONENT_TYPE: componentType,
3276
- COMPONENT_DESCRIPTION: componentDescription || "No description",
3277
- SCHEMA_DOC: schemaDoc || "No schema available",
3278
- DEFAULT_LIMIT: this.defaultLimit,
3279
- USER_PROMPT: userPrompt,
3280
- CURRENT_PROPS: JSON.stringify(originalProps, null, 2),
3281
- CONVERSATION_HISTORY: conversationHistory || "No previous conversation"
3282
- });
3283
- logger.debug("props-modification: System prompt\n", prompts.system.substring(0, 100), "\n\n\n", "User prompt:", prompts.user.substring(0, 50));
3284
- const result = await LLM.stream(
3285
- {
3286
- sys: prompts.system,
3287
- user: prompts.user
3288
- },
3289
- {
3290
- model: this.model,
3291
- maxTokens: 2500,
3292
- temperature: 0.2,
3293
- apiKey: this.getApiKey(apiKey)
3294
- },
3295
- true
3296
- // Parse as JSON
3297
- );
3298
- const props = result.props || originalProps;
3299
- if (props && props.query) {
3300
- props.query = fixScalarSubqueries(props.query);
3301
- props.query = ensureQueryLimit(props.query, this.defaultLimit);
3302
- }
3303
- if (props && props.query) {
3304
- logCollector?.logQuery(
3305
- "Props query modified",
3306
- props.query,
3307
- {
3308
- modifications: result.modifications || [],
3309
- reasoning: result.reasoning || "No modifications needed"
3310
- }
3311
- );
3312
- }
3313
- if (result.reasoning) {
3314
- logCollector?.logExplanation(
3315
- "Props modification explanation",
3316
- result.reasoning,
3317
- { modifications: result.modifications || [] }
3318
- );
3319
- }
3320
- return {
3321
- props,
3322
- isModified: result.isModified || false,
3323
- reasoning: result.reasoning || "No modifications needed",
3324
- modifications: result.modifications || []
3325
- };
3326
- } catch (error) {
3327
- const errorMsg = error instanceof Error ? error.message : String(error);
3328
- logger.error(`[${this.getProviderName()}] Error validating/modifying props: ${errorMsg}`);
3329
- logger.debug(`[${this.getProviderName()}] Props validation error details:`, error);
3330
- throw error;
3331
- }
3332
- }
3333
- /**
3334
- * Match and select a component from available components filtered by type
3335
- * This picks the best matching component based on user prompt and modifies its props
3336
- */
3337
- async generateAnalyticalComponent(userPrompt, components, preferredVisualizationType, apiKey, logCollector, conversationHistory) {
3338
- try {
3339
- const filteredComponents = preferredVisualizationType ? components.filter((c) => c.type === preferredVisualizationType) : components;
3340
- if (filteredComponents.length === 0) {
3341
- logCollector?.warn(
3342
- `No components found of type ${preferredVisualizationType}`,
3343
- "explanation",
3344
- { reason: "No matching components available for this visualization type" }
3345
- );
3346
- return {
3347
- component: null,
3348
- reasoning: `No components available of type ${preferredVisualizationType}`,
3349
- isGenerated: false
3350
- };
3351
- }
3352
- const componentsText = filteredComponents.map((comp, idx) => {
3353
- const keywords = comp.keywords ? comp.keywords.join(", ") : "";
3354
- const category = comp.category || "general";
3355
- const propsPreview = comp.props ? JSON.stringify(comp.props, null, 2) : "No props";
3356
- return `${idx + 1}. ID: ${comp.id}
3357
- Name: ${comp.name}
3358
- Type: ${comp.type}
3359
- Category: ${category}
3360
- Description: ${comp.description || "No description"}
3361
- Keywords: ${keywords}
3362
- Props Preview: ${propsPreview}`;
3363
- }).join("\n\n");
3364
- const visualizationConstraint = preferredVisualizationType ? `
3365
- **IMPORTANT: Components are filtered to type ${preferredVisualizationType}. Select the best match.**
3366
- ` : "";
3367
- const prompts = await promptLoader.loadPrompts("single-component", {
3368
- COMPONENT_TYPE: preferredVisualizationType || "any",
3369
- COMPONENTS_LIST: componentsText,
3370
- VISUALIZATION_CONSTRAINT: visualizationConstraint,
3371
- USER_PROMPT: userPrompt,
3372
- CONVERSATION_HISTORY: conversationHistory || "No previous conversation"
3373
- });
3374
- logger.debug("single-component: System prompt\n", prompts.system.substring(0, 100), "\n\n\n", "User prompt:", prompts.user.substring(0, 50));
3375
- const result = await LLM.stream(
3376
- {
3377
- sys: prompts.system,
3378
- user: prompts.user
3379
- },
3380
- {
3381
- model: this.model,
3382
- maxTokens: 2e3,
3383
- temperature: 0.2,
3384
- apiKey: this.getApiKey(apiKey)
3385
- },
3386
- true
3387
- // Parse as JSON
3388
- );
3389
- if (!result.canGenerate || result.confidence < 50) {
3390
- logCollector?.warn(
3391
- "Cannot match component",
3392
- "explanation",
3393
- { reason: result.reasoning || "Unable to find matching component for this question" }
3394
- );
3395
- return {
3396
- component: null,
3397
- reasoning: result.reasoning || "Unable to find matching component for this question",
3398
- isGenerated: false
3399
- };
3400
- }
3401
- const componentIndex = result.componentIndex;
3402
- const componentId = result.componentId;
3403
- let matchedComponent = null;
3404
- if (componentId) {
3405
- matchedComponent = filteredComponents.find((c) => c.id === componentId);
3406
- }
3407
- if (!matchedComponent && componentIndex) {
3408
- matchedComponent = filteredComponents[componentIndex - 1];
3409
- }
3410
- if (!matchedComponent) {
3411
- logCollector?.warn("Component not found in filtered list");
3412
- return {
3413
- component: null,
3414
- reasoning: "Component not found in filtered list",
3415
- isGenerated: false
3416
- };
3417
- }
3418
- logCollector?.info(`Matched component: ${matchedComponent.name} (confidence: ${result.confidence}%)`);
3419
- const propsValidation = await this.validateAndModifyProps(
3420
- userPrompt,
3421
- matchedComponent.props,
3422
- matchedComponent.name,
3423
- matchedComponent.type,
3424
- matchedComponent.description,
3425
- apiKey,
3426
- logCollector,
3427
- conversationHistory
3428
- );
3429
- const modifiedComponent = {
3430
- ...matchedComponent,
3431
- props: propsValidation.props
3432
- };
3433
- logCollector?.logExplanation(
3434
- "Analytical component selected and modified",
3435
- result.reasoning || "Selected component based on analytical question",
3436
- {
3437
- componentName: matchedComponent.name,
3438
- componentType: matchedComponent.type,
3439
- confidence: result.confidence,
3440
- propsModified: propsValidation.isModified
3441
- }
3442
- );
3443
- return {
3444
- component: modifiedComponent,
3445
- reasoning: result.reasoning || "Selected and modified component based on analytical question",
3446
- isGenerated: true
3447
- };
3448
- } catch (error) {
3449
- const errorMsg = error instanceof Error ? error.message : String(error);
3450
- logger.error(`[${this.getProviderName()}] Error generating analytical component: ${errorMsg}`);
3451
- logger.debug(`[${this.getProviderName()}] Analytical component generation error details:`, error);
3452
- throw error;
3453
- }
3454
- }
3455
- /**
3456
- * Generate container metadata (title and description) for multi-component dashboard
3457
- */
3458
- async generateContainerMetadata(userPrompt, visualizationTypes, apiKey, logCollector, conversationHistory) {
3459
- try {
3460
- const prompts = await promptLoader.loadPrompts("container-metadata", {
3461
- USER_PROMPT: userPrompt,
3462
- VISUALIZATION_TYPES: visualizationTypes.join(", "),
3463
- CONVERSATION_HISTORY: conversationHistory || "No previous conversation"
3464
- });
3465
- const result = await LLM.stream(
3466
- {
3467
- sys: prompts.system,
3468
- user: prompts.user
3469
- },
3470
- {
3471
- model: this.model,
3472
- maxTokens: 500,
3473
- temperature: 0.3,
3474
- apiKey: this.getApiKey(apiKey)
3475
- },
3476
- true
3477
- // Parse as JSON
3478
- );
3479
- logCollector?.logExplanation(
3480
- "Container metadata generated",
3481
- `Generated title and description for multi-component dashboard`,
3482
- {
3483
- title: result.title,
3484
- description: result.description,
3485
- visualizationTypes
3486
- }
3487
- );
3488
- return {
3489
- title: result.title || `${userPrompt} - Dashboard`,
3490
- description: result.description || `Multi-component dashboard showing ${visualizationTypes.join(", ")}`
3491
- };
3492
- } catch (error) {
3493
- const errorMsg = error instanceof Error ? error.message : String(error);
3494
- logger.error(`[${this.getProviderName()}] Error generating container metadata: ${errorMsg}`);
3495
- logger.debug(`[${this.getProviderName()}] Container metadata error details:`, error);
3496
- return {
3497
- title: `${userPrompt} - Dashboard`,
3498
- description: `Multi-component dashboard showing ${visualizationTypes.join(", ")}`
3499
- };
3500
- }
3501
- }
3502
- /**
3503
- * Match component from a list with enhanced props modification
3504
- */
3505
- async matchComponent(userPrompt, components, apiKey, logCollector, conversationHistory) {
3506
- try {
3507
- const componentsText = components.map((comp, idx) => {
3508
- const keywords = comp.keywords ? comp.keywords.join(", ") : "";
3509
- const category = comp.category || "general";
3510
- return `${idx + 1}. ID: ${comp.id}
3511
- Name: ${comp.name}
3512
- Type: ${comp.type}
3513
- Category: ${category}
3514
- Description: ${comp.description || "No description"}
3515
- Keywords: ${keywords}`;
3516
- }).join("\n\n");
3517
- const prompts = await promptLoader.loadPrompts("match-component", {
3518
- COMPONENTS_TEXT: componentsText,
3519
- USER_PROMPT: userPrompt,
3520
- CONVERSATION_HISTORY: conversationHistory || "No previous conversation"
3521
- });
3522
- const result = await LLM.stream(
3523
- {
3524
- sys: prompts.system,
3525
- user: prompts.user
3526
- },
3527
- {
3528
- model: this.model,
3529
- maxTokens: 800,
3530
- temperature: 0.2,
3531
- apiKey: this.getApiKey(apiKey)
3532
- },
3533
- true
3534
- // Parse as JSON
3535
- );
3536
- const componentIndex = result.componentIndex;
3537
- const componentId = result.componentId;
3538
- const confidence = result.confidence || 0;
3539
- let component = null;
3540
- if (componentId) {
3541
- component = components.find((c) => c.id === componentId);
3542
- }
3543
- if (!component && componentIndex) {
3544
- component = components[componentIndex - 1];
3545
- }
3546
- const matchedMsg = `${this.getProviderName()} matched component: ${component?.name || "None"}`;
3547
- logger.info(`[${this.getProviderName()}] \u2713 ${matchedMsg}`);
3548
- logCollector?.info(matchedMsg);
3549
- if (result.alternativeMatches && result.alternativeMatches.length > 0) {
3550
- logger.debug(`[${this.getProviderName()}] Alternative matches found: ${result.alternativeMatches.length}`);
3551
- const altMatches = result.alternativeMatches.map(
3552
- (alt) => `${components[alt.index - 1]?.name} (${alt.score}%): ${alt.reason}`
3553
- ).join(" | ");
3554
- logCollector?.info(`Alternative matches: ${altMatches}`);
3555
- result.alternativeMatches.forEach((alt) => {
3556
- logger.debug(`[${this.getProviderName()}] - ${components[alt.index - 1]?.name} (${alt.score}%): ${alt.reason}`);
3557
- });
3558
- }
3559
- if (!component) {
3560
- const noMatchMsg = `No matching component found (confidence: ${confidence}%)`;
3561
- logger.warn(`[${this.getProviderName()}] \u2717 ${noMatchMsg}`);
3562
- logCollector?.warn(noMatchMsg);
3563
- const genMsg = "Attempting to match component from analytical question...";
3564
- logger.info(`[${this.getProviderName()}] \u2713 ${genMsg}`);
3565
- logCollector?.info(genMsg);
3566
- const generatedResult = await this.generateAnalyticalComponent(userPrompt, components, void 0, apiKey, logCollector, conversationHistory);
3567
- if (generatedResult.component) {
3568
- const genSuccessMsg = `Successfully matched component: ${generatedResult.component.name}`;
3569
- logCollector?.info(genSuccessMsg);
3570
- return {
3571
- component: generatedResult.component,
3572
- reasoning: generatedResult.reasoning,
3573
- method: `${this.getProviderName()}-generated`,
3574
- confidence: 100,
3575
- // Generated components are considered 100% match to the question
3576
- propsModified: false,
3577
- queryModified: false
3578
- };
3579
- }
3580
- logCollector?.error("Failed to match component");
3581
- return {
3582
- component: null,
3583
- reasoning: result.reasoning || "No matching component found and unable to match component",
3584
- method: `${this.getProviderName()}-llm`,
3585
- confidence
3586
- };
3587
- }
3588
- let propsModified = false;
3589
- let propsModifications = [];
3590
- let queryModified = false;
3591
- let queryReasoning = "";
3592
- if (component && component.props) {
3593
- const propsValidation = await this.validateAndModifyProps(
3594
- userPrompt,
3595
- component.props,
3596
- component.name,
3597
- component.type,
3598
- component.description,
3599
- apiKey,
3600
- logCollector,
3601
- conversationHistory
3602
- );
3603
- const originalQuery = component.props.query;
3604
- const modifiedQuery = propsValidation.props.query;
3605
- component = {
3606
- ...component,
3607
- props: propsValidation.props
3608
- };
3609
- propsModified = propsValidation.isModified;
3610
- propsModifications = propsValidation.modifications;
3611
- queryModified = originalQuery !== modifiedQuery;
3612
- queryReasoning = propsValidation.reasoning;
3613
- }
3614
- return {
3615
- component,
3616
- reasoning: result.reasoning || "No reasoning provided",
3617
- queryModified,
3618
- queryReasoning,
3619
- propsModified,
3620
- propsModifications,
3621
- method: `${this.getProviderName()}-llm`,
3622
- confidence
3623
- };
3624
- } catch (error) {
3625
- const errorMsg = error instanceof Error ? error.message : String(error);
3626
- logger.error(`[${this.getProviderName()}] Error matching component: ${errorMsg}`);
3627
- logger.debug(`[${this.getProviderName()}] Component matching error details:`, error);
3628
- logCollector?.error(`Error matching component: ${errorMsg}`);
3629
- throw error;
3630
- }
3631
- }
3632
- /**
3633
- * Match multiple components for analytical questions by visualization types
3634
- * This is used when the user needs multiple visualizations
3635
- */
3636
- async generateMultipleAnalyticalComponents(userPrompt, availableComponents, visualizationTypes, apiKey, logCollector, conversationHistory) {
3637
- try {
3638
- console.log("\u2713 Matching multiple components:", visualizationTypes);
3639
- const components = [];
3640
- for (const vizType of visualizationTypes) {
3641
- const result = await this.generateAnalyticalComponent(userPrompt, availableComponents, vizType, apiKey, logCollector, conversationHistory);
3642
- if (result.component) {
3643
- components.push(result.component);
3644
- }
3645
- }
3646
- if (components.length === 0) {
3647
- return {
3648
- components: [],
3649
- reasoning: "Failed to match any components",
3650
- isGenerated: false
3651
- };
3652
- }
3653
- return {
3654
- components,
3655
- reasoning: `Matched ${components.length} components: ${visualizationTypes.join(", ")}`,
3656
- isGenerated: true
3657
- };
3658
- } catch (error) {
3659
- const errorMsg = error instanceof Error ? error.message : String(error);
3660
- logger.error(`[${this.getProviderName()}] Error matching multiple analytical components: ${errorMsg}`);
3661
- logger.debug(`[${this.getProviderName()}] Multiple components matching error details:`, error);
3662
- return {
3663
- components: [],
3664
- reasoning: "Error occurred while matching components",
3665
- isGenerated: false
3666
- };
3667
- }
3668
- }
3669
- /**
3670
- * Match multiple components and wrap them in a container
3671
- */
3672
- async generateMultiComponentResponse(userPrompt, availableComponents, visualizationTypes, apiKey, logCollector, conversationHistory) {
3673
- try {
3674
- const matchResult = await this.generateMultipleAnalyticalComponents(
3675
- userPrompt,
3676
- availableComponents,
3677
- visualizationTypes,
3678
- apiKey,
3679
- logCollector,
3680
- conversationHistory
3681
- );
3682
- if (!matchResult.isGenerated || matchResult.components.length === 0) {
3683
- return {
3684
- containerComponent: null,
3685
- reasoning: matchResult.reasoning || "Unable to match multi-component dashboard",
3686
- isGenerated: false
3687
- };
3688
- }
3689
- const generatedComponents = matchResult.components;
3690
- generatedComponents.forEach((component, index) => {
3691
- if (component.props.query) {
3692
- logCollector?.logQuery(
3693
- `Multi-component query generated (${index + 1}/${generatedComponents.length})`,
3694
- component.props.query,
3695
- {
3696
- componentType: component.type,
3697
- title: component.props.title,
3698
- position: index + 1,
3699
- totalComponents: generatedComponents.length
3700
- }
3701
- );
3702
- }
3703
- });
3704
- const containerTitle = `${userPrompt} - Dashboard`;
3705
- const containerDescription = `Multi-component dashboard showing ${visualizationTypes.join(", ")}`;
3706
- logCollector?.logExplanation(
3707
- "Multi-component dashboard matched",
3708
- matchResult.reasoning || `Matched ${generatedComponents.length} components for comprehensive analysis`,
3709
- {
3710
- totalComponents: generatedComponents.length,
3711
- componentTypes: generatedComponents.map((c) => c.type),
3712
- componentNames: generatedComponents.map((c) => c.name),
3713
- containerTitle,
3714
- containerDescription
3715
- }
3716
- );
3717
- const containerComponent = {
3718
- id: `multi_container_${Date.now()}`,
3719
- name: "MultiComponentContainer",
3720
- type: "Container",
3721
- description: containerDescription,
3722
- category: "dynamic",
3723
- keywords: ["multi", "container", "dashboard"],
3724
- props: {
3725
- config: {
3726
- components: generatedComponents,
3727
- layout: "grid",
3728
- spacing: 24,
3729
- title: containerTitle,
3730
- description: containerDescription
3731
- }
3732
- }
3733
- };
3734
- return {
3735
- containerComponent,
3736
- reasoning: matchResult.reasoning || `Matched multi-component dashboard with ${generatedComponents.length} components`,
3737
- isGenerated: true
3738
- };
3739
- } catch (error) {
3740
- const errorMsg = error instanceof Error ? error.message : String(error);
3741
- logger.error(`[${this.getProviderName()}] Error generating multi-component response: ${errorMsg}`);
3742
- logger.debug(`[${this.getProviderName()}] Multi-component response error details:`, error);
3743
- throw error;
3744
- }
3745
- }
3746
- /**
3747
- * Match components from text response suggestions and generate follow-up questions
3748
- * Takes a text response with component suggestions (c1:type format) and matches with available components
3749
- * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
3750
- * All components are placed in a default MultiComponentContainer layout
3751
- * @param analysisContent - The text response containing component suggestions
3752
- * @param components - List of available components
3753
- * @param apiKey - Optional API key
3754
- * @param logCollector - Optional log collector
3755
- * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
3756
- * @returns Object containing matched components, layout title/description, and follow-up actions
3757
- */
3758
- async matchComponentsFromAnalysis(analysisContent, components, apiKey, logCollector, componentStreamCallback) {
3759
- try {
3760
- logger.debug(`[${this.getProviderName()}] Starting component matching from text response`);
3761
- let availableComponentsText = "No components available";
3762
- if (components && components.length > 0) {
3763
- availableComponentsText = components.map((comp, idx) => {
3764
- const keywords = comp.keywords ? comp.keywords.join(", ") : "";
3765
- const propsPreview = comp.props ? JSON.stringify(comp.props, null, 2) : "No props";
3766
- return `${idx + 1}. ID: ${comp.id}
3767
- Name: ${comp.name}
3768
- Type: ${comp.type}
3769
- Description: ${comp.description || "No description"}
3770
- Keywords: ${keywords}
3771
- Props Structure: ${propsPreview}`;
3772
- }).join("\n\n");
3773
- }
3774
- const schemaDoc = schema.generateSchemaDocumentation();
3775
- logger.file("\n=============================\nText analysis response:", analysisContent);
3776
- const prompts = await promptLoader.loadPrompts("match-text-components", {
3777
- ANALYSIS_CONTENT: analysisContent,
3778
- AVAILABLE_COMPONENTS: availableComponentsText,
3779
- SCHEMA_DOC: schemaDoc
3464
+ logger.debug(`[${this.getProviderName()}] Starting component matching from text response`);
3465
+ let availableComponentsText = "No components available";
3466
+ if (components && components.length > 0) {
3467
+ availableComponentsText = components.map((comp, idx) => {
3468
+ const keywords = comp.keywords ? comp.keywords.join(", ") : "";
3469
+ const propsPreview = comp.props ? JSON.stringify(comp.props, null, 2) : "No props";
3470
+ return `${idx + 1}. ID: ${comp.id}
3471
+ Name: ${comp.name}
3472
+ Type: ${comp.type}
3473
+ Description: ${comp.description || "No description"}
3474
+ Keywords: ${keywords}
3475
+ Props Structure: ${propsPreview}`;
3476
+ }).join("\n\n");
3477
+ }
3478
+ const schemaDoc = schema.generateSchemaDocumentation();
3479
+ logger.file("\n=============================\nText analysis response:", analysisContent);
3480
+ const prompts = await promptLoader.loadPrompts("match-text-components", {
3481
+ ANALYSIS_CONTENT: analysisContent,
3482
+ AVAILABLE_COMPONENTS: availableComponentsText,
3483
+ SCHEMA_DOC: schemaDoc
3780
3484
  });
3781
3485
  logger.debug(`[${this.getProviderName()}] Loaded match-text-components prompts`);
3782
3486
  logger.file("\n=============================\nmatch text components system prompt:", prompts.system);
@@ -3968,148 +3672,136 @@ var BaseLLM = class {
3968
3672
  }
3969
3673
  }
3970
3674
  /**
3971
- * Execute external tools based on user request using agentic LLM tool calling
3972
- * The LLM can directly call tools and retry on errors
3973
- * @param userPrompt - The user's question/request
3974
- * @param availableTools - Array of available external tools
3975
- * @param apiKey - Optional API key for LLM
3976
- * @param logCollector - Optional log collector
3977
- * @returns Object containing tool execution results and summary
3675
+ * Classify user question into category and detect external tools needed
3676
+ * Determines if question is for data analysis, requires external tools, or needs text response
3978
3677
  */
3979
- async executeExternalTools(userPrompt, availableTools, apiKey, logCollector) {
3980
- const MAX_TOOL_ATTEMPTS = 3;
3981
- const toolResults = [];
3678
+ async classifyQuestionCategory(userPrompt, apiKey, logCollector, conversationHistory, externalTools) {
3982
3679
  try {
3983
- logger.debug(`[${this.getProviderName()}] Starting agentic external tool execution`);
3984
- logger.debug(`[${this.getProviderName()}] Available tools: ${availableTools.map((t) => t.name).join(", ")}`);
3985
- const llmTools = availableTools.map((tool) => {
3986
- const properties = {};
3987
- const required = [];
3988
- Object.entries(tool.params || {}).forEach(([key, type]) => {
3989
- properties[key] = {
3990
- type: String(type).toLowerCase(),
3991
- description: `${key} parameter`
3992
- };
3993
- required.push(key);
3994
- });
3995
- return {
3996
- name: tool.id,
3997
- description: tool.description,
3998
- input_schema: {
3999
- type: "object",
4000
- properties,
4001
- required
4002
- }
4003
- };
3680
+ const availableToolsDoc = externalTools && externalTools.length > 0 ? externalTools.map((tool) => {
3681
+ const paramsStr = Object.entries(tool.params || {}).map(([key, type]) => `${key}: ${type}`).join(", ");
3682
+ return `- **${tool.name}** (id: ${tool.id})
3683
+ Description: ${tool.description}
3684
+ Parameters: ${paramsStr}`;
3685
+ }).join("\n\n") : "No external tools available";
3686
+ const prompts = await promptLoader.loadPrompts("category-classification", {
3687
+ USER_PROMPT: userPrompt,
3688
+ CONVERSATION_HISTORY: conversationHistory || "No previous conversation",
3689
+ AVAILABLE_TOOLS: availableToolsDoc
4004
3690
  });
4005
- const toolAttempts = /* @__PURE__ */ new Map();
4006
- const toolHandler = async (toolName, toolInput) => {
4007
- const tool = availableTools.find((t) => t.id === toolName);
4008
- if (!tool) {
4009
- const errorMsg = `Tool ${toolName} not found in available tools`;
4010
- logger.error(`[${this.getProviderName()}] ${errorMsg}`);
4011
- logCollector?.error(errorMsg);
4012
- throw new Error(errorMsg);
4013
- }
4014
- const attempts = (toolAttempts.get(toolName) || 0) + 1;
4015
- toolAttempts.set(toolName, attempts);
4016
- logger.info(`[${this.getProviderName()}] Executing tool: ${tool.name} (attempt ${attempts}/${MAX_TOOL_ATTEMPTS})`);
4017
- logCollector?.info(`Executing ${tool.name} (attempt ${attempts}/${MAX_TOOL_ATTEMPTS})...`);
4018
- if (attempts > MAX_TOOL_ATTEMPTS) {
4019
- const errorMsg = `Maximum attempts (${MAX_TOOL_ATTEMPTS}) reached for tool: ${tool.name}`;
4020
- logger.error(`[${this.getProviderName()}] ${errorMsg}`);
4021
- logCollector?.error(errorMsg);
4022
- toolResults.push({
4023
- toolName: tool.name,
4024
- toolId: tool.id,
4025
- result: null,
4026
- error: errorMsg
4027
- });
4028
- throw new Error(errorMsg);
4029
- }
4030
- try {
4031
- logger.debug(`[${this.getProviderName()}] Tool ${tool.name} parameters:`, toolInput);
4032
- const result2 = await tool.fn(toolInput);
4033
- logger.info(`[${this.getProviderName()}] Tool ${tool.name} executed successfully`);
4034
- logCollector?.info(`\u2713 ${tool.name} completed successfully`);
4035
- toolResults.push({
4036
- toolName: tool.name,
4037
- toolId: tool.id,
4038
- result: result2
4039
- });
4040
- return JSON.stringify(result2, null, 2);
4041
- } catch (error) {
4042
- const errorMsg = error instanceof Error ? error.message : String(error);
4043
- logger.error(`[${this.getProviderName()}] Tool ${tool.name} failed (attempt ${attempts}): ${errorMsg}`);
4044
- logCollector?.error(`\u2717 ${tool.name} failed: ${errorMsg}`);
4045
- if (attempts >= MAX_TOOL_ATTEMPTS) {
4046
- toolResults.push({
4047
- toolName: tool.name,
4048
- toolId: tool.id,
4049
- result: null,
4050
- error: errorMsg
4051
- });
4052
- }
4053
- throw new Error(`Tool execution failed: ${errorMsg}`);
3691
+ const result = await LLM.stream(
3692
+ {
3693
+ sys: prompts.system,
3694
+ user: prompts.user
3695
+ },
3696
+ {
3697
+ model: this.model,
3698
+ maxTokens: 1e3,
3699
+ temperature: 0.2,
3700
+ apiKey: this.getApiKey(apiKey)
3701
+ },
3702
+ true
3703
+ // Parse as JSON
3704
+ );
3705
+ logCollector?.logExplanation(
3706
+ "Question category classified",
3707
+ result.reasoning || "No reasoning provided",
3708
+ {
3709
+ category: result.category,
3710
+ externalTools: result.externalTools || [],
3711
+ dataAnalysisType: result.dataAnalysisType,
3712
+ confidence: result.confidence
4054
3713
  }
3714
+ );
3715
+ return {
3716
+ category: result.category || "data_analysis",
3717
+ externalTools: result.externalTools || [],
3718
+ dataAnalysisType: result.dataAnalysisType,
3719
+ reasoning: result.reasoning || "No reasoning provided",
3720
+ confidence: result.confidence || 0
4055
3721
  };
4056
- const prompts = await promptLoader.loadPrompts("execute-tools", {
4057
- USER_PROMPT: userPrompt,
4058
- AVAILABLE_TOOLS: availableTools.map((tool, idx) => {
4059
- const paramsText = Object.entries(tool.params || {}).map(([key, type]) => ` - ${key}: ${type}`).join("\n");
4060
- return `${idx + 1}. ID: ${tool.id}
4061
- Name: ${tool.name}
4062
- Description: ${tool.description}
4063
- Parameters:
4064
- ${paramsText}`;
4065
- }).join("\n\n")
3722
+ } catch (error) {
3723
+ const errorMsg = error instanceof Error ? error.message : String(error);
3724
+ logger.error(`[${this.getProviderName()}] Error classifying question category: ${errorMsg}`);
3725
+ logger.debug(`[${this.getProviderName()}] Category classification error details:`, error);
3726
+ throw error;
3727
+ }
3728
+ }
3729
+ /**
3730
+ * Adapt UI block parameters based on current user question
3731
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
3732
+ */
3733
+ async adaptUIBlockParameters(currentUserPrompt, originalUserPrompt, matchedUIBlock, apiKey, logCollector) {
3734
+ try {
3735
+ const component = matchedUIBlock?.generatedComponentMetadata || matchedUIBlock?.component;
3736
+ if (!matchedUIBlock || !component) {
3737
+ return {
3738
+ success: false,
3739
+ explanation: "No component found in matched UI block"
3740
+ };
3741
+ }
3742
+ const schemaDoc = schema.generateSchemaDocumentation();
3743
+ const prompts = await promptLoader.loadPrompts("adapt-ui-block-params", {
3744
+ ORIGINAL_USER_PROMPT: originalUserPrompt,
3745
+ CURRENT_USER_PROMPT: currentUserPrompt,
3746
+ MATCHED_UI_BLOCK_COMPONENT: JSON.stringify(component, null, 2),
3747
+ COMPONENT_PROPS: JSON.stringify(component.props, null, 2),
3748
+ SCHEMA_DOC: schemaDoc || "No schema available"
4066
3749
  });
4067
- logger.debug(`[${this.getProviderName()}] Using agentic tool calling for external tools`);
4068
- logCollector?.info("Analyzing request and executing external tools...");
4069
- const result = await LLM.streamWithTools(
3750
+ const result = await LLM.stream(
4070
3751
  {
4071
3752
  sys: prompts.system,
4072
3753
  user: prompts.user
4073
3754
  },
4074
- llmTools,
4075
- toolHandler,
4076
3755
  {
4077
3756
  model: this.model,
4078
3757
  maxTokens: 2e3,
4079
3758
  temperature: 0.2,
4080
3759
  apiKey: this.getApiKey(apiKey)
4081
3760
  },
4082
- MAX_TOOL_ATTEMPTS + 2
4083
- // max iterations: allows for retries + final response
3761
+ true
3762
+ // Parse as JSON
4084
3763
  );
4085
- logger.info(`[${this.getProviderName()}] External tool execution completed`);
4086
- const successfulTools = toolResults.filter((r) => !r.error);
4087
- const failedTools = toolResults.filter((r) => r.error);
4088
- let summary = "";
4089
- if (successfulTools.length > 0) {
4090
- summary += `Successfully executed ${successfulTools.length} tool(s): ${successfulTools.map((t) => t.toolName).join(", ")}.
4091
- `;
4092
- }
4093
- if (failedTools.length > 0) {
4094
- summary += `Failed to execute ${failedTools.length} tool(s): ${failedTools.map((t) => t.toolName).join(", ")}.`;
3764
+ if (!result.success) {
3765
+ logger.info(
3766
+ `[${this.getProviderName()}] Could not adapt UI block: ${result.reason}`
3767
+ );
3768
+ logCollector?.warn(
3769
+ "Could not adapt matched UI block",
3770
+ "explanation",
3771
+ { reason: result.reason }
3772
+ );
3773
+ return {
3774
+ success: false,
3775
+ explanation: result.explanation || "Adaptation not possible"
3776
+ };
4095
3777
  }
4096
- if (toolResults.length === 0) {
4097
- summary = "No external tools were needed for this request.";
3778
+ if (result.adaptedComponent?.props?.query) {
3779
+ result.adaptedComponent.props.query = ensureQueryLimit(
3780
+ result.adaptedComponent.props.query,
3781
+ this.defaultLimit
3782
+ );
4098
3783
  }
4099
- logger.info(`[${this.getProviderName()}] Tool execution summary: ${summary}`);
3784
+ logCollector?.logExplanation(
3785
+ "UI block parameters adapted",
3786
+ result.explanation || "Parameters adapted successfully",
3787
+ {
3788
+ parametersChanged: result.parametersChanged || [],
3789
+ componentType: result.adaptedComponent?.type
3790
+ }
3791
+ );
4100
3792
  return {
4101
- toolResults,
4102
- summary,
4103
- hasResults: successfulTools.length > 0
3793
+ success: true,
3794
+ adaptedComponent: result.adaptedComponent,
3795
+ parametersChanged: result.parametersChanged,
3796
+ explanation: result.explanation || "Parameters adapted successfully"
4104
3797
  };
4105
3798
  } catch (error) {
4106
3799
  const errorMsg = error instanceof Error ? error.message : String(error);
4107
- logger.error(`[${this.getProviderName()}] Error in external tool execution: ${errorMsg}`);
4108
- logCollector?.error(`Error executing external tools: ${errorMsg}`);
3800
+ logger.error(`[${this.getProviderName()}] Error adapting UI block parameters: ${errorMsg}`);
3801
+ logger.debug(`[${this.getProviderName()}] Adaptation error details:`, error);
4109
3802
  return {
4110
- toolResults,
4111
- summary: `Error executing external tools: ${errorMsg}`,
4112
- hasResults: false
3803
+ success: false,
3804
+ explanation: `Error adapting parameters: ${errorMsg}`
4113
3805
  };
4114
3806
  }
4115
3807
  }
@@ -4128,32 +3820,24 @@ ${paramsText}`;
4128
3820
  logger.debug(`[${this.getProviderName()}] Starting text response generation`);
4129
3821
  logger.debug(`[${this.getProviderName()}] User prompt: "${userPrompt.substring(0, 50)}..."`);
4130
3822
  try {
4131
- let externalToolContext = "No external tools were used for this request.";
3823
+ let availableToolsDoc = "No external tools are available for this request.";
4132
3824
  if (externalTools && externalTools.length > 0) {
4133
- logger.info(`[${this.getProviderName()}] Executing external tools...`);
4134
- const toolExecution = await this.executeExternalTools(
4135
- userPrompt,
4136
- externalTools,
4137
- apiKey,
4138
- logCollector
4139
- );
4140
- if (toolExecution.hasResults) {
4141
- const toolResultsText = toolExecution.toolResults.map((tr) => {
4142
- if (tr.error) {
4143
- return `**${tr.toolName}** (Failed): ${tr.error}`;
3825
+ logger.info(`[${this.getProviderName()}] External tools available: ${externalTools.map((t) => t.name).join(", ")}`);
3826
+ availableToolsDoc = "\u26A0\uFE0F **EXECUTE THESE TOOLS IMMEDIATELY** \u26A0\uFE0F\n\nThe following external tools have been identified as necessary for this request. You MUST call them:\n\n" + externalTools.map((tool, idx) => {
3827
+ const paramsText = Object.entries(tool.params || {}).map(([key, value]) => {
3828
+ const valueType = typeof value;
3829
+ if (valueType === "string" && ["string", "number", "integer", "boolean", "array", "object"].includes(String(value).toLowerCase())) {
3830
+ return `- ${key}: ${value}`;
3831
+ } else {
3832
+ return `- ${key}: ${JSON.stringify(value)} (default value - use this)`;
4144
3833
  }
4145
- return `**${tr.toolName}** (Success):
4146
- ${JSON.stringify(tr.result, null, 2)}`;
4147
- }).join("\n\n");
4148
- externalToolContext = `## External Tool Results
4149
-
4150
- ${toolExecution.summary}
4151
-
4152
- ${toolResultsText}`;
4153
- logger.info(`[${this.getProviderName()}] External tools executed, results available`);
4154
- } else {
4155
- logger.info(`[${this.getProviderName()}] No external tools were needed`);
4156
- }
3834
+ }).join("\n ");
3835
+ return `${idx + 1}. **${tool.name}** (ID: ${tool.id})
3836
+ Description: ${tool.description}
3837
+ **ACTION REQUIRED**: Call this tool with the parameters below
3838
+ Parameters:
3839
+ ${paramsText}`;
3840
+ }).join("\n\n");
4157
3841
  }
4158
3842
  const schemaDoc = schema.generateSchemaDocumentation();
4159
3843
  const knowledgeBaseContext = await knowledge_base_default.getKnowledgeBase({
@@ -4162,13 +3846,12 @@ ${toolResultsText}`;
4162
3846
  topK: 1
4163
3847
  });
4164
3848
  logger.file("\n=============================\nknowledge base context:", knowledgeBaseContext);
4165
- logger.file("\n=============================\nexternal tool context:", externalToolContext);
4166
3849
  const prompts = await promptLoader.loadPrompts("text-response", {
4167
3850
  USER_PROMPT: userPrompt,
4168
3851
  CONVERSATION_HISTORY: conversationHistory || "No previous conversation",
4169
3852
  SCHEMA_DOC: schemaDoc,
4170
3853
  KNOWLEDGE_BASE_CONTEXT: knowledgeBaseContext || "No additional knowledge base context available.",
4171
- EXTERNAL_TOOL_CONTEXT: externalToolContext
3854
+ AVAILABLE_EXTERNAL_TOOLS: availableToolsDoc
4172
3855
  });
4173
3856
  logger.file("\n=============================\nsystem prompt:", prompts.system);
4174
3857
  logger.file("\n=============================\nuser prompt:", prompts.user);
@@ -4189,12 +3872,89 @@ ${toolResultsText}`;
4189
3872
  type: "string",
4190
3873
  description: "Brief explanation of what this query does and why it answers the user's question."
4191
3874
  }
4192
- },
4193
- required: ["query"]
4194
- }
4195
- }];
3875
+ },
3876
+ required: ["query"],
3877
+ additionalProperties: false
3878
+ }
3879
+ }];
3880
+ if (externalTools && externalTools.length > 0) {
3881
+ externalTools.forEach((tool) => {
3882
+ logger.info(`[${this.getProviderName()}] Processing external tool:`, JSON.stringify(tool, null, 2));
3883
+ const properties = {};
3884
+ const required = [];
3885
+ Object.entries(tool.params || {}).forEach(([key, typeOrValue]) => {
3886
+ let schemaType;
3887
+ let hasDefaultValue = false;
3888
+ let defaultValue;
3889
+ const valueType = typeof typeOrValue;
3890
+ if (valueType === "number") {
3891
+ schemaType = Number.isInteger(typeOrValue) ? "integer" : "number";
3892
+ hasDefaultValue = true;
3893
+ defaultValue = typeOrValue;
3894
+ } else if (valueType === "boolean") {
3895
+ schemaType = "boolean";
3896
+ hasDefaultValue = true;
3897
+ defaultValue = typeOrValue;
3898
+ } else if (Array.isArray(typeOrValue)) {
3899
+ schemaType = "array";
3900
+ hasDefaultValue = true;
3901
+ defaultValue = typeOrValue;
3902
+ } else if (valueType === "object" && typeOrValue !== null) {
3903
+ schemaType = "object";
3904
+ hasDefaultValue = true;
3905
+ defaultValue = typeOrValue;
3906
+ } else {
3907
+ const typeStr = String(typeOrValue).toLowerCase().trim();
3908
+ if (typeStr === "string" || typeStr === "str") {
3909
+ schemaType = "string";
3910
+ } else if (typeStr === "number" || typeStr === "num" || typeStr === "float" || typeStr === "double") {
3911
+ schemaType = "number";
3912
+ } else if (typeStr === "integer" || typeStr === "int") {
3913
+ schemaType = "integer";
3914
+ } else if (typeStr === "boolean" || typeStr === "bool") {
3915
+ schemaType = "boolean";
3916
+ } else if (typeStr === "array" || typeStr === "list") {
3917
+ schemaType = "array";
3918
+ } else if (typeStr === "object" || typeStr === "dict") {
3919
+ schemaType = "object";
3920
+ } else {
3921
+ schemaType = "string";
3922
+ hasDefaultValue = true;
3923
+ defaultValue = typeOrValue;
3924
+ }
3925
+ }
3926
+ const propertySchema = {
3927
+ type: schemaType,
3928
+ description: `${key} parameter for ${tool.name}`
3929
+ };
3930
+ if (hasDefaultValue) {
3931
+ propertySchema.default = defaultValue;
3932
+ } else {
3933
+ required.push(key);
3934
+ }
3935
+ properties[key] = propertySchema;
3936
+ });
3937
+ const inputSchema = {
3938
+ type: "object",
3939
+ properties,
3940
+ additionalProperties: false
3941
+ };
3942
+ if (required.length > 0) {
3943
+ inputSchema.required = required;
3944
+ }
3945
+ tools.push({
3946
+ name: tool.id,
3947
+ description: tool.description,
3948
+ input_schema: inputSchema
3949
+ });
3950
+ });
3951
+ logger.info(`[${this.getProviderName()}] Added ${externalTools.length} external tools to tool calling capability`);
3952
+ logger.info(`[${this.getProviderName()}] Complete tools array:`, JSON.stringify(tools, null, 2));
3953
+ }
4196
3954
  const queryAttempts = /* @__PURE__ */ new Map();
4197
3955
  const MAX_QUERY_ATTEMPTS = 6;
3956
+ const toolAttempts = /* @__PURE__ */ new Map();
3957
+ const MAX_TOOL_ATTEMPTS = 3;
4198
3958
  let maxAttemptsReached = false;
4199
3959
  let fullStreamedText = "";
4200
3960
  const wrappedStreamCallback = streamCallback ? (chunk) => {
@@ -4336,8 +4096,75 @@ ${errorMsg}
4336
4096
  }
4337
4097
  throw new Error(`Query execution failed: ${errorMsg}`);
4338
4098
  }
4099
+ } else {
4100
+ const externalTool = externalTools?.find((t) => t.id === toolName);
4101
+ if (externalTool) {
4102
+ const attempts = (toolAttempts.get(toolName) || 0) + 1;
4103
+ toolAttempts.set(toolName, attempts);
4104
+ logger.info(`[${this.getProviderName()}] Executing external tool: ${externalTool.name} (attempt ${attempts}/${MAX_TOOL_ATTEMPTS})`);
4105
+ logCollector?.info(`Executing external tool: ${externalTool.name} (attempt ${attempts}/${MAX_TOOL_ATTEMPTS})...`);
4106
+ if (attempts > MAX_TOOL_ATTEMPTS) {
4107
+ const errorMsg = `Maximum attempts (${MAX_TOOL_ATTEMPTS}) reached for tool: ${externalTool.name}`;
4108
+ logger.error(`[${this.getProviderName()}] ${errorMsg}`);
4109
+ logCollector?.error(errorMsg);
4110
+ if (wrappedStreamCallback) {
4111
+ wrappedStreamCallback(`
4112
+
4113
+ \u274C ${errorMsg}
4114
+
4115
+ Please try rephrasing your request or contact support.
4116
+
4117
+ `);
4118
+ }
4119
+ throw new Error(errorMsg);
4120
+ }
4121
+ try {
4122
+ if (wrappedStreamCallback) {
4123
+ if (attempts === 1) {
4124
+ wrappedStreamCallback(`
4125
+
4126
+ \u{1F517} **Executing ${externalTool.name}...**
4127
+
4128
+ `);
4129
+ } else {
4130
+ wrappedStreamCallback(`
4131
+
4132
+ \u{1F504} **Retrying ${externalTool.name} (attempt ${attempts}/${MAX_TOOL_ATTEMPTS})...**
4133
+
4134
+ `);
4135
+ }
4136
+ }
4137
+ const result2 = await externalTool.fn(toolInput);
4138
+ logger.info(`[${this.getProviderName()}] External tool ${externalTool.name} executed successfully`);
4139
+ logCollector?.info(`\u2713 ${externalTool.name} executed successfully`);
4140
+ if (wrappedStreamCallback) {
4141
+ wrappedStreamCallback(`\u2705 **${externalTool.name} completed successfully**
4142
+
4143
+ `);
4144
+ }
4145
+ return JSON.stringify(result2, null, 2);
4146
+ } catch (error) {
4147
+ const errorMsg = error instanceof Error ? error.message : String(error);
4148
+ logger.error(`[${this.getProviderName()}] External tool ${externalTool.name} failed (attempt ${attempts}/${MAX_TOOL_ATTEMPTS}): ${errorMsg}`);
4149
+ logCollector?.error(`\u2717 ${externalTool.name} failed: ${errorMsg}`);
4150
+ if (wrappedStreamCallback) {
4151
+ wrappedStreamCallback(`\u274C **${externalTool.name} failed:**
4152
+ \`\`\`
4153
+ ${errorMsg}
4154
+ \`\`\`
4155
+
4156
+ `);
4157
+ if (attempts < MAX_TOOL_ATTEMPTS) {
4158
+ wrappedStreamCallback(`\u{1F527} **Retrying with adjusted parameters...**
4159
+
4160
+ `);
4161
+ }
4162
+ }
4163
+ throw new Error(`Tool execution failed: ${errorMsg}`);
4164
+ }
4165
+ }
4166
+ throw new Error(`Unknown tool: ${toolName}`);
4339
4167
  }
4340
- throw new Error(`Unknown tool: ${toolName}`);
4341
4168
  };
4342
4169
  const result = await LLM.streamWithTools(
4343
4170
  {
@@ -4354,8 +4181,8 @@ ${errorMsg}
4354
4181
  partial: wrappedStreamCallback
4355
4182
  // Pass the wrapped streaming callback to LLM
4356
4183
  },
4357
- 10
4358
- // max iterations: allows for 6 retries + final response + buffer
4184
+ 20
4185
+ // max iterations: allows for 6 query retries + 3 tool retries + final response + buffer
4359
4186
  );
4360
4187
  logger.info(`[${this.getProviderName()}] Text response stream completed`);
4361
4188
  const textResponse = fullStreamedText || result || "I apologize, but I was unable to generate a response.";
@@ -4410,24 +4237,22 @@ ${errorMsg}
4410
4237
  }
4411
4238
  let container_componet = null;
4412
4239
  if (matchedComponents.length > 0) {
4240
+ logger.info(`[${this.getProviderName()}] Created MultiComponentContainer: "${layoutTitle}" with ${matchedComponents.length} components and ${actions.length} actions`);
4241
+ logCollector?.info(`Created dashboard: "${layoutTitle}" with ${matchedComponents.length} components and ${actions.length} actions`);
4413
4242
  container_componet = {
4414
- id: `multi_container_${Date.now()}`,
4243
+ id: `container_${Date.now()}`,
4415
4244
  name: "MultiComponentContainer",
4416
4245
  type: "Container",
4417
4246
  description: layoutDescription,
4418
- category: "dynamic",
4419
- keywords: ["dashboard", "layout", "container"],
4420
4247
  props: {
4421
4248
  config: {
4422
- components: matchedComponents,
4423
4249
  title: layoutTitle,
4424
- description: layoutDescription
4250
+ description: layoutDescription,
4251
+ components: matchedComponents
4425
4252
  },
4426
4253
  actions
4427
4254
  }
4428
4255
  };
4429
- logger.info(`[${this.getProviderName()}] Created MultiComponentContainer: "${layoutTitle}" with ${matchedComponents.length} components and ${actions.length} actions`);
4430
- logCollector?.info(`Created dashboard: "${layoutTitle}" with ${matchedComponents.length} components and ${actions.length} actions`);
4431
4256
  }
4432
4257
  return {
4433
4258
  success: true,
@@ -4458,201 +4283,134 @@ ${errorMsg}
4458
4283
  }
4459
4284
  }
4460
4285
  /**
4461
- * Generate component response for user question
4462
- * This provides conversational component suggestions based on user question
4463
- * Supports component generation and matching
4286
+ * Main orchestration function with semantic search and multi-step classification
4287
+ * NEW FLOW (Recommended):
4288
+ * 1. Semantic search: Check previous conversations (>60% match)
4289
+ * - If match found → Adapt UI block parameters and return
4290
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
4291
+ * 3. Route appropriately based on category and response mode
4292
+ *
4293
+ * @param responseMode - 'component' for component generation (default), 'text' for text responses
4294
+ * @param streamCallback - Optional callback function to receive text chunks as they stream (only for text mode)
4295
+ * @param collections - Collection registry for executing database queries (required for text mode)
4296
+ * @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called (only for text mode)
4464
4297
  */
4465
- async generateComponentResponse(userPrompt, components, apiKey, logCollector, conversationHistory) {
4466
- const errors = [];
4298
+ async handleUserRequest(userPrompt, components, apiKey, logCollector, conversationHistory, responseMode = "text", streamCallback, collections, externalTools, userId) {
4299
+ const startTime = Date.now();
4300
+ logger.info(`[${this.getProviderName()}] handleUserRequest called with responseMode: ${responseMode}`);
4301
+ logCollector?.info(`Starting request processing with mode: ${responseMode}`);
4467
4302
  try {
4468
- logger.info(`[${this.getProviderName()}] Using component response mode`);
4469
- const classifyMsg = "Classifying user question...";
4470
- logCollector?.info(classifyMsg);
4471
- const classification = await this.classifyUserQuestion(userPrompt, apiKey, logCollector, conversationHistory);
4472
- const classInfo = `Question type: ${classification.questionType}, Visualizations: ${classification.visualizations.join(", ") || "None"}, Multiple components: ${classification.needsMultipleComponents}`;
4473
- logCollector?.info(classInfo);
4474
- if (classification.questionType === "analytical") {
4475
- if (classification.visualizations.length > 1) {
4476
- const multiMsg = `Matching ${classification.visualizations.length} components for types: ${classification.visualizations.join(", ")}`;
4477
- logCollector?.info(multiMsg);
4478
- const componentPromises = classification.visualizations.map((vizType) => {
4479
- logCollector?.info(`Matching component for type: ${vizType}`);
4480
- return this.generateAnalyticalComponent(
4481
- userPrompt,
4482
- components,
4483
- vizType,
4484
- apiKey,
4485
- logCollector,
4486
- conversationHistory
4487
- ).then((result) => ({ vizType, result }));
4488
- });
4489
- const settledResults = await Promise.allSettled(componentPromises);
4490
- const matchedComponents = [];
4491
- for (const settledResult of settledResults) {
4492
- if (settledResult.status === "fulfilled") {
4493
- const { vizType, result } = settledResult.value;
4494
- if (result.component) {
4495
- matchedComponents.push(result.component);
4496
- logCollector?.info(`Matched: ${result.component.name}`);
4497
- logger.info("Component : ", result.component.name, " props: ", result.component.props);
4498
- } else {
4499
- logCollector?.warn(`Failed to match component for type: ${vizType}`);
4500
- }
4501
- } else {
4502
- logCollector?.warn(`Error matching component: ${settledResult.reason?.message || "Unknown error"}`);
4503
- }
4504
- }
4505
- logger.debug(`[${this.getProviderName()}] Matched ${matchedComponents.length} components for multi-component container`);
4506
- if (matchedComponents.length === 0) {
4507
- return {
4508
- success: true,
4509
- data: {
4510
- component: null,
4511
- reasoning: "Failed to match any components for the requested visualization types",
4512
- method: "classification-multi-failed",
4513
- questionType: classification.questionType,
4514
- needsMultipleComponents: true,
4515
- propsModified: false,
4516
- queryModified: false
4517
- },
4518
- errors: []
4519
- };
4520
- }
4521
- logCollector?.info("Generating container metadata...");
4522
- const containerMetadata = await this.generateContainerMetadata(
4523
- userPrompt,
4524
- classification.visualizations,
4525
- apiKey,
4526
- logCollector,
4527
- conversationHistory
4528
- );
4529
- const containerComponent = {
4530
- id: `multi_container_${Date.now()}`,
4531
- name: "MultiComponentContainer",
4532
- type: "Container",
4533
- description: containerMetadata.description,
4534
- category: "dynamic",
4535
- keywords: ["multi", "container", "dashboard"],
4536
- props: {
4537
- config: {
4538
- components: matchedComponents,
4539
- layout: "grid",
4540
- spacing: 24,
4541
- title: containerMetadata.title,
4542
- description: containerMetadata.description
4543
- }
4544
- }
4545
- };
4546
- logCollector?.info(`Created multi-component container with ${matchedComponents.length} components: "${containerMetadata.title}"`);
4303
+ logger.info(`[${this.getProviderName()}] Step 1: Searching previous conversations...`);
4304
+ logCollector?.info("Step 1: Searching for similar previous conversations...");
4305
+ const conversationMatch = await conversation_search_default.searchConversations({
4306
+ userPrompt,
4307
+ collections,
4308
+ userId,
4309
+ similarityThreshold: 0.6
4310
+ // 60% threshold
4311
+ });
4312
+ logger.info("conversationMatch:", conversationMatch);
4313
+ if (conversationMatch) {
4314
+ logger.info(
4315
+ `[${this.getProviderName()}] \u2713 Found matching conversation with ${(conversationMatch.similarity * 100).toFixed(2)}% similarity`
4316
+ );
4317
+ logCollector?.info(
4318
+ `\u2713 Found similar conversation (${(conversationMatch.similarity * 100).toFixed(2)}% match)`
4319
+ );
4320
+ if (conversationMatch.similarity >= 0.99) {
4321
+ const elapsedTime2 = Date.now() - startTime;
4322
+ logger.info(`[${this.getProviderName()}] \u2713 100% match - returning UI block directly without adaptation`);
4323
+ logCollector?.info(`\u2713 Exact match (${(conversationMatch.similarity * 100).toFixed(2)}%) - returning cached result`);
4324
+ logCollector?.info(`Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4325
+ const component = conversationMatch.uiBlock?.generatedComponentMetadata || conversationMatch.uiBlock?.component;
4547
4326
  return {
4548
4327
  success: true,
4549
4328
  data: {
4550
- component: containerComponent,
4551
- reasoning: `Matched ${matchedComponents.length} components for visualization types: ${classification.visualizations.join(", ")}`,
4552
- method: "classification-multi-generated",
4553
- questionType: classification.questionType,
4554
- needsMultipleComponents: true,
4555
- propsModified: false,
4556
- queryModified: false
4329
+ component,
4330
+ reasoning: `Exact match from previous conversation (${(conversationMatch.similarity * 100).toFixed(2)}% similarity)`,
4331
+ method: `${this.getProviderName()}-semantic-match-exact`,
4332
+ semanticSimilarity: conversationMatch.similarity
4557
4333
  },
4558
4334
  errors: []
4559
4335
  };
4560
- } else if (classification.visualizations.length === 1) {
4561
- const vizType = classification.visualizations[0];
4562
- logCollector?.info(`Matching single component for type: ${vizType}`);
4563
- const result = await this.generateAnalyticalComponent(userPrompt, components, vizType, apiKey, logCollector, conversationHistory);
4336
+ }
4337
+ logCollector?.info(`Adapting parameters for similar question...`);
4338
+ const originalPrompt = conversationMatch.metadata?.userPrompt || "Previous question";
4339
+ const adaptResult = await this.adaptUIBlockParameters(
4340
+ userPrompt,
4341
+ originalPrompt,
4342
+ conversationMatch.uiBlock,
4343
+ apiKey,
4344
+ logCollector
4345
+ );
4346
+ if (adaptResult.success && adaptResult.adaptedComponent) {
4347
+ const elapsedTime2 = Date.now() - startTime;
4348
+ logger.info(`[${this.getProviderName()}] \u2713 Successfully adapted UI block parameters`);
4349
+ logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4350
+ logCollector?.info(`\u2713 UI block adapted successfully`);
4351
+ logCollector?.info(`Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4564
4352
  return {
4565
4353
  success: true,
4566
4354
  data: {
4567
- component: result.component,
4568
- reasoning: result.reasoning,
4569
- method: "classification-generated",
4570
- questionType: classification.questionType,
4571
- needsMultipleComponents: false,
4572
- propsModified: false,
4573
- queryModified: false
4355
+ component: adaptResult.adaptedComponent,
4356
+ reasoning: `Adapted from previous conversation: ${originalPrompt}`,
4357
+ method: `${this.getProviderName()}-semantic-match`,
4358
+ semanticSimilarity: conversationMatch.similarity,
4359
+ parametersChanged: adaptResult.parametersChanged
4574
4360
  },
4575
4361
  errors: []
4576
4362
  };
4577
4363
  } else {
4578
- logCollector?.info("No specific visualization type - matching from all components");
4579
- const result = await this.generateAnalyticalComponent(userPrompt, components, void 0, apiKey, logCollector, conversationHistory);
4580
- return {
4581
- success: true,
4582
- data: {
4583
- component: result.component,
4584
- reasoning: result.reasoning,
4585
- method: "classification-generated-auto",
4586
- questionType: classification.questionType,
4587
- needsMultipleComponents: false,
4588
- propsModified: false,
4589
- queryModified: false
4590
- },
4591
- errors: []
4592
- };
4364
+ logger.info(`[${this.getProviderName()}] Could not adapt matched conversation, continuing to category classification`);
4365
+ logCollector?.warn(`Could not adapt matched conversation: ${adaptResult.explanation}`);
4593
4366
  }
4594
- } else if (classification.questionType === "data_modification" || classification.questionType === "general") {
4595
- const matchMsg = "Using component matching for data modification...";
4596
- logCollector?.info(matchMsg);
4597
- const matchResult = await this.matchComponent(userPrompt, components, apiKey, logCollector, conversationHistory);
4598
- return {
4599
- success: true,
4600
- data: {
4601
- component: matchResult.component,
4602
- reasoning: matchResult.reasoning,
4603
- method: "classification-matched",
4604
- questionType: classification.questionType,
4605
- needsMultipleComponents: false,
4606
- propsModified: matchResult.propsModified,
4607
- queryModified: matchResult.queryModified
4608
- },
4609
- errors: []
4610
- };
4611
4367
  } else {
4612
- logCollector?.info("General question - no component needed");
4613
- return {
4614
- success: true,
4615
- data: {
4616
- component: null,
4617
- reasoning: "General question - no component needed",
4618
- method: "classification-general",
4619
- questionType: classification.questionType,
4620
- needsMultipleComponents: false,
4621
- propsModified: false,
4622
- queryModified: false
4623
- },
4624
- errors: []
4625
- };
4368
+ logger.info(`[${this.getProviderName()}] No matching previous conversations found, proceeding to category classification`);
4369
+ logCollector?.info("No similar previous conversations found. Proceeding to category classification...");
4370
+ }
4371
+ logger.info(`[${this.getProviderName()}] Step 2: Classifying question category...`);
4372
+ logCollector?.info("Step 2: Classifying question category...");
4373
+ const categoryClassification = await this.classifyQuestionCategory(
4374
+ userPrompt,
4375
+ apiKey,
4376
+ logCollector,
4377
+ conversationHistory,
4378
+ externalTools
4379
+ );
4380
+ logger.info(
4381
+ `[${this.getProviderName()}] Question classified as: ${categoryClassification.category} (confidence: ${categoryClassification.confidence}%)`
4382
+ );
4383
+ logCollector?.info(
4384
+ `Category: ${categoryClassification.category} | Confidence: ${categoryClassification.confidence}%`
4385
+ );
4386
+ let toolsToUse = [];
4387
+ if (categoryClassification.externalTools && categoryClassification.externalTools.length > 0) {
4388
+ logger.info(`[${this.getProviderName()}] Identified ${categoryClassification.externalTools.length} external tools needed`);
4389
+ logCollector?.info(`Identified external tools: ${categoryClassification.externalTools.map((t) => t.name || t.type).join(", ")}`);
4390
+ toolsToUse = categoryClassification.externalTools?.map((t) => ({
4391
+ id: t.type,
4392
+ name: t.name,
4393
+ description: t.description,
4394
+ params: t.parameters || {},
4395
+ fn: (() => {
4396
+ const realTool = externalTools?.find((tool) => tool.id === t.type);
4397
+ if (realTool) {
4398
+ logger.info(`[${this.getProviderName()}] Using real tool implementation for ${t.type}`);
4399
+ return realTool.fn;
4400
+ } else {
4401
+ logger.warn(`[${this.getProviderName()}] Tool ${t.type} not found in registered tools`);
4402
+ return async () => ({ success: false, message: `Tool ${t.name || t.type} not registered` });
4403
+ }
4404
+ })()
4405
+ })) || [];
4406
+ }
4407
+ if (categoryClassification.category === "data_analysis") {
4408
+ logger.info(`[${this.getProviderName()}] Routing to data analysis (SELECT operations)`);
4409
+ logCollector?.info("Routing to data analysis...");
4410
+ } else if (categoryClassification.category === "data_modification") {
4411
+ logger.info(`[${this.getProviderName()}] Routing to data modification (INSERT/UPDATE/DELETE operations)`);
4412
+ logCollector?.info("Routing to data modification...");
4626
4413
  }
4627
- } catch (error) {
4628
- const errorMsg = error instanceof Error ? error.message : String(error);
4629
- logger.error(`[${this.getProviderName()}] Error generating component response: ${errorMsg}`);
4630
- logger.debug(`[${this.getProviderName()}] Component response generation error details:`, error);
4631
- logCollector?.error(`Error generating component response: ${errorMsg}`);
4632
- errors.push(errorMsg);
4633
- return {
4634
- success: false,
4635
- errors,
4636
- data: void 0
4637
- };
4638
- }
4639
- }
4640
- /**
4641
- * Main orchestration function that classifies question and routes to appropriate handler
4642
- * This is the NEW recommended entry point for handling user requests
4643
- * Supports both component generation and text response modes
4644
- *
4645
- * @param responseMode - 'component' for component generation (default), 'text' for text responses
4646
- * @param streamCallback - Optional callback function to receive text chunks as they stream (only for text mode)
4647
- * @param collections - Collection registry for executing database queries (required for text mode)
4648
- * @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called (only for text mode)
4649
- */
4650
- async handleUserRequest(userPrompt, components, apiKey, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools) {
4651
- const startTime = Date.now();
4652
- logger.info(`[${this.getProviderName()}] handleUserRequest called with responseMode: ${responseMode}`);
4653
- if (responseMode === "text") {
4654
- logger.info(`[${this.getProviderName()}] Using text response mode`);
4655
- logCollector?.info("Generating text response...");
4656
4414
  const textResponse = await this.generateTextResponse(
4657
4415
  userPrompt,
4658
4416
  apiKey,
@@ -4661,40 +4419,29 @@ ${errorMsg}
4661
4419
  streamCallback,
4662
4420
  collections,
4663
4421
  components,
4664
- externalTools
4422
+ toolsToUse
4665
4423
  );
4666
- if (!textResponse.success) {
4667
- const elapsedTime3 = Date.now() - startTime;
4668
- logger.error(`[${this.getProviderName()}] Text response generation failed`);
4669
- logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime3}ms (${(elapsedTime3 / 1e3).toFixed(2)}s)`);
4670
- logCollector?.info(`Total time taken: ${elapsedTime3}ms (${(elapsedTime3 / 1e3).toFixed(2)}s)`);
4671
- return textResponse;
4672
- }
4673
- const elapsedTime2 = Date.now() - startTime;
4674
- logger.info(`[${this.getProviderName()}] Text response generated successfully`);
4675
- logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4676
- logCollector?.info(`Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4424
+ const elapsedTime = Date.now() - startTime;
4425
+ logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4426
+ logCollector?.info(`Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4677
4427
  return textResponse;
4428
+ } catch (error) {
4429
+ const errorMsg = error instanceof Error ? error.message : String(error);
4430
+ logger.error(`[${this.getProviderName()}] Error in handleUserRequest: ${errorMsg}`);
4431
+ logger.debug(`[${this.getProviderName()}] Error details:`, error);
4432
+ logCollector?.error(`Error processing request: ${errorMsg}`);
4433
+ const elapsedTime = Date.now() - startTime;
4434
+ logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4435
+ logCollector?.info(`Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4436
+ return {
4437
+ success: false,
4438
+ errors: [errorMsg],
4439
+ data: {
4440
+ text: "I apologize, but I encountered an error processing your request. Please try again.",
4441
+ method: `${this.getProviderName()}-orchestration-error`
4442
+ }
4443
+ };
4678
4444
  }
4679
- const componentResponse = await this.generateComponentResponse(
4680
- userPrompt,
4681
- components,
4682
- apiKey,
4683
- logCollector,
4684
- conversationHistory
4685
- );
4686
- if (!componentResponse.success) {
4687
- const elapsedTime2 = Date.now() - startTime;
4688
- logger.error(`[${this.getProviderName()}] Component response generation failed`);
4689
- logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4690
- logCollector?.info(`Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4691
- return componentResponse;
4692
- }
4693
- const elapsedTime = Date.now() - startTime;
4694
- logger.info(`[${this.getProviderName()}] Component response generated successfully`);
4695
- logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4696
- logCollector?.info(`Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4697
- return componentResponse;
4698
4445
  }
4699
4446
  /**
4700
4447
  * Generate next questions that the user might ask based on the original prompt and generated component
@@ -4807,7 +4554,7 @@ function getLLMProviders() {
4807
4554
  return DEFAULT_PROVIDERS;
4808
4555
  }
4809
4556
  }
4810
- var useAnthropicMethod = async (prompt, components, apiKey, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools) => {
4557
+ var useAnthropicMethod = async (prompt, components, apiKey, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools, userId) => {
4811
4558
  logger.debug("[useAnthropicMethod] Initializing Anthropic Claude matching method");
4812
4559
  logger.debug(`[useAnthropicMethod] Response mode: ${responseMode}`);
4813
4560
  const msg = `Using Anthropic Claude ${responseMode === "text" ? "text response" : "matching"} method...`;
@@ -4819,11 +4566,11 @@ var useAnthropicMethod = async (prompt, components, apiKey, logCollector, conver
4819
4566
  return { success: false, errors: [emptyMsg] };
4820
4567
  }
4821
4568
  logger.debug(`[useAnthropicMethod] Processing with ${components.length} components`);
4822
- const matchResult = await anthropicLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools);
4569
+ const matchResult = await anthropicLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools, userId);
4823
4570
  logger.info(`[useAnthropicMethod] Successfully generated ${responseMode} using Anthropic`);
4824
4571
  return matchResult;
4825
4572
  };
4826
- var useGroqMethod = async (prompt, components, apiKey, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools) => {
4573
+ var useGroqMethod = async (prompt, components, apiKey, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools, userId) => {
4827
4574
  logger.debug("[useGroqMethod] Initializing Groq LLM matching method");
4828
4575
  logger.debug(`[useGroqMethod] Response mode: ${responseMode}`);
4829
4576
  const msg = `Using Groq LLM ${responseMode === "text" ? "text response" : "matching"} method...`;
@@ -4836,14 +4583,14 @@ var useGroqMethod = async (prompt, components, apiKey, logCollector, conversatio
4836
4583
  return { success: false, errors: [emptyMsg] };
4837
4584
  }
4838
4585
  logger.debug(`[useGroqMethod] Processing with ${components.length} components`);
4839
- const matchResult = await groqLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools);
4586
+ const matchResult = await groqLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools, userId);
4840
4587
  logger.info(`[useGroqMethod] Successfully generated ${responseMode} using Groq`);
4841
4588
  return matchResult;
4842
4589
  };
4843
4590
  var getUserResponseFromCache = async (prompt) => {
4844
4591
  return false;
4845
4592
  };
4846
- var get_user_response = async (prompt, components, anthropicApiKey, groqApiKey, llmProviders, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools) => {
4593
+ var get_user_response = async (prompt, components, anthropicApiKey, groqApiKey, llmProviders, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools, userId) => {
4847
4594
  logger.debug(`[get_user_response] Starting user response generation for prompt: "${prompt.substring(0, 50)}..."`);
4848
4595
  logger.debug(`[get_user_response] Response mode: ${responseMode}`);
4849
4596
  logger.debug("[get_user_response] Checking cache for existing response");
@@ -4876,9 +4623,9 @@ var get_user_response = async (prompt, components, anthropicApiKey, groqApiKey,
4876
4623
  logCollector?.info(attemptMsg);
4877
4624
  let result;
4878
4625
  if (provider === "anthropic") {
4879
- result = await useAnthropicMethod(prompt, components, anthropicApiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools);
4626
+ result = await useAnthropicMethod(prompt, components, anthropicApiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools, userId);
4880
4627
  } else if (provider === "groq") {
4881
- result = await useGroqMethod(prompt, components, groqApiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools);
4628
+ result = await useGroqMethod(prompt, components, groqApiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools, userId);
4882
4629
  } else {
4883
4630
  logger.warn(`[get_user_response] Unknown provider: ${provider} - skipping`);
4884
4631
  errors.push(`Unknown provider: ${provider}`);
@@ -5095,6 +4842,123 @@ var UILogCollector = class {
5095
4842
  }
5096
4843
  };
5097
4844
 
4845
+ // src/utils/conversation-saver.ts
4846
+ function transformUIBlockForDB(uiblock, userPrompt, uiBlockId) {
4847
+ const component = uiblock?.generatedComponentMetadata && Object.keys(uiblock.generatedComponentMetadata).length > 0 ? uiblock.generatedComponentMetadata : null;
4848
+ return {
4849
+ id: uiBlockId || uiblock?.id || "",
4850
+ component,
4851
+ analysis: uiblock?.textResponse || null,
4852
+ user_prompt: userPrompt || uiblock?.userQuestion || ""
4853
+ };
4854
+ }
4855
+ async function saveConversation(params) {
4856
+ const { userId, userPrompt, uiblock, uiBlockId, threadId, collections } = params;
4857
+ if (!userId) {
4858
+ logger.warn("[CONVERSATION_SAVER] Skipping save: userId not provided");
4859
+ return {
4860
+ success: false,
4861
+ error: "userId is required"
4862
+ };
4863
+ }
4864
+ if (!userPrompt) {
4865
+ logger.warn("[CONVERSATION_SAVER] Skipping save: userPrompt not provided");
4866
+ return {
4867
+ success: false,
4868
+ error: "userPrompt is required"
4869
+ };
4870
+ }
4871
+ if (!uiblock) {
4872
+ logger.warn("[CONVERSATION_SAVER] Skipping save: uiblock not provided");
4873
+ return {
4874
+ success: false,
4875
+ error: "uiblock is required"
4876
+ };
4877
+ }
4878
+ if (!threadId) {
4879
+ logger.warn("[CONVERSATION_SAVER] Skipping save: threadId not provided");
4880
+ return {
4881
+ success: false,
4882
+ error: "threadId is required"
4883
+ };
4884
+ }
4885
+ if (!uiBlockId) {
4886
+ logger.warn("[CONVERSATION_SAVER] Skipping save: uiBlockId not provided");
4887
+ return {
4888
+ success: false,
4889
+ error: "uiBlockId is required"
4890
+ };
4891
+ }
4892
+ if (!collections?.["user-conversations"]?.["create"]) {
4893
+ logger.debug('[CONVERSATION_SAVER] Collection "user-conversations.create" not available, skipping save');
4894
+ return {
4895
+ success: false,
4896
+ error: "user-conversations.create collection not available"
4897
+ };
4898
+ }
4899
+ try {
4900
+ logger.info(`[CONVERSATION_SAVER] Saving conversation for userId: ${userId}, uiBlockId: ${uiBlockId}, threadId: ${threadId}`);
4901
+ const userIdNumber = Number(userId);
4902
+ if (isNaN(userIdNumber)) {
4903
+ logger.warn(`[CONVERSATION_SAVER] Invalid userId: ${userId} (not a valid number)`);
4904
+ return {
4905
+ success: false,
4906
+ error: `Invalid userId: ${userId} (not a valid number)`
4907
+ };
4908
+ }
4909
+ const dbUIBlock = transformUIBlockForDB(uiblock, userPrompt, uiBlockId);
4910
+ logger.debug(`[CONVERSATION_SAVER] Transformed UIBlock for DB: ${JSON.stringify(dbUIBlock)}`);
4911
+ const saveResult = await collections["user-conversations"]["create"]({
4912
+ userId: userIdNumber,
4913
+ userPrompt,
4914
+ uiblock: dbUIBlock,
4915
+ threadId
4916
+ });
4917
+ if (!saveResult?.success) {
4918
+ logger.warn(`[CONVERSATION_SAVER] Failed to save conversation to PostgreSQL: ${saveResult?.message || "Unknown error"}`);
4919
+ return {
4920
+ success: false,
4921
+ error: saveResult?.message || "Unknown error from backend"
4922
+ };
4923
+ }
4924
+ logger.info(`[CONVERSATION_SAVER] Successfully saved conversation to PostgreSQL, id: ${saveResult.data?.id}`);
4925
+ if (collections?.["conversation-history"]?.["embed"]) {
4926
+ try {
4927
+ logger.info("[CONVERSATION_SAVER] Creating embedding for semantic search...");
4928
+ const embedResult = await collections["conversation-history"]["embed"]({
4929
+ uiBlockId,
4930
+ userPrompt,
4931
+ uiBlock: dbUIBlock,
4932
+ // Use the transformed UIBlock
4933
+ userId: userIdNumber
4934
+ });
4935
+ if (embedResult?.success) {
4936
+ logger.info("[CONVERSATION_SAVER] Successfully created embedding");
4937
+ } else {
4938
+ logger.warn("[CONVERSATION_SAVER] Failed to create embedding:", embedResult?.error || "Unknown error");
4939
+ }
4940
+ } catch (embedError) {
4941
+ const embedErrorMsg = embedError instanceof Error ? embedError.message : String(embedError);
4942
+ logger.warn("[CONVERSATION_SAVER] Error creating embedding:", embedErrorMsg);
4943
+ }
4944
+ } else {
4945
+ logger.debug("[CONVERSATION_SAVER] Embedding collection not available, skipping ChromaDB storage");
4946
+ }
4947
+ return {
4948
+ success: true,
4949
+ conversationId: saveResult.data?.id,
4950
+ message: "Conversation saved successfully"
4951
+ };
4952
+ } catch (error) {
4953
+ const errorMessage = error instanceof Error ? error.message : String(error);
4954
+ logger.error("[CONVERSATION_SAVER] Error saving conversation:", errorMessage);
4955
+ return {
4956
+ success: false,
4957
+ error: errorMessage
4958
+ };
4959
+ }
4960
+ }
4961
+
5098
4962
  // src/config/context.ts
5099
4963
  var CONTEXT_CONFIG = {
5100
4964
  /**
@@ -5106,7 +4970,7 @@ var CONTEXT_CONFIG = {
5106
4970
  };
5107
4971
 
5108
4972
  // src/handlers/user-prompt-request.ts
5109
- var get_user_request = async (data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools) => {
4973
+ var get_user_request = async (data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools, userId) => {
5110
4974
  const errors = [];
5111
4975
  logger.debug("[USER_PROMPT_REQ] Parsing incoming message data");
5112
4976
  const parseResult = UserPromptRequestMessageSchema.safeParse(data);
@@ -5187,7 +5051,8 @@ var get_user_request = async (data, components, sendMessage, anthropicApiKey, gr
5187
5051
  responseMode,
5188
5052
  streamCallback,
5189
5053
  collections,
5190
- externalTools
5054
+ externalTools,
5055
+ userId
5191
5056
  );
5192
5057
  logCollector.info("User prompt request completed");
5193
5058
  const uiBlockId = existingUiBlockId;
@@ -5238,6 +5103,34 @@ var get_user_request = async (data, components, sendMessage, anthropicApiKey, gr
5238
5103
  }
5239
5104
  thread.addUIBlock(uiBlock);
5240
5105
  logger.info(`Created UIBlock: ${uiBlockId} in Thread: ${threadId}`);
5106
+ if (userId) {
5107
+ const responseMethod = userResponse.data?.method || "";
5108
+ const semanticSimilarity = userResponse.data?.semanticSimilarity || 0;
5109
+ const isExactMatch = responseMethod.includes("semantic-match") && semanticSimilarity >= 0.99;
5110
+ if (isExactMatch) {
5111
+ logger.info(
5112
+ `Skipping conversation save - response from exact semantic match (${(semanticSimilarity * 100).toFixed(2)}% similarity)`
5113
+ );
5114
+ logCollector.info(
5115
+ `Using exact cached result (${(semanticSimilarity * 100).toFixed(2)}% match) - not saving duplicate conversation`
5116
+ );
5117
+ } else {
5118
+ const uiBlockData = uiBlock.toJSON();
5119
+ const saveResult = await saveConversation({
5120
+ userId,
5121
+ userPrompt: prompt,
5122
+ uiblock: uiBlockData,
5123
+ uiBlockId,
5124
+ threadId,
5125
+ collections
5126
+ });
5127
+ if (saveResult.success) {
5128
+ logger.info(`Conversation saved with ID: ${saveResult.conversationId}`);
5129
+ } else {
5130
+ logger.warn(`Failed to save conversation: ${saveResult.error}`);
5131
+ }
5132
+ }
5133
+ }
5241
5134
  return {
5242
5135
  success: userResponse.success,
5243
5136
  data: userResponse.data,
@@ -5248,8 +5141,8 @@ var get_user_request = async (data, components, sendMessage, anthropicApiKey, gr
5248
5141
  wsId
5249
5142
  };
5250
5143
  };
5251
- async function handleUserPromptRequest(data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools) {
5252
- const response = await get_user_request(data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools);
5144
+ async function handleUserPromptRequest(data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools, userId) {
5145
+ const response = await get_user_request(data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools, userId);
5253
5146
  sendDataResponse4(
5254
5147
  response.id || data.id,
5255
5148
  {
@@ -6336,13 +6229,15 @@ async function handleBookmarksRequest(data, collections, sendMessage) {
6336
6229
  const { id, payload, from } = request;
6337
6230
  const { operation, data: requestData } = payload;
6338
6231
  const bookmarkId = requestData?.id;
6232
+ const userId = requestData?.userId;
6233
+ const threadId = requestData?.threadId;
6339
6234
  const uiblock = requestData?.uiblock;
6340
6235
  switch (operation) {
6341
6236
  case "create":
6342
- await handleCreate4(id, uiblock, executeCollection, sendMessage, from.id);
6237
+ await handleCreate4(id, userId, threadId, uiblock, executeCollection, sendMessage, from.id);
6343
6238
  break;
6344
6239
  case "update":
6345
- await handleUpdate4(id, bookmarkId, uiblock, executeCollection, sendMessage, from.id);
6240
+ await handleUpdate4(id, bookmarkId, threadId, uiblock, executeCollection, sendMessage, from.id);
6346
6241
  break;
6347
6242
  case "delete":
6348
6243
  await handleDelete4(id, bookmarkId, executeCollection, sendMessage, from.id);
@@ -6353,6 +6248,12 @@ async function handleBookmarksRequest(data, collections, sendMessage) {
6353
6248
  case "getOne":
6354
6249
  await handleGetOne4(id, bookmarkId, executeCollection, sendMessage, from.id);
6355
6250
  break;
6251
+ case "getByUser":
6252
+ await handleGetByUser(id, userId, threadId, executeCollection, sendMessage, from.id);
6253
+ break;
6254
+ case "getByThread":
6255
+ await handleGetByThread(id, threadId, executeCollection, sendMessage, from.id);
6256
+ break;
6356
6257
  default:
6357
6258
  sendResponse6(id, {
6358
6259
  success: false,
@@ -6367,7 +6268,14 @@ async function handleBookmarksRequest(data, collections, sendMessage) {
6367
6268
  }, sendMessage);
6368
6269
  }
6369
6270
  }
6370
- async function handleCreate4(id, uiblock, executeCollection, sendMessage, clientId) {
6271
+ async function handleCreate4(id, userId, threadId, uiblock, executeCollection, sendMessage, clientId) {
6272
+ if (!userId) {
6273
+ sendResponse6(id, {
6274
+ success: false,
6275
+ error: "userId is required"
6276
+ }, sendMessage, clientId);
6277
+ return;
6278
+ }
6371
6279
  if (!uiblock) {
6372
6280
  sendResponse6(id, {
6373
6281
  success: false,
@@ -6376,7 +6284,7 @@ async function handleCreate4(id, uiblock, executeCollection, sendMessage, client
6376
6284
  return;
6377
6285
  }
6378
6286
  try {
6379
- const result = await executeCollection("bookmarks", "create", { uiblock });
6287
+ const result = await executeCollection("bookmarks", "create", { userId, threadId, uiblock });
6380
6288
  sendResponse6(id, {
6381
6289
  success: true,
6382
6290
  data: result.data,
@@ -6390,7 +6298,7 @@ async function handleCreate4(id, uiblock, executeCollection, sendMessage, client
6390
6298
  }, sendMessage, clientId);
6391
6299
  }
6392
6300
  }
6393
- async function handleUpdate4(id, bookmarkId, uiblock, executeCollection, sendMessage, clientId) {
6301
+ async function handleUpdate4(id, bookmarkId, threadId, uiblock, executeCollection, sendMessage, clientId) {
6394
6302
  if (!bookmarkId) {
6395
6303
  sendResponse6(id, {
6396
6304
  success: false,
@@ -6406,7 +6314,7 @@ async function handleUpdate4(id, bookmarkId, uiblock, executeCollection, sendMes
6406
6314
  return;
6407
6315
  }
6408
6316
  try {
6409
- const result = await executeCollection("bookmarks", "update", { id: bookmarkId, uiblock });
6317
+ const result = await executeCollection("bookmarks", "update", { id: bookmarkId, threadId, uiblock });
6410
6318
  sendResponse6(id, {
6411
6319
  success: true,
6412
6320
  data: result.data,
@@ -6483,6 +6391,54 @@ async function handleGetOne4(id, bookmarkId, executeCollection, sendMessage, cli
6483
6391
  }, sendMessage, clientId);
6484
6392
  }
6485
6393
  }
6394
+ async function handleGetByUser(id, userId, threadId, executeCollection, sendMessage, clientId) {
6395
+ if (!userId) {
6396
+ sendResponse6(id, {
6397
+ success: false,
6398
+ error: "userId is required"
6399
+ }, sendMessage, clientId);
6400
+ return;
6401
+ }
6402
+ try {
6403
+ const result = await executeCollection("bookmarks", "getByUser", { userId, threadId });
6404
+ sendResponse6(id, {
6405
+ success: true,
6406
+ data: result.data,
6407
+ count: result.count,
6408
+ message: `Retrieved ${result.count} bookmarks for user ${userId}`
6409
+ }, sendMessage, clientId);
6410
+ logger.info(`Retrieved bookmarks for user ${userId} (count: ${result.count})`);
6411
+ } catch (error) {
6412
+ sendResponse6(id, {
6413
+ success: false,
6414
+ error: error instanceof Error ? error.message : "Failed to get bookmarks by user"
6415
+ }, sendMessage, clientId);
6416
+ }
6417
+ }
6418
+ async function handleGetByThread(id, threadId, executeCollection, sendMessage, clientId) {
6419
+ if (!threadId) {
6420
+ sendResponse6(id, {
6421
+ success: false,
6422
+ error: "threadId is required"
6423
+ }, sendMessage, clientId);
6424
+ return;
6425
+ }
6426
+ try {
6427
+ const result = await executeCollection("bookmarks", "getByThread", { threadId });
6428
+ sendResponse6(id, {
6429
+ success: true,
6430
+ data: result.data,
6431
+ count: result.count,
6432
+ message: `Retrieved ${result.count} bookmarks for thread ${threadId}`
6433
+ }, sendMessage, clientId);
6434
+ logger.info(`Retrieved bookmarks for thread ${threadId} (count: ${result.count})`);
6435
+ } catch (error) {
6436
+ sendResponse6(id, {
6437
+ success: false,
6438
+ error: error instanceof Error ? error.message : "Failed to get bookmarks by thread"
6439
+ }, sendMessage, clientId);
6440
+ }
6441
+ }
6486
6442
  function sendResponse6(id, res, sendMessage, clientId) {
6487
6443
  const response = {
6488
6444
  id: id || "unknown",
@@ -7469,17 +7425,17 @@ var SuperatomSDK = class {
7469
7425
  });
7470
7426
  break;
7471
7427
  case "AUTH_LOGIN_REQ":
7472
- handleAuthLoginRequest(parsed, (msg) => this.send(msg)).catch((error) => {
7428
+ handleAuthLoginRequest(parsed, this.collections, (msg) => this.send(msg)).catch((error) => {
7473
7429
  logger.error("Failed to handle auth login request:", error);
7474
7430
  });
7475
7431
  break;
7476
7432
  case "AUTH_VERIFY_REQ":
7477
- handleAuthVerifyRequest(parsed, (msg) => this.send(msg)).catch((error) => {
7433
+ handleAuthVerifyRequest(parsed, this.collections, (msg) => this.send(msg)).catch((error) => {
7478
7434
  logger.error("Failed to handle auth verify request:", error);
7479
7435
  });
7480
7436
  break;
7481
7437
  case "USER_PROMPT_REQ":
7482
- handleUserPromptRequest(parsed, this.components, (msg) => this.send(msg), this.anthropicApiKey, this.groqApiKey, this.llmProviders, this.collections, this.tools).catch((error) => {
7438
+ handleUserPromptRequest(parsed, this.components, (msg) => this.send(msg), this.anthropicApiKey, this.groqApiKey, this.llmProviders, this.collections, this.tools, this.userId).catch((error) => {
7483
7439
  logger.error("Failed to handle user prompt request:", error);
7484
7440
  });
7485
7441
  break;