@ax-llm/ax 13.0.23 → 14.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/index.cjs +134 -52
- package/index.cjs.map +1 -1
- package/index.d.cts +1828 -179
- package/index.d.ts +1828 -179
- package/index.global.js +225 -143
- package/index.global.js.map +1 -1
- package/index.js +134 -52
- package/index.js.map +1 -1
- package/package.json +1 -1
package/index.global.js
CHANGED
|
@@ -1,125 +1,127 @@
|
|
|
1
|
-
"use strict";var ax=(()=>{var la=Object.create;var Yt=Object.defineProperty;var ca=Object.getOwnPropertyDescriptor;var pa=Object.getOwnPropertyNames;var ua=Object.getPrototypeOf,da=Object.prototype.hasOwnProperty;var Jt=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),ma=(s,e)=>{for(var t in e)Yt(s,t,{get:e[t],enumerable:!0})},Lr=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pa(e))!da.call(s,o)&&o!==t&&Yt(s,o,{get:()=>e[o],enumerable:!(n=ca(e,o))||n.enumerable});return s};var Qt=(s,e,t)=>(t=s!=null?la(ua(s)):{},Lr(e||!s||!s.__esModule?Yt(t,"default",{value:s,enumerable:!0}):t,s)),ga=s=>Lr(Yt({},"__esModule",{value:!0}),s);var yi=Jt((gr,hr)=>{"use strict";(function(s,e){typeof gr=="object"&&typeof hr<"u"?hr.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs=e()})(gr,function(){"use strict";var s=1e3,e=6e4,t=36e5,n="millisecond",o="second",r="minute",i="hour",a="day",l="week",c="month",p="quarter",d="year",u="date",m="Invalid Date",g=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,f={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(v){var R=["th","st","nd","rd"],I=v%100;return"["+v+(R[(I-20)%10]||R[I]||R[0])+"]"}},A=function(v,R,I){var S=String(v);return!S||S.length>=R?v:""+Array(R+1-S.length).join(I)+v},x={s:A,z:function(v){var R=-v.utcOffset(),I=Math.abs(R),S=Math.floor(I/60),C=I%60;return(R<=0?"+":"-")+A(S,2,"0")+":"+A(C,2,"0")},m:function v(R,I){if(R.date()<I.date())return-v(I,R);var S=12*(I.year()-R.year())+(I.month()-R.month()),C=R.clone().add(S,c),k=I-C<0,P=R.clone().add(S+(k?-1:1),c);return+(-(S+(I-C)/(k?C-P:P-C))||0)},a:function(v){return v<0?Math.ceil(v)||0:Math.floor(v)},p:function(v){return{M:c,y:d,w:l,d:a,D:u,h:i,m:r,s:o,ms:n,Q:p}[v]||String(v||"").toLowerCase().replace(/s$/,"")},u:function(v){return v===void 0}},y="en",O={};O[y]=f;var b="$isDayjsObject",T=function(v){return v instanceof N||!(!v||!v[b])},_=function v(R,I,S){var C;if(!R)return y;if(typeof R=="string"){var k=R.toLowerCase();O[k]&&(C=k),I&&(O[k]=I,C=k);var P=R.split("-");if(!C&&P.length>1)return v(P[0])}else{var G=R.name;O[G]=R,C=G}return!S&&C&&(y=C),C||!S&&y},w=function(v,R){if(T(v))return v.clone();var I=typeof R=="object"?R:{};return I.date=v,I.args=arguments,new N(I)},M=x;M.l=_,M.i=T,M.w=function(v,R){return w(v,{locale:R.$L,utc:R.$u,x:R.$x,$offset:R.$offset})};var N=function(){function v(I){this.$L=_(I.locale,null,!0),this.parse(I),this.$x=this.$x||I.x||{},this[b]=!0}var R=v.prototype;return R.parse=function(I){this.$d=function(S){var C=S.date,k=S.utc;if(C===null)return new Date(NaN);if(M.u(C))return new Date;if(C instanceof Date)return new Date(C);if(typeof C=="string"&&!/Z$/i.test(C)){var P=C.match(g);if(P){var G=P[2]-1||0,U=(P[7]||"0").substring(0,3);return k?new Date(Date.UTC(P[1],G,P[3]||1,P[4]||0,P[5]||0,P[6]||0,U)):new Date(P[1],G,P[3]||1,P[4]||0,P[5]||0,P[6]||0,U)}}return new Date(C)}(I),this.init()},R.init=function(){var I=this.$d;this.$y=I.getFullYear(),this.$M=I.getMonth(),this.$D=I.getDate(),this.$W=I.getDay(),this.$H=I.getHours(),this.$m=I.getMinutes(),this.$s=I.getSeconds(),this.$ms=I.getMilliseconds()},R.$utils=function(){return M},R.isValid=function(){return this.$d.toString()!==m},R.isSame=function(I,S){var C=w(I);return this.startOf(S)<=C&&C<=this.endOf(S)},R.isAfter=function(I,S){return w(I)<this.startOf(S)},R.isBefore=function(I,S){return this.endOf(S)<w(I)},R.$g=function(I,S,C){return M.u(I)?this[S]:this.set(C,I)},R.unix=function(){return Math.floor(this.valueOf()/1e3)},R.valueOf=function(){return this.$d.getTime()},R.startOf=function(I,S){var C=this,k=!!M.u(S)||S,P=M.p(I),G=function(de,J){var oe=M.w(C.$u?Date.UTC(C.$y,J,de):new Date(C.$y,J,de),C);return k?oe:oe.endOf(a)},U=function(de,J){return M.w(C.toDate()[de].apply(C.toDate("s"),(k?[0,0,0,0]:[23,59,59,999]).slice(J)),C)},z=this.$W,W=this.$M,X=this.$D,ye="set"+(this.$u?"UTC":"");switch(P){case d:return k?G(1,0):G(31,11);case c:return k?G(1,W):G(0,W+1);case l:var ge=this.$locale().weekStart||0,Oe=(z<ge?z+7:z)-ge;return G(k?X-Oe:X+(6-Oe),W);case a:case u:return U(ye+"Hours",0);case i:return U(ye+"Minutes",1);case r:return U(ye+"Seconds",2);case o:return U(ye+"Milliseconds",3);default:return this.clone()}},R.endOf=function(I){return this.startOf(I,!1)},R.$set=function(I,S){var C,k=M.p(I),P="set"+(this.$u?"UTC":""),G=(C={},C[a]=P+"Date",C[u]=P+"Date",C[c]=P+"Month",C[d]=P+"FullYear",C[i]=P+"Hours",C[r]=P+"Minutes",C[o]=P+"Seconds",C[n]=P+"Milliseconds",C)[k],U=k===a?this.$D+(S-this.$W):S;if(k===c||k===d){var z=this.clone().set(u,1);z.$d[G](U),z.init(),this.$d=z.set(u,Math.min(this.$D,z.daysInMonth())).$d}else G&&this.$d[G](U);return this.init(),this},R.set=function(I,S){return this.clone().$set(I,S)},R.get=function(I){return this[M.p(I)]()},R.add=function(I,S){var C,k=this;I=Number(I);var P=M.p(S),G=function(W){var X=w(k);return M.w(X.date(X.date()+Math.round(W*I)),k)};if(P===c)return this.set(c,this.$M+I);if(P===d)return this.set(d,this.$y+I);if(P===a)return G(1);if(P===l)return G(7);var U=(C={},C[r]=e,C[i]=t,C[o]=s,C)[P]||1,z=this.$d.getTime()+I*U;return M.w(z,this)},R.subtract=function(I,S){return this.add(-1*I,S)},R.format=function(I){var S=this,C=this.$locale();if(!this.isValid())return C.invalidDate||m;var k=I||"YYYY-MM-DDTHH:mm:ssZ",P=M.z(this),G=this.$H,U=this.$m,z=this.$M,W=C.weekdays,X=C.months,ye=C.meridiem,ge=function(J,oe,he,Ie){return J&&(J[oe]||J(S,k))||he[oe].slice(0,Ie)},Oe=function(J){return M.s(G%12||12,J,"0")},de=ye||function(J,oe,he){var Ie=J<12?"AM":"PM";return he?Ie.toLowerCase():Ie};return k.replace(h,function(J,oe){return oe||function(he){switch(he){case"YY":return String(S.$y).slice(-2);case"YYYY":return M.s(S.$y,4,"0");case"M":return z+1;case"MM":return M.s(z+1,2,"0");case"MMM":return ge(C.monthsShort,z,X,3);case"MMMM":return ge(X,z);case"D":return S.$D;case"DD":return M.s(S.$D,2,"0");case"d":return String(S.$W);case"dd":return ge(C.weekdaysMin,S.$W,W,2);case"ddd":return ge(C.weekdaysShort,S.$W,W,3);case"dddd":return W[S.$W];case"H":return String(G);case"HH":return M.s(G,2,"0");case"h":return Oe(1);case"hh":return Oe(2);case"a":return de(G,U,!0);case"A":return de(G,U,!1);case"m":return String(U);case"mm":return M.s(U,2,"0");case"s":return String(S.$s);case"ss":return M.s(S.$s,2,"0");case"SSS":return M.s(S.$ms,3,"0");case"Z":return P}return null}(J)||P.replace(":","")})},R.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},R.diff=function(I,S,C){var k,P=this,G=M.p(S),U=w(I),z=(U.utcOffset()-this.utcOffset())*e,W=this-U,X=function(){return M.m(P,U)};switch(G){case d:k=X()/12;break;case c:k=X();break;case p:k=X()/3;break;case l:k=(W-z)/6048e5;break;case a:k=(W-z)/864e5;break;case i:k=W/t;break;case r:k=W/e;break;case o:k=W/s;break;default:k=W}return C?k:M.a(k)},R.daysInMonth=function(){return this.endOf(c).$D},R.$locale=function(){return O[this.$L]},R.locale=function(I,S){if(!I)return this.$L;var C=this.clone(),k=_(I,S,!0);return k&&(C.$L=k),C},R.clone=function(){return M.w(this.$d,this)},R.toDate=function(){return new Date(this.valueOf())},R.toJSON=function(){return this.isValid()?this.toISOString():null},R.toISOString=function(){return this.$d.toISOString()},R.toString=function(){return this.$d.toUTCString()},v}(),H=N.prototype;return w.prototype=H,[["$ms",n],["$s",o],["$m",r],["$H",i],["$W",a],["$M",c],["$y",d],["$D",u]].forEach(function(v){H[v[1]]=function(R){return this.$g(R,v[0],v[1])}}),w.extend=function(v,R){return v.$i||(v(R,N,w),v.$i=!0),w},w.locale=_,w.isDayjs=T,w.unix=function(v){return w(1e3*v)},w.en=O[y],w.Ls=O,w.p={},w})});var Ii=Jt((Ar,fr)=>{"use strict";(function(s,e){typeof Ar=="object"&&typeof fr<"u"?fr.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_customParseFormat=e()})(Ar,function(){"use strict";var s={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},e=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,t=/\d/,n=/\d\d/,o=/\d\d?/,r=/\d*[^-_:/,()\s\d]+/,i={},a=function(g){return(g=+g)+(g>68?1900:2e3)},l=function(g){return function(h){this[g]=+h}},c=[/[+-]\d\d:?(\d\d)?|Z/,function(g){(this.zone||(this.zone={})).offset=function(h){if(!h||h==="Z")return 0;var f=h.match(/([+-]|\d\d)/g),A=60*f[1]+(+f[2]||0);return A===0?0:f[0]==="+"?-A:A}(g)}],p=function(g){var h=i[g];return h&&(h.indexOf?h:h.s.concat(h.f))},d=function(g,h){var f,A=i.meridiem;if(A){for(var x=1;x<=24;x+=1)if(g.indexOf(A(x,0,h))>-1){f=x>12;break}}else f=g===(h?"pm":"PM");return f},u={A:[r,function(g){this.afternoon=d(g,!1)}],a:[r,function(g){this.afternoon=d(g,!0)}],Q:[t,function(g){this.month=3*(g-1)+1}],S:[t,function(g){this.milliseconds=100*+g}],SS:[n,function(g){this.milliseconds=10*+g}],SSS:[/\d{3}/,function(g){this.milliseconds=+g}],s:[o,l("seconds")],ss:[o,l("seconds")],m:[o,l("minutes")],mm:[o,l("minutes")],H:[o,l("hours")],h:[o,l("hours")],HH:[o,l("hours")],hh:[o,l("hours")],D:[o,l("day")],DD:[n,l("day")],Do:[r,function(g){var h=i.ordinal,f=g.match(/\d+/);if(this.day=f[0],h)for(var A=1;A<=31;A+=1)h(A).replace(/\[|\]/g,"")===g&&(this.day=A)}],w:[o,l("week")],ww:[n,l("week")],M:[o,l("month")],MM:[n,l("month")],MMM:[r,function(g){var h=p("months"),f=(p("monthsShort")||h.map(function(A){return A.slice(0,3)})).indexOf(g)+1;if(f<1)throw new Error;this.month=f%12||f}],MMMM:[r,function(g){var h=p("months").indexOf(g)+1;if(h<1)throw new Error;this.month=h%12||h}],Y:[/[+-]?\d+/,l("year")],YY:[n,function(g){this.year=a(g)}],YYYY:[/\d{4}/,l("year")],Z:c,ZZ:c};function m(g){var h,f;h=g,f=i&&i.formats;for(var A=(g=h.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(w,M,N){var H=N&&N.toUpperCase();return M||f[N]||s[N]||f[H].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(v,R,I){return R||I.slice(1)})})).match(e),x=A.length,y=0;y<x;y+=1){var O=A[y],b=u[O],T=b&&b[0],_=b&&b[1];A[y]=_?{regex:T,parser:_}:O.replace(/^\[|\]$/g,"")}return function(w){for(var M={},N=0,H=0;N<x;N+=1){var v=A[N];if(typeof v=="string")H+=v.length;else{var R=v.regex,I=v.parser,S=w.slice(H),C=R.exec(S)[0];I.call(M,C),w=w.replace(C,"")}}return function(k){var P=k.afternoon;if(P!==void 0){var G=k.hours;P?G<12&&(k.hours+=12):G===12&&(k.hours=0),delete k.afternoon}}(M),M}}return function(g,h,f){f.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var A=h.prototype,x=A.parse;A.parse=function(y){var O=y.date,b=y.utc,T=y.args;this.$u=b;var _=T[1];if(typeof _=="string"){var w=T[2]===!0,M=T[3]===!0,N=w||M,H=T[2];M&&(H=T[2]),i=this.$locale(),!w&&H&&(i=f.Ls[H]),this.$d=function(S,C,k,P){try{if(["x","X"].indexOf(C)>-1)return new Date((C==="X"?1e3:1)*S);var G=m(C)(S),U=G.year,z=G.month,W=G.day,X=G.hours,ye=G.minutes,ge=G.seconds,Oe=G.milliseconds,de=G.zone,J=G.week,oe=new Date,he=W||(U||z?1:oe.getDate()),Ie=U||oe.getFullYear(),Vt=0;U&&!z||(Vt=z>0?z-1:oe.getMonth());var Wt,go=X||0,ho=ye||0,Ao=ge||0,fo=Oe||0;return de?new Date(Date.UTC(Ie,Vt,he,go,ho,Ao,fo+60*de.offset*1e3)):k?new Date(Date.UTC(Ie,Vt,he,go,ho,Ao,fo)):(Wt=new Date(Ie,Vt,he,go,ho,Ao,fo),J&&(Wt=P(Wt).week(J).toDate()),Wt)}catch{return new Date("")}}(O,_,b,f),this.init(),H&&H!==!0&&(this.$L=this.locale(H).$L),N&&O!=this.format(_)&&(this.$d=new Date("")),i={}}else if(_ instanceof Array)for(var v=_.length,R=1;R<=v;R+=1){T[1]=_[R-1];var I=f.apply(this,T);if(I.isValid()){this.$d=I.$d,this.$L=I.$L,this.init();break}R===v&&(this.$d=new Date(""))}else x.call(this,y)}}})});var bi=Jt((xr,yr)=>{"use strict";(function(s,e){typeof xr=="object"&&typeof yr<"u"?yr.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_timezone=e()})(xr,function(){"use strict";var s={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(t,n,o){var r,i=function(p,d,u){u===void 0&&(u={});var m=new Date(p),g=function(h,f){f===void 0&&(f={});var A=f.timeZoneName||"short",x=h+"|"+A,y=e[x];return y||(y=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:h,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:A}),e[x]=y),y}(d,u);return g.formatToParts(m)},a=function(p,d){for(var u=i(p,d),m=[],g=0;g<u.length;g+=1){var h=u[g],f=h.type,A=h.value,x=s[f];x>=0&&(m[x]=parseInt(A,10))}var y=m[3],O=y===24?0:y,b=m[0]+"-"+m[1]+"-"+m[2]+" "+O+":"+m[4]+":"+m[5]+":000",T=+p;return(o.utc(b).valueOf()-(T-=T%1e3))/6e4},l=n.prototype;l.tz=function(p,d){p===void 0&&(p=r);var u,m=this.utcOffset(),g=this.toDate(),h=g.toLocaleString("en-US",{timeZone:p}),f=Math.round((g-new Date(h))/1e3/60),A=15*-Math.round(g.getTimezoneOffset()/15)-f;if(!Number(A))u=this.utcOffset(0,d);else if(u=o(h,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(A,!0),d){var x=u.utcOffset();u=u.add(m-x,"minute")}return u.$x.$timezone=p,u},l.offsetName=function(p){var d=this.$x.$timezone||o.tz.guess(),u=i(this.valueOf(),d,{timeZoneName:p}).find(function(m){return m.type.toLowerCase()==="timezonename"});return u&&u.value};var c=l.startOf;l.startOf=function(p,d){if(!this.$x||!this.$x.$timezone)return c.call(this,p,d);var u=o(this.format("YYYY-MM-DD HH:mm:ss:SSS"),{locale:this.$L});return c.call(u,p,d).tz(this.$x.$timezone,!0)},o.tz=function(p,d,u){var m=u&&d,g=u||d||r,h=a(+o(),g);if(typeof p!="string")return o(p).tz(g);var f=function(O,b,T){var _=O-60*b*1e3,w=a(_,T);if(b===w)return[_,b];var M=a(_-=60*(w-b)*1e3,T);return w===M?[_,w]:[O-60*Math.min(w,M)*1e3,Math.max(w,M)]}(o.utc(p,m).valueOf(),h,g),A=f[0],x=f[1],y=o(A).utcOffset(x);return y.$x.$timezone=g,y},o.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},o.tz.setDefault=function(p){r=p}}})});var Ri=Jt((Ir,br)=>{"use strict";(function(s,e){typeof Ir=="object"&&typeof br<"u"?br.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_utc=e()})(Ir,function(){"use strict";var s="minute",e=/[+-]\d\d(?::?\d\d)?/g,t=/([+-]|\d\d)/g;return function(n,o,r){var i=o.prototype;r.utc=function(m){var g={date:m,utc:!0,args:arguments};return new o(g)},i.utc=function(m){var g=r(this.toDate(),{locale:this.$L,utc:!0});return m?g.add(this.utcOffset(),s):g},i.local=function(){return r(this.toDate(),{locale:this.$L,utc:!1})};var a=i.parse;i.parse=function(m){m.utc&&(this.$u=!0),this.$utils().u(m.$offset)||(this.$offset=m.$offset),a.call(this,m)};var l=i.init;i.init=function(){if(this.$u){var m=this.$d;this.$y=m.getUTCFullYear(),this.$M=m.getUTCMonth(),this.$D=m.getUTCDate(),this.$W=m.getUTCDay(),this.$H=m.getUTCHours(),this.$m=m.getUTCMinutes(),this.$s=m.getUTCSeconds(),this.$ms=m.getUTCMilliseconds()}else l.call(this)};var c=i.utcOffset;i.utcOffset=function(m,g){var h=this.$utils().u;if(h(m))return this.$u?0:h(this.$offset)?c.call(this):this.$offset;if(typeof m=="string"&&(m=function(y){y===void 0&&(y="");var O=y.match(e);if(!O)return null;var b=(""+O[0]).match(t)||["-",0,0],T=b[0],_=60*+b[1]+ +b[2];return _===0?0:T==="+"?_:-_}(m),m===null))return this;var f=Math.abs(m)<=16?60*m:m,A=this;if(g)return A.$offset=f,A.$u=m===0,A;if(m!==0){var x=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(A=this.local().add(f+x,s)).$offset=f,A.$x.$localOffset=x}else A=this.utc();return A};var p=i.format;i.format=function(m){var g=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return p.call(this,g)},i.valueOf=function(){var m=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*m},i.isUTC=function(){return!!this.$u},i.toISOString=function(){return this.toDate().toISOString()},i.toString=function(){return this.toDate().toUTCString()};var d=i.toDate;i.toDate=function(m){return m==="s"&&this.$offset?r(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():d.call(this)};var u=i.diff;i.diff=function(m,g,h){if(m&&this.$u===m.$u)return u.call(this,m,g,h);var f=this.local(),A=r(m).local();return u.call(f,A,g,h)}}})});var Jl={};ma(Jl,{AxAI:()=>Gn,AxAIAnthropic:()=>Be,AxAIAnthropicModel:()=>Tt,AxAIAnthropicVertexModel:()=>pn,AxAIAzureOpenAI:()=>Ke,AxAICohere:()=>Ve,AxAICohereEmbedModel:()=>Mt,AxAICohereModel:()=>St,AxAIDeepSeek:()=>We,AxAIDeepSeekModel:()=>Ot,AxAIGoogleGemini:()=>Ye,AxAIGoogleGeminiEmbedModel:()=>xn,AxAIGoogleGeminiEmbedTypes:()=>jo,AxAIGoogleGeminiModel:()=>kt,AxAIGoogleGeminiSafetyCategory:()=>yn,AxAIGoogleGeminiSafetyThreshold:()=>In,AxAIGrok:()=>it,AxAIGrokEmbedModels:()=>nr,AxAIGrokModel:()=>Nt,AxAIGroq:()=>Qe,AxAIGroqModel:()=>Et,AxAIHuggingFace:()=>Ze,AxAIHuggingFaceModel:()=>Tn,AxAIMistral:()=>Xe,AxAIMistralEmbedModels:()=>Yo,AxAIMistralModel:()=>_t,AxAIOllama:()=>et,AxAIOpenAI:()=>He,AxAIOpenAIBase:()=>V,AxAIOpenAIEmbedModel:()=>qe,AxAIOpenAIModel:()=>vt,AxAIOpenAIResponses:()=>nt,AxAIOpenAIResponsesBase:()=>Pt,AxAIOpenAIResponsesImpl:()=>tt,AxAIOpenAIResponsesModel:()=>ze,AxAIRefusalError:()=>$,AxAIReka:()=>ot,AxAIRekaModel:()=>Dt,AxAIServiceAbortedError:()=>De,AxAIServiceAuthenticationError:()=>be,AxAIServiceError:()=>ee,AxAIServiceNetworkError:()=>me,AxAIServiceResponseError:()=>Ae,AxAIServiceStatusError:()=>ke,AxAIServiceStreamTerminatedError:()=>le,AxAIServiceTimeoutError:()=>Ee,AxAITogether:()=>rt,AxAIWebLLM:()=>st,AxAIWebLLMModel:()=>Lt,AxAgent:()=>uo,AxApacheTika:()=>Wn,AxAssertionError:()=>Te,AxBalancer:()=>hn,AxBaseAI:()=>K,AxBaseOptimizer:()=>Me,AxBootstrapFewShot:()=>mt,AxChainOfThought:()=>xt,AxDB:()=>Ln,AxDBBase:()=>ae,AxDBCloudflare:()=>at,AxDBManager:()=>Nn,AxDBMemory:()=>Ce,AxDBPinecone:()=>lt,AxDBWeaviate:()=>ct,AxDefaultCostTracker:()=>Kt,AxDefaultResultReranker:()=>Vn,AxDockerSession:()=>io,AxEmbeddingAdapter:()=>ao,AxEvalUtil:()=>Yi,AxFlow:()=>so,AxFlowDependencyAnalyzer:()=>gt,AxFlowExecutionPlanner:()=>At,AxFlowSubContextImpl:()=>ft,AxFlowTypedSubContextImpl:()=>ro,AxFunctionError:()=>Bt,AxFunctionProcessor:()=>qt,AxGen:()=>j,AxGenerateError:()=>Ht,AxHFDataLoader:()=>Zn,AxInstanceRegistry:()=>ut,AxLLMRequestTypeValues:()=>Oo,AxMCPClient:()=>lo,AxMCPHTTPSSETransport:()=>co,AxMCPStreambleHTTPTransport:()=>po,AxMemory:()=>pt,AxMiPRO:()=>no,AxMockAIService:()=>Sn,AxMultiServiceRouter:()=>Mn,AxProgram:()=>Se,AxPromptTemplate:()=>Pe,AxRAG:()=>mo,AxRateLimiterTokenUsage:()=>Je,AxSignature:()=>q,AxSimpleClassifier:()=>Jn,AxSimpleClassifierClass:()=>Yn,AxSpanKindValues:()=>ko,AxStringUtil:()=>dt,AxTestPrompt:()=>Qn,ax:()=>ta,axAIAnthropicDefaultConfig:()=>No,axAIAnthropicVertexDefaultConfig:()=>Ns,axAIAzureOpenAIBestConfig:()=>qs,axAIAzureOpenAICreativeConfig:()=>$s,axAIAzureOpenAIDefaultConfig:()=>$o,axAIAzureOpenAIFastConfig:()=>Bs,axAICohereCreativeConfig:()=>js,axAICohereDefaultConfig:()=>qo,axAIDeepSeekCodeConfig:()=>Hs,axAIDeepSeekDefaultConfig:()=>zo,axAIGoogleGeminiDefaultConfig:()=>Ko,axAIGoogleGeminiDefaultCreativeConfig:()=>Vs,axAIGrokBestConfig:()=>ri,axAIGrokDefaultConfig:()=>Dn,axAIHuggingFaceCreativeConfig:()=>Ws,axAIHuggingFaceDefaultConfig:()=>Wo,axAIMistralBestConfig:()=>Ys,axAIMistralDefaultConfig:()=>vn,axAIOllamaDefaultConfig:()=>Jo,axAIOllamaDefaultCreativeConfig:()=>Js,axAIOpenAIBestConfig:()=>dn,axAIOpenAICreativeConfig:()=>mn,axAIOpenAIDefaultConfig:()=>_e,axAIOpenAIFastConfig:()=>gn,axAIOpenAIResponsesBestConfig:()=>Qs,axAIOpenAIResponsesCreativeConfig:()=>Zs,axAIOpenAIResponsesDefaultConfig:()=>Ft,axAIRekaBestConfig:()=>ei,axAIRekaCreativeConfig:()=>ti,axAIRekaDefaultConfig:()=>Gt,axAIRekaFastConfig:()=>ni,axAITogetherDefaultConfig:()=>Xo,axAIWebLLMCreativeConfig:()=>oi,axAIWebLLMDefaultConfig:()=>tr,axBaseAIDefaultConfig:()=>L,axBaseAIDefaultCreativeConfig:()=>Y,axCheckMetricsHealth:()=>si,axCreateDefaultColorLogger:()=>Mo,axCreateDefaultOptimizerColorLogger:()=>_r,axCreateDefaultOptimizerTextLogger:()=>Qi,axCreateDefaultTextLogger:()=>ls,axDefaultMetricsConfig:()=>ir,axDefaultOptimizerLogger:()=>Xn,axDefaultOptimizerMetricsConfig:()=>Pr,axGetMetricsConfig:()=>ai,axGetOptimizerMetricsConfig:()=>Xi,axGlobals:()=>B,axModelInfoAnthropic:()=>wt,axModelInfoCohere:()=>An,axModelInfoDeepSeek:()=>fn,axModelInfoGoogleGemini:()=>bn,axModelInfoGrok:()=>Fn,axModelInfoGroq:()=>Rn,axModelInfoHuggingFace:()=>Cn,axModelInfoMistral:()=>wn,axModelInfoOpenAI:()=>je,axModelInfoOpenAIResponses:()=>un,axModelInfoReka:()=>On,axModelInfoTogether:()=>kn,axModelInfoWebLLM:()=>Pn,axSpanAttributes:()=>D,axSpanEvents:()=>ce,axUpdateMetricsConfig:()=>ii,axUpdateOptimizerMetricsConfig:()=>Zi,axValidateChatRequestMessage:()=>En,axValidateChatResponseResult:()=>_n,f:()=>oa,s:()=>ea});function re({model:s,modelInfo:e,models:t}){let n=t?.find(l=>l.key===s),o=n&&"model"in n?n.model:s,r=e.find(l=>l.name===s);if(r)return r;let i=o.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),a=e.find(l=>l.name===i);return a||null}var Nr=(()=>{if(globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto;throw new Error("Web Crypto API with randomUUID support not available. Requires Node.js 16+ or modern browser.")})();function se(){return Nr.randomUUID()}async function ha(s){let e=new TextEncoder,t=typeof s=="string"?e.encode(s):s,n=await Nr.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var xo=class{data="";update(e){return this.data+=e,this}digest(e){if(e!=="hex")throw new Error("Only hex encoding is supported");let n=new TextEncoder().encode(this.data),o=0;for(let r=0;r<n.length;r++){let i=n[r];o=(o<<5)-o+i,o=o&o}return Math.abs(o).toString(16).padStart(8,"0")}async digestAsync(){return ha(this.data)}};function Zt(s){if(s!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new xo}var Xt=class extends TransformStream{buffer="";currentEvent={rawData:""};dataParser;onError;constructor(e={}){super({transform:(t,n)=>this.handleChunk(t,n),flush:t=>this.handleFlush(t)}),this.dataParser=e.dataParser||JSON.parse,this.onError=e.onError||((t,n)=>{console.warn("Failed to parse event data:",t),console.log("Raw data that failed to parse:",n)})}handleChunk(e,t){this.buffer+=e,this.processBuffer(t)}handleFlush(e){this.processBuffer(e),this.currentEvent.rawData&&this.processEvent(e)}processBuffer(e){let n=this.buffer.replace(/\r\n|\r/g,`
|
|
1
|
+
"use strict";var ax=(()=>{var ka=Object.create;var sn=Object.defineProperty;var Ea=Object.getOwnPropertyDescriptor;var Pa=Object.getOwnPropertyNames;var _a=Object.getPrototypeOf,Fa=Object.prototype.hasOwnProperty;var an=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Da=(s,e)=>{for(var t in e)sn(s,t,{get:e[t],enumerable:!0})},Qo=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pa(e))!Fa.call(s,r)&&r!==t&&sn(s,r,{get:()=>e[r],enumerable:!(n=Ea(e,r))||n.enumerable});return s};var ln=(s,e,t)=>(t=s!=null?ka(_a(s)):{},Qo(e||!s||!s.__esModule?sn(t,"default",{value:s,enumerable:!0}):t,s)),$a=s=>Qo(sn({},"__esModule",{value:!0}),s);var Ni=an((Eo,Po)=>{"use strict";(function(s,e){typeof Eo=="object"&&typeof Po<"u"?Po.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs=e()})(Eo,function(){"use strict";var s=1e3,e=6e4,t=36e5,n="millisecond",r="second",o="minute",i="hour",a="day",l="week",p="month",c="quarter",d="year",u="date",m="Invalid Date",g=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,A={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(v){var R=["th","st","nd","rd"],I=v%100;return"["+v+(R[(I-20)%10]||R[I]||R[0])+"]"}},f=function(v,R,I){var S=String(v);return!S||S.length>=R?v:""+Array(R+1-S.length).join(I)+v},x={s:f,z:function(v){var R=-v.utcOffset(),I=Math.abs(R),S=Math.floor(I/60),C=I%60;return(R<=0?"+":"-")+f(S,2,"0")+":"+f(C,2,"0")},m:function v(R,I){if(R.date()<I.date())return-v(I,R);var S=12*(I.year()-R.year())+(I.month()-R.month()),C=R.clone().add(S,p),E=I-C<0,_=R.clone().add(S+(E?-1:1),p);return+(-(S+(I-C)/(E?C-_:_-C))||0)},a:function(v){return v<0?Math.ceil(v)||0:Math.floor(v)},p:function(v){return{M:p,y:d,w:l,d:a,D:u,h:i,m:o,s:r,ms:n,Q:c}[v]||String(v||"").toLowerCase().replace(/s$/,"")},u:function(v){return v===void 0}},y="en",k={};k[y]=A;var b="$isDayjsObject",T=function(v){return v instanceof N||!(!v||!v[b])},P=function v(R,I,S){var C;if(!R)return y;if(typeof R=="string"){var E=R.toLowerCase();k[E]&&(C=E),I&&(k[E]=I,C=E);var _=R.split("-");if(!C&&_.length>1)return v(_[0])}else{var $=R.name;k[$]=R,C=$}return!S&&C&&(y=C),C||!S&&y},w=function(v,R){if(T(v))return v.clone();var I=typeof R=="object"?R:{};return I.date=v,I.args=arguments,new N(I)},M=x;M.l=P,M.i=T,M.w=function(v,R){return w(v,{locale:R.$L,utc:R.$u,x:R.$x,$offset:R.$offset})};var N=function(){function v(I){this.$L=P(I.locale,null,!0),this.parse(I),this.$x=this.$x||I.x||{},this[b]=!0}var R=v.prototype;return R.parse=function(I){this.$d=function(S){var C=S.date,E=S.utc;if(C===null)return new Date(NaN);if(M.u(C))return new Date;if(C instanceof Date)return new Date(C);if(typeof C=="string"&&!/Z$/i.test(C)){var _=C.match(g);if(_){var $=_[2]-1||0,G=(_[7]||"0").substring(0,3);return E?new Date(Date.UTC(_[1],$,_[3]||1,_[4]||0,_[5]||0,_[6]||0,G)):new Date(_[1],$,_[3]||1,_[4]||0,_[5]||0,_[6]||0,G)}}return new Date(C)}(I),this.init()},R.init=function(){var I=this.$d;this.$y=I.getFullYear(),this.$M=I.getMonth(),this.$D=I.getDate(),this.$W=I.getDay(),this.$H=I.getHours(),this.$m=I.getMinutes(),this.$s=I.getSeconds(),this.$ms=I.getMilliseconds()},R.$utils=function(){return M},R.isValid=function(){return this.$d.toString()!==m},R.isSame=function(I,S){var C=w(I);return this.startOf(S)<=C&&C<=this.endOf(S)},R.isAfter=function(I,S){return w(I)<this.startOf(S)},R.isBefore=function(I,S){return this.endOf(S)<w(I)},R.$g=function(I,S,C){return M.u(I)?this[S]:this.set(C,I)},R.unix=function(){return Math.floor(this.valueOf()/1e3)},R.valueOf=function(){return this.$d.getTime()},R.startOf=function(I,S){var C=this,E=!!M.u(S)||S,_=M.p(I),$=function(he,Y){var se=M.w(C.$u?Date.UTC(C.$y,Y,he):new Date(C.$y,Y,he),C);return E?se:se.endOf(a)},G=function(he,Y){return M.w(C.toDate()[he].apply(C.toDate("s"),(E?[0,0,0,0]:[23,59,59,999]).slice(Y)),C)},q=this.$W,V=this.$M,te=this.$D,Ce="set"+(this.$u?"UTC":"");switch(_){case d:return E?$(1,0):$(31,11);case p:return E?$(1,V):$(0,V+1);case l:var xe=this.$locale().weekStart||0,Pe=(q<xe?q+7:q)-xe;return $(E?te-Pe:te+(6-Pe),V);case a:case u:return G(Ce+"Hours",0);case i:return G(Ce+"Minutes",1);case o:return G(Ce+"Seconds",2);case r:return G(Ce+"Milliseconds",3);default:return this.clone()}},R.endOf=function(I){return this.startOf(I,!1)},R.$set=function(I,S){var C,E=M.p(I),_="set"+(this.$u?"UTC":""),$=(C={},C[a]=_+"Date",C[u]=_+"Date",C[p]=_+"Month",C[d]=_+"FullYear",C[i]=_+"Hours",C[o]=_+"Minutes",C[r]=_+"Seconds",C[n]=_+"Milliseconds",C)[E],G=E===a?this.$D+(S-this.$W):S;if(E===p||E===d){var q=this.clone().set(u,1);q.$d[$](G),q.init(),this.$d=q.set(u,Math.min(this.$D,q.daysInMonth())).$d}else $&&this.$d[$](G);return this.init(),this},R.set=function(I,S){return this.clone().$set(I,S)},R.get=function(I){return this[M.p(I)]()},R.add=function(I,S){var C,E=this;I=Number(I);var _=M.p(S),$=function(V){var te=w(E);return M.w(te.date(te.date()+Math.round(V*I)),E)};if(_===p)return this.set(p,this.$M+I);if(_===d)return this.set(d,this.$y+I);if(_===a)return $(1);if(_===l)return $(7);var G=(C={},C[o]=e,C[i]=t,C[r]=s,C)[_]||1,q=this.$d.getTime()+I*G;return M.w(q,this)},R.subtract=function(I,S){return this.add(-1*I,S)},R.format=function(I){var S=this,C=this.$locale();if(!this.isValid())return C.invalidDate||m;var E=I||"YYYY-MM-DDTHH:mm:ssZ",_=M.z(this),$=this.$H,G=this.$m,q=this.$M,V=C.weekdays,te=C.months,Ce=C.meridiem,xe=function(Y,se,ye,Te){return Y&&(Y[se]||Y(S,E))||ye[se].slice(0,Te)},Pe=function(Y){return M.s($%12||12,Y,"0")},he=Ce||function(Y,se,ye){var Te=Y<12?"AM":"PM";return ye?Te.toLowerCase():Te};return E.replace(h,function(Y,se){return se||function(ye){switch(ye){case"YY":return String(S.$y).slice(-2);case"YYYY":return M.s(S.$y,4,"0");case"M":return q+1;case"MM":return M.s(q+1,2,"0");case"MMM":return xe(C.monthsShort,q,te,3);case"MMMM":return xe(te,q);case"D":return S.$D;case"DD":return M.s(S.$D,2,"0");case"d":return String(S.$W);case"dd":return xe(C.weekdaysMin,S.$W,V,2);case"ddd":return xe(C.weekdaysShort,S.$W,V,3);case"dddd":return V[S.$W];case"H":return String($);case"HH":return M.s($,2,"0");case"h":return Pe(1);case"hh":return Pe(2);case"a":return he($,G,!0);case"A":return he($,G,!1);case"m":return String(G);case"mm":return M.s(G,2,"0");case"s":return String(S.$s);case"ss":return M.s(S.$s,2,"0");case"SSS":return M.s(S.$ms,3,"0");case"Z":return _}return null}(Y)||_.replace(":","")})},R.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},R.diff=function(I,S,C){var E,_=this,$=M.p(S),G=w(I),q=(G.utcOffset()-this.utcOffset())*e,V=this-G,te=function(){return M.m(_,G)};switch($){case d:E=te()/12;break;case p:E=te();break;case c:E=te()/3;break;case l:E=(V-q)/6048e5;break;case a:E=(V-q)/864e5;break;case i:E=V/t;break;case o:E=V/e;break;case r:E=V/s;break;default:E=V}return C?E:M.a(E)},R.daysInMonth=function(){return this.endOf(p).$D},R.$locale=function(){return k[this.$L]},R.locale=function(I,S){if(!I)return this.$L;var C=this.clone(),E=P(I,S,!0);return E&&(C.$L=E),C},R.clone=function(){return M.w(this.$d,this)},R.toDate=function(){return new Date(this.valueOf())},R.toJSON=function(){return this.isValid()?this.toISOString():null},R.toISOString=function(){return this.$d.toISOString()},R.toString=function(){return this.$d.toUTCString()},v}(),z=N.prototype;return w.prototype=z,[["$ms",n],["$s",r],["$m",o],["$H",i],["$W",a],["$M",p],["$y",d],["$D",u]].forEach(function(v){z[v[1]]=function(R){return this.$g(R,v[0],v[1])}}),w.extend=function(v,R){return v.$i||(v(R,N,w),v.$i=!0),w},w.locale=P,w.isDayjs=T,w.unix=function(v){return w(1e3*v)},w.en=k[y],w.Ls=k,w.p={},w})});var Gi=an((_o,Fo)=>{"use strict";(function(s,e){typeof _o=="object"&&typeof Fo<"u"?Fo.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_customParseFormat=e()})(_o,function(){"use strict";var s={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},e=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,t=/\d/,n=/\d\d/,r=/\d\d?/,o=/\d*[^-_:/,()\s\d]+/,i={},a=function(g){return(g=+g)+(g>68?1900:2e3)},l=function(g){return function(h){this[g]=+h}},p=[/[+-]\d\d:?(\d\d)?|Z/,function(g){(this.zone||(this.zone={})).offset=function(h){if(!h||h==="Z")return 0;var A=h.match(/([+-]|\d\d)/g),f=60*A[1]+(+A[2]||0);return f===0?0:A[0]==="+"?-f:f}(g)}],c=function(g){var h=i[g];return h&&(h.indexOf?h:h.s.concat(h.f))},d=function(g,h){var A,f=i.meridiem;if(f){for(var x=1;x<=24;x+=1)if(g.indexOf(f(x,0,h))>-1){A=x>12;break}}else A=g===(h?"pm":"PM");return A},u={A:[o,function(g){this.afternoon=d(g,!1)}],a:[o,function(g){this.afternoon=d(g,!0)}],Q:[t,function(g){this.month=3*(g-1)+1}],S:[t,function(g){this.milliseconds=100*+g}],SS:[n,function(g){this.milliseconds=10*+g}],SSS:[/\d{3}/,function(g){this.milliseconds=+g}],s:[r,l("seconds")],ss:[r,l("seconds")],m:[r,l("minutes")],mm:[r,l("minutes")],H:[r,l("hours")],h:[r,l("hours")],HH:[r,l("hours")],hh:[r,l("hours")],D:[r,l("day")],DD:[n,l("day")],Do:[o,function(g){var h=i.ordinal,A=g.match(/\d+/);if(this.day=A[0],h)for(var f=1;f<=31;f+=1)h(f).replace(/\[|\]/g,"")===g&&(this.day=f)}],w:[r,l("week")],ww:[n,l("week")],M:[r,l("month")],MM:[n,l("month")],MMM:[o,function(g){var h=c("months"),A=(c("monthsShort")||h.map(function(f){return f.slice(0,3)})).indexOf(g)+1;if(A<1)throw new Error;this.month=A%12||A}],MMMM:[o,function(g){var h=c("months").indexOf(g)+1;if(h<1)throw new Error;this.month=h%12||h}],Y:[/[+-]?\d+/,l("year")],YY:[n,function(g){this.year=a(g)}],YYYY:[/\d{4}/,l("year")],Z:p,ZZ:p};function m(g){var h,A;h=g,A=i&&i.formats;for(var f=(g=h.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(w,M,N){var z=N&&N.toUpperCase();return M||A[N]||s[N]||A[z].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(v,R,I){return R||I.slice(1)})})).match(e),x=f.length,y=0;y<x;y+=1){var k=f[y],b=u[k],T=b&&b[0],P=b&&b[1];f[y]=P?{regex:T,parser:P}:k.replace(/^\[|\]$/g,"")}return function(w){for(var M={},N=0,z=0;N<x;N+=1){var v=f[N];if(typeof v=="string")z+=v.length;else{var R=v.regex,I=v.parser,S=w.slice(z),C=R.exec(S)[0];I.call(M,C),w=w.replace(C,"")}}return function(E){var _=E.afternoon;if(_!==void 0){var $=E.hours;_?$<12&&(E.hours+=12):$===12&&(E.hours=0),delete E.afternoon}}(M),M}}return function(g,h,A){A.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var f=h.prototype,x=f.parse;f.parse=function(y){var k=y.date,b=y.utc,T=y.args;this.$u=b;var P=T[1];if(typeof P=="string"){var w=T[2]===!0,M=T[3]===!0,N=w||M,z=T[2];M&&(z=T[2]),i=this.$locale(),!w&&z&&(i=A.Ls[z]),this.$d=function(S,C,E,_){try{if(["x","X"].indexOf(C)>-1)return new Date((C==="X"?1e3:1)*S);var $=m(C)(S),G=$.year,q=$.month,V=$.day,te=$.hours,Ce=$.minutes,xe=$.seconds,Pe=$.milliseconds,he=$.zone,Y=$.week,se=new Date,ye=V||(G||q?1:se.getDate()),Te=G||se.getFullYear(),rn=0;G&&!q||(rn=q>0?q-1:se.getMonth());var on,Sr=te||0,Mr=Ce||0,Or=xe||0,kr=Pe||0;return he?new Date(Date.UTC(Te,rn,ye,Sr,Mr,Or,kr+60*he.offset*1e3)):E?new Date(Date.UTC(Te,rn,ye,Sr,Mr,Or,kr)):(on=new Date(Te,rn,ye,Sr,Mr,Or,kr),Y&&(on=_(on).week(Y).toDate()),on)}catch{return new Date("")}}(k,P,b,A),this.init(),z&&z!==!0&&(this.$L=this.locale(z).$L),N&&k!=this.format(P)&&(this.$d=new Date("")),i={}}else if(P instanceof Array)for(var v=P.length,R=1;R<=v;R+=1){T[1]=P[R-1];var I=A.apply(this,T);if(I.isValid()){this.$d=I.$d,this.$L=I.$L,this.init();break}R===v&&(this.$d=new Date(""))}else x.call(this,y)}}})});var Ui=an((Do,$o)=>{"use strict";(function(s,e){typeof Do=="object"&&typeof $o<"u"?$o.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_timezone=e()})(Do,function(){"use strict";var s={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(t,n,r){var o,i=function(c,d,u){u===void 0&&(u={});var m=new Date(c),g=function(h,A){A===void 0&&(A={});var f=A.timeZoneName||"short",x=h+"|"+f,y=e[x];return y||(y=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:h,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:f}),e[x]=y),y}(d,u);return g.formatToParts(m)},a=function(c,d){for(var u=i(c,d),m=[],g=0;g<u.length;g+=1){var h=u[g],A=h.type,f=h.value,x=s[A];x>=0&&(m[x]=parseInt(f,10))}var y=m[3],k=y===24?0:y,b=m[0]+"-"+m[1]+"-"+m[2]+" "+k+":"+m[4]+":"+m[5]+":000",T=+c;return(r.utc(b).valueOf()-(T-=T%1e3))/6e4},l=n.prototype;l.tz=function(c,d){c===void 0&&(c=o);var u,m=this.utcOffset(),g=this.toDate(),h=g.toLocaleString("en-US",{timeZone:c}),A=Math.round((g-new Date(h))/1e3/60),f=15*-Math.round(g.getTimezoneOffset()/15)-A;if(!Number(f))u=this.utcOffset(0,d);else if(u=r(h,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(f,!0),d){var x=u.utcOffset();u=u.add(m-x,"minute")}return u.$x.$timezone=c,u},l.offsetName=function(c){var d=this.$x.$timezone||r.tz.guess(),u=i(this.valueOf(),d,{timeZoneName:c}).find(function(m){return m.type.toLowerCase()==="timezonename"});return u&&u.value};var p=l.startOf;l.startOf=function(c,d){if(!this.$x||!this.$x.$timezone)return p.call(this,c,d);var u=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"),{locale:this.$L});return p.call(u,c,d).tz(this.$x.$timezone,!0)},r.tz=function(c,d,u){var m=u&&d,g=u||d||o,h=a(+r(),g);if(typeof c!="string")return r(c).tz(g);var A=function(k,b,T){var P=k-60*b*1e3,w=a(P,T);if(b===w)return[P,b];var M=a(P-=60*(w-b)*1e3,T);return w===M?[P,w]:[k-60*Math.min(w,M)*1e3,Math.max(w,M)]}(r.utc(c,m).valueOf(),h,g),f=A[0],x=A[1],y=r(f).utcOffset(x);return y.$x.$timezone=g,y},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(c){o=c}}})});var Bi=an((Lo,No)=>{"use strict";(function(s,e){typeof Lo=="object"&&typeof No<"u"?No.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_utc=e()})(Lo,function(){"use strict";var s="minute",e=/[+-]\d\d(?::?\d\d)?/g,t=/([+-]|\d\d)/g;return function(n,r,o){var i=r.prototype;o.utc=function(m){var g={date:m,utc:!0,args:arguments};return new r(g)},i.utc=function(m){var g=o(this.toDate(),{locale:this.$L,utc:!0});return m?g.add(this.utcOffset(),s):g},i.local=function(){return o(this.toDate(),{locale:this.$L,utc:!1})};var a=i.parse;i.parse=function(m){m.utc&&(this.$u=!0),this.$utils().u(m.$offset)||(this.$offset=m.$offset),a.call(this,m)};var l=i.init;i.init=function(){if(this.$u){var m=this.$d;this.$y=m.getUTCFullYear(),this.$M=m.getUTCMonth(),this.$D=m.getUTCDate(),this.$W=m.getUTCDay(),this.$H=m.getUTCHours(),this.$m=m.getUTCMinutes(),this.$s=m.getUTCSeconds(),this.$ms=m.getUTCMilliseconds()}else l.call(this)};var p=i.utcOffset;i.utcOffset=function(m,g){var h=this.$utils().u;if(h(m))return this.$u?0:h(this.$offset)?p.call(this):this.$offset;if(typeof m=="string"&&(m=function(y){y===void 0&&(y="");var k=y.match(e);if(!k)return null;var b=(""+k[0]).match(t)||["-",0,0],T=b[0],P=60*+b[1]+ +b[2];return P===0?0:T==="+"?P:-P}(m),m===null))return this;var A=Math.abs(m)<=16?60*m:m,f=this;if(g)return f.$offset=A,f.$u=m===0,f;if(m!==0){var x=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(f=this.local().add(A+x,s)).$offset=A,f.$x.$localOffset=x}else f=this.utc();return f};var c=i.format;i.format=function(m){var g=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return c.call(this,g)},i.valueOf=function(){var m=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*m},i.isUTC=function(){return!!this.$u},i.toISOString=function(){return this.toDate().toISOString()},i.toString=function(){return this.toDate().toUTCString()};var d=i.toDate;i.toDate=function(m){return m==="s"&&this.$offset?o(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():d.call(this)};var u=i.diff;i.diff=function(m,g,h){if(m&&this.$u===m.$u)return u.call(this,m,g,h);var A=this.local(),f=o(m).local();return u.call(A,f,g,h)}}})});var Ap={};Da(Ap,{AxAI:()=>jt,AxAIAnthropic:()=>He,AxAIAnthropicModel:()=>Ot,AxAIAnthropicVertexModel:()=>In,AxAIAzureOpenAI:()=>Je,AxAICohere:()=>Qe,AxAICohereEmbedModel:()=>_t,AxAICohereModel:()=>Pt,AxAIDeepSeek:()=>Xe,AxAIDeepSeekModel:()=>Ft,AxAIGoogleGemini:()=>Ze,AxAIGoogleGeminiEmbedModel:()=>kn,AxAIGoogleGeminiEmbedTypes:()=>so,AxAIGoogleGeminiModel:()=>Dt,AxAIGoogleGeminiSafetyCategory:()=>En,AxAIGoogleGeminiSafetyThreshold:()=>Pn,AxAIGrok:()=>ct,AxAIGrokEmbedModels:()=>yo,AxAIGrokModel:()=>zt,AxAIGroq:()=>tt,AxAIGroqModel:()=>$t,AxAIHuggingFace:()=>nt,AxAIHuggingFaceModel:()=>$n,AxAIMistral:()=>rt,AxAIMistralEmbedModels:()=>uo,AxAIMistralModel:()=>Lt,AxAIOllama:()=>ot,AxAIOpenAI:()=>Ye,AxAIOpenAIBase:()=>K,AxAIOpenAIEmbedModel:()=>Ke,AxAIOpenAIModel:()=>Et,AxAIOpenAIResponses:()=>it,AxAIOpenAIResponsesBase:()=>Nt,AxAIOpenAIResponsesImpl:()=>st,AxAIOpenAIResponsesModel:()=>Ve,AxAIRefusalError:()=>U,AxAIReka:()=>at,AxAIRekaModel:()=>Ut,AxAIServiceAbortedError:()=>Ge,AxAIServiceAuthenticationError:()=>we,AxAIServiceError:()=>re,AxAIServiceNetworkError:()=>fe,AxAIServiceResponseError:()=>Ie,AxAIServiceStatusError:()=>_e,AxAIServiceStreamTerminatedError:()=>ce,AxAIServiceTimeoutError:()=>Fe,AxAITogether:()=>lt,AxAIWebLLM:()=>pt,AxAIWebLLMModel:()=>qt,AxAgent:()=>nn,AxApacheTika:()=>pr,AxAssertionError:()=>Me,AxBalancer:()=>wn,AxBaseAI:()=>j,AxBaseOptimizer:()=>Ee,AxBootstrapFewShot:()=>At,AxContentProcessingError:()=>ue,AxDB:()=>Jn,AxDBBase:()=>pe,AxDBCloudflare:()=>ut,AxDBManager:()=>Qn,AxDBMemory:()=>Se,AxDBPinecone:()=>dt,AxDBWeaviate:()=>mt,AxDefaultCostTracker:()=>Zt,AxDefaultResultReranker:()=>lr,AxDockerSession:()=>Rr,AxEmbeddingAdapter:()=>Cr,AxEvalUtil:()=>ga,AxFlow:()=>tn,AxFlowDependencyAnalyzer:()=>xt,AxFlowExecutionPlanner:()=>It,AxFlowSubContextImpl:()=>Ct,AxFlowTypedSubContextImpl:()=>Ir,AxFluentFieldType:()=>Q,AxFunctionError:()=>Vt,AxFunctionProcessor:()=>Wt,AxGen:()=>ee,AxGenerateError:()=>Xt,AxHFDataLoader:()=>mr,AxInstanceRegistry:()=>ht,AxLLMRequestTypeValues:()=>qr,AxMCPClient:()=>Tr,AxMCPHTTPSSETransport:()=>wr,AxMCPStreambleHTTPTransport:()=>vr,AxMediaNotSupportedError:()=>ae,AxMemory:()=>gt,AxMiPRO:()=>xr,AxMockAIService:()=>Gn,AxMultiServiceRouter:()=>Un,AxProgram:()=>ke,AxPromptTemplate:()=>Le,AxProviderRouter:()=>zn,AxRateLimiterTokenUsage:()=>et,AxSignature:()=>H,AxSignatureBuilder:()=>Qt,AxSimpleClassifier:()=>ur,AxSimpleClassifierClass:()=>cr,AxSpanKindValues:()=>zr,AxStringUtil:()=>ar,AxTestPrompt:()=>dr,agent:()=>Ma,ai:()=>Ci,ax:()=>yr,axAIAnthropicDefaultConfig:()=>Xr,axAIAnthropicVertexDefaultConfig:()=>Xs,axAIAzureOpenAIBestConfig:()=>ni,axAIAzureOpenAICreativeConfig:()=>ei,axAIAzureOpenAIDefaultConfig:()=>eo,axAIAzureOpenAIFastConfig:()=>ti,axAICohereCreativeConfig:()=>ai,axAICohereDefaultConfig:()=>ro,axAIDeepSeekCodeConfig:()=>li,axAIDeepSeekDefaultConfig:()=>oo,axAIGoogleGeminiDefaultConfig:()=>lo,axAIGoogleGeminiDefaultCreativeConfig:()=>ci,axAIGrokBestConfig:()=>Ri,axAIGrokDefaultConfig:()=>Yn,axAIHuggingFaceCreativeConfig:()=>ui,axAIHuggingFaceDefaultConfig:()=>co,axAIMistralBestConfig:()=>di,axAIMistralDefaultConfig:()=>Nn,axAIOllamaDefaultConfig:()=>mo,axAIOllamaDefaultCreativeConfig:()=>mi,axAIOpenAIBestConfig:()=>Rn,axAIOpenAICreativeConfig:()=>Cn,axAIOpenAIDefaultConfig:()=>De,axAIOpenAIFastConfig:()=>Tn,axAIOpenAIResponsesBestConfig:()=>gi,axAIOpenAIResponsesCreativeConfig:()=>hi,axAIOpenAIResponsesDefaultConfig:()=>Gt,axAIRekaBestConfig:()=>xi,axAIRekaCreativeConfig:()=>yi,axAIRekaDefaultConfig:()=>Bt,axAIRekaFastConfig:()=>Ii,axAITogetherDefaultConfig:()=>fo,axAIWebLLMCreativeConfig:()=>bi,axAIWebLLMDefaultConfig:()=>xo,axAnalyzeChatPromptRequirements:()=>fi,axAnalyzeRequestRequirements:()=>$e,axBaseAIDefaultConfig:()=>L,axBaseAIDefaultCreativeConfig:()=>W,axCheckMetricsHealth:()=>Ti,axCreateDefaultColorLogger:()=>Br,axCreateDefaultOptimizerColorLogger:()=>Yo,axCreateDefaultOptimizerTextLogger:()=>fa,axCreateDefaultTextLogger:()=>Rs,axCreateFlowColorLogger:()=>en,axCreateFlowTextLogger:()=>ba,axDefaultFlowLogger:()=>Ra,axDefaultMetricsConfig:()=>Co,axDefaultOptimizerLogger:()=>gr,axDefaultOptimizerMetricsConfig:()=>Jo,axGetCompatibilityReport:()=>ri,axGetFormatCompatibility:()=>si,axGetMetricsConfig:()=>vi,axGetOptimizerMetricsConfig:()=>xa,axGetProvidersWithMediaSupport:()=>oi,axGlobals:()=>B,axModelInfoAnthropic:()=>kt,axModelInfoCohere:()=>Mn,axModelInfoDeepSeek:()=>On,axModelInfoGoogleGemini:()=>_n,axModelInfoGrok:()=>Wn,axModelInfoGroq:()=>Fn,axModelInfoHuggingFace:()=>Dn,axModelInfoMistral:()=>Ln,axModelInfoOpenAI:()=>We,axModelInfoOpenAIResponses:()=>bn,axModelInfoReka:()=>qn,axModelInfoTogether:()=>jn,axModelInfoWebLLM:()=>Vn,axProcessContentForProvider:()=>Bn,axRAG:()=>Oa,axScoreProvidersForRequest:()=>vn,axSelectOptimalProvider:()=>Sn,axSpanAttributes:()=>D,axSpanEvents:()=>de,axUpdateMetricsConfig:()=>wi,axUpdateOptimizerMetricsConfig:()=>Aa,axValidateChatRequestMessage:()=>Hn,axValidateChatResponseResult:()=>Kn,axValidateProviderCapabilities:()=>to,f:()=>ft,flow:()=>br,s:()=>ya});function ie({model:s,modelInfo:e,models:t}){let n=t?.find(l=>l.key===s),r=n&&"model"in n?n.model:s,o=e.find(l=>l.name===s);if(o)return o;let i=r.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),a=e.find(l=>l.name===i);return a||null}var Xo=(()=>{if(globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto;throw new Error("Web Crypto API with randomUUID support not available. Requires Node.js 16+ or modern browser.")})();function ne(){return Xo.randomUUID()}async function La(s){let e=new TextEncoder,t=typeof s=="string"?e.encode(s):s,n=await Xo.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var Er=class{data="";update(e){return this.data+=e,this}digest(e){if(e!=="hex")throw new Error("Only hex encoding is supported");let n=new TextEncoder().encode(this.data),r=0;for(let o=0;o<n.length;o++){let i=n[o];r=(r<<5)-r+i,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return La(this.data)}};function pn(s){if(s!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new Er}var cn=class extends TransformStream{buffer="";currentEvent={rawData:""};dataParser;onError;constructor(e={}){super({transform:(t,n)=>this.handleChunk(t,n),flush:t=>this.handleFlush(t)}),this.dataParser=e.dataParser||JSON.parse,this.onError=e.onError||((t,n)=>{console.warn("Failed to parse event data:",t),console.log("Raw data that failed to parse:",n)})}handleChunk(e,t){this.buffer+=e,this.processBuffer(t)}handleFlush(e){this.processBuffer(e),this.currentEvent.rawData&&this.processEvent(e)}processBuffer(e){let n=this.buffer.replace(/\r\n|\r/g,`
|
|
2
2
|
`).split(`
|
|
3
|
-
`);this.buffer=n.pop()||"";for(let
|
|
3
|
+
`);this.buffer=n.pop()||"";for(let r of n)r===""?this.processEvent(e):this.parseLine(r)}parseLine(e){if(e.startsWith(":"))return;let t=e.indexOf(":");if(t===-1){this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
|
|
4
4
|
`)?`
|
|
5
|
-
`:"")+e.trim();return}let n=e.slice(0,t).trim(),
|
|
5
|
+
`:"")+e.trim();return}let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();switch(n){case"event":this.currentEvent.event=r;break;case"data":this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
|
|
6
6
|
`)?`
|
|
7
|
-
`:"")+
|
|
8
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},
|
|
9
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}}
|
|
7
|
+
`:"")+r;break;case"id":this.currentEvent.id=r;break;case"retry":{let o=Number.parseInt(r,10);Number.isNaN(o)||(this.currentEvent.retry=o);break}}}processEvent(e){if(this.currentEvent.rawData){if(this.currentEvent.event||(this.currentEvent.event="message"),this.currentEvent.rawData.trim()==="[DONE]"){this.currentEvent={rawData:""};return}try{let t=this.dataParser(this.currentEvent.rawData);e.enqueue(t)}catch(t){this.onError(t,this.currentEvent.rawData)}this.currentEvent={rawData:""}}}};var Pr=class{decoder;constructor(){this.decoder=new TextDecoder}transform(e,t){if(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e)))throw new TypeError("Input data must be a BufferSource");let n=this.decoder.decode(e,{stream:!0});n.length!==0&&t.enqueue(n)}flush(e){let t=this.decoder.decode();t.length!==0&&e.enqueue(t)}},un=class extends TransformStream{constructor(){super(new Pr)}};var Na={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},Ga=globalThis.TextDecoderStream??un,re=class extends Error{constructor(t,n,r,o,i={}){super(t);this.url=n;this.requestBody=r;this.responseBody=o;this.name=this.constructor.name,this.timestamp=new Date().toISOString(),this.errorId=ne(),this.context=i,this.stack=this.toString()}timestamp;errorId;context;toString(){return[`${this.name}: ${this.message}`,`URL: ${this.url}`,`Request Body: ${JSON.stringify(this.requestBody,null,2)}`,`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
|
|
8
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},_e=class extends re{constructor(t,n,r,o,i,a){super(`HTTP ${t} - ${n}`,r,o,{httpStatus:t,httpStatusText:n,responseBody:i,...a});this.status=t;this.statusText=n;this.name=this.constructor.name}},fe=class extends re{constructor(t,n,r,o,i){super(`Network Error: ${t.message}`,n,r,o,{originalErrorName:t.name,originalErrorStack:t.stack,...i});this.originalError=t;this.name=this.constructor.name,this.stack=t.stack}},Ie=class extends re{constructor(e,t,n,r){super(e,t,n,void 0,r),this.name=this.constructor.name}},ce=class extends re{constructor(t,n,r,o){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...o});this.lastChunk=r;this.name=this.constructor.name}},Fe=class extends re{constructor(e,t,n,r){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r}),this.name=this.constructor.name}},Ge=class extends re{constructor(e,t,n,r){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r}),this.name=this.constructor.name}},we=class extends re{constructor(e,t,n,r){super("Authentication failed",e,t,n,r),this.name=this.constructor.name}},U=class extends Error{constructor(t,n,r){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=r;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=ne()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Refusal: ${this.refusalMessage}`,this.model?`Model: ${this.model}`:"",this.requestId?`Request ID: ${this.requestId}`:"",`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].filter(Boolean).join(`
|
|
9
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},ae=class extends Error{constructor(t,n,r=!1){super(`${t} not supported by ${n}${r?" (fallback available)":""}`);this.mediaType=t;this.provider=n;this.fallbackAvailable=r;this.name="AxMediaNotSupportedError",this.timestamp=new Date().toISOString(),this.errorId=ne()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Media Type: ${this.mediaType}`,`Provider: ${this.provider}`,`Fallback Available: ${this.fallbackAvailable}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
|
|
10
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},ue=class extends Error{constructor(t,n,r){super(`Failed to process ${n} during ${r}: ${t.message}`);this.originalError=t;this.contentType=n;this.processingStep=r;this.name="AxContentProcessingError",this.timestamp=new Date().toISOString(),this.errorId=ne()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Content Type: ${this.contentType}`,`Processing Step: ${this.processingStep}`,`Original Error: ${this.originalError.message}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
|
|
11
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function Zo(s){try{return s.headers.get("content-type")?.includes("application/json")?await s.json():await s.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function es(s,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**s)*(.75+Math.random()*.5)}function Ua(){return{startTime:Date.now(),retryCount:0}}function ts(s){s.retryCount++,s.lastRetryTime=Date.now()}function ns(s,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:s instanceof fe&&!(s instanceof we)}var oe=async(s,e)=>{if(s.localCall)return await s.localCall(e,s.stream);if(!s.url)throw new Error("API URL is required when localCall is not provided");let t={...Na,...s.retry},n=s.timeout,r=Ua(),o,i=new URL(s.url),a=`${[i.pathname,s.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${i.search}`,l=new URL(a,i);if(s.corsProxy){let d=l.href;l=new URL(`${s.corsProxy}?url=${encodeURIComponent(d)}`)}let p=ne();if(s.validateRequest&&!await s.validateRequest(e))throw new Ie("Invalid request data",l.href,e,{validation:"request"});s.span?.setAttributes({"http.request.method":s.put?"PUT":"POST","url.full":l.href,"request.id":p,"request.startTime":r.startTime});let c=0;for(;;){let d=new AbortController;if(s.abortSignal){if(s.abortSignal.aborted)throw new Ge(l.href,s.abortSignal.reason,e,{metrics:r});let u=()=>{d.abort(s.abortSignal.reason||"User aborted request")};s.abortSignal.addEventListener("abort",u,{once:!0});let m=d.abort.bind(d);d.abort=g=>{s.abortSignal.removeEventListener("abort",u),m(g)}}n&&(o=setTimeout(()=>{d.abort("Request timeout")},n));try{let u=await(s.fetch??fetch)(l,{method:s.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":c.toString(),...s.headers},body:JSON.stringify(e),signal:d.signal});if(o&&clearTimeout(o),u.status===401||u.status===403){let x=await Zo(u);throw new we(l.href,e,x,{metrics:r})}if(u.status>=400&&ns(new Error,u.status,c,t)){let x=es(c,t);c++,ts(r),s.span?.addEvent("retry",{attempt:c,delay:x,status:u.status,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(y=>setTimeout(y,x));continue}if(u.status>=400){let x=await Zo(u);throw new _e(u.status,u.statusText,l.href,e,x,{metrics:r})}if(!s.stream){let x=await u.json();if(s.validateResponse&&!await s.validateResponse(x))throw new Ie("Invalid response data",l.href,e,{validation:"response"});return s.span?.setAttributes({"response.time":Date.now()-r.startTime,"response.retries":r.retryCount}),x}if(!u.body)throw new Ie("Response body is null",l.href,e,{metrics:r});let m,g=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(x){let y=u.body.getReader(),k=new TextDecoder,b="";async function T(){try{for(;;){let{done:P,value:w}=await y.read();if(P){f=!0,x.close();break}b+=k.decode(w,{stream:!0});let M=b.split(`
|
|
10
12
|
|
|
11
|
-
`);b=M.pop()||"";for(let N of M){if(!N.trim())continue;let
|
|
12
|
-
`),v="",R="message";for(let I of H)I.startsWith("data: ")?v=I.slice(6):I.startsWith("event: ")&&(R=I.slice(7));if(v){if(v==="[DONE]"){x.close();return}try{let I=JSON.parse(v);m=I,g++,o.streamChunks=g,o.lastChunkTime=Date.now(),console.log("!!!!>>>>>>>>>parsed",I),x.enqueue(I),s.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-o.startTime,"response.retries":o.retryCount,"sse.event.type":R})}catch(I){s.debug&&console.warn("Skipping non-JSON SSE data:",v,I)}}}}}catch(_){let w=_,M={...o,streamDuration:Date.now()-o.startTime};w.name==="AbortError"||w.message?.includes("aborted")?x.error(new le(l.href,e,m,{streamMetrics:M})):x.error(new me(w,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:M}))}finally{y.releaseLock()}}T()}});let f=new TransformStream({transform(x,y){m=x,g++,o.streamChunks=g,o.lastChunkTime=Date.now(),y.enqueue(x),s.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-o.startTime,"response.retries":o.retryCount})}}),A=!1;return new ReadableStream({start(x){let y=u.body.pipeThrough(new xa).pipeThrough(new Xt).pipeThrough(f).getReader();async function O(){try{for(;;){let{done:b,value:T}=await y.read();if(b){A||(A=!0,x.close());break}if(A)break;x.enqueue(T)}}catch(b){let T=b,_={...o,streamDuration:Date.now()-o.startTime};throw T.name==="AbortError"||T.message?.includes("aborted")?x.error(new le(l.href,e,m,{streamMetrics:_})):T instanceof TypeError&&T.message.includes("cancelled")?x.error(new le(l.href,e,m,{streamMetrics:_,cancelReason:"Stream cancelled by client"})):x.error(new me(T,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:_})),T}finally{clearTimeout(r),y.releaseLock()}}O()},cancel(){A=!0}})}catch(u){if(u instanceof Error&&u.name==="AbortError")throw s.abortSignal?.aborted?new De(l.href,s.abortSignal.reason,e,{metrics:o}):new Ee(l.href,n,e,{metrics:o});if(s.span?.isRecording()&&(s.span.recordException(u),s.span.setAttributes({"error.time":Date.now()-o.startTime,"error.retries":o.retryCount})),u instanceof me&&qr(u,void 0,p,t)){let m=$r(p,t);p++,Br(o),s.span?.addEvent("retry",{attempt:p,delay:m,error:u.message,"metrics.startTime":o.startTime,"metrics.retryCount":o.retryCount,"metrics.lastRetryTime":o.lastRetryTime}),await new Promise(g=>setTimeout(g,m));continue}throw u instanceof ee&&(u.context.metrics=o),u}finally{r!==void 0&&clearTimeout(r)}}};var zr=typeof globalThis=="object"?globalThis:global;var fe="1.9.0";var jr=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ia(s){var e=new Set([s]),t=new Set,n=s.match(jr);if(!n)return function(){return!1};var o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(o.prerelease!=null)return function(l){return l===s};function r(a){return t.add(a),!1}function i(a){return e.add(a),!0}return function(l){if(e.has(l))return!0;if(t.has(l))return!1;var c=l.match(jr);if(!c)return r(l);var p={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return p.prerelease!=null||o.major!==p.major?r(l):o.major===0?o.minor===p.minor&&o.patch<=p.patch?i(l):r(l):o.minor<=p.minor?i(l):r(l)}}var Hr=Ia(fe);var ba=fe.split(".")[0],yt=Symbol.for("opentelemetry.js.api."+ba),It=zr;function Ge(s,e,t,n){var o;n===void 0&&(n=!1);var r=It[yt]=(o=It[yt])!==null&&o!==void 0?o:{version:fe};if(!n&&r[s]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+s);return t.error(i.stack||i.message),!1}if(r.version!==fe){var i=new Error("@opentelemetry/api: Registration of version v"+r.version+" for "+s+" does not match previously registered API v"+fe);return t.error(i.stack||i.message),!1}return r[s]=e,t.debug("@opentelemetry/api: Registered a global for "+s+" v"+fe+"."),!0}function xe(s){var e,t,n=(e=It[yt])===null||e===void 0?void 0:e.version;if(!(!n||!Hr(n)))return(t=It[yt])===null||t===void 0?void 0:t[s]}function Le(s,e){e.debug("@opentelemetry/api: Unregistering a global for "+s+" v"+fe+".");var t=It[yt];t&&delete t[s]}var Ra=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),o,r=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)r.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return r},Ca=function(s,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,r;n<o;n++)(r||!(n in e))&&(r||(r=Array.prototype.slice.call(e,0,n)),r[n]=e[n]);return s.concat(r||Array.prototype.slice.call(e))},Kr=function(){function s(e){this._namespace=e.namespace||"DiagComponentLogger"}return s.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return bt("debug",this._namespace,e)},s.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return bt("error",this._namespace,e)},s.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return bt("info",this._namespace,e)},s.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return bt("warn",this._namespace,e)},s.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return bt("verbose",this._namespace,e)},s}();function bt(s,e,t){var n=xe("diag");if(n)return t.unshift(e),n[s].apply(n,Ca([],Ra(t),!1))}var Z;(function(s){s[s.NONE=0]="NONE",s[s.ERROR=30]="ERROR",s[s.WARN=50]="WARN",s[s.INFO=60]="INFO",s[s.DEBUG=70]="DEBUG",s[s.VERBOSE=80]="VERBOSE",s[s.ALL=9999]="ALL"})(Z||(Z={}));function Vr(s,e){s<Z.NONE?s=Z.NONE:s>Z.ALL&&(s=Z.ALL),e=e||{};function t(n,o){var r=e[n];return typeof r=="function"&&s>=o?r.bind(e):function(){}}return{error:t("error",Z.ERROR),warn:t("warn",Z.WARN),info:t("info",Z.INFO),debug:t("debug",Z.DEBUG),verbose:t("verbose",Z.VERBOSE)}}var Ta=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),o,r=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)r.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return r},wa=function(s,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,r;n<o;n++)(r||!(n in e))&&(r||(r=Array.prototype.slice.call(e,0,n)),r[n]=e[n]);return s.concat(r||Array.prototype.slice.call(e))},va="diag",Ne=function(){function s(){function e(o){return function(){for(var r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];var a=xe("diag");if(a)return a[o].apply(a,wa([],Ta(r),!1))}}var t=this,n=function(o,r){var i,a,l;if(r===void 0&&(r={logLevel:Z.INFO}),o===t){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof r=="number"&&(r={logLevel:r});var p=xe("diag"),d=Vr((a=r.logLevel)!==null&&a!==void 0?a:Z.INFO,o);if(p&&!r.suppressOverrideMessage){var u=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";p.warn("Current logger will be overwritten from "+u),d.warn("Current logger will overwrite one already registered from "+u)}return Ge("diag",d,t,!0)};t.setLogger=n,t.disable=function(){Le(va,t)},t.createComponentLogger=function(o){return new Kr(o)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return s.instance=function(){return this._instance||(this._instance=new s),this._instance},s}();function Wr(s){return Symbol.for(s)}var Sa=function(){function s(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,o){var r=new s(t._currentContext);return r._currentContext.set(n,o),r},t.deleteValue=function(n){var o=new s(t._currentContext);return o._currentContext.delete(n),o}}return s}(),Yr=new Sa;var Ma=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),o,r=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)r.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return r},Oa=function(s,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,r;n<o;n++)(r||!(n in e))&&(r||(r=Array.prototype.slice.call(e,0,n)),r[n]=e[n]);return s.concat(r||Array.prototype.slice.call(e))},Jr=function(){function s(){}return s.prototype.active=function(){return Yr},s.prototype.with=function(e,t,n){for(var o=[],r=3;r<arguments.length;r++)o[r-3]=arguments[r];return t.call.apply(t,Oa([n],Ma(o),!1))},s.prototype.bind=function(e,t){return t},s.prototype.enable=function(){return this},s.prototype.disable=function(){return this},s}();var ka=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),o,r=[],i;try{for(;(e===void 0||e-- >0)&&!(o=n.next()).done;)r.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return r},Ea=function(s,e,t){if(t||arguments.length===2)for(var n=0,o=e.length,r;n<o;n++)(r||!(n in e))&&(r||(r=Array.prototype.slice.call(e,0,n)),r[n]=e[n]);return s.concat(r||Array.prototype.slice.call(e))},Io="context",_a=new Jr,Ue=function(){function s(){}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalContextManager=function(e){return Ge(Io,e,Ne.instance())},s.prototype.active=function(){return this._getContextManager().active()},s.prototype.with=function(e,t,n){for(var o,r=[],i=3;i<arguments.length;i++)r[i-3]=arguments[i];return(o=this._getContextManager()).with.apply(o,Ea([e,t,n],ka(r),!1))},s.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},s.prototype._getContextManager=function(){return xe(Io)||_a},s.prototype.disable=function(){this._getContextManager().disable(),Le(Io,Ne.instance())},s}();var tn;(function(s){s[s.NONE=0]="NONE",s[s.SAMPLED=1]="SAMPLED"})(tn||(tn={}));var bo="0000000000000000",Ro="00000000000000000000000000000000",Qr={traceId:Ro,spanId:bo,traceFlags:tn.NONE};var Re=function(){function s(e){e===void 0&&(e=Qr),this._spanContext=e}return s.prototype.spanContext=function(){return this._spanContext},s.prototype.setAttribute=function(e,t){return this},s.prototype.setAttributes=function(e){return this},s.prototype.addEvent=function(e,t){return this},s.prototype.addLink=function(e){return this},s.prototype.addLinks=function(e){return this},s.prototype.setStatus=function(e){return this},s.prototype.updateName=function(e){return this},s.prototype.end=function(e){},s.prototype.isRecording=function(){return!1},s.prototype.recordException=function(e,t){},s}();var Co=Wr("OpenTelemetry Context Key SPAN");function nn(s){return s.getValue(Co)||void 0}function Zr(){return nn(Ue.getInstance().active())}function Rt(s,e){return s.setValue(Co,e)}function Xr(s){return s.deleteValue(Co)}function es(s,e){return Rt(s,new Re(e))}function on(s){var e;return(e=nn(s))===null||e===void 0?void 0:e.spanContext()}var Pa=/^([0-9a-f]{32})$/i,Fa=/^[0-9a-f]{16}$/i;function Da(s){return Pa.test(s)&&s!==Ro}function Ga(s){return Fa.test(s)&&s!==bo}function rn(s){return Da(s.traceId)&&Ga(s.spanId)}function ts(s){return new Re(s)}var To=Ue.getInstance(),sn=function(){function s(){}return s.prototype.startSpan=function(e,t,n){n===void 0&&(n=To.active());var o=!!t?.root;if(o)return new Re;var r=n&&on(n);return La(r)&&rn(r)?new Re(r):new Re},s.prototype.startActiveSpan=function(e,t,n,o){var r,i,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(r=t,a=n):(r=t,i=n,a=o);var l=i??To.active(),c=this.startSpan(e,r,l),p=Rt(l,c);return To.with(p,a,void 0,c)}},s}();function La(s){return typeof s=="object"&&typeof s.spanId=="string"&&typeof s.traceId=="string"&&typeof s.traceFlags=="number"}var Na=new sn,ns=function(){function s(e,t,n,o){this._provider=e,this.name=t,this.version=n,this.options=o}return s.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},s.prototype.startActiveSpan=function(e,t,n,o){var r=this._getTracer();return Reflect.apply(r.startActiveSpan,r,arguments)},s.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):Na},s}();var os=function(){function s(){}return s.prototype.getTracer=function(e,t,n){return new sn},s}();var Ua=new os,wo=function(){function s(){}return s.prototype.getTracer=function(e,t,n){var o;return(o=this.getDelegateTracer(e,t,n))!==null&&o!==void 0?o:new ns(this,e,t,n)},s.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Ua},s.prototype.setDelegate=function(e){this._delegate=e},s.prototype.getDelegateTracer=function(e,t,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(e,t,n)},s}();var ie;(function(s){s[s.INTERNAL=0]="INTERNAL",s[s.SERVER=1]="SERVER",s[s.CLIENT=2]="CLIENT",s[s.PRODUCER=3]="PRODUCER",s[s.CONSUMER=4]="CONSUMER"})(ie||(ie={}));var $e=Ue.getInstance();var vo="trace",rs=function(){function s(){this._proxyTracerProvider=new wo,this.wrapSpanContext=ts,this.isSpanContextValid=rn,this.deleteSpan=Xr,this.getSpan=nn,this.getActiveSpan=Zr,this.getSpanContext=on,this.setSpan=Rt,this.setSpanContext=es}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalTracerProvider=function(e){var t=Ge(vo,this._proxyTracerProvider,Ne.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},s.prototype.getTracerProvider=function(){return xe(vo)||this._proxyTracerProvider},s.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},s.prototype.disable=function(){Le(vo,Ne.instance()),this._proxyTracerProvider=new wo},s}();var So=rs.getInstance();var B={signatureStrict:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,functionResultFormatter:s=>typeof s=="string"?s:s==null?"":JSON.stringify(s,null,2)};var ne=class{ANSI_WHITE_BRIGHT="\x1B[97m";ANSI_GREEN_BRIGHT="\x1B[92m";ANSI_BLUE_BRIGHT="\x1B[94m";ANSI_RED_BRIGHT="\x1B[91m";ANSI_YELLOW="\x1B[93m";ANSI_RED="\x1B[91m";ANSI_RESET="\x1B[0m";ANSI_ORANGE="\x1B[38;5;208m";ANSI_WHITE="\x1B[37m";ANSI_CYAN_BRIGHT="\x1B[96m";ANSI_MAGENTA_BRIGHT="\x1B[95m";ANSI_GRAY="\x1B[90m";ANSI_GREEN="\x1B[32m";ANSI_CYAN="\x1B[36m";ANSI_MAGENTA="\x1B[35m";ANSI_BLUE="\x1B[34m";ANSI_YELLOW_DIM="\x1B[33m";colorize(e,t){return`${t}${e}${this.ANSI_RESET}`}whiteBright(e){return this.colorize(e,this.ANSI_WHITE_BRIGHT)}greenBright(e){return this.colorize(e,this.ANSI_GREEN_BRIGHT)}blueBright(e){return this.colorize(e,this.ANSI_BLUE_BRIGHT)}redBright(e){return this.colorize(e,this.ANSI_RED_BRIGHT)}white(e){return this.colorize(e,this.ANSI_WHITE)}yellow(e){return this.colorize(e,this.ANSI_YELLOW)}red(e){return this.colorize(e,this.ANSI_RED)}orange(e){return this.colorize(e,this.ANSI_ORANGE)}cyanBright(e){return this.colorize(e,this.ANSI_CYAN_BRIGHT)}magentaBright(e){return this.colorize(e,this.ANSI_MAGENTA_BRIGHT)}gray(e){return this.colorize(e,this.ANSI_GRAY)}green(e){return this.colorize(e,this.ANSI_GREEN)}cyan(e){return this.colorize(e,this.ANSI_CYAN)}magenta(e){return this.colorize(e,this.ANSI_MAGENTA)}blue(e){return this.colorize(e,this.ANSI_BLUE)}yellowDim(e){return this.colorize(e,this.ANSI_YELLOW_DIM)}};var Ip=new ne,ss=s=>{console.log(s)},is=(s,e,t)=>{let n=(o,r)=>t&&r&&r in t?t[r](o):o;switch(s.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
|
|
13
|
+
`);b=M.pop()||"";for(let N of M){if(!N.trim())continue;let z=N.split(`
|
|
14
|
+
`),v="",R="message";for(let I of z)I.startsWith("data: ")?v=I.slice(6):I.startsWith("event: ")&&(R=I.slice(7));if(v){if(v==="[DONE]"){x.close();return}try{let I=JSON.parse(v);m=I,g++,r.streamChunks=g,r.lastChunkTime=Date.now(),console.log("!!!!>>>>>>>>>parsed",I),x.enqueue(I),s.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":R})}catch(I){s.debug&&console.warn("Skipping non-JSON SSE data:",v,I)}}}}}catch(P){let w=P,M={...r,streamDuration:Date.now()-r.startTime};w.name==="AbortError"||w.message?.includes("aborted")?x.error(new ce(l.href,e,m,{streamMetrics:M})):x.error(new fe(w,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:M}))}finally{y.releaseLock()}}T()}});let A=new TransformStream({transform(x,y){m=x,g++,r.streamChunks=g,r.lastChunkTime=Date.now(),y.enqueue(x),s.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),f=!1;return new ReadableStream({start(x){let y=u.body.pipeThrough(new Ga).pipeThrough(new cn).pipeThrough(A).getReader();async function k(){try{for(;;){let{done:b,value:T}=await y.read();if(b){f||(f=!0,x.close());break}if(f)break;x.enqueue(T)}}catch(b){let T=b,P={...r,streamDuration:Date.now()-r.startTime};throw T.name==="AbortError"||T.message?.includes("aborted")?x.error(new ce(l.href,e,m,{streamMetrics:P})):T instanceof TypeError&&T.message.includes("cancelled")?x.error(new ce(l.href,e,m,{streamMetrics:P,cancelReason:"Stream cancelled by client"})):x.error(new fe(T,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:P})),T}finally{o&&clearTimeout(o),y.releaseLock()}}k()},cancel(){f=!0}})}catch(u){if(u instanceof Error&&u.name==="AbortError")throw s.abortSignal?.aborted?new Ge(l.href,s.abortSignal.reason,e,{metrics:r}):new Fe(l.href,n||0,e,{metrics:r});if(s.span?.isRecording()&&(s.span.recordException(u),s.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),u instanceof fe&&ns(u,void 0,c,t)){let m=es(c,t);c++,ts(r),s.span?.addEvent("retry",{attempt:c,delay:m,error:u.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(g=>setTimeout(g,m));continue}throw u instanceof re&&(u.context.metrics=r),u}finally{o!==void 0&&clearTimeout(o)}}};var rs=typeof globalThis=="object"?globalThis:global;var be="1.9.0";var os=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ba(s){var e=new Set([s]),t=new Set,n=s.match(os);if(!n)return function(){return!1};var r={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(r.prerelease!=null)return function(l){return l===s};function o(a){return t.add(a),!1}function i(a){return e.add(a),!0}return function(l){if(e.has(l))return!0;if(t.has(l))return!1;var p=l.match(os);if(!p)return o(l);var c={major:+p[1],minor:+p[2],patch:+p[3],prerelease:p[4]};return c.prerelease!=null||r.major!==c.major?o(l):r.major===0?r.minor===c.minor&&r.patch<=c.patch?i(l):o(l):r.minor<=c.minor?i(l):o(l)}}var ss=Ba(be);var qa=be.split(".")[0],Tt=Symbol.for("opentelemetry.js.api."+qa),wt=rs;function Ue(s,e,t,n){var r;n===void 0&&(n=!1);var o=wt[Tt]=(r=wt[Tt])!==null&&r!==void 0?r:{version:be};if(!n&&o[s]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+s);return t.error(i.stack||i.message),!1}if(o.version!==be){var i=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+s+" does not match previously registered API v"+be);return t.error(i.stack||i.message),!1}return o[s]=e,t.debug("@opentelemetry/api: Registered a global for "+s+" v"+be+"."),!0}function Re(s){var e,t,n=(e=wt[Tt])===null||e===void 0?void 0:e.version;if(!(!n||!ss(n)))return(t=wt[Tt])===null||t===void 0?void 0:t[s]}function Be(s,e){e.debug("@opentelemetry/api: Unregistering a global for "+s+" v"+be+".");var t=wt[Tt];t&&delete t[s]}var za=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},ja=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},is=function(){function s(e){this._namespace=e.namespace||"DiagComponentLogger"}return s.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return vt("debug",this._namespace,e)},s.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return vt("error",this._namespace,e)},s.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return vt("info",this._namespace,e)},s.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return vt("warn",this._namespace,e)},s.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return vt("verbose",this._namespace,e)},s}();function vt(s,e,t){var n=Re("diag");if(n)return t.unshift(e),n[s].apply(n,ja([],za(t),!1))}var X;(function(s){s[s.NONE=0]="NONE",s[s.ERROR=30]="ERROR",s[s.WARN=50]="WARN",s[s.INFO=60]="INFO",s[s.DEBUG=70]="DEBUG",s[s.VERBOSE=80]="VERBOSE",s[s.ALL=9999]="ALL"})(X||(X={}));function as(s,e){s<X.NONE?s=X.NONE:s>X.ALL&&(s=X.ALL),e=e||{};function t(n,r){var o=e[n];return typeof o=="function"&&s>=r?o.bind(e):function(){}}return{error:t("error",X.ERROR),warn:t("warn",X.WARN),info:t("info",X.INFO),debug:t("debug",X.DEBUG),verbose:t("verbose",X.VERBOSE)}}var Ha=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Ka=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},Va="diag",qe=function(){function s(){function e(r){return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];var a=Re("diag");if(a)return a[r].apply(a,Ka([],Ha(o),!1))}}var t=this,n=function(r,o){var i,a,l;if(o===void 0&&(o={logLevel:X.INFO}),r===t){var p=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((i=p.stack)!==null&&i!==void 0?i:p.message),!1}typeof o=="number"&&(o={logLevel:o});var c=Re("diag"),d=as((a=o.logLevel)!==null&&a!==void 0?a:X.INFO,r);if(c&&!o.suppressOverrideMessage){var u=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn("Current logger will be overwritten from "+u),d.warn("Current logger will overwrite one already registered from "+u)}return Ue("diag",d,t,!0)};t.setLogger=n,t.disable=function(){Be(Va,t)},t.createComponentLogger=function(r){return new is(r)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return s.instance=function(){return this._instance||(this._instance=new s),this._instance},s}();function ls(s){return Symbol.for(s)}var Wa=function(){function s(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,r){var o=new s(t._currentContext);return o._currentContext.set(n,r),o},t.deleteValue=function(n){var r=new s(t._currentContext);return r._currentContext.delete(n),r}}return s}(),ps=new Wa;var Ya=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Ja=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},cs=function(){function s(){}return s.prototype.active=function(){return ps},s.prototype.with=function(e,t,n){for(var r=[],o=3;o<arguments.length;o++)r[o-3]=arguments[o];return t.call.apply(t,Ja([n],Ya(r),!1))},s.prototype.bind=function(e,t){return t},s.prototype.enable=function(){return this},s.prototype.disable=function(){return this},s}();var Qa=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Xa=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},_r="context",Za=new cs,ze=function(){function s(){}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalContextManager=function(e){return Ue(_r,e,qe.instance())},s.prototype.active=function(){return this._getContextManager().active()},s.prototype.with=function(e,t,n){for(var r,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return(r=this._getContextManager()).with.apply(r,Xa([e,t,n],Qa(o),!1))},s.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},s.prototype._getContextManager=function(){return Re(_r)||Za},s.prototype.disable=function(){this._getContextManager().disable(),Be(_r,qe.instance())},s}();var dn;(function(s){s[s.NONE=0]="NONE",s[s.SAMPLED=1]="SAMPLED"})(dn||(dn={}));var Fr="0000000000000000",Dr="00000000000000000000000000000000",us={traceId:Dr,spanId:Fr,traceFlags:dn.NONE};var ve=function(){function s(e){e===void 0&&(e=us),this._spanContext=e}return s.prototype.spanContext=function(){return this._spanContext},s.prototype.setAttribute=function(e,t){return this},s.prototype.setAttributes=function(e){return this},s.prototype.addEvent=function(e,t){return this},s.prototype.addLink=function(e){return this},s.prototype.addLinks=function(e){return this},s.prototype.setStatus=function(e){return this},s.prototype.updateName=function(e){return this},s.prototype.end=function(e){},s.prototype.isRecording=function(){return!1},s.prototype.recordException=function(e,t){},s}();var $r=ls("OpenTelemetry Context Key SPAN");function mn(s){return s.getValue($r)||void 0}function ds(){return mn(ze.getInstance().active())}function St(s,e){return s.setValue($r,e)}function ms(s){return s.deleteValue($r)}function gs(s,e){return St(s,new ve(e))}function gn(s){var e;return(e=mn(s))===null||e===void 0?void 0:e.spanContext()}var el=/^([0-9a-f]{32})$/i,tl=/^[0-9a-f]{16}$/i;function nl(s){return el.test(s)&&s!==Dr}function rl(s){return tl.test(s)&&s!==Fr}function hn(s){return nl(s.traceId)&&rl(s.spanId)}function hs(s){return new ve(s)}var Lr=ze.getInstance(),fn=function(){function s(){}return s.prototype.startSpan=function(e,t,n){n===void 0&&(n=Lr.active());var r=!!t?.root;if(r)return new ve;var o=n&&gn(n);return ol(o)&&hn(o)?new ve(o):new ve},s.prototype.startActiveSpan=function(e,t,n,r){var o,i,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(o=t,a=n):(o=t,i=n,a=r);var l=i??Lr.active(),p=this.startSpan(e,o,l),c=St(l,p);return Lr.with(c,a,void 0,p)}},s}();function ol(s){return typeof s=="object"&&typeof s.spanId=="string"&&typeof s.traceId=="string"&&typeof s.traceFlags=="number"}var sl=new fn,fs=function(){function s(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return s.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},s.prototype.startActiveSpan=function(e,t,n,r){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},s.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):sl},s}();var As=function(){function s(){}return s.prototype.getTracer=function(e,t,n){return new fn},s}();var il=new As,Nr=function(){function s(){}return s.prototype.getTracer=function(e,t,n){var r;return(r=this.getDelegateTracer(e,t,n))!==null&&r!==void 0?r:new fs(this,e,t,n)},s.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:il},s.prototype.setDelegate=function(e){this._delegate=e},s.prototype.getDelegateTracer=function(e,t,n){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(e,t,n)},s}();var le;(function(s){s[s.INTERNAL=0]="INTERNAL",s[s.SERVER=1]="SERVER",s[s.CLIENT=2]="CLIENT",s[s.PRODUCER=3]="PRODUCER",s[s.CONSUMER=4]="CONSUMER"})(le||(le={}));var je=ze.getInstance();var Gr="trace",xs=function(){function s(){this._proxyTracerProvider=new Nr,this.wrapSpanContext=hs,this.isSpanContextValid=hn,this.deleteSpan=ms,this.getSpan=mn,this.getActiveSpan=ds,this.getSpanContext=gn,this.setSpan=St,this.setSpanContext=gs}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalTracerProvider=function(e){var t=Ue(Gr,this._proxyTracerProvider,qe.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},s.prototype.getTracerProvider=function(){return Re(Gr)||this._proxyTracerProvider},s.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},s.prototype.disable=function(){Be(Gr,qe.instance()),this._proxyTracerProvider=new Nr},s}();var Ur=xs.getInstance();var B={signatureStrict:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,functionResultFormatter:s=>typeof s=="string"?s:s==null?"":JSON.stringify(s,null,2)};var Z=class{ANSI_WHITE_BRIGHT="\x1B[97m";ANSI_GREEN_BRIGHT="\x1B[92m";ANSI_BLUE_BRIGHT="\x1B[94m";ANSI_RED_BRIGHT="\x1B[91m";ANSI_YELLOW="\x1B[93m";ANSI_RED="\x1B[91m";ANSI_RESET="\x1B[0m";ANSI_ORANGE="\x1B[38;5;208m";ANSI_WHITE="\x1B[37m";ANSI_CYAN_BRIGHT="\x1B[96m";ANSI_MAGENTA_BRIGHT="\x1B[95m";ANSI_GRAY="\x1B[90m";ANSI_GREEN="\x1B[32m";ANSI_CYAN="\x1B[36m";ANSI_MAGENTA="\x1B[35m";ANSI_BLUE="\x1B[34m";ANSI_YELLOW_DIM="\x1B[33m";colorize(e,t){return`${t}${e}${this.ANSI_RESET}`}whiteBright(e){return this.colorize(e,this.ANSI_WHITE_BRIGHT)}greenBright(e){return this.colorize(e,this.ANSI_GREEN_BRIGHT)}blueBright(e){return this.colorize(e,this.ANSI_BLUE_BRIGHT)}redBright(e){return this.colorize(e,this.ANSI_RED_BRIGHT)}white(e){return this.colorize(e,this.ANSI_WHITE)}yellow(e){return this.colorize(e,this.ANSI_YELLOW)}red(e){return this.colorize(e,this.ANSI_RED)}orange(e){return this.colorize(e,this.ANSI_ORANGE)}cyanBright(e){return this.colorize(e,this.ANSI_CYAN_BRIGHT)}magentaBright(e){return this.colorize(e,this.ANSI_MAGENTA_BRIGHT)}gray(e){return this.colorize(e,this.ANSI_GRAY)}green(e){return this.colorize(e,this.ANSI_GREEN)}cyan(e){return this.colorize(e,this.ANSI_CYAN)}magenta(e){return this.colorize(e,this.ANSI_MAGENTA)}blue(e){return this.colorize(e,this.ANSI_BLUE)}yellowDim(e){return this.colorize(e,this.ANSI_YELLOW_DIM)}};var Bc=new Z,ys=s=>{console.log(s)},Is=(s,e,t)=>{let n=(r,o)=>t&&o&&o in t?t[o](r):r;switch(s.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
|
|
13
15
|
${n(s.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
|
|
14
|
-
${n(s.result??"[No result]","yellowDim")}`;case"user":{let
|
|
15
|
-
`;if(typeof s.content=="string")return
|
|
16
|
-
`)}case"assistant":{let
|
|
17
|
-
`;return s.content&&(
|
|
18
|
-
`),s.functionCalls&&s.functionCalls.length>0&&(
|
|
19
|
-
`,s.functionCalls.forEach((i,a)=>{let l=typeof i.function.params=="string"?i.function.params:JSON.stringify(i.function.params,null,2);
|
|
20
|
-
`)}),
|
|
21
|
-
`),!s.content&&(!s.functionCalls||s.functionCalls.length===0)&&(
|
|
22
|
-
${n(JSON.stringify(s),"gray")}`}},
|
|
23
|
-
`);return n=>{let
|
|
24
|
-
${e.blueBright(`[ CHAT REQUEST Step ${
|
|
16
|
+
${n(s.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","greenBright")}
|
|
17
|
+
`;if(typeof s.content=="string")return r+n(s.content,"green");let o=s.content.map(i=>{if(i.type==="text")return n(i.text,"green");if(i.type==="image"){let a=e?"[Image]":`[Image: ${i.image}]`;return n(a,"green")}if(i.type==="audio"){let a=e?"[Audio]":`[Audio: ${i.data}]`;return n(a,"green")}return n("[Unknown content type]","gray")});return r+o.join(`
|
|
18
|
+
`)}case"assistant":{let r=n("[ ASSISTANT","cyanBright");s.name&&(r+=` ${s.name}`),r+=" ]";let o=`${r}
|
|
19
|
+
`;return s.content&&(o+=`${n(s.content,"cyan")}
|
|
20
|
+
`),s.functionCalls&&s.functionCalls.length>0&&(o+=`${n("[ FUNCTION CALLS ]","yellow")}
|
|
21
|
+
`,s.functionCalls.forEach((i,a)=>{let l=typeof i.function.params=="string"?i.function.params:JSON.stringify(i.function.params,null,2);o+=n(`${a+1}. ${i.function.name}(${l}) [id: ${i.id}]`,"yellowDim"),a<(s.functionCalls?.length??0)-1&&(o+=`
|
|
22
|
+
`)}),o+=`
|
|
23
|
+
`),!s.content&&(!s.functionCalls||s.functionCalls.length===0)&&(o+=n("[No content]","gray")),o}default:return`${n("[ UNKNOWN ]","redBright")}
|
|
24
|
+
${n(JSON.stringify(s),"gray")}`}},Br=(s=ys)=>{let e=new Z,t=e.gray(`${"\u2500".repeat(60)}
|
|
25
|
+
`);return n=>{let r=n,o="";switch(r.name){case"ChatRequestChatPrompt":o=`
|
|
26
|
+
${e.blueBright(`[ CHAT REQUEST Step ${r.step} ]`)}
|
|
25
27
|
${t}
|
|
26
|
-
`,
|
|
28
|
+
`,r.value.forEach((i,a)=>{o+=Is(i,void 0,e),a<r.value.length-1&&(o+=`
|
|
27
29
|
${t}
|
|
28
|
-
`)}),
|
|
29
|
-
${t}`;break;case"FunctionResults":
|
|
30
|
+
`)}),o+=`
|
|
31
|
+
${t}`;break;case"FunctionResults":o=`
|
|
30
32
|
${e.yellow("[ FUNCTION RESULTS ]")}
|
|
31
|
-
`,
|
|
32
|
-
Result: ${i.result}`),a<
|
|
33
|
+
`,r.value.forEach((i,a)=>{o+=e.yellowDim(`Function: ${i.functionId}
|
|
34
|
+
Result: ${i.result}`),a<r.value.length-1&&(o+=`
|
|
33
35
|
${t}
|
|
34
|
-
`)});break;case"ChatResponseResults":
|
|
36
|
+
`)});break;case"ChatResponseResults":o=`
|
|
35
37
|
${e.cyanBright("[ CHAT RESPONSE ]")}
|
|
36
|
-
`,
|
|
38
|
+
`,r.value.forEach((i,a)=>{o+=e.cyan(i.content||"[No content]"),a<r.value.length-1&&(o+=`
|
|
37
39
|
${t}
|
|
38
|
-
`)});break;case"ChatResponseStreamingResult":{let i=
|
|
40
|
+
`)});break;case"ChatResponseStreamingResult":{let i=r.value.delta||r.value.content||"";o=e.cyanBright(i);return}case"ChatResponseStreamingDoneResult":{o=`
|
|
39
41
|
${e.cyanBright("[ CHAT RESPONSE ]")}
|
|
40
42
|
${t}
|
|
41
|
-
`,
|
|
42
|
-
${e.redBright(`[ FUNCTION ERROR #${
|
|
43
|
+
`,r.value.content&&(o+=e.cyanBright(r.value.content)),r.value.functionCalls&&(o+=e.cyanBright(JSON.stringify(r.value.functionCalls,null,2)));break}case"FunctionError":o=`
|
|
44
|
+
${e.redBright(`[ FUNCTION ERROR #${r.index} ]`)}
|
|
43
45
|
${t}
|
|
44
|
-
${e.white(
|
|
45
|
-
${e.red(`Error: ${
|
|
46
|
-
${e.redBright(`[ VALIDATION ERROR #${
|
|
46
|
+
${e.white(r.fixingInstructions)}
|
|
47
|
+
${e.red(`Error: ${r.error}`)}`;break;case"ValidationError":o=`
|
|
48
|
+
${e.redBright(`[ VALIDATION ERROR #${r.index} ]`)}
|
|
47
49
|
${t}
|
|
48
|
-
${e.white(
|
|
49
|
-
${e.red(`Error: ${
|
|
50
|
-
${e.redBright(`[ ASSERTION ERROR #${
|
|
50
|
+
${e.white(r.fixingInstructions)}
|
|
51
|
+
${e.red(`Error: ${r.error}`)}`;break;case"AssertionError":o=`
|
|
52
|
+
${e.redBright(`[ ASSERTION ERROR #${r.index} ]`)}
|
|
51
53
|
${t}
|
|
52
|
-
${e.white(
|
|
53
|
-
${e.red(`Error: ${
|
|
54
|
+
${e.white(r.fixingInstructions)}
|
|
55
|
+
${e.red(`Error: ${r.error}`)}`;break;case"ResultPickerUsed":o=`${e.greenBright("[ RESULT PICKER ]")}
|
|
54
56
|
${t}
|
|
55
|
-
${e.green(`Selected sample ${
|
|
57
|
+
${e.green(`Selected sample ${r.selectedIndex+1} of ${r.sampleCount} (${r.latency.toFixed(2)}ms)`)}`;break;case"Notification":o=`${e.gray(`[ NOTIFICATION ${r.id} ]`)}
|
|
56
58
|
${t}
|
|
57
|
-
${e.white(
|
|
59
|
+
${e.white(r.value)}`;break;case"EmbedRequest":o=`${e.orange(`[ EMBED REQUEST ${r.embedModel} ]`)}
|
|
58
60
|
${t}
|
|
59
|
-
`,
|
|
61
|
+
`,r.value.forEach((i,a)=>{o+=e.white(`Text ${a+1}: ${i.substring(0,100)}${i.length>100?"...":""}`),a<r.value.length-1&&(o+=`
|
|
60
62
|
${t}
|
|
61
|
-
`)});break;case"EmbedResponse":
|
|
63
|
+
`)});break;case"EmbedResponse":o=`${e.orange(`[ EMBED RESPONSE (${r.totalEmbeddings} embeddings) ]`)}
|
|
62
64
|
${t}
|
|
63
|
-
`,
|
|
65
|
+
`,r.value.forEach((i,a)=>{o+=e.white(`Embedding ${a+1}: [${i.sample.join(", ")}${i.truncated?", ...":""}] (length: ${i.length})`),a<r.value.length-1&&(o+=`
|
|
64
66
|
${t}
|
|
65
|
-
`)});break;default:
|
|
67
|
+
`)});break;default:o=e.gray(JSON.stringify(r,null,2))}s(o)}},bs=Br(),Rs=(s=ys)=>{let e="\u2500".repeat(60);return t=>{let n=t,r="";switch(n.name){case"ChatRequestChatPrompt":r=`
|
|
66
68
|
[ CHAT REQUEST Step ${n.step} ]
|
|
67
69
|
${e}
|
|
68
|
-
`,n.value.forEach((
|
|
70
|
+
`,n.value.forEach((o,i)=>{r+=Is(o),i<n.value.length-1&&(r+=`
|
|
69
71
|
${e}
|
|
70
|
-
`)}),
|
|
71
|
-
${e}`;break;case"FunctionResults":
|
|
72
|
+
`)}),r+=`
|
|
73
|
+
${e}`;break;case"FunctionResults":r=`
|
|
72
74
|
[ FUNCTION RESULTS ]
|
|
73
75
|
${e}
|
|
74
|
-
`,n.value.forEach((
|
|
75
|
-
Result: ${
|
|
76
|
+
`,n.value.forEach((o,i)=>{r+=`Function: ${o.functionId}
|
|
77
|
+
Result: ${o.result}`,i<n.value.length-1&&(r+=`
|
|
76
78
|
${e}
|
|
77
|
-
`)});break;case"ChatResponseResults":
|
|
79
|
+
`)});break;case"ChatResponseResults":r=`
|
|
78
80
|
[ CHAT RESPONSE ]
|
|
79
|
-
`,n.value.forEach((
|
|
81
|
+
`,n.value.forEach((o,i)=>{r+=o.content||"[No content]",i<n.value.length-1&&(r+=`
|
|
80
82
|
${e}
|
|
81
|
-
`)});break;case"ChatResponseStreamingResult":return;case"ChatResponseStreamingDoneResult":{
|
|
83
|
+
`)});break;case"ChatResponseStreamingResult":return;case"ChatResponseStreamingDoneResult":{r=`
|
|
82
84
|
[ CHAT RESPONSE ]
|
|
83
|
-
`,n.value.content&&(
|
|
85
|
+
`,n.value.content&&(r+=n.value.content),n.value.functionCalls&&(r+=JSON.stringify(n.value.functionCalls,null,2));break}case"FunctionError":r=`
|
|
84
86
|
[ FUNCTION ERROR #${n.index} ]
|
|
85
87
|
${e}
|
|
86
88
|
${n.fixingInstructions}
|
|
87
|
-
Error: ${n.error}`;break;case"ValidationError":
|
|
89
|
+
Error: ${n.error}`;break;case"ValidationError":r=`
|
|
88
90
|
[ VALIDATION ERROR #${n.index} ]
|
|
89
91
|
${e}
|
|
90
92
|
${n.fixingInstructions}
|
|
91
|
-
Error: ${n.error}`;break;case"AssertionError":
|
|
93
|
+
Error: ${n.error}`;break;case"AssertionError":r=`
|
|
92
94
|
[ ASSERTION ERROR #${n.index} ]
|
|
93
95
|
${e}
|
|
94
96
|
${n.fixingInstructions}
|
|
95
|
-
Error: ${n.error}`;break;case"ResultPickerUsed":
|
|
97
|
+
Error: ${n.error}`;break;case"ResultPickerUsed":r=`[ RESULT PICKER ]
|
|
96
98
|
${e}
|
|
97
|
-
Selected sample ${n.selectedIndex+1} of ${n.sampleCount} (${n.latency.toFixed(2)}ms)`;break;case"Notification":
|
|
99
|
+
Selected sample ${n.selectedIndex+1} of ${n.sampleCount} (${n.latency.toFixed(2)}ms)`;break;case"Notification":r=`[ NOTIFICATION ${n.id} ]
|
|
98
100
|
${e}
|
|
99
|
-
${n.value}`;break;case"EmbedRequest":
|
|
101
|
+
${n.value}`;break;case"EmbedRequest":r=`[ EMBED REQUEST ${n.embedModel} ]
|
|
100
102
|
${e}
|
|
101
|
-
`,n.value.forEach((
|
|
103
|
+
`,n.value.forEach((o,i)=>{r+=`Text ${i+1}: ${o.substring(0,100)}${o.length>100?"...":""}`,i<n.value.length-1&&(r+=`
|
|
102
104
|
${e}
|
|
103
|
-
`)});break;case"EmbedResponse":
|
|
105
|
+
`)});break;case"EmbedResponse":r=`[ EMBED RESPONSE (${n.totalEmbeddings} embeddings) ]
|
|
104
106
|
${e}
|
|
105
|
-
`,n.value.forEach((
|
|
107
|
+
`,n.value.forEach((o,i)=>{r+=`Embedding ${i+1}: [${o.sample.join(", ")}${o.truncated?", ...":""}] (length: ${o.length})`,i<n.value.length-1&&(r+=`
|
|
106
108
|
${e}
|
|
107
|
-
`)});break;default:o=JSON.stringify(n,null,2)}s(o)}};var D={LLM_SYSTEM:"gen_ai.system",LLM_OPERATION_NAME:"gen_ai.operation.name",LLM_REQUEST_MODEL:"gen_ai.request.model",LLM_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",LLM_REQUEST_TEMPERATURE:"gen_ai.request.temperature",LLM_REQUEST_TOP_K:"gen_ai.request.top_k",LLM_REQUEST_FREQUENCY_PENALTY:"gen_ai.request.frequency_penalty",LLM_REQUEST_PRESENCE_PENALTY:"gen_ai.request.presence_penalty",LLM_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",LLM_REQUEST_LLM_IS_STREAMING:"gen_ai.request.llm_is_streaming",LLM_REQUEST_TOP_P:"gen_ai.request.top_p",LLM_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",LLM_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",LLM_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",LLM_USAGE_THOUGHTS_TOKENS:"gen_ai.usage.thoughts_tokens",DB_SYSTEM:"db.system",DB_TABLE:"db.table",DB_NAMESPACE:"db.namespace",DB_ID:"db.id",DB_QUERY_TEXT:"db.query.text",DB_VECTOR:"db.vector",DB_OPERATION_NAME:"db.operation.name",DB_VECTOR_QUERY_TOP_K:"db.vector.query.top_k",DB_QUERY_EMBEDDINGS:"db.query.embeddings",DB_QUERY_RESULT:"db.query.result",DB_QUERY_EMBEDDINGS_VECTOR:"db.query.embeddings.vector",DB_QUERY_RESULT_ID:"db.query.result.id",DB_QUERY_RESULT_SCORE:"db.query.result.score",DB_QUERY_RESULT_DISTANCE:"db.query.result.distance",DB_QUERY_RESULT_METADATA:"db.query.result.metadata",DB_QUERY_RESULT_VECTOR:"db.query.result.vector",DB_QUERY_RESULT_DOCUMENT:"db.query.result.document"},ce={GEN_AI_USER_MESSAGE:"gen_ai.user.message",GEN_AI_SYSTEM_MESSAGE:"gen_ai.system.message",GEN_AI_ASSISTANT_MESSAGE:"gen_ai.assistant.message",GEN_AI_TOOL_MESSAGE:"gen_ai.tool.message",GEN_AI_CHOICE:"gen_ai.choice",GEN_AI_USAGE:"gen_ai.usage"},Oo=(o=>(o.COMPLETION="completion",o.CHAT="chat",o.RERANK="rerank",o.UNKNOWN="unknown",o))(Oo||{}),ko=(r=>(r.WORKFLOW="workflow",r.TASK="task",r.AGENT="agent",r.TOOL="tool",r.UNKNOWN="unknown",r))(ko||{});var Eo=class{buffer;doneCallback;transformFn;constructor(e,t){this.transformFn=e,this.doneCallback=t,this.buffer=t?[]:void 0}async transform(e,t){let n=this.transformFn(e);n&&(t.enqueue(n),this.buffer?.push(n))}async flush(e){await this.doneCallback?.(this.buffer??[]),e.terminate()}},an=class extends TransformStream{constructor(e,t){super(new Eo(e,t))}};function ln(s,e){for(let t of e){let n=s.find(o=>o.id===t.id);n?(typeof t.function.name=="string"&&t.function.name.length>0&&(n.function.name+=t.function.name),typeof t.function.params=="string"&&t.function.params.length>0&&(n.function.params+=t.function.params),typeof t.function.params=="object"&&(n.function.params=t.function.params)):s.push(t)}}var cs=(s,e,t,n)=>{let o=n?s.filter(i=>i.role!=="system"):[...s];t({name:"ChatRequestChatPrompt",step:e,value:o})};var ps=(s,e)=>{if(!s.results)return;let t={name:"ChatResponseResults",value:s.results};e(t)},us=(s,e,t)=>{t({name:"ChatResponseStreamingResult",index:e,value:s})};function ds(s,e){let t=new Map;for(let n of s)for(let o of n.results){if(!o)continue;let r=t.get(o.index);r?(o.content&&(r.content=(r.content??"")+o.content),o.thought&&(r.thought=(r.thought??"")+o.thought),o.finishReason&&(r.finishReason=o.finishReason),o.functionCalls&&(r.functionCalls?ln(r.functionCalls,structuredClone(o.functionCalls)):r.functionCalls=structuredClone(o.functionCalls))):(r=structuredClone(o),t.set(o.index,r))}for(let n of t.values()){let o={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(o)}}var ms=(s,e)=>{e({name:"FunctionResults",value:s})},gs=(s,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:s})},hs=(s,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:s})},As=(s,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:s})},fs=(s,e,t)=>{t({name:"RefusalError",index:e,error:s})};var xs=(s,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:s})},ys=(s,e)=>{let t=s.slice(0,3).map(o=>({length:o.length,sample:o.slice(0,5),truncated:o.length>5})),n={name:"EmbedResponse",totalEmbeddings:s.length,value:t};e(n)},Is=(s,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:s,selectedIndex:e,latency:t})};var _o=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let o=String(n);e[t]=o.length>100?o.substring(0,100):o}return e},cn,bs=s=>{if(cn)return cn;if(s)return cn=$a(s),cn};var $a=s=>({latencyHistogram:s.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:s.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:s.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:s.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:s.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:s.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:s.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:s.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:s.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:s.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:s.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:s.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:s.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:s.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:s.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:s.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:s.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:s.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:s.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:s.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:s.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:s.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:s.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:s.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"})}),Rs=(s,e,t,n,o)=>{try{if(s.latencyHistogram){let r=_o({operation:e,ai_service:n,...o?{model:o}:{}});s.latencyHistogram.record(t,r)}}catch(r){console.warn("Failed to record latency metric:",r)}},Cs=(s,e,t,n,o,r,i)=>{let a={operation:e,ai_service:r,...i?{model:i}:{}};s.meanLatencyGauge&&s.meanLatencyGauge.record(t,a),s.p95LatencyGauge&&s.p95LatencyGauge.record(n,a),s.p99LatencyGauge&&s.p99LatencyGauge.record(o,a)},Ts=(s,e,t,n)=>{try{if(s.errorCounter){let o=_o({operation:e,ai_service:t,...n?{model:n}:{}});s.errorCounter.add(1,o)}}catch(o){console.warn("Failed to record error metric:",o)}},ws=(s,e,t,n,o)=>{s.errorRateGauge&&s.errorRateGauge.record(t*100,{operation:e,ai_service:n,...o?{model:o}:{}})},vs=(s,e,t,n)=>{s.requestCounter&&s.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Ct=(s,e,t,n,o)=>{try{let r=_o({ai_service:n,...o?{model:o}:{}});s.tokenCounter&&s.tokenCounter.add(t,{token_type:e,...r}),e==="input"&&s.inputTokenCounter&&s.inputTokenCounter.add(t,r),e==="output"&&s.outputTokenCounter&&s.outputTokenCounter.add(t,r)}catch(r){console.warn("Failed to record token metric:",r)}},Ss=(s,e,t,n,o)=>{t&&s.streamingRequestsCounter&&s.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...o?{model:o}:{}})},Ms=(s,e,t,n,o)=>{let r={function_name:e,...n?{ai_service:n}:{},...o?{model:o}:{}};s.functionCallsCounter&&s.functionCallsCounter.add(1,r),t&&s.functionCallLatencyHistogram&&s.functionCallLatencyHistogram.record(t,r)},Po=(s,e,t,n,o)=>{s.requestSizeHistogram&&s.requestSizeHistogram.record(t,{operation:e,ai_service:n,...o?{model:o}:{}})},Fo=(s,e,t,n,o)=>{s.responseSizeHistogram&&s.responseSizeHistogram.record(t,{operation:e,ai_service:n,...o?{model:o}:{}})},Os=(s,e,t,n,o)=>{let r={...n?{ai_service:n}:{},...o?{model:o}:{}};e!==void 0&&s.temperatureGauge&&s.temperatureGauge.record(e,r),t!==void 0&&s.maxTokensGauge&&s.maxTokensGauge.record(t,r)},Do=(s,e,t,n,o)=>{s.estimatedCostCounter&&s.estimatedCostCounter.add(t,{operation:e,ai_service:n,...o?{model:o}:{}})},ks=(s,e,t,n)=>{s.promptLengthHistogram&&s.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},Es=(s,e,t,n)=>{s.contextWindowUsageGauge&&s.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},_s=(s,e,t,n)=>{s.timeoutsCounter&&s.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Ps=(s,e,t,n)=>{s.abortsCounter&&s.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Fs=(s,e,t,n)=>{s.thinkingBudgetUsageCounter&&s.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},Ds=(s,e,t,n,o)=>{(e||t)&&s.multimodalRequestsCounter&&s.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...o?{model:o}:{}})};var L=()=>structuredClone({temperature:0,topK:40,topP:.9}),Y=()=>structuredClone({temperature:.4,topP:.7,frequencyPenalty:.2}),K=class{constructor(e,{name:t,apiURL:n,headers:o,modelInfo:r,defaults:i,options:a={},supportFor:l,models:c}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=o,this.supportFor=l,this.tracer=a.tracer??B.tracer,this.meter=a.meter??B.meter,this.modelInfo=r,this.models=c,this.id=se();let p=this.getModel(i.model)??i.model,d=this.getEmbedModel(i.embedModel)??i.embedModel;if(this.defaults={model:p,embedModel:d},!i.model||typeof i.model!="string"||i.model==="")throw new Error("No model defined");this.setOptions(a),c&&qa(c)}debug=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=B.logger??as;corsProxy;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getMetricsInstruments(){return bs(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}setOptions(e){this.debug=e.debug??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??B.tracer,this.meter=e.meter??B.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??B.logger??this.logger,this.corsProxy=e.corsProxy}getOptions(){return{debug:this.debug,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger,corsProxy:this.corsProxy}}getLogger(){return this.logger}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((r,i)=>r-i),o=Math.ceil(t/100*n.length)-1;return n[o]??0}updateLatencyMetrics(e,t){let n=this.metrics.latency[e];n.samples.push(t),n.samples.length>1e3&&n.samples.shift(),n.mean=n.samples.reduce((r,i)=>r+i,0)/n.samples.length,n.p95=this.calculatePercentile(n.samples,95),n.p99=this.calculatePercentile(n.samples,99);let o=this.getMetricsInstruments();if(o){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Rs(o,e,t,this.name,r),Cs(o,e,n.mean,n.p95,n.p99,this.name,r)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let o=this.getMetricsInstruments();if(o){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;vs(o,e,this.name,r),t&&Ts(o,e,this.name,r),ws(o,e,n.rate,this.name,r)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&e?.tokens){let{promptTokens:n,completionTokens:o,totalTokens:r,thoughtsTokens:i}=e.tokens;n&&Ct(t,"input",n,this.name,e.model),o&&Ct(t,"output",o,this.name,e.model),r&&Ct(t,"total",r,this.name,e.model),i&&Ct(t,"thoughts",i,this.name,e.model)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let o of e.chatPrompt)if(o.role==="user"&&Array.isArray(o.content))for(let r of o.content)r.type==="image"?t=!0:r.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}calculatePromptLength(e){let t=0;if(e.chatPrompt&&Array.isArray(e.chatPrompt))for(let n of e.chatPrompt)if(n.role==="system"||n.role==="assistant")n.content&&(t+=n.content.length);else if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let o of n.content)o.type==="text"&&(t+=o.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!t?.tokens?.promptTokens)return 0;let n=this.modelInfo.find(o=>o.name===e);return n?.contextWindow?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:o=0,completionTokens:r=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return o*i/1e6+r*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:o=0,completionTokens:r=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return o*i/1e6+r*a/1e6}recordFunctionCallMetrics(e,t){let n=this.getMetricsInstruments();if(!(!n||!e))for(let o of e)o&&typeof o=="object"&&"function"in o&&o.function&&typeof o.function=="object"&&"name"in o.function&&Ms(n,o.function.name,void 0,this.name,t)}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;_s(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ps(t,e,this.name,n)}}recordChatMetrics(e,t,n){let o=this.getMetricsInstruments();if(!o)return;let r=this.lastUsedChatModel,i=this.lastUsedModelConfig,a=i?.stream??!1;Ss(o,"chat",a,this.name,r);let{hasImages:l,hasAudio:c}=this.detectMultimodalContent(e);Ds(o,l,c,this.name,r);let p=this.calculatePromptLength(e);ks(o,p,this.name,r),Os(o,i?.temperature,i?.maxTokens,this.name,r),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&Fs(o,this.modelUsage.tokens.thoughtsTokens,this.name,r);let d=this.calculateRequestSize(e);if(Po(o,"chat",d,this.name,r),n&&!a){let u=n,m=this.calculateResponseSize(u);if(Fo(o,"chat",m,this.name,r),u.results)for(let f of u.results)f.functionCalls&&this.recordFunctionCallMetrics(f.functionCalls,this.lastUsedChatModel);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,u.modelUsage);g>0&&Es(o,g,this.name,r);let h=this.estimateCost(this.lastUsedChatModel,u.modelUsage);h>0&&Do(o,"chat",h,this.name,r)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let o=this.lastUsedEmbedModel,r=this.calculateRequestSize(e);Po(n,"embed",r,this.name,o);let i=this.calculateResponseSize(t);Fo(n,"embed",i,this.name,o);let a=this.estimateCostByName(o,t.modelUsage);a>0&&Do(n,"embed",a,this.name,o)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),o=!1,r;try{return r=await this._chat1(e,t),r}catch(i){throw o=!0,i instanceof Error&&(i.message.includes("timeout")||i.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(i.message.includes("abort")||i.name==="AbortError")&&this.recordAbortMetric("chat")),i}finally{let i=performance.now()-n;this.updateLatencyMetrics("chat",i),this.updateErrorMetrics("chat",o),o||this.recordChatMetrics(e,t,r)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;e.chatPrompt&&Array.isArray(e.chatPrompt)&&Go(e.chatPrompt);let o={...this.aiImpl.getModelConfig(),...e.modelConfig};if(t?.thinkingTokenBudget&&!this.getFeatures(n).hasThinkingBudget)throw new Error(`Model ${n} does not support thinkingTokenBudget.`);if(t?.showThoughts&&!this.getFeatures(n).hasShowThoughts)throw new Error(`Model ${n} does not support showThoughts.`);if(this.modelInfo.find(a=>a.name===n)?.isExpensive&&t?.useExpensiveModel!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return o.stream=(t?.stream!==void 0?t.stream:o.stream)??!0,this.getFeatures(n).streaming||(o.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:ie.SERVER,attributes:{[D.LLM_SYSTEM]:this.name,[D.LLM_OPERATION_NAME]:"chat",[D.LLM_REQUEST_MODEL]:n,[D.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[D.LLM_REQUEST_TEMPERATURE]:o.temperature,[D.LLM_REQUEST_TOP_P]:o.topP??"Not set",[D.LLM_REQUEST_TOP_K]:o.topK??"Not set",[D.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[D.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[D.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[D.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??$e.active(),async a=>await this._chat2(n,o,e,t,a)):await this._chat2(n,o,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,o,r){if(!this.aiImpl.createChatReq)throw new Error("generateChatReq not implemented");let i=o?.debug??this.debug,a;n.functions&&n.functions.length>0&&(a=n.functions.map(m=>this.cleanupFunctionSchema(m)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t;let c=async()=>{let[m,g]=await this.aiImpl.createChatReq(l,o);return r?.isRecording()&&Ba(n,r,this.excludeContentFromTrace),await te({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),stream:t.stream,timeout:this.timeout,debug:i,fetch:this.fetch,span:r,abortSignal:o?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},g)};i&&cs(l.chatPrompt,o?.stepIndex??0,o?.logger??this.logger,o?.debugHideSystemPrompt);let p=o?.rateLimiter??this.rt,d=p?await p(c,{modelUsage:this.modelUsage}):await c();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("generateChatStreamResp not implemented");let m=this.aiImpl.createChatStreamResp.bind(this),g=x=>y=>{let O=m(y,x);if(O.sessionId=o?.sessionId,!O.modelUsage){let b=this.aiImpl.getTokenUsage();b&&(O.modelUsage={ai:this.name,model:e,tokens:b})}if(this.modelUsage=O.modelUsage,this.recordTokenUsage(O.modelUsage),r?.isRecording()&&Gs(O,r,this.excludeContentFromTrace),i)for(let b of O.results)us(b,b.index,o?.logger??this.logger);return O},h=async x=>{r?.isRecording()&&r.end(),i&&ds(x,o?.logger??this.logger)};if(typeof window<"u"){let x=d,y={},O=[];return new ReadableStream({start(b){let T=x.getReader();async function _(){try{for(;;){let{done:w,value:M}=await T.read();if(w){h&&await h(O),b.close();break}let N=g(y)(M);N&&(O.push(N),b.enqueue(N))}}catch(w){b.error(w)}finally{T.releaseLock()}}_()}})}return d.pipeThrough(new an(g({}),h))}if(!this.aiImpl.createChatResp)throw new Error("generateChatResp not implemented");let u=this.aiImpl.createChatResp(d);if(u.sessionId=o?.sessionId,!u.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(u.modelUsage={ai:this.name,model:e,tokens:m})}return u.modelUsage&&(this.modelUsage=u.modelUsage,this.recordTokenUsage(u.modelUsage)),r?.isRecording()&&(Gs(u,r,this.excludeContentFromTrace),r.end()),i&&ps(u,o?.logger??this.logger),u}async embed(e,t){let n=performance.now(),o=!1,r;try{return r=await this._embed1(e,t),r}catch(i){throw o=!0,i instanceof Error&&(i.message.includes("timeout")||i.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(i.message.includes("abort")||i.name==="AbortError")&&this.recordAbortMetric("embed")),i}finally{let i=performance.now()-n;this.updateLatencyMetrics("embed",i),this.updateErrorMetrics("embed",o),!o&&r&&this.recordEmbedMetrics(e,r)}}async _embed1(e,t){let n=this.getEmbedModel(e.embedModel)??e.embedModel??this.defaults.embedModel;if(!n)throw new Error("No embed model defined");return this.tracer&&await this.tracer?.startActiveSpan("AI Embed Request",{kind:ie.SERVER,attributes:{[D.LLM_SYSTEM]:this.name,[D.LLM_OPERATION_NAME]:"embeddings",[D.LLM_REQUEST_MODEL]:n}},t?.traceContext??$e.active(),async o=>{try{return await this._embed2(n,e,t,o)}finally{o.end()}}),this._embed2(n,e,t)}async _embed2(e,t,n,o){if(!this.aiImpl.createEmbedReq)throw new Error("generateEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("generateEmbedResp not implemented");let r=this.aiImpl.createEmbedReq,i=n?.debug??this.debug,a={...t,embedModel:e};this.lastUsedEmbedModel=e,i&&xs(a.texts??[],e,n?.logger??this.logger);let l=async()=>{let[d,u]=await r(a);return await te({name:d.name,url:this.apiURL,localCall:d.localCall,headers:await this.buildHeaders(d.headers),debug:i,fetch:this.fetch,timeout:this.timeout,span:o,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},u)},c=this.rt?await this.rt(l,{modelUsage:this.embedModelUsage}):await l(),p=this.aiImpl.createEmbedResp?.(c);if(p.sessionId=n?.sessionId,!p.modelUsage){let d=this.aiImpl.getTokenUsage();d&&(p.modelUsage={ai:this.name,model:e,tokens:d})}return this.embedModelUsage=p.modelUsage,this.recordTokenUsage(p.modelUsage),o?.isRecording()&&p.modelUsage?.tokens&&o.addEvent(ce.GEN_AI_USAGE,{[D.LLM_USAGE_INPUT_TOKENS]:p.modelUsage.tokens.promptTokens,[D.LLM_USAGE_OUTPUT_TOKENS]:p.modelUsage.tokens.completionTokens??0,[D.LLM_USAGE_TOTAL_TOKENS]:p.modelUsage.tokens.totalTokens}),i&&ys(p.embeddings,n?.logger??this.logger),o?.end(),p}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}};function Ba(s,e,t){let n=[];if(s.chatPrompt&&Array.isArray(s.chatPrompt)&&s.chatPrompt.length>0)for(let r of s.chatPrompt)switch(r.role){case"system":if(r.content){let i={};t||(i.content=r.content),e.addEvent(ce.GEN_AI_SYSTEM_MESSAGE,i)}break;case"user":if(typeof r.content=="string")n.push(r.content);else if(Array.isArray(r.content))for(let i of r.content)i.type==="text"&&n.push(i.text);break;case"assistant":{let i=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(i&&i.length>0){let a={function_calls:JSON.stringify(i,null,2)};!t&&r.content&&(a.content=r.content),e.addEvent(ce.GEN_AI_ASSISTANT_MESSAGE,a)}else if(r.content){let a={};t||(a.content=r.content),e.addEvent(ce.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:r.functionId};t||(i.content=r.result),e.addEvent(ce.GEN_AI_TOOL_MESSAGE,i);break}}let o={};t||(o.content=n.join(`
|
|
108
|
-
`)),e.addEvent(ce.GEN_AI_USER_MESSAGE,o)}function Gs(s,e,t){if(s.modelUsage?.tokens){let n=s.modelUsage.tokens.thoughtsTokens?{[D.LLM_USAGE_THOUGHTS_TOKENS]:s.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(ce.GEN_AI_USAGE,{[D.LLM_USAGE_INPUT_TOKENS]:s.modelUsage.tokens.promptTokens,[D.LLM_USAGE_OUTPUT_TOKENS]:s.modelUsage.tokens.completionTokens??0,[D.LLM_USAGE_TOTAL_TOKENS]:s.modelUsage.tokens.totalTokens,...n})}if(s.results)for(let n=0;n<s.results.length;n++){let o=s.results[n];if(!o||!o.content&&!o.thought&&!o.functionCalls?.length&&!o.finishReason)continue;let r=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),i={};r&&r.length>0?(t||(i.content=o.content),i.tool_calls=r):t||(i.content=o.content??""),e.addEvent(ce.GEN_AI_CHOICE,{finish_reason:o.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function Go(s){for(let e=0;e<s.length;e++){let t=s[e];if(!t||typeof t!="object")throw new Error(`AxMessage array validation failed: Item at index ${e} is not a valid message object`);if("content"in t&&typeof t.content=="string"&&t.content.trim()==="")throw new Error(`AxMessage array validation failed: Item at index ${e} has empty content`)}}function qa(s){let e=new Set;for(let t of s){if(e.has(t.key))throw new Error(`Duplicate model key detected: "${t.key}". Each model key must be unique.`);e.add(t.key)}}var Tt=(p=>(p.Claude4Opus="claude-opus-4-20250514",p.Claude4Sonnet="claude-sonnet-4-20250514",p.Claude37Sonnet="claude-3-7-sonnet-latest",p.Claude35Sonnet="claude-3-5-sonnet-latest",p.Claude35Haiku="claude-3-5-haiku-latest",p.Claude3Opus="claude-3-opus-latest",p.Claude3Sonnet="claude-3-sonnet-20240229",p.Claude3Haiku="claude-3-haiku-20240307",p.Claude21="claude-2.1",p.ClaudeInstant12="claude-instant-1.2",p))(Tt||{}),pn=(i=>(i.Claude37Sonnet="claude-3-7-sonnet",i.Claude35Haiku="claude-3-5-haiku",i.Claude35Sonnet="claude-3-5-sonnet",i.Claude35SonnetV2="claude-3-5-sonnet-v2",i.Claude3Haiku="claude-3-haiku",i.Claude3Opus="claude-3-opus",i))(pn||{});var wt=[{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var No=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...L()}),Ns=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...L()}),Lo=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,o=e.modelConfig?.stream??this.config.stream,r;this.isVertex?r={name:o?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:r={name:"/messages"};let i;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":i={tool_choice:{type:"auto"}};break;case"required":i={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)i={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.filter(y=>y.role==="system").map(y=>({type:"text",text:y.content,...y.cache?{cache:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(y=>y.role!=="system"),c=za(l),p=e.functions?.map(y=>({name:y.name,description:y.description,input_schema:y.parameters})),d=e.modelConfig?.maxTokens??this.config.maxTokens,u=e.modelConfig?.stopSequences??this.config.stopSequences,m=e.modelConfig?.temperature??this.config.temperature,g=e.modelConfig?.topP??this.config.topP,h=e.modelConfig?.topK??this.config.topK,f=e.modelConfig?.n??this.config.n;if(f&&f>1)throw new Error("Anthropic does not support sampling (n > 1)");let A;if(this.config.thinking?.budget_tokens&&(A=this.config.thinking),t?.thinkingTokenBudget){let y=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":A=void 0;break;case"minimal":A={type:"enabled",budget_tokens:y?.minimal??1024};break;case"low":A={type:"enabled",budget_tokens:y?.low??5e3};break;case"medium":A={type:"enabled",budget_tokens:y?.medium??1e4};break;case"high":A={type:"enabled",budget_tokens:y?.high??2e4};break;case"highest":A={type:"enabled",budget_tokens:y?.highest??32e3};break}}let x={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...d?{max_tokens:d}:{},...u&&u.length>0?{stop_sequences:u}:{},...m&&!A?{temperature:m}:{},...g&&(!A||g>=.95)?{top_p:g}:{},...h&&!A?{top_k:h}:{},...i,...p&&p.length>0?{tools:p}:{},...o?{stream:!0}:{},...a?{system:a}:{},...A?{thinking:A}:{},messages:c};return[r,x]};createChatResp=e=>{if(e.type==="error")throw new $(e.error.message,void 0,void 0);let t=Ls(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,o=e.content.map((r,i)=>r.type==="tool_use"?{index:i,id:r.id,functionCalls:[{id:r.id,type:"function",function:{name:r.name,params:r.input}}],finishReason:t}:(r.type==="thinking"||r.type==="redacted_thinking")&&n?{index:i,thought:r.thinking,id:e.id,finishReason:t}:{index:i,content:r.type==="text"?r.text:"",id:e.id,finishReason:t}).filter(r=>r.content!==""||r.thought!==void 0||r.functionCalls!==void 0);return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens},{results:o,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:r}=e;throw new $(r.message,void 0,void 0)}let o=0;if(e.type==="message_start"){let{message:r}=e,i=[{index:o,content:"",id:r.id}];return this.tokensUsed={promptTokens:r.usage?.input_tokens??0,completionTokens:r.usage?.output_tokens??0,totalTokens:(r.usage?.input_tokens??0)+(r.usage?.output_tokens??0)},{results:i}}if(e.type==="content_block_start"){let{content_block:r}=e;if(r.type==="text")return{results:[{index:o,content:r.text}]};if(r.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:o,thought:r.thinking}]}:{results:[{index:o,content:""}]};if(r.type==="tool_use"&&typeof r.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=r.id;let i=[{id:r.id,type:"function",function:{name:r.name,params:""}}];return{results:[{index:o,functionCalls:i}]}}}if(e.type==="content_block_delta"){let{delta:r}=e;if(r.type==="text_delta")return{results:[{index:o,content:r.text}]};if(r.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:o,thought:r.thinking}]}:{results:[{index:o,content:""}]};if(r.type==="signature_delta")return{results:[{index:o,content:""}]};if(r.type==="input_json_delta"){let i=n.indexIdMap[e.index];if(!i)throw new Error(`invalid streaming index no id found: ${e.index}`);let a=[{id:i,type:"function",function:{name:"",params:r.partial_json}}];return{results:[{index:o,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:r,usage:i}=e;return this.tokensUsed={promptTokens:0,completionTokens:i.output_tokens,totalTokens:i.output_tokens},{results:[{index:o,content:"",finishReason:Ls(r.stop_reason)}]}}return{results:[{index:o,content:""}]}}},Be=class s extends K{static create(e){return new s(e)}constructor({apiKey:e,projectId:t,region:n,config:o,options:r,models:i}){let a=t!==void 0&&n!==void 0,l,c;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");if(typeof e!="function")throw new Error("Anthropic Vertex API key must be a function for token-based authentication");l=`https://${n}-aiplatform.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",c=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"prompt-caching-2024-07-31","x-api-key":typeof e=="function"?await e():e})}let p={...No(),...o},d=new Lo(p,a),u=m=>{let g=re({model:m,modelInfo:wt,models:i});return{functions:!0,streaming:!0,hasThinkingBudget:g?.hasThinkingBudget??!1,hasShowThoughts:g?.hasShowThoughts??!1,functionCot:!0}};super(d,{name:"Anthropic",apiURL:l,headers:c,modelInfo:wt,defaults:{model:p.model},options:r,supportFor:u,models:i})}};function za(s){let e=s.map(t=>{switch(t.role){case"function":return{role:"user",content:[{type:"tool_result",content:t.result,tool_use_id:t.functionId,...t.isError?{is_error:!0}:{},...t.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof t.content=="string"?{role:"user",content:t.content}:{role:"user",content:t.content.map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,...o.cache?{cache:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:o.mimeType,data:o.image},...o.cache?{cache:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let n="";return typeof t.content=="string"&&(n=t.content),typeof t.functionCalls<"u"&&(n=t.functionCalls.map(o=>{let r={};return typeof o.function.params=="string"?r=JSON.parse(o.function.params):typeof o.function.params=="object"&&(r=o.function.params),{type:"tool_use",id:o.id,name:o.function.name,input:r,...t.cache?{cache:{type:"ephemeral"}}:{}}})),{role:"assistant",content:n}}default:throw new Error("Invalid role")}});return ja(e)}function ja(s){let e=[];for(let[t,n]of s.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&s.at(t-1)?.role==="assistant"){let o=e.pop();e.push({...o||{},...n})}else e.push(n)}return e}function Ls(s){if(s)switch(s){case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"function_call";case"end_turn":return"stop";default:return"stop"}}var vt=(A=>(A.GPT4="gpt-4",A.GPT41="gpt-4.1",A.GPT41Mini="gpt-4.1-mini",A.GPT4O="gpt-4o",A.GPT4OMini="gpt-4o-mini",A.GPT4ChatGPT4O="chatgpt-4o-latest",A.GPT4Turbo="gpt-4-turbo",A.GPT35Turbo="gpt-3.5-turbo",A.GPT35TurboInstruct="gpt-3.5-turbo-instruct",A.GPT35TextDavinci002="text-davinci-002",A.GPT3TextBabbage002="text-babbage-002",A.GPT3TextAda001="text-ada-001",A.O1="o1",A.O1Mini="o1-mini",A.O3="o3",A.O3Mini="o3-mini",A.O4Mini="o4-mini",A))(vt||{}),qe=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(qe||{});var ze=(y=>(y.GPT4="gpt-4",y.GPT41="gpt-4.1",y.GPT41Mini="gpt-4.1-mini",y.GPT4O="gpt-4o",y.GPT4OMini="gpt-4o-mini",y.GPT4ChatGPT4O="chatgpt-4o-latest",y.GPT4Turbo="gpt-4-turbo",y.GPT35Turbo="gpt-3.5-turbo",y.GPT35TurboInstruct="gpt-3.5-turbo-instruct",y.GPT35TextDavinci002="text-davinci-002",y.GPT3TextBabbage002="text-babbage-002",y.GPT3TextAda001="text-ada-001",y.O1Pro="o1-pro",y.O1="o1",y.O1Mini="o1-mini",y.O3Pro="o3-pro",y.O3="o3",y.O3Mini="o3-mini",y.O4Mini="o4-mini",y))(ze||{});var je=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],un=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,hasThinkingBudget:!0,hasShowThoughts:!0,isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,hasThinkingBudget:!0,hasShowThoughts:!0,isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,hasThinkingBudget:!0,hasShowThoughts:!0}];var Ha=s=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(s)||e.includes(s)},_e=()=>structuredClone({model:"gpt-4.1",embedModel:"text-embedding-3-small",...L()}),dn=()=>structuredClone({..._e(),model:"gpt-4.1"}),mn=()=>structuredClone({model:"gpt-4.1",embedModel:"text-embedding-3-small",...Y()}),gn=()=>({..._e(),model:"gpt-4.1-mini"}),Uo=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq(e,t){let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o={name:"/chat/completions"},r=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),i=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Ka(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,p=this.config.store,d=Ha(n),u={model:n,messages:a,response_format:this.config?.responseFormat?{type:this.config.responseFormat}:void 0,tools:r,tool_choice:i,...d?{}:{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.temperature,top_p:e.modelConfig?.topP??this.config.topP??1,n:e.modelConfig?.n??this.config.n,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...l?{frequency_penalty:l}:{}},stop:e.modelConfig?.stopSequences??this.config.stop,logit_bias:this.config.logitBias,...c&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...p?{store:p}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(u.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(u.web_search_options={...this.config.webSearchOptions.searchContextSize&&{search_context_size:this.config.webSearchOptions.searchContextSize},...this.config.webSearchOptions.userLocation&&{user_location:{approximate:{type:"approximate",...this.config.webSearchOptions.userLocation.approximate.city&&{city:this.config.webSearchOptions.userLocation.approximate.city},...this.config.webSearchOptions.userLocation.approximate.country&&{country:this.config.webSearchOptions.userLocation.approximate.country},...this.config.webSearchOptions.userLocation.approximate.region&&{region:this.config.webSearchOptions.userLocation.approximate.region},...this.config.webSearchOptions.userLocation.approximate.timezone&&{timezone:this.config.webSearchOptions.userLocation.approximate.timezone}}}}}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":u.reasoning_effort=void 0;break;case"minimal":u.reasoning_effort="low";break;case"low":u.reasoning_effort="medium";break;case"medium":u.reasoning_effort="high";break;case"high":u.reasoning_effort="high";break;case"highest":u.reasoning_effort="high";break}return this.chatReqUpdater&&(u=this.chatReqUpdater(u)),[o,u]}createEmbedReq(e){let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},o={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,o]}createChatResp(e){let{id:t,usage:n,choices:o,error:r}=e;if(r)throw r;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:o.map(a=>{if(a.message.refusal)throw new $(a.message.refusal,e.model,e.id);let l=Us(a.finish_reason),c=a.message.tool_calls?.map(({id:p,function:{arguments:d,name:u}})=>({id:p,type:"function",function:{name:u,params:d}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,annotations:a.message.annotations,functionCalls:c,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:o,choices:r}=e;this.tokensUsed=o?{promptTokens:o.prompt_tokens,completionTokens:o.completion_tokens,totalTokens:o.total_tokens}:void 0;let i=t;return i.indexIdMap||(i.indexIdMap={}),{results:r.map(({index:l,delta:{content:c,role:p,refusal:d,tool_calls:u,reasoning_content:m,annotations:g},finish_reason:h})=>{if(d)throw new $(d,void 0,n);let f=Us(h),A=u?.map(({id:x,index:y,function:{name:O,arguments:b}})=>{typeof x=="string"&&typeof y=="number"&&!i.indexIdMap[y]&&(i.indexIdMap[y]=x);let T=i.indexIdMap[y];return T?{id:T,type:"function",function:{name:O,params:b}}:null}).filter(x=>x!==null);return{index:l,content:c??void 0,role:p,thought:m,annotations:g,functionCalls:A,finishReason:f,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(o=>o.embedding)}}},Us=s=>{switch(s){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Ka(s){return s.chatPrompt.map(t=>{switch(t.role){case"system":return{role:"system",content:t.content};case"user":{let n=Array.isArray(t.content)?t.content.map(o=>{switch(o.type){case"text":return{type:"text",text:o.text};case"image":return{type:"image_url",image_url:{url:`data:${o.mimeType};base64,${o.image}`,details:o.details??"auto"}};case"audio":return{type:"input_audio",input_audio:{data:o.data,format:o.format??"wav"}};default:throw new Error("Invalid content type")}}):t.content;return{role:"user",...t.name?{name:t.name}:{},content:n}}case"assistant":{let n=t.functionCalls?.map(o=>({id:o.id,type:"function",function:{name:o.function.name,arguments:typeof o.function.params=="object"?JSON.stringify(o.function.params):o.function.params}}));if(n&&n.length>0)return{role:"assistant",...t.content?{content:t.content}:{},name:t.name,tool_calls:n};if(t.content===void 0)throw new Error("Assistant content is required when no tool calls are provided");return{role:"assistant",content:t.content,...t.name?{name:t.name}:{}}}case"function":return{role:"tool",content:t.result,tool_call_id:t.functionId};default:throw new Error("Invalid role")}})}var V=class extends K{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r,models:i,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new Uo(t,n?.streamingUsage??!0,a);super(c,{name:"OpenAI",apiURL:o||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:r,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:i})}},He=class extends V{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("OpenAI API key not set");r=[...je,...r??[]];let i=a=>{let l=re({model:a,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:l?.hasThinkingBudget??!1,hasShowThoughts:l?.hasShowThoughts??!1}};super({apiKey:e,config:{..._e(),...t},options:n,modelInfo:r,models:o,supportFor:i}),super.setName("OpenAI")}};var $o=_e,$s=mn,Bs=gn,qs=dn,Ke=class extends V{constructor({apiKey:e,resourceName:t,deploymentName:n,version:o="api-version=2024-02-15-preview",config:r,options:i,models:a,modelInfo:l}){if(!e||e==="")throw new Error("Azure OpenAPI API key not set");if(!t||t==="")throw new Error("Azure OpenAPI resource name not set");if(!n||n==="")throw new Error("Azure OpenAPI deployment id not set");let c={...$o(),...r};l=[...je,...l??[]];let p=u=>{let m=re({model:u,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:m?.hasThinkingBudget??!1,hasShowThoughts:m?.hasShowThoughts??!1}};super({apiKey:e,config:c,options:i,models:a,modelInfo:l,supportFor:p});let d=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${o}`,d).href),super.setHeaders(async()=>({"api-key":e}))}};var hn=class s{services;currentServiceIndex=0;currentService;debug;initialBackoffMs;maxBackoffMs;maxRetries;serviceFailures=new Map;constructor(e,t){if(e.length===0)throw new Error("No AI services provided.");Va(e),this.services=[...e].sort(t?.comparator??s.metricComparator);let n=this.services[this.currentServiceIndex];if(n===void 0)throw new Error("Error initializing the AI services.");this.currentService=n,this.debug=t?.debug??!0,this.initialBackoffMs=t?.initialBackoffMs??1e3,this.maxBackoffMs=t?.maxBackoffMs??32e3,this.maxRetries=t?.maxRetries??3}static create(e,t){return new s(e,t)}getLastUsedChatModel(){return this.currentService.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.currentService.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.currentService.getLastUsedModelConfig()}static inputOrderComparator=()=>0;static metricComparator=(e,t)=>{let n=e.getMetrics(),o=t.getMetrics();return n.latency.chat.mean-o.latency.chat.mean};getModelList(){return this.currentService.getModelList()}getNextService(){let e=this.services[++this.currentServiceIndex];return e===void 0?!1:(this.currentService=e,!0)}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){return this.currentService.getFeatures(e)}getMetrics(){return this.currentService.getMetrics()}canRetryService(){let e=this.serviceFailures.get(this.currentService.getId());if(!e)return!0;let{retries:t,lastFailureTime:n}=e,o=Date.now()-n,r=Math.min(this.initialBackoffMs*2**t,this.maxBackoffMs);return o>=r}handleFailure(){let t=(this.serviceFailures.get(this.currentService.getId())?.retries??0)+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:t,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${t}/${this.maxRetries})`),t>=this.maxRetries){let n=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`),n}return!0}handleSuccess(){this.serviceFailures.delete(this.currentService.getId())}async chat(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.chat(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof ee))throw n;switch(n.constructor){case be:throw n;case ke:break;case me:break;case Ae:break;case le:break;case Ee:break;default:throw n}if(!this.handleFailure())throw n}}}async embed(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.embed(e,t);return this.handleSuccess(),n}catch(n){if(!this.handleFailure())throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Va(s){let e=s.find(o=>o.getModelList()!==void 0);if(!e)return;let t=e.getModelList();if(!t)throw new Error("No model list found in any service.");let n=new Set(t.map(o=>o.key));for(let o=0;o<s.length;o++){let r=s[o];if(!r)throw new Error(`Service at index ${o} is undefined`);let i=r.getModelList();if(!i)throw new Error(`Service at index ${o} (${r.getName()}) has no model list while another service does.`);let a=new Set(i.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${o} (${r.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${o} (${r.getName()}) has extra model "${l}"`)}}var St=(o=>(o.CommandRPlus="command-r-plus",o.CommandR="command-r",o.Command="command",o.CommandLight="command-light",o))(St||{}),Mt=(o=>(o.EmbedEnglishV30="embed-english-v3.0",o.EmbedEnglishLightV30="embed-english-light-v3.0",o.EmbedMultiLingualV30="embed-multilingual-v3.0",o.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",o))(Mt||{});var An=[{name:"command-r-plus",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"command-r",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command-light",currency:"usd",promptTokenCostPer1M:.3,completionTokenCostPer1M:.6},{name:"embed-english-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-english-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1}];var qo=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...L()}),js=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Y()}),Bo=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,frequencyPenalty:e.frequencyPenalty,presencePenalty:e.presencePenalty,endSequences:e.endSequences,stopSequences:e.stopSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.at(-1),o=e.chatPrompt.slice(0,-1),r;n&&n.role==="user"&&typeof n.content=="string"&&(r=n?.content);let i=Wa(o),a=e.functions?.map(d=>{let u={};if(d.parameters?.properties)for(let[m,g]of Object.entries(d.parameters.properties))u[m]={description:g.description,type:g.type,required:d.parameters.required?.includes(m)??!1};return{name:d.name,description:d.description,parameter_definitions:u}}),l=e.chatPrompt.filter(d=>d.role==="function").map(d=>{let u=a?.find(m=>m.name===d.functionId);if(!u)throw new Error("Function not found");return{call:{name:u.name,parameters:u.parameter_definitions},outputs:[{result:d.result??""}]}}),c={name:"/chat"},p={message:r,model:t,tools:a,...l&&!r?{tool_results:l}:{},chat_history:i,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.temperature,k:e.modelConfig?.topK??this.config.topK,p:e.modelConfig?.topP??this.config.topP,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,end_sequences:this.config.endSequences,stop_sequences:e.modelConfig?.stopSequences??this.config.stopSequences};return[c,p]}createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embed"},o={model:t,texts:e.texts??[],input_type:"classification",truncate:""};return[n,o]};createChatResp=e=>{this.tokensUsed=e.meta.billed_units?{promptTokens:e.meta.billed_units.input_tokens,completionTokens:e.meta.billed_units.output_tokens,totalTokens:e.meta.billed_units.input_tokens+e.meta.billed_units.output_tokens}:void 0;let t;if("finish_reason"in e)switch(e.finish_reason){case"COMPLETE":t="stop";break;case"MAX_TOKENS":t="length";break;case"ERROR":throw new Error("Finish reason: ERROR");case"ERROR_TOXIC":throw new Error("Finish reason: CONTENT_FILTER");default:t="stop";break}let n;return"tool_calls"in e&&(n=e.tool_calls?.map(r=>({id:r.name,type:"function",function:{name:r.name,params:r.parameters}}))),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}};createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:e.meta.billed_units?.output_tokens??0,totalTokens:e.meta.billed_units?.output_tokens??0};let{results:o}=this.createChatResp(e),r=o[0];if(!r)throw new Error("No result");return r.id=n.generation_id??"",{results:o}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},Ve=class extends K{constructor({apiKey:e,config:t,options:n,models:o}){if(!e||e==="")throw new Error("Cohere API key not set");let r={...qo(),...t},i=new Bo(r);super(i,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:An,defaults:{model:r.model},supportFor:{functions:!0,streaming:!0},options:n,models:o})}};function Wa(s){return s.map(e=>{let t="";if(e.role==="system"||e.role==="assistant"||e.role==="user")if(typeof e.content=="string")t=e.content;else throw new Error("Multi-modal content not supported");switch(e.role){case"user":return{role:"USER",message:t};case"system":return{role:"SYSTEM",message:t};case"assistant":{let n=zs(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=s.map(i=>{if(i.role==="assistant")return i.functionCalls?.find(a=>a.id===e.functionId)}).filter(i=>i!==void 0),o=zs(n)?.at(0);if(!o)throw new Error("Function call not found");let r=[{result:e.result}];return{role:"TOOL",tool_results:[{call:o,outputs:r}]}}default:throw new Error("Unknown role")}})}function zs(s){return s?.map(e=>{let t=typeof e.function.params=="string"?JSON.parse(e.function.params):e.function.params;return{name:e.function.name,parameters:t}})}var Ot=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Ot||{});var fn=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var zo=()=>structuredClone({model:"deepseek-chat",...L()}),Hs=()=>structuredClone({model:"deepseek-coder",...Y()}),We=class extends V{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...zo(),...t};r=[...fn,...r??[]],super({apiKey:e,config:i,options:n,apiURL:"https://api.deepseek.com",modelInfo:r,supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1},models:o}),super.setName("DeepSeek")}};var kt=(p=>(p.Gemini25Pro="gemini-2.5-pro",p.Gemini25Flash="gemini-2.5-flash",p.Gemini25FlashLite="gemini-2.5-flash-lite",p.Gemini20Flash="gemini-2.0-flash",p.Gemini20FlashLite="gemini-2.0-flash-lite",p.Gemini1Pro="gemini-1.0-pro",p.Gemini15Flash="gemini-1.5-flash",p.Gemini15Flash002="gemini-1.5-flash-002",p.Gemini15Flash8B="gemini-1.5-flash-8b",p.Gemini15Pro="gemini-1.5-pro",p))(kt||{}),xn=(o=>(o.GeminiEmbedding="gemini-embedding-exp",o.TextEmbeddingLarge="text-embedding-large-exp-03-07",o.TextEmbedding004="text-embedding-004",o.TextEmbedding005="text-embedding-005",o))(xn||{}),yn=(o=>(o.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",o.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",o.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",o.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",o))(yn||{}),In=(r=>(r.BlockNone="BLOCK_NONE",r.BlockOnlyHigh="BLOCK_ONLY_HIGH",r.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",r.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",r.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",r))(In||{}),jo=(l=>(l.SemanticSimilarity="SEMANTIC_SIMILARITY",l.Classification="CLASSIFICATION",l.Clustering="CLUSTERING",l.RetrievalDocument="RETRIEVAL_DOCUMENT",l.RetrievalQuery="RETRIEVAL_QUERY",l.QuestionAnswering="QUESTION_ANSWERING",l.FactVerification="FACT_VERIFICATION",l.CodeRetrievalQuery="CODE_RETRIEVAL_QUERY",l))(jo||{});var bn=[{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5}];var Ks=[{category:"HARM_CATEGORY_HARASSMENT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"BLOCK_NONE"}],Ko=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Ks,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...L()}),Vs=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Ks,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Y()}),Ho=class{constructor(e,t,n,o,r){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=o;this.options=r;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,o=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r;if(this.endpointId?r={name:o?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:r={name:o?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let h=o?"&":"?",f=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;r.name+=`${h}key=${f}`}let i=e.chatPrompt.filter(h=>h.role==="system").map(h=>h.content),a=i.length>0?{role:"user",parts:[{text:i.join(" ")}]}:void 0,l=e.chatPrompt.filter(h=>h.role!=="system").map((h,f)=>{switch(h.role){case"user":return{role:"user",parts:Array.isArray(h.content)?h.content.map((x,y)=>{switch(x.type){case"text":return{text:x.text};case"image":return{inlineData:{mimeType:x.mimeType,data:x.image}};default:throw new Error(`Chat prompt content type not supported (index: ${y})`)}}):[{text:h.content}]};case"assistant":{let A=[];if(h.functionCalls){if(A=h.functionCalls.map(x=>{let y=typeof x.function.params=="string"?JSON.parse(x.function.params):x.function.params;return{functionCall:{name:x.function.name,args:y}}}),!A)throw new Error("Function call is empty");return{role:"model",parts:A}}if(!h.content)throw new Error("Assistant content is empty");return A=[{text:h.content}],{role:"model",parts:A}}case"function":{if(!("functionId"in h))throw new Error(`Chat prompt functionId is empty (index: ${f})`);return{role:"user",parts:[{functionResponse:{name:h.functionId,response:{result:h.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(h)} (index: ${f})`)}}),c=[];e.functions&&e.functions.length>0&&c.push({function_declarations:e.functions}),this.options?.codeExecution&&c.push({code_execution:{}}),this.options?.googleSearchRetrieval&&c.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&c.push({google_search:{}}),this.options?.urlContext&&c.push({url_context:{}}),c.length===0&&(c=void 0);let p;if(e.functionCall)if(e.functionCall==="none")p={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")p={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")p={function_calling_config:{mode:"ANY"}};else{let h=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...h}}else c&&c.length>0&&(p={function_calling_config:{mode:"AUTO"}});let d={};if(this.config.thinking?.includeThoughts&&(d.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(d.thinkingBudget=this.config.thinking.thinkingTokenBudget),t?.thinkingTokenBudget){let h=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":d.thinkingBudget=0,d.includeThoughts=!1;break;case"minimal":d.thinkingBudget=h?.minimal??200;break;case"low":d.thinkingBudget=h?.low??800;break;case"medium":d.thinkingBudget=h?.medium??5e3;break;case"high":d.thinkingBudget=h?.high??1e4;break;case"highest":d.thinkingBudget=h?.highest??24500;break}}t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(d.includeThoughts=t.showThoughts);let u={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.temperature,topP:e.modelConfig?.topP??this.config.topP,topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain",...Object.keys(d).length>0?{thinkingConfig:d}:{}},m=this.config.safetySettings;return[r,{contents:l,tools:c,toolConfig:p,systemInstruction:a,generationConfig:u,safetySettings:m}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,o;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},o={instances:e.texts.map(r=>({content:r,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let r=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${r}`},o={requests:e.texts.map(i=>({model:`models/${t}`,content:{parts:[{text:i}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,o]};createChatResp=e=>{let t=e.candidates?.map(n=>{let o={index:0};switch(n.finishReason){case"MAX_TOKENS":o.finishReason="length";break;case"STOP":o.finishReason="stop";break;case"SAFETY":throw new $("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new $("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new $("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new $("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new $("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new $("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new $("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new $("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new $("Other finish reason",void 0,void 0)}if(!n.content||!n.content.parts)return o;for(let r of n.content.parts){if("text"in r){"thought"in r&&r.thought?o.thought=r.text:o.content=r.text;continue}"functionCall"in r&&(o.functionCalls=[{id:se(),type:"function",function:{name:r.functionCall.name,params:r.functionCall.args}}])}return o});return e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount}),{results:t}};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}}},Ye=class s extends K{static create(e){return new s(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:o,config:r,options:i,models:a,modelInfo:l}){let c=t!==void 0&&n!==void 0,p,d;if(c){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let h;o?h="endpoints":h="publishers/google",p=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${h}`,d=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");p="https://generativelanguage.googleapis.com/v1beta",d=async()=>({})}let u={...Ko(),...r},m=new Ho(u,c,o,e,i);l=[...bn,...l??[]];let g=h=>{let f=re({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:f?.hasThinkingBudget??!1,hasShowThoughts:f?.hasShowThoughts??!1,functionCot:!1}};super(m,{name:"GoogleGeminiAI",apiURL:p,headers:d,modelInfo:l,defaults:{model:u.model,embedModel:u.embedModel},options:i,supportFor:g,models:a})}};var Ya=new ne,Je=class{options;maxTokens;refillRate;currentTokens;lastRefillTime;constructor(e,t,n){this.maxTokens=e,this.refillRate=t,this.currentTokens=e,this.lastRefillTime=Date.now(),this.options=n}refillTokens(){let e=Date.now(),n=(e-this.lastRefillTime)/1e3*this.refillRate;this.currentTokens=Math.min(this.maxTokens,this.currentTokens+n),this.lastRefillTime=e}async waitUntilTokensAvailable(e){if(this.refillTokens(),this.currentTokens>=e){this.currentTokens-=e;return}return this.options?.debug&&console.log(Ya.red(`Rate limiter: Waiting for ${e-this.currentTokens} tokens`)),await new Promise(t=>setTimeout(t,100)),this.waitUntilTokensAvailable(e)}async acquire(e){await this.waitUntilTokensAvailable(e)}};var Et=(o=>(o.Llama3_8B="llama3-8b-8192",o.Llama33_70B="llama-3.3-70b-versatile",o.Mixtral_8x7B="mixtral-8x7b-32768",o.Gemma2_9B="gemma2-9b-it",o))(Et||{});var Rn=[{name:"gemma2-9b-it",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.2,completionTokenCostPer1M:.2},{name:"llama-3.3-70b-versatile",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.59,completionTokenCostPer1M:.79},{name:"llama3-8b-8192",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.05,completionTokenCostPer1M:.08},{name:"mixtral-8x7b-32768",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.24,completionTokenCostPer1M:.24}];var Ja=()=>structuredClone({model:"llama-3.3-70b-versatile",...L()}),Qe=class extends V{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Groq API key not set");let i={...Ja(),...t},a={...n,streamingUsage:!1};r=[...Rn,...r??[]];let l={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1};super({apiKey:e,config:i,options:a,modelInfo:r,apiURL:"https://api.groq.com/openai/v1",models:o,supportFor:l}),super.setName("Groq"),this.setOptions(a)}setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})};newRateLimiter=e=>{if(e?.rateLimiter)return e.rateLimiter;let t=e?.tokensPerMinute??4800,n=new Je(t,t/60,{debug:e?.debug});return async(r,i)=>{let a=i.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await r()}}};var Cn=[];var Tn=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Tn||{});var Wo=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...L()}),Ws=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Y()}),Vo=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,n:e.n,presencePenalty:e.presencePenalty}}createChatReq=e=>{let t=e.model,n=e.functions?`Functions:
|
|
109
|
+
`)});break;default:r=JSON.stringify(n,null,2)}s(r)}};var D={LLM_SYSTEM:"gen_ai.system",LLM_OPERATION_NAME:"gen_ai.operation.name",LLM_REQUEST_MODEL:"gen_ai.request.model",LLM_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",LLM_REQUEST_TEMPERATURE:"gen_ai.request.temperature",LLM_REQUEST_TOP_K:"gen_ai.request.top_k",LLM_REQUEST_FREQUENCY_PENALTY:"gen_ai.request.frequency_penalty",LLM_REQUEST_PRESENCE_PENALTY:"gen_ai.request.presence_penalty",LLM_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",LLM_REQUEST_LLM_IS_STREAMING:"gen_ai.request.llm_is_streaming",LLM_REQUEST_TOP_P:"gen_ai.request.top_p",LLM_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",LLM_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",LLM_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",LLM_USAGE_THOUGHTS_TOKENS:"gen_ai.usage.thoughts_tokens",DB_SYSTEM:"db.system",DB_TABLE:"db.table",DB_NAMESPACE:"db.namespace",DB_ID:"db.id",DB_QUERY_TEXT:"db.query.text",DB_VECTOR:"db.vector",DB_OPERATION_NAME:"db.operation.name",DB_VECTOR_QUERY_TOP_K:"db.vector.query.top_k",DB_QUERY_EMBEDDINGS:"db.query.embeddings",DB_QUERY_RESULT:"db.query.result",DB_QUERY_EMBEDDINGS_VECTOR:"db.query.embeddings.vector",DB_QUERY_RESULT_ID:"db.query.result.id",DB_QUERY_RESULT_SCORE:"db.query.result.score",DB_QUERY_RESULT_DISTANCE:"db.query.result.distance",DB_QUERY_RESULT_METADATA:"db.query.result.metadata",DB_QUERY_RESULT_VECTOR:"db.query.result.vector",DB_QUERY_RESULT_DOCUMENT:"db.query.result.document"},de={GEN_AI_USER_MESSAGE:"gen_ai.user.message",GEN_AI_SYSTEM_MESSAGE:"gen_ai.system.message",GEN_AI_ASSISTANT_MESSAGE:"gen_ai.assistant.message",GEN_AI_TOOL_MESSAGE:"gen_ai.tool.message",GEN_AI_CHOICE:"gen_ai.choice",GEN_AI_USAGE:"gen_ai.usage"},qr=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(qr||{}),zr=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(zr||{});var jr=class{buffer;doneCallback;transformFn;constructor(e,t){this.transformFn=e,this.doneCallback=t,this.buffer=t?[]:void 0}async transform(e,t){let n=this.transformFn(e);n&&(t.enqueue(n),this.buffer?.push(n))}async flush(e){await this.doneCallback?.(this.buffer??[]),e.terminate()}},An=class extends TransformStream{constructor(e,t){super(new jr(e,t))}};function xn(s,e){for(let t of e){let n=s.find(r=>r.id===t.id);n?(typeof t.function.name=="string"&&t.function.name.length>0&&(n.function.name+=t.function.name),typeof t.function.params=="string"&&t.function.params.length>0&&(n.function.params+=t.function.params),typeof t.function.params=="object"&&(n.function.params=t.function.params)):s.push(t)}}var Cs=(s,e,t,n)=>{let r=n?s.filter(i=>i.role!=="system"):[...s];t({name:"ChatRequestChatPrompt",step:e,value:r})};var Ts=(s,e)=>{if(!s.results)return;let t={name:"ChatResponseResults",value:s.results};e(t)},ws=(s,e,t)=>{t({name:"ChatResponseStreamingResult",index:e,value:s})};function vs(s,e){let t=new Map;for(let n of s)for(let r of n.results){if(!r)continue;let o=t.get(r.index);o?(r.content&&(o.content=(o.content??"")+r.content),r.thought&&(o.thought=(o.thought??"")+r.thought),r.finishReason&&(o.finishReason=r.finishReason),r.functionCalls&&(o.functionCalls?xn(o.functionCalls,structuredClone(r.functionCalls)):o.functionCalls=structuredClone(r.functionCalls))):(o=structuredClone(r),t.set(r.index,o))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var Ss=(s,e)=>{e({name:"FunctionResults",value:s})},Ms=(s,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:s})},Os=(s,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:s})},ks=(s,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:s})},Es=(s,e,t)=>{t({name:"RefusalError",index:e,error:s})};var Ps=(s,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:s})},_s=(s,e)=>{let t=s.slice(0,3).map(r=>({length:r.length,sample:r.slice(0,5),truncated:r.length>5})),n={name:"EmbedResponse",totalEmbeddings:s.length,value:t};e(n)},Fs=(s,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:s,selectedIndex:e,latency:t})};var Hr=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n);e[t]=r.length>100?r.substring(0,100):r}return e},yn,Ds=s=>{if(yn)return yn;if(s)return yn=al(s),yn};var al=s=>({latencyHistogram:s.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:s.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:s.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:s.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:s.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:s.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:s.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:s.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:s.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:s.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:s.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:s.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:s.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:s.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:s.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:s.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:s.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:s.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:s.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:s.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:s.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:s.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:s.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:s.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"})}),$s=(s,e,t,n,r)=>{try{if(s.latencyHistogram){let o=Hr({operation:e,ai_service:n,...r?{model:r}:{}});s.latencyHistogram.record(t,o)}}catch(o){console.warn("Failed to record latency metric:",o)}},Ls=(s,e,t,n,r,o,i)=>{let a={operation:e,ai_service:o,...i?{model:i}:{}};s.meanLatencyGauge&&s.meanLatencyGauge.record(t,a),s.p95LatencyGauge&&s.p95LatencyGauge.record(n,a),s.p99LatencyGauge&&s.p99LatencyGauge.record(r,a)},Ns=(s,e,t,n)=>{try{if(s.errorCounter){let r=Hr({operation:e,ai_service:t,...n?{model:n}:{}});s.errorCounter.add(1,r)}}catch(r){console.warn("Failed to record error metric:",r)}},Gs=(s,e,t,n,r)=>{s.errorRateGauge&&s.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{}})},Us=(s,e,t,n)=>{s.requestCounter&&s.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Mt=(s,e,t,n,r)=>{try{let o=Hr({ai_service:n,...r?{model:r}:{}});s.tokenCounter&&s.tokenCounter.add(t,{token_type:e,...o}),e==="input"&&s.inputTokenCounter&&s.inputTokenCounter.add(t,o),e==="output"&&s.outputTokenCounter&&s.outputTokenCounter.add(t,o)}catch(o){console.warn("Failed to record token metric:",o)}},Bs=(s,e,t,n,r)=>{t&&s.streamingRequestsCounter&&s.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{}})},qs=(s,e,t,n,r)=>{let o={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{}};s.functionCallsCounter&&s.functionCallsCounter.add(1,o),t&&s.functionCallLatencyHistogram&&s.functionCallLatencyHistogram.record(t,o)},Kr=(s,e,t,n,r)=>{s.requestSizeHistogram&&s.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Vr=(s,e,t,n,r)=>{s.responseSizeHistogram&&s.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},zs=(s,e,t,n,r)=>{let o={...n?{ai_service:n}:{},...r?{model:r}:{}};e!==void 0&&s.temperatureGauge&&s.temperatureGauge.record(e,o),t!==void 0&&s.maxTokensGauge&&s.maxTokensGauge.record(t,o)},Wr=(s,e,t,n,r)=>{s.estimatedCostCounter&&s.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{}})},js=(s,e,t,n)=>{s.promptLengthHistogram&&s.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},Hs=(s,e,t,n)=>{s.contextWindowUsageGauge&&s.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},Ks=(s,e,t,n)=>{s.timeoutsCounter&&s.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Vs=(s,e,t,n)=>{s.abortsCounter&&s.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Ws=(s,e,t,n)=>{s.thinkingBudgetUsageCounter&&s.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},Ys=(s,e,t,n,r)=>{(e||t)&&s.multimodalRequestsCounter&&s.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{}})};var L=()=>structuredClone({temperature:0,topK:40,topP:.9}),W=()=>structuredClone({temperature:.4,topP:.7,frequencyPenalty:.2}),j=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:o,defaults:i,options:a={},supportFor:l,models:p}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=r,this.supportFor=l,this.tracer=a.tracer??B.tracer,this.meter=a.meter??B.meter,this.modelInfo=o,this.models=p,this.id=ne();let c=this.getModel(i.model)??i.model,d=this.getEmbedModel(i.embedModel)??i.embedModel;if(this.defaults={model:c,embedModel:d},!i.model||typeof i.model!="string"||i.model==="")throw new Error("No model defined");this.setOptions(a),p&&pl(p)}debug=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=B.logger??bs;corsProxy;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getMetricsInstruments(){return Ds(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}setOptions(e){this.debug=e.debug??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??B.tracer,this.meter=e.meter??B.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??B.logger??this.logger,this.corsProxy=e.corsProxy}getOptions(){return{debug:this.debug,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger,corsProxy:this.corsProxy}}getLogger(){return this.logger}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,i)=>o-i),r=Math.ceil(t/100*n.length)-1;return n[r]??0}updateLatencyMetrics(e,t){let n=this.metrics.latency[e];n.samples.push(t),n.samples.length>1e3&&n.samples.shift(),n.mean=n.samples.reduce((o,i)=>o+i,0)/n.samples.length,n.p95=this.calculatePercentile(n.samples,95),n.p99=this.calculatePercentile(n.samples,99);let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;$s(r,e,t,this.name,o),Ls(r,e,n.mean,n.p95,n.p99,this.name,o)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Us(r,e,this.name,o),t&&Ns(r,e,this.name,o),Gs(r,e,n.rate,this.name,o)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&e?.tokens){let{promptTokens:n,completionTokens:r,totalTokens:o,thoughtsTokens:i}=e.tokens;n&&Mt(t,"input",n,this.name,e.model),r&&Mt(t,"output",r,this.name,e.model),o&&Mt(t,"total",o,this.name,e.model),i&&Mt(t,"thoughts",i,this.name,e.model)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let r of e.chatPrompt)if(r.role==="user"&&Array.isArray(r.content))for(let o of r.content)o.type==="image"?t=!0:o.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}calculatePromptLength(e){let t=0;if(e.chatPrompt&&Array.isArray(e.chatPrompt))for(let n of e.chatPrompt)if(n.role==="system"||n.role==="assistant")n.content&&(t+=n.content.length);else if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content)r.type==="text"&&(t+=r.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!t?.tokens?.promptTokens)return 0;let n=this.modelInfo.find(r=>r.name===e);return n?.contextWindow?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*i/1e6+o*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*i/1e6+o*a/1e6}recordFunctionCallMetrics(e,t){let n=this.getMetricsInstruments();if(!(!n||!e))for(let r of e)r&&typeof r=="object"&&"function"in r&&r.function&&typeof r.function=="object"&&"name"in r.function&&qs(n,r.function.name,void 0,this.name,t)}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ks(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Vs(t,e,this.name,n)}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,i=this.lastUsedModelConfig,a=i?.stream??!1;Bs(r,"chat",a,this.name,o);let{hasImages:l,hasAudio:p}=this.detectMultimodalContent(e);Ys(r,l,p,this.name,o);let c=this.calculatePromptLength(e);js(r,c,this.name,o),zs(r,i?.temperature,i?.maxTokens,this.name,o),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&Ws(r,this.modelUsage.tokens.thoughtsTokens,this.name,o);let d=this.calculateRequestSize(e);if(Kr(r,"chat",d,this.name,o),n&&!a){let u=n,m=this.calculateResponseSize(u);if(Vr(r,"chat",m,this.name,o),u.results)for(let A of u.results)A.functionCalls&&this.recordFunctionCallMetrics(A.functionCalls,this.lastUsedChatModel);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,u.modelUsage);g>0&&Hs(r,g,this.name,o);let h=this.estimateCost(this.lastUsedChatModel,u.modelUsage);h>0&&Wr(r,"chat",h,this.name,o)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let r=this.lastUsedEmbedModel,o=this.calculateRequestSize(e);Kr(n,"embed",o,this.name,r);let i=this.calculateResponseSize(t);Vr(n,"embed",i,this.name,r);let a=this.estimateCostByName(r,t.modelUsage);a>0&&Wr(n,"embed",a,this.name,r)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,o;try{return o=await this._chat1(e,t),o}catch(i){throw r=!0,i instanceof Error&&(i.message.includes("timeout")||i.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(i.message.includes("abort")||i.name==="AbortError")&&this.recordAbortMetric("chat")),i}finally{let i=performance.now()-n;this.updateLatencyMetrics("chat",i),this.updateErrorMetrics("chat",r),r||this.recordChatMetrics(e,t,o)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;e.chatPrompt&&Array.isArray(e.chatPrompt)&&Yr(e.chatPrompt);let r={...this.aiImpl.getModelConfig(),...e.modelConfig};if(t?.thinkingTokenBudget&&!this.getFeatures(n).hasThinkingBudget)throw new Error(`Model ${n} does not support thinkingTokenBudget.`);if(t?.showThoughts&&!this.getFeatures(n).hasShowThoughts)throw new Error(`Model ${n} does not support showThoughts.`);if(this.modelInfo.find(a=>a.name===n)?.isExpensive&&t?.useExpensiveModel!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return r.stream=(t?.stream!==void 0?t.stream:r.stream)??!0,this.getFeatures(n).streaming||(r.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:le.SERVER,attributes:{[D.LLM_SYSTEM]:this.name,[D.LLM_OPERATION_NAME]:"chat",[D.LLM_REQUEST_MODEL]:n,[D.LLM_REQUEST_MAX_TOKENS]:r.maxTokens??"Not set",[D.LLM_REQUEST_TEMPERATURE]:r.temperature,[D.LLM_REQUEST_TOP_P]:r.topP??"Not set",[D.LLM_REQUEST_TOP_K]:r.topK??"Not set",[D.LLM_REQUEST_FREQUENCY_PENALTY]:r.frequencyPenalty??"Not set",[D.LLM_REQUEST_PRESENCE_PENALTY]:r.presencePenalty??"Not set",[D.LLM_REQUEST_STOP_SEQUENCES]:r.stopSequences?.join(", ")??"Not set",[D.LLM_REQUEST_LLM_IS_STREAMING]:r.stream??"Not set"}},t?.traceContext??je.active(),async a=>await this._chat2(n,r,e,t,a)):await this._chat2(n,r,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,r,o){if(!this.aiImpl.createChatReq)throw new Error("generateChatReq not implemented");let i=r?.debug??this.debug,a;n.functions&&n.functions.length>0&&(a=n.functions.map(m=>this.cleanupFunctionSchema(m)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t;let p=async()=>{let[m,g]=await this.aiImpl.createChatReq(l,r);return o?.isRecording()&&ll(n,o,this.excludeContentFromTrace),await oe({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),stream:t.stream,timeout:this.timeout,debug:i,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},g)};i&&Cs(l.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let c=r?.rateLimiter??this.rt,d=c?await c(p,{modelUsage:this.modelUsage}):await p();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("generateChatStreamResp not implemented");let m=this.aiImpl.createChatStreamResp.bind(this),g=x=>y=>{let k=m(y,x);if(k.sessionId=r?.sessionId,!k.modelUsage){let b=this.aiImpl.getTokenUsage();b&&(k.modelUsage={ai:this.name,model:e,tokens:b})}if(this.modelUsage=k.modelUsage,this.recordTokenUsage(k.modelUsage),o?.isRecording()&&Js(k,o,this.excludeContentFromTrace),i)for(let b of k.results)ws(b,b.index,r?.logger??this.logger);return k},h=async x=>{o?.isRecording()&&o.end(),i&&vs(x,r?.logger??this.logger)};if(typeof window<"u"){let x=d,y={},k=[];return new ReadableStream({start(b){let T=x.getReader();async function P(){try{for(;;){let{done:w,value:M}=await T.read();if(w){h&&await h(k),b.close();break}let N=g(y)(M);N&&(k.push(N),b.enqueue(N))}}catch(w){b.error(w)}finally{T.releaseLock()}}P()}})}return d.pipeThrough(new An(g({}),h))}if(!this.aiImpl.createChatResp)throw new Error("generateChatResp not implemented");let u=this.aiImpl.createChatResp(d);if(u.sessionId=r?.sessionId,!u.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(u.modelUsage={ai:this.name,model:e,tokens:m})}return u.modelUsage&&(this.modelUsage=u.modelUsage,this.recordTokenUsage(u.modelUsage)),o?.isRecording()&&(Js(u,o,this.excludeContentFromTrace),o.end()),i&&Ts(u,r?.logger??this.logger),u}async embed(e,t){let n=performance.now(),r=!1,o;try{return o=await this._embed1(e,t),o}catch(i){throw r=!0,i instanceof Error&&(i.message.includes("timeout")||i.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(i.message.includes("abort")||i.name==="AbortError")&&this.recordAbortMetric("embed")),i}finally{let i=performance.now()-n;this.updateLatencyMetrics("embed",i),this.updateErrorMetrics("embed",r),!r&&o&&this.recordEmbedMetrics(e,o)}}async _embed1(e,t){let n=this.getEmbedModel(e.embedModel)??e.embedModel??this.defaults.embedModel;if(!n)throw new Error("No embed model defined");return this.tracer&&await this.tracer?.startActiveSpan("AI Embed Request",{kind:le.SERVER,attributes:{[D.LLM_SYSTEM]:this.name,[D.LLM_OPERATION_NAME]:"embeddings",[D.LLM_REQUEST_MODEL]:n}},t?.traceContext??je.active(),async r=>{try{return await this._embed2(n,e,t,r)}finally{r.end()}}),this._embed2(n,e,t)}async _embed2(e,t,n,r){if(!this.aiImpl.createEmbedReq)throw new Error("generateEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("generateEmbedResp not implemented");let o=this.aiImpl.createEmbedReq,i=n?.debug??this.debug,a={...t,embedModel:e};this.lastUsedEmbedModel=e,i&&Ps(a.texts??[],e,n?.logger??this.logger);let l=async()=>{let[d,u]=await o(a);return await oe({name:d.name,url:this.apiURL,localCall:d.localCall,headers:await this.buildHeaders(d.headers),debug:i,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},u)},p=this.rt?await this.rt(l,{modelUsage:this.embedModelUsage}):await l(),c=this.aiImpl.createEmbedResp?.(p);if(c.sessionId=n?.sessionId,!c.modelUsage){let d=this.aiImpl.getTokenUsage();d&&(c.modelUsage={ai:this.name,model:e,tokens:d})}return this.embedModelUsage=c.modelUsage,this.recordTokenUsage(c.modelUsage),r?.isRecording()&&c.modelUsage?.tokens&&r.addEvent(de.GEN_AI_USAGE,{[D.LLM_USAGE_INPUT_TOKENS]:c.modelUsage.tokens.promptTokens,[D.LLM_USAGE_OUTPUT_TOKENS]:c.modelUsage.tokens.completionTokens??0,[D.LLM_USAGE_TOTAL_TOKENS]:c.modelUsage.tokens.totalTokens}),i&&_s(c.embeddings,n?.logger??this.logger),r?.end(),c}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}};function ll(s,e,t){let n=[];if(s.chatPrompt&&Array.isArray(s.chatPrompt)&&s.chatPrompt.length>0)for(let o of s.chatPrompt)switch(o.role){case"system":if(o.content){let i={};t||(i.content=o.content),e.addEvent(de.GEN_AI_SYSTEM_MESSAGE,i)}break;case"user":if(typeof o.content=="string")n.push(o.content);else if(Array.isArray(o.content))for(let i of o.content)i.type==="text"&&n.push(i.text);break;case"assistant":{let i=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(i&&i.length>0){let a={function_calls:JSON.stringify(i,null,2)};!t&&o.content&&(a.content=o.content),e.addEvent(de.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(de.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:o.functionId};t||(i.content=o.result),e.addEvent(de.GEN_AI_TOOL_MESSAGE,i);break}}let r={};t||(r.content=n.join(`
|
|
110
|
+
`)),e.addEvent(de.GEN_AI_USER_MESSAGE,r)}function Js(s,e,t){if(s.modelUsage?.tokens){let n=s.modelUsage.tokens.thoughtsTokens?{[D.LLM_USAGE_THOUGHTS_TOKENS]:s.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(de.GEN_AI_USAGE,{[D.LLM_USAGE_INPUT_TOKENS]:s.modelUsage.tokens.promptTokens,[D.LLM_USAGE_OUTPUT_TOKENS]:s.modelUsage.tokens.completionTokens??0,[D.LLM_USAGE_TOTAL_TOKENS]:s.modelUsage.tokens.totalTokens,...n})}if(s.results)for(let n=0;n<s.results.length;n++){let r=s.results[n];if(!r||!r.content&&!r.thought&&!r.functionCalls?.length&&!r.finishReason)continue;let o=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),i={};o&&o.length>0?(t||(i.content=r.content),i.tool_calls=o):t||(i.content=r.content??""),e.addEvent(de.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function Yr(s){for(let e=0;e<s.length;e++){let t=s[e];if(!t||typeof t!="object")throw new Error(`AxMessage array validation failed: Item at index ${e} is not a valid message object`);if("content"in t&&typeof t.content=="string"&&t.content.trim()==="")throw new Error(`AxMessage array validation failed: Item at index ${e} has empty content`)}}function pl(s){let e=new Set;for(let t of s){if(e.has(t.key))throw new Error(`Duplicate model key detected: "${t.key}". Each model key must be unique.`);e.add(t.key)}}var Ot=(c=>(c.Claude4Opus="claude-opus-4-20250514",c.Claude4Sonnet="claude-sonnet-4-20250514",c.Claude37Sonnet="claude-3-7-sonnet-latest",c.Claude35Sonnet="claude-3-5-sonnet-latest",c.Claude35Haiku="claude-3-5-haiku-latest",c.Claude3Opus="claude-3-opus-latest",c.Claude3Sonnet="claude-3-sonnet-20240229",c.Claude3Haiku="claude-3-haiku-20240307",c.Claude21="claude-2.1",c.ClaudeInstant12="claude-instant-1.2",c))(Ot||{}),In=(i=>(i.Claude37Sonnet="claude-3-7-sonnet",i.Claude35Haiku="claude-3-5-haiku",i.Claude35Sonnet="claude-3-5-sonnet",i.Claude35SonnetV2="claude-3-5-sonnet-v2",i.Claude3Haiku="claude-3-haiku",i.Claude3Opus="claude-3-opus",i))(In||{});var kt=[{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var Jr=s=>{if(!s||typeof s!="object")return s;let e={...s};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.oneOf,delete e.anyOf,delete e.allOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,Jr(n)]))),e.items&&(e.items=Jr(e.items)),e},Xr=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...L()}),Xs=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...L()}),Qr=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,r=e.modelConfig?.stream??this.config.stream,o;this.isVertex?o={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:o={name:"/messages"};let i;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":i={tool_choice:{type:"auto"}};break;case"required":i={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)i={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.filter(y=>y.role==="system").map(y=>({type:"text",text:y.content,...y.cache?{cache:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(y=>y.role!=="system"),p=cl(l),c=e.functions?.map(y=>({name:y.name,description:y.description,input_schema:y.parameters?Jr(y.parameters):void 0})),d=e.modelConfig?.maxTokens??this.config.maxTokens,u=e.modelConfig?.stopSequences??this.config.stopSequences,m=e.modelConfig?.temperature??this.config.temperature,g=e.modelConfig?.topP??this.config.topP,h=e.modelConfig?.topK??this.config.topK,A=e.modelConfig?.n??this.config.n;if(A&&A>1)throw new Error("Anthropic does not support sampling (n > 1)");let f;if(this.config.thinking?.budget_tokens&&(f=this.config.thinking),t?.thinkingTokenBudget){let y=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":f=void 0;break;case"minimal":f={type:"enabled",budget_tokens:y?.minimal??1024};break;case"low":f={type:"enabled",budget_tokens:y?.low??5e3};break;case"medium":f={type:"enabled",budget_tokens:y?.medium??1e4};break;case"high":f={type:"enabled",budget_tokens:y?.high??2e4};break;case"highest":f={type:"enabled",budget_tokens:y?.highest??32e3};break}}let x={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...d?{max_tokens:d}:{},...u&&u.length>0?{stop_sequences:u}:{},...m&&!f?{temperature:m}:{},...g&&(!f||g>=.95)?{top_p:g}:{},...h&&!f?{top_k:h}:{},...i,...c&&c.length>0?{tools:c}:{},...r?{stream:!0}:{},...a?{system:a}:{},...f?{thinking:f}:{},messages:p};return[o,x]};createChatResp=e=>{if(e.type==="error")throw new U(e.error.message,void 0,void 0);let t=Qs(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r=e.content.map((o,i)=>o.type==="tool_use"?{index:i,id:o.id,functionCalls:[{id:o.id,type:"function",function:{name:o.name,params:o.input}}],finishReason:t}:(o.type==="thinking"||o.type==="redacted_thinking")&&n?{index:i,thought:o.thinking,id:e.id,finishReason:t}:{index:i,content:o.type==="text"?o.text:"",id:e.id,finishReason:t}).filter(o=>o.content!==""||o.thought!==void 0||o.functionCalls!==void 0);return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens},{results:r,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:o}=e;throw new U(o.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:o}=e,i=[{index:r,content:"",id:o.id}];return this.tokensUsed={promptTokens:o.usage?.input_tokens??0,completionTokens:o.usage?.output_tokens??0,totalTokens:(o.usage?.input_tokens??0)+(o.usage?.output_tokens??0)},{results:i}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text")return{results:[{index:r,content:o.text}]};if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking}]}:{results:[{index:r,content:""}]};if(o.type==="tool_use"&&typeof o.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=o.id;let i=[{id:o.id,type:"function",function:{name:o.name,params:""}}];return{results:[{index:r,functionCalls:i}]}}}if(e.type==="content_block_delta"){let{delta:o}=e;if(o.type==="text_delta")return{results:[{index:r,content:o.text}]};if(o.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,content:""}]};if(o.type==="input_json_delta"){let i=n.indexIdMap[e.index];if(!i)throw new Error(`invalid streaming index no id found: ${e.index}`);let a=[{id:i,type:"function",function:{name:"",params:o.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:o,usage:i}=e;return this.tokensUsed={promptTokens:0,completionTokens:i.output_tokens,totalTokens:i.output_tokens},{results:[{index:r,content:"",finishReason:Qs(o.stop_reason)}]}}return{results:[{index:r,content:""}]}}},He=class s extends j{static create(e){return new s(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:o,models:i}){let a=t!==void 0&&n!==void 0,l,p;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");if(typeof e!="function")throw new Error("Anthropic Vertex API key must be a function for token-based authentication");l=`https://${n}-aiplatform.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,p=async()=>({Authorization:`Bearer ${await e()}`})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",p=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"prompt-caching-2024-07-31","x-api-key":typeof e=="function"?await e():e})}let c={...Xr(),...r},d=new Qr(c,a),u=m=>{let g=ie({model:m,modelInfo:kt,models:i});return{functions:!0,streaming:!0,hasThinkingBudget:g?.hasThinkingBudget??!1,hasShowThoughts:g?.hasShowThoughts??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"]},thinking:g?.hasThinkingBudget??!1,multiTurn:!0}};super(d,{name:"Anthropic",apiURL:l,headers:p,modelInfo:kt,defaults:{model:c.model},options:o,supportFor:u,models:i})}};function cl(s){let e=s.map(t=>{switch(t.role){case"function":return{role:"user",content:[{type:"tool_result",content:t.result,tool_use_id:t.functionId,...t.isError?{is_error:!0}:{},...t.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof t.content=="string"?{role:"user",content:t.content}:{role:"user",content:t.content.map(r=>{switch(r.type){case"text":return{type:"text",text:r.text,...r.cache?{cache:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:r.mimeType,data:r.image},...r.cache?{cache:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let n="";return typeof t.content=="string"&&(n=t.content),typeof t.functionCalls<"u"&&(n=t.functionCalls.map(r=>{let o={};return typeof r.function.params=="string"?o=JSON.parse(r.function.params):typeof r.function.params=="object"&&(o=r.function.params),{type:"tool_use",id:r.id,name:r.function.name,input:o,...t.cache?{cache:{type:"ephemeral"}}:{}}})),{role:"assistant",content:n}}default:throw new Error("Invalid role")}});return ul(e)}function ul(s){let e=[];for(let[t,n]of s.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&s.at(t-1)?.role==="assistant"){let r=e.pop();e.push({...r||{},...n})}else e.push(n)}return e}function Qs(s){if(s)switch(s){case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"function_call";case"end_turn":return"stop";default:return"stop"}}var Et=(f=>(f.GPT4="gpt-4",f.GPT41="gpt-4.1",f.GPT41Mini="gpt-4.1-mini",f.GPT4O="gpt-4o",f.GPT4OMini="gpt-4o-mini",f.GPT4ChatGPT4O="chatgpt-4o-latest",f.GPT4Turbo="gpt-4-turbo",f.GPT35Turbo="gpt-3.5-turbo",f.GPT35TurboInstruct="gpt-3.5-turbo-instruct",f.GPT35TextDavinci002="text-davinci-002",f.GPT3TextBabbage002="text-babbage-002",f.GPT3TextAda001="text-ada-001",f.O1="o1",f.O1Mini="o1-mini",f.O3="o3",f.O3Mini="o3-mini",f.O4Mini="o4-mini",f))(Et||{}),Ke=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Ke||{});var Ve=(y=>(y.GPT4="gpt-4",y.GPT41="gpt-4.1",y.GPT41Mini="gpt-4.1-mini",y.GPT4O="gpt-4o",y.GPT4OMini="gpt-4o-mini",y.GPT4ChatGPT4O="chatgpt-4o-latest",y.GPT4Turbo="gpt-4-turbo",y.GPT35Turbo="gpt-3.5-turbo",y.GPT35TurboInstruct="gpt-3.5-turbo-instruct",y.GPT35TextDavinci002="text-davinci-002",y.GPT3TextBabbage002="text-babbage-002",y.GPT3TextAda001="text-ada-001",y.O1Pro="o1-pro",y.O1="o1",y.O1Mini="o1-mini",y.O3Pro="o3-pro",y.O3="o3",y.O3Mini="o3-mini",y.O4Mini="o4-mini",y))(Ve||{});var We=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],bn=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,hasThinkingBudget:!0,hasShowThoughts:!0,isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,hasThinkingBudget:!0,hasShowThoughts:!0,isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,hasThinkingBudget:!0,hasShowThoughts:!0}];var dl=s=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(s)||e.includes(s)},De=()=>structuredClone({model:"gpt-4.1",embedModel:"text-embedding-3-small",...L()}),Rn=()=>structuredClone({...De(),model:"gpt-4.1"}),Cn=()=>structuredClone({model:"gpt-4.1",embedModel:"text-embedding-3-small",...W()}),Tn=()=>({...De(),model:"gpt-4.1-mini"}),Zr=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq(e,t){let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r={name:"/chat/completions"},o=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),i=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=ml(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,p=e.modelConfig?.stream??this.config.stream,c=this.config.store,d=dl(n),u={model:n,messages:a,response_format:this.config?.responseFormat?{type:this.config.responseFormat}:void 0,tools:o,tool_choice:i,...d?{}:{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.temperature,top_p:e.modelConfig?.topP??this.config.topP??1,n:e.modelConfig?.n??this.config.n,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...l?{frequency_penalty:l}:{}},stop:e.modelConfig?.stopSequences??this.config.stop,logit_bias:this.config.logitBias,...p&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...c?{store:c}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(u.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(u.web_search_options={...this.config.webSearchOptions.searchContextSize&&{search_context_size:this.config.webSearchOptions.searchContextSize},...this.config.webSearchOptions.userLocation&&{user_location:{approximate:{type:"approximate",...this.config.webSearchOptions.userLocation.approximate.city&&{city:this.config.webSearchOptions.userLocation.approximate.city},...this.config.webSearchOptions.userLocation.approximate.country&&{country:this.config.webSearchOptions.userLocation.approximate.country},...this.config.webSearchOptions.userLocation.approximate.region&&{region:this.config.webSearchOptions.userLocation.approximate.region},...this.config.webSearchOptions.userLocation.approximate.timezone&&{timezone:this.config.webSearchOptions.userLocation.approximate.timezone}}}}}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":u.reasoning_effort=void 0;break;case"minimal":u.reasoning_effort="low";break;case"low":u.reasoning_effort="medium";break;case"medium":u.reasoning_effort="high";break;case"high":u.reasoning_effort="high";break;case"highest":u.reasoning_effort="high";break}return this.chatReqUpdater&&(u=this.chatReqUpdater(u)),[r,u]}createEmbedReq(e){let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]}createChatResp(e){let{id:t,usage:n,choices:r,error:o}=e;if(o)throw o;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:r.map(a=>{if(a.message.refusal)throw new U(a.message.refusal,e.model,e.id);let l=Zs(a.finish_reason),p=a.message.tool_calls?.map(({id:c,function:{arguments:d,name:u}})=>({id:c,type:"function",function:{name:u,params:d}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,annotations:a.message.annotations,functionCalls:p,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:o}=e;this.tokensUsed=r?{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}:void 0;let i=t;return i.indexIdMap||(i.indexIdMap={}),{results:o.map(({index:l,delta:{content:p,role:c,refusal:d,tool_calls:u,reasoning_content:m,annotations:g},finish_reason:h})=>{if(d)throw new U(d,void 0,n);let A=Zs(h),f=u?.map(({id:x,index:y,function:{name:k,arguments:b}})=>{typeof x=="string"&&typeof y=="number"&&!i.indexIdMap[y]&&(i.indexIdMap[y]=x);let T=i.indexIdMap[y];return T?{id:T,type:"function",function:{name:k,params:b}}:null}).filter(x=>x!==null);return{index:l,content:p??void 0,role:c,thought:m,annotations:g,functionCalls:f,finishReason:A,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(r=>r.embedding)}}},Zs=s=>{switch(s){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function ml(s){return s.chatPrompt.map(t=>{switch(t.role){case"system":return{role:"system",content:t.content};case"user":{let n=Array.isArray(t.content)?t.content.map(r=>{switch(r.type){case"text":return{type:"text",text:r.text};case"image":return{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.image}`,details:r.details??"auto"}};case"audio":return{type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}};default:throw new Error("Invalid content type")}}):t.content;return{role:"user",...t.name?{name:t.name}:{},content:n}}case"assistant":{let n=t.functionCalls?.map(r=>({id:r.id,type:"function",function:{name:r.function.name,arguments:typeof r.function.params=="object"?JSON.stringify(r.function.params):r.function.params}}));if(n&&n.length>0)return{role:"assistant",...t.content?{content:t.content}:{},name:t.name,tool_calls:n};if(t.content===void 0)throw new Error("Assistant content is required when no tool calls are provided");return{role:"assistant",content:t.content,...t.name?{name:t.name}:{}}}case"function":return{role:"tool",content:t.result,tool_call_id:t.functionId};default:throw new Error("Invalid role")}})}var K=class extends j{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o,models:i,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let p=new Zr(t,n?.streamingUsage??!0,a);super(p,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:i})}},Ye=class extends K{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...We,...o??[]];let i=a=>{let l=ie({model:a,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.hasThinkingBudget??!1,hasShowThoughts:l?.hasShowThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","ogg"],maxDuration:25*60},files:{supported:!0,formats:["text/plain","application/pdf","image/jpeg","image/png"],maxSize:512*1024*1024,uploadMethod:"upload"},urls:{supported:!1,webSearch:!0,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:l?.hasThinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:{...De(),...t},options:n,modelInfo:o,models:r,supportFor:i}),super.setName("OpenAI")}};var eo=De,ei=Cn,ti=Tn,ni=Rn,Je=class extends K{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:o,options:i,models:a,modelInfo:l}){if(!e||e==="")throw new Error("Azure OpenAPI API key not set");if(!t||t==="")throw new Error("Azure OpenAPI resource name not set");if(!n||n==="")throw new Error("Azure OpenAPI deployment id not set");let p={...eo(),...o};l=[...We,...l??[]];let c=u=>{let m=ie({model:u,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:m?.hasThinkingBudget??!1,hasShowThoughts:m?.hasShowThoughts??!1,functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:m?.hasThinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:p,options:i,models:a,modelInfo:l,supportFor:c});let d=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${r}`,d).href),super.setHeaders(async()=>({"api-key":e}))}};var wn=class s{services;currentServiceIndex=0;currentService;debug;initialBackoffMs;maxBackoffMs;maxRetries;serviceFailures=new Map;constructor(e,t){if(e.length===0)throw new Error("No AI services provided.");gl(e),this.services=[...e].sort(t?.comparator??s.metricComparator);let n=this.services[this.currentServiceIndex];if(n===void 0)throw new Error("Error initializing the AI services.");this.currentService=n,this.debug=t?.debug??!0,this.initialBackoffMs=t?.initialBackoffMs??1e3,this.maxBackoffMs=t?.maxBackoffMs??32e3,this.maxRetries=t?.maxRetries??3}static create(e,t){return new s(e,t)}getLastUsedChatModel(){return this.currentService.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.currentService.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.currentService.getLastUsedModelConfig()}static inputOrderComparator=()=>0;static metricComparator=(e,t)=>{let n=e.getMetrics(),r=t.getMetrics();return n.latency.chat.mean-r.latency.chat.mean};getModelList(){return this.currentService.getModelList()}getNextService(){let e=this.services[++this.currentServiceIndex];return e===void 0?!1:(this.currentService=e,!0)}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){return this.currentService.getFeatures(e)}getMetrics(){return this.currentService.getMetrics()}canRetryService(){let e=this.serviceFailures.get(this.currentService.getId());if(!e)return!0;let{retries:t,lastFailureTime:n}=e,r=Date.now()-n,o=Math.min(this.initialBackoffMs*2**t,this.maxBackoffMs);return r>=o}handleFailure(){let t=(this.serviceFailures.get(this.currentService.getId())?.retries??0)+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:t,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${t}/${this.maxRetries})`),t>=this.maxRetries){let n=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`),n}return!0}handleSuccess(){this.serviceFailures.delete(this.currentService.getId())}async chat(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.chat(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof re))throw n;switch(n.constructor){case we:throw n;case _e:break;case fe:break;case Ie:break;case ce:break;case Fe:break;default:throw n}if(!this.handleFailure())throw n}}}async embed(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.embed(e,t);return this.handleSuccess(),n}catch(n){if(!this.handleFailure())throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function gl(s){let e=s.find(r=>r.getModelList()!==void 0);if(!e)return;let t=e.getModelList();if(!t)throw new Error("No model list found in any service.");let n=new Set(t.map(r=>r.key));for(let r=0;r<s.length;r++){let o=s[r];if(!o)throw new Error(`Service at index ${r} is undefined`);let i=o.getModelList();if(!i)throw new Error(`Service at index ${r} (${o.getName()}) has no model list while another service does.`);let a=new Set(i.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${r} (${o.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${r} (${o.getName()}) has extra model "${l}"`)}}function $e(s){let e=!1,t=!1,n=!1,r=!1,o=!1,i=!1,a=!1,l=new Set,p=0;if(s.chatPrompt&&Array.isArray(s.chatPrompt))for(let c of s.chatPrompt){if(c.role==="user"&&Array.isArray(c.content))for(let d of c.content)switch(l.add(d.type),d.type){case"image":e=!0,d.cache&&(a=!0),p+=85;break;case"audio":t=!0,d.cache&&(a=!0),p+=d.duration||60;break;case"file":n=!0,d.cache&&(a=!0),p+=Math.ceil((d.extractedText?.length||1e3)/4);break;case"url":r=!0,d.cache&&(a=!0),p+=Math.ceil((d.cachedContent?.length||2e3)/4);break;case"text":d.cache&&(a=!0),p+=Math.ceil(d.text.length/4);break}else"content"in c&&typeof c.content=="string"&&(p+=Math.ceil(c.content.length/4));"cache"in c&&c.cache&&(a=!0)}return s.functions&&s.functions.length>0&&(o=!0),s.modelConfig?.stream===!0&&(i=!0),s.capabilities&&(s.capabilities.requiresImages&&(e=!0),s.capabilities.requiresAudio&&(t=!0),s.capabilities.requiresFiles&&(n=!0),s.capabilities.requiresWebSearch&&(r=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r,requiresFunctions:o,requiresStreaming:i,requiresCaching:a,contentTypes:l,estimatedTokens:p}}function to(s,e){let t=s.getFeatures(),n=[],r=[],o=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),o.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),o.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),o.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),o.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),o.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),o.push("Repeated content will not be cached")),e.hasImages&&t.media.images.supported){let a=t.media.images.maxSize;a&&a<10*1024*1024&&r.push(`Image size limit is ${Math.round(a/(1024*1024))}MB`)}if(e.hasAudio&&t.media.audio.supported){let a=t.media.audio.maxDuration;a&&a<600&&r.push(`Audio duration limit is ${Math.round(a/60)} minutes`)}return{isSupported:n.length===0,missingCapabilities:n,warnings:r,alternatives:o}}function vn(s,e){return s.map(t=>{let n=t.getFeatures(),r=to(t,e),o=0,i=[];return o+=10,e.hasImages&&n.media.images.supported&&(o+=25,i.push("Images"),n.media.images.detailLevels?.includes("high")&&(o+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(o+=3)),e.hasAudio&&n.media.audio.supported&&(o+=25,i.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(o+=5)),e.hasFiles&&n.media.files.supported&&(o+=25,i.push("Files"),n.media.files.uploadMethod==="cloud"&&(o+=3)),e.hasUrls&&n.media.urls.supported&&(o+=25,i.push("URLs"),n.media.urls.webSearch&&(o+=5)),e.requiresFunctions&&n.functions&&(o+=15,i.push("Functions"),n.functionCot&&(o+=3)),e.requiresStreaming&&n.streaming&&(o+=10,i.push("Streaming")),e.requiresCaching&&n.caching.supported&&(o+=8,i.push("Caching"),n.caching.types.includes("persistent")&&(o+=3)),n.thinking&&(o+=2),n.multiTurn&&(o+=2),n.hasThinkingBudget&&(o+=1),n.hasShowThoughts&&(o+=1),o-=r.missingCapabilities.length*10,{provider:t,score:o,missingCapabilities:r.missingCapabilities,supportedCapabilities:i}}).sort((t,n)=>n.score-t.score)}function Sn(s,e,t={}){if(e.length===0)throw new Error("No providers available");let n=$e(s),r=vn(e,n);if(t.requireExactMatch){let o=r.filter(i=>i.missingCapabilities.length===0);if(o.length===0)throw new Error(`No providers fully support the request requirements: ${r[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return o[0].provider}if(!t.allowDegradation){let o=r[0];if(o.missingCapabilities.length>0)throw new Error(`Best available provider (${o.provider.getName()}) is missing: ${o.missingCapabilities.join(", ")}`)}return r[0].provider}function ri(s,e){let t=$e(s),n=vn(e,t),r=n[0]?.provider||null,o=[t.hasImages&&"images",t.hasAudio&&"audio",t.hasFiles&&"files",t.hasUrls&&"URLs",t.requiresFunctions&&"functions",t.requiresStreaming&&"streaming",t.requiresCaching&&"caching"].filter(Boolean).length,i=r?n[0].supportedCapabilities.length:0,a=r?`${r.getName()} supports ${i}/${o} requirements (${Math.round(i/Math.max(o,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function oi(s,e){return s.filter(t=>t.getFeatures().media[e].supported)}function si(s,e){let t={};for(let n of s){let o=n.getFeatures().media[e];if(o.supported)for(let i of o.formats)t[i]||(t[i]=[]),t[i].push(n)}return t}var Pt=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Pt||{}),_t=(r=>(r.EmbedEnglishV30="embed-english-v3.0",r.EmbedEnglishLightV30="embed-english-light-v3.0",r.EmbedMultiLingualV30="embed-multilingual-v3.0",r.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",r))(_t||{});var Mn=[{name:"command-r-plus",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"command-r",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command-light",currency:"usd",promptTokenCostPer1M:.3,completionTokenCostPer1M:.6},{name:"embed-english-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-english-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1}];var ro=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...L()}),ai=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...W()}),no=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,frequencyPenalty:e.frequencyPenalty,presencePenalty:e.presencePenalty,endSequences:e.endSequences,stopSequences:e.stopSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.at(-1),r=e.chatPrompt.slice(0,-1),o;n&&n.role==="user"&&typeof n.content=="string"&&(o=n?.content);let i=hl(r),a=e.functions?.map(d=>{let u={};if(d.parameters?.properties)for(let[m,g]of Object.entries(d.parameters.properties))u[m]={description:g.description,type:g.type,required:d.parameters.required?.includes(m)??!1};return{name:d.name,description:d.description,parameter_definitions:u}}),l=e.chatPrompt.filter(d=>d.role==="function").map(d=>{let u=a?.find(m=>m.name===d.functionId);if(!u)throw new Error("Function not found");return{call:{name:u.name,parameters:u.parameter_definitions},outputs:[{result:d.result??""}]}}),p={name:"/chat"},c={message:o,model:t,tools:a,...l&&!o?{tool_results:l}:{},chat_history:i,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.temperature,k:e.modelConfig?.topK??this.config.topK,p:e.modelConfig?.topP??this.config.topP,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,end_sequences:this.config.endSequences,stop_sequences:e.modelConfig?.stopSequences??this.config.stopSequences};return[p,c]}createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embed"},r={model:t,texts:e.texts??[],input_type:"classification",truncate:""};return[n,r]};createChatResp=e=>{this.tokensUsed=e.meta.billed_units?{promptTokens:e.meta.billed_units.input_tokens,completionTokens:e.meta.billed_units.output_tokens,totalTokens:e.meta.billed_units.input_tokens+e.meta.billed_units.output_tokens}:void 0;let t;if("finish_reason"in e)switch(e.finish_reason){case"COMPLETE":t="stop";break;case"MAX_TOKENS":t="length";break;case"ERROR":throw new Error("Finish reason: ERROR");case"ERROR_TOXIC":throw new Error("Finish reason: CONTENT_FILTER");default:t="stop";break}let n;return"tool_calls"in e&&(n=e.tool_calls?.map(o=>({id:o.name,type:"function",function:{name:o.name,params:o.parameters}}))),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}};createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:e.meta.billed_units?.output_tokens??0,totalTokens:e.meta.billed_units?.output_tokens??0};let{results:r}=this.createChatResp(e),o=r[0];if(!o)throw new Error("No result");return o.id=n.generation_id??"",{results:r}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},Qe=class extends j{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...ro(),...t},i=new no(o);super(i,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Mn,defaults:{model:o.model},supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[],maxSize:0,detailLevels:[]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},options:n,models:r})}};function hl(s){return s.map(e=>{let t="";if(e.role==="system"||e.role==="assistant"||e.role==="user")if(typeof e.content=="string")t=e.content;else throw new Error("Multi-modal content not supported");switch(e.role){case"user":return{role:"USER",message:t};case"system":return{role:"SYSTEM",message:t};case"assistant":{let n=ii(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=s.map(i=>{if(i.role==="assistant")return i.functionCalls?.find(a=>a.id===e.functionId)}).filter(i=>i!==void 0),r=ii(n)?.at(0);if(!r)throw new Error("Function call not found");let o=[{result:e.result}];return{role:"TOOL",tool_results:[{call:r,outputs:o}]}}default:throw new Error("Unknown role")}})}function ii(s){return s?.map(e=>{let t=typeof e.function.params=="string"?JSON.parse(e.function.params):e.function.params;return{name:e.function.name,parameters:t}})}var Ft=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Ft||{});var On=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var oo=()=>structuredClone({model:"deepseek-chat",...L()}),li=()=>structuredClone({model:"deepseek-coder",...W()}),Xe=class extends K{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...oo(),...t};o=[...On,...o??[]],super({apiKey:e,config:i,options:n,apiURL:"https://api.deepseek.com",modelInfo:o,supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r}),super.setName("DeepSeek")}};var Dt=(c=>(c.Gemini25Pro="gemini-2.5-pro",c.Gemini25Flash="gemini-2.5-flash",c.Gemini25FlashLite="gemini-2.5-flash-lite",c.Gemini20Flash="gemini-2.0-flash",c.Gemini20FlashLite="gemini-2.0-flash-lite",c.Gemini1Pro="gemini-1.0-pro",c.Gemini15Flash="gemini-1.5-flash",c.Gemini15Flash002="gemini-1.5-flash-002",c.Gemini15Flash8B="gemini-1.5-flash-8b",c.Gemini15Pro="gemini-1.5-pro",c))(Dt||{}),kn=(r=>(r.GeminiEmbedding="gemini-embedding-exp",r.TextEmbeddingLarge="text-embedding-large-exp-03-07",r.TextEmbedding004="text-embedding-004",r.TextEmbedding005="text-embedding-005",r))(kn||{}),En=(r=>(r.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",r.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",r.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",r.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",r))(En||{}),Pn=(o=>(o.BlockNone="BLOCK_NONE",o.BlockOnlyHigh="BLOCK_ONLY_HIGH",o.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",o.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",o.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",o))(Pn||{}),so=(l=>(l.SemanticSimilarity="SEMANTIC_SIMILARITY",l.Classification="CLASSIFICATION",l.Clustering="CLUSTERING",l.RetrievalDocument="RETRIEVAL_DOCUMENT",l.RetrievalQuery="RETRIEVAL_QUERY",l.QuestionAnswering="QUESTION_ANSWERING",l.FactVerification="FACT_VERIFICATION",l.CodeRetrievalQuery="CODE_RETRIEVAL_QUERY",l))(so||{});var _n=[{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5}];var io=s=>{if(!s||typeof s!="object")return s;let e={...s};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.maximum,delete e.oneOf,delete e.anyOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,io(n)]))),e.items&&(e.items=io(e.items)),e},pi=[{category:"HARM_CATEGORY_HARASSMENT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"BLOCK_NONE"}],lo=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:pi,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...L()}),ci=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:pi,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...W()}),ao=class{constructor(e,t,n,r,o){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=o;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o;if(this.endpointId?o={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:o={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let h=r?"&":"?",A=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${h}key=${A}`}let i=e.chatPrompt.filter(h=>h.role==="system").map(h=>h.content),a=i.length>0?{role:"user",parts:[{text:i.join(" ")}]}:void 0,l=e.chatPrompt.filter(h=>h.role!=="system").map((h,A)=>{switch(h.role){case"user":return{role:"user",parts:Array.isArray(h.content)?h.content.map((x,y)=>{switch(x.type){case"text":return{text:x.text};case"image":return{inlineData:{mimeType:x.mimeType,data:x.image}};default:throw new Error(`Chat prompt content type not supported (index: ${y})`)}}):[{text:h.content}]};case"assistant":{let f=[];if(h.functionCalls){if(f=h.functionCalls.map(x=>{let y=typeof x.function.params=="string"?JSON.parse(x.function.params):x.function.params;return{functionCall:{name:x.function.name,args:y}}}),!f)throw new Error("Function call is empty");return{role:"model",parts:f}}if(!h.content)throw new Error("Assistant content is empty");return f=[{text:h.content}],{role:"model",parts:f}}case"function":{if(!("functionId"in h))throw new Error(`Chat prompt functionId is empty (index: ${A})`);return{role:"user",parts:[{functionResponse:{name:h.functionId,response:{result:h.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(h)} (index: ${A})`)}}),p=[];if(e.functions&&e.functions.length>0){let h=e.functions.map(A=>({...A,parameters:A.parameters?io(A.parameters):void 0}));p.push({function_declarations:h})}this.options?.codeExecution&&p.push({code_execution:{}}),this.options?.googleSearchRetrieval&&p.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&p.push({google_search:{}}),this.options?.urlContext&&p.push({url_context:{}}),p.length===0&&(p=void 0);let c;if(e.functionCall)if(e.functionCall==="none")c={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")c={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")c={function_calling_config:{mode:"ANY"}};else{let h=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};c={function_calling_config:{mode:"ANY"},...h}}else p&&p.length>0&&(c={function_calling_config:{mode:"AUTO"}});let d={};if(this.config.thinking?.includeThoughts&&(d.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(d.thinkingBudget=this.config.thinking.thinkingTokenBudget),t?.thinkingTokenBudget){let h=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":d.thinkingBudget=0,d.includeThoughts=!1;break;case"minimal":d.thinkingBudget=h?.minimal??200;break;case"low":d.thinkingBudget=h?.low??800;break;case"medium":d.thinkingBudget=h?.medium??5e3;break;case"high":d.thinkingBudget=h?.high??1e4;break;case"highest":d.thinkingBudget=h?.highest??24500;break}}t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(d.includeThoughts=t.showThoughts);let u={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.temperature,topP:e.modelConfig?.topP??this.config.topP,topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain",...Object.keys(d).length>0?{thinkingConfig:d}:{}},m=this.config.safetySettings;return[o,{contents:l,tools:p,toolConfig:c,systemInstruction:a,generationConfig:u,safetySettings:m}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,r;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},r={instances:e.texts.map(o=>({content:o,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let o=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${o}`},r={requests:e.texts.map(i=>({model:`models/${t}`,content:{parts:[{text:i}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t=e.candidates?.map(n=>{let r={index:0};switch(n.finishReason){case"MAX_TOKENS":r.finishReason="length";break;case"STOP":r.finishReason="stop";break;case"SAFETY":throw new U("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new U("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new U("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new U("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new U("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new U("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new U("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new U("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new U("Other finish reason",void 0,void 0)}if(!n.content||!n.content.parts)return r;for(let o of n.content.parts){if("text"in o){"thought"in o&&o.thought?r.thought=o.text:r.content=o.text;continue}"functionCall"in o&&(r.functionCalls=[{id:ne(),type:"function",function:{name:o.functionCall.name,params:o.functionCall.args}}])}return r});return e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount}),{results:t}};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}}},Ze=class s extends j{static create(e){return new s(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:o,options:i,models:a,modelInfo:l}){let p=t!==void 0&&n!==void 0,c,d;if(p){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let h;r?h="endpoints":h="publishers/google",c=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${h}`,d=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");c="https://generativelanguage.googleapis.com/v1beta",d=async()=>({})}let u={...lo(),...o},m=new ao(u,p,r,e,i);l=[..._n,...l??[]];let g=h=>{let A=ie({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:A?.hasThinkingBudget??!1,hasShowThoughts:A?.hasShowThoughts??!1,functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","aac","ogg"],maxDuration:9.5*60},files:{supported:!0,formats:["application/pdf","text/plain","text/csv","text/html","text/xml"],maxSize:2*1024*1024*1024,uploadMethod:"cloud"},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:!1,types:[]},thinking:A?.hasThinkingBudget??!1,multiTurn:!0}};super(m,{name:"GoogleGeminiAI",apiURL:c,headers:d,modelInfo:l,defaults:{model:u.model,embedModel:u.embedModel},options:i,supportFor:g,models:a})}};var fl=new Z,et=class{options;maxTokens;refillRate;currentTokens;lastRefillTime;constructor(e,t,n){this.maxTokens=e,this.refillRate=t,this.currentTokens=e,this.lastRefillTime=Date.now(),this.options=n}refillTokens(){let e=Date.now(),n=(e-this.lastRefillTime)/1e3*this.refillRate;this.currentTokens=Math.min(this.maxTokens,this.currentTokens+n),this.lastRefillTime=e}async waitUntilTokensAvailable(e){if(this.refillTokens(),this.currentTokens>=e){this.currentTokens-=e;return}return this.options?.debug&&console.log(fl.red(`Rate limiter: Waiting for ${e-this.currentTokens} tokens`)),await new Promise(t=>setTimeout(t,100)),this.waitUntilTokensAvailable(e)}async acquire(e){await this.waitUntilTokensAvailable(e)}};var $t=(r=>(r.Llama3_8B="llama3-8b-8192",r.Llama33_70B="llama-3.3-70b-versatile",r.Mixtral_8x7B="mixtral-8x7b-32768",r.Gemma2_9B="gemma2-9b-it",r))($t||{});var Fn=[{name:"gemma2-9b-it",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.2,completionTokenCostPer1M:.2},{name:"llama-3.3-70b-versatile",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.59,completionTokenCostPer1M:.79},{name:"llama3-8b-8192",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.05,completionTokenCostPer1M:.08},{name:"mixtral-8x7b-32768",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.24,completionTokenCostPer1M:.24}];var Al=()=>structuredClone({model:"llama-3.3-70b-versatile",...L()}),tt=class extends K{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let i={...Al(),...t},a={...n,streamingUsage:!1};o=[...Fn,...o??[]];let l={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:i,options:a,modelInfo:o,apiURL:"https://api.groq.com/openai/v1",models:r,supportFor:l}),super.setName("Groq"),this.setOptions(a)}setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})};newRateLimiter=e=>{if(e?.rateLimiter)return e.rateLimiter;let t=e?.tokensPerMinute??4800,n=new et(t,t/60,{debug:e?.debug});return async(o,i)=>{let a=i.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await o()}}};var Dn=[];var $n=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))($n||{});var co=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...L()}),ui=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...W()}),po=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,n:e.n,presencePenalty:e.presencePenalty}}createChatReq=e=>{let t=e.model,n=e.functions?`Functions:
|
|
109
111
|
${JSON.stringify(e.functions,null,2)}
|
|
110
|
-
`:"",
|
|
111
|
-
`);return
|
|
112
|
+
`:"",r=e.chatPrompt?.map(l=>{switch(l.role){case"user":return`User: ${l.content}`;case"system":return`System: ${l.content}`;case"function":return`Function Result: ${l.result}`;case"assistant":{let p=l.functionCalls?.map(c=>{let d=typeof c.function.params=="string"?c.function.params:JSON.stringify(c.function.params);return`${c.function.name}(${d})`}).join(`
|
|
113
|
+
`);return p?`Assistant: ${l.content}
|
|
112
114
|
Functions:
|
|
113
|
-
${
|
|
114
|
-
`),r=`${n} ${o}`.trim(),i={name:"/models"},a={model:t,inputs:r,parameters:{max_new_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,repetition_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,temperature:e.modelConfig?.temperature??this.config.temperature,top_p:e.modelConfig?.topP??this.config.topP,top_k:e.modelConfig?.topK??this.config.topK,return_full_text:this.config.returnFullText,num_return_sequences:this.config.n,do_sample:this.config.doSample,max_time:this.config.maxTime},options:{use_cache:this.config.useCache,wait_for_model:this.config.waitForModel}};return[i,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},Ze=class extends K{constructor({apiKey:e,config:t,options:n,models:o}){if(!e||e==="")throw new Error("HuggingFace API key not set");let r={...Wo(),...t},i=new Vo(r);super(i,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Cn,defaults:{model:r.model},options:n,supportFor:{functions:!1,streaming:!1},models:o})}};var _t=(l=>(l.Mistral7B="open-mistral-7b",l.Mistral8x7B="open-mixtral-8x7b",l.MistralSmall="mistral-small-latest",l.MistralNemo="mistral-nemo-latest",l.MistralLarge="mistral-large-latest",l.Codestral="codestral-latest",l.OpenCodestralMamba="open-codestral-mamba",l.OpenMistralNemo="open-mistral-nemo-latest",l))(_t||{}),Yo=(e=>(e.MistralEmbed="mistral-embed",e))(Yo||{});var wn=[{name:"open-mistral-7b",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mixtral-8x7b",currency:"USD",promptTokenCostPer1M:.7,completionTokenCostPer1M:.7},{name:"mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.15,completionTokenCostPer1M:.15},{name:"mistral-small-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"mistral-large-latest",currency:"USD",promptTokenCostPer1M:2,completionTokenCostPer1M:6},{name:"codestral-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"open-codestral-mamba",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.3}];var vn=()=>structuredClone({model:"mistral-small-latest",...L(),topP:1}),Ys=()=>structuredClone({...vn(),model:"mistral-large-latest"}),Xe=class extends V{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Mistral API key not set");let i={...vn(),...t};r=[...wn,...r??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1},l=c=>{let{max_completion_tokens:p,messages:d,...u}=c;return{...u,messages:this.updateMessages(d),max_tokens:p}};super({apiKey:e,config:i,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:r,models:o,supportFor:a,chatReqUpdater:l}),super.setName("Mistral")}updateMessages(e){let t=[];if(!Array.isArray(e))return e;for(let n of e)if(n.role==="user"&&Array.isArray(n.content)){let o=n.content.map(r=>typeof r=="object"&&r!==null&&"image_url"in r?{type:"image_url",image_url:{url:r.image_url?.url}}:r);t.push({...n,content:o})}else t.push(n);return t}};var Sn=class{constructor(e={}){this.config=e;this.config.id=this.config.id??se()}metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getLastUsedChatModel(){return this.config.modelInfo?.name??"mock-model"}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??"mock-embed-model"}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??"mock-ai-service"}getId(){return this.config.id??"mock-ai-service-id"}getFeatures(e){return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1}}getModelList(){return this.config.models}getMetrics(){return this.metrics}async chat(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock chat error");return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):this.config.chatResponse??{results:[{index:0,content:"Mock response",finishReason:"stop"}],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock embed error");return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((o,r)=>o+r,0)/n.length,n.length>0){let o=[...n].sort((a,l)=>a-l),r=Math.max(0,Math.floor(o.length*.95)-1);this.metrics.latency[e].p95=o[r]??t;let i=Math.max(0,Math.floor(o.length*.99)-1);this.metrics.latency[e].p99=o[i]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let o=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=o>0?this.metrics.errors[e].count/o:0}}};var Mn=class s{options;lastUsedService;services=new Map;constructor(e){if(e.length===0)throw new Error("No AI services provided.");for(let[t,n]of e.entries())if("key"in n){if(this.services.has(n.key))throw new Error(`Duplicate model key: ${n.key}`);let{service:r,description:i,isInternal:a}=n;this.services.set(n.key,{service:r,description:i,isInternal:a})}else{let r=n.getModelList();if(!r)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let i of r){if(this.services.has(i.key)){let a=this.services.get(i.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${i.key} as service ${a?.getName()}`)}if("model"in i&&typeof i.model)this.services.set(i.key,{description:i.description,service:n,model:i.model});else if("embedModel"in i&&i.embedModel)this.services.set(i.key,{description:i.description,service:n,embedModel:i.embedModel});else throw new Error(`Key ${i.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(e){return new s(e)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let o=this.services.get(n);if(!o)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=o.service,!o.model){let{model:r,...i}=e;return await o.service.chat(i,t)}return await o.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw new Error("Embed model key must be specified for multi-service");let o=this.services.get(n);if(!o)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=o.service,!o.model){let{embedModel:r,...i}=e;return await o.service.embed(i,t)}return await o.service.embed({embedModel:n,...e},t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(",")}`}getName(){return"MultiServiceRouter"}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw new Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(e)}return{functions:!1,streaming:!1}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e="service"in t?t.service:t)}if(!e)throw new Error("No service available to get metrics.");return e.getMetrics()}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw new Error("No service available to get logger.");return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};var Jo=()=>structuredClone({...L(),model:"nous-hermes2",embedModel:"all-minilm"}),Js=()=>structuredClone({...Y(),model:"nous-hermes2",embedModel:"all-minilm"}),et=class extends V{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:o,models:r}){let i={...Jo(),...n};super({apiKey:e,options:o,config:i,apiURL:t,models:r,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1}}),super.setName("Ollama")}};var Qa=s=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(s),tt=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,stopSequences:e.stopSequences,topP:e.topP,stream:e.stream}}mapInternalContentToResponsesInput(e){return e.map(n=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="image")return{type:"image_url",image_url:{url:`data:${n.mimeType};base64,${n.image}`,details:n.details??"auto"}};if(n.type==="audio")return{type:"input_audio",input_audio:{data:n.data,format:n.format??"wav"}};let o=n;throw new Error(`Unsupported content part: ${JSON.stringify(o)}`)})}createResponsesReqInternalInput(e,t=!1){let n=[];for(let o of e){if(t&&o.role==="system")continue;let r;if(o.role==="system"||o.role==="user"||o.role==="assistant"&&o.content)if(typeof o.content=="string")r=o.content;else if(Array.isArray(o.content))r=this.mapInternalContentToResponsesInput(o.content);else{if(!(o.role==="assistant"&&!o.content&&o.functionCalls))throw new Error(`Invalid content type for role ${o.role}`);r=""}else o.role,r="";switch(o.role){case"system":n.push({type:"message",role:"system",content:r});break;case"user":n.push({type:"message",role:"user",content:r,name:o.name});break;case"assistant":if(o.content||o.functionCalls){let i={type:"message",role:"assistant",content:""};if(o.content&&(i.content=r),o.name&&(i.name=o.name),o.content&&n.push(i),o.functionCalls)for(let a of o.functionCalls)n.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:typeof a.function.params=="object"?JSON.stringify(a.function.params):a.function.params||""})}break;case"function":n.push({type:"function_call_output",call_id:o.functionId,output:o.result});break;default:{let i=o.role;throw new Error(`Invalid role in chat prompt: ${i}`)}}}return n}createChatReq(e,t){let n=e.model,o={name:"/responses"},r=null,i=!1;if(e.chatPrompt){for(let A of e.chatPrompt)if(A.role==="system"&&typeof A.content=="string"){r=A.content,i=!0;break}}let a=r??this.config.systemPrompt??null,l=e.functions?.map(A=>({type:"function",name:A.name,description:A.description,parameters:A.parameters??{}})),c=[],p=Qa(n),d=this.config.reasoningSummary;t?.showThoughts?d||(d="auto"):d=void 0;let u=this.config.reasoningEffort;if(t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":u=void 0;break;case"minimal":u="low";break;case"low":u="medium";break;case"medium":case"high":case"highest":u="high";break}let m={model:n,input:"",instructions:a,tools:l?.length?l:void 0,tool_choice:e.functionCall==="none"||e.functionCall==="auto"||e.functionCall==="required"?e.functionCall:typeof e.functionCall=="object"&&e.functionCall.function?{type:"function",name:e.functionCall.function.name}:void 0,...p?{max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0}:{temperature:e.modelConfig?.temperature??this.config.temperature??void 0,top_p:e.modelConfig?.topP??this.config.topP??void 0,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty??void 0,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty??void 0},stream:e.modelConfig?.stream??this.config.stream??!1,background:void 0,include:c.length>0?c:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...u?{reasoning:{effort:u,summary:d}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let g=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,i):[];if(g.length>0)m.input=g;else if(e.chatPrompt&&e.chatPrompt.length===1&&e.chatPrompt[0]?.role==="user"&&e.chatPrompt[0]?.content&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(g.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let h=m.reasoning??{};if(this.config.reasoningEffort&&(h={...h,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":h={};break;case"minimal":h={...h,effort:"low"};break;case"low":h={...h,effort:"medium"};break;case"medium":case"high":case"highest":h={...h,effort:"high"};break}Object.keys(h).length>0&&h.effort?m.reasoning=h:m.reasoning=void 0;let f=m;return this.responsesReqUpdater&&(f=this.responsesReqUpdater(f)),[o,f]}createChatResp(e){let{id:t,output:n,usage:o}=e;o&&(this.tokensUsed={promptTokens:o.prompt_tokens,completionTokens:o.completion_tokens,totalTokens:o.total_tokens});let r={};for(let i of n??[])switch(i.type){case"message":r.id=i.id,r.content=Qo(i.content,t),r.finishReason=i.status==="completed"?"stop":"content_filter";break;case"reasoning":r.id=i.id,i.encrypted_content?r.thought=i.encrypted_content:r.thought=i.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
|
|
115
|
-
`);break;case"file_search_call":
|
|
116
|
-
`);throw new
|
|
117
|
-
`)};var Ft=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),Qs=()=>({...Ft(),model:"gpt-4o",temperature:.5}),Zs=()=>({...Ft(),model:"gpt-4o",temperature:.9}),Pt=class extends K{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r=[],models:i,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new tt(t,n?.streamingUsage??!0,a),p=i;super(c,{name:"OpenAI",apiURL:o||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:r,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:p})}},nt=class extends Pt{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("OpenAI API key not set");r=[...un,...r??[]];let i=a=>{let l=re({model:a,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:l?.hasThinkingBudget??!1,hasShowThoughts:l?.hasShowThoughts??!1}};super({apiKey:e,config:{...Ft(),...t},options:n,modelInfo:r,models:o,supportFor:i})}};var Dt=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(Dt||{});var On=[{name:"reka-core",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"reka-flash",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2},{name:"reka-edge",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1}];var Gt=()=>structuredClone({model:"reka-core",...L()}),ei=()=>structuredClone({...Gt(),model:"reka-core"}),ti=()=>structuredClone({model:"reka-core",...Y()}),ni=()=>({...Gt(),model:"reka-flash"}),Zo=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=e=>{let t=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let n={name:"/chat/completions"},o=Za(e),r=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,i=e.modelConfig?.stream??this.config.stream,a={model:t,messages:o,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.temperature,top_k:e.modelConfig?.n??this.config.n,top_p:e.modelConfig?.topP??this.config.topP??1,stop:e.modelConfig?.stopSequences??this.config.stop,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...r?{frequency_penalty:r}:{},...i?{stream:!0}:{}};return[n,a]};createChatResp=e=>{let{id:t,usage:n,responses:o}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:o.map((i,a)=>{let l=Xs(i.finish_reason),c;return typeof i.message.content=="string"?c=i.message.content:c=i.message.content.text,{index:a,id:`${t}`,content:c,finishReason:l}}),remoteId:t}};createChatStreamResp=e=>{let{id:t,usage:n,responses:o}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:o.map((i,a)=>{let l=Xs(i.finish_reason),c;return typeof i.chunk.content=="string"?c=i.chunk.content:c=i.chunk.content.text,{index:a,id:`${t}`,content:c,finishReason:l}})}}},Xs=s=>{switch(s){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function Za(s){return s.chatPrompt.map(e=>{switch(e.role){case"system":return{role:"user",content:e.content};case"user":return Array.isArray(e.content)?{role:"user",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})}:{role:"user",content:e.content};case"assistant":if(Array.isArray(e.content))return{role:"assistant",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})};if(!e.content)throw new Error("Assistant content is empty");return{role:"user",content:e.content};default:throw new Error("Invalid role")}})}var ot=class extends K{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r=On,models:i}){if(!e||e==="")throw new Error("Reka API key not set");let a={...Gt(),...t},l=new Zo(a);super(l,{name:"Reka",apiURL:o||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:r,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0},models:i})}};var kn=[];var Xo=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...L()}),rt=class extends V{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Together API key not set");let i={...Xo(),...t};r=[...kn,...r??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1};super({apiKey:e,config:i,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:r,models:o,supportFor:a}),super.setName("Together")}};function En(s){let e=n=>JSON.stringify(n,null,2);if(!s)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(s)}`);let t=s?.role;if(!t)throw new Error(`Chat request message must have a role, received: ${e(t)}`);switch(t){case"system":{let n=s;if(!n.content||n.content.trim()==="")throw new Error(`System message content cannot be empty or whitespace-only, received: ${e(n.content)}`);break}case"user":{let n=s;if(!n.content)throw new Error(`User message content cannot be undefined, received: ${e(n.content)}`);if(typeof n.content=="string"){if(n.content.trim()==="")throw new Error(`User message content cannot be empty or whitespace-only, received: ${e(n.content)}`)}else if(Array.isArray(n.content)){if(n.content.length===0)throw new Error(`User message content array cannot be empty, received: ${e(n.content)}`);for(let o=0;o<n.content.length;o++){let r=n.content[o];if(!r||typeof r!="object")throw new Error(`User message content item at index ${o} must be an object, received: ${e(r)}`);let i=r?.type;if(!i)throw new Error(`User message content item at index ${o} must have a type, received: ${e(i)}`);switch(i){case"text":{let a=r;if(!a.text||a.text.trim()==="")throw new Error(`User message text content at index ${o} cannot be empty or whitespace-only, received: ${e(a.text)}`);break}case"image":{let a=r;if(!a.image||a.image.trim()==="")throw new Error(`User message image content at index ${o} cannot be empty, received: ${e(a.image)}`);if(!a.mimeType||a.mimeType.trim()==="")throw new Error(`User message image content at index ${o} must have a mimeType, received: ${e(a.mimeType)}`);break}case"audio":{let a=r;if(!a.data||a.data.trim()==="")throw new Error(`User message audio content at index ${o} cannot be empty, received: ${e(a.data)}`);break}default:throw new Error(`User message content item at index ${o} has unsupported type: ${e(i)}`)}}}else throw new Error(`User message content must be a string or array of content objects, received: ${e(n.content)}`);break}case"assistant":{let n=s;if(!n.content&&!n.functionCalls)throw new Error(`Assistant message must have either content or function calls, received content: ${e(n.content)}, functionCalls: ${e(n.functionCalls)}`);if(n.content&&typeof n.content!="string")throw new Error(`Assistant message content must be a string, received: ${e(n.content)}`);if(n.functionCalls&&!Array.isArray(n.functionCalls))throw new Error(`Assistant message function calls must be an array, received: ${e(n.functionCalls)}`);break}case"function":{let n=s;if(!n.functionId||n.functionId.trim()==="")throw new Error(`Function message must have a non-empty functionId, received: ${e(n.functionId)}`);if(n.result===void 0||n.result===null)throw new Error(`Function message must have a result, received: ${e(n.result)}`);if(typeof n.result!="string")throw new Error(`Function message result must be a string, received: ${e(n.result)}`);break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function _n(s){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(s)?s:[s];if(t.length===0)throw new Error(`Chat response results cannot be empty, received: ${e(t)}`);for(let n=0;n<t.length;n++){let o=t[n];if(!o)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(o)}`);if(typeof o.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(o.index)}`);if(o.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(o.index)}`);if(!o.content&&!o.thought&&!o.functionCalls&&!o.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, functionCalls, or finishReason, received: ${e({content:o.content,thought:o.thought,functionCalls:o.functionCalls,finishReason:o.finishReason})}`);if(o.content!==void 0&&typeof o.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(o.content)}`);if(o.thought!==void 0&&typeof o.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(o.thought)}`);if(o.name!==void 0){if(typeof o.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(o.name)}`);if(o.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(o.name)}`)}if(o.annotations!==void 0){if(!Array.isArray(o.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(o.annotations)}`);for(let r=0;r<o.annotations.length;r++){let i=o.annotations[r];if(!i||typeof i!="object")throw new Error(`Chat response result annotation at index ${n}[${r}] must be an object, received: ${e(i)}`);if(i.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${r}] must have type 'url_citation', received: ${e(i.type)}`);if(!i.url_citation||typeof i.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${r}] must have a valid url_citation object, received: ${e(i.url_citation)}`);if(typeof i.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${r}] url_citation.url must be a string, received: ${e(i.url_citation.url)}`)}}if(o.id!==void 0){if(typeof o.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(o.id)}`);if(o.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(o.id)}`)}if(o.functionCalls!==void 0){if(!Array.isArray(o.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(o.functionCalls)}`);for(let r=0;r<o.functionCalls.length;r++){let i=o.functionCalls[r];if(!i)throw new Error(`Function call at index ${r} in result ${n} cannot be null or undefined, received: ${e(i)}`);if(!i.id||typeof i.id!="string"||i.id.trim()==="")throw new Error(`Function call at index ${r} in result ${n} must have a non-empty string id, received: ${e(i.id)}`);if(i.type!=="function")throw new Error(`Function call at index ${r} in result ${n} must have type 'function', received: ${e(i.type)}`);if(!i.function)throw new Error(`Function call at index ${r} in result ${n} must have a function object, received: ${e(i.function)}`);if(!i.function.name||typeof i.function.name!="string"||i.function.name.trim()==="")throw new Error(`Function call at index ${r} in result ${n} must have a non-empty function name, received: ${e(i.function.name)}`);if(i.function.params!==void 0&&typeof i.function.params!="string"&&typeof i.function.params!="object")throw new Error(`Function call params at index ${r} in result ${n} must be a string or object, received: ${e(i.function.params)}`)}}if(o.finishReason!==void 0){let r=["stop","length","function_call","content_filter","error"];if(!r.includes(o.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${r.join(", ")}, received: ${e(o.finishReason)}`)}}}var Lt=(u=>(u.Llama31_8B_Instruct="Llama-3.1-8B-Instruct-q4f32_1-MLC",u.Llama31_70B_Instruct="Llama-3.1-70B-Instruct-q4f16_1-MLC",u.Llama32_1B_Instruct="Llama-3.2-1B-Instruct-q4f32_1-MLC",u.Llama32_3B_Instruct="Llama-3.2-3B-Instruct-q4f32_1-MLC",u.Mistral7B_Instruct="Mistral-7B-Instruct-v0.3-q4f32_1-MLC",u.Phi35_Mini_Instruct="Phi-3.5-mini-instruct-q4f32_1-MLC",u.Gemma2_2B_Instruct="gemma-2-2b-it-q4f32_1-MLC",u.Gemma2_9B_Instruct="gemma-2-9b-it-q4f32_1-MLC",u.Qwen2_5_0_5B_Instruct="Qwen2.5-0.5B-Instruct-q4f32_1-MLC",u.Qwen2_5_1_5B_Instruct="Qwen2.5-1.5B-Instruct-q4f32_1-MLC",u.Qwen2_5_3B_Instruct="Qwen2.5-3B-Instruct-q4f32_1-MLC",u.Qwen2_5_7B_Instruct="Qwen2.5-7B-Instruct-q4f32_1-MLC",u))(Lt||{});var Pn=[{name:"Llama-3.1-8B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"Llama-3.1-70B-Instruct-q4f16_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096,isExpensive:!0},{name:"Llama-3.2-1B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Llama-3.2-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Mistral-7B-Instruct-v0.3-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096},{name:"Phi-3.5-mini-instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"gemma-2-2b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"gemma-2-9b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"Qwen2.5-0.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-1.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-7B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096}];var tr=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...L()}),oi=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Y()}),er=class{constructor(e,t){this.config=e;this.engine=t}tokensUsed;engine;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.map(a=>{if(a.role==="function")return{role:"function",name:a.functionId,content:typeof a.result=="string"?a.result:JSON.stringify(a.result)};let l="";typeof a.content=="string"?l=a.content:Array.isArray(a.content)&&(l=a.content.filter(p=>p.type==="text").map(p=>p.text).join(`
|
|
118
|
-
`));let c={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...c,tool_calls:a.functionCalls.map(p=>({id:p.id,type:"function",function:{name:p.function.name,arguments:typeof p.function.params=="string"?p.function.params:JSON.stringify(p.function.params||{})}}))}:c}),o=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),r={name:"/chat/completions",localCall:async(a,l)=>{try{let c=await this.engine.chat.completions.create({...a,stream:l||!1});return l?new ReadableStream({async start(p){try{for await(let d of c)p.enqueue(d);p.close()}catch(d){p.error(d)}}}):c}catch(c){throw new Error(`WebLLM API error: ${c}`)}}},i={model:t,messages:n,...o?.length?{tools:o}:{},max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.temperature,top_p:e.modelConfig?.topP??this.config.topP,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,stop:e.modelConfig?.stopSequences??this.config.stopSequences,stream:e.modelConfig?.stream??this.config.stream,n:e.modelConfig?.n??this.config.n};return[r,i]}createEmbedReq=e=>{throw new Error("WebLLM does not support embeddings")};createChatResp=e=>(this.tokensUsed={promptTokens:e.usage?.prompt_tokens??0,completionTokens:e.usage?.completion_tokens??0,totalTokens:e.usage?.total_tokens??0},{results:e.choices.map((n,o)=>{let r="stop";switch(n.finish_reason){case"stop":r="stop";break;case"length":r="length";break;case"tool_calls":r="function_call";break;case"content_filter":r="content_filter";break;default:r="stop";break}let i=n.message.tool_calls?.map(a=>({id:a.id,type:"function",function:{name:a.function.name,params:a.function.arguments}}));return{index:o,id:e.id,content:n.message.content||"",functionCalls:i,finishReason:r}}),remoteId:e.id});createChatStreamResp=(e,t)=>{let n=t,o=e.choices[0];if(!o)throw new Error("No choice in WebLLM stream response");if(o.delta.content&&(n.content=(n.content||"")+o.delta.content),o.delta.tool_calls){n.toolCalls||(n.toolCalls=[]);for(let l of o.delta.tool_calls){let c=n.toolCalls[l.index];c?l.function?.arguments&&(c.function.arguments=(c.function?.arguments||"")+l.function.arguments):n.toolCalls[l.index]={id:l.id,type:l.type,function:{name:l.function?.name,arguments:l.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let r;if(o.finish_reason)switch(o.finish_reason){case"stop":r="stop";break;case"length":r="length";break;case"tool_calls":r="function_call";break;case"content_filter":r="content_filter";break;default:r="stop";break}let i=n.toolCalls?.map(l=>({id:l.id||"",type:"function",function:{name:l.function?.name||"",params:l.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:i,finishReason:r}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},st=class extends K{constructor({engine:e,config:t,options:n,models:o}){if(!e)throw new Error("WebLLM engine instance is required");let r={...tr(),...t},i=new er(r,e);super(i,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:Pn,defaults:{model:r.model},supportFor:a=>({functions:!0,streaming:!0}),options:n,models:o})}};var Nt=(o=>(o.Grok3="grok-3",o.Grok3Mini="grok-3-mini",o.Grok3Fast="grok-3-fast",o.Grok3MiniFast="grok-3-mini-fast",o))(Nt||{}),nr=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(nr||{});var Fn=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,hasThinkingBudget:!0},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,hasThinkingBudget:!0}];var Dn=()=>structuredClone({model:"grok-3-mini",...L()}),ri=()=>structuredClone({...Dn(),model:"grok-3"}),it=class extends V{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Grok API key not set");let i={...Dn(),...t};r=[...Fn,...r??[]];let a=c=>{let p=re({model:c,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:p?.hasThinkingBudget??!1,hasShowThoughts:p?.hasShowThoughts??!1}},l=c=>{if(n?.searchParameters){let p=n.searchParameters;return{...c,search_parameters:{mode:p.mode,return_citations:p.returnCitations,from_date:p.fromDate,to_date:p.toDate,max_search_results:p.maxSearchResults,sources:p.sources?.map(d=>({type:d.type,country:d.country,excluded_websites:d.excludedWebsites,allowed_websites:d.allowedWebsites,safe_search:d.safeSearch,x_handles:d.xHandles,links:d.links}))}}}return c};super({apiKey:e,config:i,options:n,apiURL:"https://api.x.ai/v1",modelInfo:r,models:o,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};var Gn=class s{ai;static create(e){return new s(e)}constructor(e){switch(e.name){case"openai":this.ai=new He(e);break;case"openai-responses":this.ai=new nt(e);break;case"azure-openai":this.ai=new Ke(e);break;case"grok":this.ai=new it(e);break;case"huggingface":this.ai=new Ze(e);break;case"groq":this.ai=new Qe(e);break;case"together":this.ai=new rt(e);break;case"cohere":this.ai=new Ve(e);break;case"google-gemini":this.ai=new Ye(e);break;case"anthropic":this.ai=new Be(e);break;case"mistral":this.ai=new Xe(e);break;case"deepseek":this.ai=new We(e);break;case"ollama":this.ai=new et(e);break;case"reka":this.ai=new ot(e);break;case"webllm":this.ai=new st(e);break;default:throw new Error("Unknown AI")}}getName(){return this.ai.getName()}getId(){return this.ai.getId()}getFeatures(e){return this.ai.getFeatures(e)}getModelList(){return this.ai.getModelList()}getLastUsedChatModel(){return this.ai.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.ai.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.ai.getLastUsedModelConfig()}getMetrics(){return this.ai.getMetrics()}async chat(e,t){return await this.ai.chat(e,t)}async embed(e,t){return await this.ai.embed(e,t)}setOptions(e){this.ai.setOptions(e)}getOptions(){return this.ai.getOptions()}getLogger(){return this.ai.getLogger()}};var ae=class{name;fetch;tracer;_upsert;_batchUpsert;_query;constructor({name:e,fetch:t,tracer:n}){this.name=e,this.fetch=t,this.tracer=n}async upsert(e,t){if(!this._upsert)throw new Error("upsert() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Upsert Request",{kind:ie.SERVER,attributes:{[D.DB_SYSTEM]:this.name,[D.DB_OPERATION_NAME]:"upsert",[D.DB_TABLE]:e.table,[D.DB_NAMESPACE]:e.namespace,[D.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._upsert(e,t,{span:n})}finally{n.end()}}):await this._upsert(e,t)}async batchUpsert(e,t){if(!this._batchUpsert)throw new Error("batchUpsert() not implemented");if(e.length===0)throw new Error("Batch request is empty");if(!e[0])throw new Error("Batch request is invalid first element is undefined");return this.tracer?await this.tracer.startActiveSpan("DB Batch Upsert Request",{kind:ie.SERVER,attributes:{[D.DB_SYSTEM]:this.name,[D.DB_OPERATION_NAME]:"upsert",[D.DB_TABLE]:e[0].table,[D.DB_NAMESPACE]:e[0].namespace,[D.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._batchUpsert(e,t,{span:n})}finally{n.end()}}):await this._batchUpsert(e,t)}async query(e){if(!this._query)throw new Error("query() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Query Request",{kind:ie.SERVER,attributes:{[D.DB_SYSTEM]:this.name,[D.DB_OPERATION_NAME]:"upsert",[D.DB_TABLE]:e.table,[D.DB_NAMESPACE]:e.namespace,[D.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var or="https://api.cloudflare.com/client/v4/accounts/",at=class extends ae{apiKey;accountId;constructor({apiKey:e,accountId:t,fetch:n,tracer:o}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:o}),this.apiKey=e,this.accountId=t}_upsert=async(e,t,n)=>{let o=await te({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,or),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(o.errors)throw new Error(`Cloudflare upsert failed: ${o.errors.map(({message:r})=>r).join(", ")}`);return{ids:o.result.ids}};batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length<1)throw new Error("Batch request is empty");if(!e[0]||!e[0].table)throw new Error("Table name is empty");let o=e[0].table,r=await te({url:new URL(`${this.accountId}/vectorize/indexes/${o}/upsert`,or),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(i=>({id:i.id,values:i.values,namespace:i.namespace,metadata:i.metadata})));if(r.errors)throw new Error(`Cloudflare batch upsert failed: ${r.errors.map(({message:i})=>i).join(", ")}`);return{ids:r.result.ids}};query=async(e,t)=>{let n=await te({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,or),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:t?.span},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:r})=>r).join(", ")}`);return{matches:n.result.matches.map(({id:r,score:i,values:a,metadata:l})=>({id:r,score:i,values:a,metadata:l}))}}};var Ce=class extends ae{state;constructor({tracer:e}={}){super({name:"Memory",tracer:e}),this.state={}}_upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let o=this.state[e.table];if(!o)throw new Error(`Table not found: ${e.table}`);o[e.id]=e}return{ids:[e.id]}};_batchUpsert=async(e,t,n)=>{let o=[];for(let r of e){let i=await this.upsert(r,t);o.push(...i.ids)}return{ids:o}};_query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let o=[];return Object.entries(n).forEach(([r,i])=>{if(e.values&&i.values){let a=Xa(e.values,i.values);o.push({id:r,score:a,metadata:i.metadata})}}),o.sort((r,i)=>r.score-i.score),e.limit&&(o.length=e.limit),{matches:o}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},Xa=(s,e)=>{if(s.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,o=0,r=!0,i=!0,a=new Float64Array(s),l=new Float64Array(e);for(let u=0;u<a.length;u++)t+=a[u]*l[u],n+=a[u]*a[u],o+=l[u]*l[u],a[u]!==0&&(r=!1),l[u]!==0&&(i=!1);if(r||i)return 1;let c=Math.sqrt(n),p=Math.sqrt(o);return 1-t/(c*p)};var el=s=>({namespace:s.namespace,topK:s.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:s.values??[],id:s.id}),lt=class extends ae{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:o}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:o}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]});_batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await te({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:o,values:r=[],metadata:i})=>({id:o,values:r,metadata:i}))),{ids:e.map(({id:o})=>o)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await te({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},el(e))).matches.map(({id:r,score:i,values:a,metadata:l})=>({id:r,score:i,metadata:l,values:a}))}}};var ct=class extends ae{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:o}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:o}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>{let o=await te({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:n?.span},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:e.metadata??{}});if(o?.result?.errors)throw new Error(`Weaviate upsert failed: ${o.result.errors.error.map(({message:r})=>r).join(", ")}`);return{ids:[o.id]}};_batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length===0)throw new Error("Batch request is empty");let o=e.map(i=>({id:i.id,class:i.table,tenant:i.namespace,vector:i.values,properties:i.metadata??{}})),r=await te({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:o});if(r?.some(({result:i})=>i?.errors))throw new Error(`Weaviate batch upsert failed: ${r.map(({result:i})=>i?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:r.map(({id:i})=>i)}};_query=async(e,t)=>{let n="";if(e.columns&&e.columns.length===0)throw new Error("Weaviate requires at least one column");if(e.values)n=`nearVector: {
|
|
115
|
+
${p}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(`
|
|
116
|
+
`),o=`${n} ${r}`.trim(),i={name:"/models"},a={model:t,inputs:o,parameters:{max_new_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,repetition_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,temperature:e.modelConfig?.temperature??this.config.temperature,top_p:e.modelConfig?.topP??this.config.topP,top_k:e.modelConfig?.topK??this.config.topK,return_full_text:this.config.returnFullText,num_return_sequences:this.config.n,do_sample:this.config.doSample,max_time:this.config.maxTime},options:{use_cache:this.config.useCache,wait_for_model:this.config.waitForModel}};return[i,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},nt=class extends j{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let o={...co(),...t},i=new po(o);super(i,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Dn,defaults:{model:o.model},options:n,supportFor:{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r})}};var Lt=(l=>(l.Mistral7B="open-mistral-7b",l.Mistral8x7B="open-mixtral-8x7b",l.MistralSmall="mistral-small-latest",l.MistralNemo="mistral-nemo-latest",l.MistralLarge="mistral-large-latest",l.Codestral="codestral-latest",l.OpenCodestralMamba="open-codestral-mamba",l.OpenMistralNemo="open-mistral-nemo-latest",l))(Lt||{}),uo=(e=>(e.MistralEmbed="mistral-embed",e))(uo||{});var Ln=[{name:"open-mistral-7b",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mixtral-8x7b",currency:"USD",promptTokenCostPer1M:.7,completionTokenCostPer1M:.7},{name:"mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.15,completionTokenCostPer1M:.15},{name:"mistral-small-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"mistral-large-latest",currency:"USD",promptTokenCostPer1M:2,completionTokenCostPer1M:6},{name:"codestral-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"open-codestral-mamba",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.3}];var Nn=()=>structuredClone({model:"mistral-small-latest",...L(),topP:1}),di=()=>structuredClone({...Nn(),model:"mistral-large-latest"}),rt=class extends K{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Mistral API key not set");let i={...Nn(),...t};o=[...Ln,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},l=p=>{let{max_completion_tokens:c,messages:d,...u}=p;return{...u,messages:this.updateMessages(d),max_tokens:c}};super({apiKey:e,config:i,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Mistral")}updateMessages(e){let t=[];if(!Array.isArray(e))return e;for(let n of e)if(n.role==="user"&&Array.isArray(n.content)){let r=n.content.map(o=>typeof o=="object"&&o!==null&&"image_url"in o?{type:"image_url",image_url:{url:o.image_url?.url}}:o);t.push({...n,content:r})}else t.push(n);return t}};var Gn=class{constructor(e={}){this.config=e;this.config.id=this.config.id??ne()}metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getLastUsedChatModel(){return this.config.modelInfo?.name??"mock-model"}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??"mock-embed-model"}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??"mock-ai-service"}getId(){return this.config.id??"mock-ai-service-id"}getFeatures(e){return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getModelList(){return this.config.models}getMetrics(){return this.metrics}async chat(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock chat error");return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):this.config.chatResponse??{results:[{index:0,content:"Mock response",finishReason:"stop"}],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock embed error");return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((r,o)=>r+o,0)/n.length,n.length>0){let r=[...n].sort((a,l)=>a-l),o=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[o]??t;let i=Math.max(0,Math.floor(r.length*.99)-1);this.metrics.latency[e].p99=r[i]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let r=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=r>0?this.metrics.errors[e].count/r:0}}};var Un=class s{options;lastUsedService;services=new Map;constructor(e){if(e.length===0)throw new Error("No AI services provided.");for(let[t,n]of e.entries())if("key"in n){if(this.services.has(n.key))throw new Error(`Duplicate model key: ${n.key}`);let{service:o,description:i,isInternal:a}=n;this.services.set(n.key,{service:o,description:i,isInternal:a})}else{let o=n.getModelList();if(!o)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let i of o){if(this.services.has(i.key)){let a=this.services.get(i.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${i.key} as service ${a?.getName()}`)}if("model"in i&&typeof i.model)this.services.set(i.key,{description:i.description,service:n,model:i.model});else if("embedModel"in i&&i.embedModel)this.services.set(i.key,{description:i.description,service:n,embedModel:i.embedModel});else throw new Error(`Key ${i.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(e){return new s(e)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{model:o,...i}=e;return await r.service.chat(i,t)}return await r.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw new Error("Embed model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{embedModel:o,...i}=e;return await r.service.embed(i,t)}return await r.service.embed({embedModel:n,...e},t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(",")}`}getName(){return"MultiServiceRouter"}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw new Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(e)}return{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e="service"in t?t.service:t)}if(!e)throw new Error("No service available to get metrics.");return e.getMetrics()}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw new Error("No service available to get logger.");return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};var mo=()=>structuredClone({...L(),model:"nous-hermes2",embedModel:"all-minilm"}),mi=()=>structuredClone({...W(),model:"nous-hermes2",embedModel:"all-minilm"}),ot=class extends K{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:o}){let i={...mo(),...n};super({apiKey:e,options:r,config:i,apiURL:t,models:o,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}),super.setName("Ollama")}};var xl=s=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(s),st=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,stopSequences:e.stopSequences,topP:e.topP,stream:e.stream}}mapInternalContentToResponsesInput(e){return e.map(n=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="image")return{type:"image_url",image_url:{url:`data:${n.mimeType};base64,${n.image}`,details:n.details??"auto"}};if(n.type==="audio")return{type:"input_audio",input_audio:{data:n.data,format:n.format==="wav"?"wav":void 0}};let r=n;throw new Error(`Unsupported content part: ${JSON.stringify(r)}`)})}createResponsesReqInternalInput(e,t=!1){let n=[];for(let r of e){if(t&&r.role==="system")continue;let o;if(r.role==="system"||r.role==="user"||r.role==="assistant"&&r.content)if(typeof r.content=="string")o=r.content;else if(Array.isArray(r.content))o=this.mapInternalContentToResponsesInput(r.content);else{if(!(r.role==="assistant"&&!r.content&&r.functionCalls))throw new Error(`Invalid content type for role ${r.role}`);o=""}else r.role,o="";switch(r.role){case"system":n.push({type:"message",role:"system",content:o});break;case"user":n.push({type:"message",role:"user",content:o,name:r.name});break;case"assistant":if(r.content||r.functionCalls){let i={type:"message",role:"assistant",content:""};if(r.content&&(i.content=o),r.name&&(i.name=r.name),r.content&&n.push(i),r.functionCalls)for(let a of r.functionCalls)n.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:typeof a.function.params=="object"?JSON.stringify(a.function.params):a.function.params||""})}break;case"function":n.push({type:"function_call_output",call_id:r.functionId,output:r.result});break;default:{let i=r.role;throw new Error(`Invalid role in chat prompt: ${i}`)}}}return n}createChatReq(e,t){let n=e.model,r={name:"/responses"},o=null,i=!1;if(e.chatPrompt){for(let f of e.chatPrompt)if(f.role==="system"&&typeof f.content=="string"){o=f.content,i=!0;break}}let a=o??this.config.systemPrompt??null,l=e.functions?.map(f=>({type:"function",name:f.name,description:f.description,parameters:f.parameters??{}})),p=[],c=xl(n),d=this.config.reasoningSummary;t?.showThoughts?d||(d="auto"):d=void 0;let u=this.config.reasoningEffort;if(t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":u=void 0;break;case"minimal":u="low";break;case"low":u="medium";break;case"medium":case"high":case"highest":u="high";break}let m={model:n,input:"",instructions:a,tools:l?.length?l:void 0,tool_choice:e.functionCall==="none"||e.functionCall==="auto"||e.functionCall==="required"?e.functionCall:typeof e.functionCall=="object"&&e.functionCall.function?{type:"function",name:e.functionCall.function.name}:void 0,...c?{max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0}:{temperature:e.modelConfig?.temperature??this.config.temperature??void 0,top_p:e.modelConfig?.topP??this.config.topP??void 0,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty??void 0,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty??void 0},stream:e.modelConfig?.stream??this.config.stream??!1,background:void 0,include:p.length>0?p:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...u?{reasoning:{effort:u,summary:d}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let g=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,i):[];if(g.length>0)m.input=g;else if(e.chatPrompt&&e.chatPrompt.length===1&&e.chatPrompt[0]?.role==="user"&&e.chatPrompt[0]?.content&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(g.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let h=m.reasoning??{};if(this.config.reasoningEffort&&(h={...h,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":h={};break;case"minimal":h={...h,effort:"low"};break;case"low":h={...h,effort:"medium"};break;case"medium":case"high":case"highest":h={...h,effort:"high"};break}Object.keys(h).length>0&&h.effort?m.reasoning=h:m.reasoning=void 0;let A=m;return this.responsesReqUpdater&&(A=this.responsesReqUpdater(A)),[r,A]}createChatResp(e){let{id:t,output:n,usage:r}=e;r&&(this.tokensUsed={promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens});let o={};for(let i of n??[])switch(i.type){case"message":o.id=i.id,o.content=go(i.content,t),o.finishReason=i.status==="completed"?"stop":"content_filter";break;case"reasoning":o.id=i.id,i.encrypted_content?o.thought=i.encrypted_content:o.thought=i.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
|
|
117
|
+
`);break;case"file_search_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"file_search",params:{queries:i.queries,results:i.results}}}],o.finishReason="function_call";break;case"web_search_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"web_search",params:{queries:i.queries}}}],o.finishReason="function_call";break;case"computer_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"computer_use",params:{action:i.action}}}],o.finishReason="function_call";break;case"code_interpreter_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"code_interpreter",params:{code:i.code,results:i.results}}}],o.finishReason="function_call";break;case"image_generation_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"image_generation",params:{result:i.result}}}],o.finishReason="function_call";break;case"local_shell_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"local_shell",params:{action:i.action}}}],o.finishReason="function_call";break;case"mcp_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"mcp",params:{name:i.name,args:i.args,serverLabel:i.server_label,output:i.output,error:i.error}}}],o.finishReason="function_call";break;case"function_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:i.name,params:i.arguments}}],o.finishReason="function_call";break}return{results:[{...o,index:0}],remoteId:t}}createChatStreamResp(e){let t=e,n={index:0,id:"",content:"",finishReason:"stop"},r;switch(t.type){case"response.created":case"response.in_progress":case"response.queued":r=t.response.id,n.id=`${t.response.id}_res_0`;break;case"response.output_item.added":switch(t.item.type){case"message":n.id=t.item.id,n.content=go(t.item.content,t.item.id);break;case"function_call":n.id=t.item.id,n.functionCalls=[{id:t.item.id,type:"function",function:{name:t.item.name,params:t.item.arguments}}];break;case"file_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"file_search",params:{queries:o.queries||[],results:o.results?.map(i=>({fileId:i.file_id,filename:i.filename,score:i.score,text:i.text,attributes:i.attributes}))}}}]}break;case"web_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"web_search",params:{queries:o.queries||[]}}}]}break;case"computer_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"computer_use",params:{action:o.action||{}}}}]}break;case"code_interpreter_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"code_interpreter",params:{code:o.code||"",results:o.results}}}]}break;case"image_generation_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"image_generation",params:{result:o.result}}}]}break;case"local_shell_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"local_shell",params:{action:o.action||{}}}}]}break;case"mcp_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"mcp",params:{name:o.name||"",args:o.args||"",serverLabel:o.server_label||"",output:o.output,error:o.error}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=go([t.part],t.item_id);break;case"response.output_text.delta":n.id=t.item_id,n.content=t.delta;break;case"response.output_text.done":break;case"response.function_call_arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.reasoning_summary_text.delta":n.id=t.item_id,n.thought=t.delta;break;case"response.file_search_call.in_progress":case"response.file_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.file_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.in_progress":case"response.web_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.in_progress":case"response.image_generation_call.generating":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.partial_image":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.in_progress":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.mcp_call.arguments.done":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.arguments}}];break;case"response.mcp_call.completed":case"response.mcp_call.failed":n.id="mcp_call_event",n.finishReason="function_call";break;case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":n.id="mcp_list_tools_event",n.finishReason="function_call";break;case"response.output_item.done":switch(t.item.type){case"message":n.id=t.item.id,n.finishReason=t.item.status==="completed"?"stop":"error";break;case"function_call":case"file_search_call":case"web_search_call":case"computer_call":case"code_interpreter_call":case"image_generation_call":case"local_shell_call":case"mcp_call":n.id=t.item.id,n.finishReason="function_call";break}break;case"response.completed":t.response.usage&&(this.tokensUsed={promptTokens:t.response.usage.prompt_tokens,completionTokens:t.response.usage.completion_tokens,totalTokens:t.response.usage.total_tokens}),r=t.response.id,n.id=`${t.response.id}_completed`,n.finishReason="stop";break;case"response.failed":r=t.response.id,n.id=`${t.response.id}_failed`,n.finishReason="error";break;case"response.incomplete":r=t.response.id,n.id=`${t.response.id}_incomplete`,n.finishReason="length";break;case"error":n.id="error",n.content=`Error: ${t.message}`,n.finishReason="error";break;default:n.id="unknown";break}return{results:[n],remoteId:r}}createEmbedReq(e){let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]}},go=(s,e)=>{let t=s.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(r=>r.refusal).join(`
|
|
118
|
+
`);throw new U(n,void 0,e)}return s.filter(n=>n.type==="output_text").map(n=>n.text).join(`
|
|
119
|
+
`)};var Gt=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),gi=()=>({...Gt(),model:"gpt-4o",temperature:.5}),hi=()=>({...Gt(),model:"gpt-4o",temperature:.9}),Nt=class extends j{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=[],models:i,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let p=new st(t,n?.streamingUsage??!0,a),c=i;super(p,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:c})}},it=class extends Nt{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...bn,...o??[]];let i=a=>{let l=ie({model:a,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.hasThinkingBudget??!1,hasShowThoughts:l?.hasShowThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}};super({apiKey:e,config:{...Gt(),...t},options:n,modelInfo:o,models:r,supportFor:i})}};async function Bn(s,e,t={}){if(typeof s=="string")return[{type:"text",text:s}];if(!Array.isArray(s))return[{type:"text",text:String(s)}];let n=e.getFeatures(),r=[];for(let o of s)try{switch(o.type){case"text":r.push({type:"text",text:o.text});break;case"image":if(n.media.images.supported)o.altText?r.push({type:"text",text:`[Image: ${o.altText}]`}):r.push({type:"text",text:"[Image content]"});else if(o.altText)r.push({type:"text",text:o.altText});else if(t.imageToText)try{let i=await t.imageToText(o.image);r.push({type:"text",text:i})}catch(i){throw new ue(i,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new ae("Images",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:"[Image content not supported by this provider]"})}break;case"audio":if(n.media.audio.supported)o.transcription?r.push({type:"text",text:o.transcription}):r.push({type:"text",text:"[Audio content]"});else if(o.transcription)r.push({type:"text",text:o.transcription});else if(t.audioToText)try{let i=await t.audioToText(o.data,o.format);r.push({type:"text",text:i})}catch(i){throw new ue(i,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new ae("Audio",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:"[Audio content not supported by this provider]"})}break;case"file":if(n.media.files.supported)o.extractedText?r.push({type:"text",text:o.extractedText}):r.push({type:"text",text:`[File: ${o.filename}]`});else if(o.extractedText)r.push({type:"text",text:o.extractedText});else if(t.fileToText)try{let i=await t.fileToText(o.data,o.mimeType);r.push({type:"text",text:i})}catch(i){throw new ue(i,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new ae("Files",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:`[File: ${o.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)o.cachedContent?r.push({type:"text",text:o.cachedContent}):r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`});else if(o.cachedContent)r.push({type:"text",text:o.cachedContent});else if(t.urlToText)try{let i=await t.urlToText(o.url);r.push({type:"text",text:i})}catch(i){throw new ue(i,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new ae("URLs",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`})}break;default:typeof o=="object"&&o.text?r.push({type:"text",text:o.text}):r.push({type:"text",text:String(o)})}}catch(i){throw i instanceof ae||i instanceof ue?i:new ue(i,o.type||"unknown","content processing")}return r}function fi(s){let e=!1,t=!1,n=!1,r=!1;for(let o of s)if(o.role==="user"&&Array.isArray(o.content))for(let i of o.content)switch(i.type){case"image":e=!0;break;case"audio":t=!0;break;case"file":n=!0;break;case"url":r=!0;break}return{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r}}var Ut=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(Ut||{});var qn=[{name:"reka-core",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"reka-flash",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2},{name:"reka-edge",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1}];var Bt=()=>structuredClone({model:"reka-core",...L()}),xi=()=>structuredClone({...Bt(),model:"reka-core"}),yi=()=>structuredClone({model:"reka-core",...W()}),Ii=()=>({...Bt(),model:"reka-flash"}),ho=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=e=>{let t=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let n={name:"/chat/completions"},r=yl(e),o=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,i=e.modelConfig?.stream??this.config.stream,a={model:t,messages:r,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.temperature,top_k:e.modelConfig?.n??this.config.n,top_p:e.modelConfig?.topP??this.config.topP??1,stop:e.modelConfig?.stopSequences??this.config.stop,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...o?{frequency_penalty:o}:{},...i?{stream:!0}:{}};return[n,a]};createChatResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((i,a)=>{let l=Ai(i.finish_reason),p;return typeof i.message.content=="string"?p=i.message.content:p=i.message.content.text,{index:a,id:`${t}`,content:p,finishReason:l}}),remoteId:t}};createChatStreamResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((i,a)=>{let l=Ai(i.finish_reason),p;return typeof i.chunk.content=="string"?p=i.chunk.content:p=i.chunk.content.text,{index:a,id:`${t}`,content:p,finishReason:l}})}}},Ai=s=>{switch(s){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function yl(s){return s.chatPrompt.map(e=>{switch(e.role){case"system":return{role:"user",content:e.content};case"user":return Array.isArray(e.content)?{role:"user",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})}:{role:"user",content:e.content};case"assistant":if(Array.isArray(e.content))return{role:"assistant",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})};if(!e.content)throw new Error("Assistant content is empty");return{role:"user",content:e.content};default:throw new Error("Invalid role")}})}var at=class extends j{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=qn,models:i}){if(!e||e==="")throw new Error("Reka API key not set");let a={...Bt(),...t},l=new ho(a);super(l,{name:"Reka",apiURL:r||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:o,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:i})}};var zn=class{providers;processingServices;config;constructor(e){this.providers=[e.providers.primary,...e.providers.alternatives],this.processingServices=e.processing,this.config=e.routing}async chat(e,t={}){let n=await this.selectProviderWithDegradation(e,t.routingOptions||{}),r=await this.preprocessRequest(e,n.provider,t.processingOptions);try{return{response:await n.provider.chat(r,t),routing:n}}catch(o){if(o instanceof ae&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw o}}async preprocessRequest(e,t,n){let r={...n,fallbackBehavior:n?.fallbackBehavior||"degrade",imageToText:n?.imageToText||this.processingServices.imageToText,audioToText:n?.audioToText||this.processingServices.audioToText,fileToText:n?.fileToText||this.processingServices.fileToText,urlToText:n?.urlToText||this.processingServices.urlToText},o=[];for(let i of e.chatPrompt)if(i.role==="user"&&Array.isArray(i.content)){let a=await Bn(i.content,t,r);a.every(p=>p.type==="text")&&a.length===1?o.push({...i,content:a[0].text}):o.push({...i,content:a.map(p=>({type:"text",text:p.text}))})}else o.push(i);return{...e,chatPrompt:o}}async selectProviderWithDegradation(e,t){let n=$e(e),r=[],o=[],i=[];try{let a=Sn(e,this.providers,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation}),l=a.getFeatures();return n.hasImages&&!l.media.images.supported&&(o.push("Images will be converted to text descriptions"),r.push("Image-to-text conversion")),n.hasAudio&&!l.media.audio.supported&&(o.push("Audio will be transcribed to text"),r.push("Audio-to-text transcription")),n.hasFiles&&!l.media.files.supported&&(o.push("File content will be extracted to text"),r.push("File-to-text extraction")),n.hasUrls&&!l.media.urls.supported&&(o.push("URL content will be pre-fetched"),r.push("URL content fetching")),n.requiresStreaming&&!l.streaming&&i.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!l.caching.supported&&i.push("Content caching not supported"),{provider:a,processingApplied:r,degradations:o,warnings:i}}catch(a){throw new Error(`Provider selection failed: ${a instanceof Error?a.message:"Unknown error"}`)}}async tryFallbackProviders(e,t,n){for(let r of t)try{let o={provider:r,processingApplied:["Fallback provider selection"],degradations:["Using fallback provider due to primary provider failure"],warnings:[]},i=await this.preprocessRequest(e,r,{fallbackBehavior:"degrade"});return{response:await r.chat(i,n),routing:o}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=$e(e),n=[],r=[];try{let o=await this.selectProviderWithDegradation(e,{});return o.degradations.length>0&&(n.push(...o.degradations),r.push("Consider using a provider that natively supports all media types")),o.warnings.length>0&&n.push(...o.warnings),t.hasImages&&this.processingServices.imageToText===void 0&&(this.providers.some(a=>a.getFeatures().media.images.supported)||(n.push("No image processing service available and no providers support images"),r.push("Add imageToText processing service or use image-capable provider"))),t.hasAudio&&this.processingServices.audioToText===void 0&&(this.providers.some(a=>a.getFeatures().media.audio.supported)||(n.push("No audio processing service available and no providers support audio"),r.push("Add audioToText processing service or use audio-capable provider"))),{canHandle:n.length===0||o.degradations.length>0,issues:n,recommendations:r}}catch(o){return{canHandle:!1,issues:[`Cannot route request: ${o instanceof Error?o.message:"Unknown error"}`],recommendations:["Add more providers or processing services to handle this request"]}}}getRoutingStats(){let e={};for(let t of this.providers){let n=t.getFeatures(),r=t.getName();n.functions&&(e.Functions=e.Functions||[],e.Functions.push(r)),n.streaming&&(e.Streaming=e.Streaming||[],e.Streaming.push(r)),n.media.images.supported&&(e.Images=e.Images||[],e.Images.push(r)),n.media.audio.supported&&(e.Audio=e.Audio||[],e.Audio.push(r)),n.media.files.supported&&(e.Files=e.Files||[],e.Files.push(r)),n.media.urls.supported&&(e.URLs=e.URLs||[],e.URLs.push(r)),n.caching.supported&&(e.Caching=e.Caching||[],e.Caching.push(r))}return{totalProviders:this.providers.length,capabilityMatrix:e,recommendedProvider:this.providers[0]?.getName()||"None"}}};var jn=[];var fo=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...L()}),lt=class extends K{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Together API key not set");let i={...fo(),...t};o=[...jn,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:i,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:o,models:r,supportFor:a}),super.setName("Together")}};function Hn(s){let e=n=>JSON.stringify(n,null,2);if(!s)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(s)}`);let t=s?.role;if(!t)throw new Error(`Chat request message must have a role, received: ${e(t)}`);switch(t){case"system":{let n=s;if(!n.content||n.content.trim()==="")throw new Error(`System message content cannot be empty or whitespace-only, received: ${e(n.content)}`);break}case"user":{let n=s;if(!n.content)throw new Error(`User message content cannot be undefined, received: ${e(n.content)}`);if(typeof n.content=="string"){if(n.content.trim()==="")throw new Error(`User message content cannot be empty or whitespace-only, received: ${e(n.content)}`)}else if(Array.isArray(n.content)){if(n.content.length===0)throw new Error(`User message content array cannot be empty, received: ${e(n.content)}`);for(let r=0;r<n.content.length;r++){let o=n.content[r];if(!o||typeof o!="object")throw new Error(`User message content item at index ${r} must be an object, received: ${e(o)}`);let i=o?.type;if(!i)throw new Error(`User message content item at index ${r} must have a type, received: ${e(i)}`);switch(i){case"text":{let a=o;if(!a.text||a.text.trim()==="")throw new Error(`User message text content at index ${r} cannot be empty or whitespace-only, received: ${e(a.text)}`);break}case"image":{let a=o;if(!a.image||a.image.trim()==="")throw new Error(`User message image content at index ${r} cannot be empty, received: ${e(a.image)}`);if(!a.mimeType||a.mimeType.trim()==="")throw new Error(`User message image content at index ${r} must have a mimeType, received: ${e(a.mimeType)}`);break}case"audio":{let a=o;if(!a.data||a.data.trim()==="")throw new Error(`User message audio content at index ${r} cannot be empty, received: ${e(a.data)}`);break}default:throw new Error(`User message content item at index ${r} has unsupported type: ${e(i)}`)}}}else throw new Error(`User message content must be a string or array of content objects, received: ${e(n.content)}`);break}case"assistant":{let n=s;if(!n.content&&!n.functionCalls)throw new Error(`Assistant message must have either content or function calls, received content: ${e(n.content)}, functionCalls: ${e(n.functionCalls)}`);if(n.content&&typeof n.content!="string")throw new Error(`Assistant message content must be a string, received: ${e(n.content)}`);if(n.functionCalls&&!Array.isArray(n.functionCalls))throw new Error(`Assistant message function calls must be an array, received: ${e(n.functionCalls)}`);break}case"function":{let n=s;if(!n.functionId||n.functionId.trim()==="")throw new Error(`Function message must have a non-empty functionId, received: ${e(n.functionId)}`);if(n.result===void 0||n.result===null)throw new Error(`Function message must have a result, received: ${e(n.result)}`);if(typeof n.result!="string")throw new Error(`Function message result must be a string, received: ${e(n.result)}`);break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function Kn(s){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(s)?s:[s];if(t.length===0)throw new Error(`Chat response results cannot be empty, received: ${e(t)}`);for(let n=0;n<t.length;n++){let r=t[n];if(!r)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(r)}`);if(typeof r.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(r.index)}`);if(r.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(r.index)}`);if(!r.content&&!r.thought&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,functionCalls:r.functionCalls,finishReason:r.finishReason})}`);if(r.content!==void 0&&typeof r.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(r.content)}`);if(r.thought!==void 0&&typeof r.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(r.thought)}`);if(r.name!==void 0){if(typeof r.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(r.name)}`);if(r.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(r.name)}`)}if(r.annotations!==void 0){if(!Array.isArray(r.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(r.annotations)}`);for(let o=0;o<r.annotations.length;o++){let i=r.annotations[o];if(!i||typeof i!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must be an object, received: ${e(i)}`);if(i.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${o}] must have type 'url_citation', received: ${e(i.type)}`);if(!i.url_citation||typeof i.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must have a valid url_citation object, received: ${e(i.url_citation)}`);if(typeof i.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${o}] url_citation.url must be a string, received: ${e(i.url_citation.url)}`)}}if(r.id!==void 0){if(typeof r.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(r.id)}`);if(r.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(r.id)}`)}if(r.functionCalls!==void 0){if(!Array.isArray(r.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(r.functionCalls)}`);for(let o=0;o<r.functionCalls.length;o++){let i=r.functionCalls[o];if(!i)throw new Error(`Function call at index ${o} in result ${n} cannot be null or undefined, received: ${e(i)}`);if(!i.id||typeof i.id!="string"||i.id.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty string id, received: ${e(i.id)}`);if(i.type!=="function")throw new Error(`Function call at index ${o} in result ${n} must have type 'function', received: ${e(i.type)}`);if(!i.function)throw new Error(`Function call at index ${o} in result ${n} must have a function object, received: ${e(i.function)}`);if(!i.function.name||typeof i.function.name!="string"||i.function.name.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty function name, received: ${e(i.function.name)}`);if(i.function.params!==void 0&&typeof i.function.params!="string"&&typeof i.function.params!="object")throw new Error(`Function call params at index ${o} in result ${n} must be a string or object, received: ${e(i.function.params)}`)}}if(r.finishReason!==void 0){let o=["stop","length","function_call","content_filter","error"];if(!o.includes(r.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${o.join(", ")}, received: ${e(r.finishReason)}`)}}}var qt=(u=>(u.Llama31_8B_Instruct="Llama-3.1-8B-Instruct-q4f32_1-MLC",u.Llama31_70B_Instruct="Llama-3.1-70B-Instruct-q4f16_1-MLC",u.Llama32_1B_Instruct="Llama-3.2-1B-Instruct-q4f32_1-MLC",u.Llama32_3B_Instruct="Llama-3.2-3B-Instruct-q4f32_1-MLC",u.Mistral7B_Instruct="Mistral-7B-Instruct-v0.3-q4f32_1-MLC",u.Phi35_Mini_Instruct="Phi-3.5-mini-instruct-q4f32_1-MLC",u.Gemma2_2B_Instruct="gemma-2-2b-it-q4f32_1-MLC",u.Gemma2_9B_Instruct="gemma-2-9b-it-q4f32_1-MLC",u.Qwen2_5_0_5B_Instruct="Qwen2.5-0.5B-Instruct-q4f32_1-MLC",u.Qwen2_5_1_5B_Instruct="Qwen2.5-1.5B-Instruct-q4f32_1-MLC",u.Qwen2_5_3B_Instruct="Qwen2.5-3B-Instruct-q4f32_1-MLC",u.Qwen2_5_7B_Instruct="Qwen2.5-7B-Instruct-q4f32_1-MLC",u))(qt||{});var Vn=[{name:"Llama-3.1-8B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"Llama-3.1-70B-Instruct-q4f16_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096,isExpensive:!0},{name:"Llama-3.2-1B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Llama-3.2-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Mistral-7B-Instruct-v0.3-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096},{name:"Phi-3.5-mini-instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"gemma-2-2b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"gemma-2-9b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"Qwen2.5-0.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-1.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-7B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096}];var xo=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...L()}),bi=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...W()}),Ao=class{constructor(e,t){this.config=e;this.engine=t}tokensUsed;engine;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.map(a=>{if(a.role==="function")return{role:"function",name:a.functionId,content:typeof a.result=="string"?a.result:JSON.stringify(a.result)};let l="";typeof a.content=="string"?l=a.content:Array.isArray(a.content)&&(l=a.content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
120
|
+
`));let p={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...p,tool_calls:a.functionCalls.map(c=>({id:c.id,type:"function",function:{name:c.function.name,arguments:typeof c.function.params=="string"?c.function.params:JSON.stringify(c.function.params||{})}}))}:p}),r=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),o={name:"/chat/completions",localCall:async(a,l)=>{try{let p=await this.engine.chat.completions.create({...a,stream:l||!1});return l?new ReadableStream({async start(c){try{for await(let d of p)c.enqueue(d);c.close()}catch(d){c.error(d)}}}):p}catch(p){throw new Error(`WebLLM API error: ${p}`)}}},i={model:t,messages:n,...r?.length?{tools:r}:{},max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.temperature,top_p:e.modelConfig?.topP??this.config.topP,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,stop:e.modelConfig?.stopSequences??this.config.stopSequences,stream:e.modelConfig?.stream??this.config.stream,n:e.modelConfig?.n??this.config.n};return[o,i]}createEmbedReq=e=>{throw new Error("WebLLM does not support embeddings")};createChatResp=e=>(this.tokensUsed={promptTokens:e.usage?.prompt_tokens??0,completionTokens:e.usage?.completion_tokens??0,totalTokens:e.usage?.total_tokens??0},{results:e.choices.map((n,r)=>{let o="stop";switch(n.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let i=n.message.tool_calls?.map(a=>({id:a.id,type:"function",function:{name:a.function.name,params:a.function.arguments}}));return{index:r,id:e.id,content:n.message.content||"",functionCalls:i,finishReason:o}}),remoteId:e.id});createChatStreamResp=(e,t)=>{let n=t,r=e.choices[0];if(!r)throw new Error("No choice in WebLLM stream response");if(r.delta.content&&(n.content=(n.content||"")+r.delta.content),r.delta.tool_calls){n.toolCalls||(n.toolCalls=[]);for(let l of r.delta.tool_calls){let p=n.toolCalls[l.index];p?l.function?.arguments&&(p.function.arguments=(p.function?.arguments||"")+l.function.arguments):n.toolCalls[l.index]={id:l.id,type:l.type,function:{name:l.function?.name,arguments:l.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let o;if(r.finish_reason)switch(r.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let i=n.toolCalls?.map(l=>({id:l.id||"",type:"function",function:{name:l.function?.name||"",params:l.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:i,finishReason:o}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},pt=class extends j{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let o={...xo(),...t},i=new Ao(o,e);super(i,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:Vn,defaults:{model:o.model},supportFor:a=>({functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}),options:n,models:r})}};var zt=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(zt||{}),yo=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(yo||{});var Wn=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,hasThinkingBudget:!0},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,hasThinkingBudget:!0}];var Yn=()=>structuredClone({model:"grok-3-mini",...L()}),Ri=()=>structuredClone({...Yn(),model:"grok-3"}),ct=class extends K{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Grok API key not set");let i={...Yn(),...t};o=[...Wn,...o??[]];let a=p=>{let c=ie({model:p,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:c?.hasThinkingBudget??!1,hasShowThoughts:c?.hasShowThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}},l=p=>{if(n?.searchParameters){let c=n.searchParameters;return{...p,search_parameters:{mode:c.mode,return_citations:c.returnCitations,from_date:c.fromDate,to_date:c.toDate,max_search_results:c.maxSearchResults,sources:c.sources?.map(d=>({type:d.type,country:d.country,excluded_websites:d.excludedWebsites,allowed_websites:d.allowedWebsites,safe_search:d.safeSearch,x_handles:d.xHandles,links:d.links}))}}}return p};super({apiKey:e,config:i,options:n,apiURL:"https://api.x.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};function Ci(s){return jt.create(s)}var jt=class s{ai;static create(e){return new s(e)}constructor(e){switch(e.name){case"openai":this.ai=new Ye(e);break;case"openai-responses":this.ai=new it(e);break;case"azure-openai":this.ai=new Je(e);break;case"grok":this.ai=new ct(e);break;case"huggingface":this.ai=new nt(e);break;case"groq":this.ai=new tt(e);break;case"together":this.ai=new lt(e);break;case"cohere":this.ai=new Qe(e);break;case"google-gemini":this.ai=new Ze(e);break;case"anthropic":this.ai=new He(e);break;case"mistral":this.ai=new rt(e);break;case"deepseek":this.ai=new Xe(e);break;case"ollama":this.ai=new ot(e);break;case"reka":this.ai=new at(e);break;case"webllm":this.ai=new pt(e);break;default:throw new Error("Unknown AI")}}getName(){return this.ai.getName()}getId(){return this.ai.getId()}getFeatures(e){return this.ai.getFeatures(e)}getModelList(){return this.ai.getModelList()}getLastUsedChatModel(){return this.ai.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.ai.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.ai.getLastUsedModelConfig()}getMetrics(){return this.ai.getMetrics()}async chat(e,t){return await this.ai.chat(e,t)}async embed(e,t){return await this.ai.embed(e,t)}setOptions(e){this.ai.setOptions(e)}getOptions(){return this.ai.getOptions()}getLogger(){return this.ai.getLogger()}};var pe=class{name;fetch;tracer;_upsert;_batchUpsert;_query;constructor({name:e,fetch:t,tracer:n}){this.name=e,this.fetch=t,this.tracer=n}async upsert(e,t){if(!this._upsert)throw new Error("upsert() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Upsert Request",{kind:le.SERVER,attributes:{[D.DB_SYSTEM]:this.name,[D.DB_OPERATION_NAME]:"upsert",[D.DB_TABLE]:e.table,[D.DB_NAMESPACE]:e.namespace,[D.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._upsert(e,t,{span:n})}finally{n.end()}}):await this._upsert(e,t)}async batchUpsert(e,t){if(!this._batchUpsert)throw new Error("batchUpsert() not implemented");if(e.length===0)throw new Error("Batch request is empty");if(!e[0])throw new Error("Batch request is invalid first element is undefined");return this.tracer?await this.tracer.startActiveSpan("DB Batch Upsert Request",{kind:le.SERVER,attributes:{[D.DB_SYSTEM]:this.name,[D.DB_OPERATION_NAME]:"upsert",[D.DB_TABLE]:e[0].table,[D.DB_NAMESPACE]:e[0].namespace,[D.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._batchUpsert(e,t,{span:n})}finally{n.end()}}):await this._batchUpsert(e,t)}async query(e){if(!this._query)throw new Error("query() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Query Request",{kind:le.SERVER,attributes:{[D.DB_SYSTEM]:this.name,[D.DB_OPERATION_NAME]:"upsert",[D.DB_TABLE]:e.table,[D.DB_NAMESPACE]:e.namespace,[D.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var Io="https://api.cloudflare.com/client/v4/accounts/",ut=class extends pe{apiKey;accountId;constructor({apiKey:e,accountId:t,fetch:n,tracer:r}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:r}),this.apiKey=e,this.accountId=t}_upsert=async(e,t,n)=>{let r=await oe({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,Io),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(r.errors)throw new Error(`Cloudflare upsert failed: ${r.errors.map(({message:o})=>o).join(", ")}`);return{ids:r.result.ids}};batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length<1)throw new Error("Batch request is empty");if(!e[0]||!e[0].table)throw new Error("Table name is empty");let r=e[0].table,o=await oe({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,Io),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(i=>({id:i.id,values:i.values,namespace:i.namespace,metadata:i.metadata})));if(o.errors)throw new Error(`Cloudflare batch upsert failed: ${o.errors.map(({message:i})=>i).join(", ")}`);return{ids:o.result.ids}};query=async(e,t)=>{let n=await oe({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,Io),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:t?.span},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:o})=>o).join(", ")}`);return{matches:n.result.matches.map(({id:o,score:i,values:a,metadata:l})=>({id:o,score:i,values:a,metadata:l}))}}};var Se=class extends pe{state;constructor({tracer:e}={}){super({name:"Memory",tracer:e}),this.state={}}_upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let r=this.state[e.table];if(!r)throw new Error(`Table not found: ${e.table}`);r[e.id]=e}return{ids:[e.id]}};_batchUpsert=async(e,t,n)=>{let r=[];for(let o of e){let i=await this.upsert(o,t);r.push(...i.ids)}return{ids:r}};_query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let r=[];return Object.entries(n).forEach(([o,i])=>{if(e.values&&i.values){let a=Il(e.values,i.values);r.push({id:o,score:a,metadata:i.metadata})}}),r.sort((o,i)=>o.score-i.score),e.limit&&(r.length=e.limit),{matches:r}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},Il=(s,e)=>{if(s.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,r=0,o=!0,i=!0,a=new Float64Array(s),l=new Float64Array(e);for(let u=0;u<a.length;u++)t+=a[u]*l[u],n+=a[u]*a[u],r+=l[u]*l[u],a[u]!==0&&(o=!1),l[u]!==0&&(i=!1);if(o||i)return 1;let p=Math.sqrt(n),c=Math.sqrt(r);return 1-t/(p*c)};var bl=s=>({namespace:s.namespace,topK:s.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:s.values??[],id:s.id}),dt=class extends pe{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]});_batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await oe({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:r,values:o=[],metadata:i})=>({id:r,values:o,metadata:i}))),{ids:e.map(({id:r})=>r)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await oe({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},bl(e))).matches.map(({id:o,score:i,values:a,metadata:l})=>({id:o,score:i,metadata:l,values:a}))}}};var mt=class extends pe{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>{let r=await oe({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:n?.span},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:e.metadata??{}});if(r?.result?.errors)throw new Error(`Weaviate upsert failed: ${r.result.errors.error.map(({message:o})=>o).join(", ")}`);return{ids:[r.id]}};_batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length===0)throw new Error("Batch request is empty");let r=e.map(i=>({id:i.id,class:i.table,tenant:i.namespace,vector:i.values,properties:i.metadata??{}})),o=await oe({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:r});if(o?.some(({result:i})=>i?.errors))throw new Error(`Weaviate batch upsert failed: ${o.map(({result:i})=>i?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:o.map(({id:i})=>i)}};_query=async(e,t)=>{let n="";if(e.columns&&e.columns.length===0)throw new Error("Weaviate requires at least one column");if(e.values)n=`nearVector: {
|
|
119
121
|
vector: [${e.values.join(",")}],
|
|
120
122
|
}`;else if(e.text)n=`nearText: {
|
|
121
123
|
concepts: ['${e.text}'],
|
|
122
|
-
}`;else throw new Error("Weaviate requires either text or values");let
|
|
124
|
+
}`;else throw new Error("Weaviate requires either text or values");let r=await oe({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/graphql",fetch:this.fetch,span:t?.span},{query:`{
|
|
123
125
|
Get {
|
|
124
126
|
${e.table} (
|
|
125
127
|
limit: ${e.limit||10},
|
|
@@ -129,98 +131,98 @@ ${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
|
|
|
129
131
|
`)}
|
|
130
132
|
}
|
|
131
133
|
}
|
|
132
|
-
}`});if(
|
|
134
|
+
}`});if(r.errors)throw new Error(`Weaviate query failed: ${r.errors.map(({message:a})=>a).join(", ")}`);let o=r.data.Get[e.table];return o?{matches:o.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var Jn=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new mt(e);break;case"pinecone":this.db=new dt(e);break;case"cloudflare":this.db=new ut(e);break;case"memory":this.db=new Se(e);break;default:throw new Error("Unknown DB")}}async upsert(e,t){return await this.db.upsert(e,t)}async batchUpsert(e,t){return await this.db.batchUpsert(e,t)}async query(e){return await this.db.query(e)}};var bo="_internal",Qn=class{ai;db;chunker;rewriter;reranker;constructor({ai:e,db:t,config:n}){this.ai=e,this.db=t,this.chunker=n?.chunker??this.defaultChunker,this.reranker=n?.reranker,this.rewriter=n?.rewriter}defaultChunker=e=>e.split(/\n\n+/);insert=async(e,t)=>{try{let n=Array.isArray(e)?e.join(`
|
|
133
135
|
|
|
134
|
-
`):e,
|
|
136
|
+
`):e,r=this.chunker(n).filter(p=>p.length>0),o=t?.maxWordsPerChunk,i=t?.minWordsPerChunk,a=Rl({initialChunks:r,minWordsPerChunk:i,maxWordsPerChunk:o}),l=t?.batchSize??10;for(let p=0;p<a.length;p+=l){let c=a.slice(p,p+l),u=(await this.ai.embed({texts:c},{abortSignal:t?.abortSignal})).embeddings.map((m,g)=>({id:`chunk_${Date.now()+g}`,table:bo,values:m,metadata:{text:c[g]??""}})).filter(m=>m.metadata?.text&&m.metadata?.text.length>0);await this.db.batchUpsert(u)}}catch(n){throw new Error(`Error processing text: ${n}`)}};query=async(e,{topPercent:t,abortSignal:n}={})=>{let r=Array.isArray(e)?e:[e];if(typeof r[0]=="string"&&this.rewriter)for(let[l,p]of r.entries()){let{rewrittenQuery:c}=await this.rewriter.forward(this.ai,{query:p});r[l]=c}let o;typeof r[0]=="string"?o=(await this.ai.embed({texts:r},{abortSignal:n})).embeddings.map(p=>this.db.query({table:bo,values:p})):o=r.map(l=>this.db.query({table:bo,values:l}));let i=await Promise.all(o),a=[];for(let{matches:l}of i){let p=l.filter(u=>u.metadata?.text&&u.metadata?.text.length>0).map(({score:u,metadata:m})=>({score:u,text:m?.text??""})),c=t&&t>1?t/100:t,d=c?Cl(p,c):p;if(this.reranker){let{rankedItems:u}=await this.reranker.forward(this.ai,{query:r[0],items:d.map(g=>g.text)}),m=u.map(g=>d.find(h=>h.text===g)).filter(g=>g!==void 0);a.push(m)}else a.push(d)}return a}},Rl=({initialChunks:s,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],r="",o=0;return s.forEach(i=>{let a=i.split(/\s+/),l=a.length;if(o+l<=e)r+=`${i}
|
|
135
137
|
|
|
136
|
-
`,
|
|
138
|
+
`,o+=l;else if(o>0&&o+l<=e*1.5)r+=`${i}
|
|
137
139
|
|
|
138
|
-
`,
|
|
140
|
+
`,o+=l;else if(o>t&&(n.push(r.trim()),r="",o=0),l>e){let p=a;for(;p.length>e*1.5;){let c=p.splice(0,e);n.push(c.join(" "))}p.length>0&&(r+=`${p.join(" ")}
|
|
139
141
|
|
|
140
|
-
`,
|
|
142
|
+
`,o+=p.length)}else r=`${i}
|
|
141
143
|
|
|
142
|
-
`,r=l}),(r>t||n.length===0)&&n.push(o.trim()),n},nl=(s,e=.1)=>{let t=[...s].sort((o,r)=>o.score-r.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var Ut=class{data=[];addRequest(e,t){this.data.push(...e.map(n=>{let o=structuredClone(n);return{role:n.role,chat:[{index:t,value:o}]}}))}addFunctionResults(e){let t=e.map(({index:o,...r})=>({index:o,value:structuredClone(r)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...o})=>({index:n,value:structuredClone(o)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,index:o}){let r=this.data.at(-1);if(!r||r.role!=="assistant"||r.role==="assistant"&&!r.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:o,value:structuredClone({content:e,name:t,functionCalls:n})}]});return}let i=r.chat.find(a=>a.index===o);if(!i){r.chat.push({index:o,value:structuredClone({content:e,name:t,functionCalls:n})});return}typeof e=="string"&&e.trim()!==""&&(i.value.content=e),typeof t=="string"&&t.trim()!==""&&(i.value.name=t),Array.isArray(n)&&n.length>0&&(i.value.functionCalls=n)}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1)throw new Error(`Tag "${e}" not found`);return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,o,r)=>(o.tags?.includes(e)&&n.push(r),n),[]);if(t.length===0)throw new Error(`No items found with tag "${e}"`);return t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:o}of this.data){let r;n==="function"?r=o.filter(i=>i.index===e).map(i=>i.value):r=o.find(i=>i.index===e)?.value,Array.isArray(r)&&r.length>0?t.push(...r.map(i=>({...i,role:n}))):typeof r=="object"&&r!==null&&t.push({...r,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[]}},pt=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Ut}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Ut),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)En(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){_n(e),this.getMemory(t).addResponse(e)}addFunctionResults(e,t){this.getMemory(t).addFunctionResults(e)}updateResult(e,t){this.getMemory(t).updateResult(e)}addTag(e,t){this.getMemory(t).addTag(e)}rewindToTag(e,t){return this.getMemory(t).rewindToTag(e)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new Ut):this.defaultMemory.reset()}};var Te=class extends Error{constructor({message:e}){super(e),this.name=this.constructor.name}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Un=async(s,e)=>{for(let t of s){let{fn:n,message:o}=t,r=await n(e);if(r!==void 0&&!r)throw o?new Te({message:o}):new Error("Assertion Failed: No message provided for assertion")}},sr=async(s,e,t,n=!1)=>{if(!e.currField||e.s===-1||!s||s.length===0)return;let o=s.filter(i=>i.fieldName===e.currField?.name);if(o.length===0)return;let r=t.substring(e.s);for(let i of o){let{message:a,fn:l}=i,c=await l(r,n);if(c!==void 0&&!c&&a)throw new Te({message:a})}};var ir={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},$t,ar=s=>{if($t)return $t;let e=s??B.meter;if(e)return $t=ol(e),$t};var si=()=>{let s=[];return B.meter||s.push("Global meter not initialized"),!$t&&B.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},ol=s=>({generationLatencyHistogram:s.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:s.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:s.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:s.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:s.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:s.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:s.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:s.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:s.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:s.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:s.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:s.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:s.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:s.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:s.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:s.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:s.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:s.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:s.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:s.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:s.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:s.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:s.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:s.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:s.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:s.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:s.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:s.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:s.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:s.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:s.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:s.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:s.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),$n=ir,ii=s=>{$n={...$n,...s}},ai=()=>({...$n}),pe=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let o=String(n),r=$n.maxLabelLength;e[t]=o.length>r?o.substring(0,r):o}return e},li=(s,e,t,n,o,r)=>{try{let i=pe({success:t.toString(),...n?{signature:n}:{},...o?{ai_service:o}:{},...r?{model:r}:{}});s.generationLatencyHistogram&&s.generationLatencyHistogram.record(e,i),s.generationRequestsCounter&&s.generationRequestsCounter.add(1,i),!t&&s.generationErrorsCounter&&s.generationErrorsCounter.add(1,i)}catch(i){console.warn("Failed to record generation metric:",i)}},Bn=(s,e,t,n)=>{try{let o=pe({...n?{signature:n}:{}});e>1&&s.multiStepGenerationsCounter&&s.multiStepGenerationsCounter.add(1,o),s.stepsPerGenerationHistogram&&s.stepsPerGenerationHistogram.record(e,o),e>=t&&s.maxStepsReachedCounter&&s.maxStepsReachedCounter.add(1,o)}catch(o){console.warn("Failed to record multi-step metric:",o)}},lr=(s,e,t)=>{try{let n=pe({error_type:e,...t?{signature:t}:{}});e==="validation"&&s.validationErrorsCounter&&s.validationErrorsCounter.add(1,n),e==="assertion"&&s.assertionErrorsCounter&&s.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},ci=(s,e)=>{try{let t=pe({error_type:"refusal",...e?{signature:e}:{}});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},cr=(s,e,t,n,o)=>{try{let r=pe({success:t.toString(),...o?{signature:o}:{}});s.errorCorrectionAttemptsHistogram&&s.errorCorrectionAttemptsHistogram.record(e,r),t&&s.errorCorrectionSuccessCounter&&s.errorCorrectionSuccessCounter.add(1,r),t||(s.errorCorrectionFailureCounter&&s.errorCorrectionFailureCounter.add(1,r),e>=n&&s.maxRetriesReachedCounter&&s.maxRetriesReachedCounter.add(1,r))}catch(r){console.warn("Failed to record error correction metric:",r)}},pr=(s,e,t,n,o=!1,r)=>{try{let i=pe({functions_enabled:e.toString(),had_function_calls:n.toString(),...r?{signature:r}:{}});e&&s.functionsEnabledGenerationsCounter&&s.functionsEnabledGenerationsCounter.add(1,i),n&&s.functionCallStepsCounter&&s.functionCallStepsCounter.add(1,i),t>0&&s.functionsExecutedPerGenerationHistogram&&s.functionsExecutedPerGenerationHistogram.record(t,i),o&&s.functionErrorCorrectionCounter&&s.functionErrorCorrectionCounter.add(1,i)}catch(i){console.warn("Failed to record function calling metric:",i)}},pi=(s,e,t,n)=>{try{let o=pe({...n?{signature:n}:{}});e>0&&s.fieldProcessorsExecutedCounter&&s.fieldProcessorsExecutedCounter.add(e,o),t>0&&s.streamingFieldProcessorsExecutedCounter&&s.streamingFieldProcessorsExecutedCounter.add(t,o)}catch(o){console.warn("Failed to record field processing metric:",o)}},ui=(s,e,t,n,o)=>{try{let r=pe({is_streaming:e.toString(),...o?{signature:o}:{}});e&&s.streamingGenerationsCounter&&s.streamingGenerationsCounter.add(1,r),t>0&&s.streamingDeltasEmittedCounter&&s.streamingDeltasEmittedCounter.add(t,r),n&&s.streamingFinalizationLatencyHistogram&&s.streamingFinalizationLatencyHistogram.record(n,r)}catch(r){console.warn("Failed to record streaming metric:",r)}},di=(s,e,t,n,o)=>{try{let r=pe({result_picker_used:t.toString(),...o?{signature:o}:{}});s.samplesGeneratedHistogram&&s.samplesGeneratedHistogram.record(e,r),t&&s.resultPickerUsageCounter&&s.resultPickerUsageCounter.add(1,r),n&&s.resultPickerLatencyHistogram&&s.resultPickerLatencyHistogram.record(n,r)}catch(r){console.warn("Failed to record samples metric:",r)}},mi=(s,e,t,n,o,r)=>{try{let i=pe({...r?{signature:r}:{}});s.inputFieldsGauge&&s.inputFieldsGauge.record(e,i),s.outputFieldsGauge&&s.outputFieldsGauge.record(t,i),s.examplesUsedGauge&&s.examplesUsedGauge.record(n,i),s.demosUsedGauge&&s.demosUsedGauge.record(o,i)}catch(i){console.warn("Failed to record signature complexity metrics:",i)}},qn=(s,e,t,n)=>{try{let o=pe({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":s.promptRenderLatencyHistogram&&s.promptRenderLatencyHistogram.record(t,o);break;case"extraction":s.extractionLatencyHistogram&&s.extractionLatencyHistogram.record(t,o);break;case"assertion":s.assertionLatencyHistogram&&s.assertionLatencyHistogram.record(t,o);break;case"state_creation":s.stateCreationLatencyHistogram&&s.stateCreationLatencyHistogram.record(t,o);break;case"memory_update":s.memoryUpdateLatencyHistogram&&s.memoryUpdateLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record performance metric:",o)}};var Q=class extends Error{fields;constructor({message:e,fields:t}){super(e),this.fields=t,this.name=this.constructor.name}getFixingInstructions=()=>{let e=t=>{let n=(()=>{switch(t?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return t?.isArray?`json array of ${n} items`:n};return this.fields.map(t=>({name:"outputError",title:"Output Correction Required",description:`The section labeled '${t.title}' does not match the expected format of '${e(t.type)}'. ${this.message} Please revise your response to ensure it conforms to the specified format.`}))};toString(){let e=t=>{let n=(()=>{switch(t?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return t?.isArray?`json array of ${n} items`:n};return[`${this.name}: ${this.message}`,...this.fields.map(t=>` - ${t.title}: Expected format '${e(t.type)}'`)].join(`
|
|
143
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},
|
|
144
|
+
`,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},Cl=(s,e=.1)=>{let t=[...s].sort((r,o)=>r.score-o.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var Ht=class{data=[];addRequest(e,t){this.data.push(...e.map(n=>{let r=structuredClone(n);return{role:n.role,chat:[{index:t,value:r}]}}))}addFunctionResults(e){let t=e.map(({index:r,...o})=>({index:r,value:structuredClone(o)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...r})=>({index:n,value:structuredClone(r)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,index:r}){let o=this.data.at(-1);if(!o||o.role!=="assistant"||o.role==="assistant"&&!o.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:r,value:structuredClone({content:e,name:t,functionCalls:n})}]});return}let i=o.chat.find(a=>a.index===r);if(!i){o.chat.push({index:r,value:structuredClone({content:e,name:t,functionCalls:n})});return}typeof e=="string"&&e.trim()!==""&&(i.value.content=e),typeof t=="string"&&t.trim()!==""&&(i.value.name=t),Array.isArray(n)&&n.length>0&&(i.value.functionCalls=n)}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1)throw new Error(`Tag "${e}" not found`);return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);if(t.length===0)throw new Error(`No items found with tag "${e}"`);return t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:r}of this.data){let o;n==="function"?o=r.filter(i=>i.index===e).map(i=>i.value):o=r.find(i=>i.index===e)?.value,Array.isArray(o)&&o.length>0?t.push(...o.map(i=>({...i,role:n}))):typeof o=="object"&&o!==null&&t.push({...o,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[]}},gt=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Ht}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Ht),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Hn(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Kn(e),this.getMemory(t).addResponse(e)}addFunctionResults(e,t){this.getMemory(t).addFunctionResults(e)}updateResult(e,t){this.getMemory(t).updateResult(e)}addTag(e,t){this.getMemory(t).addTag(e)}rewindToTag(e,t){return this.getMemory(t).rewindToTag(e)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new Ht):this.defaultMemory.reset()}};var Me=class extends Error{constructor({message:e}){super(e),this.name=this.constructor.name}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Xn=async(s,e)=>{for(let t of s){let{fn:n,message:r}=t,o=await n(e);if(o!==void 0&&!o)throw r?new Me({message:r}):new Error("Assertion Failed: No message provided for assertion")}},Ro=async(s,e,t,n=!1)=>{if(!e.currField||e.s===-1||!s||s.length===0)return;let r=s.filter(i=>i.fieldName===e.currField?.name);if(r.length===0)return;let o=t.substring(e.s);for(let i of r){let{message:a,fn:l}=i,p=await l(o,n);if(p!==void 0&&!p&&a)throw new Me({message:a})}};var Co={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Kt,To=s=>{if(Kt)return Kt;let e=s??B.meter;if(e)return Kt=Tl(e),Kt};var Ti=()=>{let s=[];return B.meter||s.push("Global meter not initialized"),!Kt&&B.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},Tl=s=>({generationLatencyHistogram:s.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:s.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:s.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:s.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:s.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:s.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:s.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:s.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:s.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:s.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:s.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:s.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:s.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:s.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:s.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:s.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:s.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:s.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:s.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:s.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:s.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:s.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:s.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:s.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:s.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:s.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:s.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:s.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:s.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:s.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:s.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:s.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:s.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),Zn=Co,wi=s=>{Zn={...Zn,...s}},vi=()=>({...Zn}),me=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=Zn.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},Si=(s,e,t,n,r,o)=>{try{let i=me({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{}});s.generationLatencyHistogram&&s.generationLatencyHistogram.record(e,i),s.generationRequestsCounter&&s.generationRequestsCounter.add(1,i),!t&&s.generationErrorsCounter&&s.generationErrorsCounter.add(1,i)}catch(i){console.warn("Failed to record generation metric:",i)}},er=(s,e,t,n)=>{try{let r=me({...n?{signature:n}:{}});e>1&&s.multiStepGenerationsCounter&&s.multiStepGenerationsCounter.add(1,r),s.stepsPerGenerationHistogram&&s.stepsPerGenerationHistogram.record(e,r),e>=t&&s.maxStepsReachedCounter&&s.maxStepsReachedCounter.add(1,r)}catch(r){console.warn("Failed to record multi-step metric:",r)}},wo=(s,e,t)=>{try{let n=me({error_type:e,...t?{signature:t}:{}});e==="validation"&&s.validationErrorsCounter&&s.validationErrorsCounter.add(1,n),e==="assertion"&&s.assertionErrorsCounter&&s.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},Mi=(s,e)=>{try{let t=me({error_type:"refusal",...e?{signature:e}:{}});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},vo=(s,e,t,n,r)=>{try{let o=me({success:t.toString(),...r?{signature:r}:{}});s.errorCorrectionAttemptsHistogram&&s.errorCorrectionAttemptsHistogram.record(e,o),t&&s.errorCorrectionSuccessCounter&&s.errorCorrectionSuccessCounter.add(1,o),t||(s.errorCorrectionFailureCounter&&s.errorCorrectionFailureCounter.add(1,o),e>=n&&s.maxRetriesReachedCounter&&s.maxRetriesReachedCounter.add(1,o))}catch(o){console.warn("Failed to record error correction metric:",o)}},So=(s,e,t,n,r=!1,o)=>{try{let i=me({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{}});e&&s.functionsEnabledGenerationsCounter&&s.functionsEnabledGenerationsCounter.add(1,i),n&&s.functionCallStepsCounter&&s.functionCallStepsCounter.add(1,i),t>0&&s.functionsExecutedPerGenerationHistogram&&s.functionsExecutedPerGenerationHistogram.record(t,i),r&&s.functionErrorCorrectionCounter&&s.functionErrorCorrectionCounter.add(1,i)}catch(i){console.warn("Failed to record function calling metric:",i)}},Oi=(s,e,t,n)=>{try{let r=me({...n?{signature:n}:{}});e>0&&s.fieldProcessorsExecutedCounter&&s.fieldProcessorsExecutedCounter.add(e,r),t>0&&s.streamingFieldProcessorsExecutedCounter&&s.streamingFieldProcessorsExecutedCounter.add(t,r)}catch(r){console.warn("Failed to record field processing metric:",r)}},ki=(s,e,t,n,r)=>{try{let o=me({is_streaming:e.toString(),...r?{signature:r}:{}});e&&s.streamingGenerationsCounter&&s.streamingGenerationsCounter.add(1,o),t>0&&s.streamingDeltasEmittedCounter&&s.streamingDeltasEmittedCounter.add(t,o),n&&s.streamingFinalizationLatencyHistogram&&s.streamingFinalizationLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record streaming metric:",o)}},Ei=(s,e,t,n,r)=>{try{let o=me({result_picker_used:t.toString(),...r?{signature:r}:{}});s.samplesGeneratedHistogram&&s.samplesGeneratedHistogram.record(e,o),t&&s.resultPickerUsageCounter&&s.resultPickerUsageCounter.add(1,o),n&&s.resultPickerLatencyHistogram&&s.resultPickerLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record samples metric:",o)}},Pi=(s,e,t,n,r,o)=>{try{let i=me({...o?{signature:o}:{}});s.inputFieldsGauge&&s.inputFieldsGauge.record(e,i),s.outputFieldsGauge&&s.outputFieldsGauge.record(t,i),s.examplesUsedGauge&&s.examplesUsedGauge.record(n,i),s.demosUsedGauge&&s.demosUsedGauge.record(r,i)}catch(i){console.warn("Failed to record signature complexity metrics:",i)}},tr=(s,e,t,n)=>{try{let r=me({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":s.promptRenderLatencyHistogram&&s.promptRenderLatencyHistogram.record(t,r);break;case"extraction":s.extractionLatencyHistogram&&s.extractionLatencyHistogram.record(t,r);break;case"assertion":s.assertionLatencyHistogram&&s.assertionLatencyHistogram.record(t,r);break;case"state_creation":s.stateCreationLatencyHistogram&&s.stateCreationLatencyHistogram.record(t,r);break;case"memory_update":s.memoryUpdateLatencyHistogram&&s.memoryUpdateLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record performance metric:",r)}};var J=class extends Error{fields;constructor({message:e,fields:t}){super(e),this.fields=t,this.name=this.constructor.name}getFixingInstructions=()=>{let e=t=>{let n=(()=>{switch(t?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return t?.isArray?`json array of ${n} items`:n};return this.fields.map(t=>({name:"outputError",title:"Output Correction Required",description:`The section labeled '${t.title}' does not match the expected format of '${e(t.type)}'. ${this.message} Please revise your response to ensure it conforms to the specified format.`}))};toString(){let e=t=>{let n=(()=>{switch(t?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return t?.isArray?`json array of ${n} items`:n};return[`${this.name}: ${this.message}`,...this.fields.map(t=>` - ${t.title}: Expected format '${e(t.type)}'`)].join(`
|
|
145
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},_i=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{let a=s.getFixingInstructions();if(t&&n){let l=a?.map(p=>p.title).join(", ")??"";Os(s,e,l,n)}return r&&wo(r,"validation",o),i&&i.addEvent("validation.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Fi=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{let a=s.getFixingInstructions();if(t&&n){let l=a?.map(p=>p.title).join(", ")??"";ks(s,e,l,n)}return r&&wo(r,"assertion",o),i&&i.addEvent("assertion.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Di=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{t&&n&&Es(s,e,n),r&&Mi(r,o),i&&i.addEvent("refusal.error",{message:s.toString()})};var $i=s=>{let e=[],t=(n,r="")=>{if(!n||typeof n!="object")return;let o=["array","integer","number","string","boolean","null","object"];if(n.anyOf&&Array.isArray(n.anyOf)){n.anyOf.length===0&&e.push({path:r||"root",issue:"anyOf array is empty",fix:"Add at least one schema to the anyOf array",example:'anyOf: [{ type: "string" }, { type: "null" }]'}),n.anyOf.forEach((i,a)=>{t(i,`${r}anyOf[${a}].`)});return}if(n.oneOf&&Array.isArray(n.oneOf)){n.oneOf.length===0&&e.push({path:r||"root",issue:"oneOf array is empty",fix:"Add at least one schema to the oneOf array",example:'oneOf: [{ type: "string" }, { type: "number" }]'}),n.oneOf.forEach((i,a)=>{t(i,`${r}oneOf[${a}].`)});return}if(n.allOf&&Array.isArray(n.allOf)){n.allOf.length===0&&e.push({path:r||"root",issue:"allOf array is empty",fix:"Add at least one schema to the allOf array",example:'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'}),n.allOf.forEach((i,a)=>{t(i,`${r}allOf[${a}].`)});return}if(n.type){if(!o.includes(n.type)){e.push({path:r||"root",issue:`Invalid type '${n.type}'`,fix:`Change type to one of: ${o.join(", ")}`,example:'{ type: "string" } or { type: "object" }'});return}if(n.type==="object"){if(n.properties)if(typeof n.properties!="object"||Array.isArray(n.properties))e.push({path:r||"root",issue:"properties must be an object, not an array or primitive",fix:"Change properties to be an object with property names as keys",example:'properties: { name: { type: "string" }, age: { type: "number" } }'});else for(let i in n.properties){let a=n.properties[i];if(a!=null){if(typeof a!="object"){e.push({path:`${r}${i}`,issue:`Property schema must be an object, got ${typeof a}`,fix:"Define the property as a proper schema object",example:`${i}: { type: "string", description: "..." }`});continue}t(a,`${r}${i}.`)}}if(n.required){if(!Array.isArray(n.required))e.push({path:r||"root",issue:`'required' must be an array, got ${typeof n.required}`,fix:"Change required to be an array of property names",example:'required: ["name", "email"] instead of required: "name,email"'});else if(n.required.length!==0){if(n.properties)for(let i of n.required)typeof i!="string"?e.push({path:`${r}required`,issue:`Required property names must be strings, got ${typeof i}`,fix:"Ensure all items in required array are strings",example:'required: ["name", "email"] not required: [123, "email"]'}):i in n.properties||e.push({path:`${r}required`,issue:`Required property '${i}' is not defined in properties`,fix:`Either add '${i}' to properties or remove it from required`,example:`properties: { ${i}: { type: "string" } }`})}}}n.type==="array"&&n.items&&(typeof n.items!="object"?e.push({path:`${r}items`,issue:`Array items schema must be an object, got ${typeof n.items}`,fix:"Define items as a proper schema object",example:'items: { type: "string" } or items: { type: "object", properties: {...} }'}):t(n.items,`${r}items.`))}};if(t(s),e.length>0){let n=["JSON Schema validation failed:","",...e.map((r,o)=>{let i=[`${o+1}. Path: ${r.path}`,` Issue: ${r.issue}`,` Fix: ${r.fix}`];return r.example&&i.push(` Example: ${r.example}`),i.join(`
|
|
144
146
|
`)}),"","Please fix these issues and try again."].join(`
|
|
145
|
-
`);throw new Error(n)}};var
|
|
146
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},
|
|
147
|
+
`);throw new Error(n)}};var Vt=class extends Error{constructor(t){super();this.fields=t;this.name=this.constructor.name}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
|
|
148
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},nr=class extends Error{constructor(t,n,r){super();this.fields=t;this.func=n;this.funcId=r}getFunctionId=()=>this.funcId;getFieldDescription(t){if(!this.func.parameters?.properties?.[t])return"";let n=this.func.parameters.properties[t],r=n.description;return n.enum?.length&&(r+=` Allowed values are: ${n.enum.join(", ")}`),r}getFixingInstructions=()=>{let t=this.fields.map(n=>{let r=this.getFieldDescription(n.field)||"";return`- \`${n.field}\` - ${n.message} (${r}).`});return`Errors In Function Arguments: Fix the following invalid arguments to '${this.func.name}'
|
|
147
149
|
${t.join(`
|
|
148
150
|
`)}`};toString(){return[`${this.name}: Function execution error in '${this.func.name}'`,...this.fields.map(t=>{let n=this.getFieldDescription(t.field);return` - ${t.field}: ${t.message}${n?` (${n})`:""}`}),this.funcId?` Function ID: ${this.funcId}`:""].join(`
|
|
149
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},
|
|
150
|
-
`),
|
|
151
|
-
`)+
|
|
152
|
-
`)+
|
|
153
|
-
Content: ${
|
|
154
|
-
Content: ${b.content}`)}let x=l.map(b=>b.values);for(let b of x)for(let T of g.getOutputFields())T.isInternal&&delete b[T.name];let y=g.getOutputFields(),
|
|
155
|
-
`)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new F(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(o){throw o instanceof F?o:new F(`Invalid first ${t} field: ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new F(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(o){throw o instanceof F?o:new F(`Invalid ${t} field after comma: ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new F(`Input field "${e}" cannot use the internal marker "!"`,this.position-1,this.getErrorContext(),"Internal markers (!) are only allowed on output fields");break}let n;if(this.skipWhitespace(),this.match(":")){if(this.skipWhitespace(),/^class\b/.test(this.input.slice(this.position)))throw new F(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let r=this.parseTypeNotClass(),i=this.match("[]");if(n={name:r,isArray:i},(r==="image"||r==="audio")&&i)throw new F(`Input field "${e}": Arrays of ${r} are not supported`,this.position,this.getErrorContext(),`Use a single ${r} type instead: "${r}"`)}catch(r){throw r instanceof F?r:new F(`Input field "${e}": ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let o;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let i=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new F(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(c=>c.trim()).filter(c=>c.length>0);if(l.length===0)throw new F(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');o={name:"class",isArray:i,options:l}}else try{let i=this.parseTypeNotClass(),a=this.match("[]");if(o={name:i,isArray:a},i==="image"&&a)throw new F(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(i==="audio"&&a)throw new F(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(i==="image")throw new F(`Output field "${e}": Image type is not supported in output fields`,this.position,this.getErrorContext(),"Image types can only be used in input fields");if(i==="audio")throw new F(`Output field "${e}": Audio type is not supported in output fields`,this.position,this.getErrorContext(),"Audio types can only be used in input fields")}catch(i){throw i instanceof F?i:new F(`Output field "${e}": ${i instanceof Error?i.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:o,isOptional:t,isInternal:n}}validateFieldName(e,t){if(B.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(e.toLowerCase())){let i=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new F(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${i.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,o=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!o.test(e))throw new F(`Invalid field name "${e}"`,this.position,this.getErrorContext(),'Field names must be in camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(e.length<2)throw new F(`Field name "${e}" is too short`,this.position,this.getErrorContext(),"Field names must be at least 2 characters long");if(e.length>50)throw new F(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","datetime","date","code"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",o=this.suggestType(n),r=`Invalid type "${n||"empty"}"`,i=o?`. Did you mean "${o}"?`:"",a=`${r}${i}`;throw new F(a,this.position,this.getErrorContext(),`Expected one of: ${e.join(", ")}`)}return t}suggestType(e){return{str:"string",text:"string",int:"number",integer:"number",float:"number",double:"number",bool:"boolean",object:"json",dict:"json",timestamp:"datetime",time:"datetime",img:"image",picture:"image",sound:"audio",voice:"audio",classification:"class",category:"class"}[e.toLowerCase()]||null}parseParsedIdentifier(){this.skipWhitespace();let e=/^[a-zA-Z_][a-zA-Z_0-9]*/.exec(this.input.slice(this.position));if(e)return this.position+=e[0].length,e[0];let t=/^\S+/.exec(this.input.slice(this.position)),n=t?t[0]:"";throw n===""?new F("Expected field name but found end of input",this.position,this.getErrorContext(),"Add a field name. Field names must start with a letter or underscore"):/^\d/.test(n)?new F(`Invalid field name "${n}" - cannot start with a number`,this.position,this.getErrorContext(),'Field names must start with a letter or underscore. Example: "userInput" or "_internal"'):new F(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",o=!1,r=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,o)n+=a,o=!1;else if(a==="\\")o=!0;else{if(a===t)return n;n+=a}}let i=this.input.slice(r,Math.min(this.position,r+20));throw new F(`Unterminated string starting at position ${r}`,r,this.getErrorContext(),`Add closing ${t} to complete the string: ${i}${t}`)}}skipWhitespace(){let e=/^[\s\t\r\n]+/.exec(this.input.slice(this.position));e&&(this.position+=e[0].length)}match(e){let t;if(typeof e=="string"){if(this.input.startsWith(e,this.position))return this.position+=e.length,!0}else if(t=e.exec(this.input.slice(this.position)),t)return this.position+=t[0].length,!0;return!1}expectArrow(){if(!this.match("->")){let e=this.input.slice(this.position,this.position+10),t=e.includes(">")?'Use "->" (dash followed by greater-than)':e.includes("-")?'Add ">" after the dash':'Add "->" to separate input and output fields';throw new F(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function Ni(s){return new kr(s).parse()}var E=class extends Error{constructor(t,n,o){super(t);this.fieldName=n;this.suggestion=o;this.name="AxSignatureValidationError"}},q=class s{description;inputFields;outputFields;sigHash;sigString;validatedAtHash;constructor(e){if(!e){this.inputFields=[],this.outputFields=[],this.sigHash="",this.sigString="";return}if(typeof e=="string"){let t;try{t=Ni(e)}catch(n){if(n instanceof Error){let o="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new E(`Invalid Signature: ${n.message}`,void 0,o)}throw new E(`Invalid Signature: ${e}`,void 0,'Please check the signature format. Example: "userInput:string -> responseText:string"')}this.description=t.desc,this.inputFields=t.inputs.map(n=>this.parseParsedField(n)),this.outputFields=t.outputs.map(n=>this.parseParsedField(n)),[this.sigHash,this.sigString]=this.updateHash()}else if(e instanceof s)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash);else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new E("Invalid signature object: missing inputs or outputs",void 0,'Signature object must have "inputs" and "outputs" arrays. Example: { inputs: [...], outputs: [...] }');if(!Array.isArray(e.inputs)||!Array.isArray(e.outputs))throw new E("Invalid signature object: inputs and outputs must be arrays",void 0,'Both "inputs" and "outputs" must be arrays of AxField objects');try{this.description=e.description,this.inputFields=e.inputs.map(t=>this.parseField(t)),this.outputFields=e.outputs.map(t=>this.parseField(t)),[this.sigHash,this.sigString]=this.updateHash()}catch(t){throw t instanceof E?t:new E(`Failed to create signature from object: ${t instanceof Error?t.message:"Unknown error"}`,void 0,"Check that all fields in inputs and outputs arrays are valid AxField objects")}}else throw new E("Invalid signature argument type",void 0,"Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays")}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new E("Field name is required",e.name,'Every field must have a descriptive name. Example: "userInput", "responseText"');let t=this.toTitle(e.name);return{name:e.name,title:t,description:"desc"in e?e.desc:void 0,type:e.type??{name:"string",isArray:!1},..."isInternal"in e?{isInternal:e.isInternal}:{},..."isOptional"in e?{isOptional:e.isOptional}:{}}};parseField=e=>{let t=!e.title||e.title.length===0?this.toTitle(e.name):e.title;if(e.type&&(!e.type.name||e.type.name.length===0))throw new E("Field type name is required",e.name,"Specify a valid type. Available types: string, number, boolean, json, image, audio, date, datetime, class, code");return{...e,title:t}};setDescription=e=>{if(typeof e!="string")throw new E("Description must be a string",void 0,"Provide a string description for the signature");this.description=e,this.invalidateValidationCache(),this.updateHashLight()};addInputField=e=>{try{let t=this.parseField(e);ve(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new E(`Duplicate input field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.outputFields)if(n.name===t.name)throw new E(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.inputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof E?t:new E(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);ve(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new E(`Duplicate output field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.inputFields)if(n.name===t.name)throw new E(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.outputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof E?t:new E(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new E("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let o=this.parseField(n);return ve(o,"input"),o});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof E?t:new E(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new E("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let o=this.parseField(n);return ve(o,"output"),o});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof E?t:new E(`Failed to set output fields: ${t instanceof Error?t.message:"Unknown error"}`)}};getInputFields=()=>this.inputFields;getOutputFields=()=>this.outputFields;getDescription=()=>this.description;invalidateValidationCache=()=>{this.validatedAtHash=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};toJSONSchema=()=>{let e={},t=[];for(let o of this.inputFields){let r=o.type?o.type.name:"string";o.type?.isArray?e[o.name]={description:o.description,type:"array",items:{type:r,description:o.description}}:e[o.name]={description:o.description,type:r},o.isOptional||t.push(o.name)}return{type:"object",properties:e,required:t}};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{ve(e,"input")}),this.getOutputFields().forEach(e=>{ve(e,"output")}),this.sigHash=Zt("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=$i(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof E?e:new E(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{ve(e,"input")}),this.getOutputFields().forEach(e=>{ve(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Zt("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=$i(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof E?e:new E(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};validateSignatureConsistency(){let e=new Set;for(let n of this.inputFields){if(e.has(n.name))throw new E(`Duplicate input field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");e.add(n.name)}let t=new Set;for(let n of this.outputFields){if(t.has(n.name))throw new E(`Duplicate output field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");t.add(n.name)}for(let n of this.outputFields)if(e.has(n.name))throw new E(`Field name "${n.name}" appears in both inputs and outputs`,n.name,"Use different names for input and output fields to avoid confusion");if(this.inputFields.length===0)throw new E("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new E("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields})};function Ui(s){let e=s.name;return s.isOptional&&(e+="?"),s.isInternal&&(e+="!"),s.type&&(e+=`:${s.type.name}`,s.type.isArray&&(e+="[]"),s.type.name==="class"&&s.type.options&&(e+=` "${s.type.options.join(" | ")}"`)),s.description&&s.type?.name!=="class"&&(e+=` "${s.description}"`),e}function $i(s,e,t){let n=s?`"${s}" `:"",o=e.map(Ui).join(", "),r=t.map(Ui).join(", ");return`${n}${o} -> ${r}`}function dl(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function ve(s,e){if(!s.name||s.name.length===0)throw new E("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!dl(s.name))throw new E(`Invalid field name '${s.name}' - must be camelCase or snake_case`,s.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(B.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(s.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new E(`Field name '${s.name}' is too generic`,s.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(s.name.length<2)throw new E(`Field name '${s.name}' is too short`,s.name,"Field names must be at least 2 characters long");if(s.name.length>50)throw new E(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&ml(s,e)}function ml(s,e){if(!s.type)return;let{type:t}=s;if(t.name==="image"||t.name==="audio"){if(e==="output")throw new E(`${t.name} type is not supported in output fields`,s.name,`${t.name} types can only be used in input fields`);if(t.isArray)throw new E(`Arrays of ${t.name} are not supported`,s.name,`Use a single ${t.name} type instead`)}if(t.name==="class"){if(e==="input")throw new E("Class type is not supported in input fields",s.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new E("Class type requires options",s.name,'Provide class options. Example: class "positive, negative, neutral"');for(let o of t.options){if(!o||o.trim().length===0)throw new E("Empty class option found",s.name,"All class options must be non-empty strings");let r=o.trim();if(r.includes(",")||r.includes("|"))throw new E(`Invalid class option "${r}"`,s.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(o=>o.trim().toLowerCase())).size!==t.options.length)throw new E("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new E("Arrays of code are not commonly supported",s.name,"Consider using a single code field or an array of strings instead");if(s.isInternal&&e==="input")throw new E("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields")}var Se=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new q(e),t?.description&&this.signature.setDescription(t.description),t?.traceLabel&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=this.signature?.hash(),this.children=new ut,this.key={id:this.signature.hash()}}getSignature(){return new q(this.signature)}setSignature(e){this.signature=new q(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let o=this.signature,r=[...o.getInputFields(),...o.getOutputFields()];this.examples=n.map(i=>{let a={};for(let l of r){let c=i[l.name];c!==void 0&&(jn(l,c),a[l.name]=c)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return zt(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(o=>o.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(o=>o.programId===this.key.id).map(o=>o.traces).flat();for(let o of Array.from(this.children))o?.setDemos(e)}};var gl=`
|
|
151
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Wt=class{funcList=[];constructor(e){this.funcList=e}executeFunction=async(e,t,n)=>{let r;typeof t.args=="string"&&t.args.length>0?r=JSON.parse(t.args):r=t.args;let o=n?{sessionId:n.sessionId,ai:n.ai}:void 0,i;return e.parameters?i=e.func.length===2?await e.func(r,o):await e.func(r):i=e.func.length===1?await e.func(o):await e.func(),(n?.functionResultFormatter??B.functionResultFormatter)(i)};execute=async(e,t)=>{let n=this.funcList.find(r=>r.name.localeCompare(e.name)===0);if(!n)throw new Error(`Function not found: ${e.name}`);if(!n.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(n,e,t)}catch(r){throw r instanceof Vt?new nr(r.getFields(),n,e.id):r}}},Mo=(s,e)=>{if(s.length===0)return[...e??[]];let t=s.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(r=>r.parameters))n.parameters&&$i(n.parameters);return[...e??[],...t]},Oo=async({ai:s,functionList:e,functionCalls:t,mem:n,sessionId:r,span:o,excludeContentFromTrace:i,index:a,functionResultFormatter:l,logger:p})=>{let c=new Wt(e),d=new Set,u=t.map(h=>{if(!h.id)throw new Error(`Function ${h.name} did not return an ID`);return c.execute(h,{sessionId:r,ai:s,functionResultFormatter:l}).then(f=>{if(d.add(h.name.toLowerCase()),o){let x={name:h.name};i||(x.args=h.args,x.result=f??""),o.addEvent("function.call",x)}return{result:f??"",role:"function",functionId:h.id,index:a}}).catch(f=>{if(!(f instanceof nr))throw f;let x=f.getFixingInstructions();if(o){let y={name:h.name,message:f.toString()};i||(y.args=h.args,y.fixing_instructions=x),o.addEvent("function.error",y)}return s.getOptions().debug&&Ms(f,a,x,p),{functionId:h.id,isError:!0,index:a,result:x,role:"function"}})}),g=(await Promise.all(u)).filter(h=>h!==void 0);if(n.addFunctionResults(g,r),s.getOptions().debug){let h=g.filter(A=>!A.isError);h.length>0&&Ss(h,p)}return g.some(h=>h.isError)&&n.addTag("error",r),d};function ko(s,e,t,n){if(!e||e.length===0)return;if(!s.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(o=>({id:o.id,name:o.function.name,args:o.function.params}))}function Li(s,e,t){let n=e;return!t&&(n==="required"||typeof n=="function")?{functions:[],functionCall:void 0}:s?{functions:s.map(o=>"toFunction"in o?o.toFunction():o).flat(),functionCall:n}:{functions:[],functionCall:n}}var Oe=ln(Ni(),1),qi=ln(Gi(),1),zi=ln(Ui(),1),ji=ln(Bi(),1);Oe.default.extend(ji.default);Oe.default.extend(zi.default);Oe.default.extend(qi.default);function Hi(s,e,t=!1){try{return wl(e)}catch(n){if(s.isOptional&&!t)return;let r=n.message;throw new J({fields:[s],message:r,value:e})}}function wl(s){if(!(0,Oe.default)(s,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return Oe.default.utc(s,"YYYY-MM-DD").startOf("day").toDate()}function Ki(s,e,t=!1){try{return vl(e)}catch(n){if(s.isOptional&&!t)return;let r=n.message;throw new J({fields:[s],message:r,value:e})}}function vl(s){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=s.match(e);if(!t)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');let[,n,r]=t;if(!n||!r)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');try{let o=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",i=Oe.default.tz(n,o,r);if(!i.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return i.utc().toDate()}catch{throw new Error(`Unrecognized time zone ${r}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`)}}var Vi=s=>(0,Oe.default)(s).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var Tg=new Z;var rr=(s,e)=>{let t=s.type??{name:"string",isArray:!1},n=(p,c)=>{switch(p){case"class":return typeof c=="string";case"code":return typeof c=="string";case"string":return typeof c=="string";case"number":return typeof c=="number";case"boolean":return typeof c=="boolean";case"date":return c instanceof Date||typeof c=="string";case"datetime":return c instanceof Date||typeof c=="string";case"json":return typeof c=="object"||typeof c=="string";default:return!1}},r=p=>!(!p||typeof p!="object"||!("mimeType"in p)||!("data"in p));if(s.type?.name==="image"){let p;if(Array.isArray(e)){for(let c of e)if(!r(c)){p="object ({ mimeType: string; data: string })";break}}else r(e)||(p="object ({ mimeType: string; data: string })");if(p)throw new Error(`Validation failed: Expected '${s.name}' to be type '${p}' instead got '${e}'`);return}let o=p=>!(!p||typeof p!="object"||!("data"in p));if(s.type?.name==="audio"){let p;if(Array.isArray(e)){for(let c of e)if(!o(c)){p="object ({ data: string; format?: string })";break}}else o(e)||(p="object ({ data: string; format?: string })");if(p)throw new Error(`Validation failed: Expected '${s.name}' to be type '${p}' instead got '${e}'`);return}let i=p=>!(!p||typeof p!="object"||!("filename"in p)||!("mimeType"in p)||!("data"in p));if(s.type?.name==="file"){let p;if(Array.isArray(e)){for(let c of e)if(!i(c)){p="object ({ filename: string; mimeType: string; data: string })";break}}else i(e)||(p="object ({ filename: string; mimeType: string; data: string })");if(p)throw new Error(`Validation failed: Expected '${s.name}' to be type '${p}' instead got '${e}'`);return}let a=p=>typeof p=="string"?!0:!(!p||typeof p!="object"||!("url"in p));if(s.type?.name==="url"){let p;if(Array.isArray(e)){for(let c of e)if(!a(c)){p="string or object ({ url: string; title?: string; description?: string })";break}}else a(e)||(p="string or object ({ url: string; title?: string; description?: string })");if(p)throw new Error(`Validation failed: Expected '${s.name}' to be type '${p}' instead got '${e}'`);return}let l=!0;if(t.isArray){if(!Array.isArray(e))l=!1;else for(let p of e)if(!n(t.name,p)){l=!1;break}}else l=n(t.name,e);if(!l){let p=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${s.name}' to be a ${s.type?.isArray?"an array of ":""}${t.name} instead got '${p}' (${JSON.stringify(e)})`)}};function Yt(s){let e={};for(let t of s){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let r=e[n];if(r){let o=r.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};o.promptTokens+=t?.tokens?.promptTokens??0,o.completionTokens+=t?.tokens?.completionTokens??0,o.totalTokens+=t?.tokens?.totalTokens??0,r.tokens=o}}return Object.values(e)}var Wi=s=>{if(!s.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=s.split(`
|
|
152
|
+
`),r=[];for(let o of n){let i=o.trim();if(i){if(i[0]&&e.has(i[0]))r.push(i.slice(1).trim());else if(t.test(i))r.push(i.replace(t,"").trim());else if(r.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(r.length===0)throw new Error("Could not parse markdown list: no valid list items found");return r};function Uo(s,e){let{index:t,delta:n,version:r}=e,o=s.find(i=>i.index===t)?.delta;if(!o)return s.push({index:t,delta:n,version:r}),s;for(let i of Object.keys(n)){let a=o[i],l=n[i];a===void 0&&Array.isArray(l)?o[i]=[...l]:Array.isArray(a)&&Array.isArray(l)?o[i]=[...a,...l]:(a===void 0||typeof a=="string")&&typeof l=="string"?o[i]=`${a??""}${l}`:o[i]=l}return s}var Go=class{cache=new Map;maxSize;constructor(e){this.maxSize=e}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(e,t)}},Sl=new Go(500);function Bo(s,e,t=0,n=Sl){if(/^```[a-zA-Z]*\s*$/.test(s))return-4;if(/^[\s`]*$/.test(s))return-3;let r=s.indexOf(e,t);if(r!==-1)return r;let o=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,o);let i=-1;for(let a=o.length-1;a>=0;a--){let l=o[a];if(s.endsWith(l)){i=a;break}}return i>=0?-2:-1}var Qi=(s,e,t,n=!1)=>{let r={extractedFields:[],streamedIndex:{},s:-1};qo(s,e,r,t,{strictMode:n}),zo(s,e,r,t,n);for(let o of s.getOutputFields())o.isInternal&&delete e[o.name]},Ml=(s,e,t)=>{let n=[];for(let r of t)r&&!r.isOptional&&e[r.name]===void 0&&n.push(r);if(n.length>0)throw new J({message:`Required ${n.length===1?"field":"fields"} not found`,fields:n})},qo=(s,e,t,n,{strictMode:r,skipEarlyFail:o}={})=>{let i=s.getOutputFields(),a;for(let[l,p]of i.entries()){if(l===t.currFieldIndex&&!t.inAssumedField||p.name in e&&!(l===t.currFieldIndex&&t.inAssumedField))continue;let d=`${(t.extractedFields.length===0?"":`
|
|
153
|
+
`)+p.title}:`,u=Bo(n,d,t.s),m=d.length;switch(u){case-1:if(o)continue;if(!r&&i.length===1&&t.currField===void 0){t.inAssumedField=!0,a=p,m=0,u=0;break}if(t.currField===void 0&&t.extractedFields.length===0){if(r&&!p.isOptional)throw new J({message:"Expected (Required) field not found",fields:[p]});if(!r){let g=!1;for(let h=l;h<i.length;h++){let A=i[h];if(!A)continue;let f=`${(t.extractedFields.length===0?"":`
|
|
154
|
+
`)+A.title}:`;if(Bo(n,f,t.s)>=0){g=!0;break}}if(!g){t.inAssumedField=!0,a=p,m=0,u=0;break}}}a=p.isOptional?void 0:p;continue;case-2:return!0;case-3:return!0;case-4:return t.inBlock=!0,!0}if(a&&a.name!==p.name)throw new J({message:"Expected (Required) field not found",fields:[a]});if(t.currField!==void 0&&t.inAssumedField){let g=n.substring(0,u).trim();if(g&&t.currField.name===p.name){let h=Jt(t.currField,g);h!==void 0&&(e[t.currField.name]=h)}else if(g){let h=Jt(t.currField,g);h!==void 0&&(e[t.currField.name]=h)}t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0}if(t.currField){let g=n.substring(t.s,u).trim(),h=Jt(t.currField,g);h!==void 0&&(e[t.currField.name]=h),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:u}):t.prevFields=[{field:t.currField,s:t.s,e:u}]}t.s=u+m,t.currField=p,t.currFieldIndex=l,t.extractedFields.includes(p)||t.extractedFields.push(p),t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},zo=(s,e,t,n,r=!1)=>{if(t.currField){let o=n.substring(t.s).trim(),i=Jt(t.currField,o);i!==void 0&&(e[t.currField.name]=i)}if(r&&!t.currField&&t.extractedFields.length===0&&n.trim()){let a=s.getOutputFields().find(l=>!l.isOptional);if(a)throw new J({message:"Expected field not found",fields:[a]})}Ol(s,e,n),Ml(t,e,s.getOutputFields())},Ol=(s,e,t)=>{let n=s.getOutputFields();for(let r of n){if(!r.isOptional||r.name in e)continue;let o=`${r.title}:`,i=t.indexOf(o);if(i===-1)continue;let a=i+o.length,l=t.length;for(let c of n){if(c.name===r.name)continue;let d=`${c.title}:`,u=t.indexOf(d,a);u!==-1&&u<l&&(l=u)}let p=t.substring(a,l).trim();if(p)try{let c=Jt(r,p);c!==void 0&&(e[r.name]=c)}catch{}}},Yi=(s,e,t=!1)=>{switch(s.type?.name){case"code":return Xi(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(s.isOptional&&!t)return;throw new Error("Invalid number")}return n}case"boolean":{if(typeof e=="boolean")return e;let n=e.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(s.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return Hi(s,e,t);case"datetime":return Ki(s,e,t);case"class":{let n=e;if(s.type.options&&!s.type.options.includes(n)){if(s.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${s.type.options.join(", ")}`)}return n}default:return e}};function*Ji(s,e,t,n,r,o){let{name:i,isInternal:a}=e,{isArray:l,name:p}=e.type??{};if(a||l||p&&p!=="string"&&p!=="code")return;let c=r.streamedIndex[i]??0,d=c===0,u=s.substring(t+c,n);if(u.length===0)return;let m=u.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(m=m.replace(/\s*```\s*$/,""));let g=d?m.trimStart():m;r.currField?.type?.name==="code"&&(g=g.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),g.length>0&&(yield{index:o,delta:{[i]:g}},r.streamedIndex[i]=c+m.length)}function*jo(s,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:l,e:p}=i;yield*Ji(e,a,l,p,n,r)}if(n.prevFields=void 0,!n.currField||n.currField.isInternal)return;yield*Ji(e,n.currField,n.s,e.length,n,r);let o=s.getOutputFields();for(let i of Object.keys(t)){let a=o.find(p=>p.name===i);if(!a||a.isInternal)continue;let l=t[i];if(Array.isArray(l)){let p=n.streamedIndex?.[i]??0,c=l.slice(p);c&&c.length>0&&(yield{index:r,delta:{[i]:c}},n.streamedIndex[i]=p+c.length);continue}n.streamedIndex[i]||(yield{index:r,delta:{[i]:l}},n.streamedIndex[i]=1)}}function Jt(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw new J({message:"Required field is missing",fields:[s],value:e})}let t;if(s.type?.name==="json")try{let n=Xi(e);return t=JSON.parse(n),t}catch(n){throw new J({message:`Invalid JSON: ${n.message}`,fields:[s],value:e})}if(s.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Wi(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(n){throw new J({message:`Invalid Array: ${n.message}`,fields:[s],value:e})}try{if(Array.isArray(t)){for(let[n,r]of t.entries())if(r!==void 0){let o=typeof r=="string"?r.trim():r;t[n]=Yi(s,o,!0)}}else t=Yi(s,e)}catch(n){throw new J({message:n.message,fields:[s],value:e})}if(!(typeof t=="string"&&t===""))return t}var Xi=s=>{let t=/```([A-Za-z]*)\n([\s\S]*?)\n```/g.exec(s);return t?t.length===3?t[2]:t.length===2?t[1]:s:s};async function Ho(s,e,t,n){for(let r of s){if(e[r.field.name]===void 0)continue;let o=r.process,i=await o(e[r.field.name],{sessionId:n,values:e,done:!0});Zi(r.field,t,i,n)}}async function Ko(s,e,t,n,r,o,i=!1){for(let a of s){if(t.currField?.name!==a.field.name)continue;let l=e.substring(t.s);t.currField?.type?.name==="code"&&(l=l.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),l=l.replace(/\s*```\s*$/,""));let p=a.process,c=await p(l,{sessionId:o,values:r,done:i});Zi(t.currField,n,c,o)}}var Zi=(s,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(i,a)=>typeof a=="bigint"?Number(a):a,2),o=kl(s,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function kl(s,e){let t=s.type?.name==="code",n=s.title;return t?`Code in the field "${n}" was executed. The code execution produced the following output: ${e}`:`The field "${n}" was processed. The field contents were transformed into the following output: ${e}`}async function*ea({res:s,usage:e,states:t,...n}){let r=(n.ai.getFeatures().functionCot??!1)&&n.functions!==void 0&&n.functions.length>0,o,i=s.getReader();try{for(;;){let{done:a,value:l}=await i.read();if(a){o&&e.push(o);break}let p=l;p.modelUsage&&(o=p.modelUsage);for(let c of p.results){if((!c.content||c.content==="")&&(!c.thought||c.thought==="")&&(!c.functionCalls||c.functionCalls.length===0))continue;let d=t.find(u=>u.index===c.index);if(!d)throw new Error(`No state found for result (index: ${c.index})`);yield*El({...n,result:c,skipEarlyFail:r,state:d})}}}finally{i.releaseLock()}for(let a of t)yield*Pl({...n,state:a})}async function*El({result:s,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,state:o,signature:i,streamingFieldProcessors:a,thoughtFieldName:l,streamingAsserts:p,asserts:c}){if(s.functionCalls&&s.functionCalls.length>0)xn(o.functionCalls,s.functionCalls),e.updateResult({name:s.name,content:s.content,functionCalls:o.functionCalls,delta:s.functionCalls?.[0]?.function?.params,index:s.index},t);else if(s.content&&s.content.length>0){if(s.thought&&s.thought.length>0&&(yield{index:s.index,delta:{[l]:s.thought}}),o.content+=s.content,e.updateResult({name:s.name,content:o.content,delta:s.content,index:s.index},t),qo(i,o.values,o.xstate,o.content,{strictMode:n,skipEarlyFail:r}))return;p.length!==0&&await Ro(p,o.xstate,o.content),a.length!==0&&await Ko(a,o.content,o.xstate,e,o.values,t),yield*jo(i,o.content,o.values,o.xstate,s.index),await Xn(c,o.values)}else s.thought&&s.thought.length>0&&(o.values[l]=(o.values[l]??"")+s.thought,yield{index:s.index,delta:{[l]:s.thought}});if(s.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
155
|
+
Content: ${o.content}`)}async function*Pl({state:s,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:i,traceId:a,span:l,strictMode:p,excludeContentFromTrace:c,streamingAsserts:d,asserts:u,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:h,logger:A}){let f=ko(t,s.functionCalls,s.values,n);if(f){if(!r)throw new Error("Functions are not defined");let x=await Oo({ai:t,functionList:r,functionCalls:f,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:c,functionResultFormatter:h,logger:A});s.functionsExecuted=new Set([...s.functionsExecuted,...x])}else zo(e,s.values,s.xstate,s.content,p),await Ro(d,s.xstate,s.content,!0),await Xn(u,s.values),m.length&&await Ho(m,s.values,o,i),g.length!==0&&await Ko(g,s.content,s.xstate,o,s.values,i,!0),yield*jo(e,s.content,s.values,s.xstate,s.index)}async function*ta({ai:s,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:i,strictMode:a,states:l,usage:p,excludeContentFromTrace:c,asserts:d,fieldProcessors:u,thoughtFieldName:m,signature:g,functionResultFormatter:h,logger:A}){let f=e.results??[];t.addResponse(f,n);for(let b of f){let T=l[b.index];if(!T)throw new Error(`No state found for result (index: ${b.index})`);if(e.modelUsage&&p.push(e.modelUsage),b.functionCalls?.length){let P=ko(s,b.functionCalls,T.values);if(P){if(!o)throw new Error("Functions are not defined");let w=await Oo({ai:s,functionList:o,functionCalls:P,mem:t,sessionId:n,traceId:r,span:i,excludeContentFromTrace:c,index:b.index,functionResultFormatter:h,logger:A});T.functionsExecuted=new Set([...T.functionsExecuted,...w])}}else b.content&&(b.thought&&b.thought.length>0&&(T.values[m]=b.thought),Qi(g,T.values,b.content,a),await Xn(d,T.values),u.length&&await Ho(u,T.values,t,n));if(b.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
156
|
+
Content: ${b.content}`)}let x=l.map(b=>b.values);for(let b of x)for(let T of g.getOutputFields())T.isInternal&&delete b[T.name];let y=g.getOutputFields(),k=x.map((b,T)=>{let P={};for(let w of y)w.isInternal||(P[w.name]=b[w.name]);return b[m]!==void 0&&(P[m]=b[m]),{index:T,delta:P}});for(let b of k)yield b}function na(s,e,t,n){let r=s.getLast(n);if(!r)return!0;for(let[o,i]of t.entries()){let a=e&&i.functionsExecuted.has(e);if(!r.chat[o])throw new Error(`No chat message found for result (index: ${o})`);let p=r.role==="function",c=r.tags?r.tags.some(d=>d==="processor"):!1;if(p&&e&&a||!(p||c))return!1}return!0}var ht=class{reg;constructor(){this.reg=new Set}register(e){this.reg.add(e)}*[Symbol.iterator](){let e=Array.from(this.reg);for(let t=0;t<e.length;t++)yield e[t]}};var F=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},Vo=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new F("Empty signature provided",0,"",'A signature must contain at least input and output fields separated by "->". Example: "userQuery:string -> aiResponse:string"')}parse(){try{this.skipWhitespace();let e=this.parseParsedString();this.skipWhitespace(),this.currentSection="inputs";let t=this.parseFieldList(this.parseInputField.bind(this),"input");if(this.skipWhitespace(),this.position>=this.input.length)throw new F("Incomplete signature: Missing output section",this.position,this.getErrorContext(),'Add "->" followed by output fields. Example: "-> responseText:string"');if(this.expectArrow(),this.skipWhitespace(),this.position>=this.input.length)throw new F('Incomplete signature: No output fields specified after "->"',this.position,this.getErrorContext(),'Add at least one output field. Example: "-> responseText:string"');this.currentSection="outputs";let n=this.parseFieldList(this.parseOutputField.bind(this),"output");if(this.skipWhitespace(),this.position<this.input.length){let r=this.input.slice(this.position);throw new F(`Unexpected content after signature: "${r}"`,this.position,this.getErrorContext(),"Remove any extra content after the output fields")}return this.validateParsedSignature({desc:e?.trim(),inputs:t,outputs:n}),{desc:e?.trim(),inputs:t,outputs:n}}catch(e){if(e instanceof F)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new F(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new F(`Duplicate input field name: "${r.name}"`,0,"","Each field name must be unique within the signature");t.add(r.name)}let n=new Set;for(let r of e.outputs){if(n.has(r.name))throw new F(`Duplicate output field name: "${r.name}"`,0,"","Each field name must be unique within the signature");n.add(r.name)}for(let r of e.outputs)if(t.has(r.name))throw new F(`Field name "${r.name}" appears in both inputs and outputs`,0,"","Use different names for input and output fields to avoid confusion");if(e.inputs.length===0)throw new F("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new F("Signature must have at least one output field",0,"",'Add an output field after "->". Example: "... -> responseText:string"')}getErrorContext(){let e=Math.max(0,this.position-25),t=Math.min(this.input.length,this.position+25),n=this.input.slice(e,this.position),r=this.input.slice(this.position,t),o=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${o}`].join(`
|
|
157
|
+
`)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new F(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(r){throw r instanceof F?r:new F(`Invalid first ${t} field: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new F(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(r){throw r instanceof F?r:new F(`Invalid ${t} field after comma: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new F(`Input field "${e}" cannot use the internal marker "!"`,this.position-1,this.getErrorContext(),"Internal markers (!) are only allowed on output fields");break}let n;if(this.skipWhitespace(),this.match(":")){if(this.skipWhitespace(),/^class\b/.test(this.input.slice(this.position)))throw new F(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let o=this.parseTypeNotClass(),i=this.match("[]");if(n={name:o,isArray:i},(o==="image"||o==="audio")&&i)throw new F(`Input field "${e}": Arrays of ${o} are not supported`,this.position,this.getErrorContext(),`Use a single ${o} type instead: "${o}"`)}catch(o){throw o instanceof F?o:new F(`Input field "${e}": ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let r;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let i=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new F(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(p=>p.trim()).filter(p=>p.length>0);if(l.length===0)throw new F(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:i,options:l}}else try{let i=this.parseTypeNotClass(),a=this.match("[]");if(r={name:i,isArray:a},i==="image"&&a)throw new F(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(i==="audio"&&a)throw new F(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(i==="image")throw new F(`Output field "${e}": Image type is not supported in output fields`,this.position,this.getErrorContext(),"Image types can only be used in input fields");if(i==="audio")throw new F(`Output field "${e}": Audio type is not supported in output fields`,this.position,this.getErrorContext(),"Audio types can only be used in input fields")}catch(i){throw i instanceof F?i:new F(`Output field "${e}": ${i instanceof Error?i.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(B.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(e.toLowerCase())){let i=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new F(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${i.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new F(`Invalid field name "${e}"`,this.position,this.getErrorContext(),'Field names must be in camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(e.length<2)throw new F(`Field name "${e}" is too short`,this.position,this.getErrorContext(),"Field names must be at least 2 characters long");if(e.length>50)throw new F(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),o=`Invalid type "${n||"empty"}"`,i=r?`. Did you mean "${r}"?`:"",a=`${o}${i}`;throw new F(a,this.position,this.getErrorContext(),`Expected one of: ${e.join(", ")}`)}return t}suggestType(e){return{str:"string",text:"string",int:"number",integer:"number",float:"number",double:"number",bool:"boolean",object:"json",dict:"json",timestamp:"datetime",time:"datetime",img:"image",picture:"image",sound:"audio",voice:"audio",classification:"class",category:"class"}[e.toLowerCase()]||null}parseParsedIdentifier(){this.skipWhitespace();let e=/^[a-zA-Z_][a-zA-Z_0-9]*/.exec(this.input.slice(this.position));if(e)return this.position+=e[0].length,e[0];let t=/^\S+/.exec(this.input.slice(this.position)),n=t?t[0]:"";throw n===""?new F("Expected field name but found end of input",this.position,this.getErrorContext(),"Add a field name. Field names must start with a letter or underscore"):/^\d/.test(n)?new F(`Invalid field name "${n}" - cannot start with a number`,this.position,this.getErrorContext(),'Field names must start with a letter or underscore. Example: "userInput" or "_internal"'):new F(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",r=!1,o=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,r)n+=a,r=!1;else if(a==="\\")r=!0;else{if(a===t)return n;n+=a}}let i=this.input.slice(o,Math.min(this.position,o+20));throw new F(`Unterminated string starting at position ${o}`,o,this.getErrorContext(),`Add closing ${t} to complete the string: ${i}${t}`)}}skipWhitespace(){let e=/^[\s\t\r\n]+/.exec(this.input.slice(this.position));e&&(this.position+=e[0].length)}match(e){let t;if(typeof e=="string"){if(this.input.startsWith(e,this.position))return this.position+=e.length,!0}else if(t=e.exec(this.input.slice(this.position)),t)return this.position+=t[0].length,!0;return!1}expectArrow(){if(!this.match("->")){let e=this.input.slice(this.position,this.position+10),t=e.includes(">")?'Use "->" (dash followed by greater-than)':e.includes("-")?'Add ">" after the dash':'Add "->" to separate input and output fields';throw new F(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function ra(s){return new Vo(s).parse()}var Qt=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional,isInternal:t.isInternal};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional,isInternal:t.isInternal};return n?this.outputFields.unshift(r):this.outputFields.push(r),this}description(e){return this.desc=e,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields};return new H(e)}},Q=class s{type;isArray;options;description;isOptional;isInternal;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.isOptional=e.isOptional,this.isInternal=e.isInternal}optional(){return new s({...this,isOptional:!0})}array(){return new s({...this,isArray:!0})}internal(){return new s({...this,isInternal:!0})}},ft=Object.assign(()=>new Qt,{string:s=>new Q({type:"string",isArray:!1,description:s}),number:s=>new Q({type:"number",isArray:!1,description:s}),boolean:s=>new Q({type:"boolean",isArray:!1,description:s}),json:s=>new Q({type:"json",isArray:!1,description:s}),datetime:s=>new Q({type:"datetime",isArray:!1,description:s}),date:s=>new Q({type:"date",isArray:!1,description:s}),class:(s,e)=>new Q({type:"class",isArray:!1,options:s,description:e}),image:s=>new Q({type:"image",isArray:!1,description:s}),audio:s=>new Q({type:"audio",isArray:!1,description:s}),file:s=>new Q({type:"file",isArray:!1,description:s}),url:s=>new Q({type:"url",isArray:!1,description:s}),code:(s,e)=>new Q({type:"code",isArray:!1,description:e||s}),array:s=>({...s,isArray:!0}),optional:s=>({...s,isOptional:!0}),internal:s=>({...s,isInternal:!0}),legacyArray:s=>({...s,isArray:!0}),legacyOptional:s=>({...s,isOptional:!0}),legacyInternal:s=>({...s,isInternal:!0})});function or(s){return{type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0},description:s.description,isOptional:s.isOptional,isInternal:s.isInternal}}var O=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},H=class s{description;inputFields;outputFields;sigHash;sigString;validatedAtHash;constructor(e){if(!e){this.inputFields=[],this.outputFields=[],this.sigHash="",this.sigString="";return}if(typeof e=="string"){let t;try{t=ra(e)}catch(n){if(n instanceof Error){let r="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new O(`Invalid Signature: ${n.message}`,void 0,r)}throw new O(`Invalid Signature: ${e}`,void 0,'Please check the signature format. Example: "userInput:string -> responseText:string"')}this.description=t.desc,this.inputFields=t.inputs.map(n=>this.parseParsedField(n)),this.outputFields=t.outputs.map(n=>this.parseParsedField(n)),[this.sigHash,this.sigString]=this.updateHash()}else if(e instanceof s)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash);else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new O("Invalid signature object: missing inputs or outputs",void 0,'Signature object must have "inputs" and "outputs" arrays. Example: { inputs: [...], outputs: [...] }');if(!Array.isArray(e.inputs)||!Array.isArray(e.outputs))throw new O("Invalid signature object: inputs and outputs must be arrays",void 0,'Both "inputs" and "outputs" must be arrays of AxField objects');try{this.description=e.description,this.inputFields=e.inputs.map(t=>this.parseField(t)),this.outputFields=e.outputs.map(t=>this.parseField(t)),[this.sigHash,this.sigString]=this.updateHash()}catch(t){throw t instanceof O?t:new O(`Failed to create signature from object: ${t instanceof Error?t.message:"Unknown error"}`,void 0,"Check that all fields in inputs and outputs arrays are valid AxField objects")}}else throw new O("Invalid signature argument type",void 0,"Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays")}static create(e){return new s(e)}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new O("Field name is required",e.name,'Every field must have a descriptive name. Example: "userInput", "responseText"');let t=this.toTitle(e.name);return{name:e.name,title:t,description:"desc"in e?e.desc:void 0,type:e.type??{name:"string",isArray:!1},..."isInternal"in e?{isInternal:e.isInternal}:{},..."isOptional"in e?{isOptional:e.isOptional}:{}}};parseField=e=>{let t=!e.title||e.title.length===0?this.toTitle(e.name):e.title;if(e.type&&(!e.type.name||e.type.name.length===0))throw new O("Field type name is required",e.name,"Specify a valid type. Available types: string, number, boolean, json, image, audio, file, url, date, datetime, class, code");return{...e,title:t}};setDescription=e=>{if(typeof e!="string")throw new O("Description must be a string",void 0,"Provide a string description for the signature");this.description=e,this.invalidateValidationCache(),this.updateHashLight()};addInputField=e=>{try{let t=this.parseField(e);Ae(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new O(`Duplicate input field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.outputFields)if(n.name===t.name)throw new O(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.inputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof O?t:new O(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);Ae(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new O(`Duplicate output field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.inputFields)if(n.name===t.name)throw new O(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.outputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof O?t:new O(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new O("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return Ae(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof O?t:new O(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new O("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return Ae(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof O?t:new O(`Failed to set output fields: ${t instanceof Error?t.message:"Unknown error"}`)}};getInputFields=()=>this.inputFields;getOutputFields=()=>this.outputFields;getDescription=()=>this.description;appendInputField=(e,t)=>{let n=new s(this);return n.addInputField({name:e,...or(t)}),n};prependInputField=(e,t)=>{let n=new s(this),r={name:e,...or(t)},o=n.parseField(r);Ae(o,"input");for(let i of n.inputFields)if(i.name===o.name)throw new O(`Duplicate input field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let i of n.outputFields)if(i.name===o.name)throw new O(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new s(this);return n.addOutputField({name:e,...or(t)}),n};prependOutputField=(e,t)=>{let n=new s(this),r={name:e,...or(t)},o=n.parseField(r);Ae(o,"output");for(let i of n.outputFields)if(i.name===o.name)throw new O(`Duplicate output field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let i of n.inputFields)if(i.name===o.name)throw new O(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};toJSONSchema=()=>{let e={},t=[];for(let r of this.inputFields){let o=r.type?r.type.name:"string";r.type?.isArray?e[r.name]={description:r.description,type:"array",items:{type:o,description:r.description}}:e[r.name]={description:r.description,type:o},r.isOptional||t.push(r.name)}return{type:"object",properties:e,required:t}};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{Ae(e,"input")}),this.getOutputFields().forEach(e=>{Ae(e,"output")}),this.sigHash=pn("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=sa(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof O?e:new O(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{Ae(e,"input")}),this.getOutputFields().forEach(e=>{Ae(e,"output")}),this.validateSignatureConsistency(),this.sigHash=pn("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=sa(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof O?e:new O(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};validateSignatureConsistency(){let e=new Set;for(let n of this.inputFields){if(e.has(n.name))throw new O(`Duplicate input field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");e.add(n.name)}let t=new Set;for(let n of this.outputFields){if(t.has(n.name))throw new O(`Duplicate output field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");t.add(n.name)}for(let n of this.outputFields)if(e.has(n.name))throw new O(`Field name "${n.name}" appears in both inputs and outputs`,n.name,"Use different names for input and output fields to avoid confusion");if(this.inputFields.length===0)throw new O("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new O("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields})};function oa(s){let e=s.name;return s.isOptional&&(e+="?"),s.isInternal&&(e+="!"),s.type&&(e+=`:${s.type.name}`,s.type.isArray&&(e+="[]"),s.type.name==="class"&&s.type.options&&(e+=` "${s.type.options.join(" | ")}"`)),s.description&&s.type?.name!=="class"&&(e+=` "${s.description}"`),e}function sa(s,e,t){let n=s?`"${s}" `:"",r=e.map(oa).join(", "),o=t.map(oa).join(", ");return`${n}${r} -> ${o}`}function _l(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function Ae(s,e){if(!s.name||s.name.length===0)throw new O("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!_l(s.name))throw new O(`Invalid field name '${s.name}' - must be camelCase or snake_case`,s.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(B.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(s.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new O(`Field name '${s.name}' is too generic`,s.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(s.name.length<2)throw new O(`Field name '${s.name}' is too short`,s.name,"Field names must be at least 2 characters long");if(s.name.length>50)throw new O(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&Fl(s,e)}function Fl(s,e){if(!s.type)return;let{type:t}=s;if(t.name==="image"||t.name==="audio"||t.name==="file"||t.name==="url"){if(e==="output")throw new O(`${t.name} type is not supported in output fields`,s.name,`${t.name} types can only be used in input fields`);if(t.isArray&&(t.name==="image"||t.name==="audio"))throw new O(`Arrays of ${t.name} are not supported`,s.name,`Use a single ${t.name} type instead`)}if(t.name==="class"){if(e==="input")throw new O("Class type is not supported in input fields",s.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new O("Class type requires options",s.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new O("Empty class option found",s.name,"All class options must be non-empty strings");let o=r.trim();if(o.includes(",")||o.includes("|"))throw new O(`Invalid class option "${o}"`,s.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(r=>r.trim().toLowerCase())).size!==t.options.length)throw new O("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new O("Arrays of code are not commonly supported",s.name,"Consider using a single code field or an array of strings instead");if(s.isInternal&&e==="input")throw new O("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields")}var ke=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new H(e),t?.description&&this.signature.setDescription(t.description),t?.traceLabel&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=this.signature?.hash(),this.children=new ht,this.key={id:this.signature.hash()}}getSignature(){return new H(this.signature)}setSignature(e){this.signature=new H(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(i=>{let a={};for(let l of o){let p=i[l.name];p!==void 0&&(rr(l,p),a[l.name]=p)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return Yt(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(r=>r.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(r=>r.programId===this.key.id).map(r=>r.traces).flat();for(let r of Array.from(this.children))r?.setDemos(e)}};var Dl=`
|
|
156
158
|
## Function Call Instructions
|
|
157
159
|
- Complete the task, using the functions defined earlier in this prompt.
|
|
158
160
|
- Output fields should only be generated after all functions have been called.
|
|
159
|
-
- Use the function results to generate the output fields
|
|
161
|
+
- Use the function results to generate the output fields.`,$l=`
|
|
160
162
|
## Strict Output Formatting Rules
|
|
161
163
|
- Output must strictly follow the defined plain-text \`field name: value\` field format.
|
|
162
164
|
- Output field, values must strictly adhere to the specified output field formatting rules.
|
|
163
165
|
- No formatting rules should override these **Strict Output Formatting Rules**
|
|
164
166
|
- Do not add any text before or after the output fields, just the field name and value.
|
|
165
|
-
- Do not use code blocks.`,
|
|
166
|
-
`);l&&l.length>0&&
|
|
167
|
-
${l}`);let
|
|
168
|
-
${
|
|
169
|
-
${
|
|
167
|
+
- Do not use code blocks.`,Le=class{sig;fieldTemplates;task;thoughtFieldName;functions;constructor(e,t,n){this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=t?.thoughtFieldName??"thought",this.functions=t?.functions;let r=[],o=ia(this.sig.getInputFields()),i=ia(this.sig.getOutputFields());r.push(`You will be provided with the following fields: ${o}. Your task is to generate new fields: ${i}.`);let l=this.functions?.map(u=>"toFunction"in u?u.toFunction():u)?.flat()?.map(u=>`- \`${u.name}\`: ${sr(u.description)}`).join(`
|
|
168
|
+
`);l&&l.length>0&&r.push(`## Available Functions
|
|
169
|
+
${l}`);let p=Ll(this.sig.getInputFields());r.push(`## Input Fields
|
|
170
|
+
${p}`);let c=Nl(this.sig.getOutputFields());r.push(`## Output Fields
|
|
171
|
+
${c}`),l&&l.length>0&&r.push(Dl.trim()),r.push($l.trim());let d=this.sig.getDescription();if(d){let u=sr(d);r.push(u)}this.task={type:"text",text:r.join(`
|
|
170
172
|
|
|
171
|
-
`)}}renderSingleValueUserContent=(e,t,n,
|
|
172
|
-
`):a.reduce(
|
|
173
|
-
`),[])};render=(e,{examples:t,demos:n})=>{let
|
|
173
|
+
`)}}renderSingleValueUserContent=(e,t,n,r)=>{let o=this.renderInputFields(e),a=(r?o:[...t,...n,...o]).filter(l=>l!==void 0);return a.every(l=>l.type==="text")?a.map(l=>l.text).join(`
|
|
174
|
+
`):a.reduce(aa(`
|
|
175
|
+
`),[])};render=(e,{examples:t,demos:n})=>{let r=t?[{type:"text",text:`
|
|
174
176
|
|
|
175
177
|
## Examples
|
|
176
|
-
`},...this.renderExamples(t)]:[],
|
|
177
|
-
`);return{title:
|
|
178
|
+
`},...this.renderExamples(t)]:[],o=n?this.renderDemos(n):[],i=r.every(u=>u.type==="text"),a=o.every(u=>u.type==="text"),l=i&&a,p=this.task.text;if(l){let u=[{type:"text",text:p},...r,...o];u.reduce(aa(""),[]),u?.[0]&&(p=u[0].text)}let c={role:"system",content:p};if(Array.isArray(e)){let u=[],m=e,g=!0;for(let h of m){let A;if(g?(A=this.renderSingleValueUserContent(h.values,r,o,l),g=!1):A=this.renderSingleValueUserContent(h.values,[],[],!1),h.role==="user"){u.push({role:"user",content:A});continue}if(h.role!=="assistant")throw new Error("Invalid message role");if(typeof A!="string")throw new Error("Assistant message cannot contain non-text content like images, files,etc");u.push({role:"assistant",content:A})}return[c,...u]}let d=this.renderSingleValueUserContent(e,r,o,l);return[c,{role:"user",content:d}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((o,i)=>{let a=i.title;return o[a]||(o[a]=[]),o[a].push(i),o},{});return Object.entries(n).map(([o,i])=>{if(i.length===1){let a=i[0];return{title:o,name:a.name,description:a.description}}if(i.length>1){let a=i.map(l=>`- ${l.description}`).join(`
|
|
179
|
+
`);return{title:o,name:i[0].name,description:a}}}).filter(Boolean).forEach(o=>{let i=this.fieldTemplates?.[o.name]??this.defaultRenderInField;t.push(...i(o,o.description))}),t};renderExamples=e=>{let t=[],n={isExample:!0};for(let[r,o]of e.entries()){let i=this.sig.getInputFields().map(p=>this.renderInField(p,o,{...n,isInputField:!0})).filter(p=>p!==void 0).flat(),a=this.sig.getOutputFields().map(p=>this.renderInField(p,o,{...n,isInputField:!1})).filter(p=>p!==void 0).flat(),l=[...i,...a];r>0&&l.length>0&&l[0]?.type==="text"&&t.push({type:"text",text:`---
|
|
178
180
|
|
|
179
|
-
`}),l.forEach(
|
|
180
|
-
`),t.push(
|
|
181
|
-
`),t.push(
|
|
182
|
-
`}),t};renderInField=(e,t,n)=>{let
|
|
183
|
-
`),n.push(t.map(
|
|
184
|
-
`))):n.push(t),[{type:"text",text:n.join("")}]}},
|
|
185
|
-
`),
|
|
186
|
-
`),xl=(s,e)=>{if(s.type?.name==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return s.type?.name==="datetime"&&e instanceof Date?Mi(e):s.type?.name==="image"&&typeof e=="object"||s.type?.name==="audio"&&typeof e=="object"||typeof e=="string"?e:JSON.stringify(e,null,2)},zi=s=>{let e=(()=>{switch(s?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return s?.isArray?`json array of ${e} items`:e};function qi(s){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=s+t.text:e.push(t)}else e.push(t);return e}}var yl=(s,e,t)=>{if(typeof e=="boolean")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||s.isOptional||s.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${s.name}' is required.`)}return!1};function Hn(s){let e=s.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Il(s,e){let t=s.history(0,e),n=t.some(r=>r.role==="function");return t.some(r=>r.role==="assistant"&&"functionCalls"in r&&Array.isArray(r.functionCalls)&&r.functionCalls.length>0)&&n}function bl(s,e){let t=s.history(0,e),n=[],o=t.filter(i=>i.role==="assistant"&&"functionCalls"in i&&Array.isArray(i.functionCalls)&&i.functionCalls.length>0),r=t.filter(i=>i.role==="function");for(let i of o)if("functionCalls"in i&&i.functionCalls)for(let a of i.functionCalls){let l=r.find(c=>"functionId"in c&&c.functionId===a.id);l&&"result"in l&&"functionId"in l&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(l.result),isError:"isError"in l?!!l.isError:!1})}return n}async function Kn(s,e,t,n){if(!e?.resultPicker||s.length<=1)return 0;let o=e.resultPicker;if((t?Il(t,n):!1)&&t){let l=bl(t,n),c=await o({type:"function",results:l});if(c<0||c>=l.length)throw new Error(`Result picker returned invalid index: ${c}. Must be between 0 and ${l.length-1}`);return c}let i=s.map((l,c)=>({index:c,sample:l.delta})),a=await o({type:"fields",results:i});if(a<0||a>=s.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${s.length-1}`);return a}async function ji(s,e,t){let n=s?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let o=n.chat.map(i=>({version:0,index:i.index,delta:i.value}));return await Kn(o,t,s,e)}var j=class extends Se{promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;constructor(e,t){super(e,{description:t?.description,traceLabel:t?.traceLabel}),this.options=t,this.thoughtFieldName=t?.thoughtFieldName??"thought";let n={functions:t?.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new(t?.promptTemplate??Pe)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.usage=[],t?.functions&&(this.functions=ur(t.functions))}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return ar()}updateMeter(e){ar(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{this.streamingAsserts.push({fieldName:e,fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let o=this.signature.getOutputFields().find(r=>r.name===e);if(!o)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let r=o.type?.name;if(!(!r||r==="string"||r==="code"))throw new Error(`addFieldProcessor: field ${e} is must be a text field`);this.streamingFieldProcessors.push({field:o,process:t})}else this.fieldProcessors.push({field:o,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:o,functions:r,functionCall:i,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:p,stream:d,thinkingTokenBudget:u,showThoughts:m}=n??{},g=await ji(t,l,{resultPicker:n?.resultPicker}),h=t?.history(g,l)??[];if(h.length===0)throw new Error("No chat prompt found");let f={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},A=this.isDebug(e,n),x=a===0,y=this.getLogger(e,n);return await e.chat({chatPrompt:h,functions:r,functionCall:i,modelConfig:f,model:c},{sessionId:l,rateLimiter:p,stream:d,debug:A,debugHideSystemPrompt:!x,thinkingTokenBudget:u,showThoughts:m,traceContext:o,abortSignal:n?.abortSignal,stepIndex:a,logger:y})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:o,span:r,traceContext:i}){let{sessionId:a,functions:l}=n??{},c=n?.functionCall??this.options?.functionCall,p=n?.strictMode??!1,d=n.model,u=this.createStates(n.sampleCount??1),m=this.usage,g=o===0,h=this.getLogger(e,n),{functions:f,functionCall:A}=xi(l,c,g),x=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:f,functionCall:A,stepIndex:o});x instanceof ReadableStream?yield*Di({ai:e,model:d,res:x,mem:t,sessionId:a,functions:f,strictMode:p,span:r,states:u,usage:m,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:h,functionResultFormatter:n?.functionResultFormatter??this.options?.functionResultFormatter}):yield*Gi({ai:e,model:d,res:x,mem:t,sessionId:a,functions:f,span:r,strictMode:p,states:u,usage:m,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:h,functionResultFormatter:n?.functionResultFormatter??this.options?.functionResultFormatter})}async*_forward2(e,t,n,o,r,i){let a=(o?.stopFunction??this.options?.stopFunction)?.toLowerCase(),l=o.maxRetries??this.options?.maxRetries??10,c=o.maxSteps??this.options?.maxSteps??10,p=o.mem??this.options?.mem??new pt,d;if(o?.functions&&o.functions.length>0){let x=this.options?.promptTemplate??Pe,y={functions:o.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new x(this.signature,y)}let u,m=performance.now();Array.isArray(t)?(Go(t),u=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):u=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let g=performance.now()-m,h=this.getMetricsInstruments();h&&qn(h,"prompt_render",g,this.getSignatureName());let f=performance.now();p.addRequest(u,o.sessionId);let A=performance.now()-f;h&&qn(h,"memory_update",A,this.getSignatureName());e:for(let x=0;x<c;x++){for(let O=0;O<l;O++)try{let b=this.forwardCore({options:o,ai:e,mem:p,stepIndex:x,span:r,traceContext:i});for await(let w of b)w!==void 0&&(yield{version:O,index:w.index,delta:w.delta});if(Li(p,a,n,o?.sessionId)){let w=this.getMetricsInstruments();w&&Bn(w,x+1,c,this.getSignatureName());continue e}let _=this.getMetricsInstruments();if(_){Bn(_,x+1,c,this.getSignatureName());let w=new Set;n.forEach(M=>{M.functionsExecuted.forEach(N=>w.add(N))}),w.size>0&&pr(_,!0,w.size,!0,!1,this.getSignatureName()),pi(_,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(b){let T,_=this.isDebug(e,o),w=this.getLogger(e,o),M=this.getMetricsInstruments(),N=this.getSignatureName(),H={error:b,errCount:O,logger:w,metricsInstruments:M,signatureName:N,span:r,debug:_};if(r?.recordException(b),b instanceof Q)T=gi(H),d=b;else if(b instanceof Te)T=hi(H),d=b;else if(b instanceof $)Ai(H);else if(!(b instanceof le))throw Er(b,e,this.signature);T&&(p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(T)}],o.sessionId),p.addTag("error",o.sessionId))}let y=this.getMetricsInstruments();throw y&&cr(y,l,!1,l,this.getSignatureName()),Er(new Error(`Unable to fix validation error: ${d?.toString()}`),e,this.signature)}throw h&&Bn(h,c,c,this.getSignatureName()),Er(new Error(`Max steps reached: ${c}`),e,this.signature)}async*_forward1(e,t,n){let o=performance.now(),r=this.createStates(n.sampleCount??1),i=performance.now()-o,a=this.getMetricsInstruments();a&&qn(a,"state_creation",i,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,c=this.functions;if(n?.functions&&(c=ur(n.functions,this.functions)),!l){yield*this._forward2(e,t,r,{...n,functions:c});return}let p=c?.map(A=>A.name).join(","),d={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...p?{provided_functions:p}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},u=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=u?`AxGen > ${u}`:"AxGen",g=l.startSpan(m,{kind:ie.SERVER,attributes:d}),h=$e.active(),f=So.setSpan(h,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,r,{...n,functions:c},g,f),!this.excludeContentFromTrace){let A=r.map(y=>y.values),x=A.length===1?A[0]:A;g.addEvent("output",{content:JSON.stringify(x,null,2)})}}finally{g.end()}}async forward(e,t,n){let o=performance.now(),r=this.getSignatureName(),i=n?.stream??!1,a=!1,l=0,c=!1,p=0,d=!1;try{let u=this.getMetricsInstruments();u&&mi(u,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,r),c=!!(n?.functions||this.functions);let m=this._forward1(e,t,n??{}),g=[],h=0,f=0;for await(let T of m)T.version!==h&&(g=[]),h=T.version,g=Cr(g,T),f++;l=h;let A=performance.now();d=!!n?.resultPicker;let x=await Kn(g,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),y=performance.now()-A,b=g[x]?.delta??{};if(this.trace={...t,...b},d&&this.isDebug(e,n)){let T=this.getLogger(e,n);Is(g.length,x,y,T)}return a=!0,u&&(di(u,g.length,d,d?y:void 0,r),ui(u,i,f,void 0,r)),b}catch(u){throw a=!1,u}finally{let u=performance.now()-o,m=this.getMetricsInstruments();m&&(li(m,u,a,r,e.getName(),n?.model?String(n.model):void 0),c&&pr(m,c,p,p>0,!1,r),l>0&&cr(m,l,a,n?.maxRetries??10,r))}}async*streamingForward(e,t,n){if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let o=this._forward1(e,t,{...n,stream:!0}),r=[],i=0;for await(let c of o)c.version!==i&&(r=[]),i=c.version,r=Cr(r,c);let a=await Kn(r,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),l=r[a];l&&(yield{version:i,index:a,delta:l.delta})}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??B.logger??e.getLogger()}},Ht=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function Er(s,e,t){let n=s instanceof Error?s:new Error(String(s)),o=e.getLastUsedChatModel(),r=e.getLastUsedModelConfig(),i={model:o,maxTokens:r?.maxTokens,streaming:r?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new Ht("Generate failed",i,{cause:n})}var Rl=s=>s.replace(/^\W+|\W+$/g,""),Cl=(s,e)=>{let t=s.search(e);if(t===-1)return[s];let n=s.match(e);if(!n)throw new Error("Match failed unexpectedly.");let o=s.substring(0,t),r=s.substring(t+n[0].length);return[o,r]},Tl=s=>{let e=new Set,t=[];for(let n of s)e.has(n)||(e.add(n),t.push(n));return t},wl=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);if(!e||e.length<3)throw new Error('line must start with a number, a dot and then text. e.g. "1. hello"');let t=Number.parseInt(e[1],10),n=e[2].trim();return{id:t,text:n}},vl=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():s},Sl=(s,e)=>{let t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t},dt={trimNonAlphaNum:Rl,splitIntoTwo:Cl,dedup:Tl,extractIdAndText:wl,extractIndexPrefixedText:vl,batchArray:Sl};var Vn=class extends j{constructor(e){super(`"You are a re-ranker assistant tasked with evaluating a set of content items in relation to a specific question. Your role involves critically analyzing each content item to determine its relevance to the question and re-ranking them accordingly. This process includes assigning a relevance score from 0 to 10 to each content item based on how well it answers the question, its coverage of the topic, and the reliability of its information. This re-ranked list should start with the content item that is most relevant to the question and end with the least relevant. Output only the list."
|
|
187
|
-
query: string, items: string[] -> rankedItems: string[] "list of id, 5-words Rationale, relevance score"`,e)}forward=async(e,t,n)=>{let{rankedItems:
|
|
188
|
-
${Hi.greenBright(JSON.stringify(r.map(a=>`${a.id}, ${a.score}`)))}`);let i=r.at(0);return i?i.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var Ki=new Set(["0o","0s","3a","3b","3d","6b","6o","a","a1","a2","a3","a4","ab","able","about","above","abst","ac","accordance","according","accordingly","across","act","actually","ad","added","adj","ae","af","affected","affecting","affects","after","afterwards","ag","again","against","ah","ain","ain't","aj","al","all","allow","allows","almost","alone","along","already","also","although","always","am","among","amongst","amoungst","amount","an","and","announce","another","any","anybody","anyhow","anymore","anyone","anything","anyway","anyways","anywhere","ao","ap","apart","apparently","appear","appreciate","appropriate","approximately","ar","are","aren","arent","aren't","arise","around","as","a's","aside","ask","asking","associated","at","au","auth","av","available","aw","away","awfully","ax","ay","az","b","b1","b2","b3","ba","back","bc","bd","be","became","because","become","becomes","becoming","been","before","beforehand","begin","beginning","beginnings","begins","behind","being","believe","below","beside","besides","best","better","between","beyond","bi","bill","biol","bj","bk","bl","bn","both","bottom","bp","br","brief","briefly","bs","bt","bu","but","bx","by","c","c1","c2","c3","ca","call","came","can","cannot","cant","can't","cause","causes","cc","cd","ce","certain","certainly","cf","cg","ch","changes","ci","cit","cj","cl","clearly","cm","c'mon","cn","co","com","come","comes","con","concerning","consequently","consider","considering","contain","containing","contains","corresponding","could","couldn","couldnt","couldn't","course","cp","cq","cr","cry","cs","c's","ct","cu","currently","cv","cx","cy","cz","d","d2","da","date","dc","dd","de","definitely","describe","described","despite","detail","df","di","did","didn","didn't","different","dj","dk","dl","do","does","doesn","doesn't","doing","don","done","don't","down","downwards","dp","dr","ds","dt","du","due","during","dx","dy","e","e2","e3","ea","each","ec","ed","edu","ee","ef","effect","eg","ei","eight","eighty","either","ej","el","eleven","else","elsewhere","em","empty","en","end","ending","enough","entirely","eo","ep","eq","er","es","especially","est","et","et-al","etc","eu","ev","even","ever","every","everybody","everyone","everything","everywhere","ex","exactly","example","except","ey","f","f2","fa","far","fc","few","ff","fi","fifteen","fifth","fify","fill","find","fire","first","five","fix","fj","fl","fn","fo","followed","following","follows","for","former","formerly","forth","forty","found","four","fr","from","front","ft","fu","full","further","furthermore","fy","g","ga","gave","ge","get","gets","getting","gi","give","given","gives","giving","gj","gl","go","goes","going","gone","got","gotten","gr","greetings","gs","gy","h","h2","h3","had","hadn","hadn't","happens","hardly","has","hasn","hasnt","hasn't","have","haven","haven't","having","he","hed","he'd","he'll","hello","help","hence","her","here","hereafter","hereby","herein","heres","here's","hereupon","hers","herself","hes","he's","hh","hi","hid","him","himself","his","hither","hj","ho","home","hopefully","how","howbeit","however","how's","hr","hs","http","hu","hundred","hy","i","i2","i3","i4","i6","i7","i8","ia","ib","ibid","ic","id","i'd","ie","if","ig","ignored","ih","ii","ij","il","i'll","im","i'm","immediate","immediately","importance","important","in","inasmuch","inc","indeed","index","indicate","indicated","indicates","information","inner","insofar","instead","interest","into","invention","inward","io","ip","iq","ir","is","isn","isn't","it","itd","it'd","it'll","its","it's","itself","iv","i've","ix","iy","iz","j","jj","jr","js","jt","ju","just","k","ke","keep","keeps","kept","kg","kj","km","know","known","knows","ko","l","l2","la","largely","last","lately","later","latter","latterly","lb","lc","le","least","les","less","lest","let","lets","let's","lf","like","liked","likely","line","little","lj","ll","ll","ln","lo","look","looking","looks","los","lr","ls","lt","ltd","m","m2","ma","made","mainly","make","makes","many","may","maybe","me","mean","means","meantime","meanwhile","merely","mg","might","mightn","mightn't","mill","million","mine","miss","ml","mn","mo","more","moreover","most","mostly","move","mr","mrs","ms","mt","mu","much","mug","must","mustn","mustn't","my","myself","model","n","n2","na","name","namely","nay","nc","nd","ne","near","nearly","necessarily","necessary","need","needn","needn't","needs","neither","never","nevertheless","new","next","ng","ni","nine","ninety","nj","nl","nn","no","nobody","non","none","nonetheless","noone","nor","normally","nos","not","noted","nothing","novel","now","nowhere","nr","ns","nt","ny","o","oa","ob","obtain","obtained","obviously","oc","od","of","off","often","og","oh","oi","oj","ok","okay","ol","old","om","omitted","on","once","one","ones","only","onto","oo","op","oq","or","ord","os","ot","other","others","otherwise","ou","ought","our","ours","ourselves","out","outside","over","overall","ow","owing","own","ox","oz","p","p1","p2","p3","page","pagecount","pages","par","part","particular","particularly","pas","past","pc","pd","pe","per","perhaps","pf","ph","pi","pj","pk","pl","placed","please","plus","pm","pn","po","poorly","possible","possibly","potentially","pp","pq","pr","predominantly","present","presumably","previously","primarily","probably","promptly","proud","provides","ps","pt","pu","put","py","q","qj","qu","que","quickly","quite","qv","r","r2","ra","ran","rather","rc","rd","re","readily","really","reasonably","recent","recently","ref","refs","regarding","regardless","regards","related","relatively","research","research-articl","respectively","resulted","resulting","results","rf","rh","ri","right","rj","rl","rm","rn","ro","rq","rr","rs","rt","ru","run","rv","ry","s","s2","sa","said","same","saw","say","saying","says","sc","sd","se","sec","second","secondly","section","see","seeing","seem","seemed","seeming","seems","seen","self","selves","sensible","sent","serious","seriously","seven","several","sf","shall","shan","shan't","she","shed","she'd","she'll","shes","she's","should","shouldn","shouldn't","should've","show","showed","shown","showns","shows","si","side","significant","significantly","similar","similarly","since","sincere","six","sixty","sj","sl","slightly","sm","sn","so","some","somebody","somehow","someone","somethan","something","sometime","sometimes","somewhat","somewhere","soon","sorry","sp","specifically","specified","specify","specifying","sq","sr","ss","st","still","stop","strongly","sub","substantially","successfully","such","sufficiently","suggest","sup","sure","sy","system","sz","t","t1","t2","t3","take","taken","taking","tb","tc","td","te","tell","ten","tends","tf","th","than","thank","thanks","thanx","that","that'll","thats","that's","that've","the","their","theirs","them","themselves","then","thence","there","thereafter","thereby","thered","therefore","therein","there'll","thereof","therere","theres","there's","thereto","thereupon","there've","these","they","theyd","they'd","they'll","theyre","they're","they've","thickv","thin","think","third","this","thorough","thoroughly","those","thou","though","thoughh","thousand","three","throug","through","throughout","thru","thus","ti","til","tip","tj","tl","tm","tn","to","together","too","took","top","toward","towards","tp","tq","tr","tried","tries","truly","try","trying","ts","t's","tt","tv","twelve","twenty","twice","two","tx","u","u201d","ue","ui","uj","uk","um","un","under","unfortunately","unless","unlike","unlikely","until","unto","uo","up","upon","ups","ur","us","use","used","useful","usefully","usefulness","uses","using","usually","ut","v","va","value","various","vd","ve","ve","very","via","viz","vj","vo","vol","vols","volumtype","vq","vs","vt","vu","w","wa","want","wants","was","wasn","wasnt","wasn't","way","we","wed","we'd","welcome","well","we'll","well-b","went","were","we're","weren","werent","weren't","we've","what","whatever","what'll","whats","what's","when","whence","whenever","when's","where","whereafter","whereas","whereby","wherein","wheres","where's","whereupon","wherever","whether","which","while","whim","whither","who","whod","whoever","whole","who'll","whom","whomever","whos","who's","whose","why","why's","wi","widely","will","willing","wish","with","within","without","wo","won","wonder","wont","won't","words","world","would","wouldn","wouldnt","wouldn't","www","x","x1","x2","x3","xf","xi","xj","xk","xl","xn","xo","xs","xt","xv","xx","y","y2","yes","yet","yj","yl","you","youd","you'd","you'll","your","youre","you're","yours","yourself","yourselves","you've","yr","ys","yt","z","zero","zi","zz","task"]);function Vi(s,e){return s.filter(t=>!e.has(t))}function Wi(s){let e={};for(let t of s)e[t]=(e[t]||0)+1;return e}function Fe(s){let e=s.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function Ml(s,e){return Fe(s)===Fe(e)?1:0}function Ol(s,e){let t=Fe(s).split(" "),n=Fe(e).split(" "),o=Wi(t),r=Wi(n),i=0;for(let c in o){let p=o[c]??0,d=r[c]??0;i+=Math.min(p,d)}if(i===0)return 0;let a=i/t.length,l=i/n.length;return 2*a*l/(a+l)}function kl(s,e,t,n=!1){let o=Fe(s).split(" "),r=Fe(e).split(" "),i=Fe(t).split(" "),a=new Set([...Ki,...o]);r=Vi(r,a),i=Vi(i,a);let l=0,c=l/r.length,p=l/i.length,d=2*c*p/(c+p);return n?p:d}var Yi={emScore:Ml,f1Score:Ol,novelF1ScoreOptimized:kl};var Qn=class{ai;program;examples;constructor({ai:e,program:t,examples:n=[]}){if(n.length===0)throw new Error("No examples found");this.ai=e,this.program=t,this.examples=n}async run(e){let t=Date.now(),n=this.examples.length,o=0;for(let i=0;i<n;i++){let a=this.examples[i];if(!a)throw new Error("Invalid example");let l=await this.program.forward(this.ai,a),c=await e({prediction:l,example:a});o+=c}let r=n>0?o/n:0;console.log(`
|
|
189
|
-
Performance: `,
|
|
190
|
-
`)}};var
|
|
181
|
+
`}),l.forEach(p=>{"text"in p&&(p.text=`${p.text}
|
|
182
|
+
`),t.push(p)})}return t};renderDemos=e=>{let t=[],n=this.sig.getInputFields(),r=this.sig.getOutputFields(),o={isExample:!0};for(let i of e){let a=n.map(c=>this.renderInField(c,i,{...o,isInputField:!0})).filter(c=>c!==void 0).flat(),l=r.map(c=>this.renderInField(c,i,{...o,isInputField:!1})).filter(c=>c!==void 0).flat();[...a,...l].slice(0,-1).forEach(c=>{"text"in c&&(c.text=`${c.text}
|
|
183
|
+
`),t.push(c)})}return t};renderInputFields=e=>{let t=this.sig.getInputFields().map(n=>this.renderInField(n,e,void 0)).filter(n=>n!==void 0).flat();return t.filter(n=>n.type==="text").forEach(n=>{n.text=`${n.text}
|
|
184
|
+
`}),t};renderInField=(e,t,n)=>{let r=t[e.name];if(Ul(e,r,n))return;e.type&&rr(e,r);let o=Gl(e,r);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,o)};defaultRenderInField=(e,t)=>{if(e.type?.name==="image"){let r=i=>{if(!i)throw new Error("Image field value is required.");if(typeof i!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in i))throw new Error("Image field must have mimeType");if(!("data"in i))throw new Error("Image field must have data");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let i=r(t);o.push({type:"image",mimeType:i.mimeType,image:i.data})}return o}if(e.type?.name==="audio"){let r=i=>{if(!i)throw new Error("Audio field value is required.");if(typeof i!="object")throw new Error("Audio field value must be an object.");if(!("data"in i))throw new Error("Audio field must have data");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let i=r(t);o.push({type:"audio",format:i.format??"wav",data:i.data})}return o}if(e.type?.name==="file"){let r=i=>{if(!i)throw new Error("File field value is required.");if(typeof i!="object")throw new Error("File field value must be an object.");if(!("filename"in i))throw new Error("File field must have filename");if(!("mimeType"in i))throw new Error("File field must have mimeType");if(!("data"in i))throw new Error("File field must have data");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return{type:"file",filename:a.filename,mimeType:a.mimeType,data:a.data}}))}else{let i=r(t);o.push({type:"file",filename:i.filename,mimeType:i.mimeType,data:i.data})}return o}if(e.type?.name==="url"){let r=i=>{if(!i)throw new Error("URL field value is required.");if(typeof i=="string")return{url:i};if(typeof i!="object")throw new Error("URL field value must be a string or object.");if(!("url"in i))throw new Error("URL field must have url property");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return{type:"url",url:a.url,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{}}}))}else{let i=r(t);o.push({type:"url",url:i.url,...i.title?{title:i.title}:{},...i.description?{description:i.description}:{}})}return o}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
|
|
185
|
+
`),n.push(t.map(r=>`- ${r}`).join(`
|
|
186
|
+
`))):n.push(t),[{type:"text",text:n.join("")}]}},ia=s=>s.map(e=>`\`${e.title}\``).join(", "),Ll=s=>s.map(t=>{let n=t.title,r=t.type?.name?la(t.type):"string",o=t.isOptional?`This optional ${r} field may be omitted`:`A ${r} field`,i=t.description?` ${sr(t.description)}`:"";return`${n}: (${o})${i}`.trim()}).join(`
|
|
187
|
+
`),Nl=s=>s.map(t=>{let n=t.title,r=t.type?.name?la(t.type):"string",o=t.isOptional?`Only include this ${r} field if its value is available`:`This ${r} field must be included`,i="";return t.description&&t.description.length>0&&(i=` ${t.type?.name==="class"?t.description:sr(t.description)}`),t.type?.options&&t.type.options.length>0&&(i.length>0&&(i+=". "),i+=`Allowed values: ${t.type.options.join(", ")}`),`${n}: (${o})${i}`.trim()}).join(`
|
|
188
|
+
`),Gl=(s,e)=>{if(s.type?.name==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return s.type?.name==="datetime"&&e instanceof Date?Vi(e):s.type?.name==="image"&&typeof e=="object"||s.type?.name==="audio"&&typeof e=="object"||s.type?.name==="file"&&typeof e=="object"||s.type?.name==="url"&&(typeof e=="string"||typeof e=="object")||typeof e=="string"?e:JSON.stringify(e,null,2)},la=s=>{let e=(()=>{switch(s?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"file":return"file (with filename, mimeType, and data)";case"url":return"URL (string or object with url, title, description)";default:return"string"}})();return s?.isArray?`json array of ${e} items`:e};function aa(s){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=s+t.text:e.push(t)}else e.push(t);return e}}var Ul=(s,e,t)=>{if(typeof e=="boolean")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||s.isOptional||s.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${s.name}' is required.`)}return!1};function sr(s){let e=s.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Bl(s,e){let t=s.history(0,e),n=t.some(o=>o.role==="function");return t.some(o=>o.role==="assistant"&&"functionCalls"in o&&Array.isArray(o.functionCalls)&&o.functionCalls.length>0)&&n}function ql(s,e){let t=s.history(0,e),n=[],r=t.filter(i=>i.role==="assistant"&&"functionCalls"in i&&Array.isArray(i.functionCalls)&&i.functionCalls.length>0),o=t.filter(i=>i.role==="function");for(let i of r)if("functionCalls"in i&&i.functionCalls)for(let a of i.functionCalls){let l=o.find(p=>"functionId"in p&&p.functionId===a.id);l&&"result"in l&&"functionId"in l&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(l.result),isError:"isError"in l?!!l.isError:!1})}return n}async function ir(s,e,t,n){if(!e?.resultPicker||s.length<=1)return 0;let r=e.resultPicker;if((t?Bl(t,n):!1)&&t){let l=ql(t,n),p=await r({type:"function",results:l});if(p<0||p>=l.length)throw new Error(`Result picker returned invalid index: ${p}. Must be between 0 and ${l.length-1}`);return p}let i=s.map((l,p)=>({index:p,sample:l.delta})),a=await r({type:"fields",results:i});if(a<0||a>=s.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${s.length-1}`);return a}async function pa(s,e,t){let n=s?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let r=n.chat.map(i=>({version:0,index:i.index,delta:i.value}));return await ir(r,t,s,e)}var ee=class extends ke{promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;constructor(e,t){super(e,{description:t?.description,traceLabel:t?.traceLabel}),this.options=t,this.thoughtFieldName=t?.thoughtFieldName??"thought";let n={functions:t?.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new(t?.promptTemplate??Le)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.usage=[],t?.functions&&(this.functions=Mo(t.functions))}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return To()}updateMeter(e){To(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{this.streamingAsserts.push({fieldName:e,fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let r=this.signature.getOutputFields().find(o=>o.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addFieldProcessor: field ${e} is must be a text field`);this.streamingFieldProcessors.push({field:r,process:t})}else this.fieldProcessors.push({field:r,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:r,functions:o,functionCall:i,stepIndex:a}){let{sessionId:l,model:p,rateLimiter:c,stream:d,thinkingTokenBudget:u,showThoughts:m}=n??{},g=await pa(t,l,{resultPicker:n?.resultPicker}),h=t?.history(g,l)??[];if(h.length===0)throw new Error("No chat prompt found");let A={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},f=this.isDebug(e,n),x=a===0,y=this.getLogger(e,n);return await e.chat({chatPrompt:h,functions:o,functionCall:i,modelConfig:A,model:p},{sessionId:l,rateLimiter:c,stream:d,debug:f,debugHideSystemPrompt:!x,thinkingTokenBudget:u,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal,stepIndex:a,logger:y})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:i}){let{sessionId:a,functions:l}=n??{},p=n?.functionCall??this.options?.functionCall,c=n?.strictMode??!1,d=n.model,u=this.createStates(n.sampleCount??1),m=this.usage,g=r===0,h=this.getLogger(e,n),{functions:A,functionCall:f}=Li(l,p,g),x=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:A,functionCall:f,stepIndex:r});x instanceof ReadableStream?yield*ea({ai:e,model:d,res:x,mem:t,sessionId:a,functions:A,strictMode:c,span:o,states:u,usage:m,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:h,functionResultFormatter:n?.functionResultFormatter??this.options?.functionResultFormatter}):yield*ta({ai:e,model:d,res:x,mem:t,sessionId:a,functions:A,span:o,strictMode:c,states:u,usage:m,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:h,functionResultFormatter:n?.functionResultFormatter??this.options?.functionResultFormatter})}async*_forward2(e,t,n,r,o,i){let a=(r?.stopFunction??this.options?.stopFunction)?.toLowerCase(),l=r.maxRetries??this.options?.maxRetries??10,p=r.maxSteps??this.options?.maxSteps??10,c=r.mem??this.options?.mem??new gt,d;if(r?.functions&&r.functions.length>0){let x=this.options?.promptTemplate??Le,y={functions:r.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new x(this.signature,y)}let u,m=performance.now();Array.isArray(t)?(Yr(t),u=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):u=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let g=performance.now()-m,h=this.getMetricsInstruments();h&&tr(h,"prompt_render",g,this.getSignatureName());let A=performance.now();c.addRequest(u,r.sessionId);let f=performance.now()-A;h&&tr(h,"memory_update",f,this.getSignatureName());e:for(let x=0;x<p;x++){for(let k=0;k<l;k++)try{let b=this.forwardCore({options:r,ai:e,mem:c,stepIndex:x,span:o,traceContext:i});for await(let w of b)w!==void 0&&(yield{version:k,index:w.index,delta:w.delta});if(na(c,a,n,r?.sessionId)){let w=this.getMetricsInstruments();w&&er(w,x+1,p,this.getSignatureName());continue e}let P=this.getMetricsInstruments();if(P){er(P,x+1,p,this.getSignatureName());let w=new Set;n.forEach(M=>{M.functionsExecuted.forEach(N=>w.add(N))}),w.size>0&&So(P,!0,w.size,!0,!1,this.getSignatureName()),Oi(P,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(b){let T,P=this.isDebug(e,r),w=this.getLogger(e,r),M=this.getMetricsInstruments(),N=this.getSignatureName(),z={error:b,errCount:k,logger:w,metricsInstruments:M,signatureName:N,span:o,debug:P};if(o?.recordException(b),b instanceof J)T=_i(z),d=b;else if(b instanceof Me)T=Fi(z),d=b;else if(b instanceof U)Di(z);else if(!(b instanceof ce))throw Wo(b,e,this.signature);T&&(c.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(T)}],r.sessionId),c.addTag("error",r.sessionId))}let y=this.getMetricsInstruments();throw y&&vo(y,l,!1,l,this.getSignatureName()),Wo(new Error(`Unable to fix validation error: ${d?.toString()}`),e,this.signature)}throw h&&er(h,p,p,this.getSignatureName()),Wo(new Error(`Max steps reached: ${p}`),e,this.signature)}async*_forward1(e,t,n){let r=performance.now(),o=this.createStates(n.sampleCount??1),i=performance.now()-r,a=this.getMetricsInstruments();a&&tr(a,"state_creation",i,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,p=this.functions;if(n?.functions&&(p=Mo(n.functions,this.functions)),!l){yield*this._forward2(e,t,o,{...n,functions:p});return}let c=p?.map(f=>f.name).join(","),d={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...c?{provided_functions:c}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},u=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=u?`AxGen > ${u}`:"AxGen",g=l.startSpan(m,{kind:le.SERVER,attributes:d}),h=je.active(),A=Ur.setSpan(h,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:p},g,A),!this.excludeContentFromTrace){let f=o.map(y=>y.values),x=f.length===1?f[0]:f;g.addEvent("output",{content:JSON.stringify(x,null,2)})}}finally{g.end()}}async forward(e,t,n){let r=performance.now(),o=this.getSignatureName(),i=n?.stream??!1,a=!1,l=0,p=!1,c=0,d=!1;try{let u=this.getMetricsInstruments();u&&Pi(u,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,o),p=!!(n?.functions||this.functions);let m=this._forward1(e,t,n??{}),g=[],h=0,A=0;for await(let T of m)T.version!==h&&(g=[]),h=T.version,g=Uo(g,T),A++;l=h;let f=performance.now();d=!!n?.resultPicker;let x=await ir(g,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),y=performance.now()-f,b=g[x]?.delta??{};if(this.trace={...t,...b},d&&this.isDebug(e,n)){let T=this.getLogger(e,n);Fs(g.length,x,y,T)}return a=!0,u&&(Ei(u,g.length,d,d?y:void 0,o),ki(u,i,A,void 0,o)),b}catch(u){throw a=!1,u}finally{let u=performance.now()-r,m=this.getMetricsInstruments();m&&(Si(m,u,a,o,e.getName(),n?.model?String(n.model):void 0),p&&So(m,p,c,c>0,!1,o),l>0&&vo(m,l,a,n?.maxRetries??10,o))}}async*streamingForward(e,t,n){if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let r=this._forward1(e,t,{...n,stream:!0}),o=[],i=0;for await(let p of r)p.version!==i&&(o=[]),i=p.version,o=Uo(o,p);let a=await ir(o,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),l=o[a];l&&(yield{version:i,index:a,delta:l.delta})}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??B.logger??e.getLogger()}},Xt=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function Wo(s,e,t){let n=s instanceof Error?s:new Error(String(s)),r=e.getLastUsedChatModel(),o=e.getLastUsedModelConfig(),i={model:r,maxTokens:o?.maxTokens,streaming:o?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new Xt("Generate failed",i,{cause:n})}var zl=s=>s.replace(/^\W+|\W+$/g,""),jl=(s,e)=>{let t=s.search(e);if(t===-1)return[s];let n=s.match(e);if(!n)throw new Error("Match failed unexpectedly.");let r=s.substring(0,t),o=s.substring(t+n[0].length);return[r,o]},Hl=s=>{let e=new Set,t=[];for(let n of s)e.has(n)||(e.add(n),t.push(n));return t},Kl=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);if(!e||e.length<3)throw new Error('line must start with a number, a dot and then text. e.g. "1. hello"');let t=Number.parseInt(e[1],10),n=e[2].trim();return{id:t,text:n}},Vl=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():s},Wl=(s,e)=>{let t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t},ar={trimNonAlphaNum:zl,splitIntoTwo:jl,dedup:Hl,extractIdAndText:Kl,extractIndexPrefixedText:Vl,batchArray:Wl};var lr=class extends ee{constructor(e){super(`"You are a re-ranker assistant tasked with evaluating a set of content items in relation to a specific question. Your role involves critically analyzing each content item to determine its relevance to the question and re-ranking them accordingly. This process includes assigning a relevance score from 0 to 10 to each content item based on how well it answers the question, its coverage of the topic, and the reliability of its information. This re-ranked list should start with the content item that is most relevant to the question and end with the least relevant. Output only the list."
|
|
189
|
+
query: string, items: string[] -> rankedItems: string[] "list of id, 5-words Rationale, relevance score"`,e)}forward=async(e,t,n)=>{let{rankedItems:r}=await super.forward(e,t,n),o=r.map(a=>{let{id:l}=ar.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let p=o[l];return p!==void 0?t.items[p]:void 0}).filter(a=>a!==void 0)}}};var pr=class{tikaUrl;fetch;constructor(e){let t=e??{url:"http://localhost:9998/"};this.tikaUrl=new URL("/tika",t.url),this.fetch=t.fetch}async _convert(e,t){if(!e)throw new Error("Failed to read file data");let n=t?.format==="html"?"text/html":"text/plain";try{let r={body:e,headers:{Accept:n},method:"PUT"};typeof window>"u"&&typeof process<"u"&&(r.duplex="half");let o=await(this.fetch??fetch)(this.tikaUrl,r);if(!o.ok)throw new Error(`Failed to upload file: ${o.statusText}`);return await o.text()}catch(r){throw new Error(`Error converting file: ${r}`)}}async convert(e,t){let n=[],r=t?.batchSize??10;for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r).map(p=>this._convert(p,{format:t?.format})),l=await Promise.all(a);n.push(...l)}return n}};var ca=new Z,cr=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},ur=class{ai;db;debug;constructor(e){this.db=new Se,this.ai=e}getState(){return this.db.getDB()}setState(e){this.db.setDB(e)}setClasses=async(e,t)=>{for(let n of e){let r=await this.ai.embed({texts:n.getContext()},{abortSignal:t?.abortSignal});await this.db.upsert({id:n.getName(),table:"classes",values:r.embeddings[0]})}};async forward(e,t){let{embeddings:n}=await this.ai.embed({texts:[e]},{abortSignal:t?.abortSignal}),o=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;o=o.filter(l=>l.score<=a)}this.debug&&console.log(`${ca.whiteBright(`query: ${e}`)}
|
|
190
|
+
${ca.greenBright(JSON.stringify(o.map(a=>`${a.id}, ${a.score}`)))}`);let i=o.at(0);return i?i.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var ua=new Set(["0o","0s","3a","3b","3d","6b","6o","a","a1","a2","a3","a4","ab","able","about","above","abst","ac","accordance","according","accordingly","across","act","actually","ad","added","adj","ae","af","affected","affecting","affects","after","afterwards","ag","again","against","ah","ain","ain't","aj","al","all","allow","allows","almost","alone","along","already","also","although","always","am","among","amongst","amoungst","amount","an","and","announce","another","any","anybody","anyhow","anymore","anyone","anything","anyway","anyways","anywhere","ao","ap","apart","apparently","appear","appreciate","appropriate","approximately","ar","are","aren","arent","aren't","arise","around","as","a's","aside","ask","asking","associated","at","au","auth","av","available","aw","away","awfully","ax","ay","az","b","b1","b2","b3","ba","back","bc","bd","be","became","because","become","becomes","becoming","been","before","beforehand","begin","beginning","beginnings","begins","behind","being","believe","below","beside","besides","best","better","between","beyond","bi","bill","biol","bj","bk","bl","bn","both","bottom","bp","br","brief","briefly","bs","bt","bu","but","bx","by","c","c1","c2","c3","ca","call","came","can","cannot","cant","can't","cause","causes","cc","cd","ce","certain","certainly","cf","cg","ch","changes","ci","cit","cj","cl","clearly","cm","c'mon","cn","co","com","come","comes","con","concerning","consequently","consider","considering","contain","containing","contains","corresponding","could","couldn","couldnt","couldn't","course","cp","cq","cr","cry","cs","c's","ct","cu","currently","cv","cx","cy","cz","d","d2","da","date","dc","dd","de","definitely","describe","described","despite","detail","df","di","did","didn","didn't","different","dj","dk","dl","do","does","doesn","doesn't","doing","don","done","don't","down","downwards","dp","dr","ds","dt","du","due","during","dx","dy","e","e2","e3","ea","each","ec","ed","edu","ee","ef","effect","eg","ei","eight","eighty","either","ej","el","eleven","else","elsewhere","em","empty","en","end","ending","enough","entirely","eo","ep","eq","er","es","especially","est","et","et-al","etc","eu","ev","even","ever","every","everybody","everyone","everything","everywhere","ex","exactly","example","except","ey","f","f2","fa","far","fc","few","ff","fi","fifteen","fifth","fify","fill","find","fire","first","five","fix","fj","fl","fn","fo","followed","following","follows","for","former","formerly","forth","forty","found","four","fr","from","front","ft","fu","full","further","furthermore","fy","g","ga","gave","ge","get","gets","getting","gi","give","given","gives","giving","gj","gl","go","goes","going","gone","got","gotten","gr","greetings","gs","gy","h","h2","h3","had","hadn","hadn't","happens","hardly","has","hasn","hasnt","hasn't","have","haven","haven't","having","he","hed","he'd","he'll","hello","help","hence","her","here","hereafter","hereby","herein","heres","here's","hereupon","hers","herself","hes","he's","hh","hi","hid","him","himself","his","hither","hj","ho","home","hopefully","how","howbeit","however","how's","hr","hs","http","hu","hundred","hy","i","i2","i3","i4","i6","i7","i8","ia","ib","ibid","ic","id","i'd","ie","if","ig","ignored","ih","ii","ij","il","i'll","im","i'm","immediate","immediately","importance","important","in","inasmuch","inc","indeed","index","indicate","indicated","indicates","information","inner","insofar","instead","interest","into","invention","inward","io","ip","iq","ir","is","isn","isn't","it","itd","it'd","it'll","its","it's","itself","iv","i've","ix","iy","iz","j","jj","jr","js","jt","ju","just","k","ke","keep","keeps","kept","kg","kj","km","know","known","knows","ko","l","l2","la","largely","last","lately","later","latter","latterly","lb","lc","le","least","les","less","lest","let","lets","let's","lf","like","liked","likely","line","little","lj","ll","ll","ln","lo","look","looking","looks","los","lr","ls","lt","ltd","m","m2","ma","made","mainly","make","makes","many","may","maybe","me","mean","means","meantime","meanwhile","merely","mg","might","mightn","mightn't","mill","million","mine","miss","ml","mn","mo","more","moreover","most","mostly","move","mr","mrs","ms","mt","mu","much","mug","must","mustn","mustn't","my","myself","model","n","n2","na","name","namely","nay","nc","nd","ne","near","nearly","necessarily","necessary","need","needn","needn't","needs","neither","never","nevertheless","new","next","ng","ni","nine","ninety","nj","nl","nn","no","nobody","non","none","nonetheless","noone","nor","normally","nos","not","noted","nothing","novel","now","nowhere","nr","ns","nt","ny","o","oa","ob","obtain","obtained","obviously","oc","od","of","off","often","og","oh","oi","oj","ok","okay","ol","old","om","omitted","on","once","one","ones","only","onto","oo","op","oq","or","ord","os","ot","other","others","otherwise","ou","ought","our","ours","ourselves","out","outside","over","overall","ow","owing","own","ox","oz","p","p1","p2","p3","page","pagecount","pages","par","part","particular","particularly","pas","past","pc","pd","pe","per","perhaps","pf","ph","pi","pj","pk","pl","placed","please","plus","pm","pn","po","poorly","possible","possibly","potentially","pp","pq","pr","predominantly","present","presumably","previously","primarily","probably","promptly","proud","provides","ps","pt","pu","put","py","q","qj","qu","que","quickly","quite","qv","r","r2","ra","ran","rather","rc","rd","re","readily","really","reasonably","recent","recently","ref","refs","regarding","regardless","regards","related","relatively","research","research-articl","respectively","resulted","resulting","results","rf","rh","ri","right","rj","rl","rm","rn","ro","rq","rr","rs","rt","ru","run","rv","ry","s","s2","sa","said","same","saw","say","saying","says","sc","sd","se","sec","second","secondly","section","see","seeing","seem","seemed","seeming","seems","seen","self","selves","sensible","sent","serious","seriously","seven","several","sf","shall","shan","shan't","she","shed","she'd","she'll","shes","she's","should","shouldn","shouldn't","should've","show","showed","shown","showns","shows","si","side","significant","significantly","similar","similarly","since","sincere","six","sixty","sj","sl","slightly","sm","sn","so","some","somebody","somehow","someone","somethan","something","sometime","sometimes","somewhat","somewhere","soon","sorry","sp","specifically","specified","specify","specifying","sq","sr","ss","st","still","stop","strongly","sub","substantially","successfully","such","sufficiently","suggest","sup","sure","sy","system","sz","t","t1","t2","t3","take","taken","taking","tb","tc","td","te","tell","ten","tends","tf","th","than","thank","thanks","thanx","that","that'll","thats","that's","that've","the","their","theirs","them","themselves","then","thence","there","thereafter","thereby","thered","therefore","therein","there'll","thereof","therere","theres","there's","thereto","thereupon","there've","these","they","theyd","they'd","they'll","theyre","they're","they've","thickv","thin","think","third","this","thorough","thoroughly","those","thou","though","thoughh","thousand","three","throug","through","throughout","thru","thus","ti","til","tip","tj","tl","tm","tn","to","together","too","took","top","toward","towards","tp","tq","tr","tried","tries","truly","try","trying","ts","t's","tt","tv","twelve","twenty","twice","two","tx","u","u201d","ue","ui","uj","uk","um","un","under","unfortunately","unless","unlike","unlikely","until","unto","uo","up","upon","ups","ur","us","use","used","useful","usefully","usefulness","uses","using","usually","ut","v","va","value","various","vd","ve","ve","very","via","viz","vj","vo","vol","vols","volumtype","vq","vs","vt","vu","w","wa","want","wants","was","wasn","wasnt","wasn't","way","we","wed","we'd","welcome","well","we'll","well-b","went","were","we're","weren","werent","weren't","we've","what","whatever","what'll","whats","what's","when","whence","whenever","when's","where","whereafter","whereas","whereby","wherein","wheres","where's","whereupon","wherever","whether","which","while","whim","whither","who","whod","whoever","whole","who'll","whom","whomever","whos","who's","whose","why","why's","wi","widely","will","willing","wish","with","within","without","wo","won","wonder","wont","won't","words","world","would","wouldn","wouldnt","wouldn't","www","x","x1","x2","x3","xf","xi","xj","xk","xl","xn","xo","xs","xt","xv","xx","y","y2","yes","yet","yj","yl","you","youd","you'd","you'll","your","youre","you're","yours","yourself","yourselves","you've","yr","ys","yt","z","zero","zi","zz","task"]);function da(s,e){return s.filter(t=>!e.has(t))}function ma(s){let e={};for(let t of s)e[t]=(e[t]||0)+1;return e}function Ne(s){let e=s.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function Yl(s,e){return Ne(s)===Ne(e)?1:0}function Jl(s,e){let t=Ne(s).split(" "),n=Ne(e).split(" "),r=ma(t),o=ma(n),i=0;for(let p in r){let c=r[p]??0,d=o[p]??0;i+=Math.min(c,d)}if(i===0)return 0;let a=i/t.length,l=i/n.length;return 2*a*l/(a+l)}function Ql(s,e,t,n=!1){let r=Ne(s).split(" "),o=Ne(e).split(" "),i=Ne(t).split(" "),a=new Set([...ua,...r]);o=da(o,a),i=da(i,a);let l=0,p=l/o.length,c=l/i.length,d=2*p*c/(p+c);return n?c:d}var ga={emScore:Yl,f1Score:Jl,novelF1ScoreOptimized:Ql};var dr=class{ai;program;examples;constructor({ai:e,program:t,examples:n=[]}){if(n.length===0)throw new Error("No examples found");this.ai=e,this.program=t,this.examples=n}async run(e){let t=Date.now(),n=this.examples.length,r=0;for(let i=0;i<n;i++){let a=this.examples[i];if(!a)throw new Error("Invalid example");try{let l=await this.program.forward(this.ai,a,{maxRetries:1}),p=await e({prediction:l,example:a});r+=p}catch(l){console.warn(`Program evaluation failed for example ${i}: ${l instanceof Error?l.message:"Unknown error"}`)}}let o=n>0?r/n:0;console.log(`
|
|
191
|
+
Performance: `,r,"/",n,"Average Score: ",o,`
|
|
192
|
+
`)}};var mr=class{rows=[];baseUrl;dataset;split;config;options;constructor({dataset:e,split:t,config:n,options:r}){this.baseUrl="https://datasets-server.huggingface.co/rows",this.dataset=e,this.split=t,this.config=n,this.options=r}async fetchDataFromAPI(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`Error fetching data: ${t.statusText}`);let n=await t.json();if(!n?.rows)throw new Error("Invalid data format");return n.rows}catch(t){throw console.error("Error fetching data from API:",t),t}}async loadData(){let e=this.options?.offset??0,t=this.options?.length??100,n=encodeURIComponent(this.dataset),r=`${this.baseUrl}?dataset=${n}&config=${this.config}&split=${this.split}&offset=${e}&length=${t}`;return console.log("Downloading data from API."),this.rows=await this.fetchDataFromAPI(r),this.rows}setData(e){this.rows=e}getData(){return this.rows}async getRows({count:e,fields:t,renameMap:n}){if(this.rows.length===0)throw new Error("No data loaded, call loadData or setData first.");return this.rows.slice(0,e).map(o=>{let i={};return t.forEach(a=>{let l=a.split("."),p=o.row;for(let d of l)Object.hasOwn(p,d)&&(p=p[d]);if(!p)return;let c=n&&a in n?n[a]:a;if(!c)throw new Error(`Invalid field name: ${a}`);i[c]=p}),i}).filter(o=>Object.keys(o).length!==0)}};var ha=s=>{console.log(s)},Yo=(s=ha)=>{let e=new Z,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let o="";switch(r.name){case"OptimizationStart":o=`
|
|
191
193
|
${e.blueBright("\u25CF ")}${e.whiteBright("Optimization Started")}
|
|
192
194
|
${t}
|
|
193
|
-
${e.white("Optimizer:")} ${e.cyan(
|
|
194
|
-
${e.white("Examples:")} ${e.green(
|
|
195
|
-
${e.white("Config:")} ${e.white(JSON.stringify(
|
|
195
|
+
${e.white("Optimizer:")} ${e.cyan(r.value.optimizerType)}
|
|
196
|
+
${e.white("Examples:")} ${e.green(r.value.exampleCount.toString())} training, ${e.green(r.value.validationCount.toString())} validation
|
|
197
|
+
${e.white("Config:")} ${e.white(JSON.stringify(r.value.config).slice(0,80))}${JSON.stringify(r.value.config).length>80?"...":""}
|
|
196
198
|
${n}
|
|
197
|
-
`;break;case"RoundProgress":
|
|
198
|
-
${e.white("Score:")} ${e.green(
|
|
199
|
-
`;break;case"EarlyStopping":
|
|
199
|
+
`;break;case"RoundProgress":o=`${e.yellow("\u25CF ")}${e.whiteBright(`Round ${r.value.round}/${r.value.totalRounds}`)}
|
|
200
|
+
${e.white("Score:")} ${e.green(r.value.currentScore.toFixed(3))} ${e.white("(best:")} ${e.greenBright(r.value.bestScore.toFixed(3))}${e.white(")")}
|
|
201
|
+
`;break;case"EarlyStopping":o=`
|
|
200
202
|
${e.red("\u25CF ")}${e.whiteBright("Early Stopping")}
|
|
201
203
|
${t}
|
|
202
|
-
${e.white("Round:")} ${e.yellow(
|
|
203
|
-
${e.white("Reason:")} ${e.yellow(
|
|
204
|
-
${e.white("Final Score:")} ${e.green(
|
|
204
|
+
${e.white("Round:")} ${e.yellow(r.value.round.toString())}
|
|
205
|
+
${e.white("Reason:")} ${e.yellow(r.value.reason)}
|
|
206
|
+
${e.white("Final Score:")} ${e.green(r.value.finalScore.toFixed(3))}
|
|
205
207
|
${n}
|
|
206
|
-
`;break;case"OptimizationComplete":
|
|
208
|
+
`;break;case"OptimizationComplete":o=`
|
|
207
209
|
${e.green("\u25CF ")}${e.whiteBright("Optimization Complete")}
|
|
208
210
|
${t}
|
|
209
|
-
${e.white("Best Score:")} ${e.greenBright(
|
|
210
|
-
${e.white("Best Config:")} ${e.cyan(JSON.stringify(
|
|
211
|
-
${e.white("Total Calls:")} ${e.white(
|
|
212
|
-
${e.white("Success Rate:")} ${e.green(`${((
|
|
211
|
+
${e.white("Best Score:")} ${e.greenBright(r.value.bestScore.toFixed(3))}
|
|
212
|
+
${e.white("Best Config:")} ${e.cyan(JSON.stringify(r.value.bestConfiguration).slice(0,80))}${JSON.stringify(r.value.bestConfiguration).length>80?"...":""}
|
|
213
|
+
${e.white("Total Calls:")} ${e.white(r.value.stats.totalCalls?.toString()||"N/A")}
|
|
214
|
+
${e.white("Success Rate:")} ${e.green(`${((r.value.stats.successfulDemos||0)/Math.max(r.value.stats.totalCalls||1,1)*100).toFixed(1)}%`)}
|
|
213
215
|
${n}
|
|
214
|
-
`;break;case"ConfigurationProposal":
|
|
215
|
-
${e.white("Candidates:")} ${e.white(
|
|
216
|
-
`;break;case"BootstrappedDemos":
|
|
217
|
-
${e.white("Generated:")} ${e.green(
|
|
218
|
-
`;break;case"BestConfigFound":
|
|
219
|
-
${e.white("Score:")} ${e.greenBright(
|
|
220
|
-
${e.white("Config:")} ${e.cyan(JSON.stringify(
|
|
221
|
-
`;break;default:
|
|
222
|
-
${e.white(JSON.stringify(
|
|
223
|
-
`}s(
|
|
216
|
+
`;break;case"ConfigurationProposal":o=`${e.magenta("\u25CF ")}${e.whiteBright(`${r.value.type} Proposals`)} ${e.white(`(${r.value.count})`)}
|
|
217
|
+
${e.white("Candidates:")} ${e.white(r.value.proposals.slice(0,2).map(i=>typeof i=="string"?`"${i.slice(0,40)}..."`:`${JSON.stringify(i).slice(0,40)}...`).join(", "))}
|
|
218
|
+
`;break;case"BootstrappedDemos":o=`${e.cyan("\u25CF ")}${e.whiteBright("Bootstrapped Demos")} ${e.white(`(${r.value.count})`)}
|
|
219
|
+
${e.white("Generated:")} ${e.green(r.value.count.toString())} demonstration examples
|
|
220
|
+
`;break;case"BestConfigFound":o=`${e.green("\u25CF ")}${e.whiteBright("Best Configuration Found")}
|
|
221
|
+
${e.white("Score:")} ${e.greenBright(r.value.score.toFixed(3))}
|
|
222
|
+
${e.white("Config:")} ${e.cyan(JSON.stringify(r.value.config).slice(0,80))}${JSON.stringify(r.value.config).length>80?"...":""}
|
|
223
|
+
`;break;default:o=`${e.red("\u25CF ")}${e.whiteBright("Unknown Event")}
|
|
224
|
+
${e.white(JSON.stringify(r).slice(0,100))}${JSON.stringify(r).length>100?"...":""}
|
|
225
|
+
`}s(o)}},fa=(s=ha)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
|
|
224
226
|
${e}
|
|
225
227
|
Config: ${JSON.stringify(t.value.config,null,2)}
|
|
226
228
|
Examples: ${t.value.exampleCount}, Validation: ${t.value.validationCount}
|
|
@@ -246,7 +248,7 @@ Score: ${t.value.score.toFixed(3)}
|
|
|
246
248
|
Config: ${JSON.stringify(t.value.config)}
|
|
247
249
|
${e}`;break;default:n=`[ UNKNOWN OPTIMIZER EVENT ]
|
|
248
250
|
${JSON.stringify(t)}
|
|
249
|
-
${e}`}s(n)}},Xn=_r();var Pr={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},eo,El=s=>{if(eo)return eo;if(s)return eo=_l(s),eo};var to=Pr,Zi=s=>{to={...to,...s}},Xi=()=>({...to}),_l=s=>({optimizationLatencyHistogram:s.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:s.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:s.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:s.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:s.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:s.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:s.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:s.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:s.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:s.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:s.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:s.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:s.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:s.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:s.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:s.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:s.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:s.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:s.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:s.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:s.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:s.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:s.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:s.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:s.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:s.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:s.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:s.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:s.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:s.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:s.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),ue=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let o=String(n),r=to.maxLabelLength;e[t]=o.length>r?o.substring(0,r):o}return e},Pl=(s,e,t,n,o)=>{try{let r=ue({success:t.toString(),optimizer_type:n,...o?{program_signature:o}:{}});s.optimizationLatencyHistogram&&s.optimizationLatencyHistogram.record(e,r),s.optimizationRequestsCounter&&s.optimizationRequestsCounter.add(1,r),!t&&s.optimizationErrorsCounter&&s.optimizationErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record optimization metric:",r)}},Fl=(s,e,t,n,o,r)=>{try{let i=ue({optimizer_type:r});s.convergenceRoundsHistogram&&s.convergenceRoundsHistogram.record(e,i),s.convergenceScoreGauge&&s.convergenceScoreGauge.record(t,i),s.convergenceImprovementGauge&&s.convergenceImprovementGauge.record(n,i),s.stagnationRoundsGauge&&s.stagnationRoundsGauge.record(o,i)}catch(i){console.warn("Failed to record convergence metric:",i)}},Dl=(s,e,t)=>{try{let n=ue({reason:e,optimizer_type:t});s.earlyStoppingCounter&&s.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},Gl=(s,e,t,n,o)=>{try{let r=ue({optimizer_type:n});s.tokenUsageCounter&&s.tokenUsageCounter.add(e,r),s.costUsageCounter&&s.costUsageCounter.add(t,r),o!==void 0&&s.memoryUsageGauge&&s.memoryUsageGauge.record(o,r)}catch(r){console.warn("Failed to record resource usage metric:",r)}},Ll=(s,e,t)=>{try{let n=ue({optimizer_type:t});s.optimizationDurationHistogram&&s.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},Nl=(s,e,t,n)=>{try{let o=ue({optimizer_type:n});s.teacherStudentUsageCounter&&s.teacherStudentUsageCounter.add(1,o),s.teacherStudentLatencyHistogram&&s.teacherStudentLatencyHistogram.record(e,o),s.teacherStudentScoreImprovementGauge&&s.teacherStudentScoreImprovementGauge.record(t,o)}catch(o){console.warn("Failed to record teacher-student metric:",o)}},Ul=(s,e,t,n,o)=>{try{let r=ue({operation:e,success:n.toString(),optimizer_type:o});e==="save"?(s.checkpointSaveCounter&&s.checkpointSaveCounter.add(1,r),s.checkpointSaveLatencyHistogram&&s.checkpointSaveLatencyHistogram.record(t,r)):(s.checkpointLoadCounter&&s.checkpointLoadCounter.add(1,r),s.checkpointLoadLatencyHistogram&&s.checkpointLoadLatencyHistogram.record(t,r))}catch(r){console.warn("Failed to record checkpoint metric:",r)}},$l=(s,e,t,n,o)=>{try{let r=ue({optimizer_type:n});s.paretoOptimizationsCounter&&s.paretoOptimizationsCounter.add(1,r),s.paretoFrontSizeHistogram&&s.paretoFrontSizeHistogram.record(e,r),o!==void 0&&s.paretoHypervolumeGauge&&s.paretoHypervolumeGauge.record(o,r),s.paretoSolutionsGeneratedHistogram&&s.paretoSolutionsGeneratedHistogram.record(t,r)}catch(r){console.warn("Failed to record Pareto metric:",r)}},Bl=(s,e,t,n,o,r)=>{try{let i=ue({optimizer_type:r});s.programInputFieldsGauge&&s.programInputFieldsGauge.record(e,i),s.programOutputFieldsGauge&&s.programOutputFieldsGauge.record(t,i),s.examplesCountGauge&&s.examplesCountGauge.record(n,i),s.validationSetSizeGauge&&s.validationSetSizeGauge.record(o,i)}catch(i){console.warn("Failed to record program complexity metric:",i)}},ql=(s,e,t,n)=>{try{let o=ue({metric_type:e,optimizer_type:n});switch(e){case"evaluation":s.evaluationLatencyHistogram&&s.evaluationLatencyHistogram.record(t,o);break;case"demo_generation":s.demoGenerationLatencyHistogram&&s.demoGenerationLatencyHistogram.record(t,o);break;case"metric_computation":s.metricComputationLatencyHistogram&&s.metricComputationLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record optimizer performance metric:",o)}},zl=(s,e,t,n)=>{try{let o=ue({optimizer_type:e});s.optimizerTypeGauge&&s.optimizerTypeGauge.record(1,o),t!==void 0&&s.targetScoreGauge&&s.targetScoreGauge.record(t,o),n!==void 0&&s.maxRoundsGauge&&s.maxRoundsGauge.record(n,o)}catch(o){console.warn("Failed to record optimizer configuration metric:",o)}},Kt=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let o=this.costPerModel[t]||.001;e+=n/1e3*o}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},Me=class{studentAI;teacherAI;examples;validationSet;targetScore;minSuccessRate;onProgress;onEarlyStop;costTracker;seed;checkpointSave;checkpointLoad;checkpointInterval;resumeFromCheckpoint;logger;verbose;debugOptimizer;optimizerLogger;currentRound=0;scoreHistory=[];configurationHistory=[];stats;metricsInstruments;constructor(e){if(e.examples.length===0)throw new Error("No examples found");this.studentAI=e.studentAI,this.teacherAI=e.teacherAI,this.examples=e.examples,this.validationSet=e.validationSet,this.targetScore=e.targetScore,this.minSuccessRate=e.minSuccessRate,this.onProgress=e.onProgress,this.onEarlyStop=e.onEarlyStop,this.seed=e.seed,this.checkpointSave=e.checkpointSave,this.checkpointLoad=e.checkpointLoad,this.checkpointInterval=e.checkpointInterval??10,this.resumeFromCheckpoint=e.resumeFromCheckpoint,this.logger=e.logger,this.verbose=e.verbose;let t=new Kt({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=El(B.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}getValidationSet(e){return e?.overrideValidationSet||this.validationSet||this.examples.slice(0,Math.floor(this.examples.length*.2))}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let o=this.getAIService(t,n);return await e(o)}async*compileStream(e,t,n){let o=Date.now(),r=this.constructor.name,i=e.getSignature().toString();this.recordOptimizationStart(r,i);let a,l=(m,g,h,f,A,x,y,O={},b)=>{this.getOptimizerLogger(b)?.({name:"RoundProgress",value:{round:m,totalRounds:b?.maxIterations??0,currentScore:g,bestScore:x,configuration:h}}),this.updateOptimizationProgress(m,g,h,f,A,x,y,O,b)},c=(m,g)=>{a=m,this.triggerEarlyStopping(m,this.currentRound)},p=m=>{this.onProgress?.(m),l(m.round,m.currentScore,m.currentConfiguration||{},r,{},m.bestScore,m.bestConfiguration,m.convergenceInfo,n)},d=await this.compile(e,t,{...n,overrideOnProgress:p,overrideOnEarlyStop:c}),u=Date.now()-o;return this.recordOptimizationComplete(u,!0,r,i),a&&this.getLogger(n)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${a}`}),{demos:d.demos,stats:d.stats,bestScore:d.bestScore,finalConfiguration:d.finalConfiguration,scoreHistory:d.scoreHistory,configurationHistory:d.configurationHistory}}async compilePareto(e,t,n){let o=this.constructor.name,r=Date.now(),i=await this.generateWeightedSolutions(e,t,n),a=await this.generateConstraintSolutions(e,t,n),l=[...i,...a],c=this.findParetoFrontier(l),p=this.calculateHypervolume(c);this.updateResourceUsage(r),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(c.length,l.length,"base_optimizer",p);let d=c.length>0?Math.max(...c.map(u=>Math.max(...Object.values(u.scores)))):0;return{demos:c.length>0?[...c[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:c,hypervolume:p,paretoFrontSize:c.length,finalConfiguration:{paretoFrontSize:c.length,hypervolume:p,strategy:"weighted_combinations_and_constraints",numSolutions:l.length}}}async generateWeightedSolutions(e,t,n){let o=[],r=this.examples[0],i=await e.forward(this.getAIService(!1,n),r),a=await t({prediction:i,example:r}),l=Object.keys(a),c=this.generateWeightCombinations(l);for(let p=0;p<c.length;p++){let d=c[p],u=async({prediction:m,example:g})=>{let h=await t({prediction:m,example:g}),f=0;for(let[A,x]of Object.entries(h))f+=x*(d[A]||0);return f};try{let m=await this.compile(e,u,{...n,verbose:!1}),g=await this.evaluateWithMultiObjective(e,m,t);o.push({scores:g,demos:m.demos,configuration:{...m.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return o}async generateConstraintSolutions(e,t,n){let o=[],r=this.examples[0],i=await e.forward(this.getAIService(!1,n),r),a=await t({prediction:i,example:r}),l=Object.keys(a);for(let c of l){let p=async({prediction:d,example:u})=>{let m=await t({prediction:d,example:u}),g=m[c]||0,h=0;for(let[f,A]of Object.entries(m))f!==c&&A<.3&&(h+=(.3-A)*2);return g-h};try{let d=await this.compile(e,p,{...n,verbose:!1}),u=await this.evaluateWithMultiObjective(e,d,t);o.push({scores:u,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:c,strategy:"constraint_based"}})}catch{}}return o}generateWeightCombinations(e){let t=[];for(let o of e){let r={};for(let i of e)r[i]=i===o?1:0;t.push(r)}let n={};for(let o of e)n[o]=1/e.length;if(t.push(n),e.length===2){let[o,r]=e;for(let i=.1;i<=.9;i+=.2){let a=1-i;t.push({[o]:i,[r]:a})}}if(e.length===3){let[o,r,i]=e;t.push({[o]:.5,[r]:.3,[i]:.2},{[o]:.3,[r]:.5,[i]:.2},{[o]:.2,[r]:.3,[i]:.5})}return t}async evaluateWithMultiObjective(e,t,n){let o=new j(e.getSignature());t.demos&&o.setDemos(t.demos);let r=[];for(let p of this.examples){let d=await o.forward(this.studentAI,p);r.push({prediction:d,example:p})}let i=this.getValidationSet(),a={},l=i.slice(0,Math.min(5,i.length));for(let p of l)try{let d=await o.forward(this.studentAI,p),u=await n({prediction:d,example:p});for(let[m,g]of Object.entries(u))a[m]||(a[m]=[]),a[m].push(g)}catch{}let c={};for(let[p,d]of Object.entries(a))c[p]=d.length>0?d.reduce((u,m)=>u+m,0)/d.length:0;return c}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n],r=!1,i=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,o.scores)){r=!0;break}this.dominates(o.scores,l.scores)&&i++}r||t.push({demos:o.demos||[],scores:o.scores,configuration:o.configuration,dominatedSolutions:i})}return t}dominates(e,t){let n=Object.keys(e),o=!0,r=!1;for(let i of n){let a=e[i]||0,l=t[i]||0;if(a<l){o=!1;break}a>l&&(r=!0)}return o&&r}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[o,r]=n,i=0,a=[...e].sort((c,p)=>(p.scores[o]||0)-(c.scores[o]||0)),l=0;for(let c of a){let p=c.scores[o]||0,d=c.scores[r]||0;i+=p*(d-l),l=Math.max(l,d)}return i}}async saveCheckpoint(e,t,n,o,r={},i){let a=i?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),c=!1,p;try{let d={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:o,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:r,examples:this.examples,validationSet:this.validationSet};p=await a(d),c=!0}catch(d){throw c=!1,d}finally{let d=Date.now()-l;this.recordCheckpointMetrics("save",d,c,e)}return p}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let o=Date.now(),r=!1,i=null;try{i=await n(e),r=i!==null}catch(a){throw r=!1,a}finally{let a=Date.now()-o;this.recordCheckpointMetrics("load",a,r,"unknown")}return i}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=t?.overrideCheckpointInterval||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,o,r,i,a,l={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(o,r,i,a,l,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:i,configuration:n}})}async saveFinalCheckpoint(e,t,n,o,r={},i){i?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,o,{...r,final:!0},i)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:this.studentAI.getLogger()}isLoggingEnabled(e){return e?.verbose!==void 0?e.verbose:this.verbose??!0}recordOptimizationStart(e,t){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,o=(t.match(/output:/g)||[]).length;Bl(this.metricsInstruments,n,o,this.examples.length,this.getValidationSet().length,e)}zl(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,o){if(!this.metricsInstruments)return;Pl(this.metricsInstruments,e,t,n,o),Ll(this.metricsInstruments,e,n);let r=this.costTracker?.getCurrentCost()??0,i=this.costTracker?.getTotalTokens()??0;Gl(this.metricsInstruments,i,r,n)}recordConvergenceMetrics(e,t,n,o,r){this.metricsInstruments&&Fl(this.metricsInstruments,e,t,n,o,r)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&Dl(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&Nl(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,o){this.metricsInstruments&&Ul(this.metricsInstruments,e,t,n,o)}recordParetoMetrics(e,t,n,o){this.metricsInstruments&&$l(this.metricsInstruments,e,t,n,o)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&ql(this.metricsInstruments,e,t,n)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??B.optimizerLogger??Xn}getStats(){return{...this.stats}}reset(){this.stats=this.initializeStats(),this.costTracker?.reset(),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}};var mt=class extends Me{maxRounds;maxDemos;maxExamples;batchSize;earlyStoppingPatience;costMonitoring;maxTokensPerGeneration;verboseMode;debugMode;traces=[];constructor(e){super(e);let t=e.options||{};this.maxRounds=t.maxRounds??3,this.maxDemos=t.maxDemos??4,this.maxExamples=t.maxExamples??16,this.batchSize=t.batchSize??1,this.earlyStoppingPatience=t.earlyStoppingPatience??0,this.costMonitoring=t.costMonitoring??!1,this.maxTokensPerGeneration=t.maxTokensPerGeneration??0,this.verboseMode=t.verboseMode??!0,this.debugMode=t.debugMode??!1}async compileRound(e,t,n,o){let r=Date.now(),i=o?.maxDemos??this.maxDemos,a={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(a.modelConfig.max_tokens=this.maxTokensPerGeneration);let l=Hl(this.examples,this.maxExamples),c=this.traces.length;for(let p=0;p<l.length;p+=this.batchSize){p>0&&(a.modelConfig.temperature=.7+.001*p);let d=l.slice(p,p+this.batchSize);for(let u of d){if(!u)continue;let m=l.filter(f=>f!==u);e.setExamples(m);let g=this.getTeacherOrStudentAI();this.stats.totalCalls++;let h;try{h=await e.forward(g,u,a),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(u).length/4+JSON.stringify(h).length/4),await n({prediction:h,example:u})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch{h={}}if(this.traces.length>=i)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-c;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:d>0?t:0,patienceExhausted:!1,reason:"No improvement detected"};else if(d>0)this.stats.earlyStopping.bestScoreRound=t;else if(t-this.stats.earlyStopping.bestScoreRound>=this.earlyStoppingPatience){this.stats.earlyStopping.patienceExhausted=!0,this.stats.earlyStopped=!0,this.stats.earlyStopping.reason=`No improvement for ${this.earlyStoppingPatience} rounds`;return}}}async compile(e,t,n){let o=n?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let a=0;a<o&&(await this.compileRound(e,a,t,n),!this.stats.earlyStopped);a++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let r=jl(this.traces),i=0;return this.traces.length>0&&(i=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),{demos:r,stats:this.stats,bestScore:i,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:i}}}};function jl(s){let e=new Map;for(let n of s)if(e.has(n.programId)){let o=e.get(n.programId);o&&o.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,o)=>{t.push({traces:n,programId:o})}),t}var Hl=(s,e)=>{let t=[...s];for(let n=t.length-1;n>0;n--){let o=Math.floor(Math.random()*(n+1)),r=t[n],i=t[o];if(!r||!i)throw new Error("Invalid array elements");[t[n],t[o]]=[i,r]}return t.slice(0,e)};var no=class extends Me{maxBootstrappedDemos;maxLabeledDemos;numCandidates;initTemperature;numTrials;minibatch;minibatchSize;minibatchFullEvalSteps;programAwareProposer;dataAwareProposer;viewDataBatchSize;tipAwareProposer;fewshotAwareProposer;earlyStoppingTrials;minImprovementThreshold;bayesianOptimization;acquisitionFunction;explorationWeight;sampleCount;miproConfigHistory=[];surrogateModel=new Map;constructor(e){super(e);let t=e.options||{};this.numCandidates=t.numCandidates??5,this.initTemperature=t.initTemperature??.7,this.maxBootstrappedDemos=t.maxBootstrappedDemos??3,this.maxLabeledDemos=t.maxLabeledDemos??4,this.numTrials=t.numTrials??30,this.minibatch=t.minibatch??!0,this.minibatchSize=t.minibatchSize??25,this.minibatchFullEvalSteps=t.minibatchFullEvalSteps??10,this.programAwareProposer=t.programAwareProposer??!0,this.dataAwareProposer=t.dataAwareProposer??!0,this.viewDataBatchSize=t.viewDataBatchSize??10,this.tipAwareProposer=t.tipAwareProposer??!0,this.fewshotAwareProposer=t.fewshotAwareProposer??!0,this.earlyStoppingTrials=t.earlyStoppingTrials??5,this.minImprovementThreshold=t.minImprovementThreshold??.01,this.bayesianOptimization=t.bayesianOptimization??!1,this.acquisitionFunction=t.acquisitionFunction??"expected_improvement",this.explorationWeight=t.explorationWeight??.1,this.sampleCount=t.sampleCount??1,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}configureAuto(e){switch(e){case"light":this.numCandidates=3,this.numTrials=10,this.minibatch=!0,this.minibatchSize=20;break;case"medium":this.numCandidates=5,this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numCandidates=7,this.numTrials=30,this.minibatch=!0,this.minibatchSize=30;break}}generateTips(){return["Be very specific and detailed in your instructions.","Focus on step-by-step reasoning in your instructions.","Provide clear constraints and guidelines in your instructions.","Keep your instructions concise and to the point.","Emphasize accuracy and precision in your instructions.","Include examples of good outputs in your instructions.","Focus on handling edge cases in your instructions.","Explicitly outline the reasoning process in your instructions."]}async generateProgramSummary(e,t){let o=`
|
|
251
|
+
${e}`}s(n)}},gr=Yo();var Jo={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},hr,Xl=s=>{if(hr)return hr;if(s)return hr=Zl(s),hr};var fr=Jo,Aa=s=>{fr={...fr,...s}},xa=()=>({...fr}),Zl=s=>({optimizationLatencyHistogram:s.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:s.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:s.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:s.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:s.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:s.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:s.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:s.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:s.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:s.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:s.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:s.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:s.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:s.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:s.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:s.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:s.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:s.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:s.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:s.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:s.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:s.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:s.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:s.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:s.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:s.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:s.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:s.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:s.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:s.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:s.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),ge=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=fr.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},ep=(s,e,t,n,r)=>{try{let o=ge({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{}});s.optimizationLatencyHistogram&&s.optimizationLatencyHistogram.record(e,o),s.optimizationRequestsCounter&&s.optimizationRequestsCounter.add(1,o),!t&&s.optimizationErrorsCounter&&s.optimizationErrorsCounter.add(1,o)}catch(o){console.warn("Failed to record optimization metric:",o)}},tp=(s,e,t,n,r,o)=>{try{let i=ge({optimizer_type:o});s.convergenceRoundsHistogram&&s.convergenceRoundsHistogram.record(e,i),s.convergenceScoreGauge&&s.convergenceScoreGauge.record(t,i),s.convergenceImprovementGauge&&s.convergenceImprovementGauge.record(n,i),s.stagnationRoundsGauge&&s.stagnationRoundsGauge.record(r,i)}catch(i){console.warn("Failed to record convergence metric:",i)}},np=(s,e,t)=>{try{let n=ge({reason:e,optimizer_type:t});s.earlyStoppingCounter&&s.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},rp=(s,e,t,n,r)=>{try{let o=ge({optimizer_type:n});s.tokenUsageCounter&&s.tokenUsageCounter.add(e,o),s.costUsageCounter&&s.costUsageCounter.add(t,o),r!==void 0&&s.memoryUsageGauge&&s.memoryUsageGauge.record(r,o)}catch(o){console.warn("Failed to record resource usage metric:",o)}},op=(s,e,t)=>{try{let n=ge({optimizer_type:t});s.optimizationDurationHistogram&&s.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},sp=(s,e,t,n)=>{try{let r=ge({optimizer_type:n});s.teacherStudentUsageCounter&&s.teacherStudentUsageCounter.add(1,r),s.teacherStudentLatencyHistogram&&s.teacherStudentLatencyHistogram.record(e,r),s.teacherStudentScoreImprovementGauge&&s.teacherStudentScoreImprovementGauge.record(t,r)}catch(r){console.warn("Failed to record teacher-student metric:",r)}},ip=(s,e,t,n,r)=>{try{let o=ge({operation:e,success:n.toString(),optimizer_type:r});e==="save"?(s.checkpointSaveCounter&&s.checkpointSaveCounter.add(1,o),s.checkpointSaveLatencyHistogram&&s.checkpointSaveLatencyHistogram.record(t,o)):(s.checkpointLoadCounter&&s.checkpointLoadCounter.add(1,o),s.checkpointLoadLatencyHistogram&&s.checkpointLoadLatencyHistogram.record(t,o))}catch(o){console.warn("Failed to record checkpoint metric:",o)}},ap=(s,e,t,n,r)=>{try{let o=ge({optimizer_type:n});s.paretoOptimizationsCounter&&s.paretoOptimizationsCounter.add(1,o),s.paretoFrontSizeHistogram&&s.paretoFrontSizeHistogram.record(e,o),r!==void 0&&s.paretoHypervolumeGauge&&s.paretoHypervolumeGauge.record(r,o),s.paretoSolutionsGeneratedHistogram&&s.paretoSolutionsGeneratedHistogram.record(t,o)}catch(o){console.warn("Failed to record Pareto metric:",o)}},lp=(s,e,t,n,r,o)=>{try{let i=ge({optimizer_type:o});s.programInputFieldsGauge&&s.programInputFieldsGauge.record(e,i),s.programOutputFieldsGauge&&s.programOutputFieldsGauge.record(t,i),s.examplesCountGauge&&s.examplesCountGauge.record(n,i),s.validationSetSizeGauge&&s.validationSetSizeGauge.record(r,i)}catch(i){console.warn("Failed to record program complexity metric:",i)}},pp=(s,e,t,n)=>{try{let r=ge({metric_type:e,optimizer_type:n});switch(e){case"evaluation":s.evaluationLatencyHistogram&&s.evaluationLatencyHistogram.record(t,r);break;case"demo_generation":s.demoGenerationLatencyHistogram&&s.demoGenerationLatencyHistogram.record(t,r);break;case"metric_computation":s.metricComputationLatencyHistogram&&s.metricComputationLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record optimizer performance metric:",r)}},cp=(s,e,t,n)=>{try{let r=ge({optimizer_type:e});s.optimizerTypeGauge&&s.optimizerTypeGauge.record(1,r),t!==void 0&&s.targetScoreGauge&&s.targetScoreGauge.record(t,r),n!==void 0&&s.maxRoundsGauge&&s.maxRoundsGauge.record(n,r)}catch(r){console.warn("Failed to record optimizer configuration metric:",r)}},Zt=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let r=this.costPerModel[t]||.001;e+=n/1e3*r}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},Ee=class{studentAI;teacherAI;examples;validationSet;targetScore;minSuccessRate;onProgress;onEarlyStop;costTracker;seed;checkpointSave;checkpointLoad;checkpointInterval;resumeFromCheckpoint;logger;verbose;debugOptimizer;optimizerLogger;currentRound=0;scoreHistory=[];configurationHistory=[];stats;metricsInstruments;constructor(e){if(e.examples.length===0)throw new Error("No examples found");this.studentAI=e.studentAI,this.teacherAI=e.teacherAI,this.examples=e.examples,this.validationSet=e.validationSet,this.targetScore=e.targetScore,this.minSuccessRate=e.minSuccessRate,this.onProgress=e.onProgress,this.onEarlyStop=e.onEarlyStop,this.seed=e.seed,this.checkpointSave=e.checkpointSave,this.checkpointLoad=e.checkpointLoad,this.checkpointInterval=e.checkpointInterval??10,this.resumeFromCheckpoint=e.resumeFromCheckpoint,this.logger=e.logger,this.verbose=e.verbose;let t=new Zt({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=Xl(B.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}getValidationSet(e){return e?.overrideValidationSet||this.validationSet||this.examples.slice(0,Math.floor(this.examples.length*.2))}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let r=this.getAIService(t,n);return await e(r)}async*compileStream(e,t,n){let r=Date.now(),o=this.constructor.name,i=e.getSignature().toString();this.recordOptimizationStart(o,i);let a,l=(m,g,h,A,f,x,y,k={},b)=>{this.getOptimizerLogger(b)?.({name:"RoundProgress",value:{round:m,totalRounds:b?.maxIterations??0,currentScore:g,bestScore:x,configuration:h}}),this.updateOptimizationProgress(m,g,h,A,f,x,y,k,b)},p=(m,g)=>{a=m,this.triggerEarlyStopping(m,this.currentRound)},c=m=>{this.onProgress?.(m),l(m.round,m.currentScore,m.currentConfiguration||{},o,{},m.bestScore,m.bestConfiguration,m.convergenceInfo,n)},d=await this.compile(e,t,{...n,overrideOnProgress:c,overrideOnEarlyStop:p}),u=Date.now()-r;return this.recordOptimizationComplete(u,!0,o,i),a&&this.getLogger(n)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${a}`}),{demos:d.demos,stats:d.stats,bestScore:d.bestScore,finalConfiguration:d.finalConfiguration,scoreHistory:d.scoreHistory,configurationHistory:d.configurationHistory}}async compilePareto(e,t,n){let r=this.constructor.name,o=Date.now(),i=await this.generateWeightedSolutions(e,t,n),a=await this.generateConstraintSolutions(e,t,n),l=[...i,...a],p=this.findParetoFrontier(l),c=this.calculateHypervolume(p);this.updateResourceUsage(o),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(p.length,l.length,"base_optimizer",c);let d=p.length>0?Math.max(...p.map(u=>Math.max(...Object.values(u.scores)))):0;return{demos:p.length>0?[...p[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:p,hypervolume:c,paretoFrontSize:p.length,finalConfiguration:{paretoFrontSize:p.length,hypervolume:c,strategy:"weighted_combinations_and_constraints",numSolutions:l.length}}}async generateWeightedSolutions(e,t,n){let r=[],o=this.examples[0],i=await e.forward(this.getAIService(!1,n),o),a=await t({prediction:i,example:o}),l=Object.keys(a),p=this.generateWeightCombinations(l);for(let c=0;c<p.length;c++){let d=p[c],u=async({prediction:m,example:g})=>{let h=await t({prediction:m,example:g}),A=0;for(let[f,x]of Object.entries(h))A+=x*(d[f]||0);return A};try{let m=await this.compile(e,u,{...n,verbose:!1}),g=await this.evaluateWithMultiObjective(e,m,t);r.push({scores:g,demos:m.demos,configuration:{...m.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return r}async generateConstraintSolutions(e,t,n){let r=[],o=this.examples[0],i=await e.forward(this.getAIService(!1,n),o),a=await t({prediction:i,example:o}),l=Object.keys(a);for(let p of l){let c=async({prediction:d,example:u})=>{let m=await t({prediction:d,example:u}),g=m[p]||0,h=0;for(let[A,f]of Object.entries(m))A!==p&&f<.3&&(h+=(.3-f)*2);return g-h};try{let d=await this.compile(e,c,{...n,verbose:!1}),u=await this.evaluateWithMultiObjective(e,d,t);r.push({scores:u,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:p,strategy:"constraint_based"}})}catch{}}return r}generateWeightCombinations(e){let t=[];for(let r of e){let o={};for(let i of e)o[i]=i===r?1:0;t.push(o)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,o]=e;for(let i=.1;i<=.9;i+=.2){let a=1-i;t.push({[r]:i,[o]:a})}}if(e.length===3){let[r,o,i]=e;t.push({[r]:.5,[o]:.3,[i]:.2},{[r]:.3,[o]:.5,[i]:.2},{[r]:.2,[o]:.3,[i]:.5})}return t}async evaluateWithMultiObjective(e,t,n){let r=new ee(e.getSignature());t.demos&&r.setDemos(t.demos);let o=[];for(let c of this.examples){let d=await r.forward(this.studentAI,c);o.push({prediction:d,example:c})}let i=this.getValidationSet(),a={},l=i.slice(0,Math.min(5,i.length));for(let c of l)try{let d=await r.forward(this.studentAI,c),u=await n({prediction:d,example:c});for(let[m,g]of Object.entries(u))a[m]||(a[m]=[]),a[m].push(g)}catch{}let p={};for(let[c,d]of Object.entries(a))p[c]=d.length>0?d.reduce((u,m)=>u+m,0)/d.length:0;return p}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=!1,i=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,r.scores)){o=!0;break}this.dominates(r.scores,l.scores)&&i++}o||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:i})}return t}dominates(e,t){let n=Object.keys(e),r=!0,o=!1;for(let i of n){let a=e[i]||0,l=t[i]||0;if(a<l){r=!1;break}a>l&&(o=!0)}return r&&o}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,o]=n,i=0,a=[...e].sort((p,c)=>(c.scores[r]||0)-(p.scores[r]||0)),l=0;for(let p of a){let c=p.scores[r]||0,d=p.scores[o]||0;i+=c*(d-l),l=Math.max(l,d)}return i}}async saveCheckpoint(e,t,n,r,o={},i){let a=i?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),p=!1,c;try{let d={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:r,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:o,examples:this.examples,validationSet:this.validationSet};c=await a(d),p=!0}catch(d){throw p=!1,d}finally{let d=Date.now()-l;this.recordCheckpointMetrics("save",d,p,e)}return c}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),o=!1,i=null;try{i=await n(e),o=i!==null}catch(a){throw o=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,o,"unknown")}return i}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=t?.overrideCheckpointInterval||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,r,o,i,a,l={},p){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,p)&&await this.saveCheckpoint(r,o,i,a,l,p),this.getOptimizerLogger(p)?.({name:"RoundProgress",value:{round:e,totalRounds:p?.maxIterations??0,currentScore:t,bestScore:i,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,o={},i){i?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...o,final:!0},i)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:this.studentAI.getLogger()}isLoggingEnabled(e){return e?.verbose!==void 0?e.verbose:this.verbose??!0}recordOptimizationStart(e,t){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,r=(t.match(/output:/g)||[]).length;lp(this.metricsInstruments,n,r,this.examples.length,this.getValidationSet().length,e)}cp(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,r){if(!this.metricsInstruments)return;ep(this.metricsInstruments,e,t,n,r),op(this.metricsInstruments,e,n);let o=this.costTracker?.getCurrentCost()??0,i=this.costTracker?.getTotalTokens()??0;rp(this.metricsInstruments,i,o,n)}recordConvergenceMetrics(e,t,n,r,o){this.metricsInstruments&&tp(this.metricsInstruments,e,t,n,r,o)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&np(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&sp(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,r){this.metricsInstruments&&ip(this.metricsInstruments,e,t,n,r)}recordParetoMetrics(e,t,n,r){this.metricsInstruments&&ap(this.metricsInstruments,e,t,n,r)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&pp(this.metricsInstruments,e,t,n)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??B.optimizerLogger??gr}getStats(){return{...this.stats}}reset(){this.stats=this.initializeStats(),this.costTracker?.reset(),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}};var At=class extends Ee{maxRounds;maxDemos;maxExamples;batchSize;earlyStoppingPatience;costMonitoring;maxTokensPerGeneration;verboseMode;debugMode;traces=[];constructor(e){super(e);let t=e.options||{};this.maxRounds=t.maxRounds??3,this.maxDemos=t.maxDemos??4,this.maxExamples=t.maxExamples??16,this.batchSize=t.batchSize??1,this.earlyStoppingPatience=t.earlyStoppingPatience??0,this.costMonitoring=t.costMonitoring??!1,this.maxTokensPerGeneration=t.maxTokensPerGeneration??0,this.verboseMode=t.verboseMode??!0,this.debugMode=t.debugMode??!1}async compileRound(e,t,n,r){let o=Date.now(),i=r?.maxDemos??this.maxDemos,a={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(a.modelConfig.max_tokens=this.maxTokensPerGeneration);let l=dp(this.examples,this.maxExamples),p=this.traces.length;for(let c=0;c<l.length;c+=this.batchSize){c>0&&(a.modelConfig.temperature=.7+.001*c);let d=l.slice(c,c+this.batchSize);for(let u of d){if(!u)continue;let m=l.filter(A=>A!==u);e.setExamples(m);let g=this.getTeacherOrStudentAI();this.stats.totalCalls++;let h;try{let A={...a,maxRetries:1};h=await e.forward(g,u,A),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(u).length/4+JSON.stringify(h).length/4),await n({prediction:h,example:u})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(A){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${A instanceof Error?A.message:"Unknown error"}`),h={}}if(this.traces.length>=i)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-p;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:d>0?t:0,patienceExhausted:!1,reason:"No improvement detected"};else if(d>0)this.stats.earlyStopping.bestScoreRound=t;else if(t-this.stats.earlyStopping.bestScoreRound>=this.earlyStoppingPatience){this.stats.earlyStopping.patienceExhausted=!0,this.stats.earlyStopped=!0,this.stats.earlyStopping.reason=`No improvement for ${this.earlyStoppingPatience} rounds`;return}}}async compile(e,t,n){let r=n?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let a=0;a<r&&(await this.compileRound(e,a,t,n),!this.stats.earlyStopped);a++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let o=up(this.traces),i=0;return this.traces.length>0&&(i=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),{demos:o,stats:this.stats,bestScore:i,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:i}}}};function up(s){let e=new Map;for(let n of s)if(e.has(n.programId)){let r=e.get(n.programId);r&&r.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,r)=>{t.push({traces:n,programId:r})}),t}var dp=(s,e)=>{let t=[...s];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),o=t[n],i=t[r];if(!o||!i)throw new Error("Invalid array elements");[t[n],t[r]]=[i,o]}return t.slice(0,e)};var Ar=class{endpoint;timeout;retryAttempts;retryDelay;logger;constructor(e){this.endpoint=e.endpoint.replace(/\/$/,""),this.timeout=e.timeout??3e4,this.retryAttempts=e.retryAttempts??3,this.retryDelay=e.retryDelay??1e3,this.logger=e.logger}async healthCheck(){try{return(await this.fetchWithRetry("/health",{method:"GET"})).ok}catch(e){return this.logger?.({name:"Notification",id:"health_check_failed",value:`Health check failed: ${e}`}),!1}}async createOptimizationJob(e){let t=await this.fetchWithRetry("/optimize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to create optimization job: ${n}`)}return t.json()}async getJobStatus(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get job status: ${n}`)}return t.json()}async cancelJob(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to cancel job: ${n}`)}}async suggestParameters(e){let t=await this.fetchWithRetry(`/studies/${e}/suggest`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to suggest parameters: ${n}`)}return t.json()}async evaluateTrial(e){let t=await this.fetchWithRetry(`/studies/${e.study_name}/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to evaluate trial: ${n}`)}}async getStudyResults(e){let t=await this.fetchWithRetry(`/studies/${e}/results`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get study results: ${n}`)}return t.json()}async deleteStudy(e){let t=await this.fetchWithRetry(`/studies/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to delete study: ${n}`)}}async listStudies(){let e=await this.fetchWithRetry("/studies",{method:"GET"});if(!e.ok){let t=await e.text();throw new Error(`Failed to list studies: ${t}`)}return e.json()}async waitForJobCompletion(e,t=2e3,n=3e5){let r=Date.now();for(;Date.now()-r<n;){let o=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(o.status))return o;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${o.status}, waiting...`}),await this.sleep(t)}throw new Error(`Job ${e} did not complete within ${n}ms`)}async fetchWithRetry(e,t){let n=`${this.endpoint}${e}`,r=null;for(let o=0;o<this.retryAttempts;o++)try{let i=new AbortController,a=setTimeout(()=>i.abort(),this.timeout),l=await fetch(n,{...t,signal:i.signal});return clearTimeout(a),l}catch(i){r=i,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${o+1} failed: ${i}`}),o<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,o))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${r?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var xr=class extends Ee{maxBootstrappedDemos;maxLabeledDemos;numCandidates;initTemperature;numTrials;minibatch;minibatchSize;minibatchFullEvalSteps;programAwareProposer;dataAwareProposer;viewDataBatchSize;tipAwareProposer;fewshotAwareProposer;earlyStoppingTrials;minImprovementThreshold;bayesianOptimization;acquisitionFunction;explorationWeight;sampleCount;miproConfigHistory=[];surrogateModel=new Map;pythonClient;constructor(e){if(super(e),this.numCandidates=e.numCandidates??5,this.initTemperature=e.initTemperature??.7,this.maxBootstrappedDemos=e.maxBootstrappedDemos??3,this.maxLabeledDemos=e.maxLabeledDemos??4,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??25,this.minibatchFullEvalSteps=e.minibatchFullEvalSteps??10,this.programAwareProposer=e.programAwareProposer??!0,this.dataAwareProposer=e.dataAwareProposer??!0,this.viewDataBatchSize=e.viewDataBatchSize??10,this.tipAwareProposer=e.tipAwareProposer??!0,this.fewshotAwareProposer=e.fewshotAwareProposer??!0,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??.01,this.bayesianOptimization=e.bayesianOptimization??!1,this.acquisitionFunction=e.acquisitionFunction??"expected_improvement",this.explorationWeight=e.explorationWeight??.1,this.sampleCount=e.sampleCount??1,e.optimizerEndpoint){let t={endpoint:e.optimizerEndpoint,timeout:e.optimizerTimeout??3e4,retryAttempts:e.optimizerRetries??3,logger:n=>{this.logger?.({name:"Notification",id:"python_client",value:typeof n=="string"?n:JSON.stringify(n)})}};this.pythonClient=new Ar(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}configureAuto(e){switch(e){case"light":this.numCandidates=3,this.numTrials=10,this.minibatch=!0,this.minibatchSize=20;break;case"medium":this.numCandidates=5,this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numCandidates=7,this.numTrials=30,this.minibatch=!0,this.minibatchSize=30;break}}generateTips(){return["Be very specific and detailed in your instructions.","Focus on step-by-step reasoning in your instructions.","Provide clear constraints and guidelines in your instructions.","Keep your instructions concise and to the point.","Emphasize accuracy and precision in your instructions.","Include examples of good outputs in your instructions.","Focus on handling edge cases in your instructions.","Explicitly outline the reasoning process in your instructions."]}async generateProgramSummary(e,t){let r=`
|
|
250
252
|
Analyze this language model program and provide a concise summary of its purpose and structure.
|
|
251
253
|
|
|
252
254
|
Program Signature: ${e.getSignature()}
|
|
@@ -256,7 +258,7 @@ Provide a 2-3 sentence summary focusing on:
|
|
|
256
258
|
2. The input-output relationship
|
|
257
259
|
3. Any special constraints or requirements
|
|
258
260
|
|
|
259
|
-
Summary:`;try{let
|
|
261
|
+
Summary:`;try{let o=await t.chat({chatPrompt:[{role:"user",content:r}]});return"results"in o&&o.results[0]?.content?.trim()||"General language model program"}catch{return"General language model program"}}async generateDatasetSummary(e,t){if(e.length===0)return"No examples available";let n=Math.min(this.viewDataBatchSize,e.length),i=`
|
|
260
262
|
Analyze this dataset and provide a concise summary of its characteristics.
|
|
261
263
|
|
|
262
264
|
Sample Examples:
|
|
@@ -268,9 +270,9 @@ Provide a 2-3 sentence summary focusing on:
|
|
|
268
270
|
2. Common patterns or structures in the examples
|
|
269
271
|
3. Key challenges or requirements for processing this data
|
|
270
272
|
|
|
271
|
-
Dataset Summary:`;try{let a=await t.chat({chatPrompt:[{role:"user",content:i}]});return"results"in a&&a.results[0]?.content?.trim()||"General dataset"}catch{return"General dataset"}}async generateInstruction({tip:e,candidateIndex:t,ai:n,programSummary:
|
|
272
|
-
Program Context: ${
|
|
273
|
-
Dataset Context: ${
|
|
273
|
+
Dataset Summary:`;try{let a=await t.chat({chatPrompt:[{role:"user",content:i}]});return"results"in a&&a.results[0]?.content?.trim()||"General dataset"}catch{return"General dataset"}}async generateInstruction({tip:e,candidateIndex:t,ai:n,programSummary:r,datasetSummary:o,previousInstructions:i=[]}){let a="";this.programAwareProposer&&r&&(a+=`
|
|
274
|
+
Program Context: ${r}`),this.dataAwareProposer&&o&&(a+=`
|
|
275
|
+
Dataset Context: ${o}`),this.fewshotAwareProposer&&i.length>0&&(a+=`
|
|
274
276
|
Previous Instructions (avoid repeating): ${i.slice(-3).join("; ")}`);let l=`
|
|
275
277
|
Generate a high-quality instruction for a language model program.
|
|
276
278
|
|
|
@@ -286,8 +288,88 @@ Requirements:
|
|
|
286
288
|
5. Keep it concise but comprehensive
|
|
287
289
|
|
|
288
290
|
Generate a single, well-crafted instruction:
|
|
289
|
-
Instruction:`;try{let d=await n.chat({chatPrompt:[{role:"user",content:l}]});if("results"in d){let u=d.results[0]?.content?.trim();if(u&&u.length>10)return u}}catch{}let c=["Analyze the input systematically and provide a precise, well-reasoned response.","Think through this step-by-step, considering all relevant factors before responding.","Examine the input carefully and generate an accurate, detailed answer.","Process the information methodically and deliver a clear, comprehensive response.","Consider the context thoroughly and provide a thoughtful, accurate answer."],p=c[t%c.length]||c[0];return e&&(p=`${p} ${e}`),p}async proposeInstructionCandidates(e,t){let n=[],o=this.getTeacherOrStudentAI(t),r,i;this.dataAwareProposer&&(i=await this.generateDatasetSummary(this.examples,o));let a=this.tipAwareProposer?this.generateTips():[];for(let l=0;l<this.numCandidates;l++){let c=a.length>0?l%a.length:-1,p=c>=0?a[c]:void 0,d=await this.generateInstruction({tip:p,candidateIndex:l,ai:o,programSummary:r,datasetSummary:i,previousInstructions:n});n.push(d)}return n}async bootstrapFewShotExamples(e,t){return(await new mt({studentAI:this.studentAI,examples:this.examples,options:{maxDemos:this.maxBootstrappedDemos,maxRounds:3,verboseMode:this.isLoggingEnabled()}}).compile(e,t,{maxDemos:this.maxBootstrappedDemos})).demos||[]}selectLabeledExamples(){let e=[],t=new Set;for(;t.size<this.maxLabeledDemos&&t.size<this.examples.length;){let n=Math.floor(Math.random()*this.examples.length);if(!t.has(n)){t.add(n);let o=this.examples[n];o&&e.push(o)}}return e}async runOptimization(e,t,n,o,r,i,a){let l={instruction:o[0]||"",bootstrappedDemos:Math.min(1,t.length),labeledExamples:Math.min(1,n.length)},c=0,p=0,d=[],u=0;if(this.resumeFromCheckpoint){let m=await this.loadCheckpoint(this.resumeFromCheckpoint,a);m&&m.optimizerType==="MiPRO"&&(this.restoreFromCheckpoint(m),u=m.currentRound,c=m.bestScore,l=m.bestConfiguration||l,p=m.stats.convergenceInfo?.stagnationRounds||0)}for(let m=u;m<this.numTrials;m++){let g;this.bayesianOptimization&&this.miproConfigHistory.length>2?g=await this.selectConfigurationViaBayesianOptimization(o,t,n):g={instruction:o[m%o.length]||o[0]||"",bootstrappedDemos:Math.min(Math.floor(Math.random()*(t.length+1)),this.maxBootstrappedDemos),labeledExamples:Math.min(Math.floor(Math.random()*(n.length+1)),this.maxLabeledDemos)};let h=await this.evaluateConfig(e,g,t,n,r,i,m+1);this.updateSurrogateModel(g,h),d.push(h);let f=h-c;if(f>this.minImprovementThreshold?(c=h,l=g,p=0):p++,await this.updateOptimizationProgress(m+1,h,g,"MiPRO",this.getConfiguration(),c,l,{stagnationRounds:p,bootstrappedDemos:t.length,labeledExamples:n.length,instructions:o.length},a),this.onProgress&&this.onProgress({round:m+1,totalRounds:this.numTrials,currentScore:h,bestScore:c,tokensUsed:this.stats.resourceUsage.totalTokens,timeElapsed:Date.now(),successfulExamples:this.stats.successfulDemos,totalExamples:this.examples.length,currentConfiguration:g,convergenceInfo:{improvement:f,stagnationRounds:p,isConverging:p<this.earlyStoppingTrials}}),this.checkCostLimits()){this.triggerEarlyStopping("Cost limit reached",m+1);break}if(p>=this.earlyStoppingTrials){this.triggerEarlyStopping(`No improvement for ${this.earlyStoppingTrials} trials`,m-p+1);break}if(this.checkTargetScore(c)){this.triggerEarlyStopping(`Target score ${this.targetScore} reached`,m+1);break}}return this.stats.convergenceInfo.stagnationRounds=p,this.stats.convergenceInfo.finalImprovement=d.length>1?c-d[0]:0,this.stats.convergenceInfo.converged=p<this.earlyStoppingTrials,{bestConfig:l,bestScore:c}}async evaluateConfig(e,t,n,o,r,i,a=0){let l=new j(e.getSignature());this.applyConfigToProgram(l,t,n,o);let c=0,p=0,d;if(this.minibatch){let g=Math.min(this.minibatchSize,r.length);a%this.minibatchFullEvalSteps===0||a>this.numTrials*.8?d=Math.min(r.length,g*2):d=Math.max(3,Math.min(g,r.length))}else d=r.length;let m=this.shuffleArray([...Array(r.length).keys()]).slice(0,d).map(g=>r[g]);for(let g of m)try{let h=await l.forward(this.studentAI,g,this.sampleCount>1?{sampleCount:this.sampleCount,resultPicker:Kl()}:void 0),f=await i({prediction:h,example:g});c+=f,p++,this.stats.totalCalls++}catch{}return p>0?c/p:0}shuffleArray(e){let t=[...e];for(let n=t.length-1;n>0;n--){let o=Math.floor(Math.random()*(n+1));[t[n],t[o]]=[t[o],t[n]]}return t}applyConfigToProgram(e,t,n,o){e.setInstruction&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples&&e.setExamples(o.slice(0,t.labeledExamples))}async compile(e,t,n){let o=Date.now();this.setupRandomSeed();let r=n;r?.auto&&this.configureAuto(r.auto);let i=this.getValidationSet(n)||(r?.validationExamples??this.examples.slice(0,Math.floor(this.examples.length*.2))),a=[];this.maxBootstrappedDemos>0&&(a=await this.bootstrapFewShotExamples(e,t));let l=[];this.maxLabeledDemos>0&&(l=this.selectLabeledExamples());let c=await this.proposeInstructionCandidates(e,n),{bestConfig:p,bestScore:d}=await this.runOptimization(e,a,l,c,i,t,n);this.checkTargetScore(d)&&this.triggerEarlyStopping(`Target score ${this.targetScore} reached with score ${d}`,this.numTrials);let u;"getSignature"in e&&typeof e.getSignature=="function"?u=e.getSignature():u="input -> output";let m=new j(u);return this.applyConfigToAxGen(m,p,a,l),this.updateResourceUsage(o),this.stats.convergenceInfo.converged=!0,this.stats.convergenceInfo.finalImprovement=d,await this.saveFinalCheckpoint("MiPRO",this.getConfiguration(),d,p,{bootstrappedDemos:a.length,labeledExamples:l.length,instructions:c.length,optimizedGen:!!m},n),{demos:a,stats:this.stats,bestScore:d,optimizedGen:m,finalConfiguration:{instruction:p.instruction,bootstrappedDemos:p.bootstrappedDemos,labeledExamples:p.labeledExamples,numCandidates:this.numCandidates,numTrials:this.numTrials,sampleCount:this.sampleCount}}}applyConfigToAxGen(e,t,n,o){"setInstruction"in e&&typeof e.setInstruction=="function"&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples(o.slice(0,t.labeledExamples))}getConfiguration(){return{numCandidates:this.numCandidates,initTemperature:this.initTemperature,maxBootstrappedDemos:this.maxBootstrappedDemos,maxLabeledDemos:this.maxLabeledDemos,numTrials:this.numTrials,minibatch:this.minibatch,minibatchSize:this.minibatchSize,minibatchFullEvalSteps:this.minibatchFullEvalSteps,programAwareProposer:this.programAwareProposer,dataAwareProposer:this.dataAwareProposer,tipAwareProposer:this.tipAwareProposer,fewshotAwareProposer:this.fewshotAwareProposer,earlyStoppingTrials:this.earlyStoppingTrials,minImprovementThreshold:this.minImprovementThreshold,bayesianOptimization:this.bayesianOptimization,acquisitionFunction:this.acquisitionFunction,explorationWeight:this.explorationWeight,sampleCount:this.sampleCount}}updateConfiguration(e){e.numCandidates!==void 0&&(this.numCandidates=e.numCandidates),e.initTemperature!==void 0&&(this.initTemperature=e.initTemperature),e.maxBootstrappedDemos!==void 0&&(this.maxBootstrappedDemos=e.maxBootstrappedDemos),e.maxLabeledDemos!==void 0&&(this.maxLabeledDemos=e.maxLabeledDemos),e.numTrials!==void 0&&(this.numTrials=e.numTrials),e.minibatch!==void 0&&(this.minibatch=e.minibatch),e.minibatchSize!==void 0&&(this.minibatchSize=e.minibatchSize),e.earlyStoppingTrials!==void 0&&(this.earlyStoppingTrials=e.earlyStoppingTrials),e.minImprovementThreshold!==void 0&&(this.minImprovementThreshold=e.minImprovementThreshold),e.sampleCount!==void 0&&(this.sampleCount=e.sampleCount)}reset(){super.reset(),this.miproConfigHistory=[],this.surrogateModel.clear(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}validateProgram(e){let t=[],n=[];return this.examples.length<this.maxBootstrappedDemos+this.maxLabeledDemos&&(t.push(`Not enough examples: need at least ${this.maxBootstrappedDemos+this.maxLabeledDemos}, got ${this.examples.length}`),n.push("Reduce maxBootstrappedDemos or maxLabeledDemos, or provide more examples")),this.getValidationSet().length<5&&(t.push("Validation set too small for reliable MiPRO optimization"),n.push("Provide more examples or a larger validation set")),{isValid:t.length===0,issues:t,suggestions:n}}encodeConfiguration(e){return`${e.instruction.length}_${e.bootstrappedDemos}_${e.labeledExamples}`}updateSurrogateModel(e,t){this.miproConfigHistory.push({config:{...e},score:t});let n=this.encodeConfiguration(e),o=this.miproConfigHistory.filter(r=>this.encodeConfiguration(r.config)===n);if(o.length>0){let r=o.map(l=>l.score),i=r.reduce((l,c)=>l+c,0)/r.length,a=r.length>1?r.reduce((l,c)=>l+(c-i)**2,0)/(r.length-1):.1;this.surrogateModel.set(n,{mean:i,variance:a})}}predictPerformance(e){let t=this.encodeConfiguration(e);if(this.surrogateModel.has(t))return this.surrogateModel.get(t);if(this.miproConfigHistory.length>0){let n=this.miproConfigHistory.map(i=>{let a=Math.abs(i.config.bootstrappedDemos-e.bootstrappedDemos)+Math.abs(i.config.labeledExamples-e.labeledExamples);return{score:i.score,similarity:1/(1+a)}}),o=n.reduce((i,a)=>i+a.similarity,0);return{mean:n.reduce((i,a)=>i+a.score*a.similarity,0)/o,variance:.2}}return{mean:.5,variance:.3}}calculateAcquisitionValue(e){let t=this.predictPerformance(e),{mean:n,variance:o}=t,r=Math.sqrt(o),i=this.miproConfigHistory.length>0?Math.max(...this.miproConfigHistory.map(a=>a.score)):0;switch(this.acquisitionFunction){case"expected_improvement":{let a=n-i;if(r===0)return Math.max(0,a);let l=a/r,c=.5*(1+this.erf(l/Math.sqrt(2))),p=Math.exp(-.5*l*l)/Math.sqrt(2*Math.PI);return a*c+r*p}case"upper_confidence_bound":return n+this.explorationWeight*r;case"probability_improvement":{let a=n-i;if(r===0)return a>0?1:0;let l=a/r;return .5*(1+this.erf(l/Math.sqrt(2)))}default:return n}}erf(e){let t=.254829592,n=-.284496736,o=1.421413741,r=-1.453152027,i=1.061405429,a=.3275911,l=e>=0?1:-1,c=Math.abs(e),p=1/(1+a*c),d=1-((((i*p+r)*p+o)*p+n)*p+t)*p*Math.exp(-c*c);return l*d}async selectConfigurationViaBayesianOptimization(e,t,n){let o=[],r=Math.min(20,e.length*3);for(let i=0;i<r;i++){let a={instruction:e[i%e.length]||e[0]||"",bootstrappedDemos:Math.min(Math.floor(Math.random()*(t.length+1)),this.maxBootstrappedDemos),labeledExamples:Math.min(Math.floor(Math.random()*(n.length+1)),this.maxLabeledDemos)},l=this.calculateAcquisitionValue(a);o.push({config:a,acquisitionValue:l})}return o.sort((i,a)=>a.acquisitionValue-i.acquisitionValue),o[0].config}},Kl=()=>async s=>{if(s.type==="fields"){let e={};for(let{index:o,sample:r}of s.results){let i=JSON.stringify(r);e[i]||(e[i]={count:0,index:o}),e[i].count+=1}let t,n=-1;for(let[o,r]of Object.entries(e))r.count>n&&(n=r.count,t=o);return e[t]?.index??0}return s.results[0]?.index??0};function ea(s,...e){let t="";for(let n=0;n<s.length;n++)if(t+=s[n]??"",n<e.length){let o=e[n];if(Dr(o)){let r=t.match(/(\w+)\s*:\s*$/);if(r&&(o.isOptional||o.isInternal)){let p=r[1];o.isOptional&&(p+="?"),o.isInternal&&(p+="!"),t=t.replace(/(\w+)(\s*:\s*)$/,`${p}$2`)}let{isOptional:i,isInternal:a,...l}=o;t+=oo(l)}else if(Gr(o))t+=Fr(o);else if(typeof o=="string"||o instanceof q)t+=na(o);else throw new Error("Unsupported template interpolation value")}return new q(t)}function ta(s,...e){let t="";for(let n=0;n<s.length;n++)if(t+=s[n]??"",n<e.length){let o=e[n];if(Dr(o)){let r=t.match(/(\w+)\s*:\s*$/);if(r&&(o.isOptional||o.isInternal)){let p=r[1];o.isOptional&&(p+="?"),o.isInternal&&(p+="!"),t=t.replace(/(\w+)(\s*:\s*)$/,`${p}$2`)}let{isOptional:i,isInternal:a,...l}=o;t+=oo(l)}else if(Gr(o))t+=Fr(o);else if(typeof o=="string"||o instanceof q)t+=na(o);else throw new Error("Unsupported template interpolation value")}return new j(t)}function na(s){if(typeof s=="string")return s;if(Dr(s))return oo(s);if(Gr(s))return Fr(s);if(s instanceof q){let e=s.toString(),t=e.indexOf(" -> ");return t!==-1?e.substring(t+4):e}throw new Error(`Unsupported template value type: ${typeof s}`)}function oo(s){let e=s.type;return s.isArray&&(e+="[]"),s.options&&s.options.length>0&&s.type==="class"&&(e+=` "${s.options.join(", ")}"`),s.description&&(e+=` "${s.description}"`),e}function Fr(s){let e=s.name;return s.isOptional&&(e+="?"),s.isInternal&&(e+="!"),s.type&&(e+=`:${oo(s.type)}`),s.description&&!s.type?.description&&(e+=` "${s.description}"`),e}function Dr(s){return s!==null&&typeof s=="object"&&s!==void 0&&"type"in s&&typeof s.type=="string"}function Gr(s){return s!==null&&typeof s=="object"&&s!==void 0&&"name"in s&&typeof s.name=="string"}var oa={string:s=>({type:"string",description:s}),number:s=>({type:"number",description:s}),boolean:s=>({type:"boolean",description:s}),date:s=>({type:"date",description:s}),datetime:s=>({type:"datetime",description:s}),json:s=>({type:"json",description:s}),image:s=>({type:"image",description:s}),audio:s=>({type:"audio",description:s}),class:(s,e)=>({type:"class",options:s,description:e}),code:(s,e)=>({type:"code",options:[s],description:e}),array:s=>({...s,isArray:!0}),optional:s=>({...s,isOptional:!0}),internal:s=>({...s,isInternal:!0})};var gt=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let o=e.toString(),r=Array.from(o.matchAll(/state\.(\w+)/g));for(let i of r)i[1]&&!n.includes(i[1])&&n.push(i[1]);if(n.length===0)try{let i=this.createDependencyTracker(n);e(i)}catch{}}catch(o){console.debug("Dependency analysis failed:",o)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(o,r){typeof r=="string"&&!t.includes(r)&&t.push(r);let i=o[r];return i&&typeof i=="object"?n.createTrackingProxy(i,t):i},has(o,r){return typeof r=="string"&&!t.includes(r)&&t.push(r),r in o}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let i of n)i[1]&&!t.includes(i[1])&&t.push(i[1]);let o=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let i of o)i[1]&&!t.includes(i[1])&&t.push(i[1]);let r=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let i of r)for(let a=1;a<i.length;a++)i[a]&&!t.includes(i[a])&&t.push(i[a])}catch(n){console.debug("Static dependency parsing failed:",n)}return t}createDependencyTracker(e){return new Proxy({},{get(t,n){return typeof n=="string"&&!e.includes(n)&&e.push(n),new Proxy({},{get:()=>{}})}})}};async function ht(s,e,t){if(!t||t<=0||t>=s.length){let o=s.map((r,i)=>e(r,i));return Promise.all(o)}let n=new Array(s.length);for(let o=0;o<s.length;o+=t){let i=s.slice(o,o+t).map((l,c)=>{let p=o+c;return e(l,p).then(d=>({result:d,originalIndex:p}))}),a=await Promise.all(i);for(let{result:l,originalIndex:c}of a)n[c]=l}return n}var At=class{steps=[];parallelGroups=[];analyzer=new gt;initialFields=new Set;addExecutionStep(e,t,n,o,r,i,a){let l=[],c=[],p=o||"map";if(t&&n)p="execute",l=this.analyzer.analyzeMappingDependencies(n,t),c=[`${t}Result`];else if(p==="map"&&r)c=this.analyzeMapTransformation(r),l=this.getAllProducedFields();else if(p==="parallel-map"){if(Array.isArray(r)){let u=new Set;for(let m of r)this.analyzeMapTransformation(m).forEach(h=>u.add(h));c=Array.from(u)}else r?c=this.analyzeMapTransformation(r):c=["_parallelMapResult"];l=this.getAllProducedFields()}else if(p==="merge"){if(i?.resultKey)c=[i.resultKey];else{let m=this.analyzeBranchMergeFields();c=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?l=["_parallelResults"]:l=this.getAllProducedFields()}else if(p==="parallel")c=["_parallelResults"],l=this.getAllProducedFields();else if(p==="derive")if(a?.outputFieldName&&a?.inputFieldName){c=[a.outputFieldName];let u=r?this.analyzer.analyzeMappingDependencies(r,"derive"):[];l=[a.inputFieldName,...u].filter((m,g,h)=>h.indexOf(m)===g)}else c=["_deriveResult"],l=this.getAllProducedFields();else e.toString().includes("transform(")?(p="map",l=this.getAllProducedFields(),c=["_mapResult"]):e.toString().includes("_parallelResults")&&(c=["_parallelResults"],l=this.getAllProducedFields());for(let u of l)this.getAllProducedFields().includes(u)||this.initialFields.add(u);let d={type:p,nodeName:t,dependencies:l,produces:c,stepFunction:e,stepIndex:this.steps.length};this.steps.push(d)}analyzeStepFunctionProduction(e){try{let t=this.analyzeStepFunctionSource(e);if(t.length>0&&!t.includes("_stepResult"))return t}catch(t){console.debug("Step function source analysis failed:",t)}try{let t=this.createMockState(),n=Object.keys(t),r=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(r&&typeof r=="object"&&"then"in r)return this.analyzeStepFunctionSource(e);if(r&&typeof r=="object"&&!Array.isArray(r)){let a=Object.keys(r).filter(l=>!n.includes(l));if(a.length>0)return a}}catch(t){console.debug("Step function dynamic analysis failed:",t)}return this.analyzeStepFunctionSource(e)}analyzeStepFunctionSource(e){try{let t=e.toString(),n=t.match(/\{\s*\.\.\.state\s*,\s*(\w+)\s*:/g);if(n){let r=n.map(i=>{let a=i.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(r.length>0)return r}let o=t.match(/state\.(\w+)\s*=/g);if(o){let r=o.map(i=>{let a=i.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(r.length>0)return r}}catch(t){console.debug("Step function source analysis failed:",t)}return["_stepResult"]}analyzeMapTransformation(e){try{let t=this.createMockState(),n=e(t);if(n&&typeof n=="object"&&!Array.isArray(n))return Object.keys(n)}catch(t){console.debug("Map transformation analysis failed:",t)}return["_mapResult"]}createMockState(){let e={};for(let t of this.initialFields)e[t]=this.createMockValue(t);for(let t of this.steps)for(let n of t.produces)n.endsWith("Result")?e[n]={text:"mockText",value:"mockValue",result:"mockResult",data:"mockData",processedText:"mockProcessedText",sentimentValue:"mockSentiment",confidenceScore:.8,isComplex:!1,mockValue:"mockValue",responseText:"mockResponseText",inputText:"mockInputText"}:e[n]=this.createMockValue(n);return e}createMockValue(e){return e.includes("List")||e.includes("Array")||e.endsWith("s")?["mockItem1","mockItem2"]:e.includes("count")||e.includes("Count")||e.includes("index")||e.includes("Index")?0:e.includes("is")||e.includes("has")||e.includes("can")?!1:"mockValue"}analyzeBranchMergeFields(){let e=this.steps.slice(-5).filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces);return e.length>0?e:this.steps.filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces)}setInitialFields(e){this.initialFields=new Set(e),this.rebuildParallelGroups()}rebuildParallelGroups(){this.parallelGroups=[];let e=new Set,t=new Set(this.initialFields),n=0;for(;e.size<this.steps.length;){let o=[];for(let r of this.steps){if(e.has(r.stepIndex))continue;if(r.dependencies.length===0||r.dependencies.every(a=>t.has(a))){if(r.type==="merge"&&o.length>0)continue;if(o.push(r),e.add(r.stepIndex),r.type==="merge")break}}if(o.length>0){for(let r of o)r.produces.forEach(i=>t.add(i));this.parallelGroups.push({level:n,steps:o}),n++}else{let r=this.steps.filter(i=>!e.has(i.stepIndex));if(r.length>0){let i=r[0];e.add(i.stepIndex),i.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[i]}),n++}else break}}}getAllProducedFields(){let e=[];for(let t of this.steps)e.push(...t.produces);return e}createOptimizedExecution(e){let t=[];for(let n of this.parallelGroups)if(n.steps.length===1){let o=n.steps[0];o&&t.push(o.stepFunction)}else if(n.steps.length>1){let o=async(r,i)=>{let a=await ht(n.steps,async p=>await p.stepFunction(r,i),e);if(a.some(p=>p&&typeof p=="object"&&"_parallelResults"in p)){let p=a.find(d=>d&&typeof d=="object"&&"_parallelResults"in d);return p||r}let c=r;for(let p of a)c={...c,...p};return c};t.push(o)}return t}getOptimizedExecutionSteps(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),this.createOptimizedExecution()}getExecutionPlan(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),{totalSteps:this.steps.length,parallelGroups:this.parallelGroups.length,maxParallelism:this.steps.length===0?1:Math.max(...this.parallelGroups.map(e=>e.steps.length),0),steps:this.steps,groups:this.parallelGroups}}};var ft=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(r,i)=>{let a=n?.ai??i.mainAi,l=n?.options??i.mainOptions,c=t(r),p=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d;if("forward"in o&&typeof o.forward=="function")d=await o.forward(a,c,{...l,traceLabel:p});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...r,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let o of this.steps)n=await o(n,t);return n}},ro=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(r,i)=>{let a=n?.ai??i.mainAi,l=n?.options??i.mainOptions,c=t(r),p=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d;if("forward"in o&&typeof o.forward=="function")d=await o.forward(a,c,{...l,traceLabel:p});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...r,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let o of this.steps)n=await o(n,t);return n}};var so=class{nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new At;program;nodeUsage=new Map;nodeTraces=new Map;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}inferSignatureFromFlow(){let e=this.executionPlanner.getExecutionPlan();if(this.nodeGenerators.size===0&&e.steps.length===0){let p=new q;return p.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),p.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),p}let t=new Set,n=new Set;for(let p of e.steps)p.produces.forEach(d=>t.add(d)),p.dependencies.forEach(d=>n.add(d));let o=new Set;for(let p of n)t.has(p)||o.add(p);let r=new Set,i=e.steps[e.steps.length-1];if(i&&(i.type==="map"||i.type==="merge")){if(i.produces.forEach(p=>{p.startsWith("_")||r.add(p)}),i.type==="merge"&&i.produces.includes("_mergedResult"))for(let p of e.steps)p.type==="execute"&&p.produces.length>0&&p.produces.forEach(d=>r.add(d))}else for(let p of t){let d=!1;for(let u of e.steps)if(u.dependencies.includes(p)){d=!0;break}if(!d)if(p.endsWith("Result")){let u=p.replace("Result",""),m=this.nodeGenerators.get(u);if(m){let g=m.getSignature(),f=new q(g).getOutputFields();for(let A of f)r.add(A.name)}else r.add(p)}else r.add(p)}if(o.size===0&&r.size===0){let p=[],d=[];for(let[m,g]of this.nodeGenerators){let h=g.getSignature(),f=new q(h);for(let A of f.getInputFields()){let x=this.toCamelCase(`${m}_${A.name}`);p.push({name:x,type:A.type,description:A.description,isOptional:A.isOptional,isInternal:A.isInternal})}for(let A of f.getOutputFields()){let x=this.toCamelCase(`${m}_${A.name}`);d.push({name:x,type:A.type,description:A.description,isOptional:A.isOptional,isInternal:A.isInternal})}}let u=new q;return p.length>0?u.setInputFields(p):u.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),d.length>0?u.setOutputFields(d):u.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),u}let a=new q,l=[];for(let p of o)l.push({name:p,type:{name:"string"},description:`Input field: ${p}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let c=[];for(let p of r)p.startsWith("_")||c.push({name:p,type:{name:"string"},description:`Output field: ${p}`});return c.length===0&&c.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(c),a}constructor(e){this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10}}ensureProgram(){let e=this.inferSignatureFromFlow();this.program=new Se(e)}setExamples(e,t){this.ensureProgram(),this.program.setExamples(e,t)}setId(e){this.ensureProgram(),this.program.setId(e)}setParentId(e){this.ensureProgram(),this.program.setParentId(e)}getTraces(){let e=[];for(let[t,n]of this.nodeTraces)e.push(...n);return e}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}getUsage(){let e=[];for(let[t,n]of this.nodeUsage)e.push(...n);return zt(e)}resetUsage(){this.nodeUsage.clear();for(let[e,t]of this.nodeGenerators)t&&"resetUsage"in t&&t.resetUsage()}resetTraces(){this.nodeTraces.clear()}getUsageReport(){let e={};for(let[t,n]of this.nodeUsage)e[t]=zt(n);return e}getTracesReport(){let e={};for(let[t,n]of this.nodeTraces)e[t]=n;return e}async*streamingForward(e,t,n){yield{version:1,index:0,delta:await this.forward(e,t,n)}}async forward(e,t,n){this.resetUsage(),this.resetTraces();let o;if(Array.isArray(t)){let l=t.filter(c=>c.role==="user").pop();if(!l)throw new Error("No user message found in values array");o=l.values}else o=t;this.nodeGenerators.size>0&&this.ensureProgram();let r={...o},i={mainAi:e,mainOptions:n?{...n,model:n.model?String(n.model):void 0}:void 0};if(n?.autoParallel!==!1&&this.autoParallelConfig.enabled){this.executionPlanner.setInitialFields(Object.keys(o));let l=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize);for(let c of l)r=await c(r,i)}else for(let l of this.flowDefinition)r=await l(r,i);return r}node(e,t){if(typeof t=="string"||t instanceof q){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let o=new j(n);this.nodeGenerators.set(e,o),this.ensureProgram(),this.program.register(o)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],o=async r=>{let i=await ht(n,async(a,l)=>a(r),this.autoParallelConfig.batchSize);return i[i.length-1]};if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"parallel-map")}else{let n=o=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");return e(o)};if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);let r=async(i,a)=>{let l=n?.ai??a.mainAi,c=n?.options??a.mainOptions,p=t(i),d=c?.traceLabel?`Node:${e} (${c.traceLabel})`:`Node:${e}`,u;if("forward"in o&&typeof o.forward=="function"){if(u=await o.forward(l,p,{...c,traceLabel:d}),"getUsage"in o&&typeof o.getUsage=="function"){let m=o.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in o&&typeof o.getTraces=="function"){let m=o.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...i,[`${e}Result`]:u}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,e,t);return this.ensureProgram(),this}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,o)=>{let r=e.predicate(n),i=e.branches.get(r);if(!i)return n;let a=n;for(let l of i)a=await l(a,o);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,o)=>{let r=await ht(e,async(i,a)=>{let l=new ft(this.nodeGenerators);return await i(l).executeSteps(n,o)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:r}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,o)=>{let r=i=>{let a=i._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=o(...a),c={...i};return delete c._parallelResults,c[n]=l,c};return this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:o}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let o=this.stepLabels.get(t),r=this.flowDefinition.length;return this.flowDefinition.push(async(i,a)=>{let l=i,c=1,p=`_feedback_${t}_iterations`;for(typeof l[p]!="number"&&(l={...l,[p]:1});e(l)&&c<n;){c++,l={...l,[p]:c};for(let d=o;d<r;d++){let u=this.flowDefinition[d];u&&(l=await u(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let o=Object.assign(r=>r,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(o),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,o=t._maxIterations,r=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(i,a)=>{let l=i,c=0;for(;n(l)&&c<o;){c++;for(let p of r)l=await p(l,a)}if(c>=o&&n(l))throw new Error(`While loop exceeded maximum iterations (${o}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,o){let r=async i=>{let a=i[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let l;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let c=o?.batchSize||this.autoParallelConfig.batchSize;l=await ht(a,async(p,d)=>n(p,d,i),c)}else l=a.map((c,p)=>n(c,p,i));else l=n(a,void 0,i);return{...i,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:o?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}};var io=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:o}){let r=t.map(c=>`${c.hostPath}:${c.containerPath}`);n||await this.pullImage(e);let i={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:r},Labels:{}};o&&(i.Labels["com.example.tag"]=o);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new Error(`Failed to create container: ${a.statusText}`);let l=await a.json();return this.containerId=l.Id,l}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:o}){let i=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===o);if(i&&i.length>0){let l=Math.floor(Math.random()*i.length),c=i[l];if(c)return await this.connectToContainer(c.Id),{Id:c.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:o})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let o=[],r=await this.listContainers(!0),i=e?r.filter(a=>a.Labels["com.example.tag"]===e):r;for(let a of i){if(a.State.Status==="running"){let l=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!l.ok){console.warn(`Failed to stop container ${a.Id}: ${l.statusText}`);continue}o.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}o.push({Id:a.Id,Action:"removed"})}}return o}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(console.log("Executing command:",e),!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let o=await n.json(),r=await this.fetchDockerAPI(`/exec/${o.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!r.ok)throw new Error(`Failed to start exec instance: ${r.statusText}`);return await r.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(r=>setTimeout(r,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var ao=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let o=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!o)throw new Error("Failed to embed text");return this.func.length===2?this.func(o,t):this.func(o)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var lo=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(r=>r.name===t.name),o=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:o,func:async r=>{let{result:i}=await this.sendRequest("tools/call",{name:t.name,arguments:r});return i}}})}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((i,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),o=await Promise.race([t,n]),{result:r}=o;if(typeof r!="object"||r===null||Object.keys(r).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(r)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=se(),o={jsonrpc:"2.0",id:n,method:e,params:t},r=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(o).then(c=>{if(this.activeRequests.delete(n),c!==null&&typeof c=="object"&&"error"in c){let p=c;l(new Error(`RPC Error ${p.error.code}: ${p.error.message}`))}else c!==null&&typeof c=="object"&&"result"in c?a({result:c.result}):l(new Error("Invalid response no result or error"))}).catch(c=>{this.activeRequests.delete(n),l(c)})}),{result:i}=await r;return{id:n,result:i}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:o}=this.options;if(o){let r={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(r)}await this.transport.sendNotification(n)}};var co=class{endpoint=null;sseUrl;eventSource;constructor(e){this.sseUrl=e}async connect(){return new Promise((e,t)=>{this.eventSource=new EventSource(this.sseUrl),this.eventSource.addEventListener("endpoint",n=>{try{let r=JSON.parse(n.data);if(!r.uri)throw new Error("Endpoint URI missing in SSE event data");this.endpoint=r.uri,e()}catch(o){t(o)}}),this.eventSource.onerror=()=>{t(new Error("Failed to establish SSE connection"))}})}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`HTTP error ${t.status}: ${t.statusText}`);return t.json()}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}},po=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers},t?.authorization&&(this.customHeaders.Authorization=t.authorization)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),o=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(o.toString()),this.eventSource.onopen=()=>{e()},this.eventSource.onmessage=r=>{try{let i=JSON.parse(r.data);this.messageHandler&&this.messageHandler(i)}catch(i){console.error("Failed to parse SSE message:",i)}},this.eventSource.onerror=()=>{t(new Error("Failed to establish SSE connection"))}})}async openListeningStreamWithFetch(e){let t=await fetch(this.mcpEndpoint,{method:"GET",headers:e});if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),o=new TextDecoder,r="",i=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}r+=o.decode(l,{stream:!0});let c=r.split(`
|
|
290
|
-
`)
|
|
291
|
-
`);
|
|
292
|
-
|
|
291
|
+
Instruction:`;try{let d=await n.chat({chatPrompt:[{role:"user",content:l}]});if("results"in d){let u=d.results[0]?.content?.trim();if(u&&u.length>10)return u}}catch{}let p=["Analyze the input systematically and provide a precise, well-reasoned response.","Think through this step-by-step, considering all relevant factors before responding.","Examine the input carefully and generate an accurate, detailed answer.","Process the information methodically and deliver a clear, comprehensive response.","Consider the context thoroughly and provide a thoughtful, accurate answer."],c=p[t%p.length]||p[0];return e&&(c=`${c} ${e}`),c}async proposeInstructionCandidates(e,t){let n=[],r=this.getTeacherOrStudentAI(t),o,i;this.dataAwareProposer&&(i=await this.generateDatasetSummary(this.examples,r));let a=this.tipAwareProposer?this.generateTips():[];for(let l=0;l<this.numCandidates;l++){let p=a.length>0?l%a.length:-1,c=p>=0?a[p]:void 0,d=await this.generateInstruction({tip:c,candidateIndex:l,ai:r,programSummary:o,datasetSummary:i,previousInstructions:n});n.push(d)}return n}async bootstrapFewShotExamples(e,t){return(await new At({studentAI:this.studentAI,examples:this.examples,options:{maxDemos:this.maxBootstrappedDemos,maxRounds:3,verboseMode:this.isLoggingEnabled()}}).compile(e,t,{maxDemos:this.maxBootstrappedDemos})).demos||[]}selectLabeledExamples(){let e=[],t=new Set;for(;t.size<this.maxLabeledDemos&&t.size<this.examples.length;){let n=Math.floor(Math.random()*this.examples.length);if(!t.has(n)){t.add(n);let r=this.examples[n];r&&e.push(r)}}return e}async runOptimization(e,t,n,r,o,i,a){let l={instruction:r[0]||"",bootstrappedDemos:Math.min(1,t.length),labeledExamples:Math.min(1,n.length)},p=0,c=0,d=[],u=0;if(this.resumeFromCheckpoint){let m=await this.loadCheckpoint(this.resumeFromCheckpoint,a);m&&m.optimizerType==="MiPRO"&&(this.restoreFromCheckpoint(m),u=m.currentRound,p=m.bestScore,l=m.bestConfiguration||l,c=m.stats.convergenceInfo?.stagnationRounds||0)}for(let m=u;m<this.numTrials;m++){let g;this.bayesianOptimization&&this.miproConfigHistory.length>2?g=await this.selectConfigurationViaBayesianOptimization(r,t,n):g={instruction:r[m%r.length]||r[0]||"",bootstrappedDemos:Math.min(Math.floor(Math.random()*(t.length+1)),this.maxBootstrappedDemos),labeledExamples:Math.min(Math.floor(Math.random()*(n.length+1)),this.maxLabeledDemos)};let h=await this.evaluateConfig(e,g,t,n,o,i,m+1);this.updateSurrogateModel(g,h),d.push(h);let A=h-p;if(A>this.minImprovementThreshold?(p=h,l=g,c=0):c++,await this.updateOptimizationProgress(m+1,h,g,"MiPRO",this.getConfiguration(),p,l,{stagnationRounds:c,bootstrappedDemos:t.length,labeledExamples:n.length,instructions:r.length},a),this.onProgress&&this.onProgress({round:m+1,totalRounds:this.numTrials,currentScore:h,bestScore:p,tokensUsed:this.stats.resourceUsage.totalTokens,timeElapsed:Date.now(),successfulExamples:this.stats.successfulDemos,totalExamples:this.examples.length,currentConfiguration:g,convergenceInfo:{improvement:A,stagnationRounds:c,isConverging:c<this.earlyStoppingTrials}}),this.checkCostLimits()){this.triggerEarlyStopping("Cost limit reached",m+1);break}if(c>=this.earlyStoppingTrials){this.triggerEarlyStopping(`No improvement for ${this.earlyStoppingTrials} trials`,m-c+1);break}if(this.checkTargetScore(p)){this.triggerEarlyStopping(`Target score ${this.targetScore} reached`,m+1);break}}return this.stats.convergenceInfo.stagnationRounds=c,this.stats.convergenceInfo.finalImprovement=d.length>1?p-d[0]:0,this.stats.convergenceInfo.converged=c<this.earlyStoppingTrials,{bestConfig:l,bestScore:p}}async evaluateConfig(e,t,n,r,o,i,a=0){let l=new ee(e.getSignature());this.applyConfigToProgram(l,t,n,r);let p=0,c=0,d;if(this.minibatch){let g=Math.min(this.minibatchSize,o.length);a%this.minibatchFullEvalSteps===0||a>this.numTrials*.8?d=Math.min(o.length,g*2):d=Math.max(3,Math.min(g,o.length))}else d=o.length;let m=this.shuffleArray([...Array(o.length).keys()]).slice(0,d).map(g=>o[g]);for(let g of m)try{let h=this.sampleCount>1?{sampleCount:this.sampleCount,resultPicker:mp(),maxRetries:1}:{maxRetries:1},A=await l.forward(this.studentAI,g,h),f=await i({prediction:A,example:g});p+=f,c++,this.stats.totalCalls++}catch(h){this.isLoggingEnabled()&&console.warn(`Student model failed during evaluation: ${h instanceof Error?h.message:"Unknown error"}`),this.stats.totalCalls++}return c>0?p/c:0}shuffleArray(e){let t=[...e];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1));[t[n],t[r]]=[t[r],t[n]]}return t}applyConfigToProgram(e,t,n,r){e.setInstruction&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples&&e.setExamples(r.slice(0,t.labeledExamples))}async compile(e,t,n){let r=Date.now();this.setupRandomSeed();let o=n;if(o?.auto&&this.configureAuto(o.auto),this.pythonClient){if(!await this.pythonClient.healthCheck())throw new Error("Python optimizer service is not available or unhealthy");return this.logger?.({name:"Notification",id:"mipro_mode",value:"Using Python optimizer service for MiPRO optimization"}),await this.compilePython(e,t,n)}let i=this.getValidationSet(n)||(o?.validationExamples??this.examples.slice(0,Math.floor(this.examples.length*.2))),a=[];this.maxBootstrappedDemos>0&&(a=await this.bootstrapFewShotExamples(e,t));let l=[];this.maxLabeledDemos>0&&(l=this.selectLabeledExamples());let p=await this.proposeInstructionCandidates(e,n),{bestConfig:c,bestScore:d}=await this.runOptimization(e,a,l,p,i,t,n);this.checkTargetScore(d)&&this.triggerEarlyStopping(`Target score ${this.targetScore} reached with score ${d}`,this.numTrials);let u;"getSignature"in e&&typeof e.getSignature=="function"?u=e.getSignature():u="input -> output";let m=new ee(u);return this.applyConfigToAxGen(m,c,a,l),this.updateResourceUsage(r),this.stats.convergenceInfo.converged=!0,this.stats.convergenceInfo.finalImprovement=d,await this.saveFinalCheckpoint("MiPRO",this.getConfiguration(),d,c,{bootstrappedDemos:a.length,labeledExamples:l.length,instructions:p.length,optimizedGen:!!m},n),{demos:a,stats:this.stats,bestScore:d,optimizedGen:m,finalConfiguration:{instruction:c.instruction,bootstrappedDemos:c.bootstrappedDemos,labeledExamples:c.labeledExamples,numCandidates:this.numCandidates,numTrials:this.numTrials,sampleCount:this.sampleCount}}}applyConfigToAxGen(e,t,n,r){"setInstruction"in e&&typeof e.setInstruction=="function"&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples(r.slice(0,t.labeledExamples))}getConfiguration(){return{numCandidates:this.numCandidates,initTemperature:this.initTemperature,maxBootstrappedDemos:this.maxBootstrappedDemos,maxLabeledDemos:this.maxLabeledDemos,numTrials:this.numTrials,minibatch:this.minibatch,minibatchSize:this.minibatchSize,minibatchFullEvalSteps:this.minibatchFullEvalSteps,programAwareProposer:this.programAwareProposer,dataAwareProposer:this.dataAwareProposer,tipAwareProposer:this.tipAwareProposer,fewshotAwareProposer:this.fewshotAwareProposer,earlyStoppingTrials:this.earlyStoppingTrials,minImprovementThreshold:this.minImprovementThreshold,bayesianOptimization:this.bayesianOptimization,acquisitionFunction:this.acquisitionFunction,explorationWeight:this.explorationWeight,sampleCount:this.sampleCount}}updateConfiguration(e){e.numCandidates!==void 0&&(this.numCandidates=e.numCandidates),e.initTemperature!==void 0&&(this.initTemperature=e.initTemperature),e.maxBootstrappedDemos!==void 0&&(this.maxBootstrappedDemos=e.maxBootstrappedDemos),e.maxLabeledDemos!==void 0&&(this.maxLabeledDemos=e.maxLabeledDemos),e.numTrials!==void 0&&(this.numTrials=e.numTrials),e.minibatch!==void 0&&(this.minibatch=e.minibatch),e.minibatchSize!==void 0&&(this.minibatchSize=e.minibatchSize),e.earlyStoppingTrials!==void 0&&(this.earlyStoppingTrials=e.earlyStoppingTrials),e.minImprovementThreshold!==void 0&&(this.minImprovementThreshold=e.minImprovementThreshold),e.sampleCount!==void 0&&(this.sampleCount=e.sampleCount)}reset(){super.reset(),this.miproConfigHistory=[],this.surrogateModel.clear(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}validateProgram(e){let t=[],n=[];return this.examples.length<this.maxBootstrappedDemos+this.maxLabeledDemos&&(t.push(`Not enough examples: need at least ${this.maxBootstrappedDemos+this.maxLabeledDemos}, got ${this.examples.length}`),n.push("Reduce maxBootstrappedDemos or maxLabeledDemos, or provide more examples")),this.getValidationSet().length<5&&(t.push("Validation set too small for reliable MiPRO optimization"),n.push("Provide more examples or a larger validation set")),{isValid:t.length===0,issues:t,suggestions:n}}encodeConfiguration(e){return`${this.hashString(e.instruction)}_${e.bootstrappedDemos}_${e.labeledExamples}`}hashString(e){let t=0;if(e.length===0)return t.toString();for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(16)}updateSurrogateModel(e,t){this.miproConfigHistory.push({config:{...e},score:t});let n=this.encodeConfiguration(e),r=this.miproConfigHistory.filter(o=>this.encodeConfiguration(o.config)===n);if(r.length>0){let o=r.map(l=>l.score),i=o.reduce((l,p)=>l+p,0)/o.length,a=o.length>1?o.reduce((l,p)=>l+(p-i)**2,0)/(o.length-1):.1;this.surrogateModel.set(n,{mean:i,variance:a})}}predictPerformance(e){let t=this.encodeConfiguration(e);if(this.surrogateModel.has(t))return this.surrogateModel.get(t);if(this.miproConfigHistory.length>0){let n=this.miproConfigHistory.map(i=>{let a=Math.abs(i.config.bootstrappedDemos-e.bootstrappedDemos)+Math.abs(i.config.labeledExamples-e.labeledExamples);return{score:i.score,similarity:1/(1+a)}}),r=n.reduce((i,a)=>i+a.similarity,0);return{mean:n.reduce((i,a)=>i+a.score*a.similarity,0)/r,variance:.2}}return{mean:.5,variance:.3}}calculateAcquisitionValue(e){let t=this.predictPerformance(e),{mean:n,variance:r}=t,o=Math.sqrt(r),i=this.miproConfigHistory.length>0?Math.max(...this.miproConfigHistory.map(a=>a.score)):0;switch(this.acquisitionFunction){case"expected_improvement":{let a=n-i;if(o===0)return Math.max(0,a);let l=a/o,p=.5*(1+this.erf(l/Math.sqrt(2))),c=Math.exp(-.5*l*l)/Math.sqrt(2*Math.PI);return a*p+o*c}case"upper_confidence_bound":return n+this.explorationWeight*o;case"probability_improvement":{let a=n-i;if(o===0)return a>0?1:0;let l=a/o;return .5*(1+this.erf(l/Math.sqrt(2)))}default:return n}}erf(e){let t=.254829592,n=-.284496736,r=1.421413741,o=-1.453152027,i=1.061405429,a=.3275911,l=e>=0?1:-1,p=Math.abs(e),c=1/(1+a*p),d=1-((((i*c+o)*c+r)*c+n)*c+t)*c*Math.exp(-p*p);return l*d}async selectConfigurationViaBayesianOptimization(e,t,n){let r=[],o=Math.min(20,e.length*3);for(let i=0;i<o;i++){let a={instruction:e[i%e.length]||e[0]||"",bootstrappedDemos:Math.min(Math.floor(Math.random()*(t.length+1)),this.maxBootstrappedDemos),labeledExamples:Math.min(Math.floor(Math.random()*(n.length+1)),this.maxLabeledDemos)},l=this.calculateAcquisitionValue(a);r.push({config:a,acquisitionValue:l})}return r.sort((i,a)=>a.acquisitionValue-i.acquisitionValue),r[0].config}async compilePython(e,t,n){if(!this.pythonClient)throw new Error("Python client not initialized");let r=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,o={study_name:r,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos}],objective:{name:"score",direction:"maximize"},n_trials:this.numTrials,sampler:"TPESampler",pruner:this.minibatch?"MedianPruner":void 0},i=await this.pythonClient.createOptimizationJob(o);this.logger?.({name:"Notification",id:"python_job_started",value:`Started Python optimization job ${i.job_id}`});let a=Number.NEGATIVE_INFINITY,l=e,p=0;for(let c=0;c<this.numTrials;c++)try{let d=await this.pythonClient.suggestParameters(r),u=d.params.temperature,m=d.params.bootstrappedDemos,g=await this.evaluateConfiguration(e,t,{temperature:u,bootstrappedDemos:m},this.minibatch?this.examples.slice(0,this.minibatchSize):this.examples);p++,await this.pythonClient.evaluateTrial({study_name:r,trial_number:d.trial_number,value:g}),g>a&&(a=g),this.logger?.({name:"Notification",id:"python_trial_result",value:`Trial ${c+1}: score=${g.toFixed(3)}, temp=${u.toFixed(2)}`}),this.onProgress?.({round:c+1,totalRounds:this.numTrials,currentScore:g,bestScore:a,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-Date.now(),successfulExamples:p,totalExamples:this.examples.length})}catch(d){this.logger?.({name:"Notification",id:"python_trial_error",value:`Trial ${c+1} failed: ${d}`})}try{let c=await this.pythonClient.getStudyResults(r);this.logger?.({name:"Notification",id:"python_results",value:`Python optimization completed with ${c.n_trials} trials`})}catch(c){this.logger?.({name:"Notification",id:"python_results_error",value:`Failed to get study results: ${c}`})}try{await this.pythonClient.deleteStudy(r)}catch{}return this.stats.bestScore=a,this.stats.totalCalls=p,{bestScore:a,stats:this.stats,optimizedGen:l}}async evaluateConfiguration(e,t,n,r){let o=0,i=0,a=r.slice(0,Math.min(5,r.length));for(let l of a)try{let p=await e.forward(this.studentAI,l),c=await t({prediction:p,example:l});typeof c=="number"&&!Number.isNaN(c)&&(o+=c,i++)}catch{}return i>0?o/i:0}},mp=()=>async s=>{if(s.type==="fields"){let e={};for(let{index:r,sample:o}of s.results){let i=JSON.stringify(o);e[i]||(e[i]={count:0,index:r}),e[i].count+=1}let t,n=-1;for(let[r,o]of Object.entries(e))o.count>n&&(n=o.count,t=r);return e[t]?.index??0}return s.results[0]?.index??0};function ya(s){return H.create(s)}function yr(s,e){let t=H.create(s);return new ee(t,e)}var xt=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let r=e.toString(),o=Array.from(r.matchAll(/state\.(\w+)/g));for(let i of o)i[1]&&!n.includes(i[1])&&n.push(i[1]);if(n.length===0)try{let i=this.createDependencyTracker(n);e(i)}catch{}}catch(r){console.debug("Dependency analysis failed:",r)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(r,o){typeof o=="string"&&!t.includes(o)&&t.push(o);let i=r[o];return i&&typeof i=="object"?n.createTrackingProxy(i,t):i},has(r,o){return typeof o=="string"&&!t.includes(o)&&t.push(o),o in r}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let i of n)i[1]&&!t.includes(i[1])&&t.push(i[1]);let r=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let i of r)i[1]&&!t.includes(i[1])&&t.push(i[1]);let o=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let i of o)for(let a=1;a<i.length;a++)i[a]&&!t.includes(i[a])&&t.push(i[a])}catch(n){console.debug("Static dependency parsing failed:",n)}return t}createDependencyTracker(e){return new Proxy({},{get(t,n){return typeof n=="string"&&!e.includes(n)&&e.push(n),new Proxy({},{get:()=>{}})}})}};async function yt(s,e,t){if(!t||t<=0||t>=s.length){let r=s.map((o,i)=>e(o,i));return Promise.all(r)}let n=new Array(s.length);for(let r=0;r<s.length;r+=t){let i=s.slice(r,r+t).map((l,p)=>{let c=r+p;return e(l,c).then(d=>({result:d,originalIndex:c}))}),a=await Promise.all(i);for(let{result:l,originalIndex:p}of a)n[p]=l}return n}var It=class{steps=[];parallelGroups=[];analyzer=new xt;initialFields=new Set;addExecutionStep(e,t,n,r,o,i,a){let l=[],p=[],c=r||"map";if(t&&n)c="execute",l=this.analyzer.analyzeMappingDependencies(n,t),p=[`${t}Result`];else if(c==="map"&&o)p=this.analyzeMapTransformation(o),l=this.getAllProducedFields();else if(c==="parallel-map"){if(Array.isArray(o)){let u=new Set;for(let m of o)this.analyzeMapTransformation(m).forEach(h=>u.add(h));p=Array.from(u)}else o?p=this.analyzeMapTransformation(o):p=["_parallelMapResult"];l=this.getAllProducedFields()}else if(c==="merge"){if(i?.resultKey)p=[i.resultKey];else{let m=this.analyzeBranchMergeFields();p=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?l=["_parallelResults"]:l=this.getAllProducedFields()}else if(c==="parallel")p=["_parallelResults"],l=this.getAllProducedFields();else if(c==="derive")if(a?.outputFieldName&&a?.inputFieldName){p=[a.outputFieldName];let u=o?this.analyzer.analyzeMappingDependencies(o,"derive"):[];l=[a.inputFieldName,...u].filter((m,g,h)=>h.indexOf(m)===g)}else p=["_deriveResult"],l=this.getAllProducedFields();else e.toString().includes("transform(")?(c="map",l=this.getAllProducedFields(),p=["_mapResult"]):e.toString().includes("_parallelResults")&&(p=["_parallelResults"],l=this.getAllProducedFields());for(let u of l)this.getAllProducedFields().includes(u)||this.initialFields.add(u);let d={type:c,nodeName:t,dependencies:l,produces:p,stepFunction:e,stepIndex:this.steps.length};this.steps.push(d)}analyzeStepFunctionProduction(e){try{let t=this.analyzeStepFunctionSource(e);if(t.length>0&&!t.includes("_stepResult"))return t}catch(t){console.debug("Step function source analysis failed:",t)}try{let t=this.createMockState(),n=Object.keys(t),o=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(o&&typeof o=="object"&&"then"in o)return this.analyzeStepFunctionSource(e);if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Object.keys(o).filter(l=>!n.includes(l));if(a.length>0)return a}}catch(t){console.debug("Step function dynamic analysis failed:",t)}return this.analyzeStepFunctionSource(e)}analyzeStepFunctionSource(e){try{let t=e.toString(),n=t.match(/\{\s*\.\.\.state\s*,\s*(\w+)\s*:/g);if(n){let o=n.map(i=>{let a=i.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}let r=t.match(/state\.(\w+)\s*=/g);if(r){let o=r.map(i=>{let a=i.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}}catch(t){console.debug("Step function source analysis failed:",t)}return["_stepResult"]}analyzeMapTransformation(e){try{let t=this.createMockState(),n=e(t);if(n&&typeof n=="object"&&!Array.isArray(n))return Object.keys(n)}catch(t){console.debug("Map transformation analysis failed:",t)}return["_mapResult"]}createMockState(){let e={};for(let t of this.initialFields)e[t]=this.createMockValue(t);for(let t of this.steps)for(let n of t.produces)n.endsWith("Result")?e[n]={text:"mockText",value:"mockValue",result:"mockResult",data:"mockData",processedText:"mockProcessedText",sentimentValue:"mockSentiment",confidenceScore:.8,isComplex:!1,mockValue:"mockValue",responseText:"mockResponseText",inputText:"mockInputText"}:e[n]=this.createMockValue(n);return e}createMockValue(e){return e.includes("List")||e.includes("Array")||e.endsWith("s")?["mockItem1","mockItem2"]:e.includes("count")||e.includes("Count")||e.includes("index")||e.includes("Index")?0:e.includes("is")||e.includes("has")||e.includes("can")?!1:"mockValue"}analyzeBranchMergeFields(){let e=this.steps.slice(-5).filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces);return e.length>0?e:this.steps.filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces)}setInitialFields(e){this.initialFields=new Set(e),this.rebuildParallelGroups()}rebuildParallelGroups(){this.parallelGroups=[];let e=new Set,t=new Set(this.initialFields),n=0;for(;e.size<this.steps.length;){let r=[];for(let o of this.steps){if(e.has(o.stepIndex))continue;if(o.dependencies.length===0||o.dependencies.every(a=>t.has(a))){if(o.type==="merge"&&r.length>0)continue;if(r.push(o),e.add(o.stepIndex),o.type==="merge")break}}if(r.length>0){for(let o of r)o.produces.forEach(i=>t.add(i));this.parallelGroups.push({level:n,steps:r}),n++}else{let o=this.steps.filter(i=>!e.has(i.stepIndex));if(o.length>0){let i=o[0];e.add(i.stepIndex),i.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[i]}),n++}else break}}}getAllProducedFields(){let e=[];for(let t of this.steps)e.push(...t.produces);return e}createOptimizedExecution(e){let t=[];for(let n of this.parallelGroups)if(n.steps.length===1){let r=n.steps[0];r&&t.push(r.stepFunction)}else if(n.steps.length>1){let r=async(o,i)=>{let a=await yt(n.steps,async c=>await c.stepFunction(o,i),e);if(a.some(c=>c&&typeof c=="object"&&"_parallelResults"in c)){let c=a.find(d=>d&&typeof d=="object"&&"_parallelResults"in d);return c||o}let p=o;for(let c of a)p={...p,...c};return p};t.push(r)}return t}getOptimizedExecutionSteps(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),this.createOptimizedExecution()}getExecutionPlan(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),{totalSteps:this.steps.length,parallelGroups:this.parallelGroups.length,maxParallelism:this.steps.length===0?1:Math.max(...this.parallelGroups.map(e=>e.steps.length),0),steps:this.steps,groups:this.parallelGroups}}};var Ia=s=>{console.log(s)},bt=(s,e=!1)=>{if(e)return"[State hidden]";let t={};for(let[n,r]of Object.entries(s))if(typeof r=="string"&&r.length>100)t[n]=`${r.substring(0,100)}...`;else if(Array.isArray(r)&&r.length>3)t[n]=[...r.slice(0,3),`... (${r.length-3} more)`];else if(typeof r=="object"&&r!==null){let o=JSON.stringify(r);o.length>200?t[n]=`${o.substring(0,200)}...`:t[n]=r}else t[n]=r;return JSON.stringify(t,null,2)},Rt=s=>s<1e3?`${s.toFixed(1)}ms`:s<6e4?`${(s/1e3).toFixed(2)}s`:`${(s/6e4).toFixed(2)}min`,en=(s=Ia)=>{let e=new Z,t=e.gray(`${"\u2501".repeat(80)}
|
|
292
|
+
`),n=e.gray(`${"\u2500".repeat(40)}
|
|
293
|
+
`);return r=>{let o="";switch(r.name){case"FlowStart":o=`
|
|
294
|
+
${e.blueBright("\u{1F504} [ AXFLOW START ]")}
|
|
295
|
+
${t}`,o+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
|
|
296
|
+
`,o+=`${e.white("Total Steps:")} ${e.yellow(r.totalSteps.toString())}
|
|
297
|
+
`,o+=`${e.white("Parallel Groups:")} ${e.yellow(r.parallelGroups.toString())}
|
|
298
|
+
`,o+=`${e.white("Max Parallelism:")} ${e.yellow(r.maxParallelism.toString())}
|
|
299
|
+
`,o+=`${e.white("Auto-Parallel:")} ${r.autoParallelEnabled?e.green("enabled"):e.red("disabled")}
|
|
300
|
+
`,o+=t;break;case"StepStart":{let i=r.stepType==="execute"?"\u26A1":r.stepType==="map"?"\u{1F504}":r.stepType==="merge"?"\u{1F500}":r.stepType==="parallel"?"\u2696\uFE0F":"\u{1F4CB}";o=`${e.greenBright(`${i} [ STEP ${r.stepIndex} START ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=`
|
|
301
|
+
`,r.dependencies.length>0&&(o+=`${e.white("Dependencies:")} ${e.gray(r.dependencies.join(", "))}
|
|
302
|
+
`),r.produces.length>0&&(o+=`${e.white("Produces:")} ${e.cyan(r.produces.join(", "))}
|
|
303
|
+
`),o+=`${e.white("State:")} ${e.gray(bt(r.state,!0))}
|
|
304
|
+
`,o+=n;break}case"StepComplete":{let i=(r.stepType==="execute"||r.stepType==="map"||r.stepType==="merge"||r.stepType==="parallel","\u2705");o=`${e.greenBright(`${i} [ STEP ${r.stepIndex} COMPLETE ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=` ${e.magenta(`in ${Rt(r.executionTime)}`)}
|
|
305
|
+
`,r.newFields&&r.newFields.length>0&&(o+=`${e.white("New Fields:")} ${e.green(r.newFields.join(", "))}
|
|
306
|
+
`),r.result&&r.nodeName&&(o+=`${e.white("Result:")} ${e.yellow(JSON.stringify(r.result,null,2))}
|
|
307
|
+
`),o+=n;break}case"ParallelGroupStart":o=`${e.blueBright("\u2696\uFE0F [ PARALLEL GROUP START ]")} ${e.white(`Level ${r.groupLevel}`)}
|
|
308
|
+
`,o+=`${e.white("Steps:")} ${e.yellow(r.stepsCount.toString())} ${e.gray(`(${r.stepTypes.join(", ")})`)}
|
|
309
|
+
`,o+=n;break;case"ParallelGroupComplete":o=`${e.blueBright("\u2705 [ PARALLEL GROUP COMPLETE ]")} ${e.white(`Level ${r.groupLevel}`)}`,o+=` ${e.magenta(`in ${Rt(r.executionTime)}`)}
|
|
310
|
+
`,o+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsCount.toString())}
|
|
311
|
+
`,o+=n;break;case"BranchEvaluation":o=`${e.yellow("\u{1F500} [ BRANCH EVALUATION ]")}
|
|
312
|
+
`,o+=`${e.white("Branch Value:")} ${e.cyan(JSON.stringify(r.branchValue))}
|
|
313
|
+
`,o+=`${e.white("Has Matching Branch:")} ${r.hasMatchingBranch?e.green("yes"):e.red("no")}
|
|
314
|
+
`,r.hasMatchingBranch&&(o+=`${e.white("Branch Steps:")} ${e.yellow(r.branchStepsCount.toString())}
|
|
315
|
+
`),o+=n;break;case"FlowComplete":o=`
|
|
316
|
+
${e.greenBright("\u2705 [ AXFLOW COMPLETE ]")}
|
|
317
|
+
${t}`,o+=`${e.white("Total Time:")} ${e.magenta(Rt(r.totalExecutionTime))}
|
|
318
|
+
`,o+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsExecuted.toString())}
|
|
319
|
+
`,o+=`${e.white("Output Fields:")} ${e.green(r.outputFields.join(", "))}
|
|
320
|
+
`,o+=`${e.white("Final State:")} ${e.gray(bt(r.finalState,!0))}
|
|
321
|
+
`,o+=t;break;case"FlowError":o=`
|
|
322
|
+
${e.redBright("\u274C [ AXFLOW ERROR ]")}
|
|
323
|
+
${t}`,r.stepIndex!==void 0&&(o+=`${e.white("Step:")} ${e.yellow(r.stepIndex.toString())}`,r.stepType&&(o+=` ${e.gray(`(${r.stepType})`)}`),r.nodeName&&(o+=` ${e.cyan(`Node: ${r.nodeName}`)}`),o+=`
|
|
324
|
+
`),o+=`${e.white("Error:")} ${e.red(r.error)}
|
|
325
|
+
`,r.state&&(o+=`${e.white("State:")} ${e.gray(bt(r.state,!0))}
|
|
326
|
+
`),o+=t;break;default:o=e.gray(JSON.stringify(r,null,2))}s(o)}},ba=(s=Ia)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
|
|
327
|
+
[ AXFLOW START ]
|
|
328
|
+
${e}
|
|
329
|
+
`,r+=`Input Fields: ${n.inputFields.join(", ")}
|
|
330
|
+
`,r+=`Total Steps: ${n.totalSteps}
|
|
331
|
+
`,r+=`Parallel Groups: ${n.parallelGroups}
|
|
332
|
+
`,r+=`Max Parallelism: ${n.maxParallelism}
|
|
333
|
+
`,r+=`Auto-Parallel: ${n.autoParallelEnabled?"enabled":"disabled"}
|
|
334
|
+
`,r+=`${e}
|
|
335
|
+
`;break;case"StepStart":r=`[ STEP ${n.stepIndex} START ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
|
|
336
|
+
`,n.dependencies.length>0&&(r+=`Dependencies: ${n.dependencies.join(", ")}
|
|
337
|
+
`),n.produces.length>0&&(r+=`Produces: ${n.produces.join(", ")}
|
|
338
|
+
`),r+=`State: ${bt(n.state,!0)}
|
|
339
|
+
`,r+=`${t}
|
|
340
|
+
`;break;case"StepComplete":r=`[ STEP ${n.stepIndex} COMPLETE ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=` in ${Rt(n.executionTime)}
|
|
341
|
+
`,n.newFields&&n.newFields.length>0&&(r+=`New Fields: ${n.newFields.join(", ")}
|
|
342
|
+
`),n.result&&n.nodeName&&(r+=`Result: ${JSON.stringify(n.result,null,2)}
|
|
343
|
+
`),r+=`${t}
|
|
344
|
+
`;break;case"ParallelGroupStart":r=`[ PARALLEL GROUP START ] Level ${n.groupLevel}
|
|
345
|
+
`,r+=`Steps: ${n.stepsCount} (${n.stepTypes.join(", ")})
|
|
346
|
+
`,r+=`${t}
|
|
347
|
+
`;break;case"ParallelGroupComplete":r=`[ PARALLEL GROUP COMPLETE ] Level ${n.groupLevel} in ${Rt(n.executionTime)}
|
|
348
|
+
`,r+=`Steps Executed: ${n.stepsCount}
|
|
349
|
+
`,r+=`${t}
|
|
350
|
+
`;break;case"BranchEvaluation":r=`[ BRANCH EVALUATION ]
|
|
351
|
+
`,r+=`Branch Value: ${JSON.stringify(n.branchValue)}
|
|
352
|
+
`,r+=`Has Matching Branch: ${n.hasMatchingBranch?"yes":"no"}
|
|
353
|
+
`,n.hasMatchingBranch&&(r+=`Branch Steps: ${n.branchStepsCount}
|
|
354
|
+
`),r+=`${t}
|
|
355
|
+
`;break;case"FlowComplete":r=`
|
|
356
|
+
[ AXFLOW COMPLETE ]
|
|
357
|
+
${e}
|
|
358
|
+
`,r+=`Total Time: ${Rt(n.totalExecutionTime)}
|
|
359
|
+
`,r+=`Steps Executed: ${n.stepsExecuted}
|
|
360
|
+
`,r+=`Output Fields: ${n.outputFields.join(", ")}
|
|
361
|
+
`,r+=`Final State: ${bt(n.finalState,!0)}
|
|
362
|
+
`,r+=`${e}
|
|
363
|
+
`;break;case"FlowError":r=`
|
|
364
|
+
[ AXFLOW ERROR ]
|
|
365
|
+
${e}
|
|
366
|
+
`,n.stepIndex!==void 0&&(r+=`Step: ${n.stepIndex}`,n.stepType&&(r+=` (${n.stepType})`),n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
|
|
367
|
+
`),r+=`Error: ${n.error}
|
|
368
|
+
`,n.state&&(r+=`State: ${bt(n.state,!0)}
|
|
369
|
+
`),r+=`${e}
|
|
370
|
+
`;break;default:r=JSON.stringify(n,null,2)}s(r)}},Ra=en(),Ca=s=>{let e=new Map;return{logger:s,startTiming:t=>{e.set(t,Date.now())},endTiming:t=>{let n=e.get(t);if(!n)return 0;let r=Date.now()-n;return e.delete(t),r},getCurrentTime:()=>Date.now()}};var Ct=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,i)=>{let a=n?.ai??i.mainAi,l=n?.options??i.mainOptions,p=t(o),c=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function")d=await r.forward(a,p,{...l,traceLabel:c});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}},Ir=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,i)=>{let a=n?.ai??i.mainAi,l=n?.options??i.mainOptions,p=t(o),c=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function")d=await r.forward(a,p,{...l,traceLabel:c});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}};var tn=class s{nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new It;program;nodeUsage=new Map;nodeTraces=new Map;flowLogger;timingLogger;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}async executeStepsWithLogging(e,t,n,r){let o={...t},i=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let p=this.getStepType(l,a),c=this.getStepMetadata(l,a),d=Object.keys(o);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:p,nodeName:c.nodeName,dependencies:c.dependencies,produces:c.produces,state:{...o}});let u=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{o=await l(o,n),i++;let g=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-u,A=Object.keys(o).filter(x=>!d.includes(x)),f;if(p==="execute"&&c.nodeName&&A.length>0){let x=`${c.nodeName}Result`;f=o[x]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:p,nodeName:c.nodeName,executionTime:g,state:{...o},newFields:A,result:f})}catch(m){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:m instanceof Error?m.message:String(m),stepIndex:a,stepType:p,nodeName:c.nodeName,state:{...o}}),m}}return{finalState:o,stepsExecuted:i}}getStepType(e,t){let n=e.toString();return n.includes("nodeName")||n.includes("nodeProgram")?"execute":n.includes("_parallelResults")||n.includes("processBatches")?"parallel":n.includes("branchValue")||n.includes("branches.get")||n.includes("mergeFunction")?"merge":n.includes("transform(")||n.includes("...state,")?"map":n.includes("inputValue")&&n.includes("transformFn")?"derive":n.includes("condition(")&&n.includes("iterations")?n.includes("while")?"while":"feedback":n.includes("branchSteps")||n.includes("currentState")?"branch":"other"}getStepMetadata(e,t){let r=this.executionPlanner.getExecutionPlan().steps.find(a=>a.stepIndex===t);if(r)return{nodeName:r.nodeName,dependencies:r.dependencies,produces:r.produces};let o=e.toString();return{nodeName:this.extractNodeNameFromSource(o),dependencies:[],produces:[]}}extractNodeNameFromSource(e){let t=e.match(/nodeName['"]?\s*[=:]\s*['"](\w+)['"]/);if(t)return t[1];let n=e.match(/nodeProgram\.get\(['"](\w+)['"]\)/);if(n)return n[1]}inferSignatureFromFlow(){let e=this.executionPlanner.getExecutionPlan();if(this.nodeGenerators.size===0&&e.steps.length===0)return ft().input("userInput",ft.string("User input to the flow")).output("flowOutput",ft.string("Output from the flow")).build();let t=new Set,n=new Set;for(let c of e.steps)c.produces.forEach(d=>t.add(d)),c.dependencies.forEach(d=>n.add(d));let r=new Set;for(let c of Array.from(n))t.has(c)||r.add(c);let o=new Set,i=e.steps[e.steps.length-1];if(i&&(i.type==="map"||i.type==="merge")){if(i.produces.forEach(c=>{c.startsWith("_")||o.add(c)}),i.type==="merge"&&i.produces.includes("_mergedResult"))for(let c of e.steps)c.type==="execute"&&c.produces.length>0&&c.produces.forEach(d=>o.add(d))}else for(let c of Array.from(t)){let d=!1;for(let u of e.steps)if(u.dependencies.includes(c)){d=!0;break}if(!d)if(c.endsWith("Result")){let u=c.replace("Result",""),m=this.nodeGenerators.get(u);if(m){let h=m.getSignature().getOutputFields();for(let A of h)o.add(A.name)}else o.add(c)}else o.add(c)}if(r.size===0&&o.size===0){let c=[],d=[];for(let[m,g]of Array.from(this.nodeGenerators)){let h=g.getSignature();for(let A of h.getInputFields()){let f=this.toCamelCase(`${m}_${A.name}`);c.push({name:f,type:A.type,description:A.description,isOptional:A.isOptional,isInternal:A.isInternal})}for(let A of h.getOutputFields()){let f=this.toCamelCase(`${m}_${A.name}`);d.push({name:f,type:A.type,description:A.description,isOptional:A.isOptional,isInternal:A.isInternal})}}let u=new H;return c.length>0?u.setInputFields(c):u.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),d.length>0?u.setOutputFields(d):u.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),u}let a=new H,l=[];for(let c of Array.from(r))l.push({name:c,type:{name:"string"},description:`Input field: ${c}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let p=[];for(let c of Array.from(o))c.startsWith("_")||p.push({name:c,type:{name:"string"},description:`Output field: ${c}`});return p.length===0&&p.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(p),a}constructor(e){this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10},e?.logger?this.flowLogger=e.logger:e?.debug===!0?this.flowLogger=en():this.flowLogger=void 0,this.timingLogger=this.flowLogger?Ca(this.flowLogger):void 0}static create(e){return new s(e)}ensureProgram(){let e=this.inferSignatureFromFlow();this.program=new ke(e)}setExamples(e,t){this.ensureProgram(),this.program.setExamples(e,t)}setId(e){this.ensureProgram(),this.program.setId(e)}setParentId(e){this.ensureProgram(),this.program.setParentId(e)}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return Yt(e)}resetUsage(){this.nodeUsage.clear();for(let[e,t]of Array.from(this.nodeGenerators))t&&"resetUsage"in t&&t.resetUsage()}resetTraces(){this.nodeTraces.clear()}getUsageReport(){let e={};for(let[t,n]of Array.from(this.nodeUsage))e[t]=Yt(n);return e}getTracesReport(){let e={};for(let[t,n]of Array.from(this.nodeTraces))e[t]=n;return e}async*streamingForward(e,t,n){yield{version:1,index:0,delta:await this.forward(e,t,n)}}async forward(e,t,n){let r=Date.now();this.timingLogger?.startTiming("flow-execution");let o={};try{this.resetUsage(),this.resetTraces();let i;if(Array.isArray(t)){let c=t.filter(d=>d.role==="user").pop();if(!c)throw new Error("No user message found in values array");i=c.values}else i=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),o={...i},this.flowLogger){let c=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:r,inputFields:Object.keys(i),totalSteps:c.totalSteps,parallelGroups:c.parallelGroups,maxParallelism:c.maxParallelism,autoParallelEnabled:c.autoParallelEnabled})}let a={mainAi:e,mainOptions:n?{...n,model:n.model?String(n.model):void 0}:void 0},l=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,p=0;if(l){this.executionPlanner.setInitialFields(Object.keys(i));let c=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),d=await this.executeStepsWithLogging(c,o,a,!0);o=d.finalState,p=d.stepsExecuted}else{let c=await this.executeStepsWithLogging(this.flowDefinition,o,a,!1);o=c.finalState,p=c.stepsExecuted}if(this.flowLogger){let c=this.timingLogger?.endTiming("flow-execution")??Date.now()-r;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:c,finalState:o,outputFields:Object.keys(o),stepsExecuted:p})}return o}catch(i){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:i instanceof Error?i.message:String(i),state:o}),i}}node(e,t){if(typeof t=="string"||t instanceof H){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let r=yr(n);this.nodeGenerators.set(e,r),this.ensureProgram(),this.program.register(r)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],r=async o=>{let i=await yt(n,async(a,l)=>{let p=a(o);return Promise.resolve(p)},this.autoParallelConfig.batchSize);return i[i.length-1]};if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"parallel-map")}else{let n=async r=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");let o=e(r);return Promise.resolve(o)};if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}returns(e){let t=async n=>{let r=e(n);return Promise.resolve(r)};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}r(e){return this.returns(e)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);let o=async(i,a)=>{let l=n?.ai??a.mainAi,p=n?.options??a.mainOptions,c=t(i),d=p?.traceLabel?`Node:${e} (${p.traceLabel})`:`Node:${e}`,u;if("forward"in r&&typeof r.forward=="function"){if(u=await r.forward(l,c,{...p,traceLabel:d}),"getUsage"in r&&typeof r.getUsage=="function"){let m=r.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in r&&typeof r.getTraces=="function"){let m=r.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...i,[`${e}Result`]:u}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,e,t);return this.ensureProgram(),this}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,r)=>{let o=e.predicate(n),i=e.branches.get(o);if(!i)return n;let a=n;for(let l of i)a=await l(a,r);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,r)=>{let o=await yt(e,async(i,a)=>{let l=new Ct(this.nodeGenerators);return await i(l).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:o}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,r)=>{let o=i=>{let a=i._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=r(...a),p={...i};return delete p._parallelResults,p[n]=l,p};return this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:r}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let r=this.stepLabels.get(t),o=this.flowDefinition.length;return this.flowDefinition.push(async(i,a)=>{let l=i,p=1,c=`_feedback_${t}_iterations`;for(typeof l[c]!="number"&&(l={...l,[c]:1});e(l)&&p<n;){p++,l={...l,[c]:p};for(let d=r;d<o;d++){let u=this.flowDefinition[d];u&&(l=await u(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let r=Object.assign(o=>o,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(r),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,r=t._maxIterations,o=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(i,a)=>{let l=i,p=0;for(;n(l)&&p<r;){p++;for(let c of o)l=await c(l,a)}if(p>=r&&n(l))throw new Error(`While loop exceeded maximum iterations (${r}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,r){let o=async i=>{let a=i[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let l;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let p=r?.batchSize||this.autoParallelConfig.batchSize;l=await yt(a,async(c,d)=>n(c,d,i),p)}else l=a.map((p,c)=>n(p,c,i));else l=n(a,void 0,i);return{...i,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:r?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}nodeExtended(e,t,n){let o=typeof t=="string"?H.create(t):t;if(n.prependInputs)for(let i of n.prependInputs)o=o.prependInputField(i.name,i.type);if(n.appendInputs)for(let i of n.appendInputs)o=o.appendInputField(i.name,i.type);if(n.prependOutputs)for(let i of n.prependOutputs)o=o.prependOutputField(i.name,i.type);if(n.appendOutputs)for(let i of n.appendOutputs)o=o.appendOutputField(i.name,i.type);return this.node(e,o)}nx(e,t,n){return this.nodeExtended(e,t,n)}mapOutput(e){let t=async n=>{let r=e(n);return{...n,...r}};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}mo(e){return this.mapOutput(e)}};function br(s){return tn.create(s)}var Rr=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let o=t.map(p=>`${p.hostPath}:${p.containerPath}`);n||await this.pullImage(e);let i={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:o},Labels:{}};r&&(i.Labels["com.example.tag"]=r);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new Error(`Failed to create container: ${a.statusText}`);let l=await a.json();return this.containerId=l.Id,l}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let i=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===r);if(i&&i.length>0){let l=Math.floor(Math.random()*i.length),p=i[l];if(p)return await this.connectToContainer(p.Id),{Id:p.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:r})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let r=[],o=await this.listContainers(!0),i=e?o.filter(a=>a.Labels["com.example.tag"]===e):o;for(let a of i){if(a.State.Status==="running"){let l=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!l.ok){console.warn(`Failed to stop container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"removed"})}}return r}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(console.log("Executing command:",e),!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let r=await n.json(),o=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!o.ok)throw new Error(`Failed to start exec instance: ${o.statusText}`);return await o.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var Cr=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let r=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!r)throw new Error("Failed to embed text");return this.func.length===2?this.func(r,t):this.func(r)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var Tr=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(o=>o.name===t.name),r=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:r,func:async o=>{let{result:i}=await this.sendRequest("tools/call",{name:t.name,arguments:o});return i}}})}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((i,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),r=await Promise.race([t,n]),{result:o}=r;if(typeof o!="object"||o===null||Object.keys(o).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(o)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=ne(),r={jsonrpc:"2.0",id:n,method:e,params:t},o=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(r).then(p=>{if(this.activeRequests.delete(n),p!==null&&typeof p=="object"&&"error"in p){let c=p;l(new Error(`RPC Error ${c.error.code}: ${c.error.message}`))}else p!==null&&typeof p=="object"&&"result"in p?a({result:p.result}):l(new Error("Invalid response no result or error"))}).catch(p=>{this.activeRequests.delete(n),l(p)})}),{result:i}=await o;return{id:n,result:i}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:r}=this.options;if(r){let o={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(o)}await this.transport.sendNotification(n)}};var wr=class{endpoint=null;sseUrl;eventSource;constructor(e){this.sseUrl=e}async connect(){return new Promise((e,t)=>{this.eventSource=new EventSource(this.sseUrl),this.eventSource.addEventListener("endpoint",n=>{try{let o=JSON.parse(n.data);if(!o.uri)throw new Error("Endpoint URI missing in SSE event data");this.endpoint=o.uri,e()}catch(r){t(r)}}),this.eventSource.onerror=()=>{t(new Error("Failed to establish SSE connection"))}})}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`HTTP error ${t.status}: ${t.statusText}`);return t.json()}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}},vr=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers},t?.authorization&&(this.customHeaders.Authorization=t.authorization)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),r=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(r.toString()),this.eventSource.onopen=()=>{e()},this.eventSource.onmessage=o=>{try{let i=JSON.parse(o.data);this.messageHandler&&this.messageHandler(i)}catch(i){console.error("Failed to parse SSE message:",i)}},this.eventSource.onerror=()=>{t(new Error("Failed to establish SSE connection"))}})}async openListeningStreamWithFetch(e){let t=await fetch(this.mcpEndpoint,{method:"GET",headers:e});if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),r=new TextDecoder,o="",i=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}o+=r.decode(l,{stream:!0});let p=o.split(`
|
|
371
|
+
`);o=p.pop()||"";for(let c of p)if(c.startsWith("data: ")){let d=c.slice(6);if(d==="[DONE]")return;try{let u=JSON.parse(d);this.messageHandler&&this.messageHandler(u)}catch(u){console.error("Failed to parse SSE data:",u)}}await i()}catch(a){throw n.releaseLock(),a}};await i()}async send(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw n.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${n.status}: ${n.statusText}`);let r=n.headers.get("Mcp-Session-Id");r&&(this.sessionId=r);let o=n.headers.get("Content-Type");if(o?.includes("text/event-stream"))return this.handleSSEResponse(n,e.id);if(o?.includes("application/json"))return n.json();throw new Error(`Unexpected content type: ${o}`)}async handleSSEResponse(e,t){return new Promise((n,r)=>{let o=e.body?.getReader();if(!o){r(new Error("No response body reader available"));return}let i=new TextDecoder,a="",l=async()=>{try{let{done:p,value:c}=await o.read();if(p){o.releaseLock();return}a+=i.decode(c,{stream:!0});let d=a.split(`
|
|
372
|
+
`);a=d.pop()||"";for(let u of d)if(u.startsWith("data: ")){let m=u.slice(6);if(m==="[DONE]")return;try{let g=JSON.parse(m);if("id"in g&&g.id===t){n(g);return}this.messageHandler&&this.messageHandler(g)}catch(g){console.error("Failed to parse SSE data:",g)}}await l()}catch(p){o.releaseLock(),r(p)}};l().catch(r)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw n.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${n.status}: ${n.statusText}`);n.status!==202&&console.warn(`Unexpected status for notification: ${n.status}`)}async terminateSession(){if(this.sessionId)try{let e=this.buildHeaders({});(await fetch(this.mcpEndpoint,{method:"DELETE",headers:e})).status===405&&console.info("Server does not support explicit session termination")}catch(e){console.error("Failed to terminate session:",e)}finally{this.sessionId=void 0}}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}};function gp(s,e,t,n,r){let o={...s};if(o.parameters){let i=o.parameters.properties?Object.keys(o.parameters.properties):[],l=t.filter(p=>i.includes(p)).filter(p=>p!=="model").filter(p=>!r.excludeFieldsFromPassthrough.includes(p));if(l.length>0){o.parameters=fp(o.parameters,l);let p=o.func;o.func=async(c,d)=>{let u={};if(Array.isArray(e)){let g=e.filter(h=>h.role==="user").pop();g&&(u=va(g.values,l))}else u=va(e,l);let m={...c,...u};return await p(m,d)}}return o}return n&&!r.disableSmartModelRouting&&r.canConfigureSmartModelRouting&&(o.parameters=Sa(o.parameters,n)),o}var Ta=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),wa=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),nn=class s{ai;program;functions;agents;disableSmartModelRouting;excludeFieldsFromPassthrough;debug;name;func;constructor({ai:e,name:t,description:n,definition:r,signature:o,agents:i,functions:a},l){let{disableSmartModelRouting:p,excludeFieldsFromPassthrough:c,debug:d}=l??{};if(this.ai=e,this.agents=i,this.functions=a,this.disableSmartModelRouting=p,this.excludeFieldsFromPassthrough=c??[],this.debug=d,!t||t.length<5)throw new Error("Agent name must be at least 10 characters (more descriptive)");if(!n||n.length<20)throw Ta;if(r&&r.length<100)throw wa;this.program=new ee(o,{...l,description:r??n});for(let m of i??[])this.program.register(m);this.name=t,this.func={name:hp(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let u=e?.getModelList();u&&!this.disableSmartModelRouting&&(this.func.parameters=Sa(this.func.parameters,u))}static create(e,t){let n=H.create(e),{ai:r,name:o,description:i,definition:a,agents:l,functions:p,...c}=t;return new s({ai:r,name:o,description:i,definition:a,signature:n,agents:l,functions:p},c)}setExamples(e,t){this.program.setExamples(e,t)}setId(e){this.program.setId(e)}setParentId(e){this.program.setParentId(e)}getTraces(){return this.program.getTraces()}setDemos(e){this.program.setDemos(e)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){let e=this.forward.bind(this),t=async(n,r)=>{let{model:o,...i}=n,a=this.ai??r?.ai;if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,i,{...r,model:o}),c=this.program.getSignature().getOutputFields();return Object.keys(l).map(u=>{let m=c.find(g=>g.name===u);return m?`${m.title}: ${l[u]}`:`${u}: ${l[u]}`}).join(`
|
|
373
|
+
`)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let r=this.ai??e,o=r?.getModelList(),a=this.program.getSignature().getInputFields().map(d=>d.name),l=this.getDebug(r,n),p=this.agents?.map(d=>{let u=d.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:u.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:u.canConfigureSmartModelRouting};return gp(d.getFunction(),t,a,o,m)}),c=[...n?.functions??this.functions??[],...p??[]];return{ai:r,functions:c,debug:l}}async forward(e,t,n){let{ai:r,functions:o,debug:i}=this.init(e,t,n);return await this.program.forward(r,t,{...n,debug:i,functions:o})}async*streamingForward(e,t,n){let{ai:r,functions:o,debug:i}=this.init(e,t,n);return yield*this.program.streamingForward(r,t,{...n,debug:i,functions:o})}setDescription(e){if(!e||e.length<20)throw Ta;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw wa;this.program.setDescription(e),this.func.description=e}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}getDebug(e,t){return t?.debug??this.debug??e?.getOptions()?.debug??!1}};function hp(s){return s.split(/[^a-zA-Z0-9]/).map((n,r)=>{let o=n.toLowerCase();return r>0&&o&&o[0]?o[0].toUpperCase()+o.slice(1):o}).join("")}function Sa(s,e){let t=s?structuredClone(s):{type:"object",properties:{},required:[]};if(t.properties?.model)return t;let n={type:"string",enum:e.map(i=>i.key),description:`The AI model to use for this function call. Available options: ${e.map(i=>`\`${i.key}\` ${i.description}`).join(", ")}`},r={...t.properties??{},model:n},o=[...t.required??[],"model"];return{...t,properties:r,required:o}}function fp(s,e){let t=structuredClone(s);if(t.properties)for(let n of e)delete t.properties[n];if(Array.isArray(t.required)){let n=t.required.filter(r=>!e.includes(r));Object.defineProperty(t,"required",{value:n,writable:!0,configurable:!0})}return t}function va(s,e){let t={};for(let n of e)n in s&&(t[n]=s[n]);return t}function Ma(s,e){let t=H.create(s),{ai:n,name:r,description:o,definition:i,agents:a,functions:l,...p}=e;return new nn({ai:n,name:r,description:o,definition:i,signature:t,agents:a,functions:l},p)}var Oa=(s,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,o=e?.qualityTarget??.85,i=e?.disableQualityHealing??!1;return br({logger:e?.logger,debug:e?.debug}).node("queryGenerator","originalQuestion:string, previousContext?:string -> searchQuery:string, queryReasoning:string").node("contextualizer","retrievedDocument:string, accumulatedContext?:string -> enhancedContext:string").node("qualityAssessor","currentContext:string, originalQuestion:string -> completenessScore:number, missingAspects:string[]").node("questionDecomposer","complexQuestion:string -> subQuestions:string[], decompositionReason:string").node("evidenceSynthesizer","collectedEvidence:string[], originalQuestion:string -> synthesizedEvidence:string, evidenceGaps:string[]").node("gapAnalyzer","synthesizedEvidence:string, evidenceGaps:string[], originalQuestion:string -> needsMoreInfo:boolean, focusedQueries:string[]").node("answerGenerator","finalContext:string, originalQuestion:string -> comprehensiveAnswer:string, confidenceLevel:number").node("queryRefiner","originalQuestion:string, currentContext:string, missingAspects:string[] -> refinedQuery:string").node("qualityValidator","generatedAnswer:string, userQuery:string -> qualityScore:number, issues:string[]").node("answerHealer","originalAnswer:string, healingDocument:string, issues?:string[] -> healedAnswer:string").map(a=>({...a,maxHops:t,qualityThreshold:n,maxIterations:r,qualityTarget:o,disableQualityHealing:i,currentHop:0,accumulatedContext:"",retrievedContexts:[],completenessScore:0,searchQuery:a.originalQuestion,shouldContinue:!0,iteration:0,allEvidence:[],evidenceSources:[],needsMoreInfo:!0,healingAttempts:0,currentQuality:0,shouldContinueHealing:!0,currentAnswer:"",currentIssues:[]})).while(a=>a.currentHop<a.maxHops&&a.completenessScore<a.qualityThreshold&&a.shouldContinue).map(a=>({...a,currentHop:a.currentHop+1})).execute("queryGenerator",a=>({originalQuestion:a.originalQuestion,previousContext:a.accumulatedContext||void 0})).map(async a=>{let l=a.queryGeneratorResult?.searchQuery||a.searchQuery||a.originalQuestion,p=await s(l);return{...a,retrievalResult:{retrievedDocument:p,retrievalConfidence:.9}}}).execute("contextualizer",a=>({retrievedDocument:a.retrievalResult.retrievedDocument,accumulatedContext:a.accumulatedContext||void 0})).execute("qualityAssessor",a=>({currentContext:a.contextualizerResult.enhancedContext,originalQuestion:a.originalQuestion})).map(a=>({...a,accumulatedContext:a.contextualizerResult.enhancedContext,retrievedContexts:[...a.retrievedContexts,a.retrievalResult.retrievedDocument],completenessScore:a.qualityAssessorResult.completenessScore,searchQuery:a.queryGeneratorResult.searchQuery,shouldContinue:a.qualityAssessorResult.completenessScore<a.qualityThreshold})).branch(a=>a.shouldContinue&&a.currentHop<a.maxHops).when(!0).execute("queryRefiner",a=>({originalQuestion:a.originalQuestion,currentContext:a.accumulatedContext,missingAspects:a.qualityAssessorResult.missingAspects})).map(a=>({...a,searchQuery:a.queryRefinerResult?.refinedQuery||a.searchQuery})).when(!1).map(a=>a).merge().endWhile().map(a=>({...a,allEvidence:a.retrievedContexts.length>0?a.retrievedContexts:[]})).while(a=>a.iteration<a.maxIterations&&a.needsMoreInfo).map(a=>({...a,iteration:a.iteration+1})).branch(a=>a.iteration===1).when(!0).execute("questionDecomposer",a=>({complexQuestion:a.originalQuestion})).map(a=>({...a,currentQueries:a.questionDecomposerResult.subQuestions})).when(!1).map(a=>({...a,currentQueries:a.gapAnalyzerResult?.focusedQueries||[]})).merge().map(async a=>{let l=a.currentQueries||[],p=l.length>0?await Promise.all(l.filter(Boolean).map(c=>s(c))):[];return{...a,retrievalResults:p}}).execute("evidenceSynthesizer",a=>{let l=[...a.allEvidence||[],...a.retrievalResults||[]].filter(Boolean);return{collectedEvidence:l.length>0?l:["No evidence collected yet"],originalQuestion:a.originalQuestion}}).execute("gapAnalyzer",a=>({synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence,evidenceGaps:a.evidenceSynthesizerResult.evidenceGaps,originalQuestion:a.originalQuestion})).map(a=>({...a,allEvidence:[...a.allEvidence,...a.retrievalResults],evidenceSources:[...a.evidenceSources,`Iteration ${a.iteration} sources`],needsMoreInfo:a.gapAnalyzerResult.needsMoreInfo,synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence})).endWhile().execute("answerGenerator",a=>({finalContext:a.accumulatedContext||a.synthesizedEvidence||a.allEvidence.join(`
|
|
374
|
+
`),originalQuestion:a.originalQuestion})).branch(a=>!a.disableQualityHealing).when(!0).execute("qualityValidator",a=>({generatedAnswer:a.answerGeneratorResult.comprehensiveAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).while(a=>a.healingAttempts<3&&a.shouldContinueHealing).map(a=>({...a,healingAttempts:a.healingAttempts+1})).map(async a=>{let l=a.currentIssues||[],p=l.length>0?`${a.originalQuestion} addressing issues: ${l.join(", ")}`:`${a.originalQuestion} quality improvement`,c=await s(p);return{...a,healingResult:{healingDocument:c}}}).execute("answerHealer",a=>({originalAnswer:a.currentAnswer,healingDocument:a.healingResult.healingDocument,issues:a.currentIssues})).execute("qualityValidator",a=>({generatedAnswer:a.answerHealerResult.healedAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerHealerResult.healedAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).endWhile().when(!1).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:1,currentIssues:[],shouldContinueHealing:!1})).merge().returns(a=>({finalAnswer:a.currentAnswer,totalHops:a.currentHop,retrievedContexts:a.retrievedContexts,iterationCount:a.iteration,healingAttempts:a.healingAttempts,qualityAchieved:a.currentQuality}))};return $a(Ap);})();
|
|
293
375
|
//# sourceMappingURL=index.global.js.map
|