@superatomai/sdk-node 0.0.13 → 0.0.14

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.mjs CHANGED
@@ -522,6 +522,25 @@ var ReportsRequestMessageSchema = z3.object({
522
522
  type: z3.literal("REPORTS"),
523
523
  payload: ReportsRequestPayloadSchema
524
524
  });
525
+ var UIBlockSchema = z3.object({
526
+ id: z3.string().optional(),
527
+ userQuestion: z3.string().optional(),
528
+ text: z3.string().optional(),
529
+ textResponse: z3.string().optional(),
530
+ component: ComponentSchema.optional(),
531
+ // Legacy field
532
+ generatedComponentMetadata: ComponentSchema.optional(),
533
+ // Actual field used by UIBlock class
534
+ componentData: z3.record(z3.any()).optional(),
535
+ actions: z3.array(z3.any()).optional(),
536
+ isFetchingActions: z3.boolean().optional(),
537
+ createdAt: z3.string().optional(),
538
+ metadata: z3.object({
539
+ timestamp: z3.number().optional(),
540
+ userPrompt: z3.string().optional(),
541
+ similarity: z3.number().optional()
542
+ }).optional()
543
+ });
525
544
  var BookmarkDataSchema = z3.object({
526
545
  id: z3.number().optional(),
527
546
  uiblock: z3.any(),
@@ -1789,489 +1808,126 @@ import path3 from "path";
1789
1808
 
1790
1809
  // src/userResponse/prompts.ts
1791
1810
  var PROMPTS = {
1792
- "classify": {
1793
- system: `You are an expert AI that classifies user questions about data and determines the appropriate visualizations needed.
1794
-
1795
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
1796
-
1797
- ## Previous Conversation
1798
- {{CONVERSATION_HISTORY}}
1799
-
1800
- **Note:** If there is previous conversation history, use it to understand context. For example:
1801
- - If user previously asked about "sales" and now asks "show me trends", understand it refers to sales trends
1802
- - If user asked for "revenue by region" and now says "make it a pie chart", understand they want to modify the previous visualization
1803
- - Use the history to resolve ambiguous references like "that", "it", "them", "the data"
1804
-
1805
- Your task is to analyze the user's question and determine:
1806
-
1807
- 1. **Question Type:**
1808
- - "analytical": Questions asking to VIEW, ANALYZE, or VISUALIZE data
1809
-
1810
- - "data_modification": Questions asking to CREATE, UPDATE, DELETE, or MODIFY data
1811
-
1812
- - "general": General questions, greetings, or requests not related to data
1813
-
1814
- 2. **Required Visualizations** (only for analytical questions):
1815
- Determine which visualization type(s) would BEST answer the user's question:
1816
-
1817
- - **KPICard**: Single metric, total, count, average, percentage, or summary number
1818
-
1819
- - **LineChart**: Trends over time, time series, growth/decline patterns
1820
-
1821
-
1822
- - **BarChart**: Comparing categories, rankings, distributions across groups
1823
-
1824
-
1825
- - **PieChart**: Proportions, percentages, composition, market share
1826
-
1827
-
1828
- - **DataTable**: Detailed lists, multiple attributes, when user needs to see records
1829
-
1830
-
1831
- 3. **Multiple Visualizations:**
1832
- User may need MULTIPLE visualizations together:
1833
-
1834
- Common combinations:
1835
- - KPICard + LineChart
1836
- - KPICard + BarChart
1837
- - KPICard + DataTable
1838
- - BarChart + PieChart:
1839
- - LineChart + DataTable
1840
- Set needsMultipleComponents to true if user needs multiple views of the data.
1811
+ "text-response": {
1812
+ 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.
1841
1813
 
1842
- **Important Guidelines:**
1843
- - If user explicitly mentions a chart type RESPECT that preference
1844
- - If question is vague or needs both summary and detail, suggest KPICard + DataTable
1845
- - Only return visualizations for "analytical" questions
1846
- - For "data_modification" or "general", return empty array for visualizations
1814
+ ## Your Task
1847
1815
 
1848
- **Output Format:**
1849
- {
1850
- "questionType": "analytical" | "data_modification" | "general",
1851
- "visualizations": ["KPICard", "LineChart", ...], // Empty array if not analytical
1852
- "reasoning": "Explanation of classification and visualization choices",
1853
- "needsMultipleComponents": boolean
1854
- }
1855
- `,
1856
- user: `{{USER_PROMPT}}
1857
- `
1858
- },
1859
- "match-component": {
1860
- system: `You are an expert AI assistant specialized in matching user requests to the most appropriate data visualization components.
1816
+ Analyze the user's question and provide a helpful text response. Your response should:
1861
1817
 
1862
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
1818
+ 1. **Be Clear and Concise**: Provide direct answers without unnecessary verbosity
1819
+ 2. **Be Contextual**: Use conversation history to understand what the user is asking about
1820
+ 3. **Be Accurate**: Provide factually correct information based on the context
1821
+ 4. **Be Helpful**: Offer additional relevant information or suggestions when appropriate
1863
1822
 
1864
- ## Previous Conversation
1865
- {{CONVERSATION_HISTORY}}
1823
+ ## Available Tools
1866
1824
 
1867
- **Context Instructions:**
1868
- - If there is conversation history, use it to understand what the user is referring to
1869
- - When user says "show that as a chart" or "change it", they are referring to a previous component
1870
- - If user asks to "modify" or "update" something, match to the component they previously saw
1871
- - Use context to resolve ambiguous requests like "show trends for that" or "make it interactive"
1872
-
1873
- Your task is to analyze the user's natural language request and find the BEST matching component from the available list.
1874
-
1875
- Available Components:
1876
- {{COMPONENTS_TEXT}}
1877
-
1878
- **Matching Guidelines:**
1879
-
1880
- 1. **Understand User Intent:**
1881
- - What type of data visualization do they need? (KPI/metric, chart, table, etc.)
1882
- - What metric or data are they asking about? (revenue, orders, customers, etc.)
1883
- - Are they asking for a summary (KPI), trend (line chart), distribution (bar/pie), or detailed list (table)?
1884
- - Do they want to compare categories, see trends over time, or show proportions?
1885
-
1886
- 2. **Component Type Matching:**
1887
- - KPICard: Single metric/number (total, average, count, percentage, rate)
1888
- - LineChart: Trends over time, time series data
1889
- - BarChart: Comparing categories, distributions, rankings
1890
- - PieChart/DonutChart: Proportions, percentages, market share
1891
- - DataTable: Detailed lists, rankings with multiple attributes
1892
-
1893
- 3. **Keyword & Semantic Matching:**
1894
- - Match user query terms with component keywords
1895
- - Consider synonyms (e.g., "sales" = "revenue", "items" = "products")
1896
- - Look for category matches (financial, orders, customers, products, suppliers, logistics, geographic, operations)
1897
-
1898
- 4. **Scoring Criteria:**
1899
- - Exact keyword matches: High priority
1900
- - Component type alignment: High priority
1901
- - Category alignment: Medium priority
1902
- - Semantic similarity: Medium priority
1903
- - Specificity: Prefer more specific components over generic ones
1904
-
1905
- **Output Requirements:**
1906
-
1907
- Respond with a JSON object containing:
1908
- - componentIndex: the 1-based index of the BEST matching component (or null if confidence < 50%)
1909
- - componentId: the ID of the matched component
1910
- - reasoning: detailed explanation of why this component was chosen
1911
- - confidence: confidence score 0-100 (100 = perfect match)
1912
- - alternativeMatches: array of up to 2 alternative component indices with scores (optional)
1913
-
1914
- Example response:
1915
- {
1916
- "componentIndex": 5,
1917
- "componentId": "total_revenue_kpi",
1918
- "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'.",
1919
- "confidence": 95,
1920
- "alternativeMatches": [
1921
- {"index": 3, "id": "monthly_revenue_kpi", "score": 75, "reason": "Could show monthly revenue if time period was intended"},
1922
- {"index": 8, "id": "revenue_trend_chart", "score": 60, "reason": "Could show revenue trend if historical view was intended"}
1923
- ]
1924
- }
1825
+ The following external tools are available for this request (if applicable):
1925
1826
 
1926
- **Important:**
1927
- - Only return componentIndex if confidence >= 50%
1928
- - Return null if no reasonable match exists
1929
- - Prefer components that exactly match the user's metric over generic ones
1930
- - Consider the full context of the request, not just individual words`,
1931
- user: `Current user request: {{USER_PROMPT}}
1827
+ {{AVAILABLE_EXTERNAL_TOOLS}}
1932
1828
 
1933
- Find the best matching component considering the conversation history above. Explain your reasoning with a confidence score. Return ONLY valid JSON.`
1934
- },
1935
- "modify-props": {
1936
- system: `You are an AI assistant that validates and modifies component props based on user requests.
1829
+ When a tool is needed to complete the user's request:
1830
+ 1. **Analyze the request** to determine which tool(s) are needed
1831
+ 2. **Extract parameters** from the user's question that the tool requires
1832
+ 3. **Execute the tool** by calling it with the extracted parameters
1833
+ 4. **Present the results** in your response in a clear, user-friendly format
1834
+ 5. **Combine with other data** if the user's request requires both database queries and external tool results
1937
1835
 
1938
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
1836
+ ## Handling Data Questions
1939
1837
 
1940
- Given:
1941
- - A user's natural language request
1942
- - Component name: {{COMPONENT_NAME}}
1943
- - Component type: {{COMPONENT_TYPE}}
1944
- - Component description: {{COMPONENT_DESCRIPTION}}
1838
+ When the user asks about data
1945
1839
 
1946
- -
1947
- - Current component props with structure:
1948
- {
1949
- query?: string, // SQL query to fetch data
1950
- title?: string, // Component title
1951
- description?: string, // Component description
1952
- config?: { // Additional configuration
1953
- [key: string]: any
1954
- }
1955
- }
1840
+ 1. **Generate a SQL query** using the database schema provided above
1841
+ 2. **Use the execute_query tool** to run the query
1842
+ 3. **If the query fails**, analyze the error and generate a corrected query
1843
+ 4. **Format the results** in a clear, readable way for the user
1956
1844
 
1957
- Schema definition for the prop that must be passed to the component
1958
- -{{CURRENT_PROPS}}
1845
+ **Query Guidelines:**
1846
+ - Use correct table and column names from the schema
1847
+ - ALWAYS include a LIMIT clause with a MAXIMUM of 32 rows
1848
+ - Ensure valid SQL syntax
1849
+ - For time-based queries, use appropriate date functions
1850
+ - When using subqueries with scalar operators (=, <, >, etc.), add LIMIT 1 to prevent "more than one row" errors
1959
1851
 
1960
- Database Schema:
1852
+ ## Database Schema
1961
1853
  {{SCHEMA_DOC}}
1962
1854
 
1963
- ## Previous Conversation
1964
- {{CONVERSATION_HISTORY}}
1965
-
1966
- **Context Instructions:**
1967
- - Review the conversation history to understand the evolution of the component
1968
- - If user says "add filter for X", understand they want to modify the current query
1969
- - If user says "change to last month" or "filter by Y", apply modifications to existing query
1970
- - Previous questions can clarify what the user means by ambiguous requests like "change that filter"
1971
- - Use context to determine appropriate time ranges if user says "recent" or "latest"
1972
-
1973
- Your task is to intelligently modify the props based on the user's request:
1855
+ **Database Type: PostgreSQL**
1974
1856
 
1975
- 1. **Query Modification**:
1976
- - Modify SQL query if user requests different data, filters, time ranges, limits, or aggregations
1977
- - Use correct table and column names from the schema
1978
- - Ensure valid SQL syntax
1979
- - ALWAYS include a LIMIT clause (default: {{DEFAULT_LIMIT}} rows) to prevent large result sets
1980
- - Preserve the query structure that the component expects (e.g., column aliases)
1857
+ **CRITICAL PostgreSQL Query Rules:**
1981
1858
 
1982
- **CRITICAL - PostgreSQL Query Rules:**
1859
+ 1. **NO AGGREGATE FUNCTIONS IN WHERE CLAUSE** - This is a fundamental SQL error
1860
+ \u274C WRONG: \`WHERE COUNT(orders) > 0\`
1861
+ \u274C WRONG: \`WHERE SUM(price) > 100\`
1862
+ \u274C WRONG: \`WHERE AVG(rating) > 4.5\`
1863
+ \u274C WRONG: \`WHERE FLOOR(AVG(rating)) = 4\` (aggregate inside any function is still not allowed)
1864
+ \u274C WRONG: \`WHERE ROUND(SUM(price), 2) > 100\`
1983
1865
 
1984
- **NO AGGREGATE FUNCTIONS IN WHERE CLAUSE:**
1985
- \u274C WRONG: \`WHERE COUNT(orders) > 0\` or \`WHERE SUM(price) > 100\`
1986
1866
  \u2705 CORRECT: Use HAVING (with GROUP BY), EXISTS, or subquery
1867
+ \u2705 CORRECT: Move aggregate logic to HAVING: \`GROUP BY ... HAVING FLOOR(AVG(rating)) = 4\`
1868
+ \u2705 CORRECT: Use subquery for filtering: \`WHERE product_id IN (SELECT product_id FROM ... GROUP BY ... HAVING AVG(rating) >= 4)\`
1987
1869
 
1988
-
1989
- **WHERE vs HAVING:**
1870
+ 2. **WHERE vs HAVING**
1990
1871
  - WHERE filters rows BEFORE grouping (cannot use aggregates)
1991
1872
  - HAVING filters groups AFTER grouping (can use aggregates)
1992
1873
  - If using HAVING, you MUST have GROUP BY
1993
1874
 
1994
- **Subquery Rules:**
1995
- - When using a subquery with scalar comparison operators (=, <, >, <=, >=, <>), the subquery MUST return exactly ONE row
1996
- - ALWAYS add \`LIMIT 1\` to scalar subqueries to prevent "more than one row returned" errors
1997
- - Example: \`WHERE location_id = (SELECT store_id FROM orders ORDER BY total_amount DESC LIMIT 1)\`
1998
- - For multiple values, use \`IN\` instead: \`WHERE location_id IN (SELECT store_id FROM orders)\`
1999
- - Test your subqueries mentally: if they could return multiple rows, add LIMIT 1 or use IN
2000
-
2001
- 2. **Title Modification**:
2002
- - Update title to reflect the user's specific request
2003
- - Keep it concise and descriptive
2004
- - Match the tone of the original title
2005
-
2006
- 3. **Description Modification**:
2007
- - Update description to explain what data is shown
2008
- - Be specific about filters, time ranges, or groupings applied
2009
-
2010
- 4. **Config Modification** (based on component type):
2011
- - For KPICard: formatter, gradient, icon
2012
- - For Charts: colors, height, xKey, yKey, nameKey, valueKey
2013
- - For Tables: columns, pageSize, formatters
2014
-
2015
-
2016
- Respond with a JSON object:
2017
- {
2018
- "props": { /* modified props object with query, title, description, config */ },
2019
- "isModified": boolean,
2020
- "reasoning": "brief explanation of changes",
2021
- "modifications": ["list of specific changes made"]
2022
- }
2023
-
2024
- IMPORTANT:
2025
- - Return the COMPLETE props object, not just modified fields
2026
- - Preserve the structure expected by the component type
2027
- - Ensure query returns columns with expected aliases
2028
- - Keep config properties that aren't affected by the request`,
2029
- user: `{{USER_PROMPT}}`
2030
- },
2031
- "single-component": {
2032
- system: `You are an expert AI assistant specialized in matching user requests to the most appropriate component from a filtered list.
2033
-
2034
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2035
-
2036
-
2037
- ## Previous Conversation
2038
- {{CONVERSATION_HISTORY}}
2039
-
2040
- **Context Instructions:**
2041
- - If there is previous conversation history, use it to understand what the user is referring to
2042
- - When user says "show trends", "add filters", "change that", understand they may be building on previous queries
2043
- - Use previous component types and queries as context to inform your current matching
2044
-
2045
- ## Available Components (Type: {{COMPONENT_TYPE}})
2046
- The following components have been filtered by type {{COMPONENT_TYPE}}. Select the BEST matching one:
2047
-
2048
- {{COMPONENTS_LIST}}
2049
-
2050
- {{VISUALIZATION_CONSTRAINT}}
2051
-
2052
- **Select the BEST matching component** from the available {{COMPONENT_TYPE}} components listed above that would best answer the user's question.
2053
-
2054
- **Matching Guidelines:**
2055
- 1. **Semantic Matching:**
2056
- - Match based on component name, description, and keywords
2057
- - Consider what metrics/data the user is asking about
2058
- - Look for semantic similarity (e.g., "sales" matches "revenue", "orders" matches "purchases")
2059
-
2060
- 2. **Query Relevance:**
2061
- - Consider the component's existing query structure
2062
- - Does it query the right tables/columns for the user's question?
2063
- - Can it be modified to answer the user's specific question?
2064
-
2065
- 3. **Scoring Criteria:**
2066
- - Exact keyword matches in name/description: High priority
2067
- - Semantic similarity to user intent: High priority
2068
- - Appropriate aggregation/grouping: Medium priority
2069
- - Category alignment: Medium priority
2070
-
2071
- **Output Requirements:**
2072
-
2073
- Respond with a JSON object:
2074
- {
2075
- "componentId": "matched_component_id",
2076
- "componentIndex": 1, // 1-based index from the filtered list above
2077
- "reasoning": "Detailed explanation of why this component best matches the user's question",
2078
- "confidence": 85, // Confidence score 0-100
2079
- "canGenerate": true // false if no suitable component found (confidence < 50)
2080
- }
2081
-
2082
- **Important:**
2083
- - Only set canGenerate to true if confidence >= 50%
2084
- - If no component from the list matches well (all have low relevance), set canGenerate to false
2085
- - Consider the full context of the request and conversation history
2086
- - The component's props (query, title, description, config) will be modified later based on the user's specific request
2087
- - Focus on finding the component that is closest to what the user needs, even if it needs modification`,
2088
- user: `{{USER_PROMPT}}
2089
-
2090
- `
2091
- },
2092
- "mutli-component": {
2093
- system: `You are an expert data analyst AI that creates comprehensive multi-component analytical dashboards with aesthetically pleasing and balanced layouts.
2094
-
2095
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2096
-
2097
- Database Schema:
2098
- {{SCHEMA_DOC}}
2099
-
2100
- ## Previous Conversation
2101
- {{CONVERSATION_HISTORY}}
2102
-
2103
- **Context Instructions:**
2104
- - Review the conversation history to understand what the user has asked before
2105
- - If user is building on previous insights (e.g., "now show me X and Y"), use context to inform dashboard design
2106
- - Previous queries can help determine appropriate filters, date ranges, or categories to use
2107
- - If user asks for "comprehensive view" or "dashboard for X", include complementary components based on context
2108
-
2109
- Given a user's analytical question and the required visualization types, your task is to:
2110
-
2111
- 1. **Determine Container Metadata:**
2112
- - title: Clear, descriptive title for the entire dashboard (2-5 words)
2113
- - description: Brief explanation of what insights this dashboard provides (1-2 sentences)
2114
-
2115
- 2. **Generate Props for Each Component:**
2116
- For each visualization type requested, create tailored props:
2117
-
2118
- - **query**: SQL query specific to this visualization using the database schema
2119
- * Use correct table and column names
2120
- * **DO NOT USE TOP keyword - use LIMIT instead (e.g., LIMIT 20, not TOP 20)**
2121
- * ALWAYS include LIMIT clause ONCE at the end (default: {{DEFAULT_LIMIT}})
2122
- * For KPICard: Return single row with column alias "value"
2123
- * For Charts: Return appropriate columns (name/label and value, or x and y)
2124
- * For Table: Return relevant columns
2125
-
2126
- - **title**: Specific title for this component (2-4 words)
2127
-
2128
- - **description**: What this specific component shows (1 sentence)
2129
-
2130
- - **config**: Type-specific configuration
2131
- * KPICard: { gradient, formatter, icon }
2132
- * BarChart: { xKey, yKey, colors, height }
2133
- * LineChart: { xKey, yKeys, colors, height }
2134
- * PieChart: { nameKey, valueKey, colors, height }
2135
- * DataTable: { pageSize }
2136
-
2137
- 3. **CRITICAL: Component Hierarchy and Ordering:**
2138
- The ORDER of components in the array MUST follow this STRICT hierarchy for proper visual layout:
2139
-
2140
- **HIERARCHY RULES (MUST FOLLOW IN THIS ORDER):**
2141
- 1. KPICards - ALWAYS FIRST (top of dashboard for summary metrics)
2142
- 2. Charts/Graphs - AFTER KPICards (middle of dashboard for visualizations)
2143
- * BarChart, LineChart, PieChart, DonutChart
2144
- 3. DataTable - ALWAYS LAST (bottom of dashboard, full width for detailed data)
2145
-
2146
- **LAYOUT BEHAVIOR (Frontend enforces):**
2147
- - KPICards: Display in responsive grid (3 columns)
2148
- - Single Chart (if only 1 chart): Takes FULL WIDTH
2149
- - Multiple Charts (if 2+ charts): Display in 2-column grid
2150
- - DataTable (if present): Always spans FULL WIDTH at bottom
2151
-
2152
-
2153
- **ABSOLUTELY DO NOT deviate from this hierarchy. Always place:**
2154
- - KPICards first
2155
- - Charts/Graphs second
2156
- - DataTable last (if present)
2157
-
2158
- **Important Guidelines:**
2159
- - Each component should answer a DIFFERENT aspect of the user's question
2160
- - Queries should be complementary, not duplicated
2161
- - If user asks "Show total revenue and trend", generate:
2162
- * KPICard: Single total value (FIRST)
2163
- * LineChart: Revenue over time (SECOND)
2164
- - Ensure queries use valid columns from the schema
2165
- - Make titles descriptive and specific to what each component shows
2166
- - **Snowflake Syntax MUST be used:**
2167
- * Use LIMIT (not TOP)
2168
- * Use DATE_TRUNC, DATEDIFF (not DATEPART)
2169
- * Include LIMIT only ONCE per query at the end
2170
-
2171
- **Output Format:**
2172
- {
2173
- "containerTitle": "Dashboard Title",
2174
- "containerDescription": "Brief description of the dashboard insights",
2175
- "components": [
2176
- {
2177
- "componentType": "KPICard" | "BarChart" | "LineChart" | "PieChart" | "DataTable",
2178
- "query": "SQL query",
2179
- "title": "Component title",
2180
- "description": "Component description",
2181
- "config": { /* type-specific config */ }
2182
- },
2183
- ...
2184
- ],
2185
- "reasoning": "Explanation of the dashboard design and component ordering",
2186
- "canGenerate": boolean
2187
- }`,
2188
- user: `Current user question: {{USER_PROMPT}}
2189
-
2190
- Required visualization types: {{VISUALIZATION_TYPES}}
2191
-
2192
- 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.`
2193
- },
2194
- "container-metadata": {
2195
- system: `You are an expert AI assistant that generates titles and descriptions for multi-component dashboards.
2196
-
2197
- CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2198
-
2199
- ## Previous Conversation
2200
- {{CONVERSATION_HISTORY}}
2201
-
2202
- **Context Instructions:**
2203
- - If there is previous conversation history, use it to understand what the user is referring to
2204
- - Use context to create relevant titles and descriptions that align with the user's intent
2205
-
2206
- Your task is to generate a concise title and description for a multi-component dashboard that will contain the following visualization types:
2207
- {{VISUALIZATION_TYPES}}
2208
-
2209
- **Guidelines:**
2210
-
2211
- 1. **Title:**
2212
- - Should be clear and descriptive (3-8 words)
2213
- - Should reflect what the user is asking about
2214
- - Should NOT include "Dashboard" suffix (that will be added automatically)
2215
-
2216
- 2. **Description:**
2217
- - Should be a brief summary (1-2 sentences)
2218
- - Should explain what insights the dashboard provides
2219
-
2220
- **Output Requirements:**
2221
-
2222
- Respond with a JSON object:
2223
- {
2224
- "title": "Dashboard title without 'Dashboard' suffix",
2225
- "description": "Brief description of what this dashboard shows"
2226
- }
2227
-
2228
- **Important:**
2229
- - Keep the title concise and meaningful
2230
- - Make the description informative but brief
2231
- - Focus on what insights the user will gain
2232
- `,
2233
- user: `{{USER_PROMPT}}
2234
- `
2235
- },
2236
- "text-response": {
2237
- system: `You are an intelligent AI assistant that provides helpful, accurate, and contextual text responses to user questions.
2238
-
2239
- ## Your Task
2240
-
2241
- Analyze the user's question and provide a helpful text response. Your response should:
1875
+ 3. **NO NESTED AGGREGATE FUNCTIONS** - PostgreSQL does NOT allow aggregates inside aggregates
1876
+ \u274C WRONG: \`AVG(ROUND(AVG(column), 2))\` or \`SELECT AVG(SUM(price)) FROM ...\`
1877
+ \u2705 CORRECT: \`ROUND(AVG(column), 2)\`
2242
1878
 
2243
- 1. **Be Clear and Concise**: Provide direct answers without unnecessary verbosity
2244
- 2. **Be Contextual**: Use conversation history to understand what the user is asking about
2245
- 3. **Be Accurate**: Provide factually correct information based on the context
2246
- 4. **Be Helpful**: Offer additional relevant information or suggestions when appropriate
1879
+ 4. **GROUP BY Requirements**
1880
+ - ALL non-aggregated columns in SELECT must be in GROUP BY
1881
+ - If you SELECT a column and don't aggregate it, add it to GROUP BY
2247
1882
 
2248
- ## Handling Data Questions
1883
+ 5. **LIMIT Clause**
1884
+ - ALWAYS include LIMIT (max 32 rows)
1885
+ - For scalar subqueries in WHERE/HAVING, add LIMIT 1
2249
1886
 
2250
- When the user asks about data
1887
+ 6. **String Escaping** - PostgreSQL uses double single-quotes, NOT backslash
1888
+ \u274C WRONG: \`'Children\\'s furniture'\`
1889
+ \u2705 CORRECT: \`'Children''s furniture'\`
2251
1890
 
2252
- 1. **Generate a SQL query** using the database schema provided above
2253
- 2. **Use the execute_query tool** to run the query
2254
- 3. **If the query fails**, analyze the error and generate a corrected query
2255
- 4. **Format the results** in a clear, readable way for the user
1891
+ 7. **Always Use Table Aliases for Column References** - Prevent ambiguous column errors
1892
+ \u274C WRONG: \`SELECT product_id FROM products p JOIN product_variants pv ON p.product_id = pv.product_id\`
1893
+ \u2705 CORRECT: \`SELECT p.product_id FROM products p JOIN product_variants pv ON p.product_id = pv.product_id\`
1894
+ - Always prefix columns with table alias (e.g., \`p.product_id\`, \`c.name\`)
1895
+ - Especially critical in subqueries and joins where multiple tables share column names
2256
1896
 
2257
- **Query Guidelines:**
2258
- - Use correct table and column names from the schema
2259
- - ALWAYS include a LIMIT clause with a MAXIMUM of 32 rows
2260
- - Ensure valid SQL syntax
2261
- - For time-based queries, use appropriate date functions
2262
- - When using subqueries with scalar operators (=, <, >, etc.), add LIMIT 1 to prevent "more than one row" errors
2263
1897
 
2264
1898
  ## Response Guidelines
2265
1899
 
2266
- - If the question is about data, use the execute_query tool to fetch data and present it
1900
+ - If the question is about viewing data, use the execute_query tool to fetch data and present it
1901
+ - If the question is about creating/updating/deleting data:
1902
+ 1. Acknowledge that the system supports this via forms
1903
+ 2. **CRITICAL:** Use the database schema to determine which fields are required based on \`nullable\` property
1904
+ 3. **CRITICAL:** If the form will have select fields for foreign keys, you MUST fetch the options data using execute_query
1905
+ 4. **CRITICAL FOR UPDATE/DELETE OPERATIONS:** If it's an update/edit/modify/delete question:
1906
+ - **NEVER update ID/primary key columns** (e.g., order_id, customer_id, product_id) - these are immutable identifiers
1907
+ - You MUST first fetch the CURRENT values of the record using a SELECT query
1908
+ - Identify the record (from user's question - e.g., "update order 123" or "delete order 123" means order_id = 123)
1909
+ - Execute: \`SELECT * FROM table_name WHERE id = <value> LIMIT 1\`
1910
+ - Present the current values in your response (e.g., "Current order status: Pending, payment method: Credit Card")
1911
+ - For DELETE: These values will be shown in a disabled form as confirmation before deletion
1912
+ - For UPDATE: These values will populate as default values for editing
1913
+ 5. Present the options data in your response (e.g., "Available categories: Furniture (id: 1), Kitchen (id: 2), Decor (id: 3)")
1914
+ 6. The form component will be generated automatically using this data
2267
1915
  - If the question is general knowledge, provide a helpful conversational response
2268
1916
  - If asking for clarification, provide options or ask specific follow-up questions
2269
1917
  - If you don't have enough information, acknowledge it and ask for more details
2270
1918
  - Keep responses focused and avoid going off-topic
2271
1919
 
1920
+ **Example for data modification with foreign keys:**
1921
+ User: "I want to create a new product"
1922
+ You should:
1923
+ 1. Execute query: \`SELECT category_id, name FROM categories LIMIT 32\`
1924
+ 2. Execute query: \`SELECT store_id, name FROM stores LIMIT 32\`
1925
+ 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)..."
1926
+ 4. Suggest Form component
1927
+
2272
1928
  ## Component Suggestions
2273
1929
 
2274
- After analyzing the query results, you MUST suggest appropriate dashboard components for displaying the data. Use this format:
1930
+ After analyzing the user's question, you MUST suggest appropriate dashboard components. Use this format:
2275
1931
 
2276
1932
  <DashboardComponents>
2277
1933
  **Dashboard Components:**
@@ -2279,12 +1935,22 @@ Format: \`{number}.{component_type} : {clear reasoning}\`
2279
1935
 
2280
1936
 
2281
1937
  **Rules for component suggestions:**
2282
- 1. Analyze the query results structure and data type
2283
- 2. Suggest components that would best visualize the data
2284
- 3. Each component suggestion must be on a new line
1938
+ 1. If a conclusive answer can be provided based on user question, suggest that as the first component.
1939
+ 2. ALways suggest context/supporting components that will give the user more information and allow them to explore further.
1940
+ 3. If the question includes a time range, also explore time-based components for past time ranges.
1941
+ 4. **For data viewing/analysis questions**: Suggest visualization components (KPICard, BarChart, LineChart, PieChart, DataTable, etc.).
1942
+ 5. **For data modification questions** (create/add/update/delete):
1943
+ - Always suggest 1-2 context components first to provide relevant information (prefer KPICard for showing key metrics)
1944
+ - Then suggest \`Form\` component for the actual modification
1945
+ - Example: "1.KPICard : Show current order total and status" then "2.Form : To update order details"
1946
+ 6. Analyze the query results structure and data type
1947
+ 7. Each component suggestion must be on a new line
2285
1948
  </DashboardComponents>
2286
1949
 
2287
- IMPORTANT: Always wrap component suggestions with <DashboardComponents> tags and include at least one component suggestion when data is returned.
1950
+ IMPORTANT:
1951
+ - Always wrap component suggestions with <DashboardComponents> tags
1952
+ - For data viewing: Include at least one component suggestion when data is returned
1953
+ - 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")
2288
1954
 
2289
1955
  ## Output Format
2290
1956
 
@@ -2299,37 +1965,22 @@ Respond with plain text that includes:
2299
1965
  - Return ONLY plain text (no JSON, no markdown code blocks)
2300
1966
 
2301
1967
 
2302
- You have access to a database and can execute SQL queries to answer data-related questions.
2303
- ## Database Schema
2304
- {{SCHEMA_DOC}}
2305
-
2306
- **Database Type: PostgreSQL**
2307
-
2308
- **CRITICAL PostgreSQL Query Rules:**
1968
+ 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.
2309
1969
 
2310
- 1. **NO AGGREGATE FUNCTIONS IN WHERE CLAUSE** - This is a fundamental SQL error
2311
- \u274C WRONG: \`WHERE COUNT(orders) > 0\`
2312
- \u274C WRONG: \`WHERE SUM(price) > 100\`
2313
- \u274C WRONG: \`WHERE AVG(rating) > 4.5\`
2314
1970
 
2315
- \u2705 CORRECT: Use HAVING (with GROUP BY), EXISTS, or subquery
1971
+ ## External Tool Results
2316
1972
 
2317
- 2. **WHERE vs HAVING**
2318
- - WHERE filters rows BEFORE grouping (cannot use aggregates)
2319
- - HAVING filters groups AFTER grouping (can use aggregates)
2320
- - If using HAVING, you MUST have GROUP BY
1973
+ The following external tools were executed for this request (if applicable):
2321
1974
 
2322
- 3. **NO NESTED AGGREGATE FUNCTIONS** - PostgreSQL does NOT allow aggregates inside aggregates
2323
- \u274C WRONG: \`AVG(ROUND(AVG(column), 2))\` or \`SELECT AVG(SUM(price)) FROM ...\`
2324
- \u2705 CORRECT: \`ROUND(AVG(column), 2)\`
1975
+ {{EXTERNAL_TOOL_CONTEXT}}
2325
1976
 
2326
- 4. **GROUP BY Requirements**
2327
- - ALL non-aggregated columns in SELECT must be in GROUP BY
2328
- - If you SELECT a column and don't aggregate it, add it to GROUP BY
1977
+ Use this external tool data to:
1978
+ - Provide information from external sources (emails, calendar, etc.)
1979
+ - Present the data in a user-friendly format
1980
+ - Combine external data with database queries when relevant
1981
+ - Reference specific results in your response
2329
1982
 
2330
- 5. **LIMIT Clause**
2331
- - ALWAYS include LIMIT (max 32 rows)
2332
- - For scalar subqueries in WHERE/HAVING, add LIMIT 1
1983
+ **Note:** If external tools were not needed, this section will indicate "No external tools were used for this request."
2333
1984
 
2334
1985
 
2335
1986
  ## Knowledge Base Context
@@ -2352,10 +2003,8 @@ Use this knowledge base information to:
2352
2003
  ## Previous Conversation
2353
2004
  {{CONVERSATION_HISTORY}}
2354
2005
 
2355
-
2356
2006
  `,
2357
2007
  user: `{{USER_PROMPT}}
2358
-
2359
2008
  `
2360
2009
  },
2361
2010
  "match-text-components": {
@@ -2369,11 +2018,21 @@ You will receive a text response containing:
2369
2018
  3. **Dashboard Components:** suggestions (1:component_type : reasoning format)
2370
2019
 
2371
2020
  Your job is to:
2372
- 1. **Parse the component suggestions** from the text response (format: 1:component_type : reasoning)
2373
- 2. **Match each suggestion with an actual component** from the available list
2374
- 3. **Generate proper props** for each matched component to **visualize the analysis results** that were already fetched
2375
- 4. **Generate title and description** for the dashboard container
2376
- 5. **Generate intelligent follow-up questions (actions)** that the user might naturally ask next based on the data analysis
2021
+ 1. **FIRST: Generate a direct answer component** (if the user question can be answered with a single visualization)
2022
+ - Determine the BEST visualization type (KPICard, BarChart, DataTable, PieChart, LineChart, etc.) to directly answer the user's question
2023
+ - Select the matching component from the available components list
2024
+ - Generate complete props for this component (query, title, description, config)
2025
+ - This component will be placed in the \`answerComponent\` field
2026
+ - This component will be streamed to the frontend IMMEDIATELY for instant user feedback
2027
+ - **CRITICAL**: Generate this FIRST in your JSON response
2028
+
2029
+ 2. **THEN: Parse ALL dashboard component suggestions** from the text response (format: 1:component_type : reasoning)
2030
+ 3. **Match EACH suggestion with an actual component** from the available list
2031
+ 4. **CRITICAL**: \`matchedComponents\` must include **ALL** dashboard components suggested in the text, INCLUDING the component you used as \`answerComponent\`
2032
+ - The answerComponent is shown first for quick feedback, but the full dashboard shows everything
2033
+ 5. **Generate proper props** for each matched component to **visualize the analysis results** that were already fetched
2034
+ 6. **Generate title and description** for the dashboard container
2035
+ 7. **Generate intelligent follow-up questions (actions)** that the user might naturally ask next based on the data analysis
2377
2036
 
2378
2037
  **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.
2379
2038
 
@@ -2408,7 +2067,8 @@ For each matched component, generate complete props:
2408
2067
 
2409
2068
  **Option B: GENERATE a new query** (when necessary)
2410
2069
  - Only generate new queries when you need DIFFERENT data
2411
- - Use the database schema below to write valid SQL
2070
+ - For SELECT queries: Use the database schema below to write valid SQL
2071
+ - For mutations (INSERT/UPDATE/DELETE): Only if matching a Form component, generate mutation query with $fieldName placeholders
2412
2072
 
2413
2073
 
2414
2074
  **Decision Logic:**
@@ -2426,8 +2086,12 @@ For each matched component, generate complete props:
2426
2086
  \u274C WRONG: \`WHERE COUNT(orders) > 0\`
2427
2087
  \u274C WRONG: \`WHERE SUM(price) > 100\`
2428
2088
  \u274C WRONG: \`WHERE AVG(rating) > 4.5\`
2089
+ \u274C WRONG: \`WHERE FLOOR(AVG(rating)) = 4\` (aggregate inside any function is still not allowed)
2090
+ \u274C WRONG: \`WHERE ROUND(SUM(price), 2) > 100\`
2429
2091
 
2430
2092
  \u2705 CORRECT: Use HAVING (with GROUP BY), EXISTS, or subquery
2093
+ \u2705 CORRECT: Move aggregate logic to HAVING: \`GROUP BY ... HAVING FLOOR(AVG(rating)) = 4\`
2094
+ \u2705 CORRECT: Use subquery for filtering: \`WHERE product_id IN (SELECT product_id FROM ... GROUP BY ... HAVING AVG(rating) >= 4)\`
2431
2095
 
2432
2096
  2. **NO NESTED AGGREGATE FUNCTIONS** - PostgreSQL does NOT allow aggregates inside aggregates
2433
2097
  \u274C WRONG: \`AVG(ROUND(AVG(column), 2))\`
@@ -2456,6 +2120,16 @@ For each matched component, generate complete props:
2456
2120
  - Subqueries used with =, <, >, etc. must return single value
2457
2121
  - Always add LIMIT 1 to scalar subqueries
2458
2122
 
2123
+ 8. **String Escaping** - PostgreSQL uses double single-quotes, NOT backslash
2124
+ \u274C WRONG: \`'Children\\'s furniture'\`
2125
+ \u2705 CORRECT: \`'Children''s furniture'\`
2126
+
2127
+ 9. **Always Use Table Aliases for Column References** - Prevent ambiguous column errors
2128
+ \u274C WRONG: \`SELECT product_id FROM products p JOIN product_variants pv ON p.product_id = pv.product_id\`
2129
+ \u2705 CORRECT: \`SELECT p.product_id FROM products p JOIN product_variants pv ON p.product_id = pv.product_id\`
2130
+ - Always prefix columns with table alias (e.g., \`p.product_id\`, \`c.name\`)
2131
+ - Especially critical in subqueries and joins where multiple tables share column names
2132
+
2459
2133
  **Query Generation Guidelines** (when creating new queries):
2460
2134
  - Use correct table and column names from the schema above
2461
2135
  - ALWAYS include LIMIT clause (max 32 rows)
@@ -2469,7 +2143,7 @@ For each matched component, generate complete props:
2469
2143
  - Brief explanation of what this component displays
2470
2144
  - Why it's useful for this data
2471
2145
 
2472
- ### 4. Config
2146
+ ### 4. Config (for visualization components)
2473
2147
  - **CRITICAL**: Look at the component's "Props Structure" to see what config fields it expects
2474
2148
  - Map query result columns to the appropriate config fields
2475
2149
  - Keep other existing config properties that don't need to change
@@ -2481,40 +2155,167 @@ For each matched component, generate complete props:
2481
2155
  - \`orientation\` = "vertical" or "horizontal" (controls visual direction only)
2482
2156
  - **DO NOT swap xAxisKey/yAxisKey based on orientation** - they always represent category and value respectively
2483
2157
 
2484
- ## Follow-Up Questions (Actions) Generation
2158
+ ### 5. Additional Props (match according to component type)
2159
+ - **CRITICAL**: Look at the matched component's "Props Structure" in the available components list
2160
+ - Generate props that match EXACTLY what the component expects
2485
2161
 
2486
- 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:
2162
+ **For Form components (type: "Form"):**
2487
2163
 
2488
- 1. **Build upon the data analysis** shown in the text response and components
2489
- 2. **Explore natural next steps** in the data exploration journey
2490
- 3. **Be progressively more detailed or specific** - go deeper into the analysis
2491
- 4. **Consider the insights revealed** - suggest questions that help users understand implications
2492
- 5. **Be phrased naturally** as if a real user would ask them
2493
- 6. **Vary in scope** - include both broad trends and specific details
2494
- 7. **Avoid redundancy** - don't ask questions already answered in the text response
2164
+ Props structure:
2165
+ - **query**: \`{ sql: "INSERT/UPDATE/DELETE query with $fieldName placeholders", params: [] }\`
2166
+ - **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\`)
2167
+ - **title**: "Update Order 5000", "Create New Product", or "Delete Order 5000"
2168
+ - **description**: What the form does
2169
+ - **submitButtonText**: Button text (default: "Submit"). For delete: "Delete", "Confirm Delete"
2170
+ - **submitButtonColor**: "primary" (blue) or "danger" (red). Use "danger" for DELETE operations
2171
+ - **successMessage**: Success message (default: "Form submitted successfully!"). For delete: "Record deleted successfully!"
2172
+ - **disableFields**: Set \`true\` for DELETE operations to show current values but prevent editing
2173
+ - **fields**: Array of field objects (structure below)
2495
2174
 
2175
+ **Field object:**
2176
+ \`\`\`json
2177
+ {
2178
+ "name": "field_name", // Matches $field_name in SQL query
2179
+ "description": "Field Label",
2180
+ "type": "text|number|email|date|select|multiselect|checkbox|textarea",
2181
+ "required": true, // Set based on schema: nullable=false \u2192 required=true, nullable=true \u2192 required=false
2182
+ "defaultValue": "current_value", // For UPDATE: extract from text response
2183
+ "placeholder": "hint text",
2184
+ "options": [...], // For select/multiselect
2185
+ "validation": {
2186
+ "minLength": { "value": 5, "message": "..." },
2187
+ "maxLength": { "value": 100, "message": "..." },
2188
+ "min": { "value": 18, "message": "..." },
2189
+ "max": { "value": 120, "message": "..." },
2190
+ "pattern": { "value": "regex", "message": "..." }
2191
+ }
2192
+ }
2193
+ \`\`\`
2496
2194
 
2497
- ## Output Format
2195
+ **CRITICAL - Set required based on database schema:**
2196
+ - Check the column's \`nullable\` property in the database schema
2197
+ - If \`nullable: false\` \u2192 set \`required: true\` (field is mandatory)
2198
+ - If \`nullable: true\` \u2192 set \`required: false\` (field is optional)
2199
+ - Never set fields as required if the schema allows NULL
2498
2200
 
2499
- You MUST respond with ONLY a valid JSON object (no markdown, no code blocks):
2201
+ **Default Values for UPDATE:**
2202
+ - **NEVER include ID/primary key fields in UPDATE forms** (e.g., order_id, customer_id, product_id) - these cannot be changed
2203
+ - Detect UPDATE by checking if SQL contains "UPDATE" keyword
2204
+ - Extract current values from text response (look for "Current values:" or SELECT results)
2205
+ - Set \`defaultValue\` for each field with the extracted current value
2500
2206
 
2501
- **IMPORTANT JSON FORMATTING RULES:**
2502
- - Put SQL queries on a SINGLE LINE (no newlines in the query string)
2503
- - Escape all quotes in SQL properly (use \\" for quotes inside strings)
2504
- - Remove any newlines, tabs, or special characters from SQL
2505
- - Do NOT use markdown code blocks (no \`\`\`)
2506
- - Return ONLY the JSON object, nothing else
2207
+ **CRITICAL - Single field with current value pre-selected:**
2208
+ For UPDATE operations, use ONE field with defaultValue set to current value (not two separate fields).
2507
2209
 
2210
+ \u2705 CORRECT - Single field, current value pre-selected:
2508
2211
  \`\`\`json
2509
2212
  {
2510
- "layoutTitle": "Clear, concise title for the overall dashboard/layout (5-10 words)",
2511
- "layoutDescription": "Brief description of what the dashboard shows and its purpose (1-2 sentences)",
2512
- "matchedComponents": [
2513
- {
2514
- "componentId": "id_from_available_list",
2515
- "componentName": "name_of_component",
2516
- "componentType": "type_of_component",
2517
- "reasoning": "Why this component was selected for this suggestion",
2213
+ "name": "category_id",
2214
+ "type": "select",
2215
+ "defaultValue": 5,
2216
+ "options": [{"id": 1, "name": "Kitchen"}, {"id": 5, "name": "Furniture"}, {"id": 7, "name": "Decor"}]
2217
+ }
2218
+ \`\`\`
2219
+ User sees dropdown with "Furniture" selected, can change to any other category.
2220
+
2221
+ \u274C WRONG - Two separate fields:
2222
+ \`\`\`json
2223
+ [
2224
+ {"name": "current_category", "type": "text", "defaultValue": "Furniture", "disabled": true},
2225
+ {"name": "new_category", "type": "select", "options": [...]}
2226
+ ]
2227
+ \`\`\`
2228
+
2229
+ **Options Format:**
2230
+ - **Enum/status fields** (non-foreign keys): String array \`["Pending", "Shipped", "Delivered"]\`
2231
+ - **Foreign keys** (reference tables): Object array \`[{"id": 1, "name": "Furniture"}, {"id": 2, "name": "Kitchen"}]\`
2232
+ - Extract from text response queries and match format to field type
2233
+
2234
+ **Example UPDATE form field:**
2235
+ \`\`\`json
2236
+ {
2237
+ "name": "status",
2238
+ "description": "Order Status",
2239
+ "type": "select",
2240
+ "required": true,
2241
+ "defaultValue": "Pending", // Current value from database
2242
+ "options": ["Pending", "Processing", "Shipped", "Delivered"]
2243
+ }
2244
+ \`\`\`
2245
+
2246
+ **Example DELETE form props:**
2247
+ \`\`\`json
2248
+ {
2249
+ "query": { "sql": "DELETE FROM orders WHERE order_id = 123", "params": [] },
2250
+ "title": "Delete Order 123",
2251
+ "description": "Are you sure you want to delete this order?",
2252
+ "submitButtonText": "Confirm Delete",
2253
+ "submitButtonColor": "danger",
2254
+ "successMessage": "Order deleted successfully!",
2255
+ "disableFields": true,
2256
+ "fields": [
2257
+ { "name": "order_id", "description": "Order ID", "type": "text", "defaultValue": "123" },
2258
+ { "name": "status", "description": "Status", "type": "text", "defaultValue": "Pending" }
2259
+ ]
2260
+ }
2261
+ \`\`\`
2262
+
2263
+ **For visualization components (Charts, Tables, KPIs):**
2264
+ - **query**: String (SQL SELECT query)
2265
+ - **title**, **description**, **config**: As per component's props structure
2266
+ - Do NOT include fields array
2267
+
2268
+ ## Follow-Up Questions (Actions) Generation
2269
+
2270
+ 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:
2271
+
2272
+ 1. **Build upon the data analysis** shown in the text response and components
2273
+ 2. **Explore natural next steps** in the data exploration journey
2274
+ 3. **Be progressively more detailed or specific** - go deeper into the analysis
2275
+ 4. **Consider the insights revealed** - suggest questions that help users understand implications
2276
+ 5. **Be phrased naturally** as if a real user would ask them
2277
+ 6. **Vary in scope** - include both broad trends and specific details
2278
+ 7. **Avoid redundancy** - don't ask questions already answered in the text response
2279
+
2280
+
2281
+ ## Output Format
2282
+
2283
+ You MUST respond with ONLY a valid JSON object (no markdown, no code blocks):
2284
+
2285
+ **IMPORTANT JSON FORMATTING RULES:**
2286
+ - Put SQL queries on a SINGLE LINE (no newlines in the query string)
2287
+ - Escape all quotes in SQL properly (use \\" for quotes inside strings)
2288
+ - Remove any newlines, tabs, or special characters from SQL
2289
+ - Do NOT use markdown code blocks (no \`\`\`)
2290
+ - Return ONLY the JSON object, nothing else
2291
+
2292
+ **Example 1: With answer component** (when user question can be answered with single visualization)
2293
+ \`\`\`json
2294
+ {
2295
+ "hasAnswerComponent": true,
2296
+ "answerComponent": {
2297
+ "componentId": "id_from_available_list",
2298
+ "componentName": "name_of_component",
2299
+ "componentType": "type_of_component (can be KPICard, BarChart, LineChart, PieChart, DataTable, etc.)",
2300
+ "reasoning": "Why this visualization type best answers the user's question",
2301
+ "props": {
2302
+ "query": "SQL query for this component",
2303
+ "title": "Component title that directly answers the user's question",
2304
+ "description": "Component description",
2305
+ "config": {
2306
+ "field1": "value1",
2307
+ "field2": "value2"
2308
+ }
2309
+ }
2310
+ },
2311
+ "layoutTitle": "Clear, concise title for the overall dashboard/layout (5-10 words)",
2312
+ "layoutDescription": "Brief description of what the dashboard shows and its purpose (1-2 sentences)",
2313
+ "matchedComponents": [
2314
+ {
2315
+ "componentId": "id_from_available_list",
2316
+ "componentName": "name_of_component",
2317
+ "componentType": "type_of_component",
2318
+ "reasoning": "Why this component was selected for the dashboard",
2518
2319
  "originalSuggestion": "c1:table : original reasoning from text",
2519
2320
  "props": {
2520
2321
  "query": "SQL query for this component",
@@ -2537,21 +2338,65 @@ You MUST respond with ONLY a valid JSON object (no markdown, no code blocks):
2537
2338
  }
2538
2339
  \`\`\`
2539
2340
 
2341
+ **Example 2: Without answer component** (when user question needs multiple visualizations or dashboard)
2342
+ \`\`\`json
2343
+ {
2344
+ "hasAnswerComponent": false,
2345
+ "answerComponent": null,
2346
+ "layoutTitle": "Clear, concise title for the overall dashboard/layout (5-10 words)",
2347
+ "layoutDescription": "Brief description of what the dashboard shows and its purpose (1-2 sentences)",
2348
+ "matchedComponents": [
2349
+ {
2350
+ "componentId": "id_from_available_list",
2351
+ "componentName": "name_of_component",
2352
+ "componentType": "type_of_component",
2353
+ "reasoning": "Why this component was selected for the dashboard",
2354
+ "originalSuggestion": "c1:chart : original reasoning from text",
2355
+ "props": {
2356
+ "query": "SQL query for this component",
2357
+ "title": "Component title",
2358
+ "description": "Component description",
2359
+ "config": {
2360
+ "field1": "value1",
2361
+ "field2": "value2"
2362
+ }
2363
+ }
2364
+ }
2365
+ ],
2366
+ "actions": [
2367
+ "Follow-up question 1?",
2368
+ "Follow-up question 2?",
2369
+ "Follow-up question 3?",
2370
+ "Follow-up question 4?",
2371
+ "Follow-up question 5?"
2372
+ ]
2373
+ }
2374
+ \`\`\`
2375
+
2540
2376
  **CRITICAL:**
2541
- - \`matchedComponents\` MUST include ALL components suggested in the text response
2377
+ - **\`hasAnswerComponent\` determines if an answer component exists**
2378
+ - Set to \`true\` if the user question can be answered with a single visualization
2379
+ - Set to \`false\` if the user question can not be answered with single visualisation and needs multiple visualizations or a dashboard overview
2380
+ - **If \`hasAnswerComponent\` is \`true\`:**
2381
+ - \`answerComponent\` MUST be generated FIRST in the JSON before \`layoutTitle\`
2382
+ - Generate complete props (query, title, description, config)
2383
+ - **If \`hasAnswerComponent\` is \`false\`:**
2384
+ - Set \`answerComponent\` to \`null\`
2385
+ - **\`matchedComponents\` MUST include ALL dashboard components from the text analysis**
2386
+ - **CRITICAL**: Even if you used a component as \`answerComponent\`, you MUST STILL include it in \`matchedComponents\`
2387
+ - 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)
2388
+ - Do NOT skip the answerComponent from matchedComponents
2389
+ - \`matchedComponents\` come from the dashboard component suggestions in the text response
2542
2390
  - \`layoutTitle\` MUST be a clear, concise title (5-10 words) that summarizes what the entire dashboard shows
2543
- - Examples: "Sales Performance Overview", "Customer Metrics Analysis", "Product Category Breakdown"
2544
2391
  - \`layoutDescription\` MUST be a brief description (1-2 sentences) explaining the purpose and scope of the dashboard
2545
2392
  - Should describe what insights the dashboard provides and what data it shows
2546
2393
  - \`actions\` MUST be an array of 4-5 intelligent follow-up questions based on the analysis
2547
2394
  - Return ONLY valid JSON (no markdown code blocks, no text before/after)
2548
- - Generate complete props for each component including query, title, description, and config
2549
-
2550
-
2395
+ - Generate complete props for each component
2551
2396
  `,
2552
- user: `## Text Response
2397
+ user: `## Analysis Content
2553
2398
 
2554
- {{TEXT_RESPONSE}}
2399
+ {{ANALYSIS_CONTENT}}
2555
2400
 
2556
2401
  ---
2557
2402
 
@@ -2598,70 +2443,269 @@ Format your response as a JSON object with this structure:
2598
2443
 
2599
2444
  Return ONLY valid JSON.`
2600
2445
  },
2601
- "execute-tools": {
2602
- system: `You are an expert AI assistant that executes external tools to fetch data from external services.
2446
+ "category-classification": {
2447
+ system: `You are an expert AI that categorizes user questions into specific action categories and identifies required tools/resources.
2603
2448
 
2604
- 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.
2449
+ CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2605
2450
 
2606
2451
  ## Available External Tools
2452
+
2607
2453
  {{AVAILABLE_TOOLS}}
2608
2454
 
2609
- ## Your Task
2455
+ ---
2610
2456
 
2611
- Analyze the user's request and:
2612
-
2613
- 1. **Determine if external tools are needed**
2614
- - Examples that NEED external tools:
2615
- - "Show me my emails" \u2192 needs email tool
2616
- - "Get my last 5 Gmail messages" \u2192 needs Gmail tool
2617
- - "Check my Outlook inbox" \u2192 needs Outlook tool
2618
-
2619
- - Examples that DON'T need external tools:
2620
- - "What is the total sales?" \u2192 database query (handled elsewhere)
2621
- - "Show me revenue trends" \u2192 internal data analysis
2622
- - "Hello" \u2192 general conversation
2623
-
2624
- 2. **Call the appropriate tools**
2625
- - Use the tool calling mechanism to execute external tools
2626
- - Extract parameters from the user's request
2627
- - Use sensible defaults when parameters aren't specified:
2628
- - For email limit: default to 10
2629
- - For email address: use "me" for the authenticated user if not specified
2630
-
2631
- 3. **Handle errors and retry**
2632
- - If a tool call fails, analyze the error message
2633
- - Retry with corrected parameters if possible
2634
- - You have up to 3 attempts per tool
2635
-
2636
- ## Important Guidelines
2637
-
2638
- - **Only call external tools when necessary** - Don't call tools for database queries or general conversation
2639
- - **Choose the right tool** - For email requests, select Gmail vs Outlook based on:
2640
- - Explicit mention (e.g., "Gmail", "Outlook")
2641
- - Email domain (e.g., @gmail.com \u2192 Gmail, @company.com \u2192 Outlook)
2642
- - **Extract parameters carefully** - Use the user's exact values when provided
2643
- - **If no tools are needed** - Simply respond that no external tools are required for this request
2644
-
2645
- ## Examples
2646
-
2647
- **Example 1 - Gmail Request:**
2648
- User: "Show me my last 5 Gmail messages"
2649
- Action: Call get-gmail-mails tool with parameters: { email: "me", limit: 5 }
2650
-
2651
- **Example 2 - Outlook Request:**
2652
- User: "Get emails from john.doe@company.com"
2653
- Action: Call get-outlook-mails tool with parameters: { email: "john.doe@company.com", limit: 10 }
2654
-
2655
- **Example 3 - No Tools Needed:**
2656
- User: "What is the total sales?"
2657
- Response: This is a database query, not an external tool request. No external tools are needed.
2658
-
2659
- **Example 4 - Error Retry:**
2660
- Tool call fails with: "Invalid email parameter"
2661
- Action: Analyze error, correct the parameter, and retry the tool call
2662
- `,
2663
- user: `{{USER_PROMPT}}
2664
- `
2457
+ Your task is to analyze the user's question and determine:
2458
+
2459
+ 1. **Question Category:**
2460
+ - "data_analysis": Questions about analyzing, querying, reading, or visualizing data from the database (SELECT operations)
2461
+ - "data_modification": Questions about creating, updating, deleting, or modifying data in the database (INSERT, UPDATE, DELETE operations)
2462
+
2463
+ 2. **External Tools Required** (for both categories):
2464
+ From the available tools listed above, identify which ones are needed to support the user's request:
2465
+ - Match the tool names/descriptions to what the user is asking for
2466
+ - Extract specific parameters mentioned in the user's question
2467
+
2468
+ 3. **Tool Parameters** (if tools are identified):
2469
+ Extract specific parameters the user mentioned:
2470
+ - For each identified tool, extract relevant parameters (email, recipient, content, etc.)
2471
+ - Only include parameters the user explicitly or implicitly mentioned
2472
+
2473
+ **Important Guidelines:**
2474
+ - If user mentions any of the available external tools \u2192 identify those tools and extract their parameters
2475
+ - If user asks to "send", "schedule", "create event", "message" \u2192 check if available tools match
2476
+ - If user asks to "show", "analyze", "compare", "calculate" data \u2192 "data_analysis"
2477
+ - If user asks to modify/create/update/delete data \u2192 "data_modification"
2478
+ - Always identify tools from the available tools list (not from generic descriptions)
2479
+ - Be precise in identifying tool types and required parameters
2480
+ - Only include tools that are explicitly mentioned or clearly needed
2481
+
2482
+ **Output Format:**
2483
+ \`\`\`json
2484
+ {
2485
+ "category": "data_analysis" | "data_modification",
2486
+ "reasoning": "Brief explanation of why this category was chosen",
2487
+ "externalTools": [
2488
+ {
2489
+ "type": "tool_id_from_available_tools",
2490
+ "name": "Tool Display Name",
2491
+ "description": "What this tool will do",
2492
+ "parameters": {
2493
+ "param1": "extracted value",
2494
+ "param2": "extracted value"
2495
+ }
2496
+ }
2497
+ ],
2498
+ "dataAnalysisType": "visualization" | "calculation" | "comparison" | "trend" | null,
2499
+ "confidence": 0-100
2500
+ }
2501
+ \`\`\`
2502
+
2503
+
2504
+ ## Previous Conversation
2505
+ {{CONVERSATION_HISTORY}}`,
2506
+ user: `{{USER_PROMPT}}`
2507
+ },
2508
+ "adapt-ui-block-params": {
2509
+ system: `You are an expert AI that adapts and modifies UI block component parameters based on the user's current question.
2510
+
2511
+ CRITICAL: You MUST respond with ONLY valid JSON, no other text before or after.
2512
+
2513
+ ## Database Schema Reference
2514
+
2515
+ {{SCHEMA_DOC}}
2516
+
2517
+ 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.
2518
+
2519
+ ## Context
2520
+ You are given:
2521
+ 1. A previous UI Block response (with component and its props) that matched the user's current question with >90% semantic similarity
2522
+ 2. The user's current question
2523
+ 3. The component that needs parameter adaptation
2524
+
2525
+ Your task is to:
2526
+ 1. **Analyze the difference** between the original question (from the matched UIBlock) and the current user question
2527
+ 2. **Identify what parameters need to change** in the component props to answer the current question
2528
+ 3. **Modify the props** to match the current request while keeping the same component type(s)
2529
+ 4. **Preserve component structure** - only change props, not the components themselves
2530
+
2531
+ ## Component Structure Handling
2532
+
2533
+ ### For Single Components:
2534
+ - Modify props directly (config, actions, query, filters, etc.)
2535
+
2536
+ ### For MultiComponentContainer:
2537
+ The component will have structure:
2538
+ \`\`\`json
2539
+ {
2540
+ "type": "Container",
2541
+ "name": "MultiComponentContainer",
2542
+ "props": {
2543
+ "config": {
2544
+ "components": [...], // Array of nested components - ADAPT EACH ONE
2545
+ "title": "...", // Container title - UPDATE based on new question
2546
+ "description": "..." // Container description - UPDATE based on new question
2547
+ },
2548
+ "actions": [...] // ADAPT actions if needed
2549
+ }
2550
+ }
2551
+ \`\`\`
2552
+
2553
+ When adapting MultiComponentContainer:
2554
+ - Update the container-level \`title\` and \`description\` to reflect the new user question
2555
+ - For each component in \`config.components\`:
2556
+ - Identify what data it shows and how the new question changes what's needed
2557
+ - Adapt its query parameters (WHERE clauses, LIMIT, ORDER BY, filters, date ranges)
2558
+ - Update its title/description to match the new context
2559
+ - Update its config settings (colors, sorting, grouping, metrics)
2560
+ - Update \`actions\` if the new question requires different actions
2561
+
2562
+ ## Important Guidelines:
2563
+ - Keep the same component type (don't change KPICard to LineChart)
2564
+ - Keep the same number of components in the container
2565
+ - For each nested component, update:
2566
+ - Query WHERE clauses, LIMIT, ORDER BY, filters, date ranges, metrics
2567
+ - Title and description to reflect the new question
2568
+ - Config settings like colors, sorting, grouping if needed
2569
+ - Maintain each component's core purpose while answering the new question
2570
+ - If query modification is needed, ensure all table/column names remain valid
2571
+ - CRITICAL: Ensure JSON is valid and complete for all nested structures
2572
+
2573
+
2574
+ ## Output Format:
2575
+
2576
+ ### For Single Component:
2577
+ \`\`\`json
2578
+ {
2579
+ "success": true,
2580
+ "adaptedComponent": {
2581
+ "id": "original_component_id",
2582
+ "name": "component_name",
2583
+ "type": "component_type",
2584
+ "description": "updated_description",
2585
+ "props": {
2586
+ "config": { },
2587
+ "actions": [],
2588
+ }
2589
+ },
2590
+ "parametersChanged": [
2591
+ {
2592
+ "field": "query",
2593
+ "reason": "Added Q4 date filter"
2594
+ },
2595
+ {
2596
+ "field": "title",
2597
+ "reason": "Updated to reflect Q4 focus"
2598
+ }
2599
+ ],
2600
+ "explanation": "How the component was adapted to answer the new question"
2601
+ }
2602
+ \`\`\`
2603
+
2604
+ ### For MultiComponentContainer:
2605
+ \`\`\`json
2606
+ {
2607
+ "success": true,
2608
+ "adaptedComponent": {
2609
+ "id": "original_container_id",
2610
+ "name": "MultiComponentContainer",
2611
+ "type": "Container",
2612
+ "description": "updated_container_description",
2613
+ "props": {
2614
+ "config": {
2615
+ "title": "Updated dashboard title based on new question",
2616
+ "description": "Updated description reflecting new question context",
2617
+ "components": [
2618
+ {
2619
+ "id": "component_1_id",
2620
+ "name": "component_1_name",
2621
+ "type": "component_1_type",
2622
+ "description": "updated description for this specific component",
2623
+ "props": {
2624
+ "query": "Modified SQL query with updated WHERE/LIMIT/ORDER BY",
2625
+ "config": { "metric": "updated_metric", "filters": {...} }
2626
+ }
2627
+ },
2628
+ {
2629
+ "id": "component_2_id",
2630
+ "name": "component_2_name",
2631
+ "type": "component_2_type",
2632
+ "description": "updated description for this component",
2633
+ "props": {
2634
+ "query": "Modified SQL query for this component",
2635
+ "config": { "metric": "updated_metric", "filters": {...} }
2636
+ }
2637
+ }
2638
+ ]
2639
+ },
2640
+ "actions": []
2641
+ }
2642
+ },
2643
+ "parametersChanged": [
2644
+ {
2645
+ "field": "container.title",
2646
+ "reason": "Updated to reflect new dashboard focus"
2647
+ },
2648
+ {
2649
+ "field": "components[0].query",
2650
+ "reason": "Modified WHERE clause for new metrics"
2651
+ },
2652
+ {
2653
+ "field": "components[1].config.metric",
2654
+ "reason": "Changed metric from X to Y based on new question"
2655
+ }
2656
+ ],
2657
+ "explanation": "Detailed explanation of how each component was adapted"
2658
+ }
2659
+ \`\`\`
2660
+
2661
+ If adaptation is not possible or would fundamentally change the component:
2662
+ \`\`\`json
2663
+ {
2664
+ "success": false,
2665
+ "reason": "Cannot adapt component - the new question requires a different visualization type",
2666
+ "explanation": "The original component shows KPI cards but the new question needs a trend chart"
2667
+ }
2668
+ \`\`\``,
2669
+ user: `## Previous Matched UIBlock
2670
+
2671
+ **Original Question:** {{ORIGINAL_USER_PROMPT}}
2672
+
2673
+ **Matched UIBlock Component:**
2674
+ \`\`\`json
2675
+ {{MATCHED_UI_BLOCK_COMPONENT}}
2676
+ \`\`\`
2677
+
2678
+ **Component Properties:**
2679
+ \`\`\`json
2680
+ {{COMPONENT_PROPS}}
2681
+ \`\`\`
2682
+
2683
+ ## Current User Question
2684
+ {{CURRENT_USER_PROMPT}}
2685
+
2686
+ ---
2687
+
2688
+ ## Adaptation Instructions
2689
+
2690
+ 1. **Analyze the difference** between the original question and the current question
2691
+ 2. **Identify what data needs to change**:
2692
+ - For single components: adapt the query/config/actions
2693
+ - For MultiComponentContainer: adapt the container title/description AND each nested component's parameters
2694
+
2695
+ 3. **Modify the parameters**:
2696
+ - **Container level** (if MultiComponentContainer):
2697
+ - Update \`title\` and \`description\` to reflect the new user question
2698
+ - Update \`actions\` if needed
2699
+
2700
+ - **For each component** (single or nested in container):
2701
+ - Identify what it shows (sales, revenue, inventory, etc.)
2702
+ - Adapt SQL queries: modify WHERE clauses, LIMIT, ORDER BY, filters, date ranges
2703
+ - Update component title and description
2704
+ - Update config settings (metrics, colors, sorting, grouping)
2705
+
2706
+ 4. **Preserve structure**: Keep the same number and type of components
2707
+
2708
+ 5. **Return complete JSON** with all adapted properties for all components`
2665
2709
  }
2666
2710
  };
2667
2711
 
@@ -2739,9 +2783,10 @@ var PromptLoader = class {
2739
2783
  }
2740
2784
  /**
2741
2785
  * Load both system and user prompts from cache and replace variables
2786
+ * Supports prompt caching by splitting static and dynamic content
2742
2787
  * @param promptName - Name of the prompt
2743
2788
  * @param variables - Variables to replace in the templates
2744
- * @returns Object containing both system and user prompts
2789
+ * @returns Object containing both system and user prompts (system can be string or array for caching)
2745
2790
  */
2746
2791
  async loadPrompts(promptName, variables) {
2747
2792
  if (!this.isInitialized) {
@@ -2752,6 +2797,26 @@ var PromptLoader = class {
2752
2797
  if (!template) {
2753
2798
  throw new Error(`Prompt template '${promptName}' not found in cache. Available prompts: ${Array.from(this.promptCache.keys()).join(", ")}`);
2754
2799
  }
2800
+ const contextMarker = "---\n\n## CONTEXT";
2801
+ if (template.system.includes(contextMarker)) {
2802
+ const [staticPart, contextPart] = template.system.split(contextMarker);
2803
+ logger.debug(`\u2713 Prompt caching enabled for '${promptName}' (static: ${staticPart.length} chars, context: ${contextPart.length} chars)`);
2804
+ const processedContext = this.replaceVariables(contextMarker + contextPart, variables);
2805
+ return {
2806
+ system: [
2807
+ {
2808
+ type: "text",
2809
+ text: staticPart.trim(),
2810
+ cache_control: { type: "ephemeral" }
2811
+ },
2812
+ {
2813
+ type: "text",
2814
+ text: processedContext.trim()
2815
+ }
2816
+ ],
2817
+ user: this.replaceVariables(template.user, variables)
2818
+ };
2819
+ }
2755
2820
  return {
2756
2821
  system: this.replaceVariables(template.system, variables),
2757
2822
  user: this.replaceVariables(template.user, variables)
@@ -2838,6 +2903,75 @@ var LLM = class {
2838
2903
  // ============================================================
2839
2904
  // PRIVATE HELPER METHODS
2840
2905
  // ============================================================
2906
+ /**
2907
+ * Normalize system prompt to Anthropic format
2908
+ * Converts string to array format if needed
2909
+ * @param sys - System prompt (string or array of blocks)
2910
+ * @returns Normalized system prompt for Anthropic API
2911
+ */
2912
+ static _normalizeSystemPrompt(sys) {
2913
+ if (typeof sys === "string") {
2914
+ return sys;
2915
+ }
2916
+ return sys;
2917
+ }
2918
+ /**
2919
+ * Log cache usage metrics from Anthropic API response
2920
+ * Shows cache hits, costs, and savings
2921
+ */
2922
+ static _logCacheUsage(usage) {
2923
+ if (!usage) return;
2924
+ const inputTokens = usage.input_tokens || 0;
2925
+ const cacheCreationTokens = usage.cache_creation_input_tokens || 0;
2926
+ const cacheReadTokens = usage.cache_read_input_tokens || 0;
2927
+ const outputTokens = usage.output_tokens || 0;
2928
+ const INPUT_PRICE = 0.8;
2929
+ const OUTPUT_PRICE = 4;
2930
+ const CACHE_WRITE_PRICE = 1;
2931
+ const CACHE_READ_PRICE = 0.08;
2932
+ const regularInputCost = inputTokens / 1e6 * INPUT_PRICE;
2933
+ const cacheWriteCost = cacheCreationTokens / 1e6 * CACHE_WRITE_PRICE;
2934
+ const cacheReadCost = cacheReadTokens / 1e6 * CACHE_READ_PRICE;
2935
+ const outputCost = outputTokens / 1e6 * OUTPUT_PRICE;
2936
+ const totalCost = regularInputCost + cacheWriteCost + cacheReadCost + outputCost;
2937
+ const totalInputTokens = inputTokens + cacheCreationTokens + cacheReadTokens;
2938
+ const costWithoutCache = totalInputTokens / 1e6 * INPUT_PRICE + outputCost;
2939
+ const savings = costWithoutCache - totalCost;
2940
+ const savingsPercent = costWithoutCache > 0 ? savings / costWithoutCache * 100 : 0;
2941
+ 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");
2942
+ console.log("\u{1F4B0} PROMPT CACHING METRICS");
2943
+ 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");
2944
+ console.log("\n\u{1F4CA} Token Usage:");
2945
+ console.log(` Input (regular): ${inputTokens.toLocaleString()} tokens`);
2946
+ if (cacheCreationTokens > 0) {
2947
+ console.log(` Cache write: ${cacheCreationTokens.toLocaleString()} tokens (first request)`);
2948
+ }
2949
+ if (cacheReadTokens > 0) {
2950
+ console.log(` Cache read: ${cacheReadTokens.toLocaleString()} tokens \u26A1 HIT!`);
2951
+ }
2952
+ console.log(` Output: ${outputTokens.toLocaleString()} tokens`);
2953
+ console.log(` Total input: ${totalInputTokens.toLocaleString()} tokens`);
2954
+ console.log("\n\u{1F4B5} Cost Breakdown:");
2955
+ console.log(` Input (regular): $${regularInputCost.toFixed(6)}`);
2956
+ if (cacheCreationTokens > 0) {
2957
+ console.log(` Cache write: $${cacheWriteCost.toFixed(6)}`);
2958
+ }
2959
+ if (cacheReadTokens > 0) {
2960
+ console.log(` Cache read: $${cacheReadCost.toFixed(6)} (90% off!)`);
2961
+ }
2962
+ console.log(` Output: $${outputCost.toFixed(6)}`);
2963
+ 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`);
2964
+ console.log(` Total cost: $${totalCost.toFixed(6)}`);
2965
+ if (cacheReadTokens > 0) {
2966
+ console.log(`
2967
+ \u{1F48E} Savings: $${savings.toFixed(6)} (${savingsPercent.toFixed(1)}% off)`);
2968
+ console.log(` Without cache: $${costWithoutCache.toFixed(6)}`);
2969
+ } else if (cacheCreationTokens > 0) {
2970
+ console.log(`
2971
+ \u23F1\uFE0F Cache created - next request will be ~90% cheaper!`);
2972
+ }
2973
+ 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");
2974
+ }
2841
2975
  /**
2842
2976
  * Parse model string to extract provider and model name
2843
2977
  * @param modelString - Format: "provider/model-name" or just "model-name"
@@ -2872,7 +3006,7 @@ var LLM = class {
2872
3006
  model: modelName,
2873
3007
  max_tokens: options.maxTokens || 1e3,
2874
3008
  temperature: options.temperature,
2875
- system: messages.sys,
3009
+ system: this._normalizeSystemPrompt(messages.sys),
2876
3010
  messages: [{
2877
3011
  role: "user",
2878
3012
  content: messages.user
@@ -2890,7 +3024,7 @@ var LLM = class {
2890
3024
  model: modelName,
2891
3025
  max_tokens: options.maxTokens || 1e3,
2892
3026
  temperature: options.temperature,
2893
- system: messages.sys,
3027
+ system: this._normalizeSystemPrompt(messages.sys),
2894
3028
  messages: [{
2895
3029
  role: "user",
2896
3030
  content: messages.user
@@ -2898,6 +3032,7 @@ var LLM = class {
2898
3032
  stream: true
2899
3033
  });
2900
3034
  let fullText = "";
3035
+ let usage = null;
2901
3036
  for await (const chunk of stream) {
2902
3037
  if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
2903
3038
  const text = chunk.delta.text;
@@ -2905,8 +3040,12 @@ var LLM = class {
2905
3040
  if (options.partial) {
2906
3041
  options.partial(text);
2907
3042
  }
3043
+ } else if (chunk.type === "message_delta" && chunk.usage) {
3044
+ usage = chunk.usage;
2908
3045
  }
2909
3046
  }
3047
+ if (usage) {
3048
+ }
2910
3049
  if (json) {
2911
3050
  return this._parseJSON(fullText);
2912
3051
  }
@@ -2929,7 +3068,7 @@ var LLM = class {
2929
3068
  model: modelName,
2930
3069
  max_tokens: options.maxTokens || 4e3,
2931
3070
  temperature: options.temperature,
2932
- system: messages.sys,
3071
+ system: this._normalizeSystemPrompt(messages.sys),
2933
3072
  messages: conversationMessages,
2934
3073
  tools,
2935
3074
  stream: true
@@ -2939,6 +3078,7 @@ var LLM = class {
2939
3078
  const contentBlocks = [];
2940
3079
  let currentTextBlock = "";
2941
3080
  let currentToolUse = null;
3081
+ let usage = null;
2942
3082
  for await (const chunk of stream) {
2943
3083
  if (chunk.type === "message_start") {
2944
3084
  contentBlocks.length = 0;
@@ -2989,11 +3129,16 @@ var LLM = class {
2989
3129
  }
2990
3130
  if (chunk.type === "message_delta") {
2991
3131
  stopReason = chunk.delta.stop_reason || stopReason;
3132
+ if (chunk.usage) {
3133
+ usage = chunk.usage;
3134
+ }
2992
3135
  }
2993
3136
  if (chunk.type === "message_stop") {
2994
3137
  break;
2995
3138
  }
2996
3139
  }
3140
+ if (usage) {
3141
+ }
2997
3142
  if (stopReason === "end_turn") {
2998
3143
  break;
2999
3144
  }
@@ -3165,6 +3310,57 @@ var KB = {
3165
3310
  };
3166
3311
  var knowledge_base_default = KB;
3167
3312
 
3313
+ // src/userResponse/conversation-search.ts
3314
+ var searchConversations = async ({
3315
+ userPrompt,
3316
+ collections,
3317
+ userId,
3318
+ similarityThreshold = 0.6
3319
+ }) => {
3320
+ try {
3321
+ if (!collections || !collections["conversation-history"] || !collections["conversation-history"]["search"]) {
3322
+ logger.info("[ConversationSearch] conversation-history.search collection not registered, skipping");
3323
+ return null;
3324
+ }
3325
+ logger.info(`[ConversationSearch] Searching conversations for: "${userPrompt.substring(0, 50)}..."`);
3326
+ logger.info(`[ConversationSearch] Using similarity threshold: ${(similarityThreshold * 100).toFixed(0)}%`);
3327
+ const result = await collections["conversation-history"]["search"]({
3328
+ userPrompt,
3329
+ userId,
3330
+ threshold: similarityThreshold
3331
+ });
3332
+ if (!result) {
3333
+ logger.info("[ConversationSearch] No matching conversations found");
3334
+ return null;
3335
+ }
3336
+ if (!result.uiBlock) {
3337
+ logger.error("[ConversationSearch] No UI block in conversation search result");
3338
+ return null;
3339
+ }
3340
+ const similarity = result.similarity || 0;
3341
+ logger.info(`[ConversationSearch] Best match similarity: ${(similarity * 100).toFixed(2)}%`);
3342
+ if (similarity < similarityThreshold) {
3343
+ logger.info(
3344
+ `[ConversationSearch] Best match has similarity ${(similarity * 100).toFixed(2)}% but below threshold ${(similarityThreshold * 100).toFixed(2)}%`
3345
+ );
3346
+ return null;
3347
+ }
3348
+ logger.info(
3349
+ `[ConversationSearch] Found matching conversation with similarity ${(similarity * 100).toFixed(2)}%`
3350
+ );
3351
+ logger.debug(`[ConversationSearch] Matched prompt: "${result.metadata?.userPrompt?.substring(0, 50)}..."`);
3352
+ return result;
3353
+ } catch (error) {
3354
+ const errorMsg = error instanceof Error ? error.message : String(error);
3355
+ logger.warn(`[ConversationSearch] Error searching conversations: ${errorMsg}`);
3356
+ return null;
3357
+ }
3358
+ };
3359
+ var ConversationSearch = {
3360
+ searchConversations
3361
+ };
3362
+ var conversation_search_default = ConversationSearch;
3363
+
3168
3364
  // src/userResponse/base-llm.ts
3169
3365
  var BaseLLM = class {
3170
3366
  constructor(config) {
@@ -3178,531 +3374,6 @@ var BaseLLM = class {
3178
3374
  getApiKey(apiKey) {
3179
3375
  return apiKey || this.apiKey || this.getDefaultApiKey();
3180
3376
  }
3181
- /**
3182
- * Classify user question to determine the type and required visualizations
3183
- */
3184
- async classifyUserQuestion(userPrompt, apiKey, logCollector, conversationHistory) {
3185
- try {
3186
- const prompts = await promptLoader.loadPrompts("classify", {
3187
- USER_PROMPT: userPrompt,
3188
- CONVERSATION_HISTORY: conversationHistory || "No previous conversation"
3189
- });
3190
- const result = await LLM.stream(
3191
- {
3192
- sys: prompts.system,
3193
- user: prompts.user
3194
- },
3195
- {
3196
- model: this.model,
3197
- maxTokens: 800,
3198
- temperature: 0.2,
3199
- apiKey: this.getApiKey(apiKey)
3200
- },
3201
- true
3202
- // Parse as JSON
3203
- );
3204
- logCollector?.logExplanation(
3205
- "User question classified",
3206
- result.reasoning || "No reasoning provided",
3207
- {
3208
- questionType: result.questionType || "general",
3209
- visualizations: result.visualizations || [],
3210
- needsMultipleComponents: result.needsMultipleComponents || false
3211
- }
3212
- );
3213
- return {
3214
- questionType: result.questionType || "general",
3215
- visualizations: result.visualizations || [],
3216
- reasoning: result.reasoning || "No reasoning provided",
3217
- needsMultipleComponents: result.needsMultipleComponents || false
3218
- };
3219
- } catch (error) {
3220
- const errorMsg = error instanceof Error ? error.message : String(error);
3221
- logger.error(`[${this.getProviderName()}] Error classifying user question: ${errorMsg}`);
3222
- logger.debug(`[${this.getProviderName()}] Classification error details:`, error);
3223
- throw error;
3224
- }
3225
- }
3226
- /**
3227
- * Enhanced function that validates and modifies the entire props object based on user request
3228
- * This includes query, title, description, and config properties
3229
- */
3230
- async validateAndModifyProps(userPrompt, originalProps, componentName, componentType, componentDescription, apiKey, logCollector, conversationHistory) {
3231
- const schemaDoc = schema.generateSchemaDocumentation();
3232
- try {
3233
- const prompts = await promptLoader.loadPrompts("modify-props", {
3234
- COMPONENT_NAME: componentName,
3235
- COMPONENT_TYPE: componentType,
3236
- COMPONENT_DESCRIPTION: componentDescription || "No description",
3237
- SCHEMA_DOC: schemaDoc || "No schema available",
3238
- DEFAULT_LIMIT: this.defaultLimit,
3239
- USER_PROMPT: userPrompt,
3240
- CURRENT_PROPS: JSON.stringify(originalProps, null, 2),
3241
- CONVERSATION_HISTORY: conversationHistory || "No previous conversation"
3242
- });
3243
- logger.debug("props-modification: System prompt\n", prompts.system.substring(0, 100), "\n\n\n", "User prompt:", prompts.user.substring(0, 50));
3244
- const result = await LLM.stream(
3245
- {
3246
- sys: prompts.system,
3247
- user: prompts.user
3248
- },
3249
- {
3250
- model: this.model,
3251
- maxTokens: 2500,
3252
- temperature: 0.2,
3253
- apiKey: this.getApiKey(apiKey)
3254
- },
3255
- true
3256
- // Parse as JSON
3257
- );
3258
- const props = result.props || originalProps;
3259
- if (props && props.query) {
3260
- props.query = fixScalarSubqueries(props.query);
3261
- props.query = ensureQueryLimit(props.query, this.defaultLimit);
3262
- }
3263
- if (props && props.query) {
3264
- logCollector?.logQuery(
3265
- "Props query modified",
3266
- props.query,
3267
- {
3268
- modifications: result.modifications || [],
3269
- reasoning: result.reasoning || "No modifications needed"
3270
- }
3271
- );
3272
- }
3273
- if (result.reasoning) {
3274
- logCollector?.logExplanation(
3275
- "Props modification explanation",
3276
- result.reasoning,
3277
- { modifications: result.modifications || [] }
3278
- );
3279
- }
3280
- return {
3281
- props,
3282
- isModified: result.isModified || false,
3283
- reasoning: result.reasoning || "No modifications needed",
3284
- modifications: result.modifications || []
3285
- };
3286
- } catch (error) {
3287
- const errorMsg = error instanceof Error ? error.message : String(error);
3288
- logger.error(`[${this.getProviderName()}] Error validating/modifying props: ${errorMsg}`);
3289
- logger.debug(`[${this.getProviderName()}] Props validation error details:`, error);
3290
- throw error;
3291
- }
3292
- }
3293
- /**
3294
- * Match and select a component from available components filtered by type
3295
- * This picks the best matching component based on user prompt and modifies its props
3296
- */
3297
- async generateAnalyticalComponent(userPrompt, components, preferredVisualizationType, apiKey, logCollector, conversationHistory) {
3298
- try {
3299
- const filteredComponents = preferredVisualizationType ? components.filter((c) => c.type === preferredVisualizationType) : components;
3300
- if (filteredComponents.length === 0) {
3301
- logCollector?.warn(
3302
- `No components found of type ${preferredVisualizationType}`,
3303
- "explanation",
3304
- { reason: "No matching components available for this visualization type" }
3305
- );
3306
- return {
3307
- component: null,
3308
- reasoning: `No components available of type ${preferredVisualizationType}`,
3309
- isGenerated: false
3310
- };
3311
- }
3312
- const componentsText = filteredComponents.map((comp, idx) => {
3313
- const keywords = comp.keywords ? comp.keywords.join(", ") : "";
3314
- const category = comp.category || "general";
3315
- const propsPreview = comp.props ? JSON.stringify(comp.props, null, 2) : "No props";
3316
- return `${idx + 1}. ID: ${comp.id}
3317
- Name: ${comp.name}
3318
- Type: ${comp.type}
3319
- Category: ${category}
3320
- Description: ${comp.description || "No description"}
3321
- Keywords: ${keywords}
3322
- Props Preview: ${propsPreview}`;
3323
- }).join("\n\n");
3324
- const visualizationConstraint = preferredVisualizationType ? `
3325
- **IMPORTANT: Components are filtered to type ${preferredVisualizationType}. Select the best match.**
3326
- ` : "";
3327
- const prompts = await promptLoader.loadPrompts("single-component", {
3328
- COMPONENT_TYPE: preferredVisualizationType || "any",
3329
- COMPONENTS_LIST: componentsText,
3330
- VISUALIZATION_CONSTRAINT: visualizationConstraint,
3331
- USER_PROMPT: userPrompt,
3332
- CONVERSATION_HISTORY: conversationHistory || "No previous conversation"
3333
- });
3334
- logger.debug("single-component: System prompt\n", prompts.system.substring(0, 100), "\n\n\n", "User prompt:", prompts.user.substring(0, 50));
3335
- const result = await LLM.stream(
3336
- {
3337
- sys: prompts.system,
3338
- user: prompts.user
3339
- },
3340
- {
3341
- model: this.model,
3342
- maxTokens: 2e3,
3343
- temperature: 0.2,
3344
- apiKey: this.getApiKey(apiKey)
3345
- },
3346
- true
3347
- // Parse as JSON
3348
- );
3349
- if (!result.canGenerate || result.confidence < 50) {
3350
- logCollector?.warn(
3351
- "Cannot match component",
3352
- "explanation",
3353
- { reason: result.reasoning || "Unable to find matching component for this question" }
3354
- );
3355
- return {
3356
- component: null,
3357
- reasoning: result.reasoning || "Unable to find matching component for this question",
3358
- isGenerated: false
3359
- };
3360
- }
3361
- const componentIndex = result.componentIndex;
3362
- const componentId = result.componentId;
3363
- let matchedComponent = null;
3364
- if (componentId) {
3365
- matchedComponent = filteredComponents.find((c) => c.id === componentId);
3366
- }
3367
- if (!matchedComponent && componentIndex) {
3368
- matchedComponent = filteredComponents[componentIndex - 1];
3369
- }
3370
- if (!matchedComponent) {
3371
- logCollector?.warn("Component not found in filtered list");
3372
- return {
3373
- component: null,
3374
- reasoning: "Component not found in filtered list",
3375
- isGenerated: false
3376
- };
3377
- }
3378
- logCollector?.info(`Matched component: ${matchedComponent.name} (confidence: ${result.confidence}%)`);
3379
- const propsValidation = await this.validateAndModifyProps(
3380
- userPrompt,
3381
- matchedComponent.props,
3382
- matchedComponent.name,
3383
- matchedComponent.type,
3384
- matchedComponent.description,
3385
- apiKey,
3386
- logCollector,
3387
- conversationHistory
3388
- );
3389
- const modifiedComponent = {
3390
- ...matchedComponent,
3391
- props: propsValidation.props
3392
- };
3393
- logCollector?.logExplanation(
3394
- "Analytical component selected and modified",
3395
- result.reasoning || "Selected component based on analytical question",
3396
- {
3397
- componentName: matchedComponent.name,
3398
- componentType: matchedComponent.type,
3399
- confidence: result.confidence,
3400
- propsModified: propsValidation.isModified
3401
- }
3402
- );
3403
- return {
3404
- component: modifiedComponent,
3405
- reasoning: result.reasoning || "Selected and modified component based on analytical question",
3406
- isGenerated: true
3407
- };
3408
- } catch (error) {
3409
- const errorMsg = error instanceof Error ? error.message : String(error);
3410
- logger.error(`[${this.getProviderName()}] Error generating analytical component: ${errorMsg}`);
3411
- logger.debug(`[${this.getProviderName()}] Analytical component generation error details:`, error);
3412
- throw error;
3413
- }
3414
- }
3415
- /**
3416
- * Generate container metadata (title and description) for multi-component dashboard
3417
- */
3418
- async generateContainerMetadata(userPrompt, visualizationTypes, apiKey, logCollector, conversationHistory) {
3419
- try {
3420
- const prompts = await promptLoader.loadPrompts("container-metadata", {
3421
- USER_PROMPT: userPrompt,
3422
- VISUALIZATION_TYPES: visualizationTypes.join(", "),
3423
- CONVERSATION_HISTORY: conversationHistory || "No previous conversation"
3424
- });
3425
- const result = await LLM.stream(
3426
- {
3427
- sys: prompts.system,
3428
- user: prompts.user
3429
- },
3430
- {
3431
- model: this.model,
3432
- maxTokens: 500,
3433
- temperature: 0.3,
3434
- apiKey: this.getApiKey(apiKey)
3435
- },
3436
- true
3437
- // Parse as JSON
3438
- );
3439
- logCollector?.logExplanation(
3440
- "Container metadata generated",
3441
- `Generated title and description for multi-component dashboard`,
3442
- {
3443
- title: result.title,
3444
- description: result.description,
3445
- visualizationTypes
3446
- }
3447
- );
3448
- return {
3449
- title: result.title || `${userPrompt} - Dashboard`,
3450
- description: result.description || `Multi-component dashboard showing ${visualizationTypes.join(", ")}`
3451
- };
3452
- } catch (error) {
3453
- const errorMsg = error instanceof Error ? error.message : String(error);
3454
- logger.error(`[${this.getProviderName()}] Error generating container metadata: ${errorMsg}`);
3455
- logger.debug(`[${this.getProviderName()}] Container metadata error details:`, error);
3456
- return {
3457
- title: `${userPrompt} - Dashboard`,
3458
- description: `Multi-component dashboard showing ${visualizationTypes.join(", ")}`
3459
- };
3460
- }
3461
- }
3462
- /**
3463
- * Match component from a list with enhanced props modification
3464
- */
3465
- async matchComponent(userPrompt, components, apiKey, logCollector, conversationHistory) {
3466
- try {
3467
- const componentsText = components.map((comp, idx) => {
3468
- const keywords = comp.keywords ? comp.keywords.join(", ") : "";
3469
- const category = comp.category || "general";
3470
- return `${idx + 1}. ID: ${comp.id}
3471
- Name: ${comp.name}
3472
- Type: ${comp.type}
3473
- Category: ${category}
3474
- Description: ${comp.description || "No description"}
3475
- Keywords: ${keywords}`;
3476
- }).join("\n\n");
3477
- const prompts = await promptLoader.loadPrompts("match-component", {
3478
- COMPONENTS_TEXT: componentsText,
3479
- USER_PROMPT: userPrompt,
3480
- CONVERSATION_HISTORY: conversationHistory || "No previous conversation"
3481
- });
3482
- const result = await LLM.stream(
3483
- {
3484
- sys: prompts.system,
3485
- user: prompts.user
3486
- },
3487
- {
3488
- model: this.model,
3489
- maxTokens: 800,
3490
- temperature: 0.2,
3491
- apiKey: this.getApiKey(apiKey)
3492
- },
3493
- true
3494
- // Parse as JSON
3495
- );
3496
- const componentIndex = result.componentIndex;
3497
- const componentId = result.componentId;
3498
- const confidence = result.confidence || 0;
3499
- let component = null;
3500
- if (componentId) {
3501
- component = components.find((c) => c.id === componentId);
3502
- }
3503
- if (!component && componentIndex) {
3504
- component = components[componentIndex - 1];
3505
- }
3506
- const matchedMsg = `${this.getProviderName()} matched component: ${component?.name || "None"}`;
3507
- logger.info(`[${this.getProviderName()}] \u2713 ${matchedMsg}`);
3508
- logCollector?.info(matchedMsg);
3509
- if (result.alternativeMatches && result.alternativeMatches.length > 0) {
3510
- logger.debug(`[${this.getProviderName()}] Alternative matches found: ${result.alternativeMatches.length}`);
3511
- const altMatches = result.alternativeMatches.map(
3512
- (alt) => `${components[alt.index - 1]?.name} (${alt.score}%): ${alt.reason}`
3513
- ).join(" | ");
3514
- logCollector?.info(`Alternative matches: ${altMatches}`);
3515
- result.alternativeMatches.forEach((alt) => {
3516
- logger.debug(`[${this.getProviderName()}] - ${components[alt.index - 1]?.name} (${alt.score}%): ${alt.reason}`);
3517
- });
3518
- }
3519
- if (!component) {
3520
- const noMatchMsg = `No matching component found (confidence: ${confidence}%)`;
3521
- logger.warn(`[${this.getProviderName()}] \u2717 ${noMatchMsg}`);
3522
- logCollector?.warn(noMatchMsg);
3523
- const genMsg = "Attempting to match component from analytical question...";
3524
- logger.info(`[${this.getProviderName()}] \u2713 ${genMsg}`);
3525
- logCollector?.info(genMsg);
3526
- const generatedResult = await this.generateAnalyticalComponent(userPrompt, components, void 0, apiKey, logCollector, conversationHistory);
3527
- if (generatedResult.component) {
3528
- const genSuccessMsg = `Successfully matched component: ${generatedResult.component.name}`;
3529
- logCollector?.info(genSuccessMsg);
3530
- return {
3531
- component: generatedResult.component,
3532
- reasoning: generatedResult.reasoning,
3533
- method: `${this.getProviderName()}-generated`,
3534
- confidence: 100,
3535
- // Generated components are considered 100% match to the question
3536
- propsModified: false,
3537
- queryModified: false
3538
- };
3539
- }
3540
- logCollector?.error("Failed to match component");
3541
- return {
3542
- component: null,
3543
- reasoning: result.reasoning || "No matching component found and unable to match component",
3544
- method: `${this.getProviderName()}-llm`,
3545
- confidence
3546
- };
3547
- }
3548
- let propsModified = false;
3549
- let propsModifications = [];
3550
- let queryModified = false;
3551
- let queryReasoning = "";
3552
- if (component && component.props) {
3553
- const propsValidation = await this.validateAndModifyProps(
3554
- userPrompt,
3555
- component.props,
3556
- component.name,
3557
- component.type,
3558
- component.description,
3559
- apiKey,
3560
- logCollector,
3561
- conversationHistory
3562
- );
3563
- const originalQuery = component.props.query;
3564
- const modifiedQuery = propsValidation.props.query;
3565
- component = {
3566
- ...component,
3567
- props: propsValidation.props
3568
- };
3569
- propsModified = propsValidation.isModified;
3570
- propsModifications = propsValidation.modifications;
3571
- queryModified = originalQuery !== modifiedQuery;
3572
- queryReasoning = propsValidation.reasoning;
3573
- }
3574
- return {
3575
- component,
3576
- reasoning: result.reasoning || "No reasoning provided",
3577
- queryModified,
3578
- queryReasoning,
3579
- propsModified,
3580
- propsModifications,
3581
- method: `${this.getProviderName()}-llm`,
3582
- confidence
3583
- };
3584
- } catch (error) {
3585
- const errorMsg = error instanceof Error ? error.message : String(error);
3586
- logger.error(`[${this.getProviderName()}] Error matching component: ${errorMsg}`);
3587
- logger.debug(`[${this.getProviderName()}] Component matching error details:`, error);
3588
- logCollector?.error(`Error matching component: ${errorMsg}`);
3589
- throw error;
3590
- }
3591
- }
3592
- /**
3593
- * Match multiple components for analytical questions by visualization types
3594
- * This is used when the user needs multiple visualizations
3595
- */
3596
- async generateMultipleAnalyticalComponents(userPrompt, availableComponents, visualizationTypes, apiKey, logCollector, conversationHistory) {
3597
- try {
3598
- console.log("\u2713 Matching multiple components:", visualizationTypes);
3599
- const components = [];
3600
- for (const vizType of visualizationTypes) {
3601
- const result = await this.generateAnalyticalComponent(userPrompt, availableComponents, vizType, apiKey, logCollector, conversationHistory);
3602
- if (result.component) {
3603
- components.push(result.component);
3604
- }
3605
- }
3606
- if (components.length === 0) {
3607
- return {
3608
- components: [],
3609
- reasoning: "Failed to match any components",
3610
- isGenerated: false
3611
- };
3612
- }
3613
- return {
3614
- components,
3615
- reasoning: `Matched ${components.length} components: ${visualizationTypes.join(", ")}`,
3616
- isGenerated: true
3617
- };
3618
- } catch (error) {
3619
- const errorMsg = error instanceof Error ? error.message : String(error);
3620
- logger.error(`[${this.getProviderName()}] Error matching multiple analytical components: ${errorMsg}`);
3621
- logger.debug(`[${this.getProviderName()}] Multiple components matching error details:`, error);
3622
- return {
3623
- components: [],
3624
- reasoning: "Error occurred while matching components",
3625
- isGenerated: false
3626
- };
3627
- }
3628
- }
3629
- /**
3630
- * Match multiple components and wrap them in a container
3631
- */
3632
- async generateMultiComponentResponse(userPrompt, availableComponents, visualizationTypes, apiKey, logCollector, conversationHistory) {
3633
- try {
3634
- const matchResult = await this.generateMultipleAnalyticalComponents(
3635
- userPrompt,
3636
- availableComponents,
3637
- visualizationTypes,
3638
- apiKey,
3639
- logCollector,
3640
- conversationHistory
3641
- );
3642
- if (!matchResult.isGenerated || matchResult.components.length === 0) {
3643
- return {
3644
- containerComponent: null,
3645
- reasoning: matchResult.reasoning || "Unable to match multi-component dashboard",
3646
- isGenerated: false
3647
- };
3648
- }
3649
- const generatedComponents = matchResult.components;
3650
- generatedComponents.forEach((component, index) => {
3651
- if (component.props.query) {
3652
- logCollector?.logQuery(
3653
- `Multi-component query generated (${index + 1}/${generatedComponents.length})`,
3654
- component.props.query,
3655
- {
3656
- componentType: component.type,
3657
- title: component.props.title,
3658
- position: index + 1,
3659
- totalComponents: generatedComponents.length
3660
- }
3661
- );
3662
- }
3663
- });
3664
- const containerTitle = `${userPrompt} - Dashboard`;
3665
- const containerDescription = `Multi-component dashboard showing ${visualizationTypes.join(", ")}`;
3666
- logCollector?.logExplanation(
3667
- "Multi-component dashboard matched",
3668
- matchResult.reasoning || `Matched ${generatedComponents.length} components for comprehensive analysis`,
3669
- {
3670
- totalComponents: generatedComponents.length,
3671
- componentTypes: generatedComponents.map((c) => c.type),
3672
- componentNames: generatedComponents.map((c) => c.name),
3673
- containerTitle,
3674
- containerDescription
3675
- }
3676
- );
3677
- const containerComponent = {
3678
- id: `multi_container_${Date.now()}`,
3679
- name: "MultiComponentContainer",
3680
- type: "Container",
3681
- description: containerDescription,
3682
- category: "dynamic",
3683
- keywords: ["multi", "container", "dashboard"],
3684
- props: {
3685
- config: {
3686
- components: generatedComponents,
3687
- layout: "grid",
3688
- spacing: 24,
3689
- title: containerTitle,
3690
- description: containerDescription
3691
- }
3692
- }
3693
- };
3694
- return {
3695
- containerComponent,
3696
- reasoning: matchResult.reasoning || `Matched multi-component dashboard with ${generatedComponents.length} components`,
3697
- isGenerated: true
3698
- };
3699
- } catch (error) {
3700
- const errorMsg = error instanceof Error ? error.message : String(error);
3701
- logger.error(`[${this.getProviderName()}] Error generating multi-component response: ${errorMsg}`);
3702
- logger.debug(`[${this.getProviderName()}] Multi-component response error details:`, error);
3703
- throw error;
3704
- }
3705
- }
3706
3377
  /**
3707
3378
  * Match components from text response suggestions and generate follow-up questions
3708
3379
  * Takes a text response with component suggestions (c1:type format) and matches with available components
@@ -3928,148 +3599,136 @@ var BaseLLM = class {
3928
3599
  }
3929
3600
  }
3930
3601
  /**
3931
- * Execute external tools based on user request using agentic LLM tool calling
3932
- * The LLM can directly call tools and retry on errors
3933
- * @param userPrompt - The user's question/request
3934
- * @param availableTools - Array of available external tools
3935
- * @param apiKey - Optional API key for LLM
3936
- * @param logCollector - Optional log collector
3937
- * @returns Object containing tool execution results and summary
3602
+ * Classify user question into category and detect external tools needed
3603
+ * Determines if question is for data analysis, requires external tools, or needs text response
3938
3604
  */
3939
- async executeExternalTools(userPrompt, availableTools, apiKey, logCollector) {
3940
- const MAX_TOOL_ATTEMPTS = 3;
3941
- const toolResults = [];
3605
+ async classifyQuestionCategory(userPrompt, apiKey, logCollector, conversationHistory, externalTools) {
3942
3606
  try {
3943
- logger.debug(`[${this.getProviderName()}] Starting agentic external tool execution`);
3944
- logger.debug(`[${this.getProviderName()}] Available tools: ${availableTools.map((t) => t.name).join(", ")}`);
3945
- const llmTools = availableTools.map((tool) => {
3946
- const properties = {};
3947
- const required = [];
3948
- Object.entries(tool.params || {}).forEach(([key, type]) => {
3949
- properties[key] = {
3950
- type: String(type).toLowerCase(),
3951
- description: `${key} parameter`
3952
- };
3953
- required.push(key);
3954
- });
3955
- return {
3956
- name: tool.id,
3957
- description: tool.description,
3958
- input_schema: {
3959
- type: "object",
3960
- properties,
3961
- required
3962
- }
3963
- };
3607
+ const availableToolsDoc = externalTools && externalTools.length > 0 ? externalTools.map((tool) => {
3608
+ const paramsStr = Object.entries(tool.params || {}).map(([key, type]) => `${key}: ${type}`).join(", ");
3609
+ return `- **${tool.name}** (id: ${tool.id})
3610
+ Description: ${tool.description}
3611
+ Parameters: ${paramsStr}`;
3612
+ }).join("\n\n") : "No external tools available";
3613
+ const prompts = await promptLoader.loadPrompts("category-classification", {
3614
+ USER_PROMPT: userPrompt,
3615
+ CONVERSATION_HISTORY: conversationHistory || "No previous conversation",
3616
+ AVAILABLE_TOOLS: availableToolsDoc
3964
3617
  });
3965
- const toolAttempts = /* @__PURE__ */ new Map();
3966
- const toolHandler = async (toolName, toolInput) => {
3967
- const tool = availableTools.find((t) => t.id === toolName);
3968
- if (!tool) {
3969
- const errorMsg = `Tool ${toolName} not found in available tools`;
3970
- logger.error(`[${this.getProviderName()}] ${errorMsg}`);
3971
- logCollector?.error(errorMsg);
3972
- throw new Error(errorMsg);
3973
- }
3974
- const attempts = (toolAttempts.get(toolName) || 0) + 1;
3975
- toolAttempts.set(toolName, attempts);
3976
- logger.info(`[${this.getProviderName()}] Executing tool: ${tool.name} (attempt ${attempts}/${MAX_TOOL_ATTEMPTS})`);
3977
- logCollector?.info(`Executing ${tool.name} (attempt ${attempts}/${MAX_TOOL_ATTEMPTS})...`);
3978
- if (attempts > MAX_TOOL_ATTEMPTS) {
3979
- const errorMsg = `Maximum attempts (${MAX_TOOL_ATTEMPTS}) reached for tool: ${tool.name}`;
3980
- logger.error(`[${this.getProviderName()}] ${errorMsg}`);
3981
- logCollector?.error(errorMsg);
3982
- toolResults.push({
3983
- toolName: tool.name,
3984
- toolId: tool.id,
3985
- result: null,
3986
- error: errorMsg
3987
- });
3988
- throw new Error(errorMsg);
3989
- }
3990
- try {
3991
- logger.debug(`[${this.getProviderName()}] Tool ${tool.name} parameters:`, toolInput);
3992
- const result2 = await tool.fn(toolInput);
3993
- logger.info(`[${this.getProviderName()}] Tool ${tool.name} executed successfully`);
3994
- logCollector?.info(`\u2713 ${tool.name} completed successfully`);
3995
- toolResults.push({
3996
- toolName: tool.name,
3997
- toolId: tool.id,
3998
- result: result2
3999
- });
4000
- return JSON.stringify(result2, null, 2);
4001
- } catch (error) {
4002
- const errorMsg = error instanceof Error ? error.message : String(error);
4003
- logger.error(`[${this.getProviderName()}] Tool ${tool.name} failed (attempt ${attempts}): ${errorMsg}`);
4004
- logCollector?.error(`\u2717 ${tool.name} failed: ${errorMsg}`);
4005
- if (attempts >= MAX_TOOL_ATTEMPTS) {
4006
- toolResults.push({
4007
- toolName: tool.name,
4008
- toolId: tool.id,
4009
- result: null,
4010
- error: errorMsg
4011
- });
4012
- }
4013
- throw new Error(`Tool execution failed: ${errorMsg}`);
3618
+ const result = await LLM.stream(
3619
+ {
3620
+ sys: prompts.system,
3621
+ user: prompts.user
3622
+ },
3623
+ {
3624
+ model: this.model,
3625
+ maxTokens: 1e3,
3626
+ temperature: 0.2,
3627
+ apiKey: this.getApiKey(apiKey)
3628
+ },
3629
+ true
3630
+ // Parse as JSON
3631
+ );
3632
+ logCollector?.logExplanation(
3633
+ "Question category classified",
3634
+ result.reasoning || "No reasoning provided",
3635
+ {
3636
+ category: result.category,
3637
+ externalTools: result.externalTools || [],
3638
+ dataAnalysisType: result.dataAnalysisType,
3639
+ confidence: result.confidence
4014
3640
  }
3641
+ );
3642
+ return {
3643
+ category: result.category || "data_analysis",
3644
+ externalTools: result.externalTools || [],
3645
+ dataAnalysisType: result.dataAnalysisType,
3646
+ reasoning: result.reasoning || "No reasoning provided",
3647
+ confidence: result.confidence || 0
4015
3648
  };
4016
- const prompts = await promptLoader.loadPrompts("execute-tools", {
4017
- USER_PROMPT: userPrompt,
4018
- AVAILABLE_TOOLS: availableTools.map((tool, idx) => {
4019
- const paramsText = Object.entries(tool.params || {}).map(([key, type]) => ` - ${key}: ${type}`).join("\n");
4020
- return `${idx + 1}. ID: ${tool.id}
4021
- Name: ${tool.name}
4022
- Description: ${tool.description}
4023
- Parameters:
4024
- ${paramsText}`;
4025
- }).join("\n\n")
3649
+ } catch (error) {
3650
+ const errorMsg = error instanceof Error ? error.message : String(error);
3651
+ logger.error(`[${this.getProviderName()}] Error classifying question category: ${errorMsg}`);
3652
+ logger.debug(`[${this.getProviderName()}] Category classification error details:`, error);
3653
+ throw error;
3654
+ }
3655
+ }
3656
+ /**
3657
+ * Adapt UI block parameters based on current user question
3658
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
3659
+ */
3660
+ async adaptUIBlockParameters(currentUserPrompt, originalUserPrompt, matchedUIBlock, apiKey, logCollector) {
3661
+ try {
3662
+ if (!matchedUIBlock || !matchedUIBlock.generatedComponentMetadata) {
3663
+ return {
3664
+ success: false,
3665
+ explanation: "No component found in matched UI block"
3666
+ };
3667
+ }
3668
+ const component = matchedUIBlock.generatedComponentMetadata;
3669
+ const schemaDoc = schema.generateSchemaDocumentation();
3670
+ const prompts = await promptLoader.loadPrompts("adapt-ui-block-params", {
3671
+ ORIGINAL_USER_PROMPT: originalUserPrompt,
3672
+ CURRENT_USER_PROMPT: currentUserPrompt,
3673
+ MATCHED_UI_BLOCK_COMPONENT: JSON.stringify(component, null, 2),
3674
+ COMPONENT_PROPS: JSON.stringify(component.props, null, 2),
3675
+ SCHEMA_DOC: schemaDoc || "No schema available"
4026
3676
  });
4027
- logger.debug(`[${this.getProviderName()}] Using agentic tool calling for external tools`);
4028
- logCollector?.info("Analyzing request and executing external tools...");
4029
- const result = await LLM.streamWithTools(
3677
+ const result = await LLM.stream(
4030
3678
  {
4031
3679
  sys: prompts.system,
4032
3680
  user: prompts.user
4033
3681
  },
4034
- llmTools,
4035
- toolHandler,
4036
3682
  {
4037
3683
  model: this.model,
4038
3684
  maxTokens: 2e3,
4039
3685
  temperature: 0.2,
4040
3686
  apiKey: this.getApiKey(apiKey)
4041
3687
  },
4042
- MAX_TOOL_ATTEMPTS + 2
4043
- // max iterations: allows for retries + final response
3688
+ true
3689
+ // Parse as JSON
4044
3690
  );
4045
- logger.info(`[${this.getProviderName()}] External tool execution completed`);
4046
- const successfulTools = toolResults.filter((r) => !r.error);
4047
- const failedTools = toolResults.filter((r) => r.error);
4048
- let summary = "";
4049
- if (successfulTools.length > 0) {
4050
- summary += `Successfully executed ${successfulTools.length} tool(s): ${successfulTools.map((t) => t.toolName).join(", ")}.
4051
- `;
4052
- }
4053
- if (failedTools.length > 0) {
4054
- summary += `Failed to execute ${failedTools.length} tool(s): ${failedTools.map((t) => t.toolName).join(", ")}.`;
3691
+ if (!result.success) {
3692
+ logger.info(
3693
+ `[${this.getProviderName()}] Could not adapt UI block: ${result.reason}`
3694
+ );
3695
+ logCollector?.warn(
3696
+ "Could not adapt matched UI block",
3697
+ "explanation",
3698
+ { reason: result.reason }
3699
+ );
3700
+ return {
3701
+ success: false,
3702
+ explanation: result.explanation || "Adaptation not possible"
3703
+ };
4055
3704
  }
4056
- if (toolResults.length === 0) {
4057
- summary = "No external tools were needed for this request.";
3705
+ if (result.adaptedComponent?.props?.query) {
3706
+ result.adaptedComponent.props.query = ensureQueryLimit(
3707
+ result.adaptedComponent.props.query,
3708
+ this.defaultLimit
3709
+ );
4058
3710
  }
4059
- logger.info(`[${this.getProviderName()}] Tool execution summary: ${summary}`);
3711
+ logCollector?.logExplanation(
3712
+ "UI block parameters adapted",
3713
+ result.explanation || "Parameters adapted successfully",
3714
+ {
3715
+ parametersChanged: result.parametersChanged || [],
3716
+ componentType: result.adaptedComponent?.type
3717
+ }
3718
+ );
4060
3719
  return {
4061
- toolResults,
4062
- summary,
4063
- hasResults: successfulTools.length > 0
3720
+ success: true,
3721
+ adaptedComponent: result.adaptedComponent,
3722
+ parametersChanged: result.parametersChanged,
3723
+ explanation: result.explanation || "Parameters adapted successfully"
4064
3724
  };
4065
3725
  } catch (error) {
4066
3726
  const errorMsg = error instanceof Error ? error.message : String(error);
4067
- logger.error(`[${this.getProviderName()}] Error in external tool execution: ${errorMsg}`);
4068
- logCollector?.error(`Error executing external tools: ${errorMsg}`);
3727
+ logger.error(`[${this.getProviderName()}] Error adapting UI block parameters: ${errorMsg}`);
3728
+ logger.debug(`[${this.getProviderName()}] Adaptation error details:`, error);
4069
3729
  return {
4070
- toolResults,
4071
- summary: `Error executing external tools: ${errorMsg}`,
4072
- hasResults: false
3730
+ success: false,
3731
+ explanation: `Error adapting parameters: ${errorMsg}`
4073
3732
  };
4074
3733
  }
4075
3734
  }
@@ -4088,32 +3747,24 @@ ${paramsText}`;
4088
3747
  logger.debug(`[${this.getProviderName()}] Starting text response generation`);
4089
3748
  logger.debug(`[${this.getProviderName()}] User prompt: "${userPrompt.substring(0, 50)}..."`);
4090
3749
  try {
4091
- let externalToolContext = "No external tools were used for this request.";
3750
+ let availableToolsDoc = "No external tools are available for this request.";
4092
3751
  if (externalTools && externalTools.length > 0) {
4093
- logger.info(`[${this.getProviderName()}] Executing external tools...`);
4094
- const toolExecution = await this.executeExternalTools(
4095
- userPrompt,
4096
- externalTools,
4097
- apiKey,
4098
- logCollector
4099
- );
4100
- if (toolExecution.hasResults) {
4101
- const toolResultsText = toolExecution.toolResults.map((tr) => {
4102
- if (tr.error) {
4103
- return `**${tr.toolName}** (Failed): ${tr.error}`;
3752
+ logger.info(`[${this.getProviderName()}] External tools available: ${externalTools.map((t) => t.name).join(", ")}`);
3753
+ 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) => {
3754
+ const paramsText = Object.entries(tool.params || {}).map(([key, value]) => {
3755
+ const valueType = typeof value;
3756
+ if (valueType === "string" && ["string", "number", "integer", "boolean", "array", "object"].includes(String(value).toLowerCase())) {
3757
+ return `- ${key}: ${value}`;
3758
+ } else {
3759
+ return `- ${key}: ${JSON.stringify(value)} (default value - use this)`;
4104
3760
  }
4105
- return `**${tr.toolName}** (Success):
4106
- ${JSON.stringify(tr.result, null, 2)}`;
4107
- }).join("\n\n");
4108
- externalToolContext = `## External Tool Results
4109
-
4110
- ${toolExecution.summary}
4111
-
4112
- ${toolResultsText}`;
4113
- logger.info(`[${this.getProviderName()}] External tools executed, results available`);
4114
- } else {
4115
- logger.info(`[${this.getProviderName()}] No external tools were needed`);
4116
- }
3761
+ }).join("\n ");
3762
+ return `${idx + 1}. **${tool.name}** (ID: ${tool.id})
3763
+ Description: ${tool.description}
3764
+ **ACTION REQUIRED**: Call this tool with the parameters below
3765
+ Parameters:
3766
+ ${paramsText}`;
3767
+ }).join("\n\n");
4117
3768
  }
4118
3769
  const schemaDoc = schema.generateSchemaDocumentation();
4119
3770
  const knowledgeBaseContext = await knowledge_base_default.getKnowledgeBase({
@@ -4122,13 +3773,12 @@ ${toolResultsText}`;
4122
3773
  topK: 1
4123
3774
  });
4124
3775
  logger.file("\n=============================\nknowledge base context:", knowledgeBaseContext);
4125
- logger.file("\n=============================\nexternal tool context:", externalToolContext);
4126
3776
  const prompts = await promptLoader.loadPrompts("text-response", {
4127
3777
  USER_PROMPT: userPrompt,
4128
3778
  CONVERSATION_HISTORY: conversationHistory || "No previous conversation",
4129
3779
  SCHEMA_DOC: schemaDoc,
4130
3780
  KNOWLEDGE_BASE_CONTEXT: knowledgeBaseContext || "No additional knowledge base context available.",
4131
- EXTERNAL_TOOL_CONTEXT: externalToolContext
3781
+ AVAILABLE_EXTERNAL_TOOLS: availableToolsDoc
4132
3782
  });
4133
3783
  logger.file("\n=============================\nsystem prompt:", prompts.system);
4134
3784
  logger.file("\n=============================\nuser prompt:", prompts.user);
@@ -4150,11 +3800,88 @@ ${toolResultsText}`;
4150
3800
  description: "Brief explanation of what this query does and why it answers the user's question."
4151
3801
  }
4152
3802
  },
4153
- required: ["query"]
3803
+ required: ["query"],
3804
+ additionalProperties: false
4154
3805
  }
4155
3806
  }];
3807
+ if (externalTools && externalTools.length > 0) {
3808
+ externalTools.forEach((tool) => {
3809
+ logger.info(`[${this.getProviderName()}] Processing external tool:`, JSON.stringify(tool, null, 2));
3810
+ const properties = {};
3811
+ const required = [];
3812
+ Object.entries(tool.params || {}).forEach(([key, typeOrValue]) => {
3813
+ let schemaType;
3814
+ let hasDefaultValue = false;
3815
+ let defaultValue;
3816
+ const valueType = typeof typeOrValue;
3817
+ if (valueType === "number") {
3818
+ schemaType = Number.isInteger(typeOrValue) ? "integer" : "number";
3819
+ hasDefaultValue = true;
3820
+ defaultValue = typeOrValue;
3821
+ } else if (valueType === "boolean") {
3822
+ schemaType = "boolean";
3823
+ hasDefaultValue = true;
3824
+ defaultValue = typeOrValue;
3825
+ } else if (Array.isArray(typeOrValue)) {
3826
+ schemaType = "array";
3827
+ hasDefaultValue = true;
3828
+ defaultValue = typeOrValue;
3829
+ } else if (valueType === "object" && typeOrValue !== null) {
3830
+ schemaType = "object";
3831
+ hasDefaultValue = true;
3832
+ defaultValue = typeOrValue;
3833
+ } else {
3834
+ const typeStr = String(typeOrValue).toLowerCase().trim();
3835
+ if (typeStr === "string" || typeStr === "str") {
3836
+ schemaType = "string";
3837
+ } else if (typeStr === "number" || typeStr === "num" || typeStr === "float" || typeStr === "double") {
3838
+ schemaType = "number";
3839
+ } else if (typeStr === "integer" || typeStr === "int") {
3840
+ schemaType = "integer";
3841
+ } else if (typeStr === "boolean" || typeStr === "bool") {
3842
+ schemaType = "boolean";
3843
+ } else if (typeStr === "array" || typeStr === "list") {
3844
+ schemaType = "array";
3845
+ } else if (typeStr === "object" || typeStr === "dict") {
3846
+ schemaType = "object";
3847
+ } else {
3848
+ schemaType = "string";
3849
+ hasDefaultValue = true;
3850
+ defaultValue = typeOrValue;
3851
+ }
3852
+ }
3853
+ const propertySchema = {
3854
+ type: schemaType,
3855
+ description: `${key} parameter for ${tool.name}`
3856
+ };
3857
+ if (hasDefaultValue) {
3858
+ propertySchema.default = defaultValue;
3859
+ } else {
3860
+ required.push(key);
3861
+ }
3862
+ properties[key] = propertySchema;
3863
+ });
3864
+ const inputSchema = {
3865
+ type: "object",
3866
+ properties,
3867
+ additionalProperties: false
3868
+ };
3869
+ if (required.length > 0) {
3870
+ inputSchema.required = required;
3871
+ }
3872
+ tools.push({
3873
+ name: tool.id,
3874
+ description: tool.description,
3875
+ input_schema: inputSchema
3876
+ });
3877
+ });
3878
+ logger.info(`[${this.getProviderName()}] Added ${externalTools.length} external tools to tool calling capability`);
3879
+ logger.info(`[${this.getProviderName()}] Complete tools array:`, JSON.stringify(tools, null, 2));
3880
+ }
4156
3881
  const queryAttempts = /* @__PURE__ */ new Map();
4157
3882
  const MAX_QUERY_ATTEMPTS = 6;
3883
+ const toolAttempts = /* @__PURE__ */ new Map();
3884
+ const MAX_TOOL_ATTEMPTS = 3;
4158
3885
  let maxAttemptsReached = false;
4159
3886
  let fullStreamedText = "";
4160
3887
  const wrappedStreamCallback = streamCallback ? (chunk) => {
@@ -4296,8 +4023,75 @@ ${errorMsg}
4296
4023
  }
4297
4024
  throw new Error(`Query execution failed: ${errorMsg}`);
4298
4025
  }
4026
+ } else {
4027
+ const externalTool = externalTools?.find((t) => t.id === toolName);
4028
+ if (externalTool) {
4029
+ const attempts = (toolAttempts.get(toolName) || 0) + 1;
4030
+ toolAttempts.set(toolName, attempts);
4031
+ logger.info(`[${this.getProviderName()}] Executing external tool: ${externalTool.name} (attempt ${attempts}/${MAX_TOOL_ATTEMPTS})`);
4032
+ logCollector?.info(`Executing external tool: ${externalTool.name} (attempt ${attempts}/${MAX_TOOL_ATTEMPTS})...`);
4033
+ if (attempts > MAX_TOOL_ATTEMPTS) {
4034
+ const errorMsg = `Maximum attempts (${MAX_TOOL_ATTEMPTS}) reached for tool: ${externalTool.name}`;
4035
+ logger.error(`[${this.getProviderName()}] ${errorMsg}`);
4036
+ logCollector?.error(errorMsg);
4037
+ if (wrappedStreamCallback) {
4038
+ wrappedStreamCallback(`
4039
+
4040
+ \u274C ${errorMsg}
4041
+
4042
+ Please try rephrasing your request or contact support.
4043
+
4044
+ `);
4045
+ }
4046
+ throw new Error(errorMsg);
4047
+ }
4048
+ try {
4049
+ if (wrappedStreamCallback) {
4050
+ if (attempts === 1) {
4051
+ wrappedStreamCallback(`
4052
+
4053
+ \u{1F517} **Executing ${externalTool.name}...**
4054
+
4055
+ `);
4056
+ } else {
4057
+ wrappedStreamCallback(`
4058
+
4059
+ \u{1F504} **Retrying ${externalTool.name} (attempt ${attempts}/${MAX_TOOL_ATTEMPTS})...**
4060
+
4061
+ `);
4062
+ }
4063
+ }
4064
+ const result2 = await externalTool.fn(toolInput);
4065
+ logger.info(`[${this.getProviderName()}] External tool ${externalTool.name} executed successfully`);
4066
+ logCollector?.info(`\u2713 ${externalTool.name} executed successfully`);
4067
+ if (wrappedStreamCallback) {
4068
+ wrappedStreamCallback(`\u2705 **${externalTool.name} completed successfully**
4069
+
4070
+ `);
4071
+ }
4072
+ return JSON.stringify(result2, null, 2);
4073
+ } catch (error) {
4074
+ const errorMsg = error instanceof Error ? error.message : String(error);
4075
+ logger.error(`[${this.getProviderName()}] External tool ${externalTool.name} failed (attempt ${attempts}/${MAX_TOOL_ATTEMPTS}): ${errorMsg}`);
4076
+ logCollector?.error(`\u2717 ${externalTool.name} failed: ${errorMsg}`);
4077
+ if (wrappedStreamCallback) {
4078
+ wrappedStreamCallback(`\u274C **${externalTool.name} failed:**
4079
+ \`\`\`
4080
+ ${errorMsg}
4081
+ \`\`\`
4082
+
4083
+ `);
4084
+ if (attempts < MAX_TOOL_ATTEMPTS) {
4085
+ wrappedStreamCallback(`\u{1F527} **Retrying with adjusted parameters...**
4086
+
4087
+ `);
4088
+ }
4089
+ }
4090
+ throw new Error(`Tool execution failed: ${errorMsg}`);
4091
+ }
4092
+ }
4093
+ throw new Error(`Unknown tool: ${toolName}`);
4299
4094
  }
4300
- throw new Error(`Unknown tool: ${toolName}`);
4301
4095
  };
4302
4096
  const result = await LLM.streamWithTools(
4303
4097
  {
@@ -4314,8 +4108,8 @@ ${errorMsg}
4314
4108
  partial: wrappedStreamCallback
4315
4109
  // Pass the wrapped streaming callback to LLM
4316
4110
  },
4317
- 10
4318
- // max iterations: allows for 6 retries + final response + buffer
4111
+ 20
4112
+ // max iterations: allows for 6 query retries + 3 tool retries + final response + buffer
4319
4113
  );
4320
4114
  logger.info(`[${this.getProviderName()}] Text response stream completed`);
4321
4115
  const textResponse = fullStreamedText || result || "I apologize, but I was unable to generate a response.";
@@ -4370,24 +4164,22 @@ ${errorMsg}
4370
4164
  }
4371
4165
  let container_componet = null;
4372
4166
  if (matchedComponents.length > 0) {
4167
+ logger.info(`[${this.getProviderName()}] Created MultiComponentContainer: "${layoutTitle}" with ${matchedComponents.length} components and ${actions.length} actions`);
4168
+ logCollector?.info(`Created dashboard: "${layoutTitle}" with ${matchedComponents.length} components and ${actions.length} actions`);
4373
4169
  container_componet = {
4374
- id: `multi_container_${Date.now()}`,
4170
+ id: `container_${Date.now()}`,
4375
4171
  name: "MultiComponentContainer",
4376
4172
  type: "Container",
4377
4173
  description: layoutDescription,
4378
- category: "dynamic",
4379
- keywords: ["dashboard", "layout", "container"],
4380
4174
  props: {
4381
4175
  config: {
4382
- components: matchedComponents,
4383
4176
  title: layoutTitle,
4384
- description: layoutDescription
4177
+ description: layoutDescription,
4178
+ components: matchedComponents
4385
4179
  },
4386
4180
  actions
4387
4181
  }
4388
4182
  };
4389
- logger.info(`[${this.getProviderName()}] Created MultiComponentContainer: "${layoutTitle}" with ${matchedComponents.length} components and ${actions.length} actions`);
4390
- logCollector?.info(`Created dashboard: "${layoutTitle}" with ${matchedComponents.length} components and ${actions.length} actions`);
4391
4183
  }
4392
4184
  return {
4393
4185
  success: true,
@@ -4418,201 +4210,134 @@ ${errorMsg}
4418
4210
  }
4419
4211
  }
4420
4212
  /**
4421
- * Generate component response for user question
4422
- * This provides conversational component suggestions based on user question
4423
- * Supports component generation and matching
4213
+ * Main orchestration function with semantic search and multi-step classification
4214
+ * NEW FLOW (Recommended):
4215
+ * 1. Semantic search: Check previous conversations (>60% match)
4216
+ * - If match found → Adapt UI block parameters and return
4217
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
4218
+ * 3. Route appropriately based on category and response mode
4219
+ *
4220
+ * @param responseMode - 'component' for component generation (default), 'text' for text responses
4221
+ * @param streamCallback - Optional callback function to receive text chunks as they stream (only for text mode)
4222
+ * @param collections - Collection registry for executing database queries (required for text mode)
4223
+ * @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called (only for text mode)
4424
4224
  */
4425
- async generateComponentResponse(userPrompt, components, apiKey, logCollector, conversationHistory) {
4426
- const errors = [];
4225
+ async handleUserRequest(userPrompt, components, apiKey, logCollector, conversationHistory, responseMode = "text", streamCallback, collections, externalTools, userId) {
4226
+ const startTime = Date.now();
4227
+ logger.info(`[${this.getProviderName()}] handleUserRequest called with responseMode: ${responseMode}`);
4228
+ logCollector?.info(`Starting request processing with mode: ${responseMode}`);
4427
4229
  try {
4428
- logger.info(`[${this.getProviderName()}] Using component response mode`);
4429
- const classifyMsg = "Classifying user question...";
4430
- logCollector?.info(classifyMsg);
4431
- const classification = await this.classifyUserQuestion(userPrompt, apiKey, logCollector, conversationHistory);
4432
- const classInfo = `Question type: ${classification.questionType}, Visualizations: ${classification.visualizations.join(", ") || "None"}, Multiple components: ${classification.needsMultipleComponents}`;
4433
- logCollector?.info(classInfo);
4434
- if (classification.questionType === "analytical") {
4435
- if (classification.visualizations.length > 1) {
4436
- const multiMsg = `Matching ${classification.visualizations.length} components for types: ${classification.visualizations.join(", ")}`;
4437
- logCollector?.info(multiMsg);
4438
- const componentPromises = classification.visualizations.map((vizType) => {
4439
- logCollector?.info(`Matching component for type: ${vizType}`);
4440
- return this.generateAnalyticalComponent(
4441
- userPrompt,
4442
- components,
4443
- vizType,
4444
- apiKey,
4445
- logCollector,
4446
- conversationHistory
4447
- ).then((result) => ({ vizType, result }));
4448
- });
4449
- const settledResults = await Promise.allSettled(componentPromises);
4450
- const matchedComponents = [];
4451
- for (const settledResult of settledResults) {
4452
- if (settledResult.status === "fulfilled") {
4453
- const { vizType, result } = settledResult.value;
4454
- if (result.component) {
4455
- matchedComponents.push(result.component);
4456
- logCollector?.info(`Matched: ${result.component.name}`);
4457
- logger.info("Component : ", result.component.name, " props: ", result.component.props);
4458
- } else {
4459
- logCollector?.warn(`Failed to match component for type: ${vizType}`);
4460
- }
4461
- } else {
4462
- logCollector?.warn(`Error matching component: ${settledResult.reason?.message || "Unknown error"}`);
4463
- }
4464
- }
4465
- logger.debug(`[${this.getProviderName()}] Matched ${matchedComponents.length} components for multi-component container`);
4466
- if (matchedComponents.length === 0) {
4467
- return {
4468
- success: true,
4469
- data: {
4470
- component: null,
4471
- reasoning: "Failed to match any components for the requested visualization types",
4472
- method: "classification-multi-failed",
4473
- questionType: classification.questionType,
4474
- needsMultipleComponents: true,
4475
- propsModified: false,
4476
- queryModified: false
4477
- },
4478
- errors: []
4479
- };
4480
- }
4481
- logCollector?.info("Generating container metadata...");
4482
- const containerMetadata = await this.generateContainerMetadata(
4483
- userPrompt,
4484
- classification.visualizations,
4485
- apiKey,
4486
- logCollector,
4487
- conversationHistory
4488
- );
4489
- const containerComponent = {
4490
- id: `multi_container_${Date.now()}`,
4491
- name: "MultiComponentContainer",
4492
- type: "Container",
4493
- description: containerMetadata.description,
4494
- category: "dynamic",
4495
- keywords: ["multi", "container", "dashboard"],
4496
- props: {
4497
- config: {
4498
- components: matchedComponents,
4499
- layout: "grid",
4500
- spacing: 24,
4501
- title: containerMetadata.title,
4502
- description: containerMetadata.description
4503
- }
4504
- }
4505
- };
4506
- logCollector?.info(`Created multi-component container with ${matchedComponents.length} components: "${containerMetadata.title}"`);
4230
+ logger.info(`[${this.getProviderName()}] Step 1: Searching previous conversations...`);
4231
+ logCollector?.info("Step 1: Searching for similar previous conversations...");
4232
+ const conversationMatch = await conversation_search_default.searchConversations({
4233
+ userPrompt,
4234
+ collections,
4235
+ userId,
4236
+ similarityThreshold: 0.6
4237
+ // 60% threshold
4238
+ });
4239
+ logger.info("conversationMatch:", conversationMatch);
4240
+ if (conversationMatch) {
4241
+ logger.info(
4242
+ `[${this.getProviderName()}] \u2713 Found matching conversation with ${(conversationMatch.similarity * 100).toFixed(2)}% similarity`
4243
+ );
4244
+ logCollector?.info(
4245
+ `\u2713 Found similar conversation (${(conversationMatch.similarity * 100).toFixed(2)}% match)`
4246
+ );
4247
+ if (conversationMatch.similarity >= 0.99) {
4248
+ const elapsedTime2 = Date.now() - startTime;
4249
+ logger.info(`[${this.getProviderName()}] \u2713 100% match - returning UI block directly without adaptation`);
4250
+ logCollector?.info(`\u2713 Exact match (${(conversationMatch.similarity * 100).toFixed(2)}%) - returning cached result`);
4251
+ logCollector?.info(`Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4252
+ const component = conversationMatch.uiBlock?.generatedComponentMetadata || conversationMatch.uiBlock?.component;
4507
4253
  return {
4508
4254
  success: true,
4509
4255
  data: {
4510
- component: containerComponent,
4511
- reasoning: `Matched ${matchedComponents.length} components for visualization types: ${classification.visualizations.join(", ")}`,
4512
- method: "classification-multi-generated",
4513
- questionType: classification.questionType,
4514
- needsMultipleComponents: true,
4515
- propsModified: false,
4516
- queryModified: false
4256
+ component,
4257
+ reasoning: `Exact match from previous conversation (${(conversationMatch.similarity * 100).toFixed(2)}% similarity)`,
4258
+ method: `${this.getProviderName()}-semantic-match-exact`,
4259
+ semanticSimilarity: conversationMatch.similarity
4517
4260
  },
4518
4261
  errors: []
4519
4262
  };
4520
- } else if (classification.visualizations.length === 1) {
4521
- const vizType = classification.visualizations[0];
4522
- logCollector?.info(`Matching single component for type: ${vizType}`);
4523
- const result = await this.generateAnalyticalComponent(userPrompt, components, vizType, apiKey, logCollector, conversationHistory);
4263
+ }
4264
+ logCollector?.info(`Adapting parameters for similar question...`);
4265
+ const originalPrompt = conversationMatch.metadata?.userPrompt || "Previous question";
4266
+ const adaptResult = await this.adaptUIBlockParameters(
4267
+ userPrompt,
4268
+ originalPrompt,
4269
+ conversationMatch.uiBlock,
4270
+ apiKey,
4271
+ logCollector
4272
+ );
4273
+ if (adaptResult.success && adaptResult.adaptedComponent) {
4274
+ const elapsedTime2 = Date.now() - startTime;
4275
+ logger.info(`[${this.getProviderName()}] \u2713 Successfully adapted UI block parameters`);
4276
+ logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4277
+ logCollector?.info(`\u2713 UI block adapted successfully`);
4278
+ logCollector?.info(`Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4524
4279
  return {
4525
4280
  success: true,
4526
4281
  data: {
4527
- component: result.component,
4528
- reasoning: result.reasoning,
4529
- method: "classification-generated",
4530
- questionType: classification.questionType,
4531
- needsMultipleComponents: false,
4532
- propsModified: false,
4533
- queryModified: false
4282
+ component: adaptResult.adaptedComponent,
4283
+ reasoning: `Adapted from previous conversation: ${originalPrompt}`,
4284
+ method: `${this.getProviderName()}-semantic-match`,
4285
+ semanticSimilarity: conversationMatch.similarity,
4286
+ parametersChanged: adaptResult.parametersChanged
4534
4287
  },
4535
4288
  errors: []
4536
4289
  };
4537
4290
  } else {
4538
- logCollector?.info("No specific visualization type - matching from all components");
4539
- const result = await this.generateAnalyticalComponent(userPrompt, components, void 0, apiKey, logCollector, conversationHistory);
4540
- return {
4541
- success: true,
4542
- data: {
4543
- component: result.component,
4544
- reasoning: result.reasoning,
4545
- method: "classification-generated-auto",
4546
- questionType: classification.questionType,
4547
- needsMultipleComponents: false,
4548
- propsModified: false,
4549
- queryModified: false
4550
- },
4551
- errors: []
4552
- };
4291
+ logger.info(`[${this.getProviderName()}] Could not adapt matched conversation, continuing to category classification`);
4292
+ logCollector?.warn(`Could not adapt matched conversation: ${adaptResult.explanation}`);
4553
4293
  }
4554
- } else if (classification.questionType === "data_modification" || classification.questionType === "general") {
4555
- const matchMsg = "Using component matching for data modification...";
4556
- logCollector?.info(matchMsg);
4557
- const matchResult = await this.matchComponent(userPrompt, components, apiKey, logCollector, conversationHistory);
4558
- return {
4559
- success: true,
4560
- data: {
4561
- component: matchResult.component,
4562
- reasoning: matchResult.reasoning,
4563
- method: "classification-matched",
4564
- questionType: classification.questionType,
4565
- needsMultipleComponents: false,
4566
- propsModified: matchResult.propsModified,
4567
- queryModified: matchResult.queryModified
4568
- },
4569
- errors: []
4570
- };
4571
4294
  } else {
4572
- logCollector?.info("General question - no component needed");
4573
- return {
4574
- success: true,
4575
- data: {
4576
- component: null,
4577
- reasoning: "General question - no component needed",
4578
- method: "classification-general",
4579
- questionType: classification.questionType,
4580
- needsMultipleComponents: false,
4581
- propsModified: false,
4582
- queryModified: false
4583
- },
4584
- errors: []
4585
- };
4295
+ logger.info(`[${this.getProviderName()}] No matching previous conversations found, proceeding to category classification`);
4296
+ logCollector?.info("No similar previous conversations found. Proceeding to category classification...");
4297
+ }
4298
+ logger.info(`[${this.getProviderName()}] Step 2: Classifying question category...`);
4299
+ logCollector?.info("Step 2: Classifying question category...");
4300
+ const categoryClassification = await this.classifyQuestionCategory(
4301
+ userPrompt,
4302
+ apiKey,
4303
+ logCollector,
4304
+ conversationHistory,
4305
+ externalTools
4306
+ );
4307
+ logger.info(
4308
+ `[${this.getProviderName()}] Question classified as: ${categoryClassification.category} (confidence: ${categoryClassification.confidence}%)`
4309
+ );
4310
+ logCollector?.info(
4311
+ `Category: ${categoryClassification.category} | Confidence: ${categoryClassification.confidence}%`
4312
+ );
4313
+ let toolsToUse = [];
4314
+ if (categoryClassification.externalTools && categoryClassification.externalTools.length > 0) {
4315
+ logger.info(`[${this.getProviderName()}] Identified ${categoryClassification.externalTools.length} external tools needed`);
4316
+ logCollector?.info(`Identified external tools: ${categoryClassification.externalTools.map((t) => t.name || t.type).join(", ")}`);
4317
+ toolsToUse = categoryClassification.externalTools?.map((t) => ({
4318
+ id: t.type,
4319
+ name: t.name,
4320
+ description: t.description,
4321
+ params: t.parameters || {},
4322
+ fn: (() => {
4323
+ const realTool = externalTools?.find((tool) => tool.id === t.type);
4324
+ if (realTool) {
4325
+ logger.info(`[${this.getProviderName()}] Using real tool implementation for ${t.type}`);
4326
+ return realTool.fn;
4327
+ } else {
4328
+ logger.warn(`[${this.getProviderName()}] Tool ${t.type} not found in registered tools`);
4329
+ return async () => ({ success: false, message: `Tool ${t.name || t.type} not registered` });
4330
+ }
4331
+ })()
4332
+ })) || [];
4333
+ }
4334
+ if (categoryClassification.category === "data_analysis") {
4335
+ logger.info(`[${this.getProviderName()}] Routing to data analysis (SELECT operations)`);
4336
+ logCollector?.info("Routing to data analysis...");
4337
+ } else if (categoryClassification.category === "data_modification") {
4338
+ logger.info(`[${this.getProviderName()}] Routing to data modification (INSERT/UPDATE/DELETE operations)`);
4339
+ logCollector?.info("Routing to data modification...");
4586
4340
  }
4587
- } catch (error) {
4588
- const errorMsg = error instanceof Error ? error.message : String(error);
4589
- logger.error(`[${this.getProviderName()}] Error generating component response: ${errorMsg}`);
4590
- logger.debug(`[${this.getProviderName()}] Component response generation error details:`, error);
4591
- logCollector?.error(`Error generating component response: ${errorMsg}`);
4592
- errors.push(errorMsg);
4593
- return {
4594
- success: false,
4595
- errors,
4596
- data: void 0
4597
- };
4598
- }
4599
- }
4600
- /**
4601
- * Main orchestration function that classifies question and routes to appropriate handler
4602
- * This is the NEW recommended entry point for handling user requests
4603
- * Supports both component generation and text response modes
4604
- *
4605
- * @param responseMode - 'component' for component generation (default), 'text' for text responses
4606
- * @param streamCallback - Optional callback function to receive text chunks as they stream (only for text mode)
4607
- * @param collections - Collection registry for executing database queries (required for text mode)
4608
- * @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called (only for text mode)
4609
- */
4610
- async handleUserRequest(userPrompt, components, apiKey, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools) {
4611
- const startTime = Date.now();
4612
- logger.info(`[${this.getProviderName()}] handleUserRequest called with responseMode: ${responseMode}`);
4613
- if (responseMode === "text") {
4614
- logger.info(`[${this.getProviderName()}] Using text response mode`);
4615
- logCollector?.info("Generating text response...");
4616
4341
  const textResponse = await this.generateTextResponse(
4617
4342
  userPrompt,
4618
4343
  apiKey,
@@ -4621,40 +4346,29 @@ ${errorMsg}
4621
4346
  streamCallback,
4622
4347
  collections,
4623
4348
  components,
4624
- externalTools
4349
+ toolsToUse
4625
4350
  );
4626
- if (!textResponse.success) {
4627
- const elapsedTime3 = Date.now() - startTime;
4628
- logger.error(`[${this.getProviderName()}] Text response generation failed`);
4629
- logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime3}ms (${(elapsedTime3 / 1e3).toFixed(2)}s)`);
4630
- logCollector?.info(`Total time taken: ${elapsedTime3}ms (${(elapsedTime3 / 1e3).toFixed(2)}s)`);
4631
- return textResponse;
4632
- }
4633
- const elapsedTime2 = Date.now() - startTime;
4634
- logger.info(`[${this.getProviderName()}] Text response generated successfully`);
4635
- logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4636
- logCollector?.info(`Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4351
+ const elapsedTime = Date.now() - startTime;
4352
+ logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4353
+ logCollector?.info(`Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4637
4354
  return textResponse;
4355
+ } catch (error) {
4356
+ const errorMsg = error instanceof Error ? error.message : String(error);
4357
+ logger.error(`[${this.getProviderName()}] Error in handleUserRequest: ${errorMsg}`);
4358
+ logger.debug(`[${this.getProviderName()}] Error details:`, error);
4359
+ logCollector?.error(`Error processing request: ${errorMsg}`);
4360
+ const elapsedTime = Date.now() - startTime;
4361
+ logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4362
+ logCollector?.info(`Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4363
+ return {
4364
+ success: false,
4365
+ errors: [errorMsg],
4366
+ data: {
4367
+ text: "I apologize, but I encountered an error processing your request. Please try again.",
4368
+ method: `${this.getProviderName()}-orchestration-error`
4369
+ }
4370
+ };
4638
4371
  }
4639
- const componentResponse = await this.generateComponentResponse(
4640
- userPrompt,
4641
- components,
4642
- apiKey,
4643
- logCollector,
4644
- conversationHistory
4645
- );
4646
- if (!componentResponse.success) {
4647
- const elapsedTime2 = Date.now() - startTime;
4648
- logger.error(`[${this.getProviderName()}] Component response generation failed`);
4649
- logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4650
- logCollector?.info(`Total time taken: ${elapsedTime2}ms (${(elapsedTime2 / 1e3).toFixed(2)}s)`);
4651
- return componentResponse;
4652
- }
4653
- const elapsedTime = Date.now() - startTime;
4654
- logger.info(`[${this.getProviderName()}] Component response generated successfully`);
4655
- logger.info(`[${this.getProviderName()}] Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4656
- logCollector?.info(`Total time taken: ${elapsedTime}ms (${(elapsedTime / 1e3).toFixed(2)}s)`);
4657
- return componentResponse;
4658
4372
  }
4659
4373
  /**
4660
4374
  * Generate next questions that the user might ask based on the original prompt and generated component
@@ -4767,7 +4481,7 @@ function getLLMProviders() {
4767
4481
  return DEFAULT_PROVIDERS;
4768
4482
  }
4769
4483
  }
4770
- var useAnthropicMethod = async (prompt, components, apiKey, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools) => {
4484
+ var useAnthropicMethod = async (prompt, components, apiKey, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools, userId) => {
4771
4485
  logger.debug("[useAnthropicMethod] Initializing Anthropic Claude matching method");
4772
4486
  logger.debug(`[useAnthropicMethod] Response mode: ${responseMode}`);
4773
4487
  const msg = `Using Anthropic Claude ${responseMode === "text" ? "text response" : "matching"} method...`;
@@ -4779,11 +4493,11 @@ var useAnthropicMethod = async (prompt, components, apiKey, logCollector, conver
4779
4493
  return { success: false, errors: [emptyMsg] };
4780
4494
  }
4781
4495
  logger.debug(`[useAnthropicMethod] Processing with ${components.length} components`);
4782
- const matchResult = await anthropicLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools);
4496
+ const matchResult = await anthropicLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools, userId);
4783
4497
  logger.info(`[useAnthropicMethod] Successfully generated ${responseMode} using Anthropic`);
4784
4498
  return matchResult;
4785
4499
  };
4786
- var useGroqMethod = async (prompt, components, apiKey, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools) => {
4500
+ var useGroqMethod = async (prompt, components, apiKey, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools, userId) => {
4787
4501
  logger.debug("[useGroqMethod] Initializing Groq LLM matching method");
4788
4502
  logger.debug(`[useGroqMethod] Response mode: ${responseMode}`);
4789
4503
  const msg = `Using Groq LLM ${responseMode === "text" ? "text response" : "matching"} method...`;
@@ -4796,14 +4510,14 @@ var useGroqMethod = async (prompt, components, apiKey, logCollector, conversatio
4796
4510
  return { success: false, errors: [emptyMsg] };
4797
4511
  }
4798
4512
  logger.debug(`[useGroqMethod] Processing with ${components.length} components`);
4799
- const matchResult = await groqLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools);
4513
+ const matchResult = await groqLLM.handleUserRequest(prompt, components, apiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools, userId);
4800
4514
  logger.info(`[useGroqMethod] Successfully generated ${responseMode} using Groq`);
4801
4515
  return matchResult;
4802
4516
  };
4803
4517
  var getUserResponseFromCache = async (prompt) => {
4804
4518
  return false;
4805
4519
  };
4806
- var get_user_response = async (prompt, components, anthropicApiKey, groqApiKey, llmProviders, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools) => {
4520
+ var get_user_response = async (prompt, components, anthropicApiKey, groqApiKey, llmProviders, logCollector, conversationHistory, responseMode = "component", streamCallback, collections, externalTools, userId) => {
4807
4521
  logger.debug(`[get_user_response] Starting user response generation for prompt: "${prompt.substring(0, 50)}..."`);
4808
4522
  logger.debug(`[get_user_response] Response mode: ${responseMode}`);
4809
4523
  logger.debug("[get_user_response] Checking cache for existing response");
@@ -4836,9 +4550,9 @@ var get_user_response = async (prompt, components, anthropicApiKey, groqApiKey,
4836
4550
  logCollector?.info(attemptMsg);
4837
4551
  let result;
4838
4552
  if (provider === "anthropic") {
4839
- result = await useAnthropicMethod(prompt, components, anthropicApiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools);
4553
+ result = await useAnthropicMethod(prompt, components, anthropicApiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools, userId);
4840
4554
  } else if (provider === "groq") {
4841
- result = await useGroqMethod(prompt, components, groqApiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools);
4555
+ result = await useGroqMethod(prompt, components, groqApiKey, logCollector, conversationHistory, responseMode, streamCallback, collections, externalTools, userId);
4842
4556
  } else {
4843
4557
  logger.warn(`[get_user_response] Unknown provider: ${provider} - skipping`);
4844
4558
  errors.push(`Unknown provider: ${provider}`);
@@ -5055,6 +4769,111 @@ var UILogCollector = class {
5055
4769
  }
5056
4770
  };
5057
4771
 
4772
+ // src/utils/conversation-saver.ts
4773
+ async function saveConversation(params) {
4774
+ const { userId, userPrompt, uiblock, uiBlockId, threadId, collections } = params;
4775
+ if (!userId) {
4776
+ logger.warn("[CONVERSATION_SAVER] Skipping save: userId not provided");
4777
+ return {
4778
+ success: false,
4779
+ error: "userId is required"
4780
+ };
4781
+ }
4782
+ if (!userPrompt) {
4783
+ logger.warn("[CONVERSATION_SAVER] Skipping save: userPrompt not provided");
4784
+ return {
4785
+ success: false,
4786
+ error: "userPrompt is required"
4787
+ };
4788
+ }
4789
+ if (!uiblock) {
4790
+ logger.warn("[CONVERSATION_SAVER] Skipping save: uiblock not provided");
4791
+ return {
4792
+ success: false,
4793
+ error: "uiblock is required"
4794
+ };
4795
+ }
4796
+ if (!threadId) {
4797
+ logger.warn("[CONVERSATION_SAVER] Skipping save: threadId not provided");
4798
+ return {
4799
+ success: false,
4800
+ error: "threadId is required"
4801
+ };
4802
+ }
4803
+ if (!uiBlockId) {
4804
+ logger.warn("[CONVERSATION_SAVER] Skipping save: uiBlockId not provided");
4805
+ return {
4806
+ success: false,
4807
+ error: "uiBlockId is required"
4808
+ };
4809
+ }
4810
+ if (!collections?.["user-conversations"]?.["create"]) {
4811
+ logger.debug('[CONVERSATION_SAVER] Collection "user-conversations.create" not available, skipping save');
4812
+ return {
4813
+ success: false,
4814
+ error: "user-conversations.create collection not available"
4815
+ };
4816
+ }
4817
+ try {
4818
+ logger.info(`[CONVERSATION_SAVER] Saving conversation for userId: ${userId}, uiBlockId: ${uiBlockId}, threadId: ${threadId}`);
4819
+ const userIdNumber = Number(userId);
4820
+ if (isNaN(userIdNumber)) {
4821
+ logger.warn(`[CONVERSATION_SAVER] Invalid userId: ${userId} (not a valid number)`);
4822
+ return {
4823
+ success: false,
4824
+ error: `Invalid userId: ${userId} (not a valid number)`
4825
+ };
4826
+ }
4827
+ const saveResult = await collections["user-conversations"]["create"]({
4828
+ userId: userIdNumber,
4829
+ userPrompt,
4830
+ uiblock,
4831
+ threadId
4832
+ });
4833
+ if (!saveResult?.success) {
4834
+ logger.warn(`[CONVERSATION_SAVER] Failed to save conversation to PostgreSQL: ${saveResult?.message || "Unknown error"}`);
4835
+ return {
4836
+ success: false,
4837
+ error: saveResult?.message || "Unknown error from backend"
4838
+ };
4839
+ }
4840
+ logger.info(`[CONVERSATION_SAVER] Successfully saved conversation to PostgreSQL, id: ${saveResult.data?.id}`);
4841
+ if (collections?.["conversation-history"]?.["embed"]) {
4842
+ try {
4843
+ logger.info("[CONVERSATION_SAVER] Creating embedding for semantic search...");
4844
+ const embedResult = await collections["conversation-history"]["embed"]({
4845
+ uiBlockId,
4846
+ userPrompt,
4847
+ uiBlock: uiblock,
4848
+ userId: userIdNumber
4849
+ });
4850
+ if (embedResult?.success) {
4851
+ logger.info("[CONVERSATION_SAVER] Successfully created embedding");
4852
+ } else {
4853
+ logger.warn("[CONVERSATION_SAVER] Failed to create embedding:", embedResult?.error || "Unknown error");
4854
+ }
4855
+ } catch (embedError) {
4856
+ const embedErrorMsg = embedError instanceof Error ? embedError.message : String(embedError);
4857
+ logger.warn("[CONVERSATION_SAVER] Error creating embedding:", embedErrorMsg);
4858
+ }
4859
+ } else {
4860
+ logger.debug("[CONVERSATION_SAVER] Embedding collection not available, skipping ChromaDB storage");
4861
+ }
4862
+ return {
4863
+ success: true,
4864
+ conversationId: saveResult.data?.id,
4865
+ message: "Conversation saved successfully"
4866
+ };
4867
+ } catch (error) {
4868
+ const errorMessage = error instanceof Error ? error.message : String(error);
4869
+ logger.error("[CONVERSATION_SAVER] Error saving conversation:", errorMessage);
4870
+ return {
4871
+ success: false,
4872
+ error: errorMessage
4873
+ };
4874
+ }
4875
+ }
4876
+
5058
4877
  // src/config/context.ts
5059
4878
  var CONTEXT_CONFIG = {
5060
4879
  /**
@@ -5066,7 +4885,7 @@ var CONTEXT_CONFIG = {
5066
4885
  };
5067
4886
 
5068
4887
  // src/handlers/user-prompt-request.ts
5069
- var get_user_request = async (data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools) => {
4888
+ var get_user_request = async (data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools, userId) => {
5070
4889
  const errors = [];
5071
4890
  logger.debug("[USER_PROMPT_REQ] Parsing incoming message data");
5072
4891
  const parseResult = UserPromptRequestMessageSchema.safeParse(data);
@@ -5147,7 +4966,8 @@ var get_user_request = async (data, components, sendMessage, anthropicApiKey, gr
5147
4966
  responseMode,
5148
4967
  streamCallback,
5149
4968
  collections,
5150
- externalTools
4969
+ externalTools,
4970
+ userId
5151
4971
  );
5152
4972
  logCollector.info("User prompt request completed");
5153
4973
  const uiBlockId = existingUiBlockId;
@@ -5198,6 +5018,34 @@ var get_user_request = async (data, components, sendMessage, anthropicApiKey, gr
5198
5018
  }
5199
5019
  thread.addUIBlock(uiBlock);
5200
5020
  logger.info(`Created UIBlock: ${uiBlockId} in Thread: ${threadId}`);
5021
+ if (userId) {
5022
+ const responseMethod = userResponse.data?.method || "";
5023
+ const semanticSimilarity = userResponse.data?.semanticSimilarity || 0;
5024
+ const isExactMatch = responseMethod.includes("semantic-match") && semanticSimilarity >= 0.99;
5025
+ if (isExactMatch) {
5026
+ logger.info(
5027
+ `Skipping conversation save - response from exact semantic match (${(semanticSimilarity * 100).toFixed(2)}% similarity)`
5028
+ );
5029
+ logCollector.info(
5030
+ `Using exact cached result (${(semanticSimilarity * 100).toFixed(2)}% match) - not saving duplicate conversation`
5031
+ );
5032
+ } else {
5033
+ const uiBlockData = uiBlock.toJSON();
5034
+ const saveResult = await saveConversation({
5035
+ userId,
5036
+ userPrompt: prompt,
5037
+ uiblock: uiBlockData,
5038
+ uiBlockId,
5039
+ threadId,
5040
+ collections
5041
+ });
5042
+ if (saveResult.success) {
5043
+ logger.info(`Conversation saved with ID: ${saveResult.conversationId}`);
5044
+ } else {
5045
+ logger.warn(`Failed to save conversation: ${saveResult.error}`);
5046
+ }
5047
+ }
5048
+ }
5201
5049
  return {
5202
5050
  success: userResponse.success,
5203
5051
  data: userResponse.data,
@@ -5208,8 +5056,8 @@ var get_user_request = async (data, components, sendMessage, anthropicApiKey, gr
5208
5056
  wsId
5209
5057
  };
5210
5058
  };
5211
- async function handleUserPromptRequest(data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools) {
5212
- const response = await get_user_request(data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools);
5059
+ async function handleUserPromptRequest(data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools, userId) {
5060
+ const response = await get_user_request(data, components, sendMessage, anthropicApiKey, groqApiKey, llmProviders, collections, externalTools, userId);
5213
5061
  sendDataResponse4(
5214
5062
  response.id || data.id,
5215
5063
  {
@@ -7439,7 +7287,7 @@ var SuperatomSDK = class {
7439
7287
  });
7440
7288
  break;
7441
7289
  case "USER_PROMPT_REQ":
7442
- handleUserPromptRequest(parsed, this.components, (msg) => this.send(msg), this.anthropicApiKey, this.groqApiKey, this.llmProviders, this.collections, this.tools).catch((error) => {
7290
+ handleUserPromptRequest(parsed, this.components, (msg) => this.send(msg), this.anthropicApiKey, this.groqApiKey, this.llmProviders, this.collections, this.tools, this.userId).catch((error) => {
7443
7291
  logger.error("Failed to handle user prompt request:", error);
7444
7292
  });
7445
7293
  break;