@aivue/tabular-intelligence 1.3.0 → 1.3.1
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/core/TabularIntelligence.d.ts.map +1 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +257 -255
- package/dist/index.mjs.map +1 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -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,EAEd,WAAW,EAMX,SAAS,EACT,UAAU,EACV,SAAS,EACT,sBAAsB,EACtB,cAAc,EAEd,eAAe,EACf,gBAAgB,EACjB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAElE,OAAO,EAA0B,KAAK,gBAAgB,EAAE,KAAK,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAI5G,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAY;IAC1B,OAAO,CAAC,QAAQ,CAAC,CAAW;IAC5B,OAAO,CAAC,gBAAgB,CAAC,CAAmB;gBAEhC,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC,EAAE,cAAc;IAYxD;;OAEG;IACH,YAAY,CAAC,QAAQ,EAAE,cAAc,GAAG,IAAI;IAI5C;;OAEG;YACW,OAAO;
|
|
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,EAEd,eAAe,EACf,gBAAgB,EACjB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAElE,OAAO,EAA0B,KAAK,gBAAgB,EAAE,KAAK,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAI5G,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAY;IAC1B,OAAO,CAAC,QAAQ,CAAC,CAAW;IAC5B,OAAO,CAAC,gBAAgB,CAAC,CAAmB;gBAEhC,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC,EAAE,cAAc;IAYxD;;OAEG;IACH,YAAY,CAAC,QAAQ,EAAE,cAAc,GAAG,IAAI;IAI5C;;OAEG;YACW,OAAO;IAkErB;;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;IAStC;;OAEG;IACH,qBAAqB,CAAC,UAAU,EAAE,GAAG,GAAG,gBAAgB;IAKxD;;OAEG;IACH,aAAa,IAAI,gBAAgB,GAAG,SAAS;IAI7C;;OAEG;IACH,YAAY,IAAI,cAAc,EAAE;IAIhC;;OAEG;IACG,gBAAgB,CACpB,YAAY,EAAE,MAAM,EACpB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACjC,OAAO,CAAC;QAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,CAAC;IAgCjD;;OAEG;IACG,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAgCnE;;OAEG;IACH,aAAa,IAAI,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAW/E"}
|
package/dist/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("vue");function $(c,e){if(c.length===0)return{columns:[],rowCount:0,name:e};const t=c[0];return{columns:Object.keys(t).map(
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("vue");function $(c,e){if(c.length===0)return{columns:[],rowCount:0,name:e};const t=c[0];return{columns:Object.keys(t).map(o=>{const a=q(c,o);return{name:o,type:a,nullable:c.some(i=>i[o]==null)}}),rowCount:c.length,name:e}}function q(c,e){const t=c.map(o=>o[e]).filter(o=>o!=null);if(t.length===0)return"string";if(t.every(o=>typeof o=="number"||!isNaN(Number(o))))return"number";if(t.every(o=>typeof o=="boolean"||o==="true"||o==="false"))return"boolean";if(t.every(o=>!isNaN(Date.parse(o))))return"date";const s=new Set(t);return s.size<t.length*.5&&s.size<20?"categorical":"string"}function V(c,e,t){const s=c.map(r=>r[e]).filter(r=>r!=null),o=s.length,a=c.length-o,i={column:e,count:o,nullCount:a};if(t==="number"){const r=s.map(Number).filter(l=>!isNaN(l));if(r.length>0){const l=[...r].sort((p,d)=>p-d),u=r.reduce((p,d)=>p+d,0);i.mean=u/r.length,i.median=l[Math.floor(l.length/2)],i.min=l[0],i.max=l[l.length-1];const h=r.reduce((p,d)=>p+Math.pow(d-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(s);i.uniqueValues=r.size;const l={};s.forEach(h=>{const p=String(h);l[p]=(l[p]||0)+1});const u=Math.max(...Object.values(l));i.mode=Object.keys(l).find(h=>l[h]===u)}return i}function M(c,e,t=.5){const s=[],o=1.5+(1-t)*1.5;return e.forEach(a=>{const i=c.map((g,y)=>({value:Number(g[a]),idx:y})).filter(g=>!isNaN(g.value));if(i.length===0)return;const r=[...i].sort((g,y)=>g.value-y.value),l=r[Math.floor(r.length*.25)].value,u=r[Math.floor(r.length*.75)].value,h=u-l,p=l-o*h,d=u+o*h;i.forEach(({value:g,idx:y})=>{if(g<p||g>d){const v=s.find(C=>C.rowIndex===y),b=g<p?`${a}: ${g.toFixed(2)} < ${p.toFixed(2)}`:`${a}: ${g.toFixed(2)} > ${d.toFixed(2)}`;v?(v.reasons.push(b),v.affectedColumns.push(a),v.score=Math.min(1,v.score+.2)):s.push({rowIndex:y,row:c[y],score:.7,reasons:[b],affectedColumns:[a]})}})}),s.sort((a,i)=>i.score-a.score)}class T{constructor(e){this.config={maxTokens:1e3,temperature:.3,...e}}async answerQuestion(e){const t=Date.now();try{const{question:s,schema:o,data:a=[],sampleSize:i=100,includeAggregates:r=!0}=e,l=a.length>i?this.sampleData(a,i):a,u=r?this.calculateAggregates(a,o):void 0,h=this.buildPrompt(s,o,l,u,a.length),p=await this.callLLM(h);return{answer:this.parseResponse(p,s,a.length>i),processingTime:Date.now()-t}}catch(s){return console.error("Q&A error:",s),{answer:{questionId:this.generateId(),text:"I encountered an error while processing your question. Please try again.",timestamp:new Date,confidence:0,cannotAnswer:!0,reason:s instanceof Error?s.message:"Unknown error"},processingTime:Date.now()-t}}}sampleData(e,t){if(e.length<=t)return e;const s=Math.floor(e.length/t),o=[];for(let a=0;a<e.length&&o.length<t;a+=s)o.push(e[a]);return o}calculateAggregates(e,t){const s={};for(const o of t.columns)if(o.type==="number"&&e.length>0)try{const a=V(e,o.name,"number");s[o.name]={mean:a.mean,median:a.median,min:a.min,max:a.max,count:a.count}}catch{}else if(o.type==="categorical"||o.type==="string"){const a=e.map(r=>r[o.name]).filter(r=>r!=null),i=new Set(a);s[o.name]={uniqueCount:i.size,totalCount:a.length,topValues:this.getTopValues(a,5)}}return s}getTopValues(e,t){const s=new Map;for(const o of e)s.set(o,(s.get(o)||0)+1);return Array.from(s.entries()).map(([o,a])=>({value:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,t)}buildPrompt(e,t,s,o,a){const i=a&&a>s.length;let r=`You are a data analyst assistant. Answer the following question about a table dataset.
|
|
2
2
|
|
|
3
3
|
`;r+=`**Table Schema:**
|
|
4
4
|
`,r+=`Table: ${t.name}
|
|
5
5
|
`,r+=`Columns:
|
|
6
6
|
`;for(const l of t.columns)r+=`- ${l.name} (${l.type})
|
|
7
7
|
`;return r+=`
|
|
8
|
-
`,
|
|
9
|
-
`,r+=JSON.stringify(
|
|
8
|
+
`,o&&Object.keys(o).length>0&&(r+=`**Summary Statistics:**
|
|
9
|
+
`,r+=JSON.stringify(o,null,2),r+=`
|
|
10
10
|
|
|
11
|
-
`),r+=`**Sample Data** (${s.length} rows${i?` out of ${
|
|
11
|
+
`),r+=`**Sample Data** (${s.length} rows${i?` out of ${a} total`:""}):
|
|
12
12
|
`,r+=JSON.stringify(s.slice(0,10),null,2),r+=`
|
|
13
13
|
|
|
14
14
|
`,r+=`**Question:** ${e}
|
|
@@ -27,5 +27,5 @@
|
|
|
27
27
|
`,r+=` "isApproximate": ${i},
|
|
28
28
|
`,r+=` "supportingData": { "key": "value" } // optional
|
|
29
29
|
`,r+=`}
|
|
30
|
-
`,r}async callLLM(e){const{provider:t,apiKey:s,baseUrl:a,model:o,maxTokens:i,temperature:r}=this.config;if(t==="openai")return this.callOpenAI(e,s,o||"gpt-4-turbo-preview",i,r);if(t==="anthropic")return this.callAnthropic(e,s,o||"claude-3-5-sonnet-20241022",i,r);if(t==="custom"&&a)return this.callCustomAPI(e,a,s);throw new Error(`Unsupported provider: ${t}`)}async callOpenAI(e,t,s,a,o){var l,u;const i=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:s,messages:[{role:"user",content:e}],max_tokens:a,temperature:o,response_format:{type:"json_object"}})});if(!i.ok)throw new Error(`OpenAI API error: ${i.statusText}`);return((u=(l=(await i.json()).choices[0])==null?void 0:l.message)==null?void 0:u.content)||""}async callAnthropic(e,t,s,a,o){var l;const i=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:s,max_tokens:a,temperature:o,messages:[{role:"user",content:e}]})});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(e,t,s){const a={"Content-Type":"application/json"};s&&(a.Authorization=`Bearer ${s}`);const o=await fetch(t,{method:"POST",headers:a,body:JSON.stringify({prompt:e})});if(!o.ok)throw new Error(`Custom API error: ${o.statusText}`);const i=await o.json();return i.response||i.answer||JSON.stringify(i)}parseResponse(e,t,s){try{const a=JSON.parse(e);return{questionId:this.generateId(),text:a.answer||a.text||e,timestamp:new Date,confidence:a.confidence||.8,cannotAnswer:a.cannotAnswer||!1,isApproximate:a.isApproximate!==void 0?a.isApproximate:s,supportingData:a.supportingData,reason:a.reason}}catch{return{questionId:this.generateId(),text:e,timestamp:new Date,confidence:.7,isApproximate:s}}}generateId(){return`qa_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function O(c={}){const{selector:e="table",includeHeaders:t=!0,maxRows:s,inferTypes:a=!0,skipEmptyRows:o=!0}=c,i=document.querySelector(e);if(!i||i.tagName!=="TABLE")return console.warn(`No table found with selector: ${e}`),null;const l=Array.from(i.rows);if(l.length===0)return null;let u=[],h=0;if(t&&l[0]){const y=l[0];u=Array.from(y.cells).map((v,b)=>{var E;return((E=v.textContent)==null?void 0:E.trim())||""||`Column${b+1}`}),h=1}else{const y=l[0];u=Array.from(y.cells).map((v,b)=>`Column${b+1}`)}const p=[],d=s?l.slice(h,h+s):l.slice(h);for(const y of d){const v=Array.from(y.cells);if(o&&v.every(C=>{var E;return!((E=C.textContent)!=null&&E.trim())}))continue;const b={};v.forEach((C,E)=>{var B;const q=u[E]||`Column${E+1}`;let D=((B=C.textContent)==null?void 0:B.trim())||"";if(a&&D){const _=parseFloat(D);!isNaN(_)&&D===_.toString()&&(D=_)}b[q]=D}),p.push(b)}return{schema:a&&p.length>0?$(p,"Extracted Table"):G(u,p.length),data:p,source:"dom",metadata:{selector:e,rowCount:p.length,columnCount:u.length,extractedAt:new Date}}}function Q(c,e,t={}){const{maxRows:s,inferTypes:a=!0}=t,o=s?c.slice(0,s):c;let i;return e&&e.length>0?i={name:"Vue Data Grid",columns:e.map(r=>({name:r.field,type:a&&o.length>0?V(o,r.field):"string",nullable:!0})),rowCount:o.length}:o.length>0?i=$(o,"Vue Data Grid"):i={name:"Vue Data Grid",columns:[],rowCount:0},{schema:i,data:o,source:"vue",metadata:{rowCount:o.length,columnCount:i.columns.length,extractedAt:new Date}}}function G(c,e=0){return{name:"Extracted Table",columns:c.map(t=>({name:t,type:"string",nullable:!0})),rowCount:e}}function F(c){const e={};c.variable&&c.variable.forEach(o=>{e[o.key]=o.value});const t=c.auth?j(c.auth):void 0,s=[];function a(o,i=""){o.forEach(r=>{r.item?a(r.item,i?`${i}/${r.name}`:r.name):r.request&&s.push(Y(r,t))})}return a(c.item),{name:c.info.name,description:c.info.description,endpoints:s,variables:e,auth:t}}function Y(c,e){const t=c.request,s={};t.header&&t.header.forEach(i=>{s[i.key]=i.value});const a={};t.url.query&&t.url.query.forEach(i=>{a[i.key]=i.value});const o=t.auth?j(t.auth):e;return{name:c.name,method:t.method,url:t.url.raw,description:t.description,headers:s,queryParams:a,auth:o}}function j(c){const e={};return c.apikey?c.apikey.forEach(t=>{e[t.key]=t.value}):c.bearer?c.bearer.forEach(t=>{e[t.key]=t.value}):c.basic&&c.basic.forEach(t=>{e[t.key]=t.value}),{type:c.type,credentials:e}}function S(c,e){let t=c;return Object.keys(e).forEach(s=>{const a=new RegExp(`{{${s}}}`,"g");t=t.replace(a,e[s])}),t}async function I(c){const{endpoint:e,variables:t={},additionalHeaders:s={},additionalParams:a={}}=c;try{let o=S(e.url,t);const i={...e.queryParams,...t,...a},r=Object.keys(i).filter(d=>i[d]!==void 0&&i[d]!=="").map(d=>`${encodeURIComponent(d)}=${encodeURIComponent(S(String(i[d]),t))}`).join("&");r&&(o=o.includes("?")?`${o}&${r}`:`${o}?${r}`);const l={"Content-Type":"application/json",...e.headers,...s};if(Object.keys(l).forEach(d=>{l[d]=S(l[d],t)}),e.auth){if(e.auth.type==="apikey"){const d=e.auth.credentials.key||"access_key",g=S(e.auth.credentials.value||"",t);e.auth.credentials.in==="header"&&(l[d]=g)}else if(e.auth.type==="bearer"){const d=S(e.auth.credentials.token||"",t);l.Authorization=`Bearer ${d}`}else if(e.auth.type==="basic"){const d=S(e.auth.credentials.username||"",t),g=S(e.auth.credentials.password||"",t),y=btoa(`${d}:${g}`);l.Authorization=`Basic ${y}`}}const u=await fetch(o,{method:e.method,headers:l}),h={};return u.headers.forEach((d,g)=>{h[g]=d}),u.ok?{success:!0,data:await u.json(),statusCode:u.status,headers:h}:{success:!1,error:`HTTP ${u.status}: ${u.statusText}`,statusCode:u.status,headers:h}}catch(o){return{success:!1,error:o.message||"Unknown error occurred"}}}async function W(c,e={}){const t=[];for(const s of c){const a=await I({endpoint:s,variables:e});t.push(a)}return t}function z(c){if(!c.success||!c.data)return[];const e=c.data;return Array.isArray(e)?e:e.data&&Array.isArray(e.data)?e.data:e.results&&Array.isArray(e.results)?e.results:e.items&&Array.isArray(e.items)?e.items:typeof e=="object"?[e]:[]}class R{constructor(e,t){this.config={timeout:3e4,...e},t&&(this.qaEngine=new T(t))}initializeQA(e){this.qaEngine=new T(e)}async callTFM(e){const t=Date.now();try{const s=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({...e,model:this.config.model}),signal:AbortSignal.timeout(this.config.timeout||3e4)});if(!s.ok){const i=await s.text();throw new Error(`TFM API error: ${s.status} - ${i}`)}const a=await s.json(),o=Date.now()-t;return{success:!0,result:a.result||a,metadata:{processingTime:o,model:this.config.model||"unknown",version:a.version}}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error",metadata:{processingTime:Date.now()-t,model:this.config.model||"unknown"}}}}async analyze(e){const t={operation:e.type,data:e.data,schema:e.schema,parameters:e.options},s=await this.callTFM(t);if(!s.success)throw new Error(s.error||"Analysis failed");return this.parseAnalysisResult(e.type,s.result,s.metadata)}parseAnalysisResult(e,t,s){const a={type:e,timestamp:new Date,summary:t.summary||"",insights:t.insights||[],recommendations:t.recommendations,confidence:t.confidence||.8,processingTime:s==null?void 0:s.processingTime};switch(e){case"descriptive_stats":return{...a,descriptiveStats:t.stats||t.descriptiveStats};case"anomaly_detection":return{...a,anomalies:t.anomalies||[]};case"segmentation":case"clustering":return{...a,clusters:t.clusters||[]};case"prediction":return{...a,predictions:t.predictions||t};case"correlation":return{...a,correlations:t.correlations||t};case"summary":return{...a,aiSummary:t.summary||t};case"qa":return{...a,qaAnswer:t.answer||t};default:return a}}async askQuestion(e){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Call initializeQA() first.");return this.qaEngine.answerQuestion(e)}async generateSummary(e,t){const s={type:"summary",data:e,schema:t},a=await this.analyze(s);if(!a.aiSummary)throw new Error("Failed to generate summary");return a.aiSummary}extractFromDOM(e){return O(e)}normalizeVueData(e,t,s){return Q(e,t,s)}updateConfig(e){this.config={...this.config,...e}}getConfig(){const{apiKey:e,...t}=this.config;return t}loadPostmanCollection(e){return this.parsedCollection=F(e),this.parsedCollection}getCollection(){return this.parsedCollection}getEndpoints(){var e;return((e=this.parsedCollection)==null?void 0:e.endpoints)||[]}async fetchDataFromAPI(e,t){if(!this.parsedCollection)throw new Error("No Postman collection loaded. Call loadPostmanCollection() first.");const s=this.parsedCollection.endpoints.find(l=>l.name===e);if(!s)throw new Error(`Endpoint "${e}" not found in collection.`);const a={...this.parsedCollection.variables,...t},o=await I({endpoint:s,variables:a});if(!o.success)throw new Error(`API request failed: ${o.error}`);const i=z(o),r=$(i);return{data:i,schema:r}}async queryAPI(e){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Provide qaConfig in constructor or call initializeQA().");const t=Date.now(),{data:s,schema:a}=await this.fetchDataFromAPI(e.dataSource.endpoint||"",e.variables),o={question:e.question,schema:a,data:s},i=await this.qaEngine.answerQuestion(o),r=Date.now()-t;return{answer:i.answer,apiResponse:s,endpoint:e.dataSource.endpoint,executionTime:r}}listEndpoints(){return this.parsedCollection?this.parsedCollection.endpoints.map(e=>({name:e.name,method:e.method,description:e.description})):[]}}function X(c){const e=new R(c.config,c.qaConfig),t=n.ref(!1),s=n.ref(null),a=n.ref(null),o=c.data||n.ref([]),i=c.schema||n.ref(null),r=n.ref([]),l=n.ref([]),u=n.ref(null),h=c.maxQuestionHistory||50,p=c.useLocalFallback!==!1;async function d(m,f){t.value=!0,s.value=null;try{const w={type:m,data:o.value,schema:i.value||void 0,options:f},k=await e.analyze(w);return a.value=k,k}catch(w){if(s.value=w instanceof Error?w:new Error("Analysis failed"),p)return g(m,f);throw s.value}finally{t.value=!1}}function g(m,f){const w=i.value||$(o.value);switch(m){case"descriptive_stats":{const k=w.columns.map(N=>x(o.value,N.name,N.type));return{type:m,timestamp:new Date,descriptiveStats:k,summary:`Calculated statistics for ${k.length} columns`,insights:[],confidence:.9}}case"anomaly_detection":{const k=w.columns.filter(A=>A.type==="number").map(A=>A.name),N=P(o.value,k,f==null?void 0:f.sensitivity);return{type:m,timestamp:new Date,anomalies:N,summary:`Found ${N.length} anomalies`,insights:N.slice(0,3).map(A=>A.reasons[0]),confidence:.8}}default:throw new Error(`Local analysis not supported for type: ${m}`)}}async function y(){return(await d("descriptive_stats")).descriptiveStats||[]}async function v(m,f){return(await d("anomaly_detection",{sensitivity:f,features:m})).anomalies||[]}async function b(m,f=3){return d("clustering",{features:m,numClusters:f})}async function C(m,f){return d("prediction",{targetColumn:m,...f})}function E(m){e.updateConfig(m)}function q(m,f=!0){o.value=m,f&&(i.value=$(m))}function D(){t.value=!1,s.value=null,a.value=null,r.value=[],l.value=[],u.value=null}async function B(m,f){t.value=!0,s.value=null;try{const w=i.value||$(o.value),k={question:m,schema:w,data:o.value,sampleSize:100,includeAggregates:!0,...f},A=(await e.askQuestion(k)).answer,K={id:A.questionId,text:m,timestamp:new Date,context:{tableSchema:w,rowCount:o.value.length}};return r.value.push(K),l.value.push(A),u.value=A,r.value.length>h&&(r.value.shift(),l.value.shift()),A}catch(w){throw s.value=w instanceof Error?w:new Error("Q&A failed"),s.value}finally{t.value=!1}}async function _(){t.value=!0,s.value=null;try{const m=i.value||$(o.value);return await e.generateSummary(o.value,m)}catch(m){throw s.value=m instanceof Error?m:new Error("Summary generation failed"),s.value}finally{t.value=!1}}function L(){r.value=[],l.value=[],u.value=null}function H(m){const f=e.extractFromDOM(m);return f&&(o.value=f.data,i.value=f.schema),f}function J(m,f,w){const k=e.normalizeVueData(m,f,w);o.value=k.data,i.value=k.schema}function U(m){e.initializeQA(m)}return{client:e,loading:t,error:s,lastResult:a,data:o,schema:i,questionHistory:r,answerHistory:l,lastAnswer:u,analyze:d,getDescriptiveStats:y,detectAnomalies:v,performClustering:b,predict:C,askQuestion:B,generateSummary:_,clearHistory:L,extractFromDOM:H,loadFromVueGrid:J,updateConfig:E,initializeQA:U,setData:q,reset:D}}const Z={class:"ti-question-input"},ee={class:"ti-input-wrapper"},te=["placeholder","disabled","onKeydown"],ne=["disabled"],se={key:0},ae={key:1,class:"ti-loading"},oe={key:0,class:"ti-hint"},re=n.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:e}){const t=c,s=e,a=n.ref("");function o(){a.value.trim()&&!t.disabled&&!t.loading&&(s("submit",a.value.trim()),a.value="")}function i(r){}return(r,l)=>(n.openBlock(),n.createElementBlock("div",Z,[n.createElementVNode("div",ee,[n.withDirectives(n.createElementVNode("textarea",{"onUpdate:modelValue":l[0]||(l[0]=u=>a.value=u),placeholder:r.placeholder,disabled:r.disabled,class:"ti-textarea",rows:"2",onKeydown:[n.withKeys(n.withModifiers(o,["exact","prevent"]),["enter"]),n.withKeys(n.withModifiers(i,["shift"]),["enter"])]},null,40,te),[[n.vModelText,a.value]]),n.createElementVNode("button",{disabled:r.disabled||!a.value.trim(),class:"ti-submit-btn",onClick:o},[r.loading?(n.openBlock(),n.createElementBlock("span",ae,n.toDisplayString(r.loadingLabel),1)):(n.openBlock(),n.createElementBlock("span",se,n.toDisplayString(r.submitLabel),1))],8,ne)]),r.showHint?(n.openBlock(),n.createElementBlock("div",oe,n.toDisplayString(r.hint),1)):n.createCommentVNode("",!0)]))}}),M=(c,e)=>{const t=c.__vccOpts||c;for(const[s,a]of e)t[s]=a;return t},ie=M(re,[["__scopeId","data-v-90db5921"]]),le={class:"ti-answer-header"},ce={class:"ti-answer-icon"},ue={key:0},de={key:1},me={class:"ti-answer-meta"},pe={class:"ti-confidence"},he={class:"ti-timestamp"},fe={class:"ti-answer-text"},ge={key:0,class:"ti-approximate-notice"},ye={key:1,class:"ti-reason"},we={key:2,class:"ti-supporting-data"},ve={key:0,class:"ti-supporting-content"},ke={key:0,class:"ti-aggregates"},be={key:1,class:"ti-rows"},Ee={class:"ti-table-wrapper"},Ae={class:"ti-table"},Ce=n.defineComponent({__name:"AnswerDisplay",props:{answer:{}},setup(c){const e=n.ref(!1);function t(s){return new Date(s).toLocaleTimeString()}return(s,a)=>(n.openBlock(),n.createElementBlock("div",{class:n.normalizeClass(["ti-answer-display",{"ti-cannot-answer":s.answer.cannotAnswer}])},[n.createElementVNode("div",le,[n.createElementVNode("div",ce,[s.answer.cannotAnswer?(n.openBlock(),n.createElementBlock("span",de,"⚠️")):(n.openBlock(),n.createElementBlock("span",ue,"💡"))]),n.createElementVNode("div",me,[n.createElementVNode("div",pe," Confidence: "+n.toDisplayString(Math.round(s.answer.confidence*100))+"% ",1),n.createElementVNode("div",he,n.toDisplayString(t(s.answer.timestamp)),1)])]),n.createElementVNode("div",fe,n.toDisplayString(s.answer.text),1),s.answer.isApproximate?(n.openBlock(),n.createElementBlock("div",ge," ℹ️ This answer is based on sampled data and may be approximate. ")):n.createCommentVNode("",!0),s.answer.reason&&s.answer.cannotAnswer?(n.openBlock(),n.createElementBlock("div",ye,[a[1]||(a[1]=n.createElementVNode("strong",null,"Reason:",-1)),n.createTextVNode(" "+n.toDisplayString(s.answer.reason),1)])):n.createCommentVNode("",!0),s.answer.supportingData?(n.openBlock(),n.createElementBlock("div",we,[n.createElementVNode("button",{class:"ti-toggle-btn",onClick:a[0]||(a[0]=o=>e.value=!e.value)},n.toDisplayString(e.value?"▼":"▶")+" Supporting Data ",1),e.value?(n.openBlock(),n.createElementBlock("div",ve,[s.answer.supportingData.aggregates?(n.openBlock(),n.createElementBlock("div",ke,[a[2]||(a[2]=n.createElementVNode("h4",null,"Aggregates:",-1)),n.createElementVNode("pre",null,n.toDisplayString(JSON.stringify(s.answer.supportingData.aggregates,null,2)),1)])):n.createCommentVNode("",!0),s.answer.supportingData.rows&&s.answer.supportingData.rows.length>0?(n.openBlock(),n.createElementBlock("div",be,[n.createElementVNode("h4",null,"Sample Rows ("+n.toDisplayString(s.answer.supportingData.rows.length)+"):",1),n.createElementVNode("div",Ee,[n.createElementVNode("table",Ae,[n.createElementVNode("thead",null,[n.createElementVNode("tr",null,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(Object.keys(s.answer.supportingData.rows[0]),(o,i)=>(n.openBlock(),n.createElementBlock("th",{key:i},n.toDisplayString(o),1))),128))])]),n.createElementVNode("tbody",null,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(s.answer.supportingData.rows.slice(0,5),(o,i)=>(n.openBlock(),n.createElementBlock("tr",{key:i},[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(Object.keys(o),(r,l)=>(n.openBlock(),n.createElementBlock("td",{key:l},n.toDisplayString(o[r]),1))),128))]))),128))])])])])):n.createCommentVNode("",!0)])):n.createCommentVNode("",!0)])):n.createCommentVNode("",!0)],2))}}),Se=M(Ce,[["__scopeId","data-v-d1aaae1d"]]),$e={class:"ti-question-history"},De={class:"ti-history-header"},Ne={key:0,class:"ti-empty-state"},_e={key:1,class:"ti-history-list"},Be=["onClick"],qe={class:"ti-question-header"},Te={class:"ti-question-number"},Ve={class:"ti-question-time"},xe={class:"ti-question-text"},Ie={key:0,class:"ti-question-context"},Me=n.defineComponent({__name:"QuestionHistory",props:{questions:{}},emits:["clear","select"],setup(c,{emit:e}){const t=c,s=n.computed(()=>[...t.questions].reverse());function a(o){const i=new Date(o),l=new Date().getTime()-i.getTime(),u=Math.floor(l/6e4),h=Math.floor(l/36e5),p=Math.floor(l/864e5);return u<1?"Just now":u<60?`${u}m ago`:h<24?`${h}h ago`:`${p}d ago`}return(o,i)=>(n.openBlock(),n.createElementBlock("div",$e,[n.createElementVNode("div",De,[i[1]||(i[1]=n.createElementVNode("h3",null,"Question History",-1)),o.questions.length>0?(n.openBlock(),n.createElementBlock("button",{key:0,class:"ti-clear-btn",onClick:i[0]||(i[0]=r=>o.$emit("clear"))}," Clear History ")):n.createCommentVNode("",!0)]),o.questions.length===0?(n.openBlock(),n.createElementBlock("div",Ne,i[2]||(i[2]=[n.createElementVNode("div",{class:"ti-empty-icon"},"💬",-1),n.createElementVNode("p",null,"No questions asked yet",-1),n.createElementVNode("p",{class:"ti-empty-hint"},"Ask a question about your data to get started",-1)]))):(n.openBlock(),n.createElementBlock("div",_e,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(s.value,(r,l)=>(n.openBlock(),n.createElementBlock("div",{key:r.id,class:"ti-history-item",onClick:u=>o.$emit("select",r)},[n.createElementVNode("div",qe,[n.createElementVNode("span",Te,"#"+n.toDisplayString(o.questions.length-l),1),n.createElementVNode("span",Ve,n.toDisplayString(a(r.timestamp)),1)]),n.createElementVNode("div",xe,n.toDisplayString(r.text),1),r.context?(n.openBlock(),n.createElementBlock("div",Ie,n.toDisplayString(r.context.rowCount)+" rows ",1)):n.createCommentVNode("",!0)],8,Be))),128))]))]))}}),Pe=M(Me,[["__scopeId","data-v-c66393d9"]]);exports.AnswerDisplay=Se;exports.QAEngine=T;exports.QuestionHistory=Pe;exports.QuestionInput=ie;exports.TabularIntelligence=R;exports.calculateStats=x;exports.convertToTabular=z;exports.detectAnomalies=P;exports.executeAPIRequest=I;exports.executeMultipleRequests=W;exports.extractFromDOM=O;exports.inferColumnType=V;exports.inferSchema=$;exports.normalizeVueData=Q;exports.parsePostmanCollection=F;exports.replaceVariables=S;exports.useTabularIntelligence=X;
|
|
30
|
+
`,r}async callLLM(e){const{provider:t,apiKey:s,baseUrl:o,model:a,maxTokens:i,temperature:r}=this.config;if(t==="openai")return this.callOpenAI(e,s,a||"gpt-4-turbo-preview",i,r);if(t==="anthropic")return this.callAnthropic(e,s,a||"claude-3-5-sonnet-20241022",i,r);if(t==="custom"&&o)return this.callCustomAPI(e,o,s);throw new Error(`Unsupported provider: ${t}`)}async callOpenAI(e,t,s,o,a){var l,u;const i=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:s,messages:[{role:"user",content:e}],max_tokens:o,temperature:a,response_format:{type:"json_object"}})});if(!i.ok)throw new Error(`OpenAI API error: ${i.statusText}`);return((u=(l=(await i.json()).choices[0])==null?void 0:l.message)==null?void 0:u.content)||""}async callAnthropic(e,t,s,o,a){var l;const i=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:s,max_tokens:o,temperature:a,messages:[{role:"user",content:e}]})});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(e,t,s){const o={"Content-Type":"application/json"};s&&(o.Authorization=`Bearer ${s}`);const a=await fetch(t,{method:"POST",headers:o,body:JSON.stringify({prompt:e})});if(!a.ok)throw new Error(`Custom API error: ${a.statusText}`);const i=await a.json();return i.response||i.answer||JSON.stringify(i)}parseResponse(e,t,s){try{const o=JSON.parse(e);return{questionId:this.generateId(),text:o.answer||o.text||e,timestamp:new Date,confidence:o.confidence||.8,cannotAnswer:o.cannotAnswer||!1,isApproximate:o.isApproximate!==void 0?o.isApproximate:s,supportingData:o.supportingData,reason:o.reason}}catch{return{questionId:this.generateId(),text:e,timestamp:new Date,confidence:.7,isApproximate:s}}}generateId(){return`qa_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function O(c={}){const{selector:e="table",includeHeaders:t=!0,maxRows:s,inferTypes:o=!0,skipEmptyRows:a=!0}=c,i=document.querySelector(e);if(!i||i.tagName!=="TABLE")return console.warn(`No table found with selector: ${e}`),null;const l=Array.from(i.rows);if(l.length===0)return null;let u=[],h=0;if(t&&l[0]){const y=l[0];u=Array.from(y.cells).map((v,b)=>{var E;return((E=v.textContent)==null?void 0:E.trim())||""||`Column${b+1}`}),h=1}else{const y=l[0];u=Array.from(y.cells).map((v,b)=>`Column${b+1}`)}const p=[],d=s?l.slice(h,h+s):l.slice(h);for(const y of d){const v=Array.from(y.cells);if(a&&v.every(C=>{var E;return!((E=C.textContent)!=null&&E.trim())}))continue;const b={};v.forEach((C,E)=>{var x;const B=u[E]||`Column${E+1}`;let D=((x=C.textContent)==null?void 0:x.trim())||"";if(o&&D){const _=parseFloat(D);!isNaN(_)&&D===_.toString()&&(D=_)}b[B]=D}),p.push(b)}return{schema:o&&p.length>0?$(p,"Extracted Table"):G(u,p.length),data:p,source:"dom",metadata:{selector:e,rowCount:p.length,columnCount:u.length,extractedAt:new Date}}}function Q(c,e,t={}){const{maxRows:s,inferTypes:o=!0}=t,a=s?c.slice(0,s):c;let i;return e&&e.length>0?i={name:"Vue Data Grid",columns:e.map(r=>({name:r.field,type:o&&a.length>0?q(a,r.field):"string",nullable:!0})),rowCount:a.length}:a.length>0?i=$(a,"Vue Data Grid"):i={name:"Vue Data Grid",columns:[],rowCount:0},{schema:i,data:a,source:"vue",metadata:{rowCount:a.length,columnCount:i.columns.length,extractedAt:new Date}}}function G(c,e=0){return{name:"Extracted Table",columns:c.map(t=>({name:t,type:"string",nullable:!0})),rowCount:e}}function F(c){const e={};c.variable&&c.variable.forEach(a=>{e[a.key]=a.value});const t=c.auth?j(c.auth):void 0,s=[];function o(a,i=""){a.forEach(r=>{r.item?o(r.item,i?`${i}/${r.name}`:r.name):r.request&&s.push(Y(r,t))})}return o(c.item),{name:c.info.name,description:c.info.description,endpoints:s,variables:e,auth:t}}function Y(c,e){const t=c.request,s={};t.header&&t.header.forEach(i=>{s[i.key]=i.value});const o={};t.url.query&&t.url.query.forEach(i=>{o[i.key]=i.value});const a=t.auth?j(t.auth):e;return{name:c.name,method:t.method,url:t.url.raw,description:t.description,headers:s,queryParams:o,auth:a}}function j(c){const e={};return c.apikey?c.apikey.forEach(t=>{e[t.key]=t.value}):c.bearer?c.bearer.forEach(t=>{e[t.key]=t.value}):c.basic&&c.basic.forEach(t=>{e[t.key]=t.value}),{type:c.type,credentials:e}}function S(c,e){let t=c;return Object.keys(e).forEach(s=>{const o=new RegExp(`{{${s}}}`,"g");t=t.replace(o,e[s])}),t}async function I(c){const{endpoint:e,variables:t={},additionalHeaders:s={},additionalParams:o={}}=c;try{let a=S(e.url,t);const i={...e.queryParams,...t,...o},r=Object.keys(i).filter(d=>i[d]!==void 0&&i[d]!=="").map(d=>`${encodeURIComponent(d)}=${encodeURIComponent(S(String(i[d]),t))}`).join("&");r&&(a=a.includes("?")?`${a}&${r}`:`${a}?${r}`);const l={"Content-Type":"application/json",...e.headers,...s};if(Object.keys(l).forEach(d=>{l[d]=S(l[d],t)}),e.auth){if(e.auth.type==="apikey"){const d=e.auth.credentials.key||"access_key",g=S(e.auth.credentials.value||"",t);e.auth.credentials.in==="header"&&(l[d]=g)}else if(e.auth.type==="bearer"){const d=S(e.auth.credentials.token||"",t);l.Authorization=`Bearer ${d}`}else if(e.auth.type==="basic"){const d=S(e.auth.credentials.username||"",t),g=S(e.auth.credentials.password||"",t),y=btoa(`${d}:${g}`);l.Authorization=`Basic ${y}`}}const u=await fetch(a,{method:e.method,headers:l}),h={};return u.headers.forEach((d,g)=>{h[g]=d}),u.ok?{success:!0,data:await u.json(),statusCode:u.status,headers:h}:{success:!1,error:`HTTP ${u.status}: ${u.statusText}`,statusCode:u.status,headers:h}}catch(a){return{success:!1,error:a.message||"Unknown error occurred"}}}async function W(c,e={}){const t=[];for(const s of c){const o=await I({endpoint:s,variables:e});t.push(o)}return t}function z(c){if(!c.success||!c.data)return[];const e=c.data;return Array.isArray(e)?e:e.data&&Array.isArray(e.data)?e.data:e.results&&Array.isArray(e.results)?e.results:e.items&&Array.isArray(e.items)?e.items:typeof e=="object"?[e]:[]}class R{constructor(e,t){this.config={timeout:3e4,...e},t&&(this.qaEngine=new T(t))}initializeQA(e){this.qaEngine=new T(e)}async callTFM(e){const t=Date.now();try{let s=this.config.baseUrl;this.config.useCorsProxy&&this.config.corsProxyUrl&&(this.config.corsProxyUrl.includes("?")?s=this.config.corsProxyUrl+encodeURIComponent(s):s=(this.config.corsProxyUrl.endsWith("/")?this.config.corsProxyUrl:this.config.corsProxyUrl+"/")+s,console.log("Using CORS proxy for TFM API call:",this.config.corsProxyUrl),console.log("Proxied URL:",s));const o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",...this.config.apiKey&&{Authorization:`Bearer ${this.config.apiKey}`},...this.config.headers},body:JSON.stringify({...e,model:this.config.model}),signal:AbortSignal.timeout(this.config.timeout||3e4)});if(!o.ok){const r=await o.text();throw new Error(`TFM API error: ${o.status} - ${r}`)}const a=await o.json(),i=Date.now()-t;return{success:!0,result:a.result||a,metadata:{processingTime:i,model:this.config.model||"unknown",version:a.version}}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error",metadata:{processingTime:Date.now()-t,model:this.config.model||"unknown"}}}}async analyze(e){const t={operation:e.type,data:e.data,schema:e.schema,parameters:e.options},s=await this.callTFM(t);if(!s.success)throw new Error(s.error||"Analysis failed");return this.parseAnalysisResult(e.type,s.result,s.metadata)}parseAnalysisResult(e,t,s){const o={type:e,timestamp:new Date,summary:t.summary||"",insights:t.insights||[],recommendations:t.recommendations,confidence:t.confidence||.8,processingTime:s==null?void 0:s.processingTime};switch(e){case"descriptive_stats":return{...o,descriptiveStats:t.stats||t.descriptiveStats};case"anomaly_detection":return{...o,anomalies:t.anomalies||[]};case"segmentation":case"clustering":return{...o,clusters:t.clusters||[]};case"prediction":return{...o,predictions:t.predictions||t};case"correlation":return{...o,correlations:t.correlations||t};case"summary":return{...o,aiSummary:t.summary||t};case"qa":return{...o,qaAnswer:t.answer||t};default:return o}}async askQuestion(e){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Call initializeQA() first.");return this.qaEngine.answerQuestion(e)}async generateSummary(e,t){const s={type:"summary",data:e,schema:t},o=await this.analyze(s);if(!o.aiSummary)throw new Error("Failed to generate summary");return o.aiSummary}extractFromDOM(e){return O(e)}normalizeVueData(e,t,s){return Q(e,t,s)}updateConfig(e){this.config={...this.config,...e}}getConfig(){const{apiKey:e,...t}=this.config;return t}loadPostmanCollection(e){return this.parsedCollection=F(e),this.parsedCollection}getCollection(){return this.parsedCollection}getEndpoints(){var e;return((e=this.parsedCollection)==null?void 0:e.endpoints)||[]}async fetchDataFromAPI(e,t){if(!this.parsedCollection)throw new Error("No Postman collection loaded. Call loadPostmanCollection() first.");const s=this.parsedCollection.endpoints.find(l=>l.name===e);if(!s)throw new Error(`Endpoint "${e}" not found in collection.`);const o={...this.parsedCollection.variables,...t},a=await I({endpoint:s,variables:o});if(!a.success)throw new Error(`API request failed: ${a.error}`);const i=z(a),r=$(i);return{data:i,schema:r}}async queryAPI(e){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Provide qaConfig in constructor or call initializeQA().");const t=Date.now(),{data:s,schema:o}=await this.fetchDataFromAPI(e.dataSource.endpoint||"",e.variables),a={question:e.question,schema:o,data:s},i=await this.qaEngine.answerQuestion(a),r=Date.now()-t;return{answer:i.answer,apiResponse:s,endpoint:e.dataSource.endpoint,executionTime:r}}listEndpoints(){return this.parsedCollection?this.parsedCollection.endpoints.map(e=>({name:e.name,method:e.method,description:e.description})):[]}}function X(c){const e=new R(c.config,c.qaConfig),t=n.ref(!1),s=n.ref(null),o=n.ref(null),a=c.data||n.ref([]),i=c.schema||n.ref(null),r=n.ref([]),l=n.ref([]),u=n.ref(null),h=c.maxQuestionHistory||50,p=c.useLocalFallback!==!1;async function d(m,f){t.value=!0,s.value=null;try{const w={type:m,data:a.value,schema:i.value||void 0,options:f},k=await e.analyze(w);return o.value=k,k}catch(w){if(s.value=w instanceof Error?w:new Error("Analysis failed"),p)return g(m,f);throw s.value}finally{t.value=!1}}function g(m,f){const w=i.value||$(a.value);switch(m){case"descriptive_stats":{const k=w.columns.map(N=>V(a.value,N.name,N.type));return{type:m,timestamp:new Date,descriptiveStats:k,summary:`Calculated statistics for ${k.length} columns`,insights:[],confidence:.9}}case"anomaly_detection":{const k=w.columns.filter(A=>A.type==="number").map(A=>A.name),N=M(a.value,k,f==null?void 0:f.sensitivity);return{type:m,timestamp:new Date,anomalies:N,summary:`Found ${N.length} anomalies`,insights:N.slice(0,3).map(A=>A.reasons[0]),confidence:.8}}default:throw new Error(`Local analysis not supported for type: ${m}`)}}async function y(){return(await d("descriptive_stats")).descriptiveStats||[]}async function v(m,f){return(await d("anomaly_detection",{sensitivity:f,features:m})).anomalies||[]}async function b(m,f=3){return d("clustering",{features:m,numClusters:f})}async function C(m,f){return d("prediction",{targetColumn:m,...f})}function E(m){e.updateConfig(m)}function B(m,f=!0){a.value=m,f&&(i.value=$(m))}function D(){t.value=!1,s.value=null,o.value=null,r.value=[],l.value=[],u.value=null}async function x(m,f){t.value=!0,s.value=null;try{const w=i.value||$(a.value),k={question:m,schema:w,data:a.value,sampleSize:100,includeAggregates:!0,...f},A=(await e.askQuestion(k)).answer,K={id:A.questionId,text:m,timestamp:new Date,context:{tableSchema:w,rowCount:a.value.length}};return r.value.push(K),l.value.push(A),u.value=A,r.value.length>h&&(r.value.shift(),l.value.shift()),A}catch(w){throw s.value=w instanceof Error?w:new Error("Q&A failed"),s.value}finally{t.value=!1}}async function _(){t.value=!0,s.value=null;try{const m=i.value||$(a.value);return await e.generateSummary(a.value,m)}catch(m){throw s.value=m instanceof Error?m:new Error("Summary generation failed"),s.value}finally{t.value=!1}}function L(){r.value=[],l.value=[],u.value=null}function U(m){const f=e.extractFromDOM(m);return f&&(a.value=f.data,i.value=f.schema),f}function H(m,f,w){const k=e.normalizeVueData(m,f,w);a.value=k.data,i.value=k.schema}function J(m){e.initializeQA(m)}return{client:e,loading:t,error:s,lastResult:o,data:a,schema:i,questionHistory:r,answerHistory:l,lastAnswer:u,analyze:d,getDescriptiveStats:y,detectAnomalies:v,performClustering:b,predict:C,askQuestion:x,generateSummary:_,clearHistory:L,extractFromDOM:U,loadFromVueGrid:H,updateConfig:E,initializeQA:J,setData:B,reset:D}}const Z={class:"ti-question-input"},ee={class:"ti-input-wrapper"},te=["placeholder","disabled","onKeydown"],ne=["disabled"],se={key:0},oe={key:1,class:"ti-loading"},ae={key:0,class:"ti-hint"},re=n.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:e}){const t=c,s=e,o=n.ref("");function a(){o.value.trim()&&!t.disabled&&!t.loading&&(s("submit",o.value.trim()),o.value="")}function i(r){}return(r,l)=>(n.openBlock(),n.createElementBlock("div",Z,[n.createElementVNode("div",ee,[n.withDirectives(n.createElementVNode("textarea",{"onUpdate:modelValue":l[0]||(l[0]=u=>o.value=u),placeholder:r.placeholder,disabled:r.disabled,class:"ti-textarea",rows:"2",onKeydown:[n.withKeys(n.withModifiers(a,["exact","prevent"]),["enter"]),n.withKeys(n.withModifiers(i,["shift"]),["enter"])]},null,40,te),[[n.vModelText,o.value]]),n.createElementVNode("button",{disabled:r.disabled||!o.value.trim(),class:"ti-submit-btn",onClick:a},[r.loading?(n.openBlock(),n.createElementBlock("span",oe,n.toDisplayString(r.loadingLabel),1)):(n.openBlock(),n.createElementBlock("span",se,n.toDisplayString(r.submitLabel),1))],8,ne)]),r.showHint?(n.openBlock(),n.createElementBlock("div",ae,n.toDisplayString(r.hint),1)):n.createCommentVNode("",!0)]))}}),P=(c,e)=>{const t=c.__vccOpts||c;for(const[s,o]of e)t[s]=o;return t},ie=P(re,[["__scopeId","data-v-90db5921"]]),le={class:"ti-answer-header"},ce={class:"ti-answer-icon"},ue={key:0},de={key:1},me={class:"ti-answer-meta"},pe={class:"ti-confidence"},he={class:"ti-timestamp"},fe={class:"ti-answer-text"},ge={key:0,class:"ti-approximate-notice"},ye={key:1,class:"ti-reason"},we={key:2,class:"ti-supporting-data"},ve={key:0,class:"ti-supporting-content"},ke={key:0,class:"ti-aggregates"},be={key:1,class:"ti-rows"},Ee={class:"ti-table-wrapper"},Ae={class:"ti-table"},Ce=n.defineComponent({__name:"AnswerDisplay",props:{answer:{}},setup(c){const e=n.ref(!1);function t(s){return new Date(s).toLocaleTimeString()}return(s,o)=>(n.openBlock(),n.createElementBlock("div",{class:n.normalizeClass(["ti-answer-display",{"ti-cannot-answer":s.answer.cannotAnswer}])},[n.createElementVNode("div",le,[n.createElementVNode("div",ce,[s.answer.cannotAnswer?(n.openBlock(),n.createElementBlock("span",de,"⚠️")):(n.openBlock(),n.createElementBlock("span",ue,"💡"))]),n.createElementVNode("div",me,[n.createElementVNode("div",pe," Confidence: "+n.toDisplayString(Math.round(s.answer.confidence*100))+"% ",1),n.createElementVNode("div",he,n.toDisplayString(t(s.answer.timestamp)),1)])]),n.createElementVNode("div",fe,n.toDisplayString(s.answer.text),1),s.answer.isApproximate?(n.openBlock(),n.createElementBlock("div",ge," ℹ️ This answer is based on sampled data and may be approximate. ")):n.createCommentVNode("",!0),s.answer.reason&&s.answer.cannotAnswer?(n.openBlock(),n.createElementBlock("div",ye,[o[1]||(o[1]=n.createElementVNode("strong",null,"Reason:",-1)),n.createTextVNode(" "+n.toDisplayString(s.answer.reason),1)])):n.createCommentVNode("",!0),s.answer.supportingData?(n.openBlock(),n.createElementBlock("div",we,[n.createElementVNode("button",{class:"ti-toggle-btn",onClick:o[0]||(o[0]=a=>e.value=!e.value)},n.toDisplayString(e.value?"▼":"▶")+" Supporting Data ",1),e.value?(n.openBlock(),n.createElementBlock("div",ve,[s.answer.supportingData.aggregates?(n.openBlock(),n.createElementBlock("div",ke,[o[2]||(o[2]=n.createElementVNode("h4",null,"Aggregates:",-1)),n.createElementVNode("pre",null,n.toDisplayString(JSON.stringify(s.answer.supportingData.aggregates,null,2)),1)])):n.createCommentVNode("",!0),s.answer.supportingData.rows&&s.answer.supportingData.rows.length>0?(n.openBlock(),n.createElementBlock("div",be,[n.createElementVNode("h4",null,"Sample Rows ("+n.toDisplayString(s.answer.supportingData.rows.length)+"):",1),n.createElementVNode("div",Ee,[n.createElementVNode("table",Ae,[n.createElementVNode("thead",null,[n.createElementVNode("tr",null,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(Object.keys(s.answer.supportingData.rows[0]),(a,i)=>(n.openBlock(),n.createElementBlock("th",{key:i},n.toDisplayString(a),1))),128))])]),n.createElementVNode("tbody",null,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(s.answer.supportingData.rows.slice(0,5),(a,i)=>(n.openBlock(),n.createElementBlock("tr",{key:i},[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(Object.keys(a),(r,l)=>(n.openBlock(),n.createElementBlock("td",{key:l},n.toDisplayString(a[r]),1))),128))]))),128))])])])])):n.createCommentVNode("",!0)])):n.createCommentVNode("",!0)])):n.createCommentVNode("",!0)],2))}}),Se=P(Ce,[["__scopeId","data-v-d1aaae1d"]]),$e={class:"ti-question-history"},De={class:"ti-history-header"},Ne={key:0,class:"ti-empty-state"},_e={key:1,class:"ti-history-list"},xe=["onClick"],Be={class:"ti-question-header"},Te={class:"ti-question-number"},qe={class:"ti-question-time"},Ve={class:"ti-question-text"},Ie={key:0,class:"ti-question-context"},Pe=n.defineComponent({__name:"QuestionHistory",props:{questions:{}},emits:["clear","select"],setup(c,{emit:e}){const t=c,s=n.computed(()=>[...t.questions].reverse());function o(a){const i=new Date(a),l=new Date().getTime()-i.getTime(),u=Math.floor(l/6e4),h=Math.floor(l/36e5),p=Math.floor(l/864e5);return u<1?"Just now":u<60?`${u}m ago`:h<24?`${h}h ago`:`${p}d ago`}return(a,i)=>(n.openBlock(),n.createElementBlock("div",$e,[n.createElementVNode("div",De,[i[1]||(i[1]=n.createElementVNode("h3",null,"Question History",-1)),a.questions.length>0?(n.openBlock(),n.createElementBlock("button",{key:0,class:"ti-clear-btn",onClick:i[0]||(i[0]=r=>a.$emit("clear"))}," Clear History ")):n.createCommentVNode("",!0)]),a.questions.length===0?(n.openBlock(),n.createElementBlock("div",Ne,i[2]||(i[2]=[n.createElementVNode("div",{class:"ti-empty-icon"},"💬",-1),n.createElementVNode("p",null,"No questions asked yet",-1),n.createElementVNode("p",{class:"ti-empty-hint"},"Ask a question about your data to get started",-1)]))):(n.openBlock(),n.createElementBlock("div",_e,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(s.value,(r,l)=>(n.openBlock(),n.createElementBlock("div",{key:r.id,class:"ti-history-item",onClick:u=>a.$emit("select",r)},[n.createElementVNode("div",Be,[n.createElementVNode("span",Te,"#"+n.toDisplayString(a.questions.length-l),1),n.createElementVNode("span",qe,n.toDisplayString(o(r.timestamp)),1)]),n.createElementVNode("div",Ve,n.toDisplayString(r.text),1),r.context?(n.openBlock(),n.createElementBlock("div",Ie,n.toDisplayString(r.context.rowCount)+" rows ",1)):n.createCommentVNode("",!0)],8,xe))),128))]))]))}}),Me=P(Pe,[["__scopeId","data-v-c66393d9"]]);exports.AnswerDisplay=Se;exports.QAEngine=T;exports.QuestionHistory=Me;exports.QuestionInput=ie;exports.TabularIntelligence=R;exports.calculateStats=V;exports.convertToTabular=z;exports.detectAnomalies=M;exports.executeAPIRequest=I;exports.executeMultipleRequests=W;exports.extractFromDOM=O;exports.inferColumnType=q;exports.inferSchema=$;exports.normalizeVueData=Q;exports.parsePostmanCollection=F;exports.replaceVariables=S;exports.useTabularIntelligence=X;
|
|
31
31
|
//# sourceMappingURL=index.js.map
|