@aivue/tabular-intelligence 1.0.0 → 1.1.0

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/README.md CHANGED
@@ -8,15 +8,29 @@
8
8
  ## đŸŽ¯ Features
9
9
 
10
10
  - 🔌 **Generic TFM Client** - Connect to any HTTP-based Tabular Foundation Model API
11
+ - đŸ’Ŧ **Natural Language Q&A** - Ask questions about your data in plain English
11
12
  - 📊 **Descriptive Statistics** - Mean, median, mode, std dev, percentiles, distributions
12
13
  - 🚨 **Anomaly Detection** - Statistical and ML-based outlier detection
13
14
  - đŸŽ¯ **Segmentation & Clustering** - K-means, DBSCAN, hierarchical clustering
14
15
  - 🔮 **Predictions** - Time series forecasting and predictive modeling
15
16
  - 📈 **Correlation Analysis** - Pearson correlation matrices and significance testing
17
+ - 🤖 **AI Summaries** - Generate intelligent summaries of your data
18
+ - 🌐 **Table Extraction** - Extract data from HTML tables or Vue data grids
16
19
  - 🔄 **Local Fallback** - Built-in statistical analysis when API is unavailable
17
20
  - 🎨 **Vue Integration** - Reactive composables for seamless Vue.js integration
18
21
  - đŸ“Ļ **Smart DataTable Ready** - Designed to work with @aivue/smart-datatable
19
22
 
23
+ ### đŸ’Ŧ Q&A Capabilities
24
+
25
+ **Ask any question about your Vue tables – AI answers directly from your data.**
26
+
27
+ - "Which region had the highest revenue last quarter?"
28
+ - "How many customers churned with tenure < 6 months?"
29
+ - "What is the average order value for India vs US?"
30
+ - "Show me products with price > $100 and quantity < 10"
31
+
32
+ The AI analyzes your table data and provides natural language answers with supporting statistics and data.
33
+
20
34
  ## đŸ“Ļ Installation
21
35
 
22
36
  ```bash
@@ -96,6 +110,111 @@ async function analyzeData() {
96
110
  </script>
97
111
  ```
98
112
 
113
+ ## đŸ’Ŧ Q&A Usage
114
+
115
+ ### Setup Q&A
116
+
117
+ ```typescript
118
+ import { useTabularIntelligence, QuestionInput, AnswerDisplay, QuestionHistory } from '@aivue/tabular-intelligence';
119
+
120
+ const {
121
+ askQuestion,
122
+ generateSummary,
123
+ questionHistory,
124
+ lastAnswer,
125
+ clearHistory,
126
+ } = useTabularIntelligence({
127
+ config: {
128
+ provider: 'local',
129
+ baseUrl: 'https://api.example.com/tfm',
130
+ },
131
+ data: tableData,
132
+ qaConfig: {
133
+ provider: 'openai',
134
+ apiKey: 'sk-...',
135
+ model: 'gpt-4-turbo-preview',
136
+ },
137
+ });
138
+
139
+ // Ask a question
140
+ const answer = await askQuestion('What is the average price by category?');
141
+
142
+ // Generate AI summary
143
+ const summary = await generateSummary();
144
+ ```
145
+
146
+ ### Q&A Components
147
+
148
+ ```vue
149
+ <template>
150
+ <div>
151
+ <!-- Question Input -->
152
+ <QuestionInput
153
+ :loading="loading"
154
+ @submit="handleQuestion"
155
+ />
156
+
157
+ <!-- Latest Answer -->
158
+ <AnswerDisplay
159
+ v-if="lastAnswer"
160
+ :answer="lastAnswer"
161
+ />
162
+
163
+ <!-- Question History -->
164
+ <QuestionHistory
165
+ :questions="questionHistory"
166
+ @clear="clearHistory"
167
+ @select="handleSelectQuestion"
168
+ />
169
+ </div>
170
+ </template>
171
+
172
+ <script setup>
173
+ import { QuestionInput, AnswerDisplay, QuestionHistory, useTabularIntelligence } from '@aivue/tabular-intelligence';
174
+
175
+ const { askQuestion, questionHistory, lastAnswer, clearHistory } = useTabularIntelligence({
176
+ config: { provider: 'local' },
177
+ data: tableData,
178
+ qaConfig: {
179
+ provider: 'openai',
180
+ apiKey: import.meta.env.VITE_OPENAI_API_KEY,
181
+ },
182
+ });
183
+
184
+ async function handleQuestion(question) {
185
+ await askQuestion(question);
186
+ }
187
+
188
+ function handleSelectQuestion(question) {
189
+ console.log('Selected:', question);
190
+ }
191
+ </script>
192
+ ```
193
+
194
+ ### Table Extraction
195
+
196
+ Extract data from HTML tables or Vue data grids:
197
+
198
+ ```typescript
199
+ // Extract from DOM
200
+ const extracted = intelligence.extractFromDOM({
201
+ selector: 'table.my-table',
202
+ includeHeaders: true,
203
+ maxRows: 1000,
204
+ inferTypes: true,
205
+ });
206
+
207
+ // Load from Vue data grid
208
+ intelligence.loadFromVueGrid(
209
+ gridData,
210
+ [
211
+ { field: 'name', header: 'Product Name' },
212
+ { field: 'price', header: 'Price' },
213
+ ],
214
+ { inferTypes: true }
215
+ );
216
+ ```
217
+
99
218
  ## 📖 API Reference
100
219
 
101
220
  ### `useTabularIntelligence(options)`
@@ -107,6 +226,8 @@ Main composable for tabular intelligence.
107
226
  - `data?: Ref<any[]>` - Reactive data array
108
227
  - `schema?: Ref<TableSchema>` - Optional table schema
109
228
  - `useLocalFallback?: boolean` - Enable local analysis fallback (default: true)
229
+ - `qaConfig?: QAEngineConfig` - Q&A engine configuration (optional)
230
+ - `maxQuestionHistory?: number` - Maximum questions to keep in history (default: 50)
110
231
 
111
232
  **Returns:**
112
233
  - `client: TabularIntelligence` - Core TFM client instance
@@ -115,12 +236,21 @@ Main composable for tabular intelligence.
115
236
  - `lastResult: Ref<AnalysisResult | null>` - Last analysis result
116
237
  - `data: Ref<any[]>` - Data array
117
238
  - `schema: Ref<TableSchema | null>` - Inferred or provided schema
239
+ - `questionHistory: Ref<Question[]>` - Q&A question history
240
+ - `answerHistory: Ref<Answer[]>` - Q&A answer history
241
+ - `lastAnswer: Ref<Answer | null>` - Last Q&A answer
118
242
  - `analyze(type, options)` - Generic analysis method
119
243
  - `getDescriptiveStats()` - Get descriptive statistics
120
244
  - `detectAnomalies(columns?, sensitivity?)` - Detect anomalies
121
245
  - `performClustering(features, numClusters?)` - Perform clustering
122
246
  - `predict(targetColumn, options?)` - Make predictions
247
+ - `askQuestion(question, options?)` - Ask a question about the data
248
+ - `generateSummary()` - Generate AI summary of the data
249
+ - `clearHistory()` - Clear Q&A history
250
+ - `extractFromDOM(options?)` - Extract table from DOM
251
+ - `loadFromVueGrid(data, columns?, options?)` - Load data from Vue grid
123
252
  - `updateConfig(config)` - Update TFM configuration
253
+ - `initializeQA(qaConfig)` - Initialize Q&A engine
124
254
  - `setData(data, autoInferSchema?)` - Set new data
125
255
  - `reset()` - Reset state
126
256
 
@@ -134,6 +264,8 @@ type AnalysisType =
134
264
  | 'clustering' // K-means, DBSCAN, etc.
135
265
  | 'prediction' // Forecasting
136
266
  | 'correlation' // Correlation analysis
267
+ | 'summary' // AI-generated summary
268
+ | 'qa' // Question answering
137
269
  | 'trend_analysis' // Trend detection
138
270
  | 'outlier_detection'; // Statistical outliers
139
271
  ```
@@ -1,11 +1,14 @@
1
1
  import { Ref } from 'vue';
2
2
  import { TabularIntelligence } from '../core/TabularIntelligence';
3
- import { TFMConfig, AnalysisResult, AnalysisType, TableSchema, DescriptiveStats, Anomaly } from '../types';
3
+ import { TFMConfig, AnalysisResult, AnalysisType, TableSchema, DescriptiveStats, Anomaly, Question, Answer, QARequest, AISummary, TableExtractionOptions, ExtractedTable } from '../types';
4
+ import { QAEngineConfig } from '../utils/qaEngine';
4
5
  export interface UseTabularIntelligenceOptions {
5
6
  config: TFMConfig;
6
7
  data?: Ref<any[]>;
7
8
  schema?: Ref<TableSchema>;
8
9
  useLocalFallback?: boolean;
10
+ qaConfig?: QAEngineConfig;
11
+ maxQuestionHistory?: number;
9
12
  }
10
13
  export interface UseTabularIntelligenceReturn {
11
14
  client: TabularIntelligence;
@@ -14,12 +17,21 @@ export interface UseTabularIntelligenceReturn {
14
17
  lastResult: Ref<AnalysisResult | null>;
15
18
  data: Ref<any[]>;
16
19
  schema: Ref<TableSchema | null>;
20
+ questionHistory: Ref<Question[]>;
21
+ answerHistory: Ref<Answer[]>;
22
+ lastAnswer: Ref<Answer | null>;
17
23
  analyze: (type: AnalysisType, options?: any) => Promise<AnalysisResult>;
18
24
  getDescriptiveStats: () => Promise<DescriptiveStats[]>;
19
25
  detectAnomalies: (columns?: string[], sensitivity?: number) => Promise<Anomaly[]>;
20
26
  performClustering: (features: string[], numClusters?: number) => Promise<AnalysisResult>;
21
27
  predict: (targetColumn: string, options?: any) => Promise<AnalysisResult>;
28
+ askQuestion: (question: string, options?: Partial<QARequest>) => Promise<Answer>;
29
+ generateSummary: () => Promise<AISummary>;
30
+ clearHistory: () => void;
31
+ extractFromDOM: (options?: TableExtractionOptions) => ExtractedTable | null;
32
+ loadFromVueGrid: (gridData: any[], columns?: any[], options?: TableExtractionOptions) => void;
22
33
  updateConfig: (config: Partial<TFMConfig>) => void;
34
+ initializeQA: (qaConfig: QAEngineConfig) => void;
23
35
  setData: (newData: any[], autoInferSchema?: boolean) => void;
24
36
  reset: () => void;
25
37
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useTabularIntelligence.d.ts","sourceRoot":"","sources":["../../src/composables/useTabularIntelligence.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAiB,GAAG,EAAE,MAAM,KAAK,CAAC;AACzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,KAAK,EACV,SAAS,EAET,cAAc,EACd,YAAY,EACZ,WAAW,EACX,gBAAgB,EAChB,OAAO,EACR,MAAM,UAAU,CAAC;AAGlB,MAAM,WAAW,6BAA6B;IAC5C,MAAM,EAAE,SAAS,CAAC;IAClB,IAAI,CAAC,EAAE,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;IAClB,MAAM,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC;IAC1B,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED,MAAM,WAAW,4BAA4B;IAE3C,MAAM,EAAE,mBAAmB,CAAC;IAG5B,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACtB,KAAK,EAAE,GAAG,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;IACzB,UAAU,EAAE,GAAG,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;IAGvC,IAAI,EAAE,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;IACjB,MAAM,EAAE,GAAG,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IAGhC,OAAO,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IACxE,mBAAmB,EAAE,MAAM,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;IACvD,eAAe,EAAE,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,WAAW,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IAClF,iBAAiB,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,WAAW,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IACzF,OAAO,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IAC1E,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;IACnD,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,EAAE,eAAe,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IAC7D,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAED,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,6BAA6B,GACrC,4BAA4B,CAiK9B"}
1
+ {"version":3,"file":"useTabularIntelligence.d.ts","sourceRoot":"","sources":["../../src/composables/useTabularIntelligence.ts"],"names":[],"mappings":"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"}
@@ -1,7 +1,13 @@
1
- import { TFMConfig, AnalysisRequest, AnalysisResult } from '../types';
1
+ import { TFMConfig, AnalysisRequest, AnalysisResult, TableSchema, QARequest, QAResponse, AISummary, TableExtractionOptions, ExtractedTable } from '../types';
2
+ import { QAEngineConfig } from '../utils/qaEngine';
2
3
  export declare class TabularIntelligence {
3
4
  private config;
4
- constructor(config: TFMConfig);
5
+ private qaEngine?;
6
+ constructor(config: TFMConfig, qaConfig?: QAEngineConfig);
7
+ /**
8
+ * Initialize or update Q&A engine
9
+ */
10
+ initializeQA(qaConfig: QAEngineConfig): void;
5
11
  /**
6
12
  * Generic API call to TFM endpoint
7
13
  */
@@ -14,6 +20,26 @@ export declare class TabularIntelligence {
14
20
  * Parse TFM response into structured AnalysisResult
15
21
  */
16
22
  private parseAnalysisResult;
23
+ /**
24
+ * Ask a question about the data (Q&A)
25
+ */
26
+ askQuestion(request: QARequest): Promise<QAResponse>;
27
+ /**
28
+ * Generate AI summary of table data
29
+ */
30
+ generateSummary(data: any[], schema: TableSchema): Promise<AISummary>;
31
+ /**
32
+ * Extract table from DOM
33
+ */
34
+ extractFromDOM(options?: TableExtractionOptions): ExtractedTable | null;
35
+ /**
36
+ * Normalize Vue data grid data
37
+ */
38
+ normalizeVueData(data: any[], columns?: Array<{
39
+ field: string;
40
+ header?: string;
41
+ label?: string;
42
+ }>, options?: TableExtractionOptions): ExtractedTable;
17
43
  /**
18
44
  * Update configuration
19
45
  */
@@ -1 +1 @@
1
- {"version":3,"file":"TabularIntelligence.d.ts","sourceRoot":"","sources":["../../src/core/TabularIntelligence.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EACV,SAAS,EAGT,eAAe,EACf,cAAc,EAQf,MAAM,UAAU,CAAC;AAElB,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAY;gBAEd,MAAM,EAAE,SAAS;IAO7B;;OAEG;YACW,OAAO;IA+CrB;;OAEG;IACG,OAAO,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC;IAkBhE;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAoD3B;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,IAAI;IAI9C;;OAEG;IACH,SAAS,IAAI,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC;CAIvC"}
1
+ {"version":3,"file":"TabularIntelligence.d.ts","sourceRoot":"","sources":["../../src/core/TabularIntelligence.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EACV,SAAS,EAGT,eAAe,EACf,cAAc,EAEd,WAAW,EAMX,SAAS,EACT,UAAU,EACV,SAAS,EACT,sBAAsB,EACtB,cAAc,EACf,MAAM,UAAU,CAAC;AAClB,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAGlE,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAY;IAC1B,OAAO,CAAC,QAAQ,CAAC,CAAW;gBAEhB,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC,EAAE,cAAc;IAYxD;;OAEG;IACH,YAAY,CAAC,QAAQ,EAAE,cAAc,GAAG,IAAI;IAI5C;;OAEG;YACW,OAAO;IA+CrB;;OAEG;IACG,OAAO,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC;IAkBhE;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAgE3B;;OAEG;IACG,WAAW,CAAC,OAAO,EAAE,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC;IAQ1D;;OAEG;IACG,eAAe,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,CAAC;IAgB3E;;OAEG;IACH,cAAc,CAAC,OAAO,CAAC,EAAE,sBAAsB,GAAG,cAAc,GAAG,IAAI;IAIvE;;OAEG;IACH,gBAAgB,CACd,IAAI,EAAE,GAAG,EAAE,EACX,OAAO,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,EACnE,OAAO,CAAC,EAAE,sBAAsB,GAC/B,cAAc;IAIjB;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,IAAI;IAI9C;;OAEG;IACH,SAAS,IAAI,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC;CAIvC"}
package/dist/index.d.ts CHANGED
@@ -5,6 +5,11 @@
5
5
  export { TabularIntelligence } from './core/TabularIntelligence';
6
6
  export { useTabularIntelligence } from './composables/useTabularIntelligence';
7
7
  export type { UseTabularIntelligenceOptions, UseTabularIntelligenceReturn } from './composables/useTabularIntelligence';
8
+ export { default as QuestionInput } from './components/QuestionInput.vue';
9
+ export { default as AnswerDisplay } from './components/AnswerDisplay.vue';
10
+ export { default as QuestionHistory } from './components/QuestionHistory.vue';
8
11
  export { inferSchema, inferColumnType, calculateStats, detectAnomalies } from './utils/helpers';
9
- export type { TFMProvider, TFMConfig, TableColumn, TableSchema, AnalysisType, AnalysisRequest, AnalysisOptions, AnalysisResult, DescriptiveStats, Anomaly, Cluster, Prediction, CorrelationMatrix, TFMRequest, TFMResponse, } from './types';
12
+ export { QAEngine, type QAEngineConfig } from './utils/qaEngine';
13
+ export { extractFromDOM, normalizeVueData } from './utils/tableExtractor';
14
+ export type { TFMProvider, TFMConfig, TableColumn, TableSchema, AnalysisType, AnalysisRequest, AnalysisOptions, AnalysisResult, DescriptiveStats, Anomaly, Cluster, Prediction, CorrelationMatrix, TFMRequest, TFMResponse, Question, Answer, QARequest, QAResponse, QAHistory, TableExtractionOptions, ExtractedTable, AISummary, } from './types';
10
15
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAGjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAC9E,YAAY,EAAE,6BAA6B,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AAGxH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGhG,YAAY,EACV,WAAW,EACX,SAAS,EACT,WAAW,EACX,WAAW,EACX,YAAY,EACZ,eAAe,EACf,eAAe,EACf,cAAc,EACd,gBAAgB,EAChB,OAAO,EACP,OAAO,EACP,UAAU,EACV,iBAAiB,EACjB,UAAU,EACV,WAAW,GACZ,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAGjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAC9E,YAAY,EAAE,6BAA6B,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AAGxH,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAG9E,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAChG,OAAO,EAAE,QAAQ,EAAE,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAG1E,YAAY,EACV,WAAW,EACX,SAAS,EACT,WAAW,EACX,WAAW,EACX,YAAY,EACZ,eAAe,EACf,eAAe,EACf,cAAc,EACd,gBAAgB,EAChB,OAAO,EACP,OAAO,EACP,UAAU,EACV,iBAAiB,EACjB,UAAU,EACV,WAAW,EACX,QAAQ,EACR,MAAM,EACN,SAAS,EACT,UAAU,EACV,SAAS,EACT,sBAAsB,EACtB,cAAc,EACd,SAAS,GACV,MAAM,SAAS,CAAC"}
package/dist/index.js CHANGED
@@ -1,2 +1,31 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("vue");class A{constructor(s){this.config={timeout:3e4,...s}}async callTFM(s){const e=Date.now();try{const n=await fetch(this.config.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",...this.config.apiKey&&{Authorization:`Bearer ${this.config.apiKey}`},...this.config.headers},body:JSON.stringify({...s,model:this.config.model}),signal:AbortSignal.timeout(this.config.timeout||3e4)});if(!n.ok){const o=await n.text();throw new Error(`TFM API error: ${n.status} - ${o}`)}const t=await n.json(),i=Date.now()-e;return{success:!0,result:t.result||t,metadata:{processingTime:i,model:this.config.model||"unknown",version:t.version}}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Unknown error",metadata:{processingTime:Date.now()-e,model:this.config.model||"unknown"}}}}async analyze(s){const e={operation:s.type,data:s.data,schema:s.schema,parameters:s.options},n=await this.callTFM(e);if(!n.success)throw new Error(n.error||"Analysis failed");return this.parseAnalysisResult(s.type,n.result,n.metadata)}parseAnalysisResult(s,e,n){const t={type:s,timestamp:new Date,summary:e.summary||"",insights:e.insights||[],recommendations:e.recommendations,confidence:e.confidence||.8,processingTime:n==null?void 0:n.processingTime};switch(s){case"descriptive_stats":return{...t,descriptiveStats:e.stats||e.descriptiveStats};case"anomaly_detection":return{...t,anomalies:e.anomalies||[]};case"segmentation":case"clustering":return{...t,clusters:e.clusters||[]};case"prediction":return{...t,predictions:e.predictions||e};case"correlation":return{...t,correlations:e.correlations||e};default:return t}}updateConfig(s){this.config={...this.config,...s}}getConfig(){const{apiKey:s,...e}=this.config;return e}}function M(c,s){if(c.length===0)return{columns:[],rowCount:0,name:s};const e=c[0];return{columns:Object.keys(e).map(t=>{const i=N(c,t);return{name:t,type:i,nullable:c.some(o=>o[t]==null)}}),rowCount:c.length,name:s}}function N(c,s){const e=c.map(t=>t[s]).filter(t=>t!=null);if(e.length===0)return"string";if(e.every(t=>typeof t=="number"||!isNaN(Number(t))))return"number";if(e.every(t=>typeof t=="boolean"||t==="true"||t==="false"))return"boolean";if(e.every(t=>!isNaN(Date.parse(t))))return"date";const n=new Set(e);return n.size<e.length*.5&&n.size<20?"categorical":"string"}function $(c,s,e){const n=c.map(l=>l[s]).filter(l=>l!=null),t=n.length,i=c.length-t,o={column:s,count:t,nullCount:i};if(e==="number"){const l=n.map(Number).filter(r=>!isNaN(r));if(l.length>0){const r=[...l].sort((u,d)=>u-d),p=l.reduce((u,d)=>u+d,0);o.mean=p/l.length,o.median=r[Math.floor(r.length/2)],o.min=r[0],o.max=r[r.length-1];const h=l.reduce((u,d)=>u+Math.pow(d-o.mean,2),0)/l.length;o.std=Math.sqrt(h),o.percentiles={25:r[Math.floor(r.length*.25)],50:o.median,75:r[Math.floor(r.length*.75)],90:r[Math.floor(r.length*.9)]}}}else{const l=new Set(n);o.uniqueValues=l.size;const r={};n.forEach(h=>{const u=String(h);r[u]=(r[u]||0)+1});const p=Math.max(...Object.values(r));o.mode=Object.keys(r).find(h=>r[h]===p)}return o}function F(c,s,e=.5){const n=[],t=1.5+(1-e)*1.5;return s.forEach(i=>{const o=c.map((m,g)=>({value:Number(m[i]),idx:g})).filter(m=>!isNaN(m.value));if(o.length===0)return;const l=[...o].sort((m,g)=>m.value-g.value),r=l[Math.floor(l.length*.25)].value,p=l[Math.floor(l.length*.75)].value,h=p-r,u=r-t*h,d=p+t*h;o.forEach(({value:m,idx:g})=>{if(m<u||m>d){const v=n.find(a=>a.rowIndex===g),C=m<u?`${i}: ${m.toFixed(2)} < ${u.toFixed(2)}`:`${i}: ${m.toFixed(2)} > ${d.toFixed(2)}`;v?(v.reasons.push(C),v.affectedColumns.push(i),v.score=Math.min(1,v.score+.2)):n.push({rowIndex:g,row:c[g],score:.7,reasons:[C],affectedColumns:[i]})}})}),n.sort((i,o)=>o.score-i.score)}function x(c){const s=new A(c.config),e=T.ref(!1),n=T.ref(null),t=T.ref(null),i=c.data||T.ref([]),o=c.schema||T.ref(null),l=c.useLocalFallback!==!1;async function r(a,f){e.value=!0,n.value=null;try{const y={type:a,data:i.value,schema:o.value||void 0,options:f},w=await s.analyze(y);return t.value=w,w}catch(y){if(n.value=y instanceof Error?y:new Error("Analysis failed"),l)return p(a,f);throw n.value}finally{e.value=!1}}function p(a,f){const y=o.value||M(i.value);switch(a){case"descriptive_stats":{const w=y.columns.map(b=>$(i.value,b.name,b.type));return{type:a,timestamp:new Date,descriptiveStats:w,summary:`Calculated statistics for ${w.length} columns`,insights:[],confidence:.9}}case"anomaly_detection":{const w=y.columns.filter(S=>S.type==="number").map(S=>S.name),b=F(i.value,w,f==null?void 0:f.sensitivity);return{type:a,timestamp:new Date,anomalies:b,summary:`Found ${b.length} anomalies`,insights:b.slice(0,3).map(S=>S.reasons[0]),confidence:.8}}default:throw new Error(`Local analysis not supported for type: ${a}`)}}async function h(){return(await r("descriptive_stats")).descriptiveStats||[]}async function u(a,f){return(await r("anomaly_detection",{sensitivity:f,features:a})).anomalies||[]}async function d(a,f=3){return r("clustering",{features:a,numClusters:f})}async function m(a,f){return r("prediction",{targetColumn:a,...f})}function g(a){s.updateConfig(a)}function v(a,f=!0){i.value=a,f&&(o.value=M(a))}function C(){e.value=!1,n.value=null,t.value=null}return{client:s,loading:e,error:n,lastResult:t,data:i,schema:o,analyze:r,getDescriptiveStats:h,detectAnomalies:u,performClustering:d,predict:m,updateConfig:g,setData:v,reset:C}}exports.TabularIntelligence=A;exports.calculateStats=$;exports.detectAnomalies=F;exports.inferColumnType=N;exports.inferSchema=M;exports.useTabularIntelligence=x;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue");function _(c,o){if(c.length===0)return{columns:[],rowCount:0,name:o};const a=c[0];return{columns:Object.keys(a).map(n=>{const s=T(c,n);return{name:n,type:s,nullable:c.some(i=>i[n]==null)}}),rowCount:c.length,name:o}}function T(c,o){const a=c.map(n=>n[o]).filter(n=>n!=null);if(a.length===0)return"string";if(a.every(n=>typeof n=="number"||!isNaN(Number(n))))return"number";if(a.every(n=>typeof n=="boolean"||n==="true"||n==="false"))return"boolean";if(a.every(n=>!isNaN(Date.parse(n))))return"date";const t=new Set(a);return t.size<a.length*.5&&t.size<20?"categorical":"string"}function x(c,o,a){const t=c.map(r=>r[o]).filter(r=>r!=null),n=t.length,s=c.length-n,i={column:o,count:n,nullCount:s};if(a==="number"){const r=t.map(Number).filter(l=>!isNaN(l));if(r.length>0){const l=[...r].sort((d,f)=>d-f),m=r.reduce((d,f)=>d+f,0);i.mean=m/r.length,i.median=l[Math.floor(l.length/2)],i.min=l[0],i.max=l[l.length-1];const h=r.reduce((d,f)=>d+Math.pow(f-i.mean,2),0)/r.length;i.std=Math.sqrt(h),i.percentiles={25:l[Math.floor(l.length*.25)],50:i.median,75:l[Math.floor(l.length*.75)],90:l[Math.floor(l.length*.9)]}}}else{const r=new Set(t);i.uniqueValues=r.size;const l={};t.forEach(h=>{const d=String(h);l[d]=(l[d]||0)+1});const m=Math.max(...Object.values(l));i.mode=Object.keys(l).find(h=>l[h]===m)}return i}function I(c,o,a=.5){const t=[],n=1.5+(1-a)*1.5;return o.forEach(s=>{const i=c.map((y,w)=>({value:Number(y[s]),idx:w})).filter(y=>!isNaN(y.value));if(i.length===0)return;const r=[...i].sort((y,w)=>y.value-w.value),l=r[Math.floor(r.length*.25)].value,m=r[Math.floor(r.length*.75)].value,h=m-l,d=l-n*h,f=m+n*h;i.forEach(({value:y,idx:w})=>{if(y<d||y>f){const v=t.find(A=>A.rowIndex===w),b=y<d?`${s}: ${y.toFixed(2)} < ${d.toFixed(2)}`:`${s}: ${y.toFixed(2)} > ${f.toFixed(2)}`;v?(v.reasons.push(b),v.affectedColumns.push(s),v.score=Math.min(1,v.score+.2)):t.push({rowIndex:w,row:c[w],score:.7,reasons:[b],affectedColumns:[s]})}})}),t.sort((s,i)=>i.score-s.score)}class V{constructor(o){this.config={maxTokens:1e3,temperature:.3,...o}}async answerQuestion(o){const a=Date.now();try{const{question:t,schema:n,data:s=[],sampleSize:i=100,includeAggregates:r=!0}=o,l=s.length>i?this.sampleData(s,i):s,m=r?this.calculateAggregates(s,n):void 0,h=this.buildPrompt(t,n,l,m,s.length),d=await this.callLLM(h);return{answer:this.parseResponse(d,t,s.length>i),processingTime:Date.now()-a}}catch(t){return console.error("Q&A error:",t),{answer:{questionId:this.generateId(),text:"I encountered an error while processing your question. Please try again.",timestamp:new Date,confidence:0,cannotAnswer:!0,reason:t instanceof Error?t.message:"Unknown error"},processingTime:Date.now()-a}}}sampleData(o,a){if(o.length<=a)return o;const t=Math.floor(o.length/a),n=[];for(let s=0;s<o.length&&n.length<a;s+=t)n.push(o[s]);return n}calculateAggregates(o,a){const t={};for(const n of a.columns)if(n.type==="number"&&o.length>0)try{const s=x(o,n.name,"number");t[n.name]={mean:s.mean,median:s.median,min:s.min,max:s.max,count:s.count}}catch{}else if(n.type==="categorical"||n.type==="string"){const s=o.map(r=>r[n.name]).filter(r=>r!=null),i=new Set(s);t[n.name]={uniqueCount:i.size,totalCount:s.length,topValues:this.getTopValues(s,5)}}return t}getTopValues(o,a){const t=new Map;for(const n of o)t.set(n,(t.get(n)||0)+1);return Array.from(t.entries()).map(([n,s])=>({value:n,count:s})).sort((n,s)=>s.count-n.count).slice(0,a)}buildPrompt(o,a,t,n,s){const i=s&&s>t.length;let r=`You are a data analyst assistant. Answer the following question about a table dataset.
2
+
3
+ `;r+=`**Table Schema:**
4
+ `,r+=`Table: ${a.name}
5
+ `,r+=`Columns:
6
+ `;for(const l of a.columns)r+=`- ${l.name} (${l.type})
7
+ `;return r+=`
8
+ `,n&&Object.keys(n).length>0&&(r+=`**Summary Statistics:**
9
+ `,r+=JSON.stringify(n,null,2),r+=`
10
+
11
+ `),r+=`**Sample Data** (${t.length} rows${i?` out of ${s} total`:""}):
12
+ `,r+=JSON.stringify(t.slice(0,10),null,2),r+=`
13
+
14
+ `,r+=`**Question:** ${o}
15
+
16
+ `,r+=`**Instructions:**
17
+ `,r+=`1. Answer ONLY based on the data provided above.
18
+ `,r+=`2. If the question cannot be answered from the available data, clearly state "I cannot answer this question from the available data" and explain why.
19
+ `,r+=`3. Provide a clear, concise answer.
20
+ `,r+=`4. Include specific numbers or examples from the data when relevant.
21
+ `,r+=`5. If the answer is based on sampled data, mention that it's an approximation.
22
+ `,r+=`6. Format your response as JSON with the following structure:
23
+ `,r+=`{
24
+ `,r+=` "answer": "Your answer text here",
25
+ `,r+=` "confidence": 0.0-1.0,
26
+ `,r+=` "cannotAnswer": false,
27
+ `,r+=` "isApproximate": ${i},
28
+ `,r+=` "supportingData": { "key": "value" } // optional
29
+ `,r+=`}
30
+ `,r}async callLLM(o){const{provider:a,apiKey:t,baseUrl:n,model:s,maxTokens:i,temperature:r}=this.config;if(a==="openai")return this.callOpenAI(o,t,s||"gpt-4-turbo-preview",i,r);if(a==="anthropic")return this.callAnthropic(o,t,s||"claude-3-5-sonnet-20241022",i,r);if(a==="custom"&&n)return this.callCustomAPI(o,n,t);throw new Error(`Unsupported provider: ${a}`)}async callOpenAI(o,a,t,n,s){var l,m;const i=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({model:t,messages:[{role:"user",content:o}],max_tokens:n,temperature:s,response_format:{type:"json_object"}})});if(!i.ok)throw new Error(`OpenAI API error: ${i.statusText}`);return((m=(l=(await i.json()).choices[0])==null?void 0:l.message)==null?void 0:m.content)||""}async callAnthropic(o,a,t,n,s){var l;const i=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":a,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:t,max_tokens:n,temperature:s,messages:[{role:"user",content:o}]})});if(!i.ok)throw new Error(`Anthropic API error: ${i.statusText}`);return((l=(await i.json()).content[0])==null?void 0:l.text)||""}async callCustomAPI(o,a,t){const n={"Content-Type":"application/json"};t&&(n.Authorization=`Bearer ${t}`);const s=await fetch(a,{method:"POST",headers:n,body:JSON.stringify({prompt:o})});if(!s.ok)throw new Error(`Custom API error: ${s.statusText}`);const i=await s.json();return i.response||i.answer||JSON.stringify(i)}parseResponse(o,a,t){try{const n=JSON.parse(o);return{questionId:this.generateId(),text:n.answer||n.text||o,timestamp:new Date,confidence:n.confidence||.8,cannotAnswer:n.cannotAnswer||!1,isApproximate:n.isApproximate!==void 0?n.isApproximate:t,supportingData:n.supportingData,reason:n.reason}}catch{return{questionId:this.generateId(),text:o,timestamp:new Date,confidence:.7,isApproximate:t}}}generateId(){return`qa_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function M(c={}){const{selector:o="table",includeHeaders:a=!0,maxRows:t,inferTypes:n=!0,skipEmptyRows:s=!0}=c,i=document.querySelector(o);if(!i||i.tagName!=="TABLE")return console.warn(`No table found with selector: ${o}`),null;const l=Array.from(i.rows);if(l.length===0)return null;let m=[],h=0;if(a&&l[0]){const w=l[0];m=Array.from(w.cells).map((v,b)=>{var E;return((E=v.textContent)==null?void 0:E.trim())||""||`Column${b+1}`}),h=1}else{const w=l[0];m=Array.from(w.cells).map((v,b)=>`Column${b+1}`)}const d=[],f=t?l.slice(h,h+t):l.slice(h);for(const w of f){const v=Array.from(w.cells);if(s&&v.every(A=>{var E;return!((E=A.textContent)!=null&&E.trim())}))continue;const b={};v.forEach((A,E)=>{var C;const $=m[E]||`Column${E+1}`;let D=((C=A.textContent)==null?void 0:C.trim())||"";if(n&&D){const B=parseFloat(D);!isNaN(B)&&D===B.toString()&&(D=B)}b[$]=D}),d.push(b)}return{schema:n&&d.length>0?_(d,"Extracted Table"):H(m,d.length),data:d,source:"dom",metadata:{selector:o,rowCount:d.length,columnCount:m.length,extractedAt:new Date}}}function O(c,o,a={}){const{maxRows:t,inferTypes:n=!0}=a,s=t?c.slice(0,t):c;let i;return o&&o.length>0?i={name:"Vue Data Grid",columns:o.map(r=>({name:r.field,type:n&&s.length>0?T(s,r.field):"string",nullable:!0})),rowCount:s.length}:s.length>0?i=_(s,"Vue Data Grid"):i={name:"Vue Data Grid",columns:[],rowCount:0},{schema:i,data:s,source:"vue",metadata:{rowCount:s.length,columnCount:i.columns.length,extractedAt:new Date}}}function H(c,o=0){return{name:"Extracted Table",columns:c.map(a=>({name:a,type:"string",nullable:!0})),rowCount:o}}class Q{constructor(o,a){this.config={timeout:3e4,...o},a&&(this.qaEngine=new V(a))}initializeQA(o){this.qaEngine=new V(o)}async callTFM(o){const a=Date.now();try{const t=await fetch(this.config.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",...this.config.apiKey&&{Authorization:`Bearer ${this.config.apiKey}`},...this.config.headers},body:JSON.stringify({...o,model:this.config.model}),signal:AbortSignal.timeout(this.config.timeout||3e4)});if(!t.ok){const i=await t.text();throw new Error(`TFM API error: ${t.status} - ${i}`)}const n=await t.json(),s=Date.now()-a;return{success:!0,result:n.result||n,metadata:{processingTime:s,model:this.config.model||"unknown",version:n.version}}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error",metadata:{processingTime:Date.now()-a,model:this.config.model||"unknown"}}}}async analyze(o){const a={operation:o.type,data:o.data,schema:o.schema,parameters:o.options},t=await this.callTFM(a);if(!t.success)throw new Error(t.error||"Analysis failed");return this.parseAnalysisResult(o.type,t.result,t.metadata)}parseAnalysisResult(o,a,t){const n={type:o,timestamp:new Date,summary:a.summary||"",insights:a.insights||[],recommendations:a.recommendations,confidence:a.confidence||.8,processingTime:t==null?void 0:t.processingTime};switch(o){case"descriptive_stats":return{...n,descriptiveStats:a.stats||a.descriptiveStats};case"anomaly_detection":return{...n,anomalies:a.anomalies||[]};case"segmentation":case"clustering":return{...n,clusters:a.clusters||[]};case"prediction":return{...n,predictions:a.predictions||a};case"correlation":return{...n,correlations:a.correlations||a};case"summary":return{...n,aiSummary:a.summary||a};case"qa":return{...n,qaAnswer:a.answer||a};default:return n}}async askQuestion(o){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Call initializeQA() first.");return this.qaEngine.answerQuestion(o)}async generateSummary(o,a){const t={type:"summary",data:o,schema:a},n=await this.analyze(t);if(!n.aiSummary)throw new Error("Failed to generate summary");return n.aiSummary}extractFromDOM(o){return M(o)}normalizeVueData(o,a,t){return O(o,a,t)}updateConfig(o){this.config={...this.config,...o}}getConfig(){const{apiKey:o,...a}=this.config;return a}}function R(c){const o=new Q(c.config,c.qaConfig),a=e.ref(!1),t=e.ref(null),n=e.ref(null),s=c.data||e.ref([]),i=c.schema||e.ref(null),r=e.ref([]),l=e.ref([]),m=e.ref(null),h=c.maxQuestionHistory||50,d=c.useLocalFallback!==!1;async function f(u,p){a.value=!0,t.value=null;try{const g={type:u,data:s.value,schema:i.value||void 0,options:p},k=await o.analyze(g);return n.value=k,k}catch(g){if(t.value=g instanceof Error?g:new Error("Analysis failed"),d)return y(u,p);throw t.value}finally{a.value=!1}}function y(u,p){const g=i.value||_(s.value);switch(u){case"descriptive_stats":{const k=g.columns.map(N=>x(s.value,N.name,N.type));return{type:u,timestamp:new Date,descriptiveStats:k,summary:`Calculated statistics for ${k.length} columns`,insights:[],confidence:.9}}case"anomaly_detection":{const k=g.columns.filter(S=>S.type==="number").map(S=>S.name),N=I(s.value,k,p==null?void 0:p.sensitivity);return{type:u,timestamp:new Date,anomalies:N,summary:`Found ${N.length} anomalies`,insights:N.slice(0,3).map(S=>S.reasons[0]),confidence:.8}}default:throw new Error(`Local analysis not supported for type: ${u}`)}}async function w(){return(await f("descriptive_stats")).descriptiveStats||[]}async function v(u,p){return(await f("anomaly_detection",{sensitivity:p,features:u})).anomalies||[]}async function b(u,p=3){return f("clustering",{features:u,numClusters:p})}async function A(u,p){return f("prediction",{targetColumn:u,...p})}function E(u){o.updateConfig(u)}function $(u,p=!0){s.value=u,p&&(i.value=_(u))}function D(){a.value=!1,t.value=null,n.value=null,r.value=[],l.value=[],m.value=null}async function C(u,p){a.value=!0,t.value=null;try{const g=i.value||_(s.value),k={question:u,schema:g,data:s.value,sampleSize:100,includeAggregates:!0,...p},S=(await o.askQuestion(k)).answer,P={id:S.questionId,text:u,timestamp:new Date,context:{tableSchema:g,rowCount:s.value.length}};return r.value.push(P),l.value.push(S),m.value=S,r.value.length>h&&(r.value.shift(),l.value.shift()),S}catch(g){throw t.value=g instanceof Error?g:new Error("Q&A failed"),t.value}finally{a.value=!1}}async function B(){a.value=!0,t.value=null;try{const u=i.value||_(s.value);return await o.generateSummary(s.value,u)}catch(u){throw t.value=u instanceof Error?u:new Error("Summary generation failed"),t.value}finally{a.value=!1}}function F(){r.value=[],l.value=[],m.value=null}function z(u){const p=o.extractFromDOM(u);return p&&(s.value=p.data,i.value=p.schema),p}function L(u,p,g){const k=o.normalizeVueData(u,p,g);s.value=k.data,i.value=k.schema}function j(u){o.initializeQA(u)}return{client:o,loading:a,error:t,lastResult:n,data:s,schema:i,questionHistory:r,answerHistory:l,lastAnswer:m,analyze:f,getDescriptiveStats:w,detectAnomalies:v,performClustering:b,predict:A,askQuestion:C,generateSummary:B,clearHistory:F,extractFromDOM:z,loadFromVueGrid:L,updateConfig:E,initializeQA:j,setData:$,reset:D}}const J={class:"ti-question-input"},K={class:"ti-input-wrapper"},U=["placeholder","disabled","onKeydown"],G=["disabled"],Y={key:0},W={key:1,class:"ti-loading"},X={key:0,class:"ti-hint"},Z=e.defineComponent({__name:"QuestionInput",props:{placeholder:{default:"Ask a question about this data..."},submitLabel:{default:"Ask"},loadingLabel:{default:"Processing..."},hint:{default:"Press Enter to submit, Shift+Enter for new line"},showHint:{type:Boolean,default:!0},disabled:{type:Boolean,default:!1},loading:{type:Boolean,default:!1}},emits:["submit"],setup(c,{emit:o}){const a=c,t=o,n=e.ref("");function s(){n.value.trim()&&!a.disabled&&!a.loading&&(t("submit",n.value.trim()),n.value="")}function i(r){}return(r,l)=>(e.openBlock(),e.createElementBlock("div",J,[e.createElementVNode("div",K,[e.withDirectives(e.createElementVNode("textarea",{"onUpdate:modelValue":l[0]||(l[0]=m=>n.value=m),placeholder:r.placeholder,disabled:r.disabled,class:"ti-textarea",rows:"2",onKeydown:[e.withKeys(e.withModifiers(s,["exact","prevent"]),["enter"]),e.withKeys(e.withModifiers(i,["shift"]),["enter"])]},null,40,U),[[e.vModelText,n.value]]),e.createElementVNode("button",{disabled:r.disabled||!n.value.trim(),class:"ti-submit-btn",onClick:s},[r.loading?(e.openBlock(),e.createElementBlock("span",W,e.toDisplayString(r.loadingLabel),1)):(e.openBlock(),e.createElementBlock("span",Y,e.toDisplayString(r.submitLabel),1))],8,G)]),r.showHint?(e.openBlock(),e.createElementBlock("div",X,e.toDisplayString(r.hint),1)):e.createCommentVNode("",!0)]))}}),q=(c,o)=>{const a=c.__vccOpts||c;for(const[t,n]of o)a[t]=n;return a},ee=q(Z,[["__scopeId","data-v-90db5921"]]),te={class:"ti-answer-header"},ne={class:"ti-answer-icon"},oe={key:0},se={key:1},ae={class:"ti-answer-meta"},re={class:"ti-confidence"},ie={class:"ti-timestamp"},le={class:"ti-answer-text"},ce={key:0,class:"ti-approximate-notice"},ue={key:1,class:"ti-reason"},me={key:2,class:"ti-supporting-data"},de={key:0,class:"ti-supporting-content"},pe={key:0,class:"ti-aggregates"},he={key:1,class:"ti-rows"},fe={class:"ti-table-wrapper"},ge={class:"ti-table"},we=e.defineComponent({__name:"AnswerDisplay",props:{answer:{}},setup(c){const o=e.ref(!1);function a(t){return new Date(t).toLocaleTimeString()}return(t,n)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["ti-answer-display",{"ti-cannot-answer":t.answer.cannotAnswer}])},[e.createElementVNode("div",te,[e.createElementVNode("div",ne,[t.answer.cannotAnswer?(e.openBlock(),e.createElementBlock("span",se,"âš ī¸")):(e.openBlock(),e.createElementBlock("span",oe,"💡"))]),e.createElementVNode("div",ae,[e.createElementVNode("div",re," Confidence: "+e.toDisplayString(Math.round(t.answer.confidence*100))+"% ",1),e.createElementVNode("div",ie,e.toDisplayString(a(t.answer.timestamp)),1)])]),e.createElementVNode("div",le,e.toDisplayString(t.answer.text),1),t.answer.isApproximate?(e.openBlock(),e.createElementBlock("div",ce," â„šī¸ This answer is based on sampled data and may be approximate. ")):e.createCommentVNode("",!0),t.answer.reason&&t.answer.cannotAnswer?(e.openBlock(),e.createElementBlock("div",ue,[n[1]||(n[1]=e.createElementVNode("strong",null,"Reason:",-1)),e.createTextVNode(" "+e.toDisplayString(t.answer.reason),1)])):e.createCommentVNode("",!0),t.answer.supportingData?(e.openBlock(),e.createElementBlock("div",me,[e.createElementVNode("button",{class:"ti-toggle-btn",onClick:n[0]||(n[0]=s=>o.value=!o.value)},e.toDisplayString(o.value?"â–ŧ":"â–ļ")+" Supporting Data ",1),o.value?(e.openBlock(),e.createElementBlock("div",de,[t.answer.supportingData.aggregates?(e.openBlock(),e.createElementBlock("div",pe,[n[2]||(n[2]=e.createElementVNode("h4",null,"Aggregates:",-1)),e.createElementVNode("pre",null,e.toDisplayString(JSON.stringify(t.answer.supportingData.aggregates,null,2)),1)])):e.createCommentVNode("",!0),t.answer.supportingData.rows&&t.answer.supportingData.rows.length>0?(e.openBlock(),e.createElementBlock("div",he,[e.createElementVNode("h4",null,"Sample Rows ("+e.toDisplayString(t.answer.supportingData.rows.length)+"):",1),e.createElementVNode("div",fe,[e.createElementVNode("table",ge,[e.createElementVNode("thead",null,[e.createElementVNode("tr",null,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Object.keys(t.answer.supportingData.rows[0]),(s,i)=>(e.openBlock(),e.createElementBlock("th",{key:i},e.toDisplayString(s),1))),128))])]),e.createElementVNode("tbody",null,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.answer.supportingData.rows.slice(0,5),(s,i)=>(e.openBlock(),e.createElementBlock("tr",{key:i},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Object.keys(s),(r,l)=>(e.openBlock(),e.createElementBlock("td",{key:l},e.toDisplayString(s[r]),1))),128))]))),128))])])])])):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)],2))}}),ye=q(we,[["__scopeId","data-v-d1aaae1d"]]),ve={class:"ti-question-history"},ke={class:"ti-history-header"},be={key:0,class:"ti-empty-state"},Ee={key:1,class:"ti-history-list"},Se=["onClick"],Ae={class:"ti-question-header"},De={class:"ti-question-number"},Ne={class:"ti-question-time"},_e={class:"ti-question-text"},Be={key:0,class:"ti-question-context"},Ce=e.defineComponent({__name:"QuestionHistory",props:{questions:{}},emits:["clear","select"],setup(c,{emit:o}){const a=c,t=e.computed(()=>[...a.questions].reverse());function n(s){const i=new Date(s),l=new Date().getTime()-i.getTime(),m=Math.floor(l/6e4),h=Math.floor(l/36e5),d=Math.floor(l/864e5);return m<1?"Just now":m<60?`${m}m ago`:h<24?`${h}h ago`:`${d}d ago`}return(s,i)=>(e.openBlock(),e.createElementBlock("div",ve,[e.createElementVNode("div",ke,[i[1]||(i[1]=e.createElementVNode("h3",null,"Question History",-1)),s.questions.length>0?(e.openBlock(),e.createElementBlock("button",{key:0,class:"ti-clear-btn",onClick:i[0]||(i[0]=r=>s.$emit("clear"))}," Clear History ")):e.createCommentVNode("",!0)]),s.questions.length===0?(e.openBlock(),e.createElementBlock("div",be,i[2]||(i[2]=[e.createElementVNode("div",{class:"ti-empty-icon"},"đŸ’Ŧ",-1),e.createElementVNode("p",null,"No questions asked yet",-1),e.createElementVNode("p",{class:"ti-empty-hint"},"Ask a question about your data to get started",-1)]))):(e.openBlock(),e.createElementBlock("div",Ee,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.value,(r,l)=>(e.openBlock(),e.createElementBlock("div",{key:r.id,class:"ti-history-item",onClick:m=>s.$emit("select",r)},[e.createElementVNode("div",Ae,[e.createElementVNode("span",De,"#"+e.toDisplayString(s.questions.length-l),1),e.createElementVNode("span",Ne,e.toDisplayString(n(r.timestamp)),1)]),e.createElementVNode("div",_e,e.toDisplayString(r.text),1),r.context?(e.openBlock(),e.createElementBlock("div",Be,e.toDisplayString(r.context.rowCount)+" rows ",1)):e.createCommentVNode("",!0)],8,Se))),128))]))]))}}),$e=q(Ce,[["__scopeId","data-v-c66393d9"]]);exports.AnswerDisplay=ye;exports.QAEngine=V;exports.QuestionHistory=$e;exports.QuestionInput=ee;exports.TabularIntelligence=Q;exports.calculateStats=x;exports.detectAnomalies=I;exports.extractFromDOM=M;exports.inferColumnType=T;exports.inferSchema=_;exports.normalizeVueData=O;exports.useTabularIntelligence=R;
2
31
  //# sourceMappingURL=index.js.map