UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 2.31 kB
const e={},t=/[A-Za-z0-9+/_=-]{16,}|\b[0-9]+\b|[{}[\]:,]/g,n=/[A-Za-z]+|[0-9]{1,3}|[^A-Za-z0-9]/y,r=/[\p{ASCII}]+|[^\p{ASCII}]/gu,i=[[[183,183],[12288,12703],[19968,40869],[44032,55215],[65281,65376]],[[4352,4607],[11904,12287],[12704,19967],[40870,40959],[40960,42239],[42752,42759],[43360,43391],[55216,55295],[63744,64255]],[[711,711],[713,715],[729,729],[746,747],[773,773],[803,803],[65040,65103],[65377,65500],[65504,65510]],[[119648,119665]],[[94176,94207],[94208,101647],[110576,110591],[110592,111359],[127488,127743],[131072,195103],[196608,210047]]],a=/* @__PURE__ */ RegExp(`[${i.flatMap(e=>e.map(([e,t])=>`\\u{${e.toString(16)}}-\\u{${t.toString(16)}}`)).join(``)}]`,`u`),o=/* @__PURE__ */ (()=>{let e=Math.max(...i.flatMap(e=>e.map(([,e])=>e))),t=new Uint8Array(e+1);for(let[e,n]of i.entries())for(let[r,i]of n)t.fill(e+1,r,i+1);return t})();function estimateStringChars(e){return estimateStringCharsWithMinimumRawWeight(e)}function estimateStringCharsWithMinimumRawWeight(t,n=e){let i=Math.max(1,n.minimumRawWeight??1);if(i!==1&&i!==2){let e=0;for(let n of t.matchAll(r)){let t=n[0],r=Math.ceil(t.length*i);e+=t.charCodeAt(0)<=127?r:Math.max(estimateStringChars(t),r)}return e}let s=t.search(a);if(s<0)return t.length*i;let c=0,l=0,u=0,d=0,f=0;for(let e=s;e<t.length;e+=1){let n=t.charCodeAt(e);if(!(n<128)){if(n>=55296&&n<=56319){let r=t.charCodeAt(e+1);r>=56320&&r<=57343&&(n=65536+(n-55296)*1024+r-56320,e+=1)}switch(o[n]){case 1:c+=1;break;case 2:l+=1;break;case 3:u+=1;break;case 4:d+=1;break;case 5:f+=1}}}return t.length*i+c*(4-i)+l*(12-i)+u*(8-i)+d*(12-2*i)+f*(16-2*i)}function estimateTokensFromChars(e){return Math.ceil(Math.max(0,e)/4)}function estimateStringTokenPressure(e,r=4){let i=estimateStringChars(e)/r;t.lastIndex=0;let a=0;for(;t.test(e);){let o=t.lastIndex,s=o,c=o,l=!1,u=!1;for(;s>a;){let t=e.charCodeAt(s-1),n=t>=48&&t<=57,r=t>=65&&t<=90||t>=97&&t<=122;if(!n&&!r&&t!==43&&t!==47&&t!==95&&t!==61&&t!==45)break;s--,l||=r,u||=n,n&&c===s+1&&(c=s)}a=o,s===o?s--:o-s<16&&(s=c);let d=o-s,f=0;if(c===s)f=Math.ceil(d/3);else if(d===1)f=1;else{if(d<64&&!(l&&u))continue;for(n.lastIndex=s;s<o&&n.test(e);){let e=n.lastIndex;f+=Math.ceil((e-s)/r),s=e}}i+=Math.max(0,f-d/r)}return Math.ceil(i)}export{estimateStringTokenPressure as n,estimateTokensFromChars as r,estimateStringChars as t};