mycai 1.0.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/LICENSE +23 -0
- package/README.md +119 -0
- package/bin/mycai.js +156 -0
- package/core/ghr_lattice_memory.js +401 -0
- package/core/hdc.js +312 -0
- package/core/memory.js +60 -0
- package/core/memory_engine.js +444 -0
- package/core/morphology.js +357 -0
- package/core/phase.js +87 -0
- package/core/reasoning_router.js +628 -0
- package/core/resonance.js +118 -0
- package/core/safetensors.js +62 -0
- package/core/sovereign_agent.js +164 -0
- package/core/spectral.js +259 -0
- package/core/spectral_decoder.js +868 -0
- package/dist/resonance_sdk.js +2703 -0
- package/dist/resonance_sdk.min.js +14 -0
- package/dist/spectral_core.wasm +0 -0
- package/index.d.ts +45 -0
- package/index.js +26 -0
- package/package.json +52 -0
- package/sdk/README.md +154 -0
- package/sdk/examples/banking_assistant.js +61 -0
- package/sdk/examples/browser_example.html +104 -0
- package/sdk/examples/express_integration.js +61 -0
- package/sdk/examples/node_example.js +33 -0
- package/sdk/examples/quickstart.js +55 -0
- package/sdk/index.js +22 -0
- package/sdk/ingestion.js +237 -0
- package/sdk/licensing.js +168 -0
- package/sdk/resonance_engine.js +594 -0
- package/sdk/resonance_sdk.js +792 -0
- package/sdk/storage.js +185 -0
- package/sdk/tests/sdk_verification.js +98 -0
- package/sdk/tests/test_commercial_sdk.js +136 -0
- package/sdk/types.d.ts +152 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
var A=class{constructor(e=[]){this.onVowels=new Set(["e","i","\xF6","\xFC"]),this.backVowels=new Set(["a","\u0131","o","u"]),this.allVowels=new Set(["a","e","\u0131","i","o","\xF6","u","\xFC"]),this.customRoots=e,this.suffixFeatures={ler:{number:"plural"},lar:{number:"plural"},den:{case:"ablative"},dan:{case:"ablative"},ten:{case:"ablative"},tan:{case:"ablative"},de:{case:"locative"},da:{case:"locative"},te:{case:"locative"},ta:{case:"locative"},e:{case:"dative"},a:{case:"dative"},in:{case:"genitive"},\u0131n:{case:"genitive"},un:{case:"genitive"},\u00FCn:{case:"genitive"},im:{possession:"1sg"},\u0131m:{possession:"1sg"},um:{possession:"1sg"},\u00FCm:{possession:"1sg"},in:{possession:"2sg"},\u0131n:{possession:"2sg"},un:{possession:"2sg"},\u00FCn:{possession:"2sg"},i:{possession:"3sg"},\u0131:{possession:"3sg"},u:{possession:"3sg"},\u00FC:{possession:"3sg"},imiz:{possession:"1pl"},\u0131m\u0131z:{possession:"1pl"},umuz:{possession:"1pl"},\u00FCm\u00FCz:{possession:"1pl"},iniz:{possession:"2pl"},\u0131n\u0131z:{possession:"2pl"},\u00FCn\u00FCz:{possession:"2pl"},unuz:{possession:"2pl"},leri:{possession:"3pl"},lar\u0131:{possession:"3pl"},iyor:{tense:"present"},\u0131yor:{tense:"present"},uyor:{tense:"present"},\u00FCyor:{tense:"present"},ecek:{tense:"future"},acak:{tense:"future"},mi\u015F:{tense:"narrative_past"},m\u0131\u015F:{tense:"narrative_past"},m\u00FC\u015F:{tense:"narrative_past"},mu\u015F:{tense:"narrative_past"},di:{tense:"past"},d\u0131:{tense:"past"},du:{tense:"past"},d\u00FC:{tense:"past"},ti:{tense:"past"},t\u0131:{tense:"past"},tu:{tense:"past"},t\u00FC:{tense:"past"},mek:{aspect:"infinitive"},mak:{aspect:"infinitive"},lik:{derivation:"noun"},l\u0131k:{derivation:"noun"},luk:{derivation:"noun"},l\u00FCk:{derivation:"noun"},li:{derivation:"with"},l\u0131:{derivation:"with"},lu:{derivation:"with"},l\u00FC:{derivation:"with"},siz:{derivation:"without"},s\u0131z:{derivation:"without"},suz:{derivation:"without"},s\u00FCz:{derivation:"without"},ce:{case:"equative"},ca:{case:"equative"},\u00E7a:{case:"equative"},\u00E7e:{case:"equative"},dir:{copula:"assertive"},d\u0131r:{copula:"assertive"},dur:{copula:"assertive"},d\u00FCr:{copula:"assertive"},tir:{copula:"assertive"},t\u0131r:{copula:"assertive"},tur:{copula:"assertive"},t\u00FCr:{copula:"assertive"},ki:{pronoun:"relative"},kiler:{pronoun:"relative_plural"},cesine:{aspect:"manner"},cas\u0131na:{aspect:"manner"},ken:{adverb:"temporal"},meli:{mood:"necessity"},mal\u0131:{mood:"necessity"},se:{mood:"conditional"},sa:{mood:"conditional"}},this.suffixesKnown=Object.keys(this.suffixFeatures).sort((i,t)=>t.length-i.length)}get roots(){return this.customRoots&&this.customRoots.length>0?this.customRoots:typeof globalThis<"u"&&globalThis.TR_CORPUS_ROOTS?globalThis.TR_CORPUS_ROOTS:["ev","g\xF6l","araba","kitap","el","ba\u015F","git","gel","yap","al","ver","g\xF6r","bilgisayar","bil","\xF6\u011Fren","anla","d\xFC\u015F\xFCn","b\xFCy\xFCk","k\xFC\xE7\xFCk","g\xFCzel","iyi","k\xF6t\xFC","yapay","zeka","beyin","sinir","dil","kelime","c\xFCmle","t\xFCrk\xE7e","bilim","teknik","okul","\xF6\u011Frenci","\xF6\u011Fretmen","yaz\u0131l\u0131m","donan\u0131m","renk","ayak","g\xF6z","kulak","diz","omuz","kar\u0131n","g\xF6\u011F\xFCs","s\u0131rt","boyun","kol","bacak","parmak","bilek","topuk","al\u0131n","bel","di\u015F","burun","a\u011F\u0131z","ci\u011Fer","kalp","akci\u011Fer","mide","b\xF6brek","karaci\u011Fer","damar","hasta","doktor","hem\u015Fire","ila\xE7","doz","tan\u0131","tedavi","ameliyat","hastal\u0131k","a\u011Fr\u0131","\u015Fi\u015Flik","ate\u015F","nab\u0131z","tansiyon","kan","idrar","re\xE7ete","a\u015F\u0131","vir\xFCs","enfeksiyon","yara","k\u0131r\u0131k","\xF6dem","alerji","\u015Feker","diyabet","gebelik","do\u011Fum","\xF6l\xE7\xFCm","muayene","rapor","tahlil","yol","su","ekmek","para","i\u015F","g\xFCn","y\u0131l","saat","hafta","ay","yer","\u015Fehir","\xFClke","k\xF6y","insan","kad\u0131n","erkek","\xE7ocuk","anne","baba","ad","isim","aile","soru","cevap","kay\u0131t","bilgi","durum","sonu\xE7","yeni","eski","uzun","k\u0131sa","s\u0131k","az","\xE7ok","son","ilk","her","oku","yaz","bak","\xE7al\u0131\u015F","ye","i\xE7","uyu","kalk","otur","ko\u015F","sor","s\xF6yle","dinle","bekle","ba\u015Fla","bitir","a\xE7","kapat","getir","g\xF6t\xFCr","koy","\xE7\u0131kar","kaydet","g\xFCncelle","kontrol"]}determineVowelHarmony(e){let i=this.getLastVowel(e);return i&&this.onVowels.has(i)?"front":"back"}getLastVowel(e){for(let i=e.length-1;i>=0;i--)if(this.allVowels.has(e[i]))return e[i];return null}normalize(e){return e.toLowerCase().trim().replace(/i̇/g,"i").replace(/[^a-zçgğıoöşuüâîû\s]/g,"")}analyze(e){let i=this.normalize(e).split(/\s+/)[0],t={word:i,root:i,suffixes:[],harmony:this.determineVowelHarmony(i),morphemes:[],features:{},vowelCount:0,syllables:[]};if(!i)return t;t.vowelCount=[...i].filter(n=>this.allVowels.has(n)).length,t.syllables=this.syllabify(i);let a=i,s=[];for(let n of this.roots){let r=!1,l=n.length;if(i.startsWith(n))r=!0;else{let o=n[n.length-1];if(["p","\xE7","t","k"].includes(o)){let h=n.slice(0,-1),u="";if(o==="p"?u=h+"b":o==="\xE7"?u=h+"c":o==="t"?u=h+"d":o==="k"&&(u=h+"\u011F"),n==="renk"&&(u=h+"g"),i.startsWith(u)&&i.length>n.length){let c=i[u.length];this.allVowels.has(c)&&(r=!0,l=u.length)}}}if(r&&n.length>=2&&n.length<i.length){let o=i.slice(l);n.length>(a===i?0:a.length)&&(a=n,s=this.splitSuffix(o))}}return t.root=a,t.suffixes=s,t.morphemes=[a,...s].filter(Boolean),t.harmony=this.determineVowelHarmony(a),s.forEach(n=>{let r=this.suffixFeatures[n];r&&Object.assign(t.features,r)}),t}splitSuffix(e){if(!e)return[];let i=[],t=e;for(;t.length>0;){let a=!1;for(let s of this.suffixesKnown)if(t.endsWith(s)){i.unshift(s),t=t.slice(0,t.length-s.length),a=!0;break}if(!a){i.unshift(t);break}}return i}syllabify(e){let i=this.normalize(e);if(!i)return[];let t=[];for(let n=0;n<i.length;n++)this.allVowels.has(i[n])&&t.push(n);if(t.length<=1)return[i];let a=[],s=0;for(let n=0;n<t.length-1;n++){let r=t[n],l=t[n+1],o=l-r-1,h;o===0||o===1?h=r+1:o===2?h=r+2:h=l-1,a.push(i.slice(s,h)),s=h}return a.push(i.slice(s)),a.filter(Boolean)}syllabifyPhrase(e){let i=e.toLowerCase().trim().split(/\s+/).filter(Boolean);if(i.length===0)return[];if(i.length===1)return this.syllabify(i[0]);let t=[],a=[...i];for(let s=0;s<a.length-1;s++){let n=a[s],r=a[s+1];if(n.length===0||r.length===0)continue;let l=n[n.length-1],o=r[0];!this.allVowels.has(l)&&this.allVowels.has(o)&&(a[s]=n.slice(0,-1),a[s+1]=l+r)}for(let s of a)s.length>0&&t.push(...this.syllabify(s));return t}};var k=class{constructor(e,i,t){this.type=e,this.values=i,this.D=t}memorySize(){return this.values.byteLength}},S=class{constructor(e=8192){this.D=e}generateRandom(e){if(e==="binary"){let t=new Uint8Array(this.D);for(let a=0;a<this.D;a++)t[a]=Math.random()<.5?0:1;return new k("binary",t,this.D)}if(e==="bipolar"){let t=new Float32Array(this.D);for(let a=0;a<this.D;a++)t[a]=Math.random()<.5?-1:1;return new k("bipolar",t,this.D)}if(e==="real"){let t=new Float32Array(this.D);for(let a=0;a<this.D;a++){let s=0,n=0;for(;s===0;)s=Math.random();for(;n===0;)n=Math.random();t[a]=Math.sqrt(-2*Math.log(s))*Math.cos(2*Math.PI*n)}return new k("real",t,this.D)}let i=new Float32Array(this.D);for(let t=0;t<this.D;t++)i[t]=Math.random()*2*Math.PI;return new k("complex",i,this.D)}generateSeeded(e,i){let t=0;for(let n=0;n<i.length;n++)t=t*31+i.charCodeAt(n)>>>0;let a=()=>(t=t*1664525+1013904223>>>0,(t>>>8)/16777216);if(e==="binary"){let n=new Uint8Array(this.D);for(let r=0;r<this.D;r++)n[r]=a()<.5?0:1;return new k("binary",n,this.D)}if(e==="bipolar"){let n=new Float32Array(this.D);for(let r=0;r<this.D;r++)n[r]=a()<.5?-1:1;return new k("bipolar",n,this.D)}if(e==="real"){let n=new Float32Array(this.D);for(let r=0;r<this.D;r++){let l=0,o=0;for(;l===0;)l=a();for(;o===0;)o=a();n[r]=Math.sqrt(-2*Math.log(l))*Math.cos(2*Math.PI*o)}return new k("real",n,this.D)}let s=new Float32Array(this.D);for(let n=0;n<this.D;n++)s[n]=a()*2*Math.PI;return new k("complex",s,this.D)}bind(e,i){if(e.type!==i.type||e.D!==i.D)throw new Error("Representation mismatch for bind operation.");let t=e.D;if(e.type==="binary"){let s=new Uint8Array(t);for(let n=0;n<t;n++)s[n]=e.values[n]^i.values[n];return new k("binary",s,t)}if(e.type==="bipolar"){let s=new Float32Array(t);for(let n=0;n<t;n++)s[n]=e.values[n]*i.values[n];return new k("bipolar",s,t)}if(e.type==="real"){let s=new Float32Array(t);for(let n=0;n<t;n++)s[n]=e.values[n]*i.values[n];return new k("real",s,t)}let a=new Float32Array(t);for(let s=0;s<t;s++)a[s]=(e.values[s]+i.values[s])%(2*Math.PI);return new k("complex",a,t)}unbind(e,i){if(e.type!==i.type||e.D!==i.D)throw new Error("Representation mismatch for unbind operation.");let t=e.D;if(e.type==="binary")return this.bind(e,i);if(e.type==="bipolar")return this.bind(e,i);if(e.type==="real"){let s=new Float32Array(t);for(let n=0;n<t;n++)s[n]=Math.abs(i.values[n])>1e-6?e.values[n]/i.values[n]:e.values[n];return new k("real",s,t)}let a=new Float32Array(t);for(let s=0;s<t;s++){let n=e.values[s]-i.values[s];n<0&&(n+=2*Math.PI),a[s]=n%(2*Math.PI)}return new k("complex",a,t)}bundle(e){if(!e||e.length===0)throw new Error("No representations to bundle.");let i=e[0].type,t=e[0].D;if(i==="binary"){let r=new Uint8Array(t),l=new Int32Array(t);for(let o of e)for(let h=0;h<t;h++)l[h]+=o.values[h]===1?1:-1;for(let o=0;o<t;o++)r[o]=l[o]>=0?1:0;return new k("binary",r,t)}if(i==="bipolar"){let r=new Float32Array(t);for(let l of e)for(let o=0;o<t;o++)r[o]+=l.values[o];for(let l=0;l<t;l++)r[l]=r[l]>=0?1:-1;return new k("bipolar",r,t)}if(i==="real"){let r=new Float32Array(t);for(let o of e)for(let h=0;h<t;h++)r[h]+=o.values[h];let l=e.length;for(let o=0;o<t;o++)r[o]/=l;return new k("real",r,t)}let a=new Float32Array(t),s=new Float32Array(t);for(let r of e)for(let l=0;l<t;l++)a[l]+=Math.cos(r.values[l]),s[l]+=Math.sin(r.values[l]);let n=new Float32Array(t);for(let r=0;r<t;r++){let l=Math.atan2(s[r],a[r]);l<0&&(l+=2*Math.PI),n[r]=l}return new k("complex",n,t)}permute(e,i){let t=e.D,a=(i%t+t)%t,s=new e.values.constructor(t);for(let n=0;n<t;n++)s[(n+a)%t]=e.values[n];return new k(e.type,s,t)}similarity(e,i){if(e.type!==i.type||e.D!==i.D)return 0;let t=e.D;if(e.type==="binary"){let s=0;for(let n=0;n<t;n++)e.values[n]!==i.values[n]&&s++;return 1-s/t}if(e.type==="bipolar"){let s=0;for(let n=0;n<t;n++)s+=e.values[n]*i.values[n];return s/t}if(e.type==="real"){let s=0,n=0,r=0;for(let o=0;o<t;o++)s+=e.values[o]*i.values[o],n+=e.values[o]*e.values[o],r+=i.values[o]*i.values[o];let l=Math.sqrt(n)*Math.sqrt(r);return l>0?s/l:0}let a=0;for(let s=0;s<t;s++)a+=Math.cos(e.values[s]-i.values[s]);return a/t}};import R from"fs";var D=class{constructor(){}_bitReverse(e,i){let t=e.length,a=0;for(let s=0;s<t;s++){if(s<a){let r=e[s];e[s]=e[a],e[a]=r,r=i[s],i[s]=i[a],i[a]=r}let n=t>>1;for(;n>=2&&a>=n;)a-=n,n>>=1;a+=n}}_fftCore(e,i,t=!1){let a=e.length;this._bitReverse(e,i);for(let s=2;s<=a;s<<=1){let n=2*Math.PI/s*(t?1:-1),r=Math.cos(n),l=Math.sin(n);for(let o=0;o<a;o+=s){let h=1,u=0,c=s>>1;for(let d=0;d<c;d++){let y=e[o+d],p=i[o+d],z=e[o+d+c],m=i[o+d+c],f=z*h-m*u,w=z*u+m*h;e[o+d]=y+f,i[o+d]=p+w,e[o+d+c]=y-f,i[o+d+c]=p-w;let v=h*r-u*l,b=h*l+u*r;h=v,u=b}}}if(t)for(let s=0;s<a;s++)e[s]/=a,i[s]/=a}spectralTransform(e){let i=e.D,t=new Float32Array(i),a=new Float32Array(i);if(e.type==="complex")for(let r=0;r<i;r++)t[r]=Math.cos(e.values[r]),a[r]=Math.sin(e.values[r]);else if(e.type==="bipolar"||e.type==="real")for(let r=0;r<i;r++)t[r]=e.values[r],a[r]=0;else if(e.type==="binary")for(let r=0;r<i;r++)t[r]=e.values[r]===1?1:-1,a[r]=0;this._fftCore(t,a,!1);let s=new Float32Array(i),n=new Float32Array(i);for(let r=0;r<i;r++)s[r]=Math.sqrt(t[r]*t[r]+a[r]*a[r]),n[r]=Math.atan2(a[r],t[r]);return{type:e.type,D:i,re:t,im:a,magnitude:s,phase:n}}inverseSpectralTransform(e){let i=e.D,t=new Float32Array(e.re),a=new Float32Array(e.im);if(this._fftCore(t,a,!0),e.type==="complex"){let n=new Float32Array(i);for(let r=0;r<i;r++){let l=Math.atan2(a[r],t[r]);l<0&&(l+=2*Math.PI),n[r]=l}return new k("complex",n,i)}if(e.type==="binary"){let n=new Uint8Array(i);for(let r=0;r<i;r++)n[r]=t[r]>=0?1:0;return new k("binary",n,i)}if(e.type==="bipolar"){let n=new Float32Array(i);for(let r=0;r<i;r++)n[r]=t[r]>=0?1:-1;return new k("bipolar",n,i)}let s=new Float32Array(i);for(let n=0;n<i;n++)s[n]=t[n];return new k("real",s,i)}extractDominantFrequencies(e,i=10){let t=e.D,a=[];for(let s=0;s<t;s++)a.push({freq:s,mag:e.magnitude[s]});return a.sort((s,n)=>n.mag-s.mag),a.slice(0,i)}spectralEnergy(e){let i=0,t=e.D;for(let a=0;a<t;a++)i+=e.magnitude[a]*e.magnitude[a];return i}spectralEntropy(e){let i=e.D,t=new Float32Array(i),a=0;for(let n=0;n<i;n++)t[n]=e.magnitude[n]*e.magnitude[n],a+=t[n];if(a===0)return 0;let s=0;for(let n=0;n<i;n++){let r=t[n]/a;r>0&&(s-=r*Math.log2(r))}return s/Math.log2(i)}spectralSparsity(e){let i=e.D,t=0,a=0;for(let r=0;r<i;r++)t+=e.magnitude[r],a+=e.magnitude[r]*e.magnitude[r];let s=Math.sqrt(a);if(s===0)return 0;let n=Math.sqrt(i);return(n-t/s)/(n-1)}lowFrequencyEnergy(e){let i=0,t=Math.floor(e.D/2),a=Math.floor(t/2);for(let s=0;s<a;s++)i+=e.magnitude[s]*e.magnitude[s];return i}highFrequencyEnergy(e){let i=0,t=Math.floor(e.D/2),a=Math.floor(t/2);for(let s=a;s<t;s++)i+=e.magnitude[s]*e.magnitude[s];return i}spectralSimilarity(e,i){if(e.D!==i.D)return 0;let t=0,a=0,s=0,n=e.D;for(let l=0;l<n;l++)t+=e.magnitude[l]*i.magnitude[l],a+=e.magnitude[l]*e.magnitude[l],s+=i.magnitude[l]*i.magnitude[l];let r=Math.sqrt(a)*Math.sqrt(s);return r>0?t/r:0}};var I=class{constructor(e={}){this.records=new Map,this.recordsList=[],this.spectral=new D,this.alpha=e.alpha!==void 0?e.alpha:.3,this.lambda=e.lambda!==void 0?e.lambda:.01,this.ws=e.ws!==void 0?e.ws:.4,this.wr=e.wr!==void 0?e.wr:.2,this.wc=e.wc!==void 0?e.wc:.1,this.wf=e.wf!==void 0?e.wf:.1,this.wd=e.wd!==void 0?e.wd:.1,this.wx=e.wx!==void 0?e.wx:.1,this.numTables=4,this.numProjections=8,this.tablesProjections=null,this.tablesBuckets=null,this.highPriorityRecords=new Map,this._saveTimeout=null,this._savePromise=Promise.resolve()}_initLSH(e){this.D=e,this.tablesProjections=[],this.tablesBuckets=[];for(let i=0;i<this.numTables;i++){let t=[];for(let a=0;a<this.numProjections;a++){let s=new Float32Array(e);for(let n=0;n<e;n++)s[n]=Math.random()*2-1;t.push(s)}this.tablesProjections.push(t),this.tablesBuckets.push(Array.from({length:256},()=>[]))}}_hash(e,i){let t=0,a=this.tablesProjections[i];for(let s=0;s<this.numProjections;s++){let n=0,r=a[s];for(let l=0;l<this.D;l++)n+=e[l]*r[l];n>0&&(t|=1<<s)}return t}addRecord(e){let i=Date.now(),t=e.id||Math.random().toString(36).substring(2,11),a=e.representation;!a||a.length===0?a=new Float32Array(this.D||8192):a instanceof Float32Array||(a=new Float32Array(a));let s={id:t,representation:a,content:e.content,confidence:e.confidence!==void 0?e.confidence:1,reinforcement:e.reinforcement!==void 0?e.reinforcement:1,createdAt:e.createdAt||i,lastAccessedAt:e.lastAccessedAt||i,lastReinforcedAt:e.lastReinforcedAt||i,source:e.source||"user",sourceType:e.sourceType||"user",status:e.status||"active",contradictionIds:e.contradictionIds||[],priority:e.priority||"normal"},n=this.recordsList.length;this.recordsList.push(s),this.records.set(t,s),s.priority==="high"&&this.highPriorityRecords.set(t,n),this.tablesProjections||this._initLSH(s.representation.length);for(let r=0;r<this.numTables;r++){let l=this._hash(s.representation,r);this.tablesBuckets[r][l].push(n)}return this._checkAndFlagContradictions(s),s}reinforce(e,i=this.alpha){let t=this.records.get(e);if(!t)return;let a=Date.now(),s=this.getDecayedConfidence(t,a);t.confidence=s+i*(1-s),t.reinforcement+=1,t.lastReinforcedAt=a}getDecayedConfidence(e,i=Date.now()){let a=(i-e.lastReinforcedAt)/(1e3*3600),s=Math.log2(e.reinforcement+1),n=this.lambda/(s||1);return e.confidence*Math.exp(-n*a)}flagContradiction(e,i){let t=this.records.get(e),a=this.records.get(i);t&&a&&(t.contradictionIds.includes(i)||t.contradictionIds.push(i),a.contradictionIds.includes(e)||a.contradictionIds.push(e),t.status="conflicted",a.status="conflicted")}retrieve(e,i=5,t=Date.now()){let a=e.length;this.tablesProjections||this._initLSH(a);let s=new Set;for(let[c,d]of this.highPriorityRecords.entries())s.add(d);let n=0;for(let c=0;c<this.numTables;c++){let d=this._hash(e,c),y=this.tablesBuckets[c][d];for(let p=0;p<y.length;p++)s.add(y[p]),n++;for(let p=0;p<this.numProjections;p++){let z=d^1<<p,m=this.tablesBuckets[c][z];for(let f=0;f<m.length;f++)s.add(m[f]),n++}}let r=!1;if(n===0)r=!0;else{let c=-1,d=-1;for(let y of s){let p=this.recordsList[y],z=this.getDecayedConfidence(p,t);z>c&&(c=z);let m=this._cosineSimilarity(e,p.representation);m>d&&(d=m)}(c<.45||d<.35)&&(r=!0)}let l=s;r&&(l=new Set(Array.from({length:this.recordsList.length},(c,d)=>d)));let o=[],h=this.spectral.spectralTransform({type:"real",values:e,D:a});for(let c of l){let d=this.recordsList[c],y=this._cosineSimilarity(e,d.representation),p=d.spectralTransform||(d.spectralTransform=this.spectral.spectralTransform({type:"real",values:d.representation,D:a})),z=this.spectral.spectralSimilarity(h,p),m=this.getDecayedConfidence(d,t),f=Math.min(1,Math.log10(d.reinforcement+1)),w=d.confidence-m,v=d.status==="conflicted"||d.contradictionIds.length>0?1:0,b=this.ws*y+this.wr*z+this.wc*m+this.wf*f-this.wd*w-this.wx*v;o.push({record:d,score:b})}o.sort((c,d)=>d.score-c.score);let u=o.slice(0,i);for(let c of u)c.record.lastAccessedAt=t;return u.map(c=>({record:c.record,score:c.score}))}saveToFile(e){this._saveTimeout&&clearTimeout(this._saveTimeout);let i=[];for(let t of this.recordsList)i.push({id:t.id,representation:Array.from(t.representation),content:t.content,confidence:t.confidence,reinforcement:t.reinforcement,createdAt:t.createdAt,lastAccessedAt:t.lastAccessedAt,lastReinforcedAt:t.lastReinforcedAt,source:t.source,sourceType:t.sourceType,status:t.status,contradictionIds:t.contradictionIds});this._savePromise=new Promise(t=>{this._saveTimeout=setTimeout(async()=>{try{await R.promises.writeFile(e,JSON.stringify(i,null,2),"utf8")}catch(a){console.error("MemoryEngine: Asynchronous write failed:",a.message)}t()},50)})}loadFromFile(e){if(R.existsSync(e))try{let i=R.readFileSync(e,"utf8"),t=JSON.parse(i);this.records.clear(),this.recordsList=[],this.tablesProjections=null,this.tablesBuckets=null;for(let a of t)this.addRecord({id:a.id,representation:new Float32Array(a.representation),content:a.content,confidence:a.confidence,reinforcement:a.reinforcement,createdAt:a.createdAt,lastAccessedAt:a.lastAccessedAt,lastReinforcedAt:a.lastReinforcedAt,source:a.source,sourceType:a.sourceType,status:a.status,contradictionIds:a.contradictionIds})}catch(i){console.error("MemoryEngine: Failed to load from file:",i.message)}}_cosineSimilarity(e,i){let t=0,a=e.length;for(let s=0;s<a;s++)t+=Math.cos(e[s]-i[s]);return t/a}_checkAndFlagContradictions(e){if(this.recordsList.length<=1)return;let i=this.retrieve(e.representation,3);for(let t of i){let a=this._cosineSimilarity(e.representation,t.record.representation),s=this._isContradictory(e.content,t.record.content);a>.35&&t.record.id!==e.id&&t.record.content!==e.content&&s&&this.flagContradiction(e.id,t.record.id)}}_isContradictory(e,i){let t=r=>r.includes("a pozitif")||r.includes("a+")||r.includes("a poz")?"A+":r.includes("b negatif")||r.includes("b-")||r.includes("b neg")?"B-":r.includes("0")||r.includes("s\u0131f\u0131r")?"0":r.includes("ab")?"AB":null,a=r=>r.includes("y\xFCksek")||r.includes("riskli")?"high":r.includes("normal")||r.includes("d\xFC\u015F\xFCk")||r.includes("risk yok")?"normal":null,s=e.toLowerCase(),n=i.toLowerCase();if((s.includes("kan grubu")||s.includes("grubu"))&&(n.includes("kan grubu")||n.includes("grubu"))){let r=t(s),l=t(n);if(r&&l&&r!==l)return!0}if(s.includes("risk")&&n.includes("risk")){let r=a(s),l=a(n);if(r&&l&&r!==l)return!0}if((s.includes("tansiyon")||s.includes("bas\u0131nc\u0131"))&&(n.includes("tansiyon")||n.includes("bas\u0131nc\u0131"))){let r=s.match(/\d+/g),l=n.match(/\d+/g);if(r&&l&&r[0]!==l[0])return!0}return!1}resolveConflict(e,i){let t=this.records.get(e),a=this.records.get(i);if(t){let s=Date.now(),n=this.getDecayedConfidence(t,s);t.confidence=Math.min(1,n+.3*(1-n)),t.status="active",t.contradictionIds=[],t.lastReinforcedAt=s}a&&(a.confidence=0,a.status="rejected",a.contradictionIds=[])}};function V(g){let e=[],i=0;for(;i<g.length;){let u=g[i];if(/\s/.test(u)){i++;continue}if(/[0-9.]/.test(u)){let c="";for(;i<g.length&&/[0-9.]/.test(g[i]);)c+=g[i],i++;e.push({type:"NUMBER",value:parseFloat(c)});continue}if(u==="+"||u==="-"||u==="*"||u==="/"||u==="%"||u==="^"||u==="("||u===")"){e.push({type:"OP",value:u}),i++;continue}throw new Error("Invalid character in math expression: "+u)}let t=0;function a(){return e[t]}function s(u){let c=e[t];if(!c)throw new Error("Unexpected end of expression");if(u!==void 0&&c.value!==u)throw new Error(`Expected ${u} but got ${c.value}`);return t++,c}function n(){let u=r();for(;;){let c=a();if(c&&c.type==="OP"&&(c.value==="+"||c.value==="-")){s();let d=r();c.value==="+"?u+=d:u-=d}else break}return u}function r(){let u=l();for(;;){let c=a();if(c&&c.type==="OP"&&(c.value==="*"||c.value==="/"||c.value==="%")){s();let d=l();if(c.value==="*")u*=d;else if(c.value==="/"){if(d===0)throw new Error("Division by zero");u/=d}else u%=d}else break}return u}function l(){let u=o();for(;;){let c=a();if(c&&c.type==="OP"&&c.value==="^"){s();let d=l();u=Math.pow(u,d)}else break}return u}function o(){let u=a();if(!u)throw new Error("Unexpected end of expression");if(u.type==="NUMBER")return s(),u.value;if(u.type==="OP"&&u.value==="("){s("(");let c=n();return s(")"),c}if(u.type==="OP"&&u.value==="-")return s("-"),-o();if(u.type==="OP"&&u.value==="+")return s("+"),o();throw new Error(`Unexpected token: ${u.value}`)}let h=n();if(t<e.length)throw new Error("Unexpected trailing tokens at end of expression");return h}var P=class{constructor(e,i){if(this.memory=e,this.sdk=i,this.D=i?i.D:4096,this.sdk&&this.sdk.hdc){let t=["hat\u0131rla","hat\u0131rl\u0131yor","favori","nerede","kim","haf\u0131za","hasta","kay\u0131t","bilgi","durum"].map(n=>this.sdk.hdc.generateSeeded("complex",n));this.memoryIntentVec=this.sdk.hdc.bundle(t).values;let a=["\xE7eli\u015Fki","kural","kar\u015F\u0131la\u015Ft\u0131r","do\u011Fru","yasak","uygun"].map(n=>this.sdk.hdc.generateSeeded("complex",n));this.ruleIntentVec=this.sdk.hdc.bundle(a).values;let s=["hesapla","toplam","\xE7arp","b\xF6l","ka\xE7","say\u0131","doz","miktar"].map(n=>this.sdk.hdc.generateSeeded("complex",n));this.mathIntentVec=this.sdk.hdc.bundle(s).values}else this.memoryIntentVec=new Float32Array(this.D),this.ruleIntentVec=new Float32Array(this.D),this.mathIntentVec=new Float32Array(this.D);this.chatState="idle",this.pendingRecord=null}vectorize(e){let t=e.toLowerCase().trim().replace(/[^a-zçgğıoöşuüâîû\s]/g,"").split(/\s+/).filter(Boolean);if(this.sdk&&this.sdk.hdc){if(t.length===0)return new Float32Array(this.D);if(t.length===1)return this.sdk.hdc.generateSeeded("complex",t[0]).values;let a=t.map(s=>this.sdk.hdc.generateSeeded("complex",s));return this.sdk.hdc.bundle(a).values}return new Float32Array(this.D)}validateAxis(e,i){if(!e)return!1;if(i===1&&e.route==="math"){let t=e.input.match(/^\s*([0-9.]+)\s*([+\-*/%^])\s*([0-9.]+)\s*$/);if(t){let a=parseFloat(t[1]),s=t[2],n=parseFloat(t[3]),r=parseFloat(e.output);if(s==="*"){if(n!==0&&Math.abs(r/n-a)>1e-4)return!1}else if(s==="+"){if(Math.abs(r-n-a)>1e-4)return!1}else if(s==="-"){if(Math.abs(r+n-a)>1e-4)return!1}else if(s==="/"&&n!==0&&Math.abs(r*n-a)>1e-4)return!1}return!0}if(i===2&&e.route==="math"){let t=parseFloat(e.output);return!(isNaN(t)||!isFinite(t)||e.input.includes("/0"))}if(i===3&&e.route==="memory"){if(!e.results||e.results.length===0)return!1;let t=e.results[0].record;return!(t.status==="conflicted"||t.contradictionIds.length>0)}if(i===4&&e.route==="memory"){if(!e.results||e.results.length===0)return!1;let t=e.results[0].record;return!(this.memory.getDecayedConfidence(t)<.5)}if(i===5&&e.route==="memory"){if(!e.results||e.results.length===0)return!1;let t=this.vectorize(e.input);return!(this._cosineSimilarity(t,e.results[0].record.representation)<.15)}if(i===6&&(e.route==="llm"||e.route==="memory")){if(this.sdk&&this.sdk.morphology){let t=e.output.split(/\s+/).filter(Boolean);for(let a of t){let s=a.toLowerCase().replace(/[^a-zçgğıoöşuüâîû]/g,"");if(s.length>=2){let n=this.sdk.morphology.determineVowelHarmony(s);if(n!=="front"&&n!=="back")return!1}}}return!0}if(i===7&&e.route==="llm"){let t=e.output.split(/\s+/).filter(Boolean);for(let a of t){let s=a.toLowerCase().replace(/[^a-zçgğıoöşuüâîû]/g,"");if(/(kitapı|bebeki|çiçeki|ağacı)/.test(s))return!1}return!0}if(i===8&&e.route==="memory"){let t=e.input.toLowerCase().split(/\s+/).filter(s=>s.length>3),a=e.output.toLowerCase();return!(t.length>0&&!t.some(n=>a.includes(n)))}return!0}validateAllAxes(e){for(let i=1;i<=8;i++)if(!this.validateAxis(e,i))return!1;return!0}route(e,i={}){let t=e.trim(),a=/kaydet|ekle|yaz|not al|sakla|sisteme gir|oluştur/i,s=/^(evet|tamam|doğru|olur|kaydet|kabul|onay|evet kaydet)$/i,n=/^(hayır|iptal|vazgeç|yanlış|dur|bekle)$/i;if(this.chatState==="pending_confirmation")if(s.test(t)){this.chatState="recording";let r=this.pendingRecord,l=[r.baslik,r.kategori,r.aciklama,r.etiketler].filter(Boolean).join(" "),o=this.vectorize(l),h=this.memory.addRecord({content:`${r.baslik} \u2014 ${r.aciklama}`,representation:o,priority:"normal"});return this.chatState="idle",this.pendingRecord=null,{input:t,route:"memory",llmBypassed:!0,output:"Haf\u0131za kayd\u0131 ba\u015Far\u0131yla eklendi.",reason:"Chat state machine confirm and record"}}else{if(n.test(t))return this.chatState="idle",this.pendingRecord=null,{input:t,route:"memory",llmBypassed:!0,output:"Kay\u0131t iptal edildi.",reason:"Chat state machine reject"};{this.chatState="idle",this.pendingRecord=null;let r=this._routeNormal(e,i);return r.output="\xD6nceki kayd\u0131 iptal ettim. "+r.output,r}}if(this.chatState==="idle"&&a.test(t)){let r=this._extractDataFromText(t);if(r.baslik&&r.aciklama)return this.chatState="pending_confirmation",this.pendingRecord=r,{input:t,route:"memory",llmBypassed:!0,output:`\u015Eunu kaydediyorum:
|
|
2
|
+
Ba\u015Fl\u0131k: ${r.baslik}
|
|
3
|
+
Not: ${r.aciklama}
|
|
4
|
+
Do\u011Fru mu?`,reason:"Chat state machine save intent detected"}}return this._routeNormal(e,i)}_extractDataFromText(e){let i=e.replace(/kaydet|ekle|yaz|not al|sakla|sisteme gir|oluştur/ig,"").trim(),t=i.split(",").map(l=>l.trim()).filter(Boolean),a="",s="",n="",r="";if(t.length>=2)a=t[0],s=t[1],t.length>=3&&(n=t[2]),t.length>=4&&(r=t.slice(3).join(", "));else{let l=i.split(/\s+/);l.length>2?(a=l.slice(0,2).join(" "),s=l.slice(2).join(" ")):(a=i,s=i)}return a=a.replace(/[,.;!]+$/,"").trim(),s=s.replace(/[,.;!]+$/,"").trim(),a||(a=i||"Yeni Kay\u0131t"),s||(s=i||"Detay girilmedi"),{baslik:a,aciklama:s,kategori:n,etiketler:r}}_routeNormal(e,i={}){let t=e.trim(),a=/^[0-9+\-*/().\s%^]+$/,s=/[+\-*/%^]/.test(t);if(a.test(t)&&s)try{let m=V(t),f={input:t,route:"math",llmBypassed:!0,output:m.toString(),reason:"Deterministic arithmetic evaluation"};return this.validateAllAxes(f)?f:{input:t,route:"math",llmBypassed:!0,output:"Hata: Ge\xE7ersiz aritmetik i\u015Flem (S\u0131f\u0131ra b\xF6lme veya tan\u0131ms\u0131z sonu\xE7)",reason:"Math verifier failure recovery"}}catch{}let n=this.vectorize(t),r=this._cosineSimilarity(n,this.memoryIntentVec),l=this._cosineSimilarity(n,this.ruleIntentVec),o=/hatırlıyor\s*musun|benim\s*favori|nerede|hatırla|kayıt|hasta|durumu|kaydı|geçmiş|bilgi|var\s*mı|söyle|kim|yaşı|şikayeti|tanı|ilaç|doz|kan\s*grubu|risk|gebelik|diyabet|tansiyon|unuttun|hâlâ|güncelle|seviye|ölçüm|ne\s*zaman|değişti|sonuç|nedir|kaydı\s*var/i,h=/çelişki|kural|karşılaştır|doğru\s*mu|yasak|uygun/i;if(o.test(t)||r>.18){let m=this.memory?this.memory.retrieve(n,5):[];if(console.log(`[Router DBG] Memory triggered. Query: "${t}". Results count: ${m.length}`),m.length>0){console.log("[Router DBG] Candidate list:"),m.forEach((b,M)=>{let x=this._cosineSimilarity(n,b.record.representation);console.log(` #${M}: "${b.record.content}" | score: ${b.score.toFixed(4)} | sSem: ${x.toFixed(4)} | status: ${b.record.status}`)});let f=null;for(let b of m)if(this._cosineSimilarity(n,b.record.representation)>.15&&(b.record.status==="conflicted"||b.record.contradictionIds.length>0)){f=b.record;break}if(f){let b=[f];for(let x of f.contradictionIds){let _=this.memory.records.get(x);_&&b.push(_)}let M=b.map(x=>x.content).join(" | ");return console.log("[Router DBG] Contradiction detected!"),{input:t,route:"memory",llmBypassed:!0,output:`\xC7eli\u015Fen kay\u0131tlar tespit edildi: ${M}. L\xFCtfen do\u011Fru olan\u0131 belirtin.`,conflict:{detected:!0,records:b.map(x=>({id:x.id,content:x.content,confidence:this.memory.getDecayedConfidence(x)})),message:"Bu kay\u0131tta \xE7eli\u015Fen bilgi var. L\xFCtfen do\u011Fru olan\u0131 belirtin."},results:m.slice(0,3),reason:"Contradiction detected in memory"}}let w={input:t,route:"memory",llmBypassed:!0,output:m[0].record.content,results:[m[0]],reason:"Semantic memory query candidate"},v=this.validateAllAxes(w);if(console.log(`[Router DBG] Candidate isValid: ${v}`),!v)for(let b=1;b<=8;b++)console.log(` Axis ${b}: ${this.validateAxis(w,b)}`);if(v)return w;for(let b=1;b<m.length;b++){let M={input:t,route:"memory",llmBypassed:!0,output:m[b].record.content,results:[m[b]],reason:"Replan candidate"};if(this.validateAllAxes(M))return console.log(`[Router DBG] Replan candidate ${b} is valid.`),M}return{input:t,route:"memory",llmBypassed:!0,output:"Bu bilgi haf\u0131zada bulunamad\u0131. Hen\xFCz kay\u0131t edilmemi\u015F olabilir.",results:[],reason:"Memory candidates failed validation (low similarity)"}}else return{input:t,route:"memory",llmBypassed:!0,output:"Bu bilgi haf\u0131zada bulunamad\u0131. Hen\xFCz kay\u0131t edilmemi\u015F olabilir.",results:[],reason:"Memory triggered but empty"}}if(h.test(t)||l>.28)return{route:"rules",llmBypassed:!0,output:"Kural de\u011Ferlendirmesi bilgi graf\u0131 / kural katman\u0131na aktar\u0131ld\u0131.",reason:`Rule structure detected (Match Sim: ${l.toFixed(4)})`};let c=[this._cosineSimilarity(n,this.mathIntentVec),r,l],d=Math.max(...c);if(d<.12)return{input:t,route:"boundary",output:"Bu konuda bilgim yok. Ba\u015Fka bir konuda yard\u0131mc\u0131 olabilir miyim?",llmBypassed:!0,confidence:d,reason:`Capability boundary \u2014 no intent matched (max similarity: ${d.toFixed(4)})`};let y="",p=null;this.sdk&&typeof this.sdk.generate=="function"?(p=this.sdk.generate(t,{temperature:i.temperature!==void 0?i.temperature:0,maxLength:i.maxLength!==void 0?i.maxLength:this.sdk.maxLength}),y=p.generatedText):y=`[SLM Fallback] ${t}`;let z={input:t,route:"llm",llmBypassed:!1,output:y,sdkResult:p,reason:"Generative language synthesis required"};return this.validateAllAxes(z)||(z.output=`${y}.`),z}_cosineSimilarity(e,i){let t=0,a=e.length;for(let s=0;s<a;s++)t+=Math.cos(e[s]-i[s]);return t/a}};var F=class{constructor(e){this.sdk=e,this.memory=e?e.memory:null,this.morphology=e?e.morphology:null,this.router=e?e.router:null,this.tools={memory_lookup:i=>{if(!this.memory)return"Hata: Bellek motoru y\xFCkl\xFC de\u011Fil.";let t=this.router?this.router.vectorize(i):new Float32Array(1024),a=this.memory.retrieve(t,1);return a.length===0?"Bulunamad\u0131.":a[0].record.content},math_eval:i=>{try{return V(i).toString()}catch(t){return`Hata: Matematiksel hesaplama ba\u015Far\u0131s\u0131z. ${t.message}`}},morphology_analyze:i=>{if(!this.morphology)return"Hata: Morfoloji motoru y\xFCkl\xFC de\u011Fil.";let t=this.morphology.analyze(i);return JSON.stringify({root:t.root,suffixes:t.suffixes,harmony:t.harmony,syllables:t.syllables})},spectral_transform:i=>{if(!this.sdk||!this.sdk.spectral)return"Hata: Spektral motor y\xFCkl\xFC de\u011Fil.";let t=this.router?this.router.vectorize(i):new Float32Array(1024);return`Energy: ${this.sdk.spectral.spectralTransform({type:"real",values:t,D:t.length}).magnitude.reduce((s,n)=>s+n,0).toFixed(2)}`},system_time:()=>new Date().toISOString()}}async execute(e,i=5){let t=[],a=1,s=!1,n="",r=e.toLowerCase();for(;a<=i&&!s;){let l="",o="",h="";if(r.includes("hat\u0131rla")||r.includes("haf\u0131za")||r.includes("favori"))if(a===1)l="Kullan\u0131c\u0131n\u0131n sordu\u011Fu favori veya bellek kayd\u0131n\u0131 bulmak i\xE7in haf\u0131zada arama yapmal\u0131y\u0131m.",o="memory_lookup",h=r.includes("renk")?"favori renk":"haf\u0131za sorgusu";else if(a===2){let u=t[0].observation;l=`Haf\u0131zadan '${u}' bilgisini ald\u0131m. Bu kelimeyi morfolojik olarak analiz etmeliyim.`,o="morphology_analyze",h=u.split(/\s+/).pop().replace(/[^a-zçgğıoöşuüâîû]/g,"")}else{let u=t[1].observation;l="Gerekli aramalar\u0131 ve analizleri tamamlad\u0131m. Sonucu kullan\u0131c\u0131ya sunuyorum.",s=!0,n=`Otonom ReAct G\xF6revi Ba\u015Far\u0131yla Tamamland\u0131.
|
|
5
|
+
- Haf\u0131za Kayd\u0131: ${t[0].observation}
|
|
6
|
+
- Morfolojik Yap\u0131: ${u}`}else if(r.includes("hesapla")||/[0-9+\-*/%^]/.test(r))if(a===1){l="Matematiksel ifadeyi deterministik parser ile hesaplamal\u0131y\u0131m.",o="math_eval";let u=e.match(/[0-9+\-*/%^().\s]+/);h=u?u[0].trim():"0"}else if(a===2){let u=t[0].observation;l=`Hesaplanan '${u}' sonucunun spektral enerji yo\u011Funlu\u011Funu kontrol etmeliyim.`,o="spectral_transform",h=u}else l="Hesaplama ve spektral d\xF6n\xFC\u015F\xFCm ad\u0131mlar\u0131 bitti. Sonucu d\xF6n\xFCyorum.",s=!0,n=`Hesaplama Sonucu: ${t[0].observation} | Spektral Temsiliyet: ${t[1].observation}`;else a===1?(l="Sistem saatini alarak g\xFCncel zaman\u0131 kontrol etmeliyim.",o="system_time",h=""):(l="Varsay\u0131lan otonom ak\u0131\u015F tamamland\u0131.",s=!0,n=`Mevcut Zaman Dilimi: ${t[0].observation}`);if(s)t.push({step:a,thought:l,action:"final_answer",argument:"",observation:n});else{let u="",c=this.tools[o];c?u=c(h):u=`Hata: '${o}' arac\u0131 tan\u0131ml\u0131 de\u011Fil.`,t.push({step:a,thought:l,action:o,argument:h,observation:u}),a++}}return{goal:e,stepsRun:a-1,logs:t,finalAnswer:n}}};function T(g,e){let i=e.determineVowelHarmony(g),t=g[g.length-1],a=e.allVowels.has(t),s=[g],r=new Set(["t","k","\xE7","p","s","\u015F","h","f"]).has(t),l=(o,h)=>{if(!h)return o;if(e.allVowels.has(h[0])){let c=o[o.length-1],d=o.slice(0,-1);if(c==="p")return d+"b"+h;if(c==="\xE7")return d+"c"+h;if(c==="t")return d+"d"+h;if(c==="k")return o==="renk"?d+"g"+h:d+"\u011F"+h}return o+h};return i==="front"?(s.push(g+"ler"),s.push(a?g+"nin":l(g,"in")),s.push(a?g+"ye":l(g,"e")),s.push(a?g+"yi":l(g,"i")),s.push(g+(r?"te":"de")),s.push(g+(r?"ten":"den")),s.push(a?g+"m":l(g,"im"))):(s.push(g+"lar"),s.push(a?g+"n\u0131n":l(g,"\u0131n")),s.push(a?g+"ya":l(g,"a")),s.push(a?g+"y\u0131":l(g,"\u0131")),s.push(g+(r?"ta":"da")),s.push(g+(r?"tan":"dan")),s.push(a?g+"m":l(g,"\u0131m"))),s}var B=class{constructor(e={}){this.D=e.D||4096,this.hdc=new S(this.D),this.morphology=new A,this.spectral=new D,this.memory=new I(e.memory||{}),this.router=new P(this.memory,this),this.temperature=e.temperature!==void 0?e.temperature:.7,this.maxLength=e.maxLength||10,this.vocab=[],this.vocabMap=new Map,this.embeddings=new Map,this.wordCounts=new Map,this.freqIndices=[],this.wordDerivationIndices=new Map,this.transitionCounts=new Map,this.sparseWeightsSpec=null,this.wasmInstance=null,this.wasmMemory=null,this.vocabCosPtr=0,this.vocabSinPtr=0,this.scoresPtr=0,this.candidateIndicesPtr=0,this._initialized=!1,this._runtime=typeof window<"u"?"browser":"node"}async init(e={}){this._initialized||(await this._loadWasm(e),await this._buildVocabulary(e),this._initialized=!0)}generate(e,i={}){this._assertInit();let t=i.maxLength||this.maxLength,a=i.temperature!==void 0?i.temperature:this.temperature,s=i.onToken||null,r=this.morphology.normalize(e).split(/\s+/).filter(Boolean);r.length===0&&r.push("ev");let l=r.length,o=[],h="length",u=performance.now();for(let c=0;c<t;c++){let d=performance.now(),y=this._predictNext(r,a,l),p=performance.now();r.push(y.word);let z={word:y.word,score:y.score,latencyMs:p-d};if(o.push(z),s&&s(y.word,z),this._isTerminal(y.word)){h="stop";break}if(r.length>l+2&&r.slice(-3).every(m=>m===r[r.length-1])){h="stop";break}}return{prompt:e,generatedText:r.join(" "),newTokens:r.slice(l),steps:o,totalLatencyMs:performance.now()-u,finishReason:h,vocabSize:this.vocab.length}}analyze(e){return this.morphology.analyze(e)}getMetrics(){return{runtime:this._runtime,vocabSize:this.vocab.length,dimension:this.D,wasmActive:this.wasmInstance!==null,initialized:this._initialized}}createAgent(){return new F(this)}async _loadWasm(e){let i={env:{cosf:Math.cos,sinf:Math.sin,atan2f:Math.atan2,expf:Math.exp,sqrtf:Math.sqrt}};try{if(e.wasmBinary){let t=new WebAssembly.Module(e.wasmBinary);this.wasmInstance=new WebAssembly.Instance(t,i),this.wasmMemory=this.wasmInstance.exports.memory}else if(this._runtime==="browser"){let t=e.wasmUrl||"../wasm/spectral_core.wasm",s=await(await fetch(t)).arrayBuffer(),n=new WebAssembly.Module(s);this.wasmInstance=new WebAssembly.Instance(n,i),this.wasmMemory=this.wasmInstance.exports.memory}else{let t=await import("fs"),a=await import("path"),{fileURLToPath:s}=await import("url"),n=a.dirname(s(import.meta.url)),r=e.wasmPath||a.join(n,"..","wasm","spectral_core.wasm");if(t.existsSync(r)){let l=t.readFileSync(r),o=new WebAssembly.Module(l);this.wasmInstance=new WebAssembly.Instance(o,i),this.wasmMemory=this.wasmInstance.exports.memory}}}catch(t){console.warn("ResonanceSDK: WASM load failed, Pure JS fallback active.",t.message)}}async _buildVocabulary(e){let i=["evimizden yeni \xE7\u0131kt\u0131k","yeni bir kitap ald\u0131m","bilimsel ara\u015Ft\u0131rmalar yapay zeka ile h\u0131zland\u0131","g\xFCzel bir g\xFCn ba\u015Flad\u0131","iyi bir insan olmak \xF6nemlidir","t\xFCrk\xE7e dil yap\u0131s\u0131 \xE7ok zengindir","yapay zeka insan beyni gibi \xE7al\u0131\u015F\u0131r","\xF6\u011Frenmek ve d\xFC\u015F\xFCnmek zihni geli\u015Ftirir","b\xFCy\xFCk bir ad\u0131m att\u0131k","yeni projeler \xFCzerinde \xE7al\u0131\u015F\u0131yoruz","okuma al\u0131\u015Fkanl\u0131\u011F\u0131 kazanmak \xF6nemlidir","bilim ve teknik d\xFCnyay\u0131 de\u011Fi\u015Ftiriyor","evimizden okula kadar y\xFCr\xFCd\xFCk","yapay zeka dil modelleri \xFCzerine kuruludur","yeni bir d\xFCnya bizi bekliyor","kitaplar en iyi arkada\u015Ft\u0131r","g\xFCzel bir gelecek in\u015Fa ediyoruz","iyi bir e\u011Fitim almak \xF6nemlidir","t\xFCrk\xE7e konu\u015Fmak ve yazmak \xE7ok g\xFCzel","bilimsel ger\xE7ekler her zaman kazan\u0131r","yapay sinir a\u011Flar\u0131 karma\u015F\u0131k modellerdir","beyin ve zihin ara\u015Ft\u0131rmalar\u0131 s\xFCr\xFCyor","evimizden yeni bir yola \xE7\u0131kt\u0131k","yeni bir ba\u015Flang\u0131\xE7 yapmak iyidir","bilimsel okuma yapmak zihni a\xE7ar","okuma yapmak insan\u0131 geli\u015Ftirir","evimizden \xE7\u0131kt\u0131k ve okula gittik","yeni bir g\xFCne uyand\u0131k","bilim insanlar\u0131 yapay zeka geli\u015Ftiriyor","t\xFCrk\xE7e dil bilgisi kurallar\u0131 \xF6nemlidir","evimizden okula gittik yeni bir kitap ald\u0131k","televizyonu a\xE7\u0131p haberleri izledik","arabaya binip okula gittik","bilgisayar\u0131 kapat\u0131p uyudum","bilgisayar\u0131 kapat\u0131p yatt\u0131m","yaz\u0131l\u0131m m\xFChendisleri yapay zeka modelleri \xFCzerine ara\u015Ft\u0131rma yap\u0131yor","bilgi teknolojileri ve veri analizi i\u015F s\xFCre\xE7lerini kolayla\u015Ft\u0131r\u0131r","sa\u011Fl\u0131kl\u0131 beslenme ve spor yapmak ya\u015Fam kalitesini art\u0131r\u0131r","do\u011Fal ya\u015Fam\u0131 ve \xE7evreyi korumak hepimizin sorumlulu\u011Fundad\u0131r","sanat ve edebiyat toplumun k\xFClt\xFCrel zenginli\u011Fini besler ve geli\u015Ftirir","e\u011Fitim sistemi yeni nesillerin gelece\u011Fini ve ba\u015Far\u0131s\u0131n\u0131 belirler","bilgisayar a\u011Flar\u0131 veri g\xFCvenli\u011Fi ve h\u0131zl\u0131 bilgi ak\u0131\u015F\u0131 sa\u011Flar","merhaba size nas\u0131l yard\u0131mc\u0131 olabilirim","g\xFCnayd\u0131n bug\xFCn size nas\u0131l yard\u0131mc\u0131 olay\u0131m","iyi g\xFCnler l\xFCtfen sorunuzu belirtin","ho\u015F geldiniz nas\u0131l yard\u0131mc\u0131 olabilirim","merhaba buyurun nas\u0131l yard\u0131mc\u0131 olay\u0131m","iyi ak\u015Famlar size nas\u0131l yard\u0131mc\u0131 olabilirim","hasta kayd\u0131 olu\u015Fturuldu","kay\u0131t sisteme ba\u015Far\u0131yla eklendi","hastan\u0131n bilgileri g\xFCncellendi","bu hasta daha \xF6nce kay\u0131t edilmemi\u015F","hastan\u0131n ad\u0131 ve ya\u015F\u0131 kaydedildi","hasta bilgileri sisteme girildi","yeni hasta kayd\u0131 a\xE7\u0131ld\u0131","hasta \u015Fikayeti sisteme i\u015Flendi","kay\u0131t ba\u015Far\u0131yla g\xFCncellendi","hastan\u0131n ge\xE7mi\u015F kay\u0131tlar\u0131 bulundu","bu hasta i\xE7in kay\u0131t bulunamad\u0131","hastan\u0131n durumu kaydedildi","bu soruyu yan\u0131tlayacak bilgiye sahip de\u011Filim","bu konuda bilgim yok ba\u015Fka bir soru sorabilirsiniz","l\xFCtfen daha fazla bilgi verir misiniz","hangi hastay\u0131 soruyorsunuz","bu bilgi haf\u0131zada bulunamad\u0131","hen\xFCz bu konuda kay\u0131t yok","bu i\u015Flemi yapabilmem i\xE7in daha fazla bilgiye ihtiyac\u0131m var","maalesef bu konuda yard\u0131mc\u0131 olam\u0131yorum","hastan\u0131n \u015Fikayeti ba\u015F a\u011Fr\u0131s\u0131 ve tansiyon y\xFCksekli\u011Fi","kan bas\u0131nc\u0131 de\u011Feri y\xFCz k\u0131rk b\xF6l\xFC doksan olarak \xF6l\xE7\xFCld\xFC","ila\xE7 dozu hesapland\u0131 ve re\xE7eteye yaz\u0131ld\u0131","risk durumu y\xFCksek riskli olarak i\u015Faretlendi","hastan\u0131n kan \u015Fekeri y\xFCz seksen olarak \xF6l\xE7\xFCld\xFC","diyabet hastas\u0131 olarak kay\u0131t edildi","gebelik takibi i\xE7in kontrol randevusu olu\u015Fturuldu","hastan\u0131n ate\u015Fi otuz sekiz derece \xF6l\xE7\xFCld\xFC","tansiyon \xF6l\xE7\xFCm\xFC yap\u0131ld\u0131 ve kaydedildi","ila\xE7lardan hangisinin verilmesi gerekti\u011Fi belirlendi","doktorlar\u0131m\u0131zdan birini \xE7a\u011F\u0131rabilir misiniz","hastan\u0131n ayaklar\u0131ndan birinde \u015Fi\u015Flik tespit edildi","kan grubu belirlenmesi i\xE7in tahlil istendi","hastaya g\xFCnde \xFC\xE7 kez ila\xE7 verilecek","haftal\u0131k toplam doz hesapland\u0131","ameliyat \xF6ncesi haz\u0131rl\u0131klar tamamland\u0131","hastan\u0131n nabz\u0131 ve tansiyonu normal s\u0131n\u0131rlarda","tedavi plan\u0131 olu\u015Fturuldu ve hastaya bildirildi","a\u015F\u0131 takvimi kontrol edildi","acil m\xFCdahale gerekli de\u011Fil hasta stabil","kay\u0131tlarda \xE7eli\u015Fen bilgi tespit edildi","l\xFCtfen do\u011Fru bilgiyi belirtin","iki farkl\u0131 kay\u0131t bulundu hangisi do\u011Fru","bu bilgi \xF6nceki kay\u0131tla \xE7eli\u015Fiyor","\xE7eli\u015Fen kay\u0131tlar kullan\u0131c\u0131ya sunuldu","evlerimizden geliyoruz hasta getirdik","hastan\u0131n ayaklar\u0131ndan birinde \u015Fi\u015Flik var","ila\xE7lardan hangisini vermemiz gerekiyor","doktorlar\u0131m\u0131zdan birini \xE7a\u011F\u0131rabilir misiniz","bu hastal\u0131klardan kurtulabilir mi","k\xF6ylerden gelen hastalar muayene edildi","\xE7ocuklar\u0131n a\u015F\u0131lar\u0131 yap\u0131ld\u0131","hastalar\u0131n kay\u0131tlar\u0131 g\xFCncellendi"],t=[];try{if(this._runtime==="browser"){let o=e.corpusUrl||"../tr_corpus_embed.js",c=(await(await fetch(o)).text()).match(/const TR_CORPUS_ROOTS\s*=\s*(\[[\s\S]*?\]);/);c&&(t=JSON.parse(c[1]))}else{let o=await import("fs"),h=await import("path"),{fileURLToPath:u}=await import("url"),c=h.dirname(u(import.meta.url)),d=e.corpusPath||h.join(c,"..","tr_corpus_embed.js");if(o.existsSync(d)){let p=o.readFileSync(d,"utf8").match(/const TR_CORPUS_ROOTS\s*=\s*(\[[\s\S]*?\]);/);p&&(t=JSON.parse(p[1]))}}}catch{}let a=/^[a-zçgğıoöşuüâîû]+$/,s=new Set(["ev","yeni","bir","kitap","okul","\xE7\u0131kt\u0131k","ald\u0131m","g\xFCzel","iyi","yapay","zeka","bilimsel","okuma","\xF6\u011Frenmek","dil","t\xFCrk\xE7e","insan","olmak","\xF6nemlidir","geli\u015Ftirir","de\u011Fi\u015Ftiriyor","y\xFCr\xFCd\xFCk","gittik","yola","ba\u015Flang\u0131\xE7","g\xFCne","uyand\u0131k","kuruludur","televizyonu","a\xE7\u0131p","izledik","izledim","arabaya","binip","bilgisayar\u0131","kapat\u0131p","uyudum","yatt\u0131m"]);this.wordCounts.clear();for(let o of i)for(let h of o.split(/\s+/)){let u=h.trim().toLowerCase().replace(/[^a-zçgğıoöşuüâîû]/g,"");u.length>=2&&a.test(u)&&this.wordCounts.set(u,(this.wordCounts.get(u)||0)+1)}for(let[o,h]of this.wordCounts)h>=2&&s.add(o);for(let o of t){let h=o.trim().toLowerCase().replace(/[^a-zçgğıoöşuüâîû]/g,"");if(h.length>=2&&a.test(h))for(let u of T(h,this.morphology))s.add(u)}this.vocab=["<unk>",...Array.from(s)],this.vocabMap.clear();for(let o=0;o<this.vocab.length;o++)this.vocabMap.set(this.vocab[o],o);this.freqIndices=this.vocab.map((o,h)=>({w:o,idx:h})).sort((o,h)=>(this.wordCounts.get(h.w)||0)-(this.wordCounts.get(o.w)||0)).slice(0,15).map(o=>o.idx),this.wordDerivationIndices.clear();for(let o of this.vocab){let h=[];for(let u of T(o,this.morphology)){let c=this.vocabMap.get(u);c!==void 0&&h.push(c)}this.wordDerivationIndices.set(o,h)}for(let o of this.vocab){let h=this.hdc.generateSeeded("complex",o);h.values=new Float32Array(h.values);let u=new Float32Array(this.D),c=new Float32Array(this.D);for(let d=0;d<this.D;d++)u[d]=Math.cos(h.values[d]),c[d]=Math.sin(h.values[d]);this.embeddings.set(o,{emb:h,cosVals:u,sinVals:c})}if(this.wasmInstance){let o=this.vocab.length,h=this.D;if(this.vocabCosPtr=this.wasmInstance.exports.malloc(o*h*4),this.vocabSinPtr=this.wasmInstance.exports.malloc(o*h*4),this.scoresPtr=this.wasmInstance.exports.malloc(o*4),this.transIndicesPtr=this.wasmInstance.exports.malloc(256),this.transMultipliersPtr=this.wasmInstance.exports.malloc(256),this.topIndicesPtr=this.wasmInstance.exports.malloc(20),this.topScoresPtr=this.wasmInstance.exports.malloc(20),this.candidateIndicesPtr=this.wasmInstance.exports.malloc(1024*4),this.vocabCosPtr&&this.vocabSinPtr&&this.scoresPtr&&this.transIndicesPtr&&this.transMultipliersPtr&&this.topIndicesPtr&&this.topScoresPtr&&this.candidateIndicesPtr){let u=this.wasmMemory.buffer,c=new Float32Array(u,this.vocabCosPtr,o*h),d=new Float32Array(u,this.vocabSinPtr,o*h);for(let y=0;y<o;y++){let p=this.embeddings.get(this.vocab[y]);c.set(p.cosVals,y*h),d.set(p.sinVals,y*h)}}else console.warn("ResonanceSDK: WASM malloc failed, falling back to Pure JS."),this.wasmInstance=null}this.transitionCounts=new Map;let n=new Float32Array(this.D),r=new Float32Array(this.D),l=0;for(let o of i){let h=o.split(/\s+/).map(u=>u.trim().toLowerCase().replace(/[^a-zçgğıoöşuüâîû]/g,"")).filter(u=>u.length>=2);for(let u=0;u<h.length-1;u++){let c=h[u],d=h[u+1];this.transitionCounts.has(c)||this.transitionCounts.set(c,new Map),this.transitionCounts.get(c).set(d,(this.transitionCounts.get(c).get(d)||0)+1);let y=this.embeddings.get(c),p=this.embeddings.get(d);if(y&&p){let z=1/Math.sqrt(this.wordCounts.get(d)||1);for(let m=0;m<this.D;m++){let f=p.emb.values[m]-y.emb.values[m];f<0&&(f+=2*Math.PI),n[m]+=z*Math.cos(f%(2*Math.PI)),r[m]+=z*Math.sin(f%(2*Math.PI))}l++}}}if(l>0){let o=new Float32Array(this.D);for(let h=0;h<this.D;h++){let u=Math.atan2(r[h],n[h]);u<0&&(u+=2*Math.PI),o[h]=u}this.sparseWeightsSpec=new k("complex",o,this.D)}else this.sparseWeightsSpec=this.hdc.generateSeeded("complex","fallback_transitions");if(this.wasmInstance&&this.sparseWeightsSpec){let o=this.wasmMemory.buffer,h=new Float32Array(o,this.wasmInstance.exports.get_transition_spec_re_ptr(),this.D),u=new Float32Array(o,this.wasmInstance.exports.get_transition_spec_im_ptr(),this.D);for(let c=0;c<this.D;c++)h[c]=Math.cos(this.sparseWeightsSpec.values[c]),u[c]=Math.sin(this.sparseWeightsSpec.values[c])}}_predictNext(e,i,t){return this.wasmInstance&&this.wasmMemory?this._predictWasm(e,i,t):this._predictJS(e,i,t)}_predictWasm(e,i,t){let a=this.wasmMemory.buffer,s=this.wasmInstance.exports.get_context_angles_ptr(),n=new Float32Array(a,s,this.D);if(t>0&&e.length>t){let m=this.vocabMap.get(e[t-1])??0,f=this.vocabMap.get(e[e.length-1])??0;this.wasmInstance.exports.combine_phases_by_indices(m,.4,f,.6,this.vocabCosPtr,this.vocabSinPtr,s)}else{let m=this.embeddings.get(e[e.length-1])||this.embeddings.get("<unk>");n.set(m.emb.values)}this.wasmInstance.exports.spectral_predict();let r=new Int32Array(a,this.candidateIndicesPtr,1024),l=this.freqIndices.length;for(let m=0;m<l;m++)r[m]=this.freqIndices[m];let o=l;for(let m=0;m<t;m++){let f=this.vocabMap.get(e[m]);f!==void 0&&o<1024&&(r[o++]=f)}let h=e[e.length-1],u=-1;if(h){let m=this.transitionCounts.get(h);if(!m)u=0;else{let f=new Int32Array(a,this.transIndicesPtr,m.size),w=new Float32Array(a,this.transMultipliersPtr,m.size),v=0;for(let[b,M]of m.entries()){let x=this.vocabMap.get(b);if(x!==void 0){f[v]=x,w[v]=1.5+M*2,v++,o<1024&&(r[o++]=x);let _=this.wordDerivationIndices.get(b);if(_){let j=_.length;for(let C=0;C<j;C++)o<1024&&(r[o++]=_[C])}}}u=v}}this.wasmInstance.exports.compute_similarity_for_candidates(this.candidateIndicesPtr,o,this.vocabCosPtr,this.vocabSinPtr,this.transIndicesPtr,this.transMultipliersPtr,u,this.topIndicesPtr,this.topScoresPtr);let c=new Int32Array(a,this.topIndicesPtr,5),d=new Float32Array(a,this.topScoresPtr,5),y=[],p=h?this.morphology.determineVowelHarmony(h):null,z=e.slice(-4);for(let m=0;m<5;m++){let f=c[m];if(f===-1)continue;let w=this.vocab[f],v=d[m];if(e.length>=1){let b=e[e.length-1];for(let M=0;M<e.length-1;M++)if(e[M]===b&&e[M+1]===w){v=0;break}}if(e.length>=2){let b=e[e.length-2],M=e[e.length-1];for(let x=0;x<e.length-2;x++)if(e[x]===b&&e[x+1]===M&&e[x+2]===w){v=0;break}}z.includes(w)&&(v*=.1),p&&this.morphology.suffixFeatures.hasOwnProperty(w)?this.morphology.determineVowelHarmony(w)!==p&&(v=0):p&&this.morphology.determineVowelHarmony(w)===p&&(v*=1.15),y.push({word:w,score:v})}return y.sort((m,f)=>f.score-m.score),this._sample(y,i)}_predictJS(e,i,t){let a=new Float32Array(this.D);if(t>0&&e.length>t){let c=this.embeddings.get(e[t-1])||this.embeddings.get("<unk>"),d=this.embeddings.get(e[e.length-1])||this.embeddings.get("<unk>");for(let y=0;y<this.D;y++){let p=c.emb.values[y]+d.emb.values[y];p<0&&(p+=2*Math.PI),a[y]=p%(2*Math.PI)}}else{let c=this.embeddings.get(e[e.length-1])||this.embeddings.get("<unk>");a.set(c.emb.values)}let s=new Float32Array(this.D);for(let c=0;c<this.D;c++){let d=a[c]+(this.sparseWeightsSpec?this.sparseWeightsSpec.values[c]:0);d<0&&(d+=2*Math.PI),s[c]=d%(2*Math.PI)}let n=new Float32Array(this.D),r=new Float32Array(this.D);for(let c=0;c<this.D;c++)n[c]=Math.cos(s[c]),r[c]=Math.sin(s[c]);let l=[],o=e[e.length-1],h=o?this.morphology.determineVowelHarmony(o):null,u=e.slice(-4);for(let[c,d]of this.embeddings.entries()){let y=0,p=d.cosVals,z=d.sinVals;for(let f=0;f<this.D;f++)y+=n[f]*p[f]+r[f]*z[f];let m=y/this.D;if(m=Math.max(1e-4,(m+1)/2),o){let f=this.transitionCounts.get(o);if(f){let w=f.get(c)||0;m*=w>0?1.5+w*2:.1}else m*=.5}if(e.length>=1){let f=e[e.length-1];for(let w=0;w<e.length-1;w++)if(e[w]===f&&e[w+1]===c){m=0;break}}if(e.length>=2){let f=e[e.length-2],w=e[e.length-1];for(let v=0;v<e.length-2;v++)if(e[v]===f&&e[v+1]===w&&e[v+2]===c){m=0;break}}u.includes(c)&&(m*=.1),h&&this.morphology.suffixFeatures.hasOwnProperty(c)?this.morphology.determineVowelHarmony(c)!==h&&(m=0):h&&this.morphology.determineVowelHarmony(c)===h&&(m*=1.15),l.push({word:c,score:m})}return l.sort((c,d)=>d.score-c.score),this._sample(l.slice(0,5),i)}_sample(e,i){if(!e.length)return{word:"<unk>",score:0};if(i<=.05)return e[0];let t=e[0].score,a=e.map(o=>Math.exp((o.score-t)/i)),s=a.reduce((o,h)=>o+h,0),n=a.map(o=>o/s),r=Math.random(),l=0;for(let o=0;o<e.length;o++)if(l+=n[o],r<=l)return e[o];return e[0]}_isTerminal(e){return new Set([".","gittik","ald\u0131m","ald\u0131k","geli\u015Ftirir","uyand\u0131k","kuruludur","\xE7\u0131kt\u0131k","izledim","izledik","uyudum","yatt\u0131m","gittim","yapt\u0131m","\xF6\u011Frendim"]).has(e)||e.endsWith(".")}_assertInit(){if(!this._initialized)throw new Error("ResonanceSDK: Not initialized. Call await sdk.init() first.")}};export{B as ResonanceSDK};
|
|
7
|
+
/**
|
|
8
|
+
* Resonance SDK v1.0 - B2B Commercial Edge AI Engine
|
|
9
|
+
* Unified SDK interface wrapping the Turkish Resonance AI Core (v5.2).
|
|
10
|
+
* Supports both Browser (fetch/streaming) and Node.js environments.
|
|
11
|
+
*
|
|
12
|
+
* @license Commercial - Per-device licensing
|
|
13
|
+
* @author Turkish Resonance AI Core Team
|
|
14
|
+
*/
|
|
Binary file
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TypeScript Type Definitions for mycai
|
|
3
|
+
* https://mycai.pro
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export class TurkishMorphology {
|
|
7
|
+
constructor(roots?: string[]);
|
|
8
|
+
normalize(text: string): string;
|
|
9
|
+
analyze(word: string): {
|
|
10
|
+
word: string;
|
|
11
|
+
root: string;
|
|
12
|
+
suffixes: string[];
|
|
13
|
+
harmony: string;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class GHRLatticeMemory {
|
|
18
|
+
constructor(options?: { D?: number; cellSize?: number; sigma?: number });
|
|
19
|
+
insert(packet: { id: string; phases: Float64Array | Float32Array }, metadata?: any): void;
|
|
20
|
+
query(queryVector: { phases: Float64Array | Float32Array }, k?: number): Array<{ id: string; score: number; metadata: any }>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class LicenseManager {
|
|
24
|
+
static generateLicenseKey(opts: {
|
|
25
|
+
tier?: 'STARTER' | 'BUSINESS' | 'SOVEREIGN';
|
|
26
|
+
expiresAt?: number | Date;
|
|
27
|
+
maxNodes?: number;
|
|
28
|
+
clientId?: string;
|
|
29
|
+
}): string;
|
|
30
|
+
verifyLicense(key: string): {
|
|
31
|
+
valid: boolean;
|
|
32
|
+
tier: any;
|
|
33
|
+
expiresAt: Date;
|
|
34
|
+
maxNodes: number;
|
|
35
|
+
clientId: string;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class ResonanceEngine {
|
|
40
|
+
constructor(config?: { licenseKey?: string; storagePath?: string });
|
|
41
|
+
ingest(document: string | object, metadata?: any): Promise<number>;
|
|
42
|
+
query(text: string, options?: { topK?: number }): Promise<any>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export default ResonanceEngine;
|
package/index.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mycai — Sovereign Air-Gapped Cognitive AI SDK
|
|
3
|
+
*
|
|
4
|
+
* Official SDK for 100% On-Device, Offline Turkish NLP,
|
|
5
|
+
* GHR-Lattice Resonance Memory, and Industrial Edge Automation.
|
|
6
|
+
*
|
|
7
|
+
* @author mycai Core Team (https://mycai.pro)
|
|
8
|
+
* @license Apache-2.0
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export { TurkishMorphology } from './core/morphology.js';
|
|
12
|
+
export { GHRLatticeMemory } from './core/ghr_lattice_memory.js';
|
|
13
|
+
export { HDCEngine, Representation } from './core/hdc.js';
|
|
14
|
+
export { SpectralDecoder } from './core/spectral_decoder.js';
|
|
15
|
+
export { ReasoningRouter } from './core/reasoning_router.js';
|
|
16
|
+
export { SovereignAgent } from './core/sovereign_agent.js';
|
|
17
|
+
|
|
18
|
+
export { ResonanceEngine } from './sdk/resonance_engine.js';
|
|
19
|
+
export { ResonanceSDK } from './sdk/resonance_sdk.js';
|
|
20
|
+
export { LicenseManager, LICENSE_TIERS } from './sdk/licensing.js';
|
|
21
|
+
export { IngestionPipeline } from './sdk/ingestion.js';
|
|
22
|
+
export { SovereignStorage } from './sdk/storage.js';
|
|
23
|
+
|
|
24
|
+
// Default export
|
|
25
|
+
import { ResonanceEngine } from './sdk/resonance_engine.js';
|
|
26
|
+
export default ResonanceEngine;
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "mycai",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Sovereign Air-Gapped Cognitive AI & Embedded Intent Engine for Turkish NLP and Industrial Automation",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"module": "index.js",
|
|
7
|
+
"types": "index.d.ts",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"bin": {
|
|
10
|
+
"mycai": "./bin/mycai.js"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"bin",
|
|
14
|
+
"core",
|
|
15
|
+
"sdk",
|
|
16
|
+
"dist/resonance_sdk.js",
|
|
17
|
+
"dist/resonance_sdk.min.js",
|
|
18
|
+
"dist/spectral_core.wasm",
|
|
19
|
+
"index.js",
|
|
20
|
+
"index.d.ts",
|
|
21
|
+
"README.md",
|
|
22
|
+
"LICENSE"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"start": "node bin/mycai.js",
|
|
26
|
+
"test": "node tests.js"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"ai",
|
|
30
|
+
"edge-ai",
|
|
31
|
+
"air-gapped",
|
|
32
|
+
"turkish-nlp",
|
|
33
|
+
"nlp",
|
|
34
|
+
"plc",
|
|
35
|
+
"modbus",
|
|
36
|
+
"embedded",
|
|
37
|
+
"sovereign-ai",
|
|
38
|
+
"ghr-lattice",
|
|
39
|
+
"mycai"
|
|
40
|
+
],
|
|
41
|
+
"author": "mycai Core Engineering Team (https://mycai.pro)",
|
|
42
|
+
"license": "Apache-2.0",
|
|
43
|
+
"homepage": "https://mycai.pro",
|
|
44
|
+
"repository": {
|
|
45
|
+
"type": "git",
|
|
46
|
+
"url": "https://github.com/mycai-pro/mycai"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"express": "^4.19.2",
|
|
50
|
+
"xlsx": "^0.18.5"
|
|
51
|
+
}
|
|
52
|
+
}
|
package/sdk/README.md
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# @resonance/core — Commercial B2B Infrastructure SDK
|
|
2
|
+
|
|
3
|
+
**Turkish Resonance AI Core & Sovereign Cognitive Runtime v2.0**
|
|
4
|
+
*100% Air-Gapped, Sub-Millisecond Turkish Language Intelligence & Living Memory Engine*
|
|
5
|
+
|
|
6
|
+
[]()
|
|
7
|
+
[]()
|
|
8
|
+
[]()
|
|
9
|
+
[]()
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 💎 Executive Summary & Value Proposition
|
|
14
|
+
|
|
15
|
+
Traditional generative AI models (OpenAI, Claude, Llama) require power-hungry GPU clusters, constant internet connectivity, and introduce unpredictable token billing, telemetry leaks, and 500ms–3000ms latency.
|
|
16
|
+
|
|
17
|
+
**Resonance SDK** is an enterprise-grade, edge-compatible cognitive infrastructure library engineered specifically for **Turkish language intelligence, tactical edge devices, defense systems, and regulated enterprise environments (Banking, Legal, Telecom)**.
|
|
18
|
+
|
|
19
|
+
| Metric | Resonance SDK (@resonance/core) | Traditional Cloud LLM APIs |
|
|
20
|
+
| :--- | :--- | :--- |
|
|
21
|
+
| **Reaction Latency** | **< 0.05 ms (Math/Rules) / < 3 ms (Memory)** | 500 ms – 3000 ms |
|
|
22
|
+
| **Cloud Dependency** | **Zero (100% Offline / Air-Gapped)** | Mandatory Internet Connection |
|
|
23
|
+
| **Hardware Footprint** | **< 20 MB RAM (Runs on MCU / SBC / Laptop)** | Server Racks / High-End GPUs |
|
|
24
|
+
| **Data Privacy** | **Zero Telemetry Leak (Data never leaves device)** | Sent to 3rd party cloud |
|
|
25
|
+
| **Inference Margins** | **100% Gross Margin (Zero per-query cost)** | Recurring API bill per token |
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 📦 Commercial License Tiers
|
|
30
|
+
|
|
31
|
+
Resonance SDK enforces cryptographic, zero-cloud offline license keys (`RES-{TIER}-{EXPIRY}-{MAX_NODES}-{CLIENT_ID}-{SIG}`):
|
|
32
|
+
|
|
33
|
+
| Feature | Starter Tier | Business Tier | Sovereign / Tactical Tier |
|
|
34
|
+
| :--- | :--- | :--- | :--- |
|
|
35
|
+
| **Memory Node Quota** | Up to **1,000 Nodes** | Up to **50,000 Nodes** | **Unlimited Nodes** |
|
|
36
|
+
| **Cognitive Gates** | AST Math, Rule Gates | Math, Morphology, Q&A | All Gates + Custom Rules |
|
|
37
|
+
| **Ingestion Pipeline** | Plain Text, Markdown | Text, CSV, PDF, Web HTML | All Formats + Streaming Chunker |
|
|
38
|
+
| **Storage Adapters** | RAM (In-Memory) | RAM, Local Disk, IndexedDB | Pluggable Custom Storage |
|
|
39
|
+
| **Hardware Acceleration**| Standard CPU | Multi-Core Optimization | WASM SIMD / FPGA / Embedded |
|
|
40
|
+
| **Target Clients** | Prototyping & Startups | Medium Enterprises / Apps | Defense, Banking, Critical Infra |
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## 🚀 Quick Start (Node.js & TypeScript)
|
|
45
|
+
|
|
46
|
+
### 1. Installation
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
# From private scoped registry or vendor tgz archive
|
|
50
|
+
npm install @resonance/core
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### 2. Implementation
|
|
54
|
+
|
|
55
|
+
```javascript
|
|
56
|
+
import { ResonanceEngine, LicenseManager, FileStorageAdapter } from '@resonance/core';
|
|
57
|
+
|
|
58
|
+
// 1. Initialize Engine with Offline License & Disk Persistence
|
|
59
|
+
const engine = new ResonanceEngine({
|
|
60
|
+
licenseKey: process.env.RESONANCE_LICENSE_KEY,
|
|
61
|
+
storage: new FileStorageAdapter('./data/enterprise_memory.json')
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
await engine.init();
|
|
65
|
+
|
|
66
|
+
// 2. Ingest Multi-Page Documents, Laws, or Business Data
|
|
67
|
+
await engine.ingest({
|
|
68
|
+
type: 'text',
|
|
69
|
+
title: '6100 Sayılı HMK',
|
|
70
|
+
data: 'Madde 2: Asliye hukuk mahkemelerinin görevi malvarlığı davalarını görmektir.'
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// 3. Sub-Millisecond Q&A
|
|
74
|
+
const reply = await engine.ask('Asliye hukuk mahkemelerinin görevi nedir?');
|
|
75
|
+
console.log(reply.answer);
|
|
76
|
+
console.log(`Latency: ${reply.latencyMs}ms | Route: ${reply.route}`);
|
|
77
|
+
|
|
78
|
+
// 4. Real-time Operational Telemetry
|
|
79
|
+
console.log(engine.getTelemetry());
|
|
80
|
+
// => { activeNodes: 45, maxNodesQuota: 50000, avgLatencyMs: 0.85, ... }
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## 🛠️ Architecture & Core Components
|
|
86
|
+
|
|
87
|
+
```
|
|
88
|
+
┌────────────────────────────────────────────────────────────────────────┐
|
|
89
|
+
│ @resonance/core — Commercial Architecture │
|
|
90
|
+
├────────────────────────────────────────────────────────────────────────┤
|
|
91
|
+
│ [1] ResonanceEngine (Public Facade API) │
|
|
92
|
+
│ • ask(prompt) → { answer, route, latencyMs, confidence } │
|
|
93
|
+
│ • ingest({ data, type, title }) → { success, recordsAdded } │
|
|
94
|
+
│ • summarize({ page, mode: 'concise'|'single' }) │
|
|
95
|
+
│ • search(query, limit) │
|
|
96
|
+
│ • getTelemetry() │
|
|
97
|
+
├────────────────────────────────────────────────────────────────────────┤
|
|
98
|
+
│ [2] Cognitive Dispatcher & Routing Gates │
|
|
99
|
+
│ • Math Gate (Deterministic AST Parser, 0.02ms) │
|
|
100
|
+
│ • Morphology Gate (Turkish Inflection & Root Engine, 0.1ms) │
|
|
101
|
+
│ • Precision Q&A Gate (Direct snippet and article extraction) │
|
|
102
|
+
│ • Concise Page Summarizer (Filters boilerplate, single sentence) │
|
|
103
|
+
├────────────────────────────────────────────────────────────────────────┤
|
|
104
|
+
│ [3] Ingestion Pipeline (Modular Zero-Bloat) │
|
|
105
|
+
│ • Text / Markdown (Native 0-dependency) │
|
|
106
|
+
│ • CSV / Tabular (Native column mapper) │
|
|
107
|
+
│ • PDF Ingestion (On-demand dynamic import) │
|
|
108
|
+
│ • Web HTML Ingestion (HTML sanitization & chunking) │
|
|
109
|
+
├────────────────────────────────────────────────────────────────────────┤
|
|
110
|
+
│ [4] Pluggable Persistence Layer │
|
|
111
|
+
│ • MemoryStorageAdapter (Ultra-fast RAM) │
|
|
112
|
+
│ • FileStorageAdapter (Node.js JSON/Binary on disk) │
|
|
113
|
+
│ • IndexedDBStorageAdapter (Browser / Electron persistent store) │
|
|
114
|
+
├────────────────────────────────────────────────────────────────────────┤
|
|
115
|
+
│ [5] Cryptographic Licensing & Security │
|
|
116
|
+
│ • 100% Air-Gapped HMAC/Ed25519 Token Validation │
|
|
117
|
+
│ • Constant-Time Signature Comparison │
|
|
118
|
+
│ • Quota & Feature Gating │
|
|
119
|
+
└────────────────────────────────────────────────────────────────────────┘
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## 🔑 Vendor License Generation (For Sales & Operations)
|
|
125
|
+
|
|
126
|
+
Vendors can generate cryptographic offline licenses using the SDK CLI or programmatic API:
|
|
127
|
+
|
|
128
|
+
```javascript
|
|
129
|
+
import { LicenseManager } from '@resonance/core';
|
|
130
|
+
|
|
131
|
+
const enterpriseLicense = LicenseManager.generateLicenseKey({
|
|
132
|
+
tier: 'BUSINESS',
|
|
133
|
+
expiresAt: new Date('2027-12-31'),
|
|
134
|
+
maxNodes: 50000,
|
|
135
|
+
clientId: 'turkcell-fintech'
|
|
136
|
+
}, process.env.VENDOR_MASTER_SECRET);
|
|
137
|
+
|
|
138
|
+
console.log(enterpriseLicense);
|
|
139
|
+
// => RES-BUSINESS-1830211200000-50000-turkcellfintech-9f8a7b6c...
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## 📄 Full TypeScript Support
|
|
145
|
+
|
|
146
|
+
Full type declarations (`types.d.ts`) are bundled with IntelliSense support for Visual Studio Code, Cursor, and WebStorm.
|
|
147
|
+
|
|
148
|
+
---
|
|
149
|
+
|
|
150
|
+
## 📞 Enterprise Commercial Support
|
|
151
|
+
|
|
152
|
+
For custom military/defense hardware deployments, specialized rule sets, or volume licensing contracts:
|
|
153
|
+
* **Email:** enterprise@resonance-ai.internal
|
|
154
|
+
* **SLA:** 24/7 Air-Gapped On-Premise Support Available
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resonance SDK v1.0 — Example: Banking Chatbot Integration
|
|
3
|
+
* Demonstrates real-world B2B use case: Edge AI for a Turkish banking assistant.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { ResonanceSDK } from '../resonance_sdk.js';
|
|
7
|
+
|
|
8
|
+
async function main() {
|
|
9
|
+
console.log('═══════════════════════════════════════════════');
|
|
10
|
+
console.log(' 🏦 Turkish Banking Assistant — Edge AI Demo');
|
|
11
|
+
console.log('═══════════════════════════════════════════════\n');
|
|
12
|
+
|
|
13
|
+
// 1. Initialize SDK (sub-5s cold start, zero cloud)
|
|
14
|
+
const sdk = new ResonanceSDK({
|
|
15
|
+
temperature: 0.3, // Low temp for banking = more deterministic
|
|
16
|
+
maxLength: 8
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
console.log('⏳ Initializing Resonance SDK...');
|
|
20
|
+
const t0 = performance.now();
|
|
21
|
+
await sdk.init();
|
|
22
|
+
const initMs = performance.now() - t0;
|
|
23
|
+
console.log(`✅ Ready in ${initMs.toFixed(0)}ms | Vocab: ${sdk.getMetrics().vocabSize} words\n`);
|
|
24
|
+
|
|
25
|
+
// 2. Simulate customer queries
|
|
26
|
+
const queries = [
|
|
27
|
+
"yeni bir hesap açmak istiyorum",
|
|
28
|
+
"bilimsel araştırmalar",
|
|
29
|
+
"evimizden okula gittik",
|
|
30
|
+
"yapay zeka ile",
|
|
31
|
+
"güzel bir gün"
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
for (const query of queries) {
|
|
35
|
+
console.log(`👤 Müşteri: "${query}"`);
|
|
36
|
+
|
|
37
|
+
// Streaming output
|
|
38
|
+
process.stdout.write('🤖 Asistan: ');
|
|
39
|
+
const result = sdk.generate(query, {
|
|
40
|
+
maxLength: 6,
|
|
41
|
+
onToken: (word) => process.stdout.write(word + ' ')
|
|
42
|
+
});
|
|
43
|
+
console.log(`\n ⚡ ${result.totalLatencyMs.toFixed(1)}ms | ${result.newTokens.length} tokens | ${result.finishReason}`);
|
|
44
|
+
console.log('');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// 3. Morphological analysis demo
|
|
48
|
+
console.log('═══════════════════════════════════════════════');
|
|
49
|
+
console.log(' 📝 Morfolojik Analiz Örnekleri');
|
|
50
|
+
console.log('═══════════════════════════════════════════════\n');
|
|
51
|
+
|
|
52
|
+
const words = ["evlerimizden", "kitaplarınız", "bilgisayarları"];
|
|
53
|
+
for (const w of words) {
|
|
54
|
+
const analysis = sdk.analyze(w);
|
|
55
|
+
console.log(` "${w}" → kök: "${analysis.root}", ekler: [${(analysis.suffixes || []).join(', ')}]`);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
console.log('\n✅ Demo tamamlandı.\n');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
main().catch(console.error);
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="tr">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
6
|
+
<title>Resonance SDK v1.0 - Browser Integration Example</title>
|
|
7
|
+
<style>
|
|
8
|
+
body {
|
|
9
|
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
|
10
|
+
background-color: #0f172a;
|
|
11
|
+
color: #e2e8f0;
|
|
12
|
+
max-width: 800px;
|
|
13
|
+
margin: 40px auto;
|
|
14
|
+
padding: 20px;
|
|
15
|
+
}
|
|
16
|
+
h1 {
|
|
17
|
+
color: #38bdf8;
|
|
18
|
+
border-bottom: 1px solid #334155;
|
|
19
|
+
padding-bottom: 10px;
|
|
20
|
+
}
|
|
21
|
+
.card {
|
|
22
|
+
background-color: #1e293b;
|
|
23
|
+
border-radius: 8px;
|
|
24
|
+
padding: 20px;
|
|
25
|
+
margin-top: 20px;
|
|
26
|
+
border: 1px solid #334155;
|
|
27
|
+
}
|
|
28
|
+
button {
|
|
29
|
+
background-color: #0284c7;
|
|
30
|
+
color: white;
|
|
31
|
+
border: none;
|
|
32
|
+
padding: 10px 20px;
|
|
33
|
+
border-radius: 4px;
|
|
34
|
+
cursor: pointer;
|
|
35
|
+
font-size: 16px;
|
|
36
|
+
}
|
|
37
|
+
button:hover {
|
|
38
|
+
background-color: #0369a1;
|
|
39
|
+
}
|
|
40
|
+
pre {
|
|
41
|
+
background-color: #0f172a;
|
|
42
|
+
padding: 15px;
|
|
43
|
+
border-radius: 6px;
|
|
44
|
+
overflow-x: auto;
|
|
45
|
+
border: 1px solid #1e293b;
|
|
46
|
+
}
|
|
47
|
+
.status {
|
|
48
|
+
font-weight: bold;
|
|
49
|
+
color: #10b981;
|
|
50
|
+
}
|
|
51
|
+
</style>
|
|
52
|
+
</head>
|
|
53
|
+
<body>
|
|
54
|
+
<h1>Resonance SDK Browser Example</h1>
|
|
55
|
+
<div class="card">
|
|
56
|
+
<p>Status: <span id="status" class="status">Loading WASM & Corpus...</span></p>
|
|
57
|
+
<button id="generateBtn" disabled>Generate Text</button>
|
|
58
|
+
<div style="margin-top: 20px;">
|
|
59
|
+
<h3>Prompt:</h3>
|
|
60
|
+
<pre>yeni bir kitap</pre>
|
|
61
|
+
<h3>Result:</h3>
|
|
62
|
+
<pre id="output">Click "Generate Text" to run.</pre>
|
|
63
|
+
</div>
|
|
64
|
+
</div>
|
|
65
|
+
|
|
66
|
+
<script type="module">
|
|
67
|
+
import { ResonanceSDK } from '../resonance_sdk.js';
|
|
68
|
+
|
|
69
|
+
const sdk = new ResonanceSDK({
|
|
70
|
+
temperature: 0.7,
|
|
71
|
+
maxLength: 8
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
const statusEl = document.getElementById('status');
|
|
75
|
+
const generateBtn = document.getElementById('generateBtn');
|
|
76
|
+
const outputEl = document.getElementById('output');
|
|
77
|
+
|
|
78
|
+
try {
|
|
79
|
+
await sdk.init({
|
|
80
|
+
wasmUrl: '../../wasm/spectral_core.wasm',
|
|
81
|
+
corpusUrl: '../../tr_corpus_embed.js'
|
|
82
|
+
});
|
|
83
|
+
statusEl.textContent = 'Ready (SDK version 1.0)';
|
|
84
|
+
generateBtn.disabled = false;
|
|
85
|
+
} catch (err) {
|
|
86
|
+
statusEl.textContent = 'Initialization Failed';
|
|
87
|
+
statusEl.style.color = '#ef4444';
|
|
88
|
+
outputEl.textContent = err.message;
|
|
89
|
+
console.error(err);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
generateBtn.addEventListener('click', () => {
|
|
93
|
+
outputEl.textContent = 'Generating...';
|
|
94
|
+
const prompt = 'yeni bir kitap';
|
|
95
|
+
const result = sdk.generate(prompt, {
|
|
96
|
+
onToken: (token) => {
|
|
97
|
+
console.log('Streamed token:', token);
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
outputEl.textContent = JSON.stringify(result, null, 2);
|
|
101
|
+
});
|
|
102
|
+
</script>
|
|
103
|
+
</body>
|
|
104
|
+
</html>
|