@ax-llm/ax 14.0.40 → 14.0.42
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 +6 -6
- package/index.cjs.map +1 -1
- package/index.d.cts +20 -1
- package/index.d.ts +20 -1
- package/index.global.js +8 -8
- package/index.global.js.map +1 -1
- package/index.js +15 -15
- package/index.js.map +1 -1
- package/package.json +1 -1
package/index.global.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ax=(()=>{var Mc=Object.create;var yr=Object.defineProperty;var Ec=Object.getOwnPropertyDescriptor;var Pc=Object.getOwnPropertyNames;var Fc=Object.getPrototypeOf,_c=Object.prototype.hasOwnProperty;var Dc=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var br=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Nc=(s,e)=>{for(var t in e)yr(s,t,{get:e[t],enumerable:!0})},Si=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pc(e))!_c.call(s,r)&&r!==t&&yr(s,r,{get:()=>e[r],enumerable:!(n=Ec(e,r))||n.enumerable});return s};var kn=(s,e,t)=>(t=s!=null?Mc(Fc(s)):{},Si(e||!s||!s.__esModule?yr(t,"default",{value:s,enumerable:!0}):t,s)),$c=s=>Si(yr({},"__esModule",{value:!0}),s);var Rl=br((Zs,Xs)=>{"use strict";(function(s,e){typeof Zs=="object"&&typeof Xs<"u"?Xs.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs=e()})(Zs,function(){"use strict";var s=1e3,e=6e4,t=36e5,n="millisecond",r="second",o="minute",i="hour",a="day",l="week",c="month",u="quarter",d="year",p="date",m="Invalid Date",h=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,A=/\[([^\]]+)]|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,g={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(w){var v=["th","st","nd","rd"],I=w%100;return"["+w+(v[(I-20)%10]||v[I]||v[0])+"]"}},f=function(w,v,I){var S=String(w);return!S||S.length>=v?w:""+Array(v+1-S.length).join(I)+w},x={s:f,z:function(w){var v=-w.utcOffset(),I=Math.abs(v),S=Math.floor(I/60),C=I%60;return(v<=0?"+":"-")+f(S,2,"0")+":"+f(C,2,"0")},m:function w(v,I){if(v.date()<I.date())return-w(I,v);var S=12*(I.year()-v.year())+(I.month()-v.month()),C=v.clone().add(S,c),M=I-C<0,_=v.clone().add(S+(M?-1:1),c);return+(-(S+(I-C)/(M?C-_:_-C))||0)},a:function(w){return w<0?Math.ceil(w)||0:Math.floor(w)},p:function(w){return{M:c,y:d,w:l,d:a,D:p,h:i,m:o,s:r,ms:n,Q:u}[w]||String(w||"").toLowerCase().replace(/s$/,"")},u:function(w){return w===void 0}},b="en",T={};T[b]=g;var E="$isDayjsObject",R=function(w){return w instanceof F||!(!w||!w[E])},k=function w(v,I,S){var C;if(!v)return b;if(typeof v=="string"){var M=v.toLowerCase();T[M]&&(C=M),I&&(T[M]=I,C=M);var _=v.split("-");if(!C&&_.length>1)return w(_[0])}else{var D=v.name;T[D]=v,C=D}return!S&&C&&(b=C),C||!S&&b},y=function(w,v){if(R(w))return w.clone();var I=typeof v=="object"?v:{};return I.date=w,I.args=arguments,new F(I)},O=x;O.l=k,O.i=R,O.w=function(w,v){return y(w,{locale:v.$L,utc:v.$u,x:v.$x,$offset:v.$offset})};var F=function(){function w(I){this.$L=k(I.locale,null,!0),this.parse(I),this.$x=this.$x||I.x||{},this[E]=!0}var v=w.prototype;return v.parse=function(I){this.$d=function(S){var C=S.date,M=S.utc;if(C===null)return new Date(NaN);if(O.u(C))return new Date;if(C instanceof Date)return new Date(C);if(typeof C=="string"&&!/Z$/i.test(C)){var _=C.match(h);if(_){var D=_[2]-1||0,z=(_[7]||"0").substring(0,3);return M?new Date(Date.UTC(_[1],D,_[3]||1,_[4]||0,_[5]||0,_[6]||0,z)):new Date(_[1],D,_[3]||1,_[4]||0,_[5]||0,_[6]||0,z)}}return new Date(C)}(I),this.init()},v.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()},v.$utils=function(){return O},v.isValid=function(){return this.$d.toString()!==m},v.isSame=function(I,S){var C=y(I);return this.startOf(S)<=C&&C<=this.endOf(S)},v.isAfter=function(I,S){return y(I)<this.startOf(S)},v.isBefore=function(I,S){return this.endOf(S)<y(I)},v.$g=function(I,S,C){return O.u(I)?this[S]:this.set(C,I)},v.unix=function(){return Math.floor(this.valueOf()/1e3)},v.valueOf=function(){return this.$d.getTime()},v.startOf=function(I,S){var C=this,M=!!O.u(S)||S,_=O.p(I),D=function(Oe,ue){var ke=O.w(C.$u?Date.UTC(C.$y,ue,Oe):new Date(C.$y,ue,Oe),C);return M?ke:ke.endOf(a)},z=function(Oe,ue){return O.w(C.toDate()[Oe].apply(C.toDate("s"),(M?[0,0,0,0]:[23,59,59,999]).slice(ue)),C)},j=this.$W,Q=this.$M,le=this.$D,xe="set"+(this.$u?"UTC":"");switch(_){case d:return M?D(1,0):D(31,11);case c:return M?D(1,Q):D(0,Q+1);case l:var _e=this.$locale().weekStart||0,We=(j<_e?j+7:j)-_e;return D(M?le-We:le+(6-We),Q);case a:case p:return z(xe+"Hours",0);case i:return z(xe+"Minutes",1);case o:return z(xe+"Seconds",2);case r:return z(xe+"Milliseconds",3);default:return this.clone()}},v.endOf=function(I){return this.startOf(I,!1)},v.$set=function(I,S){var C,M=O.p(I),_="set"+(this.$u?"UTC":""),D=(C={},C[a]=_+"Date",C[p]=_+"Date",C[c]=_+"Month",C[d]=_+"FullYear",C[i]=_+"Hours",C[o]=_+"Minutes",C[r]=_+"Seconds",C[n]=_+"Milliseconds",C)[M],z=M===a?this.$D+(S-this.$W):S;if(M===c||M===d){var j=this.clone().set(p,1);j.$d[D](z),j.init(),this.$d=j.set(p,Math.min(this.$D,j.daysInMonth())).$d}else D&&this.$d[D](z);return this.init(),this},v.set=function(I,S){return this.clone().$set(I,S)},v.get=function(I){return this[O.p(I)]()},v.add=function(I,S){var C,M=this;I=Number(I);var _=O.p(S),D=function(Q){var le=y(M);return O.w(le.date(le.date()+Math.round(Q*I)),M)};if(_===c)return this.set(c,this.$M+I);if(_===d)return this.set(d,this.$y+I);if(_===a)return D(1);if(_===l)return D(7);var z=(C={},C[o]=e,C[i]=t,C[r]=s,C)[_]||1,j=this.$d.getTime()+I*z;return O.w(j,this)},v.subtract=function(I,S){return this.add(-1*I,S)},v.format=function(I){var S=this,C=this.$locale();if(!this.isValid())return C.invalidDate||m;var M=I||"YYYY-MM-DDTHH:mm:ssZ",_=O.z(this),D=this.$H,z=this.$m,j=this.$M,Q=C.weekdays,le=C.months,xe=C.meridiem,_e=function(ue,ke,De,Le){return ue&&(ue[ke]||ue(S,M))||De[ke].slice(0,Le)},We=function(ue){return O.s(D%12||12,ue,"0")},Oe=xe||function(ue,ke,De){var Le=ue<12?"AM":"PM";return De?Le.toLowerCase():Le};return M.replace(A,function(ue,ke){return ke||function(De){switch(De){case"YY":return String(S.$y).slice(-2);case"YYYY":return O.s(S.$y,4,"0");case"M":return j+1;case"MM":return O.s(j+1,2,"0");case"MMM":return _e(C.monthsShort,j,le,3);case"MMMM":return _e(le,j);case"D":return S.$D;case"DD":return O.s(S.$D,2,"0");case"d":return String(S.$W);case"dd":return _e(C.weekdaysMin,S.$W,Q,2);case"ddd":return _e(C.weekdaysShort,S.$W,Q,3);case"dddd":return Q[S.$W];case"H":return String(D);case"HH":return O.s(D,2,"0");case"h":return We(1);case"hh":return We(2);case"a":return Oe(D,z,!0);case"A":return Oe(D,z,!1);case"m":return String(z);case"mm":return O.s(z,2,"0");case"s":return String(S.$s);case"ss":return O.s(S.$s,2,"0");case"SSS":return O.s(S.$ms,3,"0");case"Z":return _}return null}(ue)||_.replace(":","")})},v.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},v.diff=function(I,S,C){var M,_=this,D=O.p(S),z=y(I),j=(z.utcOffset()-this.utcOffset())*e,Q=this-z,le=function(){return O.m(_,z)};switch(D){case d:M=le()/12;break;case c:M=le();break;case u:M=le()/3;break;case l:M=(Q-j)/6048e5;break;case a:M=(Q-j)/864e5;break;case i:M=Q/t;break;case o:M=Q/e;break;case r:M=Q/s;break;default:M=Q}return C?M:O.a(M)},v.daysInMonth=function(){return this.endOf(c).$D},v.$locale=function(){return T[this.$L]},v.locale=function(I,S){if(!I)return this.$L;var C=this.clone(),M=k(I,S,!0);return M&&(C.$L=M),C},v.clone=function(){return O.w(this.$d,this)},v.toDate=function(){return new Date(this.valueOf())},v.toJSON=function(){return this.isValid()?this.toISOString():null},v.toISOString=function(){return this.$d.toISOString()},v.toString=function(){return this.$d.toUTCString()},w}(),P=F.prototype;return y.prototype=P,[["$ms",n],["$s",r],["$m",o],["$H",i],["$W",a],["$M",c],["$y",d],["$D",p]].forEach(function(w){P[w[1]]=function(v){return this.$g(v,w[0],w[1])}}),y.extend=function(w,v){return w.$i||(w(v,F,y),w.$i=!0),y},y.locale=k,y.isDayjs=R,y.unix=function(w){return y(1e3*w)},y.en=T[b],y.Ls=T,y.p={},y})});var wl=br((ei,ti)=>{"use strict";(function(s,e){typeof ei=="object"&&typeof ti<"u"?ti.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_customParseFormat=e()})(ei,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(h){return(h=+h)+(h>68?1900:2e3)},l=function(h){return function(A){this[h]=+A}},c=[/[+-]\d\d:?(\d\d)?|Z/,function(h){(this.zone||(this.zone={})).offset=function(A){if(!A||A==="Z")return 0;var g=A.match(/([+-]|\d\d)/g),f=60*g[1]+(+g[2]||0);return f===0?0:g[0]==="+"?-f:f}(h)}],u=function(h){var A=i[h];return A&&(A.indexOf?A:A.s.concat(A.f))},d=function(h,A){var g,f=i.meridiem;if(f){for(var x=1;x<=24;x+=1)if(h.indexOf(f(x,0,A))>-1){g=x>12;break}}else g=h===(A?"pm":"PM");return g},p={A:[o,function(h){this.afternoon=d(h,!1)}],a:[o,function(h){this.afternoon=d(h,!0)}],Q:[t,function(h){this.month=3*(h-1)+1}],S:[t,function(h){this.milliseconds=100*+h}],SS:[n,function(h){this.milliseconds=10*+h}],SSS:[/\d{3}/,function(h){this.milliseconds=+h}],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(h){var A=i.ordinal,g=h.match(/\d+/);if(this.day=g[0],A)for(var f=1;f<=31;f+=1)A(f).replace(/\[|\]/g,"")===h&&(this.day=f)}],w:[r,l("week")],ww:[n,l("week")],M:[r,l("month")],MM:[n,l("month")],MMM:[o,function(h){var A=u("months"),g=(u("monthsShort")||A.map(function(f){return f.slice(0,3)})).indexOf(h)+1;if(g<1)throw new Error;this.month=g%12||g}],MMMM:[o,function(h){var A=u("months").indexOf(h)+1;if(A<1)throw new Error;this.month=A%12||A}],Y:[/[+-]?\d+/,l("year")],YY:[n,function(h){this.year=a(h)}],YYYY:[/\d{4}/,l("year")],Z:c,ZZ:c};function m(h){var A,g;A=h,g=i&&i.formats;for(var f=(h=A.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(y,O,F){var P=F&&F.toUpperCase();return O||g[F]||s[F]||g[P].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(w,v,I){return v||I.slice(1)})})).match(e),x=f.length,b=0;b<x;b+=1){var T=f[b],E=p[T],R=E&&E[0],k=E&&E[1];f[b]=k?{regex:R,parser:k}:T.replace(/^\[|\]$/g,"")}return function(y){for(var O={},F=0,P=0;F<x;F+=1){var w=f[F];if(typeof w=="string")P+=w.length;else{var v=w.regex,I=w.parser,S=y.slice(P),C=v.exec(S)[0];I.call(O,C),y=y.replace(C,"")}}return function(M){var _=M.afternoon;if(_!==void 0){var D=M.hours;_?D<12&&(M.hours+=12):D===12&&(M.hours=0),delete M.afternoon}}(O),O}}return function(h,A,g){g.p.customParseFormat=!0,h&&h.parseTwoDigitYear&&(a=h.parseTwoDigitYear);var f=A.prototype,x=f.parse;f.parse=function(b){var T=b.date,E=b.utc,R=b.args;this.$u=E;var k=R[1];if(typeof k=="string"){var y=R[2]===!0,O=R[3]===!0,F=y||O,P=R[2];O&&(P=R[2]),i=this.$locale(),!y&&P&&(i=g.Ls[P]),this.$d=function(S,C,M,_){try{if(["x","X"].indexOf(C)>-1)return new Date((C==="X"?1e3:1)*S);var D=m(C)(S),z=D.year,j=D.month,Q=D.day,le=D.hours,xe=D.minutes,_e=D.seconds,We=D.milliseconds,Oe=D.zone,ue=D.week,ke=new Date,De=Q||(z||j?1:ke.getDate()),Le=z||ke.getFullYear(),gt=0;z&&!j||(gt=j>0?j-1:ke.getMonth());var ht,N=le||0,U=xe||0,q=_e||0,H=We||0;return Oe?new Date(Date.UTC(Le,gt,De,N,U,q,H+60*Oe.offset*1e3)):M?new Date(Date.UTC(Le,gt,De,N,U,q,H)):(ht=new Date(Le,gt,De,N,U,q,H),ue&&(ht=_(ht).week(ue).toDate()),ht)}catch{return new Date("")}}(T,k,E,g),this.init(),P&&P!==!0&&(this.$L=this.locale(P).$L),F&&T!=this.format(k)&&(this.$d=new Date("")),i={}}else if(k instanceof Array)for(var w=k.length,v=1;v<=w;v+=1){R[1]=k[v-1];var I=g.apply(this,R);if(I.isValid()){this.$d=I.$d,this.$L=I.$L,this.init();break}v===w&&(this.$d=new Date(""))}else x.call(this,b)}}})});var vl=br((ni,ri)=>{"use strict";(function(s,e){typeof ni=="object"&&typeof ri<"u"?ri.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_timezone=e()})(ni,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(u,d,p){p===void 0&&(p={});var m=new Date(u),h=function(A,g){g===void 0&&(g={});var f=g.timeZoneName||"short",x=A+"|"+f,b=e[x];return b||(b=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:A,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:f}),e[x]=b),b}(d,p);return h.formatToParts(m)},a=function(u,d){for(var p=i(u,d),m=[],h=0;h<p.length;h+=1){var A=p[h],g=A.type,f=A.value,x=s[g];x>=0&&(m[x]=parseInt(f,10))}var b=m[3],T=b===24?0:b,E=m[0]+"-"+m[1]+"-"+m[2]+" "+T+":"+m[4]+":"+m[5]+":000",R=+u;return(r.utc(E).valueOf()-(R-=R%1e3))/6e4},l=n.prototype;l.tz=function(u,d){u===void 0&&(u=o);var p,m=this.utcOffset(),h=this.toDate(),A=h.toLocaleString("en-US",{timeZone:u}),g=Math.round((h-new Date(A))/1e3/60),f=15*-Math.round(h.getTimezoneOffset()/15)-g;if(!Number(f))p=this.utcOffset(0,d);else if(p=r(A,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(f,!0),d){var x=p.utcOffset();p=p.add(m-x,"minute")}return p.$x.$timezone=u,p},l.offsetName=function(u){var d=this.$x.$timezone||r.tz.guess(),p=i(this.valueOf(),d,{timeZoneName:u}).find(function(m){return m.type.toLowerCase()==="timezonename"});return p&&p.value};var c=l.startOf;l.startOf=function(u,d){if(!this.$x||!this.$x.$timezone)return c.call(this,u,d);var p=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"),{locale:this.$L});return c.call(p,u,d).tz(this.$x.$timezone,!0)},r.tz=function(u,d,p){var m=p&&d,h=p||d||o,A=a(+r(),h);if(typeof u!="string")return r(u).tz(h);var g=function(T,E,R){var k=T-60*E*1e3,y=a(k,R);if(E===y)return[k,E];var O=a(k-=60*(y-E)*1e3,R);return y===O?[k,y]:[T-60*Math.min(y,O)*1e3,Math.max(y,O)]}(r.utc(u,m).valueOf(),A,h),f=g[0],x=g[1],b=r(f).utcOffset(x);return b.$x.$timezone=h,b},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(u){o=u}}})});var Sl=br((oi,si)=>{"use strict";(function(s,e){typeof oi=="object"&&typeof si<"u"?si.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_utc=e()})(oi,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 h={date:m,utc:!0,args:arguments};return new r(h)},i.utc=function(m){var h=o(this.toDate(),{locale:this.$L,utc:!0});return m?h.add(this.utcOffset(),s):h},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 c=i.utcOffset;i.utcOffset=function(m,h){var A=this.$utils().u;if(A(m))return this.$u?0:A(this.$offset)?c.call(this):this.$offset;if(typeof m=="string"&&(m=function(b){b===void 0&&(b="");var T=b.match(e);if(!T)return null;var E=(""+T[0]).match(t)||["-",0,0],R=E[0],k=60*+E[1]+ +E[2];return k===0?0:R==="+"?k:-k}(m),m===null))return this;var g=Math.abs(m)<=16?60*m:m,f=this;if(h)return f.$offset=g,f.$u=m===0,f;if(m!==0){var x=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(f=this.local().add(g+x,s)).$offset=g,f.$x.$localOffset=x}else f=this.utc();return f};var u=i.format;i.format=function(m){var h=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return u.call(this,h)},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 p=i.diff;i.diff=function(m,h,A){if(m&&this.$u===m.$u)return p.call(this,m,h,A);var g=this.local(),f=o(m).local();return p.call(g,f,h,A)}}})});var Mp={};Nc(Mp,{AxACE:()=>Uo,AxACEOptimizedProgram:()=>pr,AxAI:()=>Zn,AxAIAnthropic:()=>Ht,AxAIAnthropicModel:()=>Nn,AxAIAnthropicVertexModel:()=>Pr,AxAIAzureOpenAI:()=>Yt,AxAICohere:()=>Qt,AxAICohereEmbedModel:()=>Bn,AxAICohereModel:()=>Un,AxAIDeepSeek:()=>Zt,AxAIDeepSeekModel:()=>jn,AxAIGoogleGemini:()=>Xt,AxAIGoogleGeminiEmbedModel:()=>jr,AxAIGoogleGeminiEmbedTypes:()=>Os,AxAIGoogleGeminiModel:()=>zn,AxAIGoogleGeminiSafetyCategory:()=>zr,AxAIGoogleGeminiSafetyThreshold:()=>qr,AxAIGrok:()=>dn,AxAIGrokEmbedModels:()=>Bs,AxAIGrokModel:()=>Qn,AxAIGroq:()=>tn,AxAIGroqModel:()=>qn,AxAIHuggingFace:()=>nn,AxAIHuggingFaceModel:()=>Jr,AxAIMistral:()=>rn,AxAIMistralEmbedModels:()=>Fs,AxAIMistralModel:()=>Hn,AxAIOllama:()=>on,AxAIOpenAI:()=>Jt,AxAIOpenAIBase:()=>he,AxAIOpenAIEmbedModel:()=>Kt,AxAIOpenAIModel:()=>Gn,AxAIOpenAIResponses:()=>an,AxAIOpenAIResponsesBase:()=>Kn,AxAIOpenAIResponsesImpl:()=>sn,AxAIOpenAIResponsesModel:()=>Wt,AxAIOpenRouter:()=>ln,AxAIRefusalError:()=>de,AxAIReka:()=>cn,AxAIRekaModel:()=>Vn,AxAIServiceAbortedError:()=>Gt,AxAIServiceAuthenticationError:()=>yt,AxAIServiceError:()=>we,AxAIServiceNetworkError:()=>rt,AxAIServiceResponseError:()=>pt,AxAIServiceStatusError:()=>kt,AxAIServiceStreamTerminatedError:()=>Qe,AxAIServiceTimeoutError:()=>Mt,AxAITogether:()=>un,AxAIWebLLM:()=>pn,AxAIWebLLMModel:()=>Yn,AxAgent:()=>Ar,AxApacheTika:()=>Fo,AxAssertionError:()=>ot,AxBalancer:()=>$r,AxBaseAI:()=>fe,AxBaseOptimizer:()=>Fe,AxBootstrapFewShot:()=>bn,AxContentProcessingError:()=>Ze,AxDB:()=>lo,AxDBBase:()=>ze,AxDBCloudflare:()=>mn,AxDBManager:()=>co,AxDBMemory:()=>Tt,AxDBPinecone:()=>gn,AxDBWeaviate:()=>hn,AxDefaultCostTracker:()=>cr,AxDefaultResultReranker:()=>Po,AxDockerSession:()=>Vo,AxEmbeddingAdapter:()=>Jo,AxEvalUtil:()=>nc,AxFlow:()=>hr,AxFlowDependencyAnalyzer:()=>In,AxFlowExecutionPlanner:()=>Cn,AxFlowSubContextImpl:()=>vn,AxFlowTypedSubContextImpl:()=>Ko,AxFluentFieldType:()=>be,AxFunctionError:()=>tr,AxFunctionProcessor:()=>rr,AxGEPA:()=>jo,AxGEPAFlow:()=>zo,AxGen:()=>Pe,AxGenerateError:()=>ar,AxHFDataLoader:()=>$o,AxInstanceRegistry:()=>yn,AxLLMRequestTypeValues:()=>ds,AxMCPClient:()=>Yo,AxMCPHTTPSSETransport:()=>Xo,AxMCPStreambleHTTPTransport:()=>Zo,AxMediaNotSupportedError:()=>je,AxMemory:()=>fn,AxMiPRO:()=>Ho,AxMockAIService:()=>Zr,AxMultiServiceRouter:()=>Xr,AxOptimizedProgramImpl:()=>it,AxProgram:()=>wt,AxPromptTemplate:()=>_t,AxProviderRouter:()=>ro,AxRateLimiterTokenUsage:()=>en,AxSignature:()=>ge,AxSignatureBuilder:()=>sr,AxSimpleClassifier:()=>Do,AxSimpleClassifierClass:()=>_o,AxSpanKindValues:()=>ms,AxStopFunctionCallException:()=>Ft,AxStringUtil:()=>Eo,AxTestPrompt:()=>No,agent:()=>Rc,ai:()=>el,ax:()=>Ie,axAIAnthropicDefaultConfig:()=>Is,axAIAnthropicVertexDefaultConfig:()=>ka,axAIAzureOpenAIBestConfig:()=>Fa,axAIAzureOpenAICreativeConfig:()=>Ea,axAIAzureOpenAIDefaultConfig:()=>Cs,axAIAzureOpenAIFastConfig:()=>Pa,axAICohereCreativeConfig:()=>La,axAICohereDefaultConfig:()=>vs,axAIDeepSeekCodeConfig:()=>Ga,axAIDeepSeekDefaultConfig:()=>Ss,axAIGoogleGeminiDefaultConfig:()=>Ms,axAIGoogleGeminiDefaultCreativeConfig:()=>Ba,axAIGrokBestConfig:()=>Xa,axAIGrokDefaultConfig:()=>ao,axAIHuggingFaceCreativeConfig:()=>ja,axAIHuggingFaceDefaultConfig:()=>Ps,axAIMistralBestConfig:()=>za,axAIMistralDefaultConfig:()=>Qr,axAIOllamaDefaultConfig:()=>_s,axAIOllamaDefaultCreativeConfig:()=>qa,axAIOpenAIBestConfig:()=>_r,axAIOpenAICreativeConfig:()=>Dr,axAIOpenAIDefaultConfig:()=>Et,axAIOpenAIFastConfig:()=>Nr,axAIOpenAIResponsesBestConfig:()=>Ha,axAIOpenAIResponsesCreativeConfig:()=>Ka,axAIOpenAIResponsesDefaultConfig:()=>Wn,axAIOpenRouterDefaultConfig:()=>Ns,axAIRekaBestConfig:()=>Ja,axAIRekaCreativeConfig:()=>Ya,axAIRekaDefaultConfig:()=>Jn,axAIRekaFastConfig:()=>Qa,axAITogetherDefaultConfig:()=>Ls,axAIWebLLMCreativeConfig:()=>Za,axAIWebLLMDefaultConfig:()=>Us,axAnalyzeChatPromptRequirements:()=>Wa,axAnalyzeRequestRequirements:()=>Pt,axBaseAIDefaultConfig:()=>te,axBaseAIDefaultCreativeConfig:()=>Ae,axCheckMetricsHealth:()=>tl,axCreateDefaultColorLogger:()=>ps,axCreateDefaultOptimizerColorLogger:()=>yi,axCreateDefaultOptimizerTextLogger:()=>oc,axCreateDefaultTextLogger:()=>Zi,axCreateFlowColorLogger:()=>gr,axCreateFlowTextLogger:()=>pc,axDefaultFlowLogger:()=>dc,axDefaultMetricsConfig:()=>Hs,axDefaultOptimizerLogger:()=>lr,axDefaultOptimizerMetricsConfig:()=>bi,axGetCompatibilityReport:()=>_a,axGetFormatCompatibility:()=>Na,axGetMetricsConfig:()=>rl,axGetOptimizerMetricsConfig:()=>ic,axGetProvidersWithMediaSupport:()=>Da,axGlobals:()=>ee,axModelInfoAnthropic:()=>$n,axModelInfoCohere:()=>Ur,axModelInfoDeepSeek:()=>Br,axModelInfoGoogleGemini:()=>Hr,axModelInfoGrok:()=>io,axModelInfoGroq:()=>Wr,axModelInfoHuggingFace:()=>Vr,axModelInfoMistral:()=>Yr,axModelInfoOpenAI:()=>Vt,axModelInfoOpenAIResponses:()=>Fr,axModelInfoReka:()=>no,axModelInfoTogether:()=>oo,axModelInfoWebLLM:()=>so,axProcessContentForProvider:()=>to,axRAG:()=>wc,axScoreProvidersForRequest:()=>Lr,axSelectOptimalProvider:()=>Gr,axSpanAttributes:()=>V,axSpanEvents:()=>Xe,axUpdateMetricsConfig:()=>nl,axUpdateOptimizerMetricsConfig:()=>sc,axValidateChatRequestMessage:()=>qt,axValidateChatResponseResult:()=>Er,axValidateProviderCapabilities:()=>Rs,f:()=>ie,flow:()=>Wo,s:()=>ac});function Ue({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 ns=(()=>{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 Te(){return ns.randomUUID()}async function Lc(s){let e=new TextEncoder,t=typeof s=="string"?e.encode(s):s,n=await ns.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var ts=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 Lc(this.data)}};function Be(s){if(s!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new ts}function Oi(){return ns}var Ir=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 Mc=Object.create;var yr=Object.defineProperty;var Ec=Object.getOwnPropertyDescriptor;var Pc=Object.getOwnPropertyNames;var Fc=Object.getPrototypeOf,_c=Object.prototype.hasOwnProperty;var Dc=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var br=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Nc=(s,e)=>{for(var t in e)yr(s,t,{get:e[t],enumerable:!0})},Si=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pc(e))!_c.call(s,r)&&r!==t&&yr(s,r,{get:()=>e[r],enumerable:!(n=Ec(e,r))||n.enumerable});return s};var kn=(s,e,t)=>(t=s!=null?Mc(Fc(s)):{},Si(e||!s||!s.__esModule?yr(t,"default",{value:s,enumerable:!0}):t,s)),$c=s=>Si(yr({},"__esModule",{value:!0}),s);var Rl=br((Zs,Xs)=>{"use strict";(function(s,e){typeof Zs=="object"&&typeof Xs<"u"?Xs.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs=e()})(Zs,function(){"use strict";var s=1e3,e=6e4,t=36e5,n="millisecond",r="second",o="minute",i="hour",a="day",l="week",c="month",u="quarter",d="year",p="date",m="Invalid Date",h=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,A=/\[([^\]]+)]|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,g={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(w){var v=["th","st","nd","rd"],I=w%100;return"["+w+(v[(I-20)%10]||v[I]||v[0])+"]"}},f=function(w,v,I){var S=String(w);return!S||S.length>=v?w:""+Array(v+1-S.length).join(I)+w},x={s:f,z:function(w){var v=-w.utcOffset(),I=Math.abs(v),S=Math.floor(I/60),C=I%60;return(v<=0?"+":"-")+f(S,2,"0")+":"+f(C,2,"0")},m:function w(v,I){if(v.date()<I.date())return-w(I,v);var S=12*(I.year()-v.year())+(I.month()-v.month()),C=v.clone().add(S,c),M=I-C<0,_=v.clone().add(S+(M?-1:1),c);return+(-(S+(I-C)/(M?C-_:_-C))||0)},a:function(w){return w<0?Math.ceil(w)||0:Math.floor(w)},p:function(w){return{M:c,y:d,w:l,d:a,D:p,h:i,m:o,s:r,ms:n,Q:u}[w]||String(w||"").toLowerCase().replace(/s$/,"")},u:function(w){return w===void 0}},b="en",T={};T[b]=g;var E="$isDayjsObject",R=function(w){return w instanceof F||!(!w||!w[E])},k=function w(v,I,S){var C;if(!v)return b;if(typeof v=="string"){var M=v.toLowerCase();T[M]&&(C=M),I&&(T[M]=I,C=M);var _=v.split("-");if(!C&&_.length>1)return w(_[0])}else{var D=v.name;T[D]=v,C=D}return!S&&C&&(b=C),C||!S&&b},y=function(w,v){if(R(w))return w.clone();var I=typeof v=="object"?v:{};return I.date=w,I.args=arguments,new F(I)},O=x;O.l=k,O.i=R,O.w=function(w,v){return y(w,{locale:v.$L,utc:v.$u,x:v.$x,$offset:v.$offset})};var F=function(){function w(I){this.$L=k(I.locale,null,!0),this.parse(I),this.$x=this.$x||I.x||{},this[E]=!0}var v=w.prototype;return v.parse=function(I){this.$d=function(S){var C=S.date,M=S.utc;if(C===null)return new Date(NaN);if(O.u(C))return new Date;if(C instanceof Date)return new Date(C);if(typeof C=="string"&&!/Z$/i.test(C)){var _=C.match(h);if(_){var D=_[2]-1||0,z=(_[7]||"0").substring(0,3);return M?new Date(Date.UTC(_[1],D,_[3]||1,_[4]||0,_[5]||0,_[6]||0,z)):new Date(_[1],D,_[3]||1,_[4]||0,_[5]||0,_[6]||0,z)}}return new Date(C)}(I),this.init()},v.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()},v.$utils=function(){return O},v.isValid=function(){return this.$d.toString()!==m},v.isSame=function(I,S){var C=y(I);return this.startOf(S)<=C&&C<=this.endOf(S)},v.isAfter=function(I,S){return y(I)<this.startOf(S)},v.isBefore=function(I,S){return this.endOf(S)<y(I)},v.$g=function(I,S,C){return O.u(I)?this[S]:this.set(C,I)},v.unix=function(){return Math.floor(this.valueOf()/1e3)},v.valueOf=function(){return this.$d.getTime()},v.startOf=function(I,S){var C=this,M=!!O.u(S)||S,_=O.p(I),D=function(Oe,ue){var ke=O.w(C.$u?Date.UTC(C.$y,ue,Oe):new Date(C.$y,ue,Oe),C);return M?ke:ke.endOf(a)},z=function(Oe,ue){return O.w(C.toDate()[Oe].apply(C.toDate("s"),(M?[0,0,0,0]:[23,59,59,999]).slice(ue)),C)},j=this.$W,Q=this.$M,le=this.$D,ye="set"+(this.$u?"UTC":"");switch(_){case d:return M?D(1,0):D(31,11);case c:return M?D(1,Q):D(0,Q+1);case l:var _e=this.$locale().weekStart||0,We=(j<_e?j+7:j)-_e;return D(M?le-We:le+(6-We),Q);case a:case p:return z(ye+"Hours",0);case i:return z(ye+"Minutes",1);case o:return z(ye+"Seconds",2);case r:return z(ye+"Milliseconds",3);default:return this.clone()}},v.endOf=function(I){return this.startOf(I,!1)},v.$set=function(I,S){var C,M=O.p(I),_="set"+(this.$u?"UTC":""),D=(C={},C[a]=_+"Date",C[p]=_+"Date",C[c]=_+"Month",C[d]=_+"FullYear",C[i]=_+"Hours",C[o]=_+"Minutes",C[r]=_+"Seconds",C[n]=_+"Milliseconds",C)[M],z=M===a?this.$D+(S-this.$W):S;if(M===c||M===d){var j=this.clone().set(p,1);j.$d[D](z),j.init(),this.$d=j.set(p,Math.min(this.$D,j.daysInMonth())).$d}else D&&this.$d[D](z);return this.init(),this},v.set=function(I,S){return this.clone().$set(I,S)},v.get=function(I){return this[O.p(I)]()},v.add=function(I,S){var C,M=this;I=Number(I);var _=O.p(S),D=function(Q){var le=y(M);return O.w(le.date(le.date()+Math.round(Q*I)),M)};if(_===c)return this.set(c,this.$M+I);if(_===d)return this.set(d,this.$y+I);if(_===a)return D(1);if(_===l)return D(7);var z=(C={},C[o]=e,C[i]=t,C[r]=s,C)[_]||1,j=this.$d.getTime()+I*z;return O.w(j,this)},v.subtract=function(I,S){return this.add(-1*I,S)},v.format=function(I){var S=this,C=this.$locale();if(!this.isValid())return C.invalidDate||m;var M=I||"YYYY-MM-DDTHH:mm:ssZ",_=O.z(this),D=this.$H,z=this.$m,j=this.$M,Q=C.weekdays,le=C.months,ye=C.meridiem,_e=function(ue,ke,De,Le){return ue&&(ue[ke]||ue(S,M))||De[ke].slice(0,Le)},We=function(ue){return O.s(D%12||12,ue,"0")},Oe=ye||function(ue,ke,De){var Le=ue<12?"AM":"PM";return De?Le.toLowerCase():Le};return M.replace(A,function(ue,ke){return ke||function(De){switch(De){case"YY":return String(S.$y).slice(-2);case"YYYY":return O.s(S.$y,4,"0");case"M":return j+1;case"MM":return O.s(j+1,2,"0");case"MMM":return _e(C.monthsShort,j,le,3);case"MMMM":return _e(le,j);case"D":return S.$D;case"DD":return O.s(S.$D,2,"0");case"d":return String(S.$W);case"dd":return _e(C.weekdaysMin,S.$W,Q,2);case"ddd":return _e(C.weekdaysShort,S.$W,Q,3);case"dddd":return Q[S.$W];case"H":return String(D);case"HH":return O.s(D,2,"0");case"h":return We(1);case"hh":return We(2);case"a":return Oe(D,z,!0);case"A":return Oe(D,z,!1);case"m":return String(z);case"mm":return O.s(z,2,"0");case"s":return String(S.$s);case"ss":return O.s(S.$s,2,"0");case"SSS":return O.s(S.$ms,3,"0");case"Z":return _}return null}(ue)||_.replace(":","")})},v.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},v.diff=function(I,S,C){var M,_=this,D=O.p(S),z=y(I),j=(z.utcOffset()-this.utcOffset())*e,Q=this-z,le=function(){return O.m(_,z)};switch(D){case d:M=le()/12;break;case c:M=le();break;case u:M=le()/3;break;case l:M=(Q-j)/6048e5;break;case a:M=(Q-j)/864e5;break;case i:M=Q/t;break;case o:M=Q/e;break;case r:M=Q/s;break;default:M=Q}return C?M:O.a(M)},v.daysInMonth=function(){return this.endOf(c).$D},v.$locale=function(){return T[this.$L]},v.locale=function(I,S){if(!I)return this.$L;var C=this.clone(),M=k(I,S,!0);return M&&(C.$L=M),C},v.clone=function(){return O.w(this.$d,this)},v.toDate=function(){return new Date(this.valueOf())},v.toJSON=function(){return this.isValid()?this.toISOString():null},v.toISOString=function(){return this.$d.toISOString()},v.toString=function(){return this.$d.toUTCString()},w}(),P=F.prototype;return y.prototype=P,[["$ms",n],["$s",r],["$m",o],["$H",i],["$W",a],["$M",c],["$y",d],["$D",p]].forEach(function(w){P[w[1]]=function(v){return this.$g(v,w[0],w[1])}}),y.extend=function(w,v){return w.$i||(w(v,F,y),w.$i=!0),y},y.locale=k,y.isDayjs=R,y.unix=function(w){return y(1e3*w)},y.en=T[b],y.Ls=T,y.p={},y})});var wl=br((ei,ti)=>{"use strict";(function(s,e){typeof ei=="object"&&typeof ti<"u"?ti.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_customParseFormat=e()})(ei,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(h){return(h=+h)+(h>68?1900:2e3)},l=function(h){return function(A){this[h]=+A}},c=[/[+-]\d\d:?(\d\d)?|Z/,function(h){(this.zone||(this.zone={})).offset=function(A){if(!A||A==="Z")return 0;var g=A.match(/([+-]|\d\d)/g),f=60*g[1]+(+g[2]||0);return f===0?0:g[0]==="+"?-f:f}(h)}],u=function(h){var A=i[h];return A&&(A.indexOf?A:A.s.concat(A.f))},d=function(h,A){var g,f=i.meridiem;if(f){for(var x=1;x<=24;x+=1)if(h.indexOf(f(x,0,A))>-1){g=x>12;break}}else g=h===(A?"pm":"PM");return g},p={A:[o,function(h){this.afternoon=d(h,!1)}],a:[o,function(h){this.afternoon=d(h,!0)}],Q:[t,function(h){this.month=3*(h-1)+1}],S:[t,function(h){this.milliseconds=100*+h}],SS:[n,function(h){this.milliseconds=10*+h}],SSS:[/\d{3}/,function(h){this.milliseconds=+h}],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(h){var A=i.ordinal,g=h.match(/\d+/);if(this.day=g[0],A)for(var f=1;f<=31;f+=1)A(f).replace(/\[|\]/g,"")===h&&(this.day=f)}],w:[r,l("week")],ww:[n,l("week")],M:[r,l("month")],MM:[n,l("month")],MMM:[o,function(h){var A=u("months"),g=(u("monthsShort")||A.map(function(f){return f.slice(0,3)})).indexOf(h)+1;if(g<1)throw new Error;this.month=g%12||g}],MMMM:[o,function(h){var A=u("months").indexOf(h)+1;if(A<1)throw new Error;this.month=A%12||A}],Y:[/[+-]?\d+/,l("year")],YY:[n,function(h){this.year=a(h)}],YYYY:[/\d{4}/,l("year")],Z:c,ZZ:c};function m(h){var A,g;A=h,g=i&&i.formats;for(var f=(h=A.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(y,O,F){var P=F&&F.toUpperCase();return O||g[F]||s[F]||g[P].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(w,v,I){return v||I.slice(1)})})).match(e),x=f.length,b=0;b<x;b+=1){var T=f[b],E=p[T],R=E&&E[0],k=E&&E[1];f[b]=k?{regex:R,parser:k}:T.replace(/^\[|\]$/g,"")}return function(y){for(var O={},F=0,P=0;F<x;F+=1){var w=f[F];if(typeof w=="string")P+=w.length;else{var v=w.regex,I=w.parser,S=y.slice(P),C=v.exec(S)[0];I.call(O,C),y=y.replace(C,"")}}return function(M){var _=M.afternoon;if(_!==void 0){var D=M.hours;_?D<12&&(M.hours+=12):D===12&&(M.hours=0),delete M.afternoon}}(O),O}}return function(h,A,g){g.p.customParseFormat=!0,h&&h.parseTwoDigitYear&&(a=h.parseTwoDigitYear);var f=A.prototype,x=f.parse;f.parse=function(b){var T=b.date,E=b.utc,R=b.args;this.$u=E;var k=R[1];if(typeof k=="string"){var y=R[2]===!0,O=R[3]===!0,F=y||O,P=R[2];O&&(P=R[2]),i=this.$locale(),!y&&P&&(i=g.Ls[P]),this.$d=function(S,C,M,_){try{if(["x","X"].indexOf(C)>-1)return new Date((C==="X"?1e3:1)*S);var D=m(C)(S),z=D.year,j=D.month,Q=D.day,le=D.hours,ye=D.minutes,_e=D.seconds,We=D.milliseconds,Oe=D.zone,ue=D.week,ke=new Date,De=Q||(z||j?1:ke.getDate()),Le=z||ke.getFullYear(),gt=0;z&&!j||(gt=j>0?j-1:ke.getMonth());var ht,N=le||0,U=ye||0,q=_e||0,H=We||0;return Oe?new Date(Date.UTC(Le,gt,De,N,U,q,H+60*Oe.offset*1e3)):M?new Date(Date.UTC(Le,gt,De,N,U,q,H)):(ht=new Date(Le,gt,De,N,U,q,H),ue&&(ht=_(ht).week(ue).toDate()),ht)}catch{return new Date("")}}(T,k,E,g),this.init(),P&&P!==!0&&(this.$L=this.locale(P).$L),F&&T!=this.format(k)&&(this.$d=new Date("")),i={}}else if(k instanceof Array)for(var w=k.length,v=1;v<=w;v+=1){R[1]=k[v-1];var I=g.apply(this,R);if(I.isValid()){this.$d=I.$d,this.$L=I.$L,this.init();break}v===w&&(this.$d=new Date(""))}else x.call(this,b)}}})});var vl=br((ni,ri)=>{"use strict";(function(s,e){typeof ni=="object"&&typeof ri<"u"?ri.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_timezone=e()})(ni,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(u,d,p){p===void 0&&(p={});var m=new Date(u),h=function(A,g){g===void 0&&(g={});var f=g.timeZoneName||"short",x=A+"|"+f,b=e[x];return b||(b=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:A,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:f}),e[x]=b),b}(d,p);return h.formatToParts(m)},a=function(u,d){for(var p=i(u,d),m=[],h=0;h<p.length;h+=1){var A=p[h],g=A.type,f=A.value,x=s[g];x>=0&&(m[x]=parseInt(f,10))}var b=m[3],T=b===24?0:b,E=m[0]+"-"+m[1]+"-"+m[2]+" "+T+":"+m[4]+":"+m[5]+":000",R=+u;return(r.utc(E).valueOf()-(R-=R%1e3))/6e4},l=n.prototype;l.tz=function(u,d){u===void 0&&(u=o);var p,m=this.utcOffset(),h=this.toDate(),A=h.toLocaleString("en-US",{timeZone:u}),g=Math.round((h-new Date(A))/1e3/60),f=15*-Math.round(h.getTimezoneOffset()/15)-g;if(!Number(f))p=this.utcOffset(0,d);else if(p=r(A,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(f,!0),d){var x=p.utcOffset();p=p.add(m-x,"minute")}return p.$x.$timezone=u,p},l.offsetName=function(u){var d=this.$x.$timezone||r.tz.guess(),p=i(this.valueOf(),d,{timeZoneName:u}).find(function(m){return m.type.toLowerCase()==="timezonename"});return p&&p.value};var c=l.startOf;l.startOf=function(u,d){if(!this.$x||!this.$x.$timezone)return c.call(this,u,d);var p=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"),{locale:this.$L});return c.call(p,u,d).tz(this.$x.$timezone,!0)},r.tz=function(u,d,p){var m=p&&d,h=p||d||o,A=a(+r(),h);if(typeof u!="string")return r(u).tz(h);var g=function(T,E,R){var k=T-60*E*1e3,y=a(k,R);if(E===y)return[k,E];var O=a(k-=60*(y-E)*1e3,R);return y===O?[k,y]:[T-60*Math.min(y,O)*1e3,Math.max(y,O)]}(r.utc(u,m).valueOf(),A,h),f=g[0],x=g[1],b=r(f).utcOffset(x);return b.$x.$timezone=h,b},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(u){o=u}}})});var Sl=br((oi,si)=>{"use strict";(function(s,e){typeof oi=="object"&&typeof si<"u"?si.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_utc=e()})(oi,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 h={date:m,utc:!0,args:arguments};return new r(h)},i.utc=function(m){var h=o(this.toDate(),{locale:this.$L,utc:!0});return m?h.add(this.utcOffset(),s):h},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 c=i.utcOffset;i.utcOffset=function(m,h){var A=this.$utils().u;if(A(m))return this.$u?0:A(this.$offset)?c.call(this):this.$offset;if(typeof m=="string"&&(m=function(b){b===void 0&&(b="");var T=b.match(e);if(!T)return null;var E=(""+T[0]).match(t)||["-",0,0],R=E[0],k=60*+E[1]+ +E[2];return k===0?0:R==="+"?k:-k}(m),m===null))return this;var g=Math.abs(m)<=16?60*m:m,f=this;if(h)return f.$offset=g,f.$u=m===0,f;if(m!==0){var x=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(f=this.local().add(g+x,s)).$offset=g,f.$x.$localOffset=x}else f=this.utc();return f};var u=i.format;i.format=function(m){var h=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return u.call(this,h)},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 p=i.diff;i.diff=function(m,h,A){if(m&&this.$u===m.$u)return p.call(this,m,h,A);var g=this.local(),f=o(m).local();return p.call(g,f,h,A)}}})});var Mp={};Nc(Mp,{AxACE:()=>Uo,AxACEOptimizedProgram:()=>pr,AxAI:()=>Zn,AxAIAnthropic:()=>Ht,AxAIAnthropicModel:()=>Nn,AxAIAnthropicVertexModel:()=>Pr,AxAIAzureOpenAI:()=>Yt,AxAICohere:()=>Qt,AxAICohereEmbedModel:()=>Bn,AxAICohereModel:()=>Un,AxAIDeepSeek:()=>Zt,AxAIDeepSeekModel:()=>jn,AxAIGoogleGemini:()=>Xt,AxAIGoogleGeminiEmbedModel:()=>jr,AxAIGoogleGeminiEmbedTypes:()=>Os,AxAIGoogleGeminiModel:()=>zn,AxAIGoogleGeminiSafetyCategory:()=>zr,AxAIGoogleGeminiSafetyThreshold:()=>qr,AxAIGrok:()=>dn,AxAIGrokEmbedModels:()=>Bs,AxAIGrokModel:()=>Qn,AxAIGroq:()=>tn,AxAIGroqModel:()=>qn,AxAIHuggingFace:()=>nn,AxAIHuggingFaceModel:()=>Jr,AxAIMistral:()=>rn,AxAIMistralEmbedModels:()=>Fs,AxAIMistralModel:()=>Hn,AxAIOllama:()=>on,AxAIOpenAI:()=>Jt,AxAIOpenAIBase:()=>he,AxAIOpenAIEmbedModel:()=>Kt,AxAIOpenAIModel:()=>Gn,AxAIOpenAIResponses:()=>an,AxAIOpenAIResponsesBase:()=>Kn,AxAIOpenAIResponsesImpl:()=>sn,AxAIOpenAIResponsesModel:()=>Wt,AxAIOpenRouter:()=>ln,AxAIRefusalError:()=>de,AxAIReka:()=>cn,AxAIRekaModel:()=>Vn,AxAIServiceAbortedError:()=>Gt,AxAIServiceAuthenticationError:()=>yt,AxAIServiceError:()=>we,AxAIServiceNetworkError:()=>rt,AxAIServiceResponseError:()=>pt,AxAIServiceStatusError:()=>kt,AxAIServiceStreamTerminatedError:()=>Qe,AxAIServiceTimeoutError:()=>Mt,AxAITogether:()=>un,AxAIWebLLM:()=>pn,AxAIWebLLMModel:()=>Yn,AxAgent:()=>Ar,AxApacheTika:()=>Fo,AxAssertionError:()=>ot,AxBalancer:()=>$r,AxBaseAI:()=>fe,AxBaseOptimizer:()=>Fe,AxBootstrapFewShot:()=>bn,AxContentProcessingError:()=>Ze,AxDB:()=>lo,AxDBBase:()=>ze,AxDBCloudflare:()=>mn,AxDBManager:()=>co,AxDBMemory:()=>Tt,AxDBPinecone:()=>gn,AxDBWeaviate:()=>hn,AxDefaultCostTracker:()=>cr,AxDefaultResultReranker:()=>Po,AxDockerSession:()=>Vo,AxEmbeddingAdapter:()=>Jo,AxEvalUtil:()=>nc,AxFlow:()=>hr,AxFlowDependencyAnalyzer:()=>In,AxFlowExecutionPlanner:()=>Cn,AxFlowSubContextImpl:()=>vn,AxFlowTypedSubContextImpl:()=>Ko,AxFluentFieldType:()=>xe,AxFunctionError:()=>tr,AxFunctionProcessor:()=>rr,AxGEPA:()=>jo,AxGEPAFlow:()=>zo,AxGen:()=>Pe,AxGenerateError:()=>ar,AxHFDataLoader:()=>$o,AxInstanceRegistry:()=>yn,AxLLMRequestTypeValues:()=>ds,AxMCPClient:()=>Yo,AxMCPHTTPSSETransport:()=>Xo,AxMCPStreambleHTTPTransport:()=>Zo,AxMediaNotSupportedError:()=>je,AxMemory:()=>fn,AxMiPRO:()=>Ho,AxMockAIService:()=>Zr,AxMultiServiceRouter:()=>Xr,AxOptimizedProgramImpl:()=>it,AxProgram:()=>wt,AxPromptTemplate:()=>_t,AxProviderRouter:()=>ro,AxRateLimiterTokenUsage:()=>en,AxSignature:()=>ge,AxSignatureBuilder:()=>sr,AxSimpleClassifier:()=>Do,AxSimpleClassifierClass:()=>_o,AxSpanKindValues:()=>ms,AxStopFunctionCallException:()=>Ft,AxStringUtil:()=>Eo,AxTestPrompt:()=>No,agent:()=>Rc,ai:()=>el,ax:()=>Ie,axAIAnthropicDefaultConfig:()=>Is,axAIAnthropicVertexDefaultConfig:()=>ka,axAIAzureOpenAIBestConfig:()=>Fa,axAIAzureOpenAICreativeConfig:()=>Ea,axAIAzureOpenAIDefaultConfig:()=>Cs,axAIAzureOpenAIFastConfig:()=>Pa,axAICohereCreativeConfig:()=>La,axAICohereDefaultConfig:()=>vs,axAIDeepSeekCodeConfig:()=>Ga,axAIDeepSeekDefaultConfig:()=>Ss,axAIGoogleGeminiDefaultConfig:()=>Ms,axAIGoogleGeminiDefaultCreativeConfig:()=>Ba,axAIGrokBestConfig:()=>Xa,axAIGrokDefaultConfig:()=>ao,axAIHuggingFaceCreativeConfig:()=>ja,axAIHuggingFaceDefaultConfig:()=>Ps,axAIMistralBestConfig:()=>za,axAIMistralDefaultConfig:()=>Qr,axAIOllamaDefaultConfig:()=>_s,axAIOllamaDefaultCreativeConfig:()=>qa,axAIOpenAIBestConfig:()=>_r,axAIOpenAICreativeConfig:()=>Dr,axAIOpenAIDefaultConfig:()=>Et,axAIOpenAIFastConfig:()=>Nr,axAIOpenAIResponsesBestConfig:()=>Ha,axAIOpenAIResponsesCreativeConfig:()=>Ka,axAIOpenAIResponsesDefaultConfig:()=>Wn,axAIOpenRouterDefaultConfig:()=>Ns,axAIRekaBestConfig:()=>Ja,axAIRekaCreativeConfig:()=>Ya,axAIRekaDefaultConfig:()=>Jn,axAIRekaFastConfig:()=>Qa,axAITogetherDefaultConfig:()=>Ls,axAIWebLLMCreativeConfig:()=>Za,axAIWebLLMDefaultConfig:()=>Us,axAnalyzeChatPromptRequirements:()=>Wa,axAnalyzeRequestRequirements:()=>Pt,axBaseAIDefaultConfig:()=>te,axBaseAIDefaultCreativeConfig:()=>Ae,axCheckMetricsHealth:()=>tl,axCreateDefaultColorLogger:()=>ps,axCreateDefaultOptimizerColorLogger:()=>yi,axCreateDefaultOptimizerTextLogger:()=>oc,axCreateDefaultTextLogger:()=>Zi,axCreateFlowColorLogger:()=>gr,axCreateFlowTextLogger:()=>pc,axDefaultFlowLogger:()=>dc,axDefaultMetricsConfig:()=>Hs,axDefaultOptimizerLogger:()=>lr,axDefaultOptimizerMetricsConfig:()=>bi,axGetCompatibilityReport:()=>_a,axGetFormatCompatibility:()=>Na,axGetMetricsConfig:()=>rl,axGetOptimizerMetricsConfig:()=>ic,axGetProvidersWithMediaSupport:()=>Da,axGlobals:()=>ee,axModelInfoAnthropic:()=>$n,axModelInfoCohere:()=>Ur,axModelInfoDeepSeek:()=>Br,axModelInfoGoogleGemini:()=>Hr,axModelInfoGrok:()=>io,axModelInfoGroq:()=>Wr,axModelInfoHuggingFace:()=>Vr,axModelInfoMistral:()=>Yr,axModelInfoOpenAI:()=>Vt,axModelInfoOpenAIResponses:()=>Fr,axModelInfoReka:()=>no,axModelInfoTogether:()=>oo,axModelInfoWebLLM:()=>so,axProcessContentForProvider:()=>to,axRAG:()=>wc,axScoreProvidersForRequest:()=>Lr,axSelectOptimalProvider:()=>Gr,axSpanAttributes:()=>V,axSpanEvents:()=>Xe,axUpdateMetricsConfig:()=>nl,axUpdateOptimizerMetricsConfig:()=>sc,axValidateChatRequestMessage:()=>qt,axValidateChatResponseResult:()=>Er,axValidateProviderCapabilities:()=>Rs,f:()=>ie,flow:()=>Wo,s:()=>ac});function Ue({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 ns=(()=>{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 Te(){return ns.randomUUID()}async function Lc(s){let e=new TextEncoder,t=typeof s=="string"?e.encode(s):s,n=await ns.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var ts=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 Lc(this.data)}};function Be(s){if(s!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new ts}function Oi(){return ns}var Ir=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
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
|
`)?`
|
|
@@ -149,7 +149,7 @@ ${e}
|
|
|
149
149
|
`)}),r+=`${e}
|
|
150
150
|
`;break}default:r=JSON.stringify(n,null,2)}s(r)}};var V={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"},Xe={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"},ds=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(ds||{}),ms=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(ms||{});var gs=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()}},Or=class extends TransformStream{constructor(e,t){super(new gs(e,t))}};function kr(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 Xi=(s,e,t,n)=>{let r=n?s.filter(i=>i.role!=="system"):[...s];t({name:"ChatRequestChatPrompt",step:e,value:r})};var ea=(s,e)=>{if(!s.results)return;let t={name:"ChatResponseResults",value:s.results};e(t)},ta=(s,e,t)=>{t({name:"ChatResponseStreamingResult",index:e,value:s})};function na(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?kr(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 ra=(s,e)=>{e({name:"FunctionResults",value:s})},hs=(s,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:s})},oa=(s,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:s})},sa=(s,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:s})},ia=(s,e,t)=>{t({name:"RefusalError",index:e,error:s})};var aa=(s,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:s})},la=(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)},ca=(s,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:s,selectedIndex:e,latency:t})};var fs=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},Mr,ua=s=>{if(Mr)return Mr;if(s)return Mr=lu(s),Mr};var lu=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)"})}),pa=(s,e,t,n,r)=>{try{if(s.latencyHistogram){let o=fs({operation:e,ai_service:n,...r?{model:r}:{}});s.latencyHistogram.record(t,o)}}catch(o){console.warn("Failed to record latency metric:",o)}},da=(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)},ma=(s,e,t,n)=>{try{if(s.errorCounter){let r=fs({operation:e,ai_service:t,...n?{model:n}:{}});s.errorCounter.add(1,r)}}catch(r){console.warn("Failed to record error metric:",r)}},ga=(s,e,t,n,r)=>{s.errorRateGauge&&s.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{}})},ha=(s,e,t,n)=>{s.requestCounter&&s.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Dn=(s,e,t,n,r)=>{try{let o=fs({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)}},fa=(s,e,t,n,r)=>{t&&s.streamingRequestsCounter&&s.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{}})},Aa=(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)},As=(s,e,t,n,r)=>{s.requestSizeHistogram&&s.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},xs=(s,e,t,n,r)=>{s.responseSizeHistogram&&s.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},xa=(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)},ys=(s,e,t,n,r)=>{s.estimatedCostCounter&&s.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{}})},ya=(s,e,t,n)=>{s.promptLengthHistogram&&s.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},ba=(s,e,t,n)=>{s.contextWindowUsageGauge&&s.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},Ia=(s,e,t,n)=>{s.timeoutsCounter&&s.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Ta=(s,e,t,n)=>{s.abortsCounter&&s.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Ca=(s,e,t,n)=>{s.thinkingBudgetUsageCounter&&s.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},Ra=(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}:{}})};function wa(s){try{return JSON.stringify(s,null,2)}catch{return String(s)}}function et(s,e={}){let t=[s];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${wa(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${wa(e.item)}`),new Error(t.join(`
|
|
151
151
|
`))}function qt(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=typeof s=="object"&&s!==null&&"role"in s&&typeof s.role=="string"?s.role:void 0;if(!t)throw new Error(`Chat request message must have a role, received: ${e(t)}`);switch(t){case"system":{let n=typeof s=="object"&&s!==null&&"content"in s&&typeof s.content=="string"?s.content:void 0;if(!n||n.trim()==="")throw new Error(`System message content cannot be empty or whitespace-only, received: ${e(n)}`);break}case"user":{let n=typeof s=="object"&&s!==null&&"content"in s?s.content:void 0;if(n===void 0)throw new Error(`User message content cannot be undefined, received: ${e(n)}`);if(typeof n=="string"){if(n.trim()==="")throw new Error(`User message content cannot be empty or whitespace-only, received: ${e(n)}`)}else if(Array.isArray(n)){if(n.length===0)throw new Error(`User message content array cannot be empty, received: ${e(n)}`);for(let r=0;r<n.length;r++){let o=n[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=typeof o=="object"&&o!==null&&"type"in o&&typeof o.type=="string"?o.type:void 0;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="text"in o&&typeof o.text=="string"?o.text:void 0;if(!a||a.trim()==="")throw new Error(`User message text content at index ${r} cannot be empty or whitespace-only, received: ${e(a)}`);break}case"image":{let a="image"in o&&typeof o.image=="string"?o.image:void 0,l="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:void 0;if(!a||a.trim()==="")throw new Error(`User message image content at index ${r} cannot be empty, received: ${e(a)}`);if(!l||l.trim()==="")throw new Error(`User message image content at index ${r} must have a mimeType, received: ${e(l)}`);break}case"audio":{let a="data"in o&&typeof o.data=="string"?o.data:void 0;if(!a||a.trim()==="")throw new Error(`User message audio content at index ${r} cannot be empty, received: ${e(a)}`);break}case"file":{let a="fileUri"in o&&typeof o.fileUri=="string",l="data"in o&&typeof o.data=="string";if(!a&&!l)throw new Error(`User message file content at index ${r} must have either 'data' or 'fileUri', received: ${e(o)}`);if(a&&l)throw new Error(`User message file content at index ${r} cannot have both 'data' and 'fileUri', received: ${e(o)}`);if(a){let u=o.fileUri;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} fileUri cannot be empty, received: ${e(u)}`)}if(l){let u=o.data;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} data cannot be empty, received: ${e(u)}`)}let c="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:null;if(!c||c.trim()==="")throw new Error(`User message file content at index ${r} must have a mimeType, received: ${e(c)}`);break}case"url":{let a="url"in o&&typeof o.url=="string"?o.url:void 0;if(!a||a.trim()==="")throw new Error(`User message url content at index ${r} cannot be empty, received: ${e(a)}`);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)}`);break}case"assistant":{let n=typeof s=="object"&&s!==null&&"content"in s?s.content:void 0,r=typeof s=="object"&&s!==null&&"functionCalls"in s?s.functionCalls:void 0,o=typeof n=="string"&&n.trim()!=="",i=Array.isArray(r)&&r.length>0;if(!o&&!i&&et("Assistant message must include non-empty content or at least one function call",{fieldPath:"content | functionCalls",value:{content:n,functionCalls:r},item:s}),n!==void 0&&typeof n!="string"&&et("Assistant message content must be a string",{fieldPath:"content",value:n,item:s}),r!==void 0&&!Array.isArray(r)&&et("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:s}),Array.isArray(r))for(let a=0;a<r.length;a++){let l=r[a];if((!l||typeof l!="object")&&et("functionCalls entry must be an object",{fieldPath:`functionCalls[${a}]`,value:l,item:s}),(!("id"in l)||typeof l.id!="string"||l.id.trim()==="")&&et("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${a}].id`,value:l.id,item:s}),(!("type"in l)||l.type!=="function")&&et("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${a}].type`,value:l.type,item:s}),!("function"in l)||!l.function)et("functionCalls entry must include a function object",{fieldPath:`functionCalls[${a}].function`,value:l.function,item:s});else{let c=l.function;(!("name"in c)||typeof c.name!="string"||c.name.trim()==="")&&et("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${a}].function.name`,value:c?.name,item:s}),c.params!==void 0&&typeof c.params!="string"&&typeof c.params!="object"&&et("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${a}].function.params`,value:c.params,item:s})}}if(s.name!==void 0){let a=s.name;(typeof a!="string"||a.trim()==="")&&et("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:a,item:s})}break}case"function":{let n=typeof s=="object"&&s!==null&&"functionId"in s&&typeof s.functionId=="string"?s.functionId:void 0,r=typeof s=="object"&&s!==null&&"result"in s?s.result:void 0;if(!n||n.trim()==="")throw new Error(`Function message must have a non-empty functionId, received: ${e(n)}`);if(r==null)throw new Error(`Function message must have a result, received: ${e(r)}`);if(typeof r!="string")throw new Error(`Function message result must be a string, received: ${e(r)}`);s.isError!==void 0&&typeof s.isError!="boolean"&&et("Function message isError must be a boolean when provided",{fieldPath:"isError",value:s.isError,item:s});break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function Er(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.thoughtBlock&&!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.thoughtBlock!==void 0){if(typeof r.thoughtBlock!="object"||r.thoughtBlock===null)throw new Error(`Chat response result thoughtBlock at index ${n} must be an object, received: ${e(r.thoughtBlock)}`);let o=r.thoughtBlock;if(typeof o.data!="string")throw new Error(`Chat response result thoughtBlock.data at index ${n} must be a string, received: ${e(o.data)}`);if(typeof o.encrypted!="boolean")throw new Error(`Chat response result thoughtBlock.encrypted at index ${n} must be a boolean, received: ${e(o.encrypted)}`);if(o.signature!==void 0&&typeof o.signature!="string")throw new Error(`Chat response result thoughtBlock.signature at index ${n} must be a string when provided, received: ${e(o.signature)}`)}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 te=()=>structuredClone({temperature:0}),Ae=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),fe=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:o,defaults:i,options:a={},supportFor:l,models:c}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=r,this.supportFor=l,this.tracer=a.tracer??ee.tracer,this.meter=a.meter??ee.meter,this.modelInfo=o,this.models=c,this.id=Te();let u=this.getModel(i.model)??i.model,d=this.getEmbedModel(i.embedModel)??i.embedModel;if(this.defaults={model:u,embedModel:d},!i.model||typeof i.model!="string"||i.model==="")throw new Error("No model defined");this.setOptions(a),c&&uu(c)}#e=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=ee.logger??Qi;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 ua(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}get debug(){return this.#e}setOptions(e){this.#e=e.debug??ee.debug??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??ee.tracer,this.meter=e.meter??ee.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??ee.logger??this.logger,this.corsProxy=e.corsProxy}getOptions(){return{debug:this.#e,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;pa(r,e,t,this.name,o),da(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;ha(r,e,this.name,o),t&&ma(r,e,this.name,o),ga(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&&Dn(t,"input",n,this.name,e.model),r&&Dn(t,"output",r,this.name,e.model),o&&Dn(t,"total",o,this.name,e.model),i&&Dn(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&&Aa(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;Ia(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ta(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;fa(r,"chat",a,this.name,o);let{hasImages:l,hasAudio:c}=this.detectMultimodalContent(e);Ra(r,l,c,this.name,o);let u=this.calculatePromptLength(e);ya(r,u,this.name,o),xa(r,i?.temperature,i?.maxTokens,this.name,o),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&Ca(r,this.modelUsage.tokens.thoughtsTokens,this.name,o);let d=this.calculateRequestSize(e);if(As(r,"chat",d,this.name,o),n&&!a){let p=n,m=this.calculateResponseSize(p);if(xs(r,"chat",m,this.name,o),p.results)for(let g of p.results)g.functionCalls&&this.recordFunctionCallMetrics(g.functionCalls,this.lastUsedChatModel);let h=this.calculateContextWindowUsage(this.lastUsedChatModel,p.modelUsage);h>0&&ba(r,h,this.name,o);let A=this.estimateCost(this.lastUsedChatModel,p.modelUsage);A>0&&ys(r,"chat",A,this.name,o)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let r=this.lastUsedEmbedModel,o=this.calculateRequestSize(e);As(n,"embed",o,this.name,r);let i=this.calculateResponseSize(t);xs(n,"embed",i,this.name,r);let a=this.estimateCostByName(r,t.modelUsage);a>0&&ys(n,"embed",a,this.name,r)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,o,i=this.getModelByKey(e.model),a=i?i.thinkingTokenBudget:void 0,l={...i?{thinkingTokenBudget:a,showThoughts:i.showThoughts,stream:i.stream,debug:i.debug,useExpensiveModel:i.useExpensiveModel}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,c])=>c!==void 0))};try{return o=await this._chat1(e,l),o}catch(c){throw r=!0,c instanceof Error&&(c.message.includes("timeout")||c.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("chat")),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("chat",c),this.updateErrorMetrics("chat",r),r||this.recordChatMetrics(e,l,o)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let c of e.chatPrompt)qt(c);let r=this.getModelByKey(e.model),o={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},i=this.modelInfo.find(c=>c.name===n);if(i?.notSupported?.temperature&&"temperature"in o&&delete o.temperature,i?.notSupported?.topP&&"topP"in o&&delete o.topP,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(c=>c.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:Ee.SERVER,attributes:{[V.LLM_SYSTEM]:this.name,[V.LLM_OPERATION_NAME]:"chat",[V.LLM_REQUEST_MODEL]:n,[V.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[V.LLM_REQUEST_TEMPERATURE]:o.temperature,[V.LLM_REQUEST_TOP_P]:o.topP??"Not set",[V.LLM_REQUEST_TOP_K]:o.topK??"Not set",[V.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[V.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[V.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[V.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??It.active(),async c=>await this._chat2(n,o,e,t,c)):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,r,o){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let i=r?.debug??this.#e,a;n.functions&&n.functions.length>0&&(a=n.functions.map(f=>this.cleanupFunctionSchema(f)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,i&&Xi(l.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let c=this.getFeatures(e).functions,u=r?.functionCallMode??"auto",p=u==="prompt"||u==="auto"&&!c?{...l,chatPrompt:l.chatPrompt.map(f=>{if(f.role==="assistant"){let{content:x,name:b,cache:T}=f;return{role:"assistant",content:x,name:b,cache:T}}return f.role==="function"?{role:"user",content:f.result}:f}),functions:[]}:l,m=async()=>{let[f,x]=await this.aiImpl.createChatReq(p,r);return o?.isRecording()&&cu(n,o,this.excludeContentFromTrace),await Me({name:f.name,url:this.apiURL,localCall:f.localCall,headers:await this.buildHeaders(f.headers),stream:t.stream,timeout:this.timeout,debug:i,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},x)},h=r?.rateLimiter??this.rt,A=h?await h(m,{modelUsage:this.modelUsage}):await m();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let f=this.aiImpl.createChatStreamResp.bind(this),x=R=>k=>{let y=f(k,R);if(y.sessionId=r?.sessionId,!y.modelUsage){let O=this.aiImpl.getTokenUsage();O&&(y.modelUsage={ai:this.name,model:e,tokens:O})}if(this.modelUsage=y.modelUsage,this.recordTokenUsage(y.modelUsage),o?.isRecording()&&va(y,o,this.excludeContentFromTrace),i)for(let O of y.results)ta(O,O.index,r?.logger??this.logger);return y},b=async R=>{o?.isRecording()&&o.end(),i&&na(R,r?.logger??this.logger)};if(typeof window<"u"){let R=A,k={},y=[],O=r?.abortSignal??this.abortSignal;return new ReadableStream({start:F=>{let P=R.getReader(),w=()=>{try{P.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat")}catch{}try{o?.isRecording()&&o.end()}catch{}try{F.error(new DOMException("Aborted","AbortError"))}catch{F.error(new Error("Aborted"))}};if(O){if(O.aborted){w();return}O.addEventListener("abort",w,{once:!0})}async function v(){try{for(;;){let{done:I,value:S}=await P.read();if(I){b&&await b(y),F.close();break}let C=x(k)(S);C&&(y.push(C),F.enqueue(C))}}catch(I){if(F.error(I),o?.isRecording())try{o.end()}catch{}}finally{if(P.releaseLock(),O)try{O.removeEventListener("abort",w)}catch{}}}v()}})}return A.pipeThrough(new Or(x({}),b))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let g=this.aiImpl.createChatResp(A);if(g.sessionId=r?.sessionId,!g.modelUsage){let f=this.aiImpl.getTokenUsage();f&&(g.modelUsage={ai:this.name,model:e,tokens:f})}return g.modelUsage&&(this.modelUsage=g.modelUsage,this.recordTokenUsage(g.modelUsage)),o?.isRecording()&&(va(g,o,this.excludeContentFromTrace),o.end()),i&&ea(g,r?.logger??this.logger),g}async embed(e,t){let n=performance.now(),r=!1,o,i=this.getModelByKey(e.embedModel),a={...i?{thinkingTokenBudget:i.thinkingTokenBudget,showThoughts:i.showThoughts,stream:i.stream,debug:i.debug,useExpensiveModel:i.useExpensiveModel}:void 0,...t};try{return o=await this._embed1(e,a),o}catch(l){throw r=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed")),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l),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:Ee.SERVER,attributes:{[V.LLM_SYSTEM]:this.name,[V.LLM_OPERATION_NAME]:"embeddings",[V.LLM_REQUEST_MODEL]:n}},t?.traceContext??It.active(),async r=>await this._embed2(n,e,t,r)):await this._embed2(n,e,t)}async _embed2(e,t,n,r){if(!this.aiImpl.createEmbedReq)throw new Error("createEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("createEmbedResp not implemented");let o=this.aiImpl.createEmbedReq.bind(this.aiImpl),i=n?.debug??this.#e,a={...t,embedModel:e};this.lastUsedEmbedModel=e,i&&aa(a.texts??[],e,n?.logger??this.logger);let l=async()=>{let[p,m]=await o(a);return await Me({name:p.name,url:this.apiURL,localCall:p.localCall,headers:await this.buildHeaders(p.headers),debug:i,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},m)},c=n?.rateLimiter??this.rt,u=c?await c(l,{modelUsage:this.embedModelUsage}):await l(),d=this.aiImpl.createEmbedResp?.(u);if(d.sessionId=n?.sessionId,!d.modelUsage){let p=this.aiImpl.getTokenUsage();p&&(d.modelUsage={ai:this.name,model:e,tokens:p})}return this.embedModelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(Xe.GEN_AI_USAGE,{[V.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[V.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[V.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),i&&la(d.embeddings,n?.logger??this.logger),r?.end(),d}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 cu(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(Xe.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(Xe.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(Xe.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:o.functionId};t||(i.content=o.result),e.addEvent(Xe.GEN_AI_TOOL_MESSAGE,i);break}}let r={};t||(r.content=n.join(`
|
|
152
|
-
`)),e.addEvent(Xe.GEN_AI_USER_MESSAGE,r)}function va(s,e,t){if(s.modelUsage?.tokens){let n=s.modelUsage.tokens.thoughtsTokens?{[V.LLM_USAGE_THOUGHTS_TOKENS]:s.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(Xe.GEN_AI_USAGE,{[V.LLM_USAGE_INPUT_TOKENS]:s.modelUsage.tokens.promptTokens,[V.LLM_USAGE_OUTPUT_TOKENS]:s.modelUsage.tokens.completionTokens??0,[V.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(Xe.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function Sa(s){let e=0;for(let t of s){if(!t||typeof t!="object")throw new Error(`AxMessage array validation failed: Item at index ${e} is not a valid message object`);if(t.role!=="user"&&t.role!=="assistant")throw new Error(`AxMessage array validation failed: Item at index ${e} has invalid role: ${t.role}`);e++}}function uu(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 Nn=(m=>(m.Claude41Opus="claude-opus-4-1-20250805",m.Claude4Opus="claude-opus-4-20250514",m.Claude4Sonnet="claude-sonnet-4-20250514",m.Claude45Sonnet="claude-sonnet-4-5-20250929",m.Claude45Haiku="claude-haiku-4-5",m.Claude37Sonnet="claude-3-7-sonnet-latest",m.Claude35Sonnet="claude-3-5-sonnet-latest",m.Claude35Haiku="claude-3-5-haiku-latest",m.Claude3Opus="claude-3-opus-latest",m.Claude3Sonnet="claude-3-sonnet-20240229",m.Claude3Haiku="claude-3-haiku-20240307",m.Claude21="claude-2.1",m.ClaudeInstant12="claude-instant-1.2",m))(Nn||{}),Pr=(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))(Pr||{});var $n=[{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!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 Ln=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,Ln(n)]))),e.items&&(e.items=Ln(e.items)),e},Is=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...te()}),ka=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...te()}),bs=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;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_control:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(y=>y.role!=="system"),c=e.functions?.map(y=>{let O={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},F=y.parameters?Ln(y.parameters):void 0;return F===void 0||F&&typeof F=="object"&&Object.keys(F).length===0?F={...O}:F&&typeof F=="object"&&F.type==="object"&&(!("properties"in F)||!F.properties||Object.keys(F.properties).length===0)&&(F={...F,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:y.name,description:y.description,input_schema:F}}),d=(this.config.tools??[]).map(y=>y&&typeof y=="object"&&"type"in y?y:{name:y.name,description:y.description,input_schema:y.input_schema?Ln(y.input_schema):void 0,...y.cache_control?{cache_control:y.cache_control}:{}}),p=[...c??[],...d];this.isVertex&&p.length>0&&(p=p.filter(y=>!(y&&typeof y=="object"&&"type"in y))),p.length===0&&(p=void 0);let m=e.modelConfig?.maxTokens??this.config.maxTokens,h=e.modelConfig?.stopSequences??this.config.stopSequences,A=e.modelConfig?.temperature,g=e.modelConfig?.topP,f=e.modelConfig?.topK??this.config.topK,x=e.modelConfig?.n??this.config.n;if(x&&x>1)throw new Error("Anthropic does not support sampling (n > 1)");let b;if(this.config.thinking?.budget_tokens&&(b=this.config.thinking),t?.thinkingTokenBudget){let y=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":b=void 0;break;case"minimal":b={type:"enabled",budget_tokens:y?.minimal??1024};break;case"low":b={type:"enabled",budget_tokens:y?.low??5e3};break;case"medium":b={type:"enabled",budget_tokens:y?.medium??1e4};break;case"high":b={type:"enabled",budget_tokens:y?.high??2e4};break;case"highest":b={type:"enabled",budget_tokens:y?.highest??32e3};break}}if(!b&&t?.thinkingTokenBudget===void 0){let y=this.config.thinkingTokenBudgetLevels}let T=pu(l,!!b);T.some(y=>y.role==="assistant"&&Array.isArray(y.content)&&y.content.length>0&&y.content[0]?.type==="tool_use")&&(b=void 0);let R;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let y=e.responseFormat.schema.schema||e.responseFormat.schema;R={type:"json_schema",schema:Ln(y)},this.usedStructuredOutput=!0}let k={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...m?{max_tokens:m}:{},...h&&h.length>0?{stop_sequences:h}:{},...A!==void 0&&!b?{temperature:A}:{},...g!==void 0&&(!b||g>=.95)?{top_p:g}:{},...f&&!b?{top_k:f}:{},...i,...p?{tools:p}:{},...r?{stream:!0}:{},...a?{system:a}:{},...b?{thinking:b}:{},...R?{output_format:R}:{},messages:T};return[o,k]};createChatResp=e=>{if(e.type==="error")throw new de(e.error.message,void 0,void 0);let t=Oa(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o="",i=!1,a,l=[],c=[];for(let p of e.content)switch(p.type){case"text":if(r+=p.text??"",Array.isArray(p.citations))for(let m of p.citations)m?.url&&c.push({url:String(m.url),title:typeof m.title=="string"?m.title:void 0,snippet:typeof m.cited_text=="string"?m.cited_text:void 0});break;case"thinking":case"redacted_thinking":n&&(o+=p.thinking??p.data??""),p.type==="redacted_thinking"&&(i=!0),typeof p.signature=="string"&&(a=p.signature);break;case"tool_use":l.push({id:p.id,type:"function",function:{name:p.name,params:p.input}});break}let u={index:0,id:e.id,finishReason:t};r&&(u.content=r),o&&(u.thought=o,u.thoughtBlock={data:o,encrypted:i,...a?{signature:a}:{}}),l.length>0&&(u.functionCalls=l),c.length>0&&(u.citations=c);let d=[u];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens},{results:d,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 de(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)+(o.usage?.cache_creation_input_tokens??0)+(o.usage?.cache_read_input_tokens??0),cacheCreationTokens:o.usage?.cache_creation_input_tokens,cacheReadTokens:o.usage?.cache_read_input_tokens},{results:i}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let i=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&i.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...i.length?{citations:i}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlock:{data:o.thinking,encrypted:!1}}]}:{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(o.type==="web_search_tool_result"||o.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:o}=e;if(o.type==="citations_delta"){let i=o.citation;if(i&&typeof i.url=="string"&&i.url.length>0){let a=[{url:String(i.url),title:typeof i.title=="string"?i.title:void 0,snippet:typeof i.cited_text=="string"?i.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(o.type==="text_delta"){let i=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&i.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...i.length?{citations:i}:{}}]}}if(o.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlock:{data:o.thinking,encrypted:!1}}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,thoughtBlock:{data:"",encrypted:!1,signature:o.signature}}]};if(o.type==="input_json_delta"){let i=n.indexIdMap[e.index];if(!i)return{results:[{index:r,content:""}]};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:this.tokensUsed?.promptTokens??0,completionTokens:i.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+i.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens},{results:[{index:r,content:"",finishReason:Oa(o.stop_reason)}]}}return{results:[{index:r,content:""}]}}},Ht=class s extends fe{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,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":"structured-outputs-2025-11-13","x-api-key":typeof e=="function"?await e():e})}let u={...Is(),...r},d=new bs(u,a),p=h=>{let A=Ue({model:h,modelInfo:$n,models:i});return{functions:!0,streaming:!0,hasThinkingBudget:A?.supported?.thinkingBudget??!1,hasShowThoughts:A?.supported?.showThoughts??!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:A?.supported?.thinkingBudget??!1,multiTurn:!0}},m=i?.map(h=>{let A=h,g=A?.config;if(!g)return h;let f={};g.maxTokens!==void 0&&(f.maxTokens=g.maxTokens),g.temperature!==void 0&&(f.temperature=g.temperature),g.topP!==void 0&&(f.topP=g.topP),g.topK!==void 0&&(f.topK=g.topK),g.presencePenalty!==void 0&&(f.presencePenalty=g.presencePenalty),g.frequencyPenalty!==void 0&&(f.frequencyPenalty=g.frequencyPenalty),g.stopSequences!==void 0&&(f.stopSequences=g.stopSequences),g.endSequences!==void 0&&(f.endSequences=g.endSequences),g.stream!==void 0&&(f.stream=g.stream),g.n!==void 0&&(f.n=g.n);let x={...A};Object.keys(f).length>0&&(x.modelConfig={...A.modelConfig??{},...f});let b=g.thinking?.thinkingTokenBudget;if(typeof b=="number"){let T=u.thinkingTokenBudgetLevels,E=[["minimal",T?.minimal??200],["low",T?.low??800],["medium",T?.medium??5e3],["high",T?.high??1e4],["highest",T?.highest??24500]],R="minimal",k=Number.POSITIVE_INFINITY;for(let[y,O]of E){let F=Math.abs(b-O);F<k&&(k=F,R=y)}x.thinkingTokenBudget=R}return g.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!g.thinking.includeThoughts),x});super(d,{name:"Anthropic",apiURL:l,headers:c,modelInfo:$n,defaults:{model:u.model},options:o,supportFor:p,models:m??i})}};function pu(s,e){let t=s.map(r=>{switch(r.role){case"function":return{role:"user",content:[{type:"tool_result",content:r.result,tool_use_id:r.functionId,...r.isError?{is_error:!0}:{},...r.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof r.content=="string"?{role:"user",content:r.content}:{role:"user",content:r.content.map(i=>{switch(i.type){case"text":return{type:"text",text:i.text,...i.cache?{cache_control:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:i.mimeType,data:i.image},...i.cache?{cache_control:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let o="",i=[],a=r.thoughtBlock;return a&&typeof a.data=="string"&&a.data.length>0&&(a.encrypted?i.push(a.signature?{type:"redacted_thinking",data:a.data,signature:a.signature}:{type:"redacted_thinking",data:a.data}):i.push(a.signature?{type:"thinking",thinking:a.data,signature:a.signature}:{type:"thinking",thinking:a.data})),typeof r.content=="string"&&(i.length>0?o=[...i,{type:"text",text:r.content}]:o=r.content),typeof r.functionCalls<"u"&&(o=r.functionCalls.map(l=>{let c={};if(typeof l.function.params=="string"){let u=l.function.params;if(u.trim().length===0)c={};else try{c=JSON.parse(u)}catch{throw new Error(`Failed to parse function params JSON: ${u}`)}}else typeof l.function.params=="object"&&(c=l.function.params);return{type:"tool_use",id:l.id,name:l.function.name,input:c,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(o)&&i.length>0&&(o=[...i,...o])),{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=du(t);return mu(n)}function du(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 mu(s){return s.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Oa(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 Gn=(R=>(R.GPT4="gpt-4",R.GPT41="gpt-4.1",R.GPT41Mini="gpt-4.1-mini",R.GPT41Nano="gpt-4.1-nano",R.GPT4O="gpt-4o",R.GPT4OMini="gpt-4o-mini",R.GPT4ChatGPT4O="chatgpt-4o-latest",R.GPT4Turbo="gpt-4-turbo",R.GPT35Turbo="gpt-3.5-turbo",R.GPT35TurboInstruct="gpt-3.5-turbo-instruct",R.GPT35TextDavinci002="text-davinci-002",R.GPT3TextBabbage002="text-babbage-002",R.GPT3TextAda001="text-ada-001",R.GPT5="gpt-5",R.GPT5Nano="gpt-5-nano",R.GPT5Mini="gpt-5-mini",R.GPT5Chat="gpt-5-chat",R.O1="o1",R.O1Mini="o1-mini",R.O3="o3",R.O3Mini="o3-mini",R.O4Mini="o4-mini",R))(Gn||{}),Kt=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Kt||{});var Wt=(y=>(y.GPT4="gpt-4",y.GPT41="gpt-4.1",y.GPT41Mini="gpt-4.1-mini",y.GPT41Nano="gpt-4.1-nano",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.GPT5="gpt-5",y.GPT5Nano="gpt-5-nano",y.GPT5Mini="gpt-5-mini",y.GPT5Chat="gpt-5-chat",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))(Wt||{});var Vt=[{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-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4},{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:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0}},{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:"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}],Fr=[{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-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4},{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:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}}];var gu=s=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(s)||e.includes(s)},Et=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...te()}),_r=()=>structuredClone({...Et(),model:"gpt-5"}),Dr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Ae()}),Nr=()=>({...Et(),model:"gpt-5-nano"}),Ts=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=hu(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,d=gu(n),p={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...i?{tool_choice:i}:{},...d?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...l!==void 0?{frequency_penalty:l}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...c&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...u?{store:u}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(p.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(p.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":p.reasoning_effort=void 0;break;case"minimal":p.reasoning_effort="minimal";break;case"low":p.reasoning_effort="medium";break;case"medium":p.reasoning_effort="high";break;case"high":p.reasoning_effort="high";break;case"highest":p.reasoning_effort="high";break}if(!p.reasoning_effort&&t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"minimal":p.reasoning_effort="minimal";break;case"low":p.reasoning_effort="medium";break;case"medium":case"high":case"highest":p.reasoning_effort="high";break}return this.chatReqUpdater&&(p=this.chatReqUpdater(p)),[r,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:"/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 de(a.message.refusal,e.model,e.id);let l=Ma(a.finish_reason),c=a.message.tool_calls?.map(({id:u,function:{arguments:d,name:p}})=>({id:u,type:"function",function:{name:p,params:d}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(u=>u?.type==="url_citation"&&u.url_citation).map(u=>({url:u.url_citation?.url,title:u.url_citation?.title,description:u.url_citation?.description})),functionCalls:c,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:c,role:u,refusal:d,tool_calls:p,reasoning_content:m,annotations:h},finish_reason:A})=>{if(d)throw new de(d,void 0,n);let g=Ma(A),f=p?.map(({id:x,index:b,function:{name:T,arguments:E}})=>{typeof x=="string"&&typeof b=="number"&&!i.indexIdMap[b]&&(i.indexIdMap[b]=x);let R=i.indexIdMap[b];return R?{id:R,type:"function",function:{name:T,params:E}}:null}).filter(x=>x!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:h?.filter(x=>x?.type==="url_citation"&&x.url_citation).map(x=>({url:x.url_citation?.url,title:x.url_citation?.title,description:x.url_citation?.description})),functionCalls:f,finishReason:g,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)}}},Ma=s=>{switch(s){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function hu(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 he=class extends fe{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 c=new Ts(t,n?.streamingUsage??!0,a);super(c,{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})}},Jt=class extends he{constructor({apiKey:e,apiURL:t,config:n,options:r,models:o,modelInfo:i}){if(!e||e==="")throw new Error("OpenAI API key not set");i=[...Vt,...i??[]];let a=c=>{let u=Ue({model:c,modelInfo:i,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!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:u?.supported?.thinkingBudget??!1,multiTurn:!0}},l=o?.map(c=>{let u=c,d=u?.config;if(!d)return c;let p={};d.maxTokens!==void 0&&(p.maxTokens=d.maxTokens),d.temperature!==void 0&&(p.temperature=d.temperature),d.topP!==void 0&&(p.topP=d.topP),d.presencePenalty!==void 0&&(p.presencePenalty=d.presencePenalty),d.frequencyPenalty!==void 0&&(p.frequencyPenalty=d.frequencyPenalty);let m=d.stopSequences??d.stop;m!==void 0&&(p.stopSequences=m),d.n!==void 0&&(p.n=d.n),d.stream!==void 0&&(p.stream=d.stream);let h={...u};Object.keys(p).length>0&&(h.modelConfig={...u.modelConfig??{},...p});let A=d?.thinking?.thinkingTokenBudget;if(typeof A=="number"){let g=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],f="minimal",x=Number.POSITIVE_INFINITY;for(let[b,T]of g){let E=Math.abs(A-T);E<x&&(x=E,f=b)}h.thinkingTokenBudget=f}return d?.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!d.thinking.includeThoughts),h});super({apiKey:e,apiURL:t,config:{...Et(),...n},options:r,modelInfo:i,models:l??o,supportFor:a}),super.setName("OpenAI")}};var Cs=Et,Ea=Dr,Pa=Nr,Fa=_r,Yt=class extends he{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 c={...Cs(),...o};l=[...Vt,...l??[]];let u=p=>{let m=Ue({model:p,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:m?.supported?.thinkingBudget??!1,hasShowThoughts:m?.supported?.showThoughts??!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?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:i,models:a,modelInfo:l,supportFor:u});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 $r=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.");fu(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(e){let n=(this.serviceFailures.get(this.currentService.getId())?.retries??0)+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:n,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${n}/${this.maxRetries})`,e),n>=this.maxRetries){let r=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`,e),r}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 we))throw n;switch(n.constructor){case yt:throw n;case kt:break;case rt:break;case pt:break;case Qe:break;case Mt:break;default:throw n}if(!this.handleFailure(n))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(!(n instanceof we)||!this.handleFailure(n))throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function fu(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 Pt(s){let e=!1,t=!1,n=!1,r=!1,o=!1,i=!1,a=!1,l=new Set,c=0;if(s.chatPrompt&&Array.isArray(s.chatPrompt))for(let u of s.chatPrompt){if(u.role==="user"&&Array.isArray(u.content))for(let d of u.content)switch(l.add(d.type),d.type){case"image":e=!0,d.cache&&(a=!0),c+=85;break;case"audio":t=!0,d.cache&&(a=!0),c+=d.duration||60;break;case"file":n=!0,d.cache&&(a=!0),c+=Math.ceil((d.extractedText?.length||1e3)/4);break;case"url":r=!0,d.cache&&(a=!0),c+=Math.ceil((d.cachedContent?.length||2e3)/4);break;case"text":d.cache&&(a=!0),c+=Math.ceil(d.text.length/4);break}else"content"in u&&typeof u.content=="string"&&(c+=Math.ceil(u.content.length/4));"cache"in u&&u.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:c}}function Rs(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 Lr(s,e){return s.map(t=>{let n=t.getFeatures(),r=Rs(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 Gr(s,e,t={}){if(e.length===0)throw new Error("No providers available");let n=Pt(s),r=Lr(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 _a(s,e){let t=Pt(s),n=Lr(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 Da(s,e){return s.filter(t=>t.getFeatures().media[e].supported)}function Na(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 Un=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Un||{}),Bn=(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))(Bn||{});var Ur=[{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 vs=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...te()}),La=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Ae()}),ws=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=Au(r),a=e.functions?.map(d=>{let p={};if(d.parameters?.properties)for(let[m,h]of Object.entries(d.parameters.properties))p[m]={description:h.description,type:h.type,required:d.parameters.required?.includes(m)??!1};return{name:d.name,description:d.description,parameter_definitions:p}}),l=e.chatPrompt.filter(d=>d.role==="function").map(d=>{let p=a?.find(m=>m.name===d.functionId);if(!p)throw new Error("Function not found");return{call:{name:p.name,parameters:p.parameter_definitions},outputs:[{result:d.result??""}]}}),c={name:"/chat"},u={message:o,model:t,tools:a,...l&&!o?{tool_results:l}:{},chat_history:i,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},k:e.modelConfig?.topK??this.config.topK,...e.modelConfig?.topP!==void 0?{p:e.modelConfig.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,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:"/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}}},Qt=class extends fe{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...vs(),...t},i=new ws(o),a=r?.map(l=>{let c=l,u=c?.config;if(!u)return l;let d={};u.maxTokens!==void 0&&(d.maxTokens=u.maxTokens),u.temperature!==void 0&&(d.temperature=u.temperature),u.topP!==void 0&&(d.topP=u.topP),u.topK!==void 0&&(d.topK=u.topK),u.presencePenalty!==void 0&&(d.presencePenalty=u.presencePenalty),u.frequencyPenalty!==void 0&&(d.frequencyPenalty=u.frequencyPenalty),u.stopSequences!==void 0&&(d.stopSequences=u.stopSequences),u.endSequences!==void 0&&(d.endSequences=u.endSequences),u.stream!==void 0&&(d.stream=u.stream),u.n!==void 0&&(d.n=u.n);let p={...c};return Object.keys(d).length>0&&(p.modelConfig={...c.modelConfig??{},...d}),p});super(i,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Ur,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:a??r})}};function Au(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=$a(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=$a(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 $a(s){return s?.map(e=>{let t;if(typeof e.function.params=="string"){let n=e.function.params;if(n.trim().length===0)t={};else try{t=JSON.parse(n)}catch{throw new Error(`Failed to parse function params JSON: ${n}`)}}else t=e.function.params;return{name:e.function.name,parameters:t}})}var jn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(jn||{});var Br=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Ss=()=>structuredClone({model:"deepseek-chat",...te()}),Ga=()=>structuredClone({model:"deepseek-coder",...Ae()}),Zt=class extends he{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...Ss(),...t};o=[...Br,...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 zn=(f=>(f.Gemini3ProPreview="gemini-3-pro-preview",f.Gemini3ProImagePreview="gemini-3-pro-image-preview",f.Gemini25Pro="gemini-2.5-pro",f.Gemini25Flash="gemini-2.5-flash",f.Gemini25FlashLite="gemini-2.5-flash-lite",f.Gemini20Flash="gemini-2.0-flash",f.Gemini20FlashLite="gemini-2.0-flash-lite",f.Gemini20ProExp="gemini-2.0-pro-exp-02-05",f.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",f.Gemini1Pro="gemini-1.0-pro",f.Gemini15Flash="gemini-1.5-flash",f.Gemini15Flash002="gemini-1.5-flash-002",f.Gemini15Flash8B="gemini-1.5-flash-8b",f.Gemini15Pro="gemini-1.5-pro",f.GeminiFlashLatest="gemini-flash-latest",f.GeminiFlashLiteLatest="gemini-flash-lite-latest",f.GeminiProLatest="gemini-pro-latest",f))(zn||{}),jr=(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))(jr||{}),zr=(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))(zr||{}),qr=(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))(qr||{}),Os=(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))(Os||{});var Hr=[{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!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},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0}}];var Kr=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,Kr(n)]))),e.items&&(e.items=Kr(e.items)),e},Ua=[{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"}],Ms=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Ua,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...te()}),Ba=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Ua,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Ae()}),ks=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 g=r?"&":"?",f=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${g}key=${f}`}let i=e.chatPrompt.filter(g=>g.role==="system").map(g=>g.content),a=i.length>0?{role:"user",parts:[{text:i.join(" ")}]}:void 0,l=e.chatPrompt.filter(g=>g.role!=="system").map((g,f)=>{switch(g.role){case"user":return{role:"user",parts:Array.isArray(g.content)?g.content.map((b,T)=>{switch(b.type){case"text":return{text:b.text};case"image":return{inlineData:{mimeType:b.mimeType,data:b.image}};case"audio":return{inlineData:{mimeType:`audio/${b.format??"mp3"}`,data:b.data}};case"file":return"fileUri"in b?{fileData:{mimeType:b.mimeType,fileUri:b.fileUri}}:{inlineData:{mimeType:b.mimeType,data:b.data}};default:throw new Error(`Chat prompt content type not supported (index: ${T})`)}}):[{text:g.content}]};case"assistant":{let x=[],b=g.thoughtBlock,T=!1;if(b?.data&&(x.push({thought:!0,text:b.data,...b.signature?{thoughtSignature:b.signature}:{}}),b.signature&&(T=!0)),g.functionCalls){let E=g.functionCalls.map((R,k)=>{let y;if(typeof R.function.params=="string"){let F=R.function.params;if(F.trim().length===0)y={};else try{y=JSON.parse(F)}catch{throw new Error(`Failed to parse function params JSON: ${F}`)}}else y=R.function.params;let O={functionCall:{name:R.function.name,args:y}};return k===0&&!T&&b&&b.signature&&(O.thoughtSignature=b.signature,T=!0),O});x.push(...E)}if(g.content&&x.push({text:g.content}),x.length===0)throw new Error("Assistant content is empty");return{role:"model",parts:x}}case"function":{if(!("functionId"in g))throw new Error(`Chat prompt functionId is empty (index: ${f})`);return{role:"user",parts:[{functionResponse:{name:g.functionId,response:{result:g.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(g)} (index: ${f})`)}}),c=[];if(e.functions&&e.functions.length>0){let g=e.functions.map(f=>{let x={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},b=f.parameters?Kr(f.parameters):void 0;return b===void 0||b&&typeof b=="object"&&Object.keys(b).length===0?b={...x}:b&&typeof b=="object"&&b.type==="object"&&(!("properties"in b)||!b.properties||Object.keys(b.properties).length===0)&&(b={...b,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{...f,parameters:b}});c.push({function_declarations:g})}if(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?.googleMaps){let g=this.options.googleMaps,f=g?.enableWidget!==void 0?{enableWidget:g.enableWidget}:{};c.push({google_maps:f})}this.options?.urlContext&&c.push({url_context:{}}),c.length===0&&(c=void 0);let u,d=Array.isArray(c)?c.some(g=>g&&Array.isArray(g.function_declarations)&&g.function_declarations.length>0):!1;if(e.functionCall)if(e.functionCall==="none")u={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")u={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")u={function_calling_config:{mode:"ANY"}};else{let g=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};u={function_calling_config:{mode:"ANY"},...g}}else d&&(u={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(u={...u??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let p={};if(this.config.thinking?.includeThoughts&&(p.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(p.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&(p.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let g=this.config.thinkingTokenBudgetLevels,f=n.includes("gemini-3");switch(t.thinkingTokenBudget){case"none":p.thinkingBudget=0,p.includeThoughts=!1,delete p.thinkingLevel;break;case"minimal":p.thinkingBudget=g?.minimal??200,f&&(p.thinkingLevel="low");break;case"low":p.thinkingBudget=g?.low??800,f&&(p.thinkingLevel="low");break;case"medium":p.thinkingBudget=g?.medium??5e3,f&&(p.thinkingLevel="high");break;case"high":p.thinkingBudget=g?.high??1e4,f&&(p.thinkingLevel="high");break;case"highest":p.thinkingBudget=g?.highest??24500,f&&(p.thinkingLevel="high");break}}p.thinkingLevel&&delete p.thinkingBudget,t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(p.includeThoughts=t.showThoughts);let m={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.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(p).length>0?{thinkingConfig:p}:{}};if(e.responseFormat){if(m.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let g=e.responseFormat.schema.schema||e.responseFormat.schema;m.responseSchema=Kr(g)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(m.responseMimeType="application/json");let h=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:u,systemInstruction:a,generationConfig:m,safetySettings:h}]};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,n=e.candidates?.map(o=>{let i={index:0};switch(o.finishReason){case"MAX_TOKENS":i.finishReason="length";break;case"STOP":i.finishReason="stop";break;case"SAFETY":throw new de("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new de("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new de("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new de("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new de("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new de("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new de("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new de("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new de("Other finish reason",void 0,void 0)}if(!o.content||!o.content.parts)return i;for(let c of o.content.parts){if("text"in c){"thought"in c&&c.thought||c.thought===!0?(i.thought=c.text,i.thoughtBlock={data:c.text,encrypted:!1,...c.thoughtSignature?{signature:c.thoughtSignature}:{}}):i.content=c.text;continue}"functionCall"in c&&(c.thoughtSignature&&(i.thoughtBlock?i.thoughtBlock.signature=c.thoughtSignature:i.thoughtBlock={data:"",encrypted:!1,signature:c.thoughtSignature}),i.functionCalls=[...i.functionCalls??[],{id:Te(),type:"function",function:{name:c.functionCall.name,params:c.functionCall.args}}])}let a=o.citationMetadata?.citations;if(Array.isArray(a)&&a.length){let c=u=>u?`${u.year}-${String(u.month).padStart(2,"0")}-${String(u.day).padStart(2,"0")}`:void 0;i.citations=a.filter(u=>typeof u?.uri=="string").map(u=>({url:u.uri,title:u.title,license:u.license,publicationDate:c(u.publicationDate)}))}let l=o.groundingMetadata;if(l){if(Array.isArray(l.groundingChunks)){let c=l.groundingChunks.map(u=>u?.maps).filter(u=>u&&typeof u.uri=="string").map(u=>({url:u.uri,title:u.title}));c.length&&(i.citations=[...i.citations??[],...c])}typeof l.googleMapsWidgetContextToken=="string"&&(t=l.googleMapsWidgetContextToken)}return i});e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount});let r={results:n};return t&&(r.providerMetadata={...r.providerMetadata,google:{...r.providerMetadata?.google??{},mapsWidgetContextToken:t}}),r};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}}},Xt=class s extends fe{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 c=t!==void 0&&n!==void 0,u,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 g;r?g="endpoints":g="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${g}`,d=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");u="https://generativelanguage.googleapis.com/v1beta",d=async()=>({})}let p={...Ms(),...o},m=new ks(p,c,r,e,i);l=[...Hr,...l??[]];let h=g=>{let f=Ue({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:f?.supported?.thinkingBudget??!1,hasShowThoughts:f?.supported?.showThoughts??!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:f?.supported?.thinkingBudget??!1,multiTurn:!0}},A=a?.map(g=>{let f=g,x=f?.config;if(!x)return g;let b={};x.maxTokens!==void 0&&(b.maxTokens=x.maxTokens),x.temperature!==void 0&&(b.temperature=x.temperature),x.topP!==void 0&&(b.topP=x.topP),x.topK!==void 0&&(b.topK=x.topK),x.presencePenalty!==void 0&&(b.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(b.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(b.stopSequences=x.stopSequences),x.endSequences!==void 0&&(b.endSequences=x.endSequences),x.stream!==void 0&&(b.stream=x.stream),x.n!==void 0&&(b.n=x.n);let T={...f};Object.keys(b).length>0&&(T.modelConfig={...f.modelConfig??{},...b});let E=x.thinking?.thinkingTokenBudget;if(typeof E=="number"){let R=p.thinkingTokenBudgetLevels,k=[["minimal",R?.minimal??200],["low",R?.low??800],["medium",R?.medium??5e3],["high",R?.high??1e4],["highest",R?.highest??24500]],y="minimal",O=Number.POSITIVE_INFINITY;for(let[F,P]of k){let w=Math.abs(E-P);w<O&&(O=w,y=F)}T.thinkingTokenBudget=y}return x.thinking?.includeThoughts!==void 0&&(T.showThoughts=!!x.thinking.includeThoughts),T});super(m,{name:"GoogleGeminiAI",apiURL:u,headers:d,modelInfo:l,defaults:{model:p.model,embedModel:p.embedModel},options:i,supportFor:h,models:A??a})}};var xu=new Se,en=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(xu.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 qn=(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))(qn||{});var Wr=[{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 yu=()=>structuredClone({model:"llama-3.3-70b-versatile",...te()}),tn=class extends he{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let i={...yu(),...t},a={...n,streamingUsage:!1};o=[...Wr,...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 en(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 Vr=[];var Jr=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Jr||{});var Ps=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...te()}),ja=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Ae()}),Es=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:
|
|
152
|
+
`)),e.addEvent(Xe.GEN_AI_USER_MESSAGE,r)}function va(s,e,t){if(s.modelUsage?.tokens){let n=s.modelUsage.tokens.thoughtsTokens?{[V.LLM_USAGE_THOUGHTS_TOKENS]:s.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(Xe.GEN_AI_USAGE,{[V.LLM_USAGE_INPUT_TOKENS]:s.modelUsage.tokens.promptTokens,[V.LLM_USAGE_OUTPUT_TOKENS]:s.modelUsage.tokens.completionTokens??0,[V.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(Xe.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function Sa(s){let e=0;for(let t of s){if(!t||typeof t!="object")throw new Error(`AxMessage array validation failed: Item at index ${e} is not a valid message object`);if(t.role!=="user"&&t.role!=="assistant")throw new Error(`AxMessage array validation failed: Item at index ${e} has invalid role: ${t.role}`);e++}}function uu(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 Nn=(m=>(m.Claude41Opus="claude-opus-4-1-20250805",m.Claude4Opus="claude-opus-4-20250514",m.Claude4Sonnet="claude-sonnet-4-20250514",m.Claude45Sonnet="claude-sonnet-4-5-20250929",m.Claude45Haiku="claude-haiku-4-5",m.Claude37Sonnet="claude-3-7-sonnet-latest",m.Claude35Sonnet="claude-3-5-sonnet-latest",m.Claude35Haiku="claude-3-5-haiku-latest",m.Claude3Opus="claude-3-opus-latest",m.Claude3Sonnet="claude-3-sonnet-20240229",m.Claude3Haiku="claude-3-haiku-20240307",m.Claude21="claude-2.1",m.ClaudeInstant12="claude-instant-1.2",m))(Nn||{}),Pr=(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))(Pr||{});var $n=[{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!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 Ln=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,Ln(n)]))),e.items&&(e.items=Ln(e.items)),e},Is=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...te()}),ka=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...te()}),bs=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;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_control:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(y=>y.role!=="system"),c=e.functions?.map(y=>{let O={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},F=y.parameters?Ln(y.parameters):void 0;return F===void 0||F&&typeof F=="object"&&Object.keys(F).length===0?F={...O}:F&&typeof F=="object"&&F.type==="object"&&(!("properties"in F)||!F.properties||Object.keys(F.properties).length===0)&&(F={...F,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:y.name,description:y.description,input_schema:F}}),d=(this.config.tools??[]).map(y=>y&&typeof y=="object"&&"type"in y?y:{name:y.name,description:y.description,input_schema:y.input_schema?Ln(y.input_schema):void 0,...y.cache_control?{cache_control:y.cache_control}:{}}),p=[...c??[],...d];this.isVertex&&p.length>0&&(p=p.filter(y=>!(y&&typeof y=="object"&&"type"in y))),p.length===0&&(p=void 0);let m=e.modelConfig?.maxTokens??this.config.maxTokens,h=e.modelConfig?.stopSequences??this.config.stopSequences,A=e.modelConfig?.temperature,g=e.modelConfig?.topP,f=e.modelConfig?.topK??this.config.topK,x=e.modelConfig?.n??this.config.n;if(x&&x>1)throw new Error("Anthropic does not support sampling (n > 1)");let b;if(this.config.thinking?.budget_tokens&&(b=this.config.thinking),t?.thinkingTokenBudget){let y=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":b=void 0;break;case"minimal":b={type:"enabled",budget_tokens:y?.minimal??1024};break;case"low":b={type:"enabled",budget_tokens:y?.low??5e3};break;case"medium":b={type:"enabled",budget_tokens:y?.medium??1e4};break;case"high":b={type:"enabled",budget_tokens:y?.high??2e4};break;case"highest":b={type:"enabled",budget_tokens:y?.highest??32e3};break}}if(!b&&t?.thinkingTokenBudget===void 0){let y=this.config.thinkingTokenBudgetLevels}let T=pu(l,!!b);T.some(y=>y.role==="assistant"&&Array.isArray(y.content)&&y.content.length>0&&y.content[0]?.type==="tool_use")&&(b=void 0);let R;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let y=e.responseFormat.schema.schema||e.responseFormat.schema;R={type:"json_schema",schema:Ln(y)},this.usedStructuredOutput=!0}let k={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...m?{max_tokens:m}:{},...h&&h.length>0?{stop_sequences:h}:{},...A!==void 0&&!b?{temperature:A}:{},...g!==void 0&&(!b||g>=.95)?{top_p:g}:{},...f&&!b?{top_k:f}:{},...i,...p?{tools:p}:{},...r?{stream:!0}:{},...a?{system:a}:{},...b?{thinking:b}:{},...R?{output_format:R}:{},messages:T};return[o,k]};createChatResp=e=>{if(e.type==="error")throw new de(e.error.message,void 0,void 0);let t=Oa(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o="",i=!1,a,l=[],c=[];for(let p of e.content)switch(p.type){case"text":if(r+=p.text??"",Array.isArray(p.citations))for(let m of p.citations)m?.url&&c.push({url:String(m.url),title:typeof m.title=="string"?m.title:void 0,snippet:typeof m.cited_text=="string"?m.cited_text:void 0});break;case"thinking":case"redacted_thinking":n&&(o+=p.thinking??p.data??""),p.type==="redacted_thinking"&&(i=!0),typeof p.signature=="string"&&(a=p.signature);break;case"tool_use":l.push({id:p.id,type:"function",function:{name:p.name,params:p.input}});break}let u={index:0,id:e.id,finishReason:t};r&&(u.content=r),o&&(u.thought=o,u.thoughtBlock={data:o,encrypted:i,...a?{signature:a}:{}}),l.length>0&&(u.functionCalls=l),c.length>0&&(u.citations=c);let d=[u];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens},{results:d,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 de(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)+(o.usage?.cache_creation_input_tokens??0)+(o.usage?.cache_read_input_tokens??0),cacheCreationTokens:o.usage?.cache_creation_input_tokens,cacheReadTokens:o.usage?.cache_read_input_tokens},{results:i}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let i=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&i.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...i.length?{citations:i}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlock:{data:o.thinking,encrypted:!1}}]}:{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(o.type==="web_search_tool_result"||o.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:o}=e;if(o.type==="citations_delta"){let i=o.citation;if(i&&typeof i.url=="string"&&i.url.length>0){let a=[{url:String(i.url),title:typeof i.title=="string"?i.title:void 0,snippet:typeof i.cited_text=="string"?i.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(o.type==="text_delta"){let i=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&i.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...i.length?{citations:i}:{}}]}}if(o.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlock:{data:o.thinking,encrypted:!1}}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,thoughtBlock:{data:"",encrypted:!1,signature:o.signature}}]};if(o.type==="input_json_delta"){let i=n.indexIdMap[e.index];if(!i)return{results:[{index:r,content:""}]};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:this.tokensUsed?.promptTokens??0,completionTokens:i.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+i.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens},{results:[{index:r,content:"",finishReason:Oa(o.stop_reason)}]}}return{results:[{index:r,content:""}]}}},Ht=class s extends fe{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,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":"structured-outputs-2025-11-13","x-api-key":typeof e=="function"?await e():e})}let u={...Is(),...r},d=new bs(u,a),p=h=>{let A=Ue({model:h,modelInfo:$n,models:i});return{functions:!0,streaming:!0,hasThinkingBudget:A?.supported?.thinkingBudget??!1,hasShowThoughts:A?.supported?.showThoughts??!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:A?.supported?.thinkingBudget??!1,multiTurn:!0}},m=i?.map(h=>{let A=h,g=A?.config;if(!g)return h;let f={};g.maxTokens!==void 0&&(f.maxTokens=g.maxTokens),g.temperature!==void 0&&(f.temperature=g.temperature),g.topP!==void 0&&(f.topP=g.topP),g.topK!==void 0&&(f.topK=g.topK),g.presencePenalty!==void 0&&(f.presencePenalty=g.presencePenalty),g.frequencyPenalty!==void 0&&(f.frequencyPenalty=g.frequencyPenalty),g.stopSequences!==void 0&&(f.stopSequences=g.stopSequences),g.endSequences!==void 0&&(f.endSequences=g.endSequences),g.stream!==void 0&&(f.stream=g.stream),g.n!==void 0&&(f.n=g.n);let x={...A};Object.keys(f).length>0&&(x.modelConfig={...A.modelConfig??{},...f});let b=g.thinking?.thinkingTokenBudget;if(typeof b=="number"){let T=u.thinkingTokenBudgetLevels,E=[["minimal",T?.minimal??200],["low",T?.low??800],["medium",T?.medium??5e3],["high",T?.high??1e4],["highest",T?.highest??24500]],R="minimal",k=Number.POSITIVE_INFINITY;for(let[y,O]of E){let F=Math.abs(b-O);F<k&&(k=F,R=y)}x.thinkingTokenBudget=R}return g.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!g.thinking.includeThoughts),x});super(d,{name:"Anthropic",apiURL:l,headers:c,modelInfo:$n,defaults:{model:u.model},options:o,supportFor:p,models:m??i})}};function pu(s,e){let t=s.map(r=>{switch(r.role){case"function":return{role:"user",content:[{type:"tool_result",content:r.result,tool_use_id:r.functionId,...r.isError?{is_error:!0}:{},...r.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof r.content=="string"?{role:"user",content:r.content}:{role:"user",content:r.content.map(i=>{switch(i.type){case"text":return{type:"text",text:i.text,...i.cache?{cache_control:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:i.mimeType,data:i.image},...i.cache?{cache_control:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let o="",i=[],a=r.thoughtBlock;return a&&typeof a.data=="string"&&a.data.length>0&&(a.encrypted?i.push(a.signature?{type:"redacted_thinking",data:a.data,signature:a.signature}:{type:"redacted_thinking",data:a.data}):i.push(a.signature?{type:"thinking",thinking:a.data,signature:a.signature}:{type:"thinking",thinking:a.data})),typeof r.content=="string"&&(i.length>0?o=[...i,{type:"text",text:r.content}]:o=r.content),typeof r.functionCalls<"u"&&(o=r.functionCalls.map(l=>{let c={};if(typeof l.function.params=="string"){let u=l.function.params;if(u.trim().length===0)c={};else try{c=JSON.parse(u)}catch{throw new Error(`Failed to parse function params JSON: ${u}`)}}else typeof l.function.params=="object"&&(c=l.function.params);return{type:"tool_use",id:l.id,name:l.function.name,input:c,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(o)&&i.length>0&&(o=[...i,...o])),{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=du(t);return mu(n)}function du(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 mu(s){return s.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Oa(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 Gn=(R=>(R.GPT4="gpt-4",R.GPT41="gpt-4.1",R.GPT41Mini="gpt-4.1-mini",R.GPT41Nano="gpt-4.1-nano",R.GPT4O="gpt-4o",R.GPT4OMini="gpt-4o-mini",R.GPT4ChatGPT4O="chatgpt-4o-latest",R.GPT4Turbo="gpt-4-turbo",R.GPT35Turbo="gpt-3.5-turbo",R.GPT35TurboInstruct="gpt-3.5-turbo-instruct",R.GPT35TextDavinci002="text-davinci-002",R.GPT3TextBabbage002="text-babbage-002",R.GPT3TextAda001="text-ada-001",R.GPT5="gpt-5",R.GPT5Nano="gpt-5-nano",R.GPT5Mini="gpt-5-mini",R.GPT5Chat="gpt-5-chat",R.O1="o1",R.O1Mini="o1-mini",R.O3="o3",R.O3Mini="o3-mini",R.O4Mini="o4-mini",R))(Gn||{}),Kt=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Kt||{});var Wt=(y=>(y.GPT4="gpt-4",y.GPT41="gpt-4.1",y.GPT41Mini="gpt-4.1-mini",y.GPT41Nano="gpt-4.1-nano",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.GPT5="gpt-5",y.GPT5Nano="gpt-5-nano",y.GPT5Mini="gpt-5-mini",y.GPT5Chat="gpt-5-chat",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))(Wt||{});var Vt=[{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-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4},{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:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0}},{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:"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}],Fr=[{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-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4},{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:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}}];var gu=s=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(s)||e.includes(s)},Et=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...te()}),_r=()=>structuredClone({...Et(),model:"gpt-5"}),Dr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Ae()}),Nr=()=>({...Et(),model:"gpt-5-nano"}),Ts=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=hu(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,d=gu(n),p={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...i?{tool_choice:i}:{},...d?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...l!==void 0?{frequency_penalty:l}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...c&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...u?{store:u}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(p.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(p.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":p.reasoning_effort=void 0;break;case"minimal":p.reasoning_effort="minimal";break;case"low":p.reasoning_effort="medium";break;case"medium":p.reasoning_effort="high";break;case"high":p.reasoning_effort="high";break;case"highest":p.reasoning_effort="high";break}if(!p.reasoning_effort&&t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"minimal":p.reasoning_effort="minimal";break;case"low":p.reasoning_effort="medium";break;case"medium":case"high":case"highest":p.reasoning_effort="high";break}return this.chatReqUpdater&&(p=this.chatReqUpdater(p)),[r,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:"/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 de(a.message.refusal,e.model,e.id);let l=Ma(a.finish_reason),c=a.message.tool_calls?.map(({id:u,function:{arguments:d,name:p}})=>({id:u,type:"function",function:{name:p,params:d}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(u=>u?.type==="url_citation"&&u.url_citation).map(u=>({url:u.url_citation?.url,title:u.url_citation?.title,description:u.url_citation?.description})),functionCalls:c,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:c,role:u,refusal:d,tool_calls:p,reasoning_content:m,annotations:h},finish_reason:A})=>{if(d)throw new de(d,void 0,n);let g=Ma(A),f=p?.map(({id:x,index:b,function:{name:T,arguments:E}})=>{typeof x=="string"&&typeof b=="number"&&!i.indexIdMap[b]&&(i.indexIdMap[b]=x);let R=i.indexIdMap[b];return R?{id:R,type:"function",function:{name:T,params:E}}:null}).filter(x=>x!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:h?.filter(x=>x?.type==="url_citation"&&x.url_citation).map(x=>({url:x.url_citation?.url,title:x.url_citation?.title,description:x.url_citation?.description})),functionCalls:f,finishReason:g,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)}}},Ma=s=>{switch(s){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function hu(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 he=class extends fe{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 c=new Ts(t,n?.streamingUsage??!0,a);super(c,{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})}},Jt=class extends he{constructor({apiKey:e,apiURL:t,config:n,options:r,models:o,modelInfo:i}){if(!e||e==="")throw new Error("OpenAI API key not set");i=[...Vt,...i??[]];let a=c=>{let u=Ue({model:c,modelInfo:i,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!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:u?.supported?.thinkingBudget??!1,multiTurn:!0}},l=o?.map(c=>{let u=c,d=u?.config;if(!d)return c;let p={};d.maxTokens!==void 0&&(p.maxTokens=d.maxTokens),d.temperature!==void 0&&(p.temperature=d.temperature),d.topP!==void 0&&(p.topP=d.topP),d.presencePenalty!==void 0&&(p.presencePenalty=d.presencePenalty),d.frequencyPenalty!==void 0&&(p.frequencyPenalty=d.frequencyPenalty);let m=d.stopSequences??d.stop;m!==void 0&&(p.stopSequences=m),d.n!==void 0&&(p.n=d.n),d.stream!==void 0&&(p.stream=d.stream);let h={...u};Object.keys(p).length>0&&(h.modelConfig={...u.modelConfig??{},...p});let A=d?.thinking?.thinkingTokenBudget;if(typeof A=="number"){let g=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],f="minimal",x=Number.POSITIVE_INFINITY;for(let[b,T]of g){let E=Math.abs(A-T);E<x&&(x=E,f=b)}h.thinkingTokenBudget=f}return d?.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!d.thinking.includeThoughts),h});super({apiKey:e,apiURL:t,config:{...Et(),...n},options:r,modelInfo:i,models:l??o,supportFor:a}),super.setName("OpenAI")}};var Cs=Et,Ea=Dr,Pa=Nr,Fa=_r,Yt=class extends he{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 c={...Cs(),...o};l=[...Vt,...l??[]];let u=p=>{let m=Ue({model:p,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:m?.supported?.thinkingBudget??!1,hasShowThoughts:m?.supported?.showThoughts??!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?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:i,models:a,modelInfo:l,supportFor:u});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 $r=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.");fu(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(e){let n=(this.serviceFailures.get(this.currentService.getId())?.retries??0)+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:n,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${n}/${this.maxRetries})`,e),n>=this.maxRetries){let r=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`,e),r}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 we))throw n;switch(n.constructor){case yt:throw n;case kt:break;case rt:break;case pt:break;case Qe:break;case Mt:break;default:throw n}if(!this.handleFailure(n))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(!(n instanceof we)||!this.handleFailure(n))throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function fu(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 Pt(s){let e=!1,t=!1,n=!1,r=!1,o=!1,i=!1,a=!1,l=new Set,c=0;if(s.chatPrompt&&Array.isArray(s.chatPrompt))for(let u of s.chatPrompt){if(u.role==="user"&&Array.isArray(u.content))for(let d of u.content)switch(l.add(d.type),d.type){case"image":e=!0,d.cache&&(a=!0),c+=85;break;case"audio":t=!0,d.cache&&(a=!0),c+=d.duration||60;break;case"file":n=!0,d.cache&&(a=!0),c+=Math.ceil((d.extractedText?.length||1e3)/4);break;case"url":r=!0,d.cache&&(a=!0),c+=Math.ceil((d.cachedContent?.length||2e3)/4);break;case"text":d.cache&&(a=!0),c+=Math.ceil(d.text.length/4);break}else"content"in u&&typeof u.content=="string"&&(c+=Math.ceil(u.content.length/4));"cache"in u&&u.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:c}}function Rs(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 Lr(s,e){return s.map(t=>{let n=t.getFeatures(),r=Rs(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 Gr(s,e,t={}){if(e.length===0)throw new Error("No providers available");let n=Pt(s),r=Lr(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 _a(s,e){let t=Pt(s),n=Lr(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 Da(s,e){return s.filter(t=>t.getFeatures().media[e].supported)}function Na(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 Un=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Un||{}),Bn=(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))(Bn||{});var Ur=[{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 vs=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...te()}),La=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Ae()}),ws=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=Au(r),a=e.functions?.map(d=>{let p={};if(d.parameters?.properties)for(let[m,h]of Object.entries(d.parameters.properties))p[m]={description:h.description,type:h.type,required:d.parameters.required?.includes(m)??!1};return{name:d.name,description:d.description,parameter_definitions:p}}),l=e.chatPrompt.filter(d=>d.role==="function").map(d=>{let p=a?.find(m=>m.name===d.functionId);if(!p)throw new Error("Function not found");return{call:{name:p.name,parameters:p.parameter_definitions},outputs:[{result:d.result??""}]}}),c={name:"/chat"},u={message:o,model:t,tools:a,...l&&!o?{tool_results:l}:{},chat_history:i,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},k:e.modelConfig?.topK??this.config.topK,...e.modelConfig?.topP!==void 0?{p:e.modelConfig.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,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:"/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}}},Qt=class extends fe{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...vs(),...t},i=new ws(o),a=r?.map(l=>{let c=l,u=c?.config;if(!u)return l;let d={};u.maxTokens!==void 0&&(d.maxTokens=u.maxTokens),u.temperature!==void 0&&(d.temperature=u.temperature),u.topP!==void 0&&(d.topP=u.topP),u.topK!==void 0&&(d.topK=u.topK),u.presencePenalty!==void 0&&(d.presencePenalty=u.presencePenalty),u.frequencyPenalty!==void 0&&(d.frequencyPenalty=u.frequencyPenalty),u.stopSequences!==void 0&&(d.stopSequences=u.stopSequences),u.endSequences!==void 0&&(d.endSequences=u.endSequences),u.stream!==void 0&&(d.stream=u.stream),u.n!==void 0&&(d.n=u.n);let p={...c};return Object.keys(d).length>0&&(p.modelConfig={...c.modelConfig??{},...d}),p});super(i,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Ur,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:a??r})}};function Au(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=$a(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=$a(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 $a(s){return s?.map(e=>{let t;if(typeof e.function.params=="string"){let n=e.function.params;if(n.trim().length===0)t={};else try{t=JSON.parse(n)}catch{throw new Error(`Failed to parse function params JSON: ${n}`)}}else t=e.function.params;return{name:e.function.name,parameters:t}})}var jn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(jn||{});var Br=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Ss=()=>structuredClone({model:"deepseek-chat",...te()}),Ga=()=>structuredClone({model:"deepseek-coder",...Ae()}),Zt=class extends he{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...Ss(),...t};o=[...Br,...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 zn=(f=>(f.Gemini3ProPreview="gemini-3-pro-preview",f.Gemini3ProImagePreview="gemini-3-pro-image-preview",f.Gemini25Pro="gemini-2.5-pro",f.Gemini25Flash="gemini-2.5-flash",f.Gemini25FlashLite="gemini-2.5-flash-lite",f.Gemini20Flash="gemini-2.0-flash",f.Gemini20FlashLite="gemini-2.0-flash-lite",f.Gemini20ProExp="gemini-2.0-pro-exp-02-05",f.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",f.Gemini1Pro="gemini-1.0-pro",f.Gemini15Flash="gemini-1.5-flash",f.Gemini15Flash002="gemini-1.5-flash-002",f.Gemini15Flash8B="gemini-1.5-flash-8b",f.Gemini15Pro="gemini-1.5-pro",f.GeminiFlashLatest="gemini-flash-latest",f.GeminiFlashLiteLatest="gemini-flash-lite-latest",f.GeminiProLatest="gemini-pro-latest",f))(zn||{}),jr=(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))(jr||{}),zr=(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))(zr||{}),qr=(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))(qr||{}),Os=(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))(Os||{});var Hr=[{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!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},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0}}];var Kr=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,Kr(n)]))),e.items&&(e.items=Kr(e.items)),e},Ua=[{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"}],Ms=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Ua,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...te()}),Ba=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Ua,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Ae()}),ks=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 g=r?"&":"?",f=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${g}key=${f}`}let i=e.chatPrompt.filter(g=>g.role==="system").map(g=>g.content),a=i.length>0?{role:"user",parts:[{text:i.join(" ")}]}:void 0,l=e.chatPrompt.filter(g=>g.role!=="system").map((g,f)=>{switch(g.role){case"user":return{role:"user",parts:Array.isArray(g.content)?g.content.map((b,T)=>{switch(b.type){case"text":return{text:b.text};case"image":return{inlineData:{mimeType:b.mimeType,data:b.image}};case"audio":return{inlineData:{mimeType:`audio/${b.format??"mp3"}`,data:b.data}};case"file":return"fileUri"in b?{fileData:{mimeType:b.mimeType,fileUri:b.fileUri}}:{inlineData:{mimeType:b.mimeType,data:b.data}};default:throw new Error(`Chat prompt content type not supported (index: ${T})`)}}):[{text:g.content}]};case"assistant":{let x=[],b=g.thoughtBlock,T=g.functionCalls&&g.functionCalls.length>0;if(b?.data&&x.push({thought:!0,text:b.data,...b.signature&&!T?{thought_signature:b.signature}:{}}),g.functionCalls){let E=g.functionCalls.map((R,k)=>{let y;if(typeof R.function.params=="string"){let F=R.function.params;if(F.trim().length===0)y={};else try{y=JSON.parse(F)}catch{throw new Error(`Failed to parse function params JSON: ${F}`)}}else y=R.function.params;let O={functionCall:{name:R.function.name,args:y}};return b?.signature&&k===0&&(O.thought_signature=b.signature),O});x.push(...E)}if(g.content&&x.push({text:g.content}),x.length===0)throw new Error("Assistant content is empty");return{role:"model",parts:x}}case"function":{if(!("functionId"in g))throw new Error(`Chat prompt functionId is empty (index: ${f})`);return{role:"user",parts:[{functionResponse:{name:g.functionId,response:{result:g.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(g)} (index: ${f})`)}}),c=[];if(e.functions&&e.functions.length>0){let g=e.functions.map(f=>{let x={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},b=f.parameters?Kr(f.parameters):void 0;return b===void 0||b&&typeof b=="object"&&Object.keys(b).length===0?b={...x}:b&&typeof b=="object"&&b.type==="object"&&(!("properties"in b)||!b.properties||Object.keys(b.properties).length===0)&&(b={...b,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{...f,parameters:b}});c.push({function_declarations:g})}if(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?.googleMaps){let g=this.options.googleMaps,f=g?.enableWidget!==void 0?{enableWidget:g.enableWidget}:{};c.push({google_maps:f})}this.options?.urlContext&&c.push({url_context:{}}),c.length===0&&(c=void 0);let u,d=Array.isArray(c)?c.some(g=>g&&Array.isArray(g.function_declarations)&&g.function_declarations.length>0):!1;if(e.functionCall)if(e.functionCall==="none")u={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")u={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")u={function_calling_config:{mode:"ANY"}};else{let g=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};u={function_calling_config:{mode:"ANY"},...g}}else d&&(u={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(u={...u??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let p={};if(this.config.thinking?.includeThoughts&&(p.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(p.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&(p.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let g=this.config.thinkingTokenBudgetLevels,f=n.includes("gemini-3");switch(t.thinkingTokenBudget){case"none":p.thinkingBudget=0,p.includeThoughts=!1,delete p.thinkingLevel;break;case"minimal":p.thinkingBudget=g?.minimal??200,f&&(p.thinkingLevel="low");break;case"low":p.thinkingBudget=g?.low??800,f&&(p.thinkingLevel="low");break;case"medium":p.thinkingBudget=g?.medium??5e3,f&&(p.thinkingLevel="high");break;case"high":p.thinkingBudget=g?.high??1e4,f&&(p.thinkingLevel="high");break;case"highest":p.thinkingBudget=g?.highest??24500,f&&(p.thinkingLevel="high");break}}p.thinkingLevel&&delete p.thinkingBudget,t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(p.includeThoughts=t.showThoughts);let m={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.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(p).length>0?{thinkingConfig:p}:{}};if(e.responseFormat){if(m.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let g=e.responseFormat.schema.schema||e.responseFormat.schema;m.responseSchema=Kr(g)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(m.responseMimeType="application/json");let h=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:u,systemInstruction:a,generationConfig:m,safetySettings:h}]};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,n=e.candidates?.map(o=>{let i={index:0};switch(o.finishReason){case"MAX_TOKENS":i.finishReason="length";break;case"STOP":i.finishReason="stop";break;case"SAFETY":throw new de("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new de("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new de("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new de("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new de("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new de("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new de("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new de("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new de("Other finish reason",void 0,void 0)}if(!o.content||!o.content.parts)return i;for(let c of o.content.parts){if("text"in c){if("thought"in c&&c.thought||c.thought===!0){i.thought=c.text;let u=c.thoughtSignature||c.thought_signature;i.thoughtBlock={data:c.text,encrypted:!1,...u?{signature:u}:{}}}else i.content=c.text;continue}if("functionCall"in c){let u=c.thoughtSignature||c.thought_signature;u&&(i.thoughtBlock?i.thoughtBlock.signature=u:i.thoughtBlock={data:"",encrypted:!1,signature:u}),i.functionCalls=[...i.functionCalls??[],{id:Te(),type:"function",function:{name:c.functionCall.name,params:c.functionCall.args}}]}}let a=o.citationMetadata?.citations;if(Array.isArray(a)&&a.length){let c=u=>u?`${u.year}-${String(u.month).padStart(2,"0")}-${String(u.day).padStart(2,"0")}`:void 0;i.citations=a.filter(u=>typeof u?.uri=="string").map(u=>({url:u.uri,title:u.title,license:u.license,publicationDate:c(u.publicationDate)}))}let l=o.groundingMetadata;if(l){if(Array.isArray(l.groundingChunks)){let c=l.groundingChunks.map(u=>u?.maps).filter(u=>u&&typeof u.uri=="string").map(u=>({url:u.uri,title:u.title}));c.length&&(i.citations=[...i.citations??[],...c])}typeof l.googleMapsWidgetContextToken=="string"&&(t=l.googleMapsWidgetContextToken)}return i});e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount});let r={results:n};return t&&(r.providerMetadata={...r.providerMetadata,google:{...r.providerMetadata?.google??{},mapsWidgetContextToken:t}}),r};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}}},Xt=class s extends fe{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 c=t!==void 0&&n!==void 0,u,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 g;r?g="endpoints":g="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${g}`,d=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");u="https://generativelanguage.googleapis.com/v1beta",d=async()=>({})}let p={...Ms(),...o},m=new ks(p,c,r,e,i);l=[...Hr,...l??[]];let h=g=>{let f=Ue({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:f?.supported?.thinkingBudget??!1,hasShowThoughts:f?.supported?.showThoughts??!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:f?.supported?.thinkingBudget??!1,multiTurn:!0}},A=a?.map(g=>{let f=g,x=f?.config;if(!x)return g;let b={};x.maxTokens!==void 0&&(b.maxTokens=x.maxTokens),x.temperature!==void 0&&(b.temperature=x.temperature),x.topP!==void 0&&(b.topP=x.topP),x.topK!==void 0&&(b.topK=x.topK),x.presencePenalty!==void 0&&(b.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(b.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(b.stopSequences=x.stopSequences),x.endSequences!==void 0&&(b.endSequences=x.endSequences),x.stream!==void 0&&(b.stream=x.stream),x.n!==void 0&&(b.n=x.n);let T={...f};Object.keys(b).length>0&&(T.modelConfig={...f.modelConfig??{},...b});let E=x.thinking?.thinkingTokenBudget;if(typeof E=="number"){let R=p.thinkingTokenBudgetLevels,k=[["minimal",R?.minimal??200],["low",R?.low??800],["medium",R?.medium??5e3],["high",R?.high??1e4],["highest",R?.highest??24500]],y="minimal",O=Number.POSITIVE_INFINITY;for(let[F,P]of k){let w=Math.abs(E-P);w<O&&(O=w,y=F)}T.thinkingTokenBudget=y}return x.thinking?.includeThoughts!==void 0&&(T.showThoughts=!!x.thinking.includeThoughts),T});super(m,{name:"GoogleGeminiAI",apiURL:u,headers:d,modelInfo:l,defaults:{model:p.model,embedModel:p.embedModel},options:i,supportFor:h,models:A??a})}};var xu=new Se,en=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(xu.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 qn=(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))(qn||{});var Wr=[{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 yu=()=>structuredClone({model:"llama-3.3-70b-versatile",...te()}),tn=class extends he{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let i={...yu(),...t},a={...n,streamingUsage:!1};o=[...Wr,...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 en(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 Vr=[];var Jr=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Jr||{});var Ps=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...te()}),ja=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Ae()}),Es=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:
|
|
153
153
|
${JSON.stringify(e.functions,null,2)}
|
|
154
154
|
`:"",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 c=l.functionCalls?.map(u=>{let d=typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params);return`${u.function.name}(${d})`}).join(`
|
|
155
155
|
`);return c?`Assistant: ${l.content}
|
|
@@ -183,7 +183,7 @@ ${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
|
|
|
183
183
|
|
|
184
184
|
`,o+=c.length)}else r=`${i}
|
|
185
185
|
|
|
186
|
-
`,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},wu=(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 Xn=class{data=[];seenTags=new Set;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,thought:r,thoughtBlock:o,index:i}){let a=this.data.at(-1);if(!a||a.role!=="assistant"||a.role==="assistant"&&!a.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlock:o})}]});return}let l=a.chat.find(c=>c.index===i);if(!l){a.chat.push({index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlock:o})});return}if(typeof e=="string"&&e.trim()!==""&&(l.value.content=e),typeof t=="string"&&t.trim()!==""&&(l.value.name=t),Array.isArray(n)&&n.length>0&&(l.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let c=l.value.thought;l.value.thought=typeof c=="string"?c+r:r}if(o&&typeof o=="object"){let c=l.value.thoughtBlock??{},u={data:(c.data??"")+(o.data??""),encrypted:!!c.encrypted||!!o.encrypted,...o.signature?{signature:o.signature}:{}};l.value.thoughtBlock=u}}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]: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=[],this.seenTags=new Set}},fn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Xn}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Xn),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)qt(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Er(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)}removeByTag(e,t){return this.getMemory(t).removeByTag(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 Xn):this.defaultMemory.reset()}};var ot=class extends Error{constructor({message:e}){super(e),this.name="AxAssertionError"}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()}},uo=async(s,e)=>{for(let t of s){let{fn:n,message:r}=t,o=await n(e);if(o!==void 0){if(typeof o=="string")throw new ot({message:o});if(!o)throw r?new ot({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},qs=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,c=await l(o,n);if(c!==void 0){if(typeof c=="string")throw new ot({message:c});if(!c&&a)throw new ot({message:a})}}};var Hs={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},er,Ks=s=>{if(er)return er;let e=s??ee.meter;if(e)return er=vu(e),er};var tl=()=>{let s=[];return ee.meter||s.push("Global meter not initialized"),!er&&ee.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},vu=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"})}),po=Hs,nl=s=>{po={...po,...s}},rl=()=>({...po}),tt=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=po.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},ol=(s,e,t,n,r,o)=>{try{let i=tt({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)}},mo=(s,e,t,n)=>{try{let r=tt({...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)}},Ws=(s,e,t)=>{try{let n=tt({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)}},sl=(s,e)=>{try{let t=tt({error_type:"refusal",...e?{signature:e}:{}});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},Vs=(s,e,t,n,r)=>{try{let o=tt({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)}},il=(s,e,t,n,r=!1,o)=>{try{let i=tt({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)}},al=(s,e,t,n)=>{try{let r=tt({...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)}},ll=(s,e,t,n,r)=>{try{let o=tt({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)}},cl=(s,e,t,n,r)=>{try{let o=tt({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)}},ul=(s,e,t,n,r,o)=>{try{let i=tt({...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)}},go=(s,e,t,n)=>{try{let r=tt({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 An=s=>{let e=(()=>{switch(s?.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 s?.isArray?`json array of ${e} items`:e},ye=class extends Error{constructor(e){super(e),this.name="ValidationError"}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field **Only return the invalid, remaining fields**",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},pl=s=>{let t=s.map(n=>`'${n.title}' (${An(n.type)})`).join(", ");return new ye(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${s[0]?.title}:") and then provide a valid ${An(s[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},ho=s=>new ye(`Expected (Required) field not found: '${s.title}'. Begin a new section with "${s.title}:" and then provide a valid ${An(s.type)} value directly after.`);var fo=s=>new ye(`Required field is missing: '${s.title}'. After the "${s.title}:" label, provide a non-empty ${An(s.type)}. Do not use null, undefined, or leave it blank.`),dl=(s,e)=>new ye(`Invalid JSON: ${e} in field '${s.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),ml=(s,e)=>new ye(`Invalid Array: ${e} for '${s.title}'. Provide a JSON array of ${An(s.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),gl=(s,e,t)=>new ye(`Field '${s.title}' has an invalid value '${e}': ${t}. Provide a ${An(s.type)}. Ensure formatting exactly matches the expected type.`),hl=(s,e,t)=>new ye(`Invalid date for '${s.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),fl=(s,e,t)=>new ye(`Invalid date/time for '${s.title}': ${t}. Use the format YYYY-MM-DD HH:mm or YYYY-MM-DD HH:mm:ss followed by a valid timezone (e.g., America/New_York). You provided: ${e}.`),Js=(s,e,t)=>new ye(`Invalid URL for '${s.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),xn=(s,e,t,n)=>{let r=`Field '${s.title}' failed validation: `;return t==="minLength"?r+=`String must be at least ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="maxLength"?r+=`String must be at most ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="pattern"?r+=`String must match pattern /${n}/. You provided: "${e}".`:t==="format"&&(r+=`String must be a ${n}. You provided: "${e}".`),new ye(r)},Ys=(s,e,t,n)=>{let r=`Field '${s.title}' failed validation: `;return t==="minimum"?r+=`Number must be at least ${n}. You provided: ${e}.`:t==="maximum"&&(r+=`Number must be at most ${n}. You provided: ${e}.`),new ye(r)};var Al=({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(c=>c.title).join(", ")??"";oa(s,e,l,n)}return r&&Ws(r,"validation",o),i&&i.addEvent("validation.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},xl=({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(c=>c.title).join(", ")??"";sa(s,e,l,n)}return r&&Ws(r,"assertion",o),i&&i.addEvent("assertion.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},yl=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{t&&n&&ia(s,e,n),r&&sl(r,o),i&&i.addEvent("refusal.error",{message:s.toString()})};function bl(s,e){if(!e)return s;let t=[];if(e.format==="email"&&t.push("Must be a valid email address format"),(e.format==="uri"||e.format==="url"||e.name==="url")&&t.push("Must be a valid URL format"),(e.name==="string"||e.name==="code"||e.name==="url"||e.name==="date"||e.name==="datetime")&&(e.minLength!==void 0&&e.maxLength!==void 0?t.push(`Minimum length: ${e.minLength} characters, maximum length: ${e.maxLength} characters`):e.minLength!==void 0?t.push(`Minimum length: ${e.minLength} characters`):e.maxLength!==void 0&&t.push(`Maximum length: ${e.maxLength} characters`)),e.name==="number"&&(e.minimum!==void 0&&e.maximum!==void 0?t.push(`Minimum value: ${e.minimum}, maximum value: ${e.maximum}`):e.minimum!==void 0?t.push(`Minimum value: ${e.minimum}`):e.maximum!==void 0&&t.push(`Maximum value: ${e.maximum}`)),e.pattern!==void 0){if(!e.patternDescription)throw new Error(`Field with pattern '${e.pattern}' must include a patternDescription to explain the pattern to the LLM`);t.push(e.patternDescription)}if(e.name==="date"&&t.push("Format: YYYY-MM-DD"),e.name==="datetime"&&t.push("Format: ISO 8601 date-time"),t.length===0)return s;let n=t.join(". ");return!s||s.trim().length===0?n:`${s.trim().endsWith(".")?s.trim():`${s.trim()}.`} ${n}`}function yo(s,e="Schema"){if("name"in s&&"type"in s)return Ao(s);let t={},n=[];for(let r of s){if(r.isInternal)continue;let o=Ao(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function Ao(s,e=!1){let t=s.type,n=bl(s.description,t);if(e&&t?.name&&(t.name==="image"||t.name==="audio"||t.name==="file"))throw new Error(`Media type '${t.name}' is not allowed in nested object fields. Media types (image, audio, file) can only be used as top-level input fields. Field: ${s.name}`);let r={};if(n&&(r.description=n),t?.isArray)if(r.type="array",t.fields){r.items={type:"object",properties:{},required:[],additionalProperties:!1};for(let[o,i]of Object.entries(t.fields)){let a={name:o,description:i.description,type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format},isOptional:i.isOptional,isInternal:i.isInternal};r.items.properties[o]=Ao(a,!0),i.isOptional||r.items.required.push(o)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let o=bl(s.description,t);r.items={type:Il(t.name)},o&&(r.items.description=o),t.name==="string"||t.name==="code"||t.name==="url"||t.name==="date"||t.name==="datetime"?(t.minLength!==void 0&&(r.items.minLength=t.minLength),t.maxLength!==void 0&&(r.items.maxLength=t.maxLength),t.pattern!==void 0&&(r.items.pattern=t.pattern),t.format!==void 0&&(r.items.format=t.format)):t.name==="number"&&(t.minimum!==void 0&&(r.items.minimum=t.minimum),t.maximum!==void 0&&(r.items.maximum=t.maximum))}else if(t?.name==="object"&&t.fields){r.type="object",r.properties={},r.required=[],r.additionalProperties=!1;for(let[o,i]of Object.entries(t.fields)){let a={name:o,description:i.description,type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format},isOptional:i.isOptional,isInternal:i.isInternal};r.properties[o]=Ao(a,!0),i.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=Il(t?.name??"string"),t?.name==="string"||t?.name==="code"||t?.name==="url"||t?.name==="date"||t?.name==="datetime"?(t.minLength!==void 0&&(r.minLength=t.minLength),t.maxLength!==void 0&&(r.maxLength=t.maxLength),t.pattern!==void 0&&(r.pattern=t.pattern),t.format!==void 0&&(r.format=t.format),t.name==="url"&&!t.format&&(r.format="uri"),t.name==="date"&&!t.format&&(r.format="date"),t.name==="datetime"&&!t.format&&(r.format="date-time")):t?.name==="number"&&(t.minimum!==void 0&&(r.minimum=t.minimum),t.maximum!==void 0&&(r.maximum=t.maximum)));return r}function Il(s){switch(s){case"string":case"code":case"url":case"date":case"datetime":case"image":case"audio":case"file":return"string";case"number":return"number";case"boolean":return"boolean";case"json":case"object":return["object","array","string","number","boolean","null"];default:return"string"}}function xo(s){if(!s||typeof s!="object")throw new Error("Schema must be an object");if(s.type==="array"){if(!s.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');xo(s.items)}else if(s.type==="object"&&s.properties)for(let e of Object.values(s.properties))xo(e)}var Ft=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},tr=class extends Error{constructor(t){super();this.fields=t;this.name="AxFunctionError"}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
|
|
186
|
+
`,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},wu=(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 Xn=class{data=[];seenTags=new Set;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,thought:r,thoughtBlock:o,index:i}){let a=this.data.at(-1);if(!a||a.role!=="assistant"||a.role==="assistant"&&!a.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlock:o})}]});return}let l=a.chat.find(c=>c.index===i);if(!l){a.chat.push({index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlock:o})});return}if(typeof e=="string"&&e.trim()!==""&&(l.value.content=e),typeof t=="string"&&t.trim()!==""&&(l.value.name=t),Array.isArray(n)&&n.length>0&&(l.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let c=l.value.thought;l.value.thought=typeof c=="string"?c+r:r}if(o&&typeof o=="object"){let c=l.value.thoughtBlock??{},u={data:(c.data??"")+(o.data??""),encrypted:!!c.encrypted||!!o.encrypted,...o.signature?{signature:o.signature}:{}};l.value.thoughtBlock=u}}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]: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=[],this.seenTags=new Set}},fn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Xn}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Xn),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)qt(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Er(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)}removeByTag(e,t){return this.getMemory(t).removeByTag(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 Xn):this.defaultMemory.reset()}};var ot=class extends Error{constructor({message:e}){super(e),this.name="AxAssertionError"}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()}},uo=async(s,e)=>{for(let t of s){let{fn:n,message:r}=t,o=await n(e);if(o!==void 0){if(typeof o=="string")throw new ot({message:o});if(!o)throw r?new ot({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},qs=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,c=await l(o,n);if(c!==void 0){if(typeof c=="string")throw new ot({message:c});if(!c&&a)throw new ot({message:a})}}};var Hs={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},er,Ks=s=>{if(er)return er;let e=s??ee.meter;if(e)return er=vu(e),er};var tl=()=>{let s=[];return ee.meter||s.push("Global meter not initialized"),!er&&ee.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},vu=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"})}),po=Hs,nl=s=>{po={...po,...s}},rl=()=>({...po}),tt=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=po.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},ol=(s,e,t,n,r,o)=>{try{let i=tt({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)}},mo=(s,e,t,n)=>{try{let r=tt({...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)}},Ws=(s,e,t)=>{try{let n=tt({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)}},sl=(s,e)=>{try{let t=tt({error_type:"refusal",...e?{signature:e}:{}});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},Vs=(s,e,t,n,r)=>{try{let o=tt({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)}},il=(s,e,t,n,r=!1,o)=>{try{let i=tt({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)}},al=(s,e,t,n)=>{try{let r=tt({...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)}},ll=(s,e,t,n,r)=>{try{let o=tt({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)}},cl=(s,e,t,n,r)=>{try{let o=tt({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)}},ul=(s,e,t,n,r,o)=>{try{let i=tt({...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)}},go=(s,e,t,n)=>{try{let r=tt({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 An=s=>{let e=(()=>{switch(s?.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 s?.isArray?`json array of ${e} items`:e},be=class extends Error{constructor(e){super(e),this.name="ValidationError"}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field **Only return the invalid, remaining fields**",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},pl=s=>{let t=s.map(n=>`'${n.title}' (${An(n.type)})`).join(", ");return new be(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${s[0]?.title}:") and then provide a valid ${An(s[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},ho=s=>new be(`Expected (Required) field not found: '${s.title}'. Begin a new section with "${s.title}:" and then provide a valid ${An(s.type)} value directly after.`);var fo=s=>new be(`Required field is missing: '${s.title}'. After the "${s.title}:" label, provide a non-empty ${An(s.type)}. Do not use null, undefined, or leave it blank.`),dl=(s,e)=>new be(`Invalid JSON: ${e} in field '${s.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),ml=(s,e)=>new be(`Invalid Array: ${e} for '${s.title}'. Provide a JSON array of ${An(s.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),gl=(s,e,t)=>new be(`Field '${s.title}' has an invalid value '${e}': ${t}. Provide a ${An(s.type)}. Ensure formatting exactly matches the expected type.`),hl=(s,e,t)=>new be(`Invalid date for '${s.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),fl=(s,e,t)=>new be(`Invalid date/time for '${s.title}': ${t}. Use the format YYYY-MM-DD HH:mm or YYYY-MM-DD HH:mm:ss followed by a valid timezone (e.g., America/New_York). You provided: ${e}.`),Js=(s,e,t)=>new be(`Invalid URL for '${s.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),xn=(s,e,t,n)=>{let r=`Field '${s.title}' failed validation: `;return t==="minLength"?r+=`String must be at least ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="maxLength"?r+=`String must be at most ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="pattern"?r+=`String must match pattern /${n}/. You provided: "${e}".`:t==="format"&&(r+=`String must be a ${n}. You provided: "${e}".`),new be(r)},Ys=(s,e,t,n)=>{let r=`Field '${s.title}' failed validation: `;return t==="minimum"?r+=`Number must be at least ${n}. You provided: ${e}.`:t==="maximum"&&(r+=`Number must be at most ${n}. You provided: ${e}.`),new be(r)};var Al=({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(c=>c.title).join(", ")??"";oa(s,e,l,n)}return r&&Ws(r,"validation",o),i&&i.addEvent("validation.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},xl=({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(c=>c.title).join(", ")??"";sa(s,e,l,n)}return r&&Ws(r,"assertion",o),i&&i.addEvent("assertion.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},yl=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{t&&n&&ia(s,e,n),r&&sl(r,o),i&&i.addEvent("refusal.error",{message:s.toString()})};function bl(s,e){if(!e)return s;let t=[];if(e.format==="email"&&t.push("Must be a valid email address format"),(e.format==="uri"||e.format==="url"||e.name==="url")&&t.push("Must be a valid URL format"),(e.name==="string"||e.name==="code"||e.name==="url"||e.name==="date"||e.name==="datetime")&&(e.minLength!==void 0&&e.maxLength!==void 0?t.push(`Minimum length: ${e.minLength} characters, maximum length: ${e.maxLength} characters`):e.minLength!==void 0?t.push(`Minimum length: ${e.minLength} characters`):e.maxLength!==void 0&&t.push(`Maximum length: ${e.maxLength} characters`)),e.name==="number"&&(e.minimum!==void 0&&e.maximum!==void 0?t.push(`Minimum value: ${e.minimum}, maximum value: ${e.maximum}`):e.minimum!==void 0?t.push(`Minimum value: ${e.minimum}`):e.maximum!==void 0&&t.push(`Maximum value: ${e.maximum}`)),e.pattern!==void 0){if(!e.patternDescription)throw new Error(`Field with pattern '${e.pattern}' must include a patternDescription to explain the pattern to the LLM`);t.push(e.patternDescription)}if(e.name==="date"&&t.push("Format: YYYY-MM-DD"),e.name==="datetime"&&t.push("Format: ISO 8601 date-time"),t.length===0)return s;let n=t.join(". ");return!s||s.trim().length===0?n:`${s.trim().endsWith(".")?s.trim():`${s.trim()}.`} ${n}`}function yo(s,e="Schema"){if("name"in s&&"type"in s)return Ao(s);let t={},n=[];for(let r of s){if(r.isInternal)continue;let o=Ao(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function Ao(s,e=!1){let t=s.type,n=bl(s.description,t);if(e&&t?.name&&(t.name==="image"||t.name==="audio"||t.name==="file"))throw new Error(`Media type '${t.name}' is not allowed in nested object fields. Media types (image, audio, file) can only be used as top-level input fields. Field: ${s.name}`);let r={};if(n&&(r.description=n),t?.isArray)if(r.type="array",t.fields){r.items={type:"object",properties:{},required:[],additionalProperties:!1};for(let[o,i]of Object.entries(t.fields)){let a={name:o,description:i.description,type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format},isOptional:i.isOptional,isInternal:i.isInternal};r.items.properties[o]=Ao(a,!0),i.isOptional||r.items.required.push(o)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let o=bl(s.description,t);r.items={type:Il(t.name)},o&&(r.items.description=o),t.name==="string"||t.name==="code"||t.name==="url"||t.name==="date"||t.name==="datetime"?(t.minLength!==void 0&&(r.items.minLength=t.minLength),t.maxLength!==void 0&&(r.items.maxLength=t.maxLength),t.pattern!==void 0&&(r.items.pattern=t.pattern),t.format!==void 0&&(r.items.format=t.format)):t.name==="number"&&(t.minimum!==void 0&&(r.items.minimum=t.minimum),t.maximum!==void 0&&(r.items.maximum=t.maximum))}else if(t?.name==="object"&&t.fields){r.type="object",r.properties={},r.required=[],r.additionalProperties=!1;for(let[o,i]of Object.entries(t.fields)){let a={name:o,description:i.description,type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format},isOptional:i.isOptional,isInternal:i.isInternal};r.properties[o]=Ao(a,!0),i.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=Il(t?.name??"string"),t?.name==="string"||t?.name==="code"||t?.name==="url"||t?.name==="date"||t?.name==="datetime"?(t.minLength!==void 0&&(r.minLength=t.minLength),t.maxLength!==void 0&&(r.maxLength=t.maxLength),t.pattern!==void 0&&(r.pattern=t.pattern),t.format!==void 0&&(r.format=t.format),t.name==="url"&&!t.format&&(r.format="uri"),t.name==="date"&&!t.format&&(r.format="date"),t.name==="datetime"&&!t.format&&(r.format="date-time")):t?.name==="number"&&(t.minimum!==void 0&&(r.minimum=t.minimum),t.maximum!==void 0&&(r.maximum=t.maximum)));return r}function Il(s){switch(s){case"string":case"code":case"url":case"date":case"datetime":case"image":case"audio":case"file":return"string";case"number":return"number";case"boolean":return"boolean";case"json":case"object":return["object","array","string","number","boolean","null"];default:return"string"}}function xo(s){if(!s||typeof s!="object")throw new Error("Schema must be an object");if(s.type==="array"){if(!s.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');xo(s.items)}else if(s.type==="object"&&s.properties)for(let e of Object.values(s.properties))xo(e)}var Ft=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},tr=class extends Error{constructor(t){super();this.fields=t;this.name="AxFunctionError"}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
|
|
187
187
|
`)}[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}'
|
|
188
188
|
${t.join(`
|
|
189
189
|
`)}`};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(`
|
|
@@ -194,10 +194,10 @@ Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } }
|
|
|
194
194
|
`)+A.title}:`,x=Dl(n,f,t.s);if(x===-2||x===-3)return!0;if(x===-4)return t.inBlock=!0,!0;x>=0&&(p===-1||x<p)&&(p=x,m=f.length,u=h,d=A)}if(p===-1){if(o)return;if(!r&&t.currField===void 0&&t.extractedFields.length===0&&i.length===1){t.inAssumedField=!0,t.currField=i[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(i[0])||t.extractedFields.push(i[0]),t.streamedIndex[i[0].name]===void 0&&(t.streamedIndex[i[0].name]=0);return}if(r&&t.currField===void 0&&t.extractedFields.length===0){let h=i.find(A=>!A.isOptional);if(h)throw ho(h)}break}if(a&&d&&a.name!==d.name)throw ho(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let h=n.substring(t.s,p).trim(),A=Co(t.currField,h);A!==void 0&&(e[t.currField.name]=A),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:p}):t.prevFields=[{field:t.currField,s:t.s,e:p}]}t.s=p+m,d!==void 0&&u!==void 0&&(t.currField=d,t.currFieldIndex=u),d&&!t.extractedFields.includes(d)&&t.extractedFields.push(d),d&&t.streamedIndex[d.name]===void 0&&(t.streamedIndex[d.name]=0)}},ui=(s,e,t,n,r)=>{let o=r?.strictMode??!1,i=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,l=r?.forceFinalize??!1;if(t.currField){let c=n.length,u=s.getOutputFields();for(let m of u){if(m.name===t.currField.name)continue;let h=`
|
|
195
195
|
${m.title}:`,A=n.indexOf(h,t.s);A!==-1&&A<c&&(c=A)}let d=n.substring(t.s,c).trim(),p=Co(t.currField,d);p!==void 0&&(e[t.currField.name]=p)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let d=s.getOutputFields().find(p=>!p.isOptional);if(d)throw ho(d)}if(Eu(s,e,n,t),!i){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?li(t,e,s.getOutputFields()):c||li(t,e,s.getOutputFields())}},Eu=(s,e,t,n)=>{let r=s.getOutputFields();if(r.length===1){let i=r[0];if(i){let a=`${i.title}:`,l=t.indexOf(a);if(l!==-1){let c=l+a.length,u=`
|
|
196
196
|
${i.title}:`,d=t.indexOf(u,c),p=t.substring(c,d===-1?t.length:d).trim();if(p)try{let m=Co(i,p);if(m!==void 0){e[i.name]=m;return}}catch{}}}}let o=t.split(`
|
|
197
|
-
`);for(let i of r){if(i.name in e)continue;let a=`${i.title}:`;for(let l of o){let c=l.trim();if(c.startsWith(a)){let u=c.substring(a.length).trim();if(u)try{let d=Co(i,u);if(d!==void 0){e[i.name]=d;break}}catch(d){if(!i.isOptional)throw d}break}}}},Nl=(s,e,t=!1)=>{switch(s.type?.name){case"code":return Ll(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 El(s,e,t);case"datetime":return Pl(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*$l(s,e,t,n,r,o){let{name:i,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[i]??0,d=u===0,p=(t<0?0:t)+u,m=s.substring(p,n);if(m.length===0)return;let h=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(h=h.replace(/\s*```\s*$/,""));let A=d?h.trimStart():h;r.currField?.type?.name==="code"&&(A=A.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),A.length>0&&(yield{index:o,delta:{[i]:A}},r.streamedIndex[i]=u+h.length)}function*pi(s,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:l,e:c}=i;yield*$l(e,a,l,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(s.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*$l(e,n.currField,n.s,e.length,n,r);let o=s.getOutputFields();for(let i of Object.keys(t)){let a=o.find(u=>u.name===i);if(!a||a.isInternal)continue;let l=t[i];if(Array.isArray(l)){let u=n.streamedIndex?.[i]??0,d=l.slice(u);d&&d.length>0&&(yield{index:r,delta:{[i]:d}},n.streamedIndex[i]=u+d.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[i])yield{index:r,delta:{[i]:l}},n.streamedIndex[i]=c?c.length:1;else if(c){let u=n.streamedIndex[i];if(c.length>u){let d=c.substring(u);yield{index:r,delta:{[i]:d}},n.streamedIndex[i]=c.length}}}}function Co(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw fo(s)}let t;if(s.type?.name==="json")try{let r=Ll(e);return t=JSON.parse(r),t}catch(r){throw dl(s,r.message)}if(s.type?.isArray)try{try{t=JSON.parse(e)}catch{t=_l(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw ml(s,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let i=typeof o=="string"?o.trim():o;t[r]=Nl(s,i,!0)}}else t=Nl(s,e)}catch(r){throw gl(s,e,r.message)}if(typeof t=="string"&&t==="")return;let n=s.type;if(n&&t!==void 0&&(n.name==="url"&&Ct(t,s),(n.name==="string"||n.name==="code")&&qe(t,s),n.name==="number"&&He(t,s),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?qe(r,s):n.name==="number"&&He(r,s));return t}function vo(s,e){let t=s.getOutputFields();for(let n of t){let r=e[n.name];if(r==null){if(!n.isOptional)throw fo(n);continue}let o=n.type;if(o){if(o.name==="url"&&Ct(r,n),(o.name==="string"||o.name==="code")&&qe(r,n),o.name==="number"&&He(r,n),o.isArray&&Array.isArray(r))for(let i of r)i!=null&&(o.name==="url"?Ct(i,n):o.name==="string"||o.name==="code"?qe(i,n):o.name==="number"&&He(i,n));if(o.name==="object"&&o.fields&&typeof r=="object"&&Ro(n,r),o.isArray&&o.fields&&Array.isArray(r)&&o.name==="object")for(let i of r)i&&typeof i=="object"&&Ro(n,i)}}}function Ro(s,e){let t=s.type?.fields;if(!(!t||typeof t!="object"))for(let[n,r]of Object.entries(t)){let o={name:n,title:n,description:r.description,type:{name:r.type,isArray:r.isArray,options:r.options,fields:r.fields,minLength:r.minLength,maxLength:r.maxLength,minimum:r.minimum,maximum:r.maximum,pattern:r.pattern,patternDescription:r.patternDescription,format:r.format},isOptional:r.isOptional??!1,isInternal:r.isInternal??!1},i=e[o.name];if(i==null){if(!o.isOptional)throw fo(o);continue}let a=o.type;if(a){if(a.name==="url"&&Ct(i,o),(a.name==="string"||a.name==="code")&&qe(i,o),a.name==="number"&&He(i,o),a.isArray&&Array.isArray(i))for(let l of i)l!=null&&(a.name==="url"?Ct(l,o):a.name==="string"||a.name==="code"?qe(l,o):a.name==="number"&&He(l,o));if(a.name==="object"&&a.fields&&typeof i=="object"&&!Array.isArray(i)&&Ro(o,i),a.isArray&&a.fields&&Array.isArray(i)&&a.name==="object")for(let l of i)l&&typeof l=="object"&&Ro(o,l)}}}var Ll=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 di(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});Gl(r.field,t,i,n)}}async function mi(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 c=a.process,u=await c(l,{sessionId:o,values:r,done:i});Gl(t.currField,n,u,o)}}var Gl=(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=Pu(s,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function Pu(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*Ul({res:s,usage:e,states:t,debug:n,...r}){let o=(r.ai.getFeatures().functionCot??!1)&&r.functions!==void 0&&r.functions.length>0,i,a=[],l=s.getReader();try{for(;;){let{done:c,value:u}=await l.read();if(c)break;let d=u;d.modelUsage&&(i=d.modelUsage);for(let p of d.results){if(Array.isArray(p.citations))for(let h of p.citations)h?.url&&a.push({url:h.url,title:h.title,description:h.description,license:h.license,publicationDate:h.publicationDate,snippet:h.snippet});if((!p.content||p.content==="")&&(!p.thought||p.thought==="")&&!p.thoughtBlock&&(!p.functionCalls||p.functionCalls.length===0))continue;let m=t.find(h=>h.index===p.index);if(!m)throw new Error(`No state found for result (index: ${p.index})`);yield*Fu({...r,result:p,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*_u({...r,state:c,debug:n});if(i){if(a.length){let c=Array.from(new Map(a.filter(u=>u.url).map(u=>[u.url,u])).values());i.citations=c}if(e.push(i),n&&r.logger){let c=structuredClone(i);delete c.citations,r.logger({name:"ChatResponseUsage",value:c}),i.citations&&i.citations.length>0&&r.logger({name:"ChatResponseCitations",value:i.citations})}}}async function*Fu({result:s,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:i,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:d}){if(s.functionCalls&&s.functionCalls.length>0)kr(i.functionCalls,s.functionCalls),e.updateResult({name:s.name,content:s.content,functionCalls:i.functionCalls,delta:s.functionCalls?.[0]?.function?.params,index:s.index},t);else if(s.content&&s.content.length>0){s.thought&&s.thought.length>0&&(yield{index:s.index,delta:{[c]:s.thought}}),i.content+=s.content,e.updateResult({name:s.name,content:i.content,delta:s.content,index:s.index},t);let p=a.getOutputFields();if(p.some(A=>A.type?.name==="object"||A.type?.isArray&&A.type.fields)){let A=Cl(i.content);if(A&&typeof A=="object"){let g={};for(let f of Object.keys(A))p.some(x=>x.name===f)&&(g[f]=A[f]);vo(a,g),Object.assign(i.values,g),yield{index:s.index,delta:g};return}}if(ci(a,i.values,i.xstate,i.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await qs(u,i.xstate,i.content),l.length!==0&&await mi(l,i.content,i.xstate,e,i.values,t),yield*pi(a,i.content,i.values,i.xstate,s.index),await uo(d,i.values)}else s.thought&&s.thought.length>0?(i.values[c]=(i.values[c]??"")+s.thought,yield{index:s.index,delta:{[c]:s.thought}},e.updateResult({name:s.name,content:i.content,delta:"",index:s.index,thought:s.thought,thoughtBlock:s.thoughtBlock},t)):s.thoughtBlock&&e.updateResult({name:s.name,content:i.content,delta:"",index:s.index,thoughtBlock:s.thoughtBlock},t);if(s.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
197
|
+
`);for(let i of r){if(i.name in e)continue;let a=`${i.title}:`;for(let l of o){let c=l.trim();if(c.startsWith(a)){let u=c.substring(a.length).trim();if(u)try{let d=Co(i,u);if(d!==void 0){e[i.name]=d;break}}catch(d){if(!i.isOptional)throw d}break}}}},Nl=(s,e,t=!1)=>{switch(s.type?.name){case"code":return Ll(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 El(s,e,t);case"datetime":return Pl(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*$l(s,e,t,n,r,o){let{name:i,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[i]??0,d=u===0,p=(t<0?0:t)+u,m=s.substring(p,n);if(m.length===0)return;let h=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(h=h.replace(/\s*```\s*$/,""));let A=d?h.trimStart():h;r.currField?.type?.name==="code"&&(A=A.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),A.length>0&&(yield{index:o,delta:{[i]:A}},r.streamedIndex[i]=u+h.length)}function*pi(s,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:l,e:c}=i;yield*$l(e,a,l,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(s.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*$l(e,n.currField,n.s,e.length,n,r);let o=s.getOutputFields();for(let i of Object.keys(t)){let a=o.find(u=>u.name===i);if(!a||a.isInternal)continue;let l=t[i];if(Array.isArray(l)){let u=n.streamedIndex?.[i]??0,d=l.slice(u);d&&d.length>0&&(yield{index:r,delta:{[i]:d}},n.streamedIndex[i]=u+d.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[i])yield{index:r,delta:{[i]:l}},n.streamedIndex[i]=c?c.length:1;else if(c){let u=n.streamedIndex[i];if(c.length>u){let d=c.substring(u);yield{index:r,delta:{[i]:d}},n.streamedIndex[i]=c.length}}}}function Co(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw fo(s)}let t;if(s.type?.name==="json")try{let r=Ll(e);return t=JSON.parse(r),t}catch(r){throw dl(s,r.message)}if(s.type?.isArray)try{try{t=JSON.parse(e)}catch{t=_l(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw ml(s,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let i=typeof o=="string"?o.trim():o;t[r]=Nl(s,i,!0)}}else t=Nl(s,e)}catch(r){throw gl(s,e,r.message)}if(typeof t=="string"&&t==="")return;let n=s.type;if(n&&t!==void 0&&(n.name==="url"&&Ct(t,s),(n.name==="string"||n.name==="code")&&qe(t,s),n.name==="number"&&He(t,s),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?qe(r,s):n.name==="number"&&He(r,s));return t}function vo(s,e){let t=s.getOutputFields();for(let n of t){let r=e[n.name];if(r==null){if(!n.isOptional)throw fo(n);continue}let o=n.type;if(o){if(o.name==="url"&&Ct(r,n),(o.name==="string"||o.name==="code")&&qe(r,n),o.name==="number"&&He(r,n),o.isArray&&Array.isArray(r))for(let i of r)i!=null&&(o.name==="url"?Ct(i,n):o.name==="string"||o.name==="code"?qe(i,n):o.name==="number"&&He(i,n));if(o.name==="object"&&o.fields&&typeof r=="object"&&Ro(n,r),o.isArray&&o.fields&&Array.isArray(r)&&o.name==="object")for(let i of r)i&&typeof i=="object"&&Ro(n,i)}}}function Ro(s,e){let t=s.type?.fields;if(!(!t||typeof t!="object"))for(let[n,r]of Object.entries(t)){let o={name:n,title:n,description:r.description,type:{name:r.type,isArray:r.isArray,options:r.options,fields:r.fields,minLength:r.minLength,maxLength:r.maxLength,minimum:r.minimum,maximum:r.maximum,pattern:r.pattern,patternDescription:r.patternDescription,format:r.format},isOptional:r.isOptional??!1,isInternal:r.isInternal??!1},i=e[o.name];if(i==null){if(!o.isOptional)throw fo(o);continue}let a=o.type;if(a){if(a.name==="url"&&Ct(i,o),(a.name==="string"||a.name==="code")&&qe(i,o),a.name==="number"&&He(i,o),a.isArray&&Array.isArray(i))for(let l of i)l!=null&&(a.name==="url"?Ct(l,o):a.name==="string"||a.name==="code"?qe(l,o):a.name==="number"&&He(l,o));if(a.name==="object"&&a.fields&&typeof i=="object"&&!Array.isArray(i)&&Ro(o,i),a.isArray&&a.fields&&Array.isArray(i)&&a.name==="object")for(let l of i)l&&typeof l=="object"&&Ro(o,l)}}}var Ll=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 di(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});Gl(r.field,t,i,n)}}async function mi(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 c=a.process,u=await c(l,{sessionId:o,values:r,done:i});Gl(t.currField,n,u,o)}}var Gl=(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=Pu(s,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function Pu(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*Ul({res:s,usage:e,states:t,debug:n,...r}){let o=(r.ai.getFeatures().functionCot??!1)&&r.functions!==void 0&&r.functions.length>0,i,a=[],l=s.getReader();try{for(;;){let{done:c,value:u}=await l.read();if(c)break;let d=u;d.modelUsage&&(i=d.modelUsage);for(let p of d.results){if(Array.isArray(p.citations))for(let h of p.citations)h?.url&&a.push({url:h.url,title:h.title,description:h.description,license:h.license,publicationDate:h.publicationDate,snippet:h.snippet});if((!p.content||p.content==="")&&(!p.thought||p.thought==="")&&!p.thoughtBlock&&(!p.functionCalls||p.functionCalls.length===0))continue;let m=t.find(h=>h.index===p.index);if(!m)throw new Error(`No state found for result (index: ${p.index})`);yield*Fu({...r,result:p,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*_u({...r,state:c,debug:n});if(i){if(a.length){let c=Array.from(new Map(a.filter(u=>u.url).map(u=>[u.url,u])).values());i.citations=c}if(e.push(i),n&&r.logger){let c=structuredClone(i);delete c.citations,r.logger({name:"ChatResponseUsage",value:c}),i.citations&&i.citations.length>0&&r.logger({name:"ChatResponseCitations",value:i.citations})}}}async function*Fu({result:s,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:i,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:d}){if(s.functionCalls&&s.functionCalls.length>0)kr(i.functionCalls,s.functionCalls),e.updateResult({name:s.name,content:s.content,functionCalls:i.functionCalls,thoughtBlock:s.thoughtBlock,delta:s.functionCalls?.[0]?.function?.params,index:s.index},t);else if(s.content&&s.content.length>0){s.thought&&s.thought.length>0&&(yield{index:s.index,delta:{[c]:s.thought}}),i.content+=s.content,e.updateResult({name:s.name,content:i.content,thoughtBlock:s.thoughtBlock,delta:s.content,index:s.index},t);let p=a.getOutputFields();if(p.some(A=>A.type?.name==="object"||A.type?.isArray&&A.type.fields)){let A=Cl(i.content);if(A&&typeof A=="object"){let g={};for(let f of Object.keys(A))p.some(x=>x.name===f)&&(g[f]=A[f]);vo(a,g),Object.assign(i.values,g),yield{index:s.index,delta:g};return}}if(ci(a,i.values,i.xstate,i.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await qs(u,i.xstate,i.content),l.length!==0&&await mi(l,i.content,i.xstate,e,i.values,t),yield*pi(a,i.content,i.values,i.xstate,s.index),await uo(d,i.values)}else s.thought&&s.thought.length>0?(i.values[c]=(i.values[c]??"")+s.thought,yield{index:s.index,delta:{[c]:s.thought}},e.updateResult({name:s.name,content:i.content,delta:"",index:s.index,thought:s.thought,thoughtBlock:s.thoughtBlock},t)):s.thoughtBlock&&e.updateResult({name:s.name,content:i.content,delta:"",index:s.index,thoughtBlock:s.thoughtBlock},t);if(s.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
198
198
|
Content: ${i.content}`)}async function*_u({state:s,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:i,traceId:a,span:l,strictMode:c,excludeContentFromTrace:u,streamingAsserts:d,asserts:p,fieldProcessors:m,streamingFieldProcessors:h,functionResultFormatter:A,signatureToolCallingManager:g,logger:f,debug:x,stopFunctionNames:b}){let T=g?void 0:Qs(t,s.functionCalls,s.values,n);if(T){if(!r)throw new Error("Functions are not defined");let E=await Io({ai:t,functionList:r,functionCalls:T,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:u,functionResultFormatter:A,logger:f,debug:x,stopFunctionNames:b});s.functionsExecuted=new Set([...s.functionsExecuted,...E]),s.functionCalls=[]}else{let E=e.getOutputFields(),R=E.some(y=>y.type?.name==="object"||y.type?.isArray&&y.type.fields),k=!1;if(R)try{let y=JSON.parse(s.content),O={};for(let F of Object.keys(y))E.some(P=>P.name===F)&&(O[F]=y[F]);vo(e,O),Object.assign(s.values,O),yield{index:s.index,delta:O},k=!0}catch(y){let O=(y.message||"").toLowerCase();if(O.includes("at least")||O.includes("at most")||O.includes("must match pattern")||O.includes("invalid url")||O.includes("required")||O.includes("missing")||O.includes("valid email")||O.includes("number must be"))throw y}if(!k){let y=g!==void 0;ui(e,s.values,s.xstate,s.content,{strictMode:c,treatAllFieldsOptional:y,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(g){let y=await g.processResults(s.values);if(y&&y.length>0){if(!r)throw new Error("Functions are not defined");let O=await Io({ai:t,functionList:r,functionCalls:y,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:u,functionResultFormatter:A,logger:f,debug:x,stopFunctionNames:b});s.functionsExecuted=new Set([...s.functionsExecuted,...O]),o.updateResult({name:void 0,content:s.content,functionCalls:y.map(F=>({id:F.id,type:"function",function:{name:F.name,params:F.args}})),index:s.index},i);return}}await qs(d,s.xstate,s.content,!0),await uo(p,s.values),m.length&&await di(m,s.values,o,i),h.length!==0&&await mi(h,s.content,s.xstate,o,s.values,i,!0),yield*pi(e,s.content,s.values,s.xstate,s.index)}}async function*Bl({ai:s,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:i,strictMode:a,states:l,usage:c,excludeContentFromTrace:u,asserts:d,fieldProcessors:p,thoughtFieldName:m,signature:h,functionResultFormatter:A,logger:g,debug:f,signatureToolCallingManager:x,stopFunctionNames:b,disableMemoryCleanup:T}){let E=e.results??[],R=x!==void 0;t.addResponse(E,n);let k=[];for(let P of E)if(Array.isArray(P?.citations))for(let w of P.citations)w?.url&&k.push({url:w.url,title:w.title,description:w.description,license:w.license,publicationDate:w.publicationDate,snippet:w.snippet});for(let P of E){let w=l[P.index];if(!w)throw new Error(`No state found for result (index: ${P.index})`);if(e.modelUsage){let v=Array.from(new Map(k.filter(S=>S.url).map(S=>[S.url,S])).values()),I={...e.modelUsage,...v.length?{citations:v}:{}};if(c.push(I),f&&g){let S=structuredClone(I);delete S.citations,g({name:"ChatResponseUsage",value:S}),I.citations&&I.citations.length>0&&g({name:"ChatResponseCitations",value:I.citations})}}if(x&&P.content){P.thought&&P.thought.length>0&&(w.values[m]=P.thought),wo(h,w.values,P.content,{strictMode:a,treatAllFieldsOptional:R});let I=(await x.processResults(w.values))?.map(S=>({id:S.id,type:"function",function:{name:S.name,params:S.args}}));I&&I.length>0&&t.updateResult({name:P.name,content:P.content,functionCalls:I,index:P.index},n)}if(P.functionCalls?.length){let v=Qs(s,P.functionCalls,w.values);if(v&&v.length>0){if(!o)throw new Error("Functions are not defined");let I;try{I=await Io({ai:s,functionList:o,functionCalls:v,mem:t,sessionId:n,traceId:r,span:i,excludeContentFromTrace:u,index:P.index,functionResultFormatter:A,logger:g,debug:f,stopFunctionNames:b})}catch(S){throw t.addRequest([{role:"user",content:"The previous tool call failed. Fix arguments and try again, ensuring required fields match schema."}],n),t.addTag("correction",n),S}w.functionsExecuted=new Set([...w.functionsExecuted,...I])}}else if(P.content){P.thought&&P.thought.length>0&&(w.values[m]=P.thought);let v=h.getOutputFields();if(v.some(S=>S.type?.name==="object"||S.type?.isArray&&S.type.fields))try{let S=JSON.parse(P.content),C={};for(let M of Object.keys(S))v.some(_=>_.name===M)&&(C[M]=S[M]);vo(h,C),Object.assign(w.values,C)}catch(S){if(S.name?.includes("ValidationError")||S.name?.includes("Error")){let C=(S.message||"").toLowerCase();if(C.includes("at least")||C.includes("at most")||C.includes("must match pattern")||C.includes("invalid url")||C.includes("required")||C.includes("missing")||C.includes("valid email")||C.includes("number must be"))throw S}wo(h,w.values,P.content,{strictMode:a,treatAllFieldsOptional:R})}else wo(h,w.values,P.content,{strictMode:a,treatAllFieldsOptional:R})}if(await uo(d,w.values),T||(t.removeByTag("correction",n),t.removeByTag("error",n)),p.length&&await di(p,w.values,t,n),P.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
199
199
|
Content: ${P.content}`)}let y=l.map(P=>P.values);for(let P of y)for(let w of h.getOutputFields())w.isInternal&&delete P[w.name];let O=h.getOutputFields(),F=y.map((P,w)=>{let v={};for(let I of O)I.isInternal||(v[I.name]=P[I.name]);return P[m]!==void 0&&(v[m]=P[m]),{index:w,delta:v}});for(let P of F)yield P}function jl(s,e,t,n){let r=s.getLast(n);if(!r)return!0;for(let[o,i]of t.entries()){let a=e?Array.from(e).some(d=>i.functionsExecuted.has(d)):!1;if(!r.chat[o])throw new Error(`No chat message found for result (index: ${o})`);let c=r.role==="function",u=r.tags?r.tags.some(d=>d==="processor"):!1;if(c&&e&&a||!(c||u))return!1}return!0}var yn=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 K=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},gi=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new K("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 K("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 K('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 K(`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 K)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new K(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new K(`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 K(`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 K(`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 K("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new K("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(`
|
|
200
|
-
`)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new K(`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 K?r:new K(`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 K(`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 K?r:new K(`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 K(`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 K(`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("[]");n={name:o,isArray:i}}catch(o){throw o instanceof K?o:new K(`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 K(`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 K(`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 K(`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 K(`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 K(`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 K(`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 K?i:new K(`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(ee.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 K(`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 K(`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 K(`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 K(`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","object"],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 K(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 K("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 K(`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 K(`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 K(`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 K(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function zl(s){return new gi(s).parse()}var sr=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,i])=>[o,hi(i)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};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||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,i])=>[o,hi(i)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};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 ge(e)}},be=class s{type;isArray;options;description;isOptional;isInternal;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;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,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new s({...this,isOptional:!0})}array(e){return new s({...this,isArray:!0,description:e||this.description})}internal(){return new s({...this,isInternal:!0})}min(e){return this.type==="string"?new s({...this,minLength:e}):this.type==="number"?new s({...this,minimum:e}):this}max(e){return this.type==="string"?new s({...this,maxLength:e}):this.type==="number"?new s({...this,maximum:e}):this}email(){return this.type==="string"?new s({...this,format:"email"}):this}url(){return this.type==="string"?new s({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new s({...this,pattern:e,patternDescription:t}):this}},ie=Object.assign(()=>new sr,{string:s=>new be({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1}),number:s=>new be({type:"number",isArray:!1,description:s,isOptional:!1,isInternal:!1}),boolean:s=>new be({type:"boolean",isArray:!1,description:s,isOptional:!1,isInternal:!1}),json:s=>new be({type:"json",isArray:!1,description:s,isOptional:!1,isInternal:!1}),datetime:s=>new be({type:"datetime",isArray:!1,description:s,isOptional:!1,isInternal:!1}),date:s=>new be({type:"date",isArray:!1,description:s,isOptional:!1,isInternal:!1}),class:(s,e)=>new be({type:"class",isArray:!1,options:s,description:e,isOptional:!1,isInternal:!1}),image:s=>new be({type:"image",isArray:!1,description:s,isOptional:!1,isInternal:!1}),audio:s=>new be({type:"audio",isArray:!1,description:s,isOptional:!1,isInternal:!1}),file:s=>new be({type:"file",isArray:!1,description:s,isOptional:!1,isInternal:!1}),url:s=>new be({type:"url",isArray:!1,description:s,isOptional:!1,isInternal:!1}),code:(s,e)=>new be({type:"code",isArray:!1,description:e||s,isOptional:!1,isInternal:!1}),object:(s,e)=>new be({type:"object",isArray:!1,fields:s,description:e,isOptional:!1,isInternal:!1})});function hi(s){return{type:s.type,isArray:s.isArray,options:s.options,description:s.description,isOptional:s.isOptional,isInternal:s.isInternal,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format,fields:s.fields?Object.fromEntries(Object.entries(s.fields).map(([e,t])=>[e,hi(t)])):void 0}}function So(s){return{type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields},description:s.description,isOptional:s.isOptional,isInternal:s.isInternal}}var B=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},ge=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=zl(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 B(`Invalid Signature: ${n.message}`,void 0,r)}throw new B(`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 B("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 B("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 B?t:new B(`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 B("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 B("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 B("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 B("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);st(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new B(`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 B(`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 B?t:new B(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);st(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new B(`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 B(`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 B?t:new B(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new B("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 st(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof B?t:new B(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new B("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 st(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof B?t:new B(`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,...So(t)}),n};prependInputField=(e,t)=>{let n=new s(this),r={name:e,...So(t)},o=n.parseField(r);st(o,"input");for(let i of n.inputFields)if(i.name===o.name)throw new B(`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 B(`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,...So(t)}),n};prependOutputField=(e,t)=>{let n=new s(this),r={name:e,...So(t)},o=n.parseField(r);st(o,"output");for(let i of n.outputFields)if(i.name===o.name)throw new B(`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 B(`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)};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{st(e,"input")}),this.getOutputFields().forEach(e=>{st(e,"output")}),this.sigHash=Be("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Hl(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof B?e:new B(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{st(e,"input")}),this.getOutputFields().forEach(e=>{st(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Be("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Hl(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof B?e:new B(`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 B(`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 B(`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 B(`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 B("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new B("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});toJSONSchema=()=>{let e=[...this.inputFields,...this.outputFields];return yo(e,this.description??"Schema")}};function ql(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 Hl(s,e,t){let n=s?`"${s}" `:"",r=e.map(ql).join(", "),o=t.map(ql).join(", ");return`${n}${r} -> ${o}`}function Du(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function st(s,e){if(!s.name||s.name.length===0)throw new B("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!Du(s.name))throw new B(`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(ee.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 B(`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 B(`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 B(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&Nu(s,e)}function Nu(s,e){if(!s.type)return;let{type:t}=s;if((t.name==="image"||t.name==="audio"||t.name==="file"||t.name==="url")&&e==="output")throw new B(`${t.name} type is not supported in output fields`,s.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new B("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 B("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 B("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 B(`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 B("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new B("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 B("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&fi(t.fields,s.name,e)}function fi(s,e,t,n=1){for(let[r,o]of Object.entries(s)){let i=`${e}.${r}`;if(o.type==="image"||o.type==="audio"||o.type==="file")throw new B(`${o.type} type is not allowed in nested object fields`,i,`Media types (image, audio, file) can only be used as top-level input fields, not within objects. Found at depth ${n}.`);o.type==="object"&&o.fields&&fi(o.fields,i,t,n+1),o.isArray&&o.fields&&fi(o.fields,`${i}[]`,t,n+1)}}var wt=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new ge(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 yn,this.key={id:this.signature.hash()}}getSignature(){return new ge(this.signature)}setSignature(e){this.signature=new ge(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 c=i[l.name];c!==void 0&&(To(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 or(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)}applyOptimization(e){e.applyTo(this);for(let t of Array.from(this.children))t&&"applyOptimization"in t&&typeof t.applyOptimization=="function"&&t.applyOptimization(e)}};var $u=`
|
|
200
|
+
`)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new K(`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 K?r:new K(`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 K(`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 K?r:new K(`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 K(`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 K(`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("[]");n={name:o,isArray:i}}catch(o){throw o instanceof K?o:new K(`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 K(`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 K(`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 K(`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 K(`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 K(`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 K(`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 K?i:new K(`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(ee.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 K(`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 K(`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 K(`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 K(`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","object"],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 K(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 K("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 K(`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 K(`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 K(`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 K(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function zl(s){return new gi(s).parse()}var sr=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,i])=>[o,hi(i)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};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||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,i])=>[o,hi(i)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};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 ge(e)}},xe=class s{type;isArray;options;description;isOptional;isInternal;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;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,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new s({...this,isOptional:!0})}array(e){return new s({...this,isArray:!0,description:e||this.description})}internal(){return new s({...this,isInternal:!0})}min(e){return this.type==="string"?new s({...this,minLength:e}):this.type==="number"?new s({...this,minimum:e}):this}max(e){return this.type==="string"?new s({...this,maxLength:e}):this.type==="number"?new s({...this,maximum:e}):this}email(){return this.type==="string"?new s({...this,format:"email"}):this}url(){return this.type==="string"?new s({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new s({...this,pattern:e,patternDescription:t}):this}date(){return this.type==="string"?new s({...this,format:"date"}):this}datetime(){return this.type==="string"?new s({...this,format:"date-time"}):this}},ie=Object.assign(()=>new sr,{string:s=>new xe({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1}),number:s=>new xe({type:"number",isArray:!1,description:s,isOptional:!1,isInternal:!1}),boolean:s=>new xe({type:"boolean",isArray:!1,description:s,isOptional:!1,isInternal:!1}),json:s=>new xe({type:"json",isArray:!1,description:s,isOptional:!1,isInternal:!1}),datetime:s=>new xe({type:"datetime",isArray:!1,description:s,isOptional:!1,isInternal:!1}),date:s=>new xe({type:"date",isArray:!1,description:s,isOptional:!1,isInternal:!1}),class:(s,e)=>new xe({type:"class",isArray:!1,options:s,description:e,isOptional:!1,isInternal:!1}),image:s=>new xe({type:"image",isArray:!1,description:s,isOptional:!1,isInternal:!1}),audio:s=>new xe({type:"audio",isArray:!1,description:s,isOptional:!1,isInternal:!1}),file:s=>new xe({type:"file",isArray:!1,description:s,isOptional:!1,isInternal:!1}),url:s=>new xe({type:"url",isArray:!1,description:s,isOptional:!1,isInternal:!1}),email:s=>new xe({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1,format:"email"}),code:(s,e)=>new xe({type:"code",isArray:!1,description:e||s,isOptional:!1,isInternal:!1}),object:(s,e)=>new xe({type:"object",isArray:!1,fields:s,description:e,isOptional:!1,isInternal:!1})});function hi(s){return{type:s.type,isArray:s.isArray,options:s.options,description:s.description,isOptional:s.isOptional,isInternal:s.isInternal,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format,fields:s.fields?Object.fromEntries(Object.entries(s.fields).map(([e,t])=>[e,hi(t)])):void 0}}function So(s){return{type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields},description:s.description,isOptional:s.isOptional,isInternal:s.isInternal}}var B=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},ge=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=zl(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 B(`Invalid Signature: ${n.message}`,void 0,r)}throw new B(`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 B("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 B("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 B?t:new B(`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 B("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 B("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 B("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 B("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);st(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new B(`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 B(`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 B?t:new B(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);st(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new B(`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 B(`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 B?t:new B(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new B("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 st(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof B?t:new B(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new B("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 st(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof B?t:new B(`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,...So(t)}),n};prependInputField=(e,t)=>{let n=new s(this),r={name:e,...So(t)},o=n.parseField(r);st(o,"input");for(let i of n.inputFields)if(i.name===o.name)throw new B(`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 B(`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,...So(t)}),n};prependOutputField=(e,t)=>{let n=new s(this),r={name:e,...So(t)},o=n.parseField(r);st(o,"output");for(let i of n.outputFields)if(i.name===o.name)throw new B(`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 B(`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)};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{st(e,"input")}),this.getOutputFields().forEach(e=>{st(e,"output")}),this.sigHash=Be("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Hl(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof B?e:new B(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{st(e,"input")}),this.getOutputFields().forEach(e=>{st(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Be("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Hl(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof B?e:new B(`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 B(`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 B(`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 B(`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 B("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new B("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});toJSONSchema=()=>{let e=[...this.inputFields,...this.outputFields];return yo(e,this.description??"Schema")}};function ql(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 Hl(s,e,t){let n=s?`"${s}" `:"",r=e.map(ql).join(", "),o=t.map(ql).join(", ");return`${n}${r} -> ${o}`}function Du(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function st(s,e){if(!s.name||s.name.length===0)throw new B("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!Du(s.name))throw new B(`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(ee.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 B(`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 B(`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 B(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&Nu(s,e)}function Nu(s,e){if(!s.type)return;let{type:t}=s;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new B(`${t.name} type is not supported in output fields`,s.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new B("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 B("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 B("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 B(`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 B("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new B("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 B("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&fi(t.fields,s.name,e)}function fi(s,e,t,n=1){for(let[r,o]of Object.entries(s)){let i=`${e}.${r}`;if(o.type==="image"||o.type==="audio"||o.type==="file")throw new B(`${o.type} type is not allowed in nested object fields`,i,`Media types (image, audio, file) can only be used as top-level input fields, not within objects. Found at depth ${n}.`);o.type==="object"&&o.fields&&fi(o.fields,i,t,n+1),o.isArray&&o.fields&&fi(o.fields,`${i}[]`,t,n+1)}}var wt=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new ge(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 yn,this.key={id:this.signature.hash()}}getSignature(){return new ge(this.signature)}setSignature(e){this.signature=new ge(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 c=i[l.name];c!==void 0&&(To(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 or(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)}applyOptimization(e){e.applyTo(this);for(let t of Array.from(this.children))t&&"applyOptimization"in t&&typeof t.applyOptimization=="function"&&t.applyOptimization(e)}};var $u=`
|
|
201
201
|
## Function Call Instructions
|
|
202
202
|
- Complete the task, using the functions defined earlier in this prompt.
|
|
203
203
|
- Output fields should only be generated after all functions have been called.
|
|
@@ -229,7 +229,7 @@ ${u}`),l&&l.length>0&&r.push($u.trim()),this.sig.getOutputFields().some(m=>m.typ
|
|
|
229
229
|
`),n.push(t.map(r=>`- ${r}`).join(`
|
|
230
230
|
`))):n.push(t),[{type:"text",text:n.join("")}]}},Kl=s=>s.map(e=>`\`${e.title}\``).join(", "),Gu=s=>s.map(t=>{let n=t.title,r=t.type?.name?Vl(t.type):"string",o=t.isOptional?`This optional ${r} field may be omitted`:`A ${r} field`,i=t.description?` ${Oo(t.description)}`:"";return`${n}: (${o})${i}`.trim()}).join(`
|
|
231
231
|
`),Uu=s=>s.map(t=>{let n=t.title,r=t.type?.name?Vl(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:Oo(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(`
|
|
232
|
-
`),Bu=(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?Fl(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)},Vl=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)";case"object":return"object";default:return"string"}})();return s?.isArray?`json array of ${e} items`:e};function Wl(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 ju=(s,e,t)=>{if(typeof e=="boolean"||s?.type?.name==="number"&&typeof e=="number")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 Oo(s){let e=s.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function zu(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 qu(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(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 ko(s,e,t,n){if(!e?.resultPicker||s.length<=1)return 0;let r=e.resultPicker;if((t?zu(t,n):!1)&&t){let l=qu(t,n),c=await r({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 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 Jl(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 ko(r,t,s,e)}var Mo=class{tools;logger;constructor(e,t){this.tools=new Map(e.map(n=>[n.name,n])),this.logger=t}getToolParamFieldMap(){let e=new Map;for(let[,t]of this.tools.entries())if(t.parameters?.properties&&Object.keys(t.parameters.properties).length>0){let{paramFieldMap:n}=Hu(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},o=new Map,i=new Map;for(let[a,l]of this.tools.entries())i.set(a,this.buildSanitizedFieldMap(l));for(let[a,l]of Object.entries(e)){let c=this.tools.get(this.normalizeToolName(a));if(c){l!=null&&typeof l=="object"&&o.set(c.name,l);continue}r[a]=l}for(let[a,l]of Object.entries(e))for(let[c,u]of this.tools.entries()){let d=i.get(c);if(!d)continue;let p=d.get(a);if(!p)continue;let m=o.get(u.name)??{};this.setNested(m,p,l),o.set(u.name,m)}for(let[a,l]of this.tools.entries()){let c=o.get(l.name);if(!(!c||Object.keys(c).length===0)){if(l.parameters&&l.parameters.type==="object"){let d=(l.parameters.required||[]).filter(p=>c[p]===void 0);if(d.length>0)throw new ye(`Missing required arguments for tool '${l.name}': ${d.join(", ")}`)}n.push({id:l.name,name:l.name,args:JSON.stringify(c)})}}return{functionCalls:n,remainingFields:r}}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}buildSanitizedFieldMap(e){let t=new Map;if(!e.parameters||!("properties"in e.parameters))return t;let n=(r,o)=>{for(let[i,a]of Object.entries(r)){let l=[...o,i];if(a&&a.type==="object"&&a.properties)n(a.properties,l);else{let c=`${e.name}.${l.join(".")}`,u=this.sanitizeFieldName(c);t.set(u,l)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let o=0;o<t.length-1;o++){let i=t[o],a=r[i];(typeof a!="object"||a===null)&&(r[i]={}),r=r[i]}r[t[t.length-1]]=n}isToolField(e){return this.tools.has(this.normalizeToolName(e))}getToolFieldNames(){return Array.from(this.tools.keys()).map(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""))}};function Hu(s){let e=[],t=new Map;if(!s.parameters||!s.parameters.properties)return{fields:e,paramFieldMap:t};let n=s.parameters.properties,r=s.parameters.required||[],o=(i,a,l)=>{for(let[c,u]of Object.entries(i)){let d=a?`${a}.${c}`:c,p=`${s.name}.${d}`;if(u.type==="object"&&u.properties)o(u.properties,d,u.required||[]);else{let m=Ku(u);e.push({name:Vu(p),title:Wu(s.name,d),type:m,description:u.description||`${c} parameter for ${s.name}`,isOptional:!0}),t.set(p,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Ku(s){switch(s.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=s.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function Wu(s,e){return`${s} ${e.replace(/\./g," ")}`}function Vu(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Zl(s,e,t){let n=new ge(e);if(t){let r=t.getToolParamFieldMap();for(let o of s){let i=r.get(o.name);if(i&&i.size>0)for(let a of i.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=Ai(o.name),l=Ql(o.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:Yl(o.name),type:l,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let o of s)if(o.parameters?.properties&&Object.keys(o.parameters.properties).length>0){let{fields:i,paramFieldMap:a}=Ju(o);r.set(o.name,a);for(let l of i)n.getOutputFields().some(u=>u.name===l.name)||n.addOutputField(l)}else{let i=Ai(o.name),a=Ql(o.parameters);n.getOutputFields().some(c=>c.name===i)||n.addOutputField({name:i,title:Yl(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function Ju(s){let e=[],t=new Map;if(!s.parameters||!s.parameters.properties)return{fields:e,paramFieldMap:t};let n=s.parameters.properties,r=s.parameters.required||[],o=(i,a,l)=>{for(let[c,u]of Object.entries(i)){let d=a?`${a}.${c}`:c,p=`${s.name}.${d}`;if(u.type==="object"&&u.properties)o(u.properties,d,u.required||[]);else{let m=Yu(u),h={name:Ai(p),title:Qu(s.name,d),type:m,description:u.description||`${c} parameter for ${s.name}`,isOptional:!0};e.push(h),t.set(p,h)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Yu(s){switch(s.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=s.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function Qu(s,e){return`${s} ${e.replace(/\./g," ")}`}function Ai(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Yl(s){return s.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function Ql(s){return!s||!s.properties||Object.keys(s.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var ir=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new Mo(e)}processSignature(e){let{signature:t}=Zl(this.tools,e),n=new Set(t.getOutputFields().map(o=>o.name)),r=new Set(e.getOutputFields().map(o=>o.name));return this.injectedToolFieldNames=new Set([...n].filter(o=>!r.has(o))),t}async processResults(e,t){let{functionCalls:n}=await this.router.route(e,t);return n.length>0?n:void 0}getInjectedToolFieldNames(){return Array.from(this.injectedToolFieldNames)}getRouter(){return this.router}};var Pe=class extends wt{promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;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,cacheSystemPrompt:t?.cacheSystemPrompt};this.promptTemplate=new(t?.promptTemplate??_t)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?bo(t.functions):[],this.usage=[]}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Ks()}updateMeter(e){Ks(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)=>{let r=this.signature.getOutputFields().find(a=>a.name===e);if(!r)throw new Error(`addStreamingAssert: field ${String(e)} not found in output signature`);let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addStreamingAssert: field ${String(e)} must be a string field for streaming assertions`);this.streamingAsserts.push({fieldName:String(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(String(e),t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:r,functions:o,functionCall:i,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:u,stream:d,thinkingTokenBudget:p,showThoughts:m}=n??{},h=await Jl(t,l,{resultPicker:n?.resultPicker}),A=t?.history(h,l)??[];if(A.length===0)throw new Error("No chat prompt found");let g={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},f=this.isDebug(e,n),x=a===0,b=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let T,E=this.signature.getOutputFields();return E.some(y=>y.type?.name==="object"||y.type?.isArray&&y.type.fields)&&(T={type:"json_schema",schema:{name:"output",strict:!0,schema:yo(E)}}),await e.chat({chatPrompt:A,functions:o,functionCall:i,modelConfig:g,model:c,responseFormat:T},{sessionId:l,rateLimiter:u,stream:d,debug:f,debugHideSystemPrompt:!x,thinkingTokenBudget:p,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??ee.abortSignal,stepIndex:a,logger:b,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto"})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:i,states:a,stopFunctionNames:l}){let{sessionId:c,functions:u}=n??{},d=n?.functionResultFormatter??this.options?.functionResultFormatter,p=n?.functionCall??this.options?.functionCall,m=this.signatureToolCallingManager,h=n?.strictMode??!1,A=n.model,g=this.usage,f=r===0,x=this.isDebug(e,n),b=this.getLogger(e,n),{functions:T,functionCall:E}=Tl(u,p,f,n),R=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:T,functionCall:E,stepIndex:r});R instanceof ReadableStream?yield*Ul({ai:e,model:A,res:R,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:T,strictMode:h,span:o,states:a,usage:g,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:b,debug:x,functionResultFormatter:d,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*Bl({ai:e,model:A,res:R,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:T,span:o,strictMode:h,states:a,usage:g,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:b,debug:x,functionResultFormatter:d,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,i){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(F=>F.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??10,u=r.maxSteps??this.options?.maxSteps??10,d=r.mem??this.options?.mem??new fn,p=[...this.functions,...r.functions?bo(r.functions):[]],m=p&&p.length>0,h=r.functionCallMode??this.options?.functionCallMode??"auto",A=r.cacheSystemPrompt??this.options?.cacheSystemPrompt;m&&h==="prompt"&&(this.signatureToolCallingManager=new ir(p)),m&&h==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new ir(p));let g,f,x=this.options?.promptTemplate??_t;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let b={functions:this.signatureToolCallingManager?[]:p,thoughtFieldName:this.thoughtFieldName,cacheSystemPrompt:A};this.promptTemplate=new x(this.signature,b);let T,E=performance.now();Array.isArray(t)?(Sa(t),T=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):T=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let R=performance.now()-E,k=this.getMetricsInstruments();k&&go(k,"prompt_render",R,this.getSignatureName());let y=performance.now();d.addRequest(T,r.sessionId);let O=performance.now()-y;k&&go(k,"memory_update",O,this.getSignatureName());e:for(let F=0;F<u;F++){for(let w=0;w<c;w++)try{let v=this.forwardCore({options:r,ai:e,mem:d,stepIndex:F,span:o,traceContext:i,states:n,stopFunctionNames:l}),I=!1;try{for await(let M of v)M!==void 0&&(yield{version:w,index:M.index,delta:M.delta})}catch(M){if(M instanceof Ft)I=!0;else throw M}if(I?!1:jl(d,l,n,r?.sessionId)){let M=this.getMetricsInstruments();M&&mo(M,F+1,u,this.getSignatureName());continue e}r?.disableMemoryCleanup||(d.removeByTag("invalid-assistant",r.sessionId),d.removeByTag("correction",r.sessionId),d.removeByTag("error",r.sessionId));let C=this.getMetricsInstruments();if(C){mo(C,F+1,u,this.getSignatureName());let M=new Set;n.forEach(_=>{_.functionsExecuted.forEach(D=>M.add(D))}),M.size>0&&il(C,!0,M.size,!0,!1,this.getSignatureName()),al(C,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(v){f=v;let I,S=this.isDebug(e,r),C=this.getLogger(e,r),M=this.getMetricsInstruments(),_=this.getSignatureName(),D={error:v,errCount:w,logger:C,metricsInstruments:M,signatureName:_,span:o,debug:S};if(o?.recordException(v),v instanceof ye)I=Al(D),g=v;else if(v instanceof ot)I=xl(D),g=v;else if(v instanceof de)yl(D);else if(!(v instanceof Qe))throw xi(v,e,this.signature);I&&(d.addTag("error",r.sessionId),d.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(I)}],r.sessionId),d.addTag("correction",r.sessionId))}let P=this.getMetricsInstruments();throw P&&Vs(P,c,!1,c,this.getSignatureName()),xi(new Error(`Unable to fix validation error: ${(g??f)?.message??(g??f)?.toString()??"unknown error"}`),e,this.signature)}throw k&&mo(k,u,u,this.getSignatureName()),xi(new Error(`Max steps reached: ${u}`),e,this.signature)}validateInputs(e){let t=this.signature.getInputFields();for(let n of t){if(n.isInternal)continue;let r=e[n.name];if(n.isOptional&&r===void 0)continue;let o=n.type;if(o&&(o.name==="url"&&Ct(r,n),o.name,o.name,(o.name==="string"||o.name==="code")&&qe(r,n),o.name==="number"&&He(r,n),o.name==="object"&&o.fields&&typeof r=="object"&&r!==null&&this.validateObjectFields(r,o.fields,n.name),o.isArray&&Array.isArray(r)))for(let i=0;i<r.length;i++){let a=r[i];o.name==="string"||o.name==="code"?qe(a,n):o.name==="number"?He(a,n):o.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,o.fields,`${n.name}[${i}]`)}}}validateObjectFields(e,t,n){for(let[r,o]of Object.entries(t)){let i=e[r];if(o.isOptional&&i===void 0)continue;let a={name:`${n}.${r}`,type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,format:o.format},description:o.description,isOptional:o.isOptional};if(o.type==="string"||o.type==="code"?qe(i,a):o.type==="number"?He(i,a):o.type==="object"&&o.fields&&typeof i=="object"&&i!==null&&this.validateObjectFields(i,o.fields,a.name),o.isArray&&Array.isArray(i))for(let l=0;l<i.length;l++){let c=i[l];o.type==="string"||o.type==="code"?qe(c,a):o.type==="number"?He(c,a):o.fields&&typeof c=="object"&&c!==null&&this.validateObjectFields(c,o.fields,`${a.name}[${l}]`)}}}async*_forward1(e,t,n){(!Array.isArray(t)||!t.every(f=>"role"in f))&&this.validateInputs(t);let r=performance.now(),o=this.createStates(n.sampleCount??1),i=performance.now()-r,a=this.getMetricsInstruments();a&&go(a,"state_creation",i,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,c=this.functions;if(n?.functions&&(c=bo(n.functions,this.functions)),!l){yield*this._forward2(e,t,o,{...n,functions:c});return}let u=c?.map(f=>f.name).join(","),d={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...u?{provided_functions:u}:{},...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}:{}},p=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=p?`AxGen > ${p}`:"AxGen",h=l.startSpan(m,{kind:Ee.SERVER,attributes:d}),A=It.active(),g=_n.setSpan(A,h);try{if(this.excludeContentFromTrace||h.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:c},h,g),!this.excludeContentFromTrace){let f=o.map(b=>b.values),x=f.length===1?f[0]:f;h.addEvent("output",{content:JSON.stringify(x,null,2)})}}finally{h.end()}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??ee.cachingFunction,o=(()=>{if(!r)return;let p=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,p)})();if(r&&o){let p=await r(o);if(p!==void 0)return p}let i=performance.now(),a=this.getSignatureName(),l=n?.stream??!1,c=!1,u=0,d=!1;try{let p=this.getMetricsInstruments();p&&ul(p,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a);let m=this._forward1(e,t,n??{}),h=[],A=0,g=0;for await(let k of m)k.version!==A&&(h=[]),A=k.version,h=ai(h,k),g++;u=A;let f=performance.now();d=!!n?.resultPicker;let x=await ko(h,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),b=performance.now()-f,E=h[x]?.delta??{},R=Array.isArray(t)?{}:t??{};if(this.trace={...R,...E},d&&this.isDebug(e,n)){let k=this.getLogger(e,n);ca(h.length,x,b,k)}if(c=!0,p&&(cl(p,h.length,d,d?b:void 0,a),ll(p,l,g,void 0,a)),r&&o)try{await r(o,E)}catch{}return E}catch(p){throw c=!1,p}finally{let p=performance.now()-i,m=this.getMetricsInstruments();m&&(ol(m,p,c,a,e.getName(),n?.model?String(n.model):void 0),u>0&&Vs(m,u,c,n?.maxRetries??10,a))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??ee.cachingFunction,o=(()=>{if(!r)return;let d=this.signature.getInputFields().map(p=>p.name);return this.computeCacheKey(t,d)})();if(r&&o){let d;try{d=await r(o)}catch{}if(d!==void 0){yield{version:0,index:0,delta:d};return}}if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let i=this._forward1(e,t,{...n,stream:!0}),a=[],l=0;for await(let d of i)d.version!==l&&(a=[]),l=d.version,a=ai(a,d);let c=await ko(a,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),u=a[c];if(u){if(r&&o)try{await r(o,u.delta)}catch{}yield{version:l,index:c,delta:u.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??ee.logger??e.getLogger()}computeCacheKey(e,t){let n=Be("sha256");n.update(this.signature.hash()??"");let r=o=>{let i=typeof o;if(n.update(`|${i}|`),o==null){n.update("null");return}if(i==="string"||i==="number"||i==="boolean"){n.update(String(o));return}if(Array.isArray(o)){n.update("[");for(let a of o)r(a);n.update("]");return}if(typeof o=="object"&&o!==null&&"mimeType"in o&&"data"in o){let a=o;n.update(a.mimeType??"");let l=Be("sha256").update(a.data??"").digest("hex");n.update(l);return}if(typeof o=="object"){let a=o,l=Object.keys(a).sort();for(let c of l)n.update(`{${c}}`),r(a[c]);return}n.update(String(o))};if(Array.isArray(e))for(let o of e){n.update(`role:${o.role}`);let i=t.map(a=>o.values?.[a]);for(let a of i)r(a)}else{let o=t.map(i=>e?.[i]);for(let i of o)r(i)}return n.digest("hex")}},ar=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function xi(s,e,t){let n=s instanceof Error?s:new Error(String(s)),r=(n.message||"").toLowerCase();if(r.includes("at least")||r.includes("at most")||r.includes("must match pattern")||r.includes("invalid url")||r.includes("required")||r.includes("missing")||r.includes("valid email")||r.includes("number must be")||n.name==="ValidationError"||n.name==="AssertionError"||n.name==="AxAssertionError"||n.stack?.includes("asserts.ts"))return n;let i=e.getLastUsedChatModel(),a=e.getLastUsedModelConfig(),l={model:i,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new ar("Generate failed",l,{cause:n})}var Zu=s=>s.replace(/^\W+|\W+$/g,""),Xu=(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]},ep=s=>{let e=new Set,t=[];for(let n of s)e.has(n)||(e.add(n),t.push(n));return t},tp=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}},np=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():s},rp=(s,e)=>{let t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t},Eo={trimNonAlphaNum:Zu,splitIntoTwo:Xu,dedup:ep,extractIdAndText:tp,extractIndexPrefixedText:np,batchArray:rp};var Po=class extends Pe{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."
|
|
232
|
+
`),Bu=(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?Fl(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)},Vl=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)";case"object":return"object";default:return"string"}})();return s?.isArray?`json array of ${e} items`:e};function Wl(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 ju=(s,e,t)=>{if(typeof e=="boolean"||s?.type?.name==="number"&&typeof e=="number")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 Oo(s){let e=s.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function zu(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 qu(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(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 ko(s,e,t,n){if(!e?.resultPicker||s.length<=1)return 0;let r=e.resultPicker;if((t?zu(t,n):!1)&&t){let l=qu(t,n),c=await r({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 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 Jl(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 ko(r,t,s,e)}var Mo=class{tools;logger;constructor(e,t){this.tools=new Map(e.map(n=>[n.name,n])),this.logger=t}getToolParamFieldMap(){let e=new Map;for(let[,t]of this.tools.entries())if(t.parameters?.properties&&Object.keys(t.parameters.properties).length>0){let{paramFieldMap:n}=Hu(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},o=new Map,i=new Map;for(let[a,l]of this.tools.entries())i.set(a,this.buildSanitizedFieldMap(l));for(let[a,l]of Object.entries(e)){let c=this.tools.get(this.normalizeToolName(a));if(c){l!=null&&typeof l=="object"&&o.set(c.name,l);continue}r[a]=l}for(let[a,l]of Object.entries(e))for(let[c,u]of this.tools.entries()){let d=i.get(c);if(!d)continue;let p=d.get(a);if(!p)continue;let m=o.get(u.name)??{};this.setNested(m,p,l),o.set(u.name,m)}for(let[a,l]of this.tools.entries()){let c=o.get(l.name);if(!(!c||Object.keys(c).length===0)){if(l.parameters&&l.parameters.type==="object"){let d=(l.parameters.required||[]).filter(p=>c[p]===void 0);if(d.length>0)throw new be(`Missing required arguments for tool '${l.name}': ${d.join(", ")}`)}n.push({id:l.name,name:l.name,args:JSON.stringify(c)})}}return{functionCalls:n,remainingFields:r}}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}buildSanitizedFieldMap(e){let t=new Map;if(!e.parameters||!("properties"in e.parameters))return t;let n=(r,o)=>{for(let[i,a]of Object.entries(r)){let l=[...o,i];if(a&&a.type==="object"&&a.properties)n(a.properties,l);else{let c=`${e.name}.${l.join(".")}`,u=this.sanitizeFieldName(c);t.set(u,l)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let o=0;o<t.length-1;o++){let i=t[o],a=r[i];(typeof a!="object"||a===null)&&(r[i]={}),r=r[i]}r[t[t.length-1]]=n}isToolField(e){return this.tools.has(this.normalizeToolName(e))}getToolFieldNames(){return Array.from(this.tools.keys()).map(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""))}};function Hu(s){let e=[],t=new Map;if(!s.parameters||!s.parameters.properties)return{fields:e,paramFieldMap:t};let n=s.parameters.properties,r=s.parameters.required||[],o=(i,a,l)=>{for(let[c,u]of Object.entries(i)){let d=a?`${a}.${c}`:c,p=`${s.name}.${d}`;if(u.type==="object"&&u.properties)o(u.properties,d,u.required||[]);else{let m=Ku(u);e.push({name:Vu(p),title:Wu(s.name,d),type:m,description:u.description||`${c} parameter for ${s.name}`,isOptional:!0}),t.set(p,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Ku(s){switch(s.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=s.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function Wu(s,e){return`${s} ${e.replace(/\./g," ")}`}function Vu(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Zl(s,e,t){let n=new ge(e);if(t){let r=t.getToolParamFieldMap();for(let o of s){let i=r.get(o.name);if(i&&i.size>0)for(let a of i.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=Ai(o.name),l=Ql(o.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:Yl(o.name),type:l,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let o of s)if(o.parameters?.properties&&Object.keys(o.parameters.properties).length>0){let{fields:i,paramFieldMap:a}=Ju(o);r.set(o.name,a);for(let l of i)n.getOutputFields().some(u=>u.name===l.name)||n.addOutputField(l)}else{let i=Ai(o.name),a=Ql(o.parameters);n.getOutputFields().some(c=>c.name===i)||n.addOutputField({name:i,title:Yl(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function Ju(s){let e=[],t=new Map;if(!s.parameters||!s.parameters.properties)return{fields:e,paramFieldMap:t};let n=s.parameters.properties,r=s.parameters.required||[],o=(i,a,l)=>{for(let[c,u]of Object.entries(i)){let d=a?`${a}.${c}`:c,p=`${s.name}.${d}`;if(u.type==="object"&&u.properties)o(u.properties,d,u.required||[]);else{let m=Yu(u),h={name:Ai(p),title:Qu(s.name,d),type:m,description:u.description||`${c} parameter for ${s.name}`,isOptional:!0};e.push(h),t.set(p,h)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Yu(s){switch(s.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=s.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function Qu(s,e){return`${s} ${e.replace(/\./g," ")}`}function Ai(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Yl(s){return s.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function Ql(s){return!s||!s.properties||Object.keys(s.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var ir=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new Mo(e)}processSignature(e){let{signature:t}=Zl(this.tools,e),n=new Set(t.getOutputFields().map(o=>o.name)),r=new Set(e.getOutputFields().map(o=>o.name));return this.injectedToolFieldNames=new Set([...n].filter(o=>!r.has(o))),t}async processResults(e,t){let{functionCalls:n}=await this.router.route(e,t);return n.length>0?n:void 0}getInjectedToolFieldNames(){return Array.from(this.injectedToolFieldNames)}getRouter(){return this.router}};var Pe=class extends wt{promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;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,cacheSystemPrompt:t?.cacheSystemPrompt};this.promptTemplate=new(t?.promptTemplate??_t)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?bo(t.functions):[],this.usage=[]}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Ks()}updateMeter(e){Ks(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)=>{let r=this.signature.getOutputFields().find(a=>a.name===e);if(!r)throw new Error(`addStreamingAssert: field ${String(e)} not found in output signature`);let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addStreamingAssert: field ${String(e)} must be a string field for streaming assertions`);this.streamingAsserts.push({fieldName:String(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(String(e),t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:r,functions:o,functionCall:i,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:u,stream:d,thinkingTokenBudget:p,showThoughts:m}=n??{},h=await Jl(t,l,{resultPicker:n?.resultPicker}),A=t?.history(h,l)??[];if(A.length===0)throw new Error("No chat prompt found");let g={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},f=this.isDebug(e,n),x=a===0,b=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let T,E=this.signature.getOutputFields();return E.some(y=>y.type?.name==="object"||y.type?.isArray&&y.type.fields)&&(T={type:"json_schema",schema:{name:"output",strict:!0,schema:yo(E)}}),await e.chat({chatPrompt:A,functions:o,functionCall:i,modelConfig:g,model:c,responseFormat:T},{sessionId:l,rateLimiter:u,stream:d,debug:f,debugHideSystemPrompt:!x,thinkingTokenBudget:p,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??ee.abortSignal,stepIndex:a,logger:b,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto"})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:i,states:a,stopFunctionNames:l}){let{sessionId:c,functions:u}=n??{},d=n?.functionResultFormatter??this.options?.functionResultFormatter,p=n?.functionCall??this.options?.functionCall,m=this.signatureToolCallingManager,h=n?.strictMode??!1,A=n.model,g=this.usage,f=r===0,x=this.isDebug(e,n),b=this.getLogger(e,n),{functions:T,functionCall:E}=Tl(u,p,f,n),R=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:T,functionCall:E,stepIndex:r});R instanceof ReadableStream?yield*Ul({ai:e,model:A,res:R,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:T,strictMode:h,span:o,states:a,usage:g,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:b,debug:x,functionResultFormatter:d,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*Bl({ai:e,model:A,res:R,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:T,span:o,strictMode:h,states:a,usage:g,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:b,debug:x,functionResultFormatter:d,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,i){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(F=>F.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??10,u=r.maxSteps??this.options?.maxSteps??10,d=r.mem??this.options?.mem??new fn,p=[...this.functions,...r.functions?bo(r.functions):[]],m=p&&p.length>0,h=r.functionCallMode??this.options?.functionCallMode??"auto",A=r.cacheSystemPrompt??this.options?.cacheSystemPrompt;m&&h==="prompt"&&(this.signatureToolCallingManager=new ir(p)),m&&h==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new ir(p));let g,f,x=this.options?.promptTemplate??_t;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let b={functions:this.signatureToolCallingManager?[]:p,thoughtFieldName:this.thoughtFieldName,cacheSystemPrompt:A};this.promptTemplate=new x(this.signature,b);let T,E=performance.now();Array.isArray(t)?(Sa(t),T=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):T=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let R=performance.now()-E,k=this.getMetricsInstruments();k&&go(k,"prompt_render",R,this.getSignatureName());let y=performance.now();d.addRequest(T,r.sessionId);let O=performance.now()-y;k&&go(k,"memory_update",O,this.getSignatureName());e:for(let F=0;F<u;F++){for(let w=0;w<c;w++)try{let v=this.forwardCore({options:r,ai:e,mem:d,stepIndex:F,span:o,traceContext:i,states:n,stopFunctionNames:l}),I=!1;try{for await(let M of v)M!==void 0&&(yield{version:w,index:M.index,delta:M.delta})}catch(M){if(M instanceof Ft)I=!0;else throw M}if(I?!1:jl(d,l,n,r?.sessionId)){let M=this.getMetricsInstruments();M&&mo(M,F+1,u,this.getSignatureName());continue e}r?.disableMemoryCleanup||(d.removeByTag("invalid-assistant",r.sessionId),d.removeByTag("correction",r.sessionId),d.removeByTag("error",r.sessionId));let C=this.getMetricsInstruments();if(C){mo(C,F+1,u,this.getSignatureName());let M=new Set;n.forEach(_=>{_.functionsExecuted.forEach(D=>M.add(D))}),M.size>0&&il(C,!0,M.size,!0,!1,this.getSignatureName()),al(C,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(v){f=v;let I,S=this.isDebug(e,r),C=this.getLogger(e,r),M=this.getMetricsInstruments(),_=this.getSignatureName(),D={error:v,errCount:w,logger:C,metricsInstruments:M,signatureName:_,span:o,debug:S};if(o?.recordException(v),v instanceof be)I=Al(D),g=v;else if(v instanceof ot)I=xl(D),g=v;else if(v instanceof de)yl(D);else if(!(v instanceof Qe))throw xi(v,e,this.signature);I&&(d.addTag("error",r.sessionId),d.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(I)}],r.sessionId),d.addTag("correction",r.sessionId))}let P=this.getMetricsInstruments();throw P&&Vs(P,c,!1,c,this.getSignatureName()),xi(new Error(`Unable to fix validation error: ${(g??f)?.message??(g??f)?.toString()??"unknown error"}`),e,this.signature)}throw k&&mo(k,u,u,this.getSignatureName()),xi(new Error(`Max steps reached: ${u}`),e,this.signature)}validateInputs(e){let t=this.signature.getInputFields();for(let n of t){if(n.isInternal)continue;let r=e[n.name];if(n.isOptional&&r===void 0)continue;let o=n.type;if(o&&(o.name==="url"&&Ct(r,n),o.name,o.name,(o.name==="string"||o.name==="code")&&qe(r,n),o.name==="number"&&He(r,n),o.name==="object"&&o.fields&&typeof r=="object"&&r!==null&&this.validateObjectFields(r,o.fields,n.name),o.isArray&&Array.isArray(r)))for(let i=0;i<r.length;i++){let a=r[i];o.name==="string"||o.name==="code"?qe(a,n):o.name==="number"?He(a,n):o.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,o.fields,`${n.name}[${i}]`)}}}validateObjectFields(e,t,n){for(let[r,o]of Object.entries(t)){let i=e[r];if(o.isOptional&&i===void 0)continue;let a={name:`${n}.${r}`,type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,format:o.format},description:o.description,isOptional:o.isOptional};if(o.type==="string"||o.type==="code"?qe(i,a):o.type==="number"?He(i,a):o.type==="object"&&o.fields&&typeof i=="object"&&i!==null&&this.validateObjectFields(i,o.fields,a.name),o.isArray&&Array.isArray(i))for(let l=0;l<i.length;l++){let c=i[l];o.type==="string"||o.type==="code"?qe(c,a):o.type==="number"?He(c,a):o.fields&&typeof c=="object"&&c!==null&&this.validateObjectFields(c,o.fields,`${a.name}[${l}]`)}}}async*_forward1(e,t,n){(!Array.isArray(t)||!t.every(f=>"role"in f))&&this.validateInputs(t);let r=performance.now(),o=this.createStates(n.sampleCount??1),i=performance.now()-r,a=this.getMetricsInstruments();a&&go(a,"state_creation",i,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,c=this.functions;if(n?.functions&&(c=bo(n.functions,this.functions)),!l){yield*this._forward2(e,t,o,{...n,functions:c});return}let u=c?.map(f=>f.name).join(","),d={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...u?{provided_functions:u}:{},...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}:{}},p=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=p?`AxGen > ${p}`:"AxGen",h=l.startSpan(m,{kind:Ee.SERVER,attributes:d}),A=It.active(),g=_n.setSpan(A,h);try{if(this.excludeContentFromTrace||h.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:c},h,g),!this.excludeContentFromTrace){let f=o.map(b=>b.values),x=f.length===1?f[0]:f;h.addEvent("output",{content:JSON.stringify(x,null,2)})}}finally{h.end()}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??ee.cachingFunction,o=(()=>{if(!r)return;let p=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,p)})();if(r&&o){let p=await r(o);if(p!==void 0)return p}let i=performance.now(),a=this.getSignatureName(),l=n?.stream??!1,c=!1,u=0,d=!1;try{let p=this.getMetricsInstruments();p&&ul(p,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a);let m=this._forward1(e,t,n??{}),h=[],A=0,g=0;for await(let k of m)k.version!==A&&(h=[]),A=k.version,h=ai(h,k),g++;u=A;let f=performance.now();d=!!n?.resultPicker;let x=await ko(h,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),b=performance.now()-f,E=h[x]?.delta??{},R=Array.isArray(t)?{}:t??{};if(this.trace={...R,...E},d&&this.isDebug(e,n)){let k=this.getLogger(e,n);ca(h.length,x,b,k)}if(c=!0,p&&(cl(p,h.length,d,d?b:void 0,a),ll(p,l,g,void 0,a)),r&&o)try{await r(o,E)}catch{}return E}catch(p){throw c=!1,p}finally{let p=performance.now()-i,m=this.getMetricsInstruments();m&&(ol(m,p,c,a,e.getName(),n?.model?String(n.model):void 0),u>0&&Vs(m,u,c,n?.maxRetries??10,a))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??ee.cachingFunction,o=(()=>{if(!r)return;let d=this.signature.getInputFields().map(p=>p.name);return this.computeCacheKey(t,d)})();if(r&&o){let d;try{d=await r(o)}catch{}if(d!==void 0){yield{version:0,index:0,delta:d};return}}if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let i=this._forward1(e,t,{...n,stream:!0}),a=[],l=0;for await(let d of i)d.version!==l&&(a=[]),l=d.version,a=ai(a,d);let c=await ko(a,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),u=a[c];if(u){if(r&&o)try{await r(o,u.delta)}catch{}yield{version:l,index:c,delta:u.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??ee.logger??e.getLogger()}computeCacheKey(e,t){let n=Be("sha256");n.update(this.signature.hash()??"");let r=o=>{let i=typeof o;if(n.update(`|${i}|`),o==null){n.update("null");return}if(i==="string"||i==="number"||i==="boolean"){n.update(String(o));return}if(Array.isArray(o)){n.update("[");for(let a of o)r(a);n.update("]");return}if(typeof o=="object"&&o!==null&&"mimeType"in o&&"data"in o){let a=o;n.update(a.mimeType??"");let l=Be("sha256").update(a.data??"").digest("hex");n.update(l);return}if(typeof o=="object"){let a=o,l=Object.keys(a).sort();for(let c of l)n.update(`{${c}}`),r(a[c]);return}n.update(String(o))};if(Array.isArray(e))for(let o of e){n.update(`role:${o.role}`);let i=t.map(a=>o.values?.[a]);for(let a of i)r(a)}else{let o=t.map(i=>e?.[i]);for(let i of o)r(i)}return n.digest("hex")}},ar=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function xi(s,e,t){let n=s instanceof Error?s:new Error(String(s)),r=(n.message||"").toLowerCase();if(r.includes("at least")||r.includes("at most")||r.includes("must match pattern")||r.includes("invalid url")||r.includes("required")||r.includes("missing")||r.includes("valid email")||r.includes("number must be")||n.name==="ValidationError"||n.name==="AssertionError"||n.name==="AxAssertionError"||n.stack?.includes("asserts.ts"))return n;let i=e.getLastUsedChatModel(),a=e.getLastUsedModelConfig(),l={model:i,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new ar("Generate failed",l,{cause:n})}var Zu=s=>s.replace(/^\W+|\W+$/g,""),Xu=(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]},ep=s=>{let e=new Set,t=[];for(let n of s)e.has(n)||(e.add(n),t.push(n));return t},tp=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}},np=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():s},rp=(s,e)=>{let t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t},Eo={trimNonAlphaNum:Zu,splitIntoTwo:Xu,dedup:ep,extractIdAndText:tp,extractIndexPrefixedText:np,batchArray:rp};var Po=class extends Pe{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."
|
|
233
233
|
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}=Eo.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let c=o[l];return c!==void 0?t.items[c]:void 0}).filter(a=>a!==void 0)}}};var Fo=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(c=>this._convert(c,{format:t?.format})),l=await Promise.all(a);n.push(...l)}return n}};var rx=new Se,_o=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},Do=class{ai;db;debug;constructor(e){this.db=new Tt,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)}let i=o.at(0);return i?i.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var Xl=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 ec(s,e){return s.filter(t=>!e.has(t))}function tc(s){let e={};for(let t of s)e[t]=(e[t]||0)+1;return e}function Dt(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 op(s,e){return Dt(s)===Dt(e)?1:0}function sp(s,e){let t=Dt(s).split(" "),n=Dt(e).split(" "),r=tc(t),o=tc(n),i=0;for(let c in r){let u=r[c]??0,d=o[c]??0;i+=Math.min(u,d)}if(i===0)return 0;let a=i/t.length,l=i/n.length;return 2*a*l/(a+l)}function ip(s,e,t,n=!1){let r=Dt(s).split(" "),o=Dt(e).split(" "),i=Dt(t).split(" "),a=new Set([...Xl,...r]);o=ec(o,a),i=ec(i,a);let l=0,c=l/o.length,u=l/i.length,d=2*c*u/(c+u);return n?u:d}var nc={emScore:op,f1Score:sp,novelF1ScoreOptimized:ip};var No=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}),c=await e({prediction:l,example:a});r+=c}catch(l){console.warn(`Program evaluation failed for example ${i}: ${l instanceof Error?l.message:"Unknown error"}`)}}let o=n>0?r/n:0;this.ai.getOptions().debug&&console.log(`
|
|
234
234
|
Performance: `,r,"/",n,"Average Score: ",o,`
|
|
235
235
|
`)}};var $o=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 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("."),c=o.row;for(let d of l)Object.hasOwn(c,d)&&(c=c[d]);if(!c)return;let u=n&&a in n?n[a]:a;if(!u)throw new Error(`Invalid field name: ${a}`);i[u]=c}),i}).filter(o=>Object.keys(o).length!==0)}};var rc=s=>{console.log(s)},yi=(s=rc)=>{let e=new Se,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let o="";switch(r.name){case"OptimizationStart":o=`
|
|
@@ -314,7 +314,7 @@ ${t}`.trim()}function Ip(s){let e=s.toLowerCase().replace(/[^a-z0-9]+/g,"-").rep
|
|
|
314
314
|
|
|
315
315
|
`);e.setDescription(r)}},Uo=class extends Fe{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;constructor(e,t){super(e),this.aceConfig={...Cp,...t},this.playbook=t?.initialPlaybook!==void 0?Nt(t.initialPlaybook):Ii()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?Nt(this.aceConfig.initialPlaybook):Ii(),this.generatorHistory=[],this.deltaHistory=[]}configureAuto(e){switch(e){case"light":this.aceConfig.maxEpochs=1,this.aceConfig.maxReflectorRounds=1;break;case"medium":this.aceConfig.maxEpochs=2,this.aceConfig.maxReflectorRounds=2;break;case"heavy":this.aceConfig.maxEpochs=3,this.aceConfig.maxReflectorRounds=3;break}}async compile(e,t,n,r){let o=r?.aceOptions;o&&(Object.assign(this.aceConfig,{maxEpochs:o.maxEpochs??this.aceConfig.maxEpochs,maxReflectorRounds:o.maxReflectorRounds??this.aceConfig.maxReflectorRounds,maxSectionSize:o.maxSectionSize??this.aceConfig.maxSectionSize,similarityThreshold:o.similarityThreshold??this.aceConfig.similarityThreshold,allowDynamicSections:o.allowDynamicSections??this.aceConfig.allowDynamicSections}),o.initialPlaybook&&(this.playbook=Nt(o.initialPlaybook)));let i=Date.now();this.validateExamples(t);let a=await this.extractProgramInstruction(e),l=e.getSignature().getDescription()??"";this.generatorHistory=[],this.deltaHistory=[];let c=Number.NEGATIVE_INFINITY,u=0,d=Math.max(this.aceConfig.maxEpochs,1),p=d*t.length;try{for(let f=0;f<d;f++)for(let x=0;x<t.length;x++){let b=t[x],T=this.composeInstruction(a??l,this.playbook);e.setDescription?.(T);let E=await e.forward(this.studentAI,b);this.stats.totalCalls+=1;let R=await n({prediction:E,example:b});typeof R=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,R),c=Math.max(c,R));let k=E?.severity,y=b?.severity,O=this.createGeneratorOutput(E,b),F=y&&k&&y!==k,P=await this.runReflectionRounds({example:b,generatorOutput:O,feedback:y&&k&&y!==k?`Expected severity "${y}" but model predicted "${k}".`:void 0}),w=await this.runCurator({example:b,reflection:P,playbook:this.playbook}),v=this.normalizeCuratorOperations(w?.operations);v.length===0&&F&&(v=this.inferOperationsFromReflection(P)),v=this.resolveCuratorOperationTargets(v,this.playbook,P,O);let I=w||v.length>0?{...w??{},operations:v}:void 0,S=[];if(v.length>0){let z=this.collectProtectedBulletIds(v),j=Ti(this.playbook,v,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:z});S=j.updatedBulletIds,j.autoRemoved.length>0&&(v.push(...j.autoRemoved),I&&(I.operations=v))}if(P?.bulletTags)for(let z of P.bulletTags)Ci(this.playbook,z.id,z.tag);v.length>0&&S.length>0&&Ri(this.playbook,this.aceConfig.similarityThreshold);let C={example:b,prediction:E,score:typeof R=="number"?R:0,generatorOutput:O,reflection:P,curator:I,timestamp:new Date().toISOString()};this.generatorHistory.push(C),S.length>0&&I?.operations?.length&&this.deltaHistory.push({epoch:f,exampleIndex:x,operations:I.operations}),u+=1,this.currentRound=u;let M=typeof R=="number"&&Number.isFinite(R)?R:0,_=Number.isFinite(c)?c:M,D={...r??{},maxIterations:p};await this.updateOptimizationProgress(u,M,{epoch:f,exampleIndex:x,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:d,totalRounds:p},_,{playbookBullets:this.playbook.stats.bulletCount},void 0,D),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,M)}}finally{e.setDescription?.(l)}let m=Date.now()-i;this.stats.resourceUsage.totalTime=m,this.stats.convergenceInfo.converged=!0,this.stats.bestScore=Number.isFinite(c)?c:0;let h={playbook:Nt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},A=new pr({baseInstruction:a??l,playbook:this.playbook,artifact:h,bestScore:Number.isFinite(c)?c:0,stats:this.stats,optimizerType:"ACE",optimizationTime:m,totalRounds:u,converged:this.stats.convergenceInfo.converged});return{stats:this.stats,bestScore:Number.isFinite(c)?c:0,finalConfiguration:{strategy:"ace",epochs:d},optimizedProgram:A,playbook:Nt(this.playbook),artifact:h}}async applyOnlineUpdate(e){let t=this.createGeneratorOutput(e.prediction,e.example),n=e.prediction?.severity,r=e.example?.severity,o=await this.runReflectionRounds({example:e.example,generatorOutput:t,feedback:e.feedback??(r&&n&&r!==n?`Expected severity "${r}" but model predicted "${n}".`:void 0)}),i=await this.runCurator({example:e.example,reflection:o,playbook:this.playbook}),a=this.normalizeCuratorOperations(i?.operations),l=r&&n&&r!==n;a.length===0&&l&&(a=this.inferOperationsFromReflection(o)),a=this.resolveCuratorOperationTargets(a,this.playbook,o,t);let c=i||a.length>0?{...i??{},operations:a}:void 0;if(o?.bulletTags)for(let d of o.bulletTags)Ci(this.playbook,d.id,d.tag);if(a.length>0){let d=this.collectProtectedBulletIds(a),p=Ti(this.playbook,a,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:d});p.autoRemoved.length>0&&(a.push(...p.autoRemoved),c&&(c.operations=a)),Ri(this.playbook,this.aceConfig.similarityThreshold)}let u={example:e.example,prediction:e.prediction,score:0,generatorOutput:t,reflection:o,curator:c,timestamp:new Date().toISOString()};return this.generatorHistory.push(u),c}composeInstruction(e,t){return[e.trim(),"",ur(t)].filter(r=>r.trim().length>0).join(`
|
|
316
316
|
|
|
317
|
-
`)}async extractProgramInstruction(e){try{return e.getSignature().getDescription()??void 0}catch{return}}createGeneratorOutput(e,t){let n=e?.thought?.toString()??"",r=Array.isArray(e?.bullet_ids)?e?.bullet_ids:[];return{reasoning:n,answer:e,bulletIds:r,trajectory:JSON.stringify({example:t,prediction:e}),metadata:{predictedSeverity:e?.severity,expectedSeverity:t?.severity}}}resolveCuratorOperationTargets(e,t,n,r){if(!e.length)return e;let o=[],i=new Set(e.map(u=>u.bulletId).filter(u=>typeof u=="string")),a=new Map,l=(u,d)=>{if(i.has(u))return;let p=this.locateBullet(t,u);if(!p)return;let m=a.get(p.section)??{harmful:[],primary:[],generator:[]};m[d].push(p.id),a.set(p.section,m)};for(let u of n?.bulletTags??[]){let d=u.tag==="harmful"?"harmful":"primary";l(u.id,d)}if(r?.bulletIds)for(let u of r.bulletIds)l(u,"generator");let c=u=>{let d=a.get(u);if(!d)return this.locateFallbackBullet(t,u,i);let p=h=>{for(;h.length>0;){let A=h.shift();if(!i.has(A))return A}},m=p(d.harmful)??p(d.primary)??p(d.generator);return m||this.locateFallbackBullet(t,u,i)};for(let u of e){if((u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId){let d=c(u.section);d&&(u.bulletId=d,i.add(d))}(u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId||o.push(u)}return o}locateBullet(e,t){for(let n of Object.values(e.sections)){let r=n.find(o=>o.id===t);if(r)return r}}locateFallbackBullet(e,t,n){let r=e.sections[t]??[];for(let o of r)if(!n.has(o.id))return o.id}collectProtectedBulletIds(e){let t=new Set;for(let n of e)n.type==="UPDATE"&&n.bulletId&&t.add(n.bulletId);return t}normalizeCuratorOperations(e){if(!e)return[];if(Array.isArray(e)){let t=[],n=new Set;for(let r of e){if(!r||typeof r!="object")continue;let o=r.type??"ADD",i=typeof o=="string"?o.toUpperCase():"ADD",a=i==="UPDATE"?"UPDATE":i==="REMOVE"?"REMOVE":"ADD",l=r.section??"Guidelines",c=typeof l=="string"&&l.trim().length>0?l.trim():"Guidelines",u=r.content??"",d=typeof u=="string"?u.trim():"";if(a!=="REMOVE"&&d.length===0)continue;let p=r.bulletId??r.id,m=typeof p=="string"&&p.trim().length>0?p.trim():void 0,A=[a,c,d,m??""].join(":");if(n.has(A))continue;n.add(A);let g={type:a,section:c};a!=="REMOVE"&&(g.content=d),m&&(g.bulletId=m);let f=r.metadata;f&&typeof f=="object"&&(g.metadata={...f}),t.push(g)}return t}if(typeof e=="string")try{let t=JSON.parse(e);return this.normalizeCuratorOperations(t)}catch{return[]}if(typeof e=="object"){let t=e;if(t&&Array.isArray(t.operations))return this.normalizeCuratorOperations(t.operations);if(t&&typeof t.operations=="string")try{let n=JSON.parse(t.operations);return this.normalizeCuratorOperations(n)}catch{return[]}return[]}return[]}inferOperationsFromReflection(e){if(!e)return[];let t=[],n=new Set,r=(o,i)=>{if(!i)return;let a=i.trim();if(!a||a.toLowerCase().startsWith("no error"))return;let c=`${o}:${a}`;n.has(c)||(n.add(c),t.push({type:"ADD",section:o,content:a}))};return r("Guidelines",e.keyInsight),r("Response Strategies",e.correctApproach),r("Common Pitfalls",e.errorIdentification),r("Root Cause Notes",e.rootCauseAnalysis),t}async runReflectionRounds({example:e,generatorOutput:t,feedback:n}){let r=Math.max(this.aceConfig.maxReflectorRounds,1),o;for(let i=0;i<r;i++){let a=await this.runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:o});if(!a)break;o=a;let l=a.errorIdentification?.toLowerCase().trim()??"";if(a.metadata?.resolved===!0||l.length===0||l.startsWith("no error")||l.startsWith("resolved"))break}return o}async runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:r}){let o=this.getOrCreateReflectorProgram(),i=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint};return await o.forward(i,{question:JSON.stringify(e),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:ur(this.playbook),structured:this.playbook}),expected_answer:a.severity||a.policyHint?JSON.stringify(a):void 0,feedback:n,previous_reflection:r?JSON.stringify(r):void 0})}catch(a){this.verbose&&console.warn("[AxACE] Reflector error:",a instanceof Error?a.message:a);return}}async runCurator({example:e,reflection:t,playbook:n}){if(!t)return;let r=this.getOrCreateCuratorProgram(),o=this.teacherAI??this.studentAI;try{return await r.forward(o,{playbook:JSON.stringify({markdown:ur(n),structured:n}),reflection:JSON.stringify(t),question_context:JSON.stringify(e),token_budget:1024})}catch(i){this.verbose&&console.warn("[AxACE] Curator error:",i instanceof Error?i.message:i);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=ie().input("question",ie.string("Original task input serialized as JSON")).input("generator_answer",ie.string("Generator output serialized as JSON")).input("generator_reasoning",ie.string("Generator reasoning trace").optional()).input("playbook",ie.string("Current context playbook rendered as markdown")).input("expected_answer",ie.string("Expected output when ground truth is available").optional()).input("feedback",ie.string("External feedback or reward signal").optional()).input("previous_reflection",ie.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",ie.string("Step-by-step analysis of generator performance")).output("errorIdentification",ie.string("Specific mistakes detected")).output("rootCauseAnalysis",ie.string("Underlying cause of the error")).output("correctApproach",ie.string("What the generator should do differently")).output("keyInsight",ie.string("Reusable insight to remember")).output("bulletTags",ie.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=Ie(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=ie().input("playbook",ie.string("Current playbook serialized as JSON")).input("reflection",ie.string("Latest reflection output serialized as JSON")).input("question_context",ie.string("Original task input serialized as JSON")).input("token_budget",ie.number("Approximate token budget for curator response").optional()).output("reasoning",ie.string("Justification for the proposed updates")).output("operations",ie.json("List of operations with type/section/content fields")).build();this.curatorProgram=Ie(e)}return this.curatorProgram}};var bn=class extends Fe{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,o){let i=Date.now(),a=o?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=wp([...t],this.maxExamples),u=this.traces.length;for(let d=0;d<c.length;d+=this.batchSize){d>0&&(l.modelConfig.temperature=.7+.001*d);let p=c.slice(d,d+this.batchSize);for(let m of p){if(!m||typeof m!="object")continue;let h=t.filter(f=>f!==m);e.setExamples(h);let A=this.getTeacherOrStudentAI();this.stats.totalCalls++;let g;try{let f={...l,maxRetries:1};g=await e.forward(A,m,f),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(g).length/4),await r({prediction:g,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(f){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${f instanceof Error?f.message:"Unknown error"}`),g={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let p=this.traces.length-u;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:p>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(p>0)this.stats.earlyStopping.bestScoreRound=n;else if(n-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,r){this.validateExamples(t,!1);let o=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<o&&(await this.compileRound(e,t,l,n,r),!this.stats.earlyStopped);l++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let i=Rp(this.traces),a=0;return this.traces.length>0&&(a=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),await this.logOptimizationComplete("BootstrapFewShot",a,{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a,demosGenerated:i.length,tracesCollected:this.traces.length},r),{demos:i,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function Rp(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 wp=(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)};function cc(s,e,t=0){let n=new Set([...Object.keys(s),...Object.keys(e)]),r=!0,o=!1;for(let i of n){let a=s[i]??0,l=e[i]??0;if(a+t<l){r=!1;break}a>l+t&&(o=!0)}return r&&o}function at(s,e=0){let t=[];for(let n=0;n<s.length;n++){let r=0,o=!1;for(let i=0;i<s.length;i++)if(n!==i){if(cc(s[i].scores,s[n].scores,e)){o=!0;break}cc(s[n].scores,s[i].scores,e)&&r++}o||t.push({idx:s[n].idx,scores:s[n].scores,dominated:r})}return t}function Ke(s){if(s.length===0)return;let e=Object.keys(s[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...s].sort((a,l)=>(l[t]??0)-(a[t]??0)),o=0,i=0;for(let a of r){let l=a[t]??0,c=a[n]??0,u=Math.max(c-i,0);o+=l*u,i=Math.max(i,c)}return o}function $t(s){if(s.length===0)return 0;let e=0;for(let t of s)e+=t;return e/s.length}function Bo(s){let e={},t={};for(let r of s)for(let[o,i]of Object.entries(r))e[o]=(e[o]||0)+(typeof i=="number"?i:0),t[o]=(t[o]||0)+1;let n={};for(let[r,o]of Object.entries(e))n[r]=o/Math.max(t[r]||1,1);return n}function dr(s,e){let t=new Set;for(let u of s)for(let d of u)t.add(d);let r=[...Array.from(t)].sort((u,d)=>(e[u]??0)-(e[d]??0)),o=new Set,i=(u,d)=>{for(let p of s){if(!p.has(u))continue;let m=!1;for(let h of d)if(p.has(h)){m=!0;break}if(!m)return!1}return!0},a=!0;for(;a;){a=!1;for(let u of r){if(o.has(u))continue;let d=new Set(r.filter(p=>p!==u&&!o.has(p)));if(i(u,d)){o.add(u),a=!0;break}}}let l=r.filter(u=>!o.has(u)),c=new Set(l);return s.map(u=>{let d=new Set;for(let p of u)c.has(p)&&d.add(p);return d})}function mr(s,e,t){let n=dr(s,e),r={};for(let l of n)for(let c of l)r[c]=(r[c]||0)+1;let o=[];for(let[l,c]of Object.entries(r)){let u=Number(l);for(let d=0;d<c;d++)o.push(u)}if(o.length===0)return 0;let i=typeof t=="function"?t():Math.random(),a=Math.floor(i*o.length);return o[a]}var jo=class extends Fe{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;paretoSetSize;crossoverEvery;tieEpsilon;feedbackMemorySize;feedbackMemory=[];mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;rngState=123456789;samplerState={epoch:-1,shuffled:[],freq:new Map};localScoreHistory=[];localConfigurationHistory=[];constructor(e){super(e);let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??20,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(o??Math.max(3,Math.floor(this.numTrials/4))));let i=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(i)?i:0;let a=e?.feedbackMemorySize;this.feedbackMemorySize=Math.max(0,Math.floor(a??4));let l=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(l??0)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.localScoreHistory=[],this.localConfigurationHistory=[],this.feedbackMemory=[],this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}async compile(e,t,n,r){let o=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let i=r?.validationExamples,a=r?.feedbackExamples,l=(i&&i.length>0?i:t).slice(0,this.paretoSetSize),c=a&&a.length>0?a:t,u=async(I,S)=>{try{e.setInstruction?.(I);let C=await e.forward(this.studentAI,S,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:C,example:S})||{}}catch{return{}}},d=async(I,S)=>{let C=[];for(let M of S)C.push(await u(I,M));return Bo(C)},p=await this.getBaseInstruction(e),m=[{instruction:p,parent:void 0,scores:await d(p,l)}],h=I=>{let S=r?.paretoMetricKey,C=r?.paretoScalarize;if(typeof C=="function")return C(I);if(S)return Number.isFinite(I[S])?I[S]:0;let M=Object.values(I);return M.length?M.reduce((_,D)=>_+D,0)/M.length:0},A=[],g=async(I,S)=>{let C=[];for(let M of S){let _=await u(I,M);C.push(h(_))}return C};A.push(await g(p,l));let f=()=>{let I=A[0]?.length??0,S=[];for(let M=0;M<I;M++){let _=Number.NEGATIVE_INFINITY,D=new Set;for(let z=0;z<A.length;z++){let j=A[z][M];j>_+this.tieEpsilon?(_=j,D.clear(),D.add(z)):Math.abs(j-_)<=this.tieEpsilon&&D.add(z)}S.push(D)}let C=A.map(M=>$t(M));return mr(S,C)};this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let b=0,T=at(m.map((I,S)=>({idx:S,scores:I.scores})),this.tieEpsilon).map(I=>I.idx),E,R=r?.maxMetricCalls;if(!Number.isFinite(R)||R<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let k=Math.floor(R);for(let I=0;I<this.numTrials&&!(k!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(k)));I++){let S=A[0]?.length??0,C=[];for(let N=0;N<S;N++){let U=Number.NEGATIVE_INFINITY,q=new Set;for(let H=0;H<A.length;H++){let J=A[H][N];J>U+this.tieEpsilon?(U=J,q.clear(),q.add(H)):Math.abs(J-U)<=this.tieEpsilon&&q.add(H)}C.push(q)}let M=A.map(N=>$t(N));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let N=L=>{let $=[],G=L;for(;G!==void 0;)$.push(G),G=m[G]?.parent;return $},U=L=>L.length?L[Math.floor(this.rand()*L.length)]:void 0,q=dr(C,M),H=new Set;for(let L of q)for(let $ of L)H.add($);let J=Array.from(H),oe;for(let L=0;L<10&&!oe&&!(J.length<2);L++){let $=U(J),G=U(J);if($===G)continue;G<$&&([$,G]=[G,$]);let ne=new Set(N($)),me=new Set(N(G));if(ne.has(G)||me.has($))continue;let re=[...ne].filter(pe=>me.has(pe));if(re.length===0)continue;let Y=re.map(pe=>Math.max(1e-9,M[pe])),Z=this.rand()*Y.reduce((pe,Ve)=>pe+Ve,0),X=re[re.length-1];for(let pe=0;pe<re.length;pe++){if(Z<Y[pe]){X=re[pe];break}Z-=Y[pe]}oe={i:$,j:G,a:X}}if(this.lastIterFoundNewProgram=!1,oe){let{i:L,j:$,a:G}=oe,ne=M[G],me=M[L],re=M[$],Y=m[G].instruction,Z=m[L].instruction,X=m[$].instruction,pe=Z===Y&&X!==Z||X===Y&&Z!==X,Ve=ne<=Math.min(me,re)&&pe,Ne="",$e="i",ft=!1;if(Ve){let lt=`${L}|${$}|${G}`;if(this.mergeAttemptKeys.has(lt))Ve=!1;else{Z===Y&&X!==Z?(Ne=X,$e="j"):X===Y&&Z!==X?(Ne=Z,$e="i"):Z!==Y&&X!==Y&&Z!==X?me>re||me===re&&this.rand()<.5?(Ne=Z,$e="i"):(Ne=X,$e="j"):(Ne=Z,$e="i");let ce=`${Math.min(L,$)}|${Math.max(L,$)}|${$e}`;if(this.mergeCompositionKeys.has(ce))Ve=!1;else{this.mergeAttemptKeys.add(lt),this.mergeCompositionKeys.add(ce);let Je=A[L],ct=A[$],Ge=Array.from({length:Je.length},(se,Re)=>Re),At=Ge.filter(se=>(Je[se]??0)>(ct[se]??0)),Lt=Ge.filter(se=>(ct[se]??0)>(Je[se]??0)),vt=Ge.filter(se=>!(At.includes(se)||Lt.includes(se))),ut=5,xt=Math.ceil(ut/3),W=(se,Re)=>{if(Re<=0||se.length===0)return[];if(se.length<=Re)return[...se];let On=[],xr=new Set;for(;On.length<Re;){let Ye=Math.floor(this.rand()*se.length);xr.has(Ye)||(xr.add(Ye),On.push(se[Ye]))}return On},ae=[];ae.push(...W(At,Math.min(xt,At.length))),ae.push(...W(Lt,Math.min(xt,Lt.length)));let St=ut-ae.length;ae.push(...W(vt,Math.max(0,St)));let Ot=ut-ae.length;if(Ot>0){let se=Ge.filter(Re=>!ae.includes(Re));ae.push(...W(se,Math.min(Ot,se.length)))}let Ce=ae.slice(0,Math.min(ut,Ge.length)),es=Ce.map(se=>l[se]);ft=!0;let vc=(await g(Ne,es)).reduce((se,Re)=>se+Re,0),Sc=Ce.reduce((se,Re)=>se+(Je[Re]??0),0),Oc=Ce.reduce((se,Re)=>se+(ct[Re]??0),0);if(vc>=Math.max(Sc,Oc)+this.tieEpsilon){let se=await d(Ne,l);m.push({instruction:Ne,parent:G,scores:se}),A.push(await g(Ne,l));let Re=T.length,On=Ke(T.map(Ye=>m[Ye].scores))??0;T=at(m.map((Ye,kc)=>({idx:kc,scores:Ye.scores})),this.tieEpsilon).map(Ye=>Ye.idx);let xr=Ke(T.map(Ye=>m[Ye].scores))??0;(T.length>Re||xr>On+1e-6)&&(b=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(ft)continue}}let _=mr(C,M,()=>this.rand()),D=this.minibatch?this.nextMinibatchIndices(c.length,I).map(N=>c[N]):c;if(r?.skipPerfectScore??!0){let N=Number(r?.perfectScore??1),U=await g(m[_].instruction,D);if(U.length>0&&U.every(q=>q>=N))continue}let z=!1,j=m[_].instruction,Q="reflective_mutation",le,xe;if(z){let N=(_+1)%m.length;j=await this.mergeInstructions(m[_].instruction,m[N].instruction,r),Q="merge",this.mergesUsed+=1}else{let N=r?.gepaAdapter;if(N){try{let U={instruction:m[_].instruction},q=await N.evaluate(D,U,!0);le=Array.isArray(q?.scores)?q.scores.reduce((L,$)=>L+(Number($)||0),0):void 0;let H=N.make_reflective_dataset(U,q,["instruction"]),J=await N.propose_new_texts?.(U,H,["instruction"]),oe=J?.instruction??(J?Object.values(J)[0]:void 0);typeof oe=="string"&&oe.length>0?j=oe:j=await this.reflectInstruction(m[_].instruction,e,D,async({prediction:L,example:$})=>{let G=await n({prediction:L,example:$}),ne=Object.values(G||{});return ne.length?ne.reduce((me,re)=>me+re,0)/ne.length:0},r)}catch{j=await this.reflectInstruction(m[_].instruction,e,D,async({prediction:U,example:q})=>{let H=await n({prediction:U,example:q}),J=Object.values(H||{});return J.length?J.reduce((oe,L)=>oe+L,0)/J.length:0},r)}if(le!==void 0)try{let U=await N.evaluate(D,{instruction:j},!1);xe=Array.isArray(U?.scores)?U.scores.reduce((q,H)=>q+(Number(H)||0),0):void 0}catch{}}else j=await this.reflectInstruction(m[_].instruction,e,D,async({prediction:U,example:q})=>{let H=await n({prediction:U,example:q}),J=Object.values(H||{});return J.length?J.reduce((oe,L)=>oe+L,0)/J.length:0},r)}let _e=await g(m[_].instruction,D),We=await g(j,D),Oe=_e.reduce((N,U)=>N+U,0),ue=We.reduce((N,U)=>N+U,0);if(this.currentRound=I+1,await this.updateOptimizationProgress(this.currentRound,ue,{instructionLen:j.length,parent:_,totalRounds:this.numTrials},"GEPA",{strategy:Q,paretoSetSize:l.length},ue,{instructionLen:m[_].instruction.length,idx:_},{...r??{},maxIterations:this.numTrials}),!(ue>Oe+this.tieEpsilon&&(le===void 0||xe===void 0||xe>le+this.tieEpsilon))){if(++b>=this.earlyStoppingTrials)break;continue}let De=await d(j,l);m.push({instruction:j,parent:_,scores:De}),A.push(await g(j,l));let Le=T.length,gt=Ke(T.map(N=>m[N].scores))??0;T=at(m.map((N,U)=>({idx:U,scores:N.scores})),this.tieEpsilon).map(N=>N.idx);let ht=Ke(T.map(N=>m[N].scores))??0;if(T.length>Le||ht>gt+1e-6)b=0;else if(b++,b>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let y=at(m.map((I,S)=>({idx:S,scores:I.scores})),this.tieEpsilon),O=y.length>0?Math.max(...y.map(I=>h(I.scores))):0,F;if(y.length>0){let I=Number.NEGATIVE_INFINITY;for(let S of y){let C=h(S.scores);C>I&&(I=C,F=S.idx)}}let P=Ke(y.map(I=>I.scores));this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(y.length,m.length,"GEPA",P);let w=Date.now()-o,v=typeof F=="number"?new it({bestScore:O,stats:this.stats,instruction:m[F].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:w,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0;return this.generateOptimizationReport(y,P,O),{demos:[],stats:this.stats,bestScore:O,paretoFront:y.map(I=>({demos:[],scores:I.scores,configuration:{candidate:I.idx},dominatedSolutions:I.dominated})),paretoFrontSize:y.length,hypervolume:P,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:v}}configureAuto(e){switch(e){case"light":this.numTrials=10,this.minibatch=!0,this.minibatchSize=15;break;case"medium":this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numTrials=35,this.minibatch=!0,this.minibatchSize=35;break}}async getBaseInstruction(e){try{let t=e.getSignature?.();if(t&&typeof t.instruction=="string"&&t.instruction.length>0)return t.instruction}catch{}return"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let i of n){let a=await this.evaluateOne(e,t,i,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?$t(o):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let i=await r({prediction:o,example:n});if(typeof i=="number"&&!Number.isNaN(i)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return i>=a&&(this.stats.successfulDemos+=1),i}return 0}catch(o){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(o)}),0}}async reflectInstruction(e,t,n,r,o){let i=[];for(let m of n)try{t.setInstruction?.(e);let h=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let A=await r({prediction:h,example:m});i.push({input:m,prediction:h,score:typeof A=="number"?A:0})}catch{i.push({input:m,prediction:{},score:0})}let a=o?.overrideTeacherAI??this.teacherAI??this.studentAI,l=Ie('minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback per case if available" -> feedbackSummary:string "Concise feedback: common errors, missing constraints, desired changes"'),c=[],u=o?.feedbackFn;if(typeof u=="function")for(let m=0;m<i.length;m++)try{let h=u({prediction:i[m].prediction,example:i[m].input});h&&(Array.isArray(h)?c.push(...h):c.push(h))}catch{}let d="";try{d=(await l.forward(a,{minibatch:i,evalFeedback:c}))?.feedbackSummary?.trim()||"",d&&(this.feedbackMemory.unshift(d),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop())}catch{}let p=Ie('currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", recentFeedback?:string[] "Past feedback memory", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction within 1-6 sentences."');try{let h=(await p.forward(a,{currentInstruction:e,feedbackSummary:d,recentFeedback:this.feedbackMemory,minibatch:i}))?.newInstruction?.trim();if(h&&h.length>16)return h}catch{}return`${e.trim()} Focus on step-by-step evidence-based reasoning. Avoid hallucinations.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,c)=>c);for(let l=t.length-1;l>0;l--){let c=Math.floor(this.rand()*(l+1));[t[l],t[c]]=[t[c],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,i=Array.from({length:e},(l,c)=>c).sort((l,c)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let l=0;l<o;l++){let c=i[l%i.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let i=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(i,i+n)}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}generateOptimizationReport(e,t,n){console.log(`
|
|
317
|
+
`)}async extractProgramInstruction(e){try{return e.getSignature().getDescription()??void 0}catch{return}}createGeneratorOutput(e,t){let n=e?.thought?.toString()??"",r=Array.isArray(e?.bullet_ids)?e?.bullet_ids:[];return{reasoning:n,answer:e,bulletIds:r,trajectory:JSON.stringify({example:t,prediction:e}),metadata:{predictedSeverity:e?.severity,expectedSeverity:t?.severity}}}resolveCuratorOperationTargets(e,t,n,r){if(!e.length)return e;let o=[],i=new Set(e.map(u=>u.bulletId).filter(u=>typeof u=="string")),a=new Map,l=(u,d)=>{if(i.has(u))return;let p=this.locateBullet(t,u);if(!p)return;let m=a.get(p.section)??{harmful:[],primary:[],generator:[]};m[d].push(p.id),a.set(p.section,m)};for(let u of n?.bulletTags??[]){let d=u.tag==="harmful"?"harmful":"primary";l(u.id,d)}if(r?.bulletIds)for(let u of r.bulletIds)l(u,"generator");let c=u=>{let d=a.get(u);if(!d)return this.locateFallbackBullet(t,u,i);let p=h=>{for(;h.length>0;){let A=h.shift();if(!i.has(A))return A}},m=p(d.harmful)??p(d.primary)??p(d.generator);return m||this.locateFallbackBullet(t,u,i)};for(let u of e){if((u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId){let d=c(u.section);d&&(u.bulletId=d,i.add(d))}(u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId||o.push(u)}return o}locateBullet(e,t){for(let n of Object.values(e.sections)){let r=n.find(o=>o.id===t);if(r)return r}}locateFallbackBullet(e,t,n){let r=e.sections[t]??[];for(let o of r)if(!n.has(o.id))return o.id}collectProtectedBulletIds(e){let t=new Set;for(let n of e)n.type==="UPDATE"&&n.bulletId&&t.add(n.bulletId);return t}normalizeCuratorOperations(e){if(!e)return[];if(Array.isArray(e)){let t=[],n=new Set;for(let r of e){if(!r||typeof r!="object")continue;let o=r.type??"ADD",i=typeof o=="string"?o.toUpperCase():"ADD",a=i==="UPDATE"?"UPDATE":i==="REMOVE"?"REMOVE":"ADD",l=r.section??"Guidelines",c=typeof l=="string"&&l.trim().length>0?l.trim():"Guidelines",u=r.content??"",d=typeof u=="string"?u.trim():"";if(a!=="REMOVE"&&d.length===0)continue;let p=r.bulletId??r.id,m=typeof p=="string"&&p.trim().length>0?p.trim():void 0,A=[a,c,d,m??""].join(":");if(n.has(A))continue;n.add(A);let g={type:a,section:c};a!=="REMOVE"&&(g.content=d),m&&(g.bulletId=m);let f=r.metadata;f&&typeof f=="object"&&(g.metadata={...f}),t.push(g)}return t}if(typeof e=="string")try{let t=JSON.parse(e);return this.normalizeCuratorOperations(t)}catch{return[]}if(typeof e=="object"){let t=e;if(t&&Array.isArray(t.operations))return this.normalizeCuratorOperations(t.operations);if(t&&typeof t.operations=="string")try{let n=JSON.parse(t.operations);return this.normalizeCuratorOperations(n)}catch{return[]}return[]}return[]}inferOperationsFromReflection(e){if(!e)return[];let t=[],n=new Set,r=(o,i)=>{if(!i)return;let a=i.trim();if(!a||a.toLowerCase().startsWith("no error"))return;let c=`${o}:${a}`;n.has(c)||(n.add(c),t.push({type:"ADD",section:o,content:a}))};return r("Guidelines",e.keyInsight),r("Response Strategies",e.correctApproach),r("Common Pitfalls",e.errorIdentification),r("Root Cause Notes",e.rootCauseAnalysis),t}async runReflectionRounds({example:e,generatorOutput:t,feedback:n}){let r=Math.max(this.aceConfig.maxReflectorRounds,1),o;for(let i=0;i<r;i++){let a=await this.runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:o});if(!a)break;o=a;let l=a.errorIdentification?.toLowerCase().trim()??"";if(a.metadata?.resolved===!0||l.length===0||l.startsWith("no error")||l.startsWith("resolved"))break}return o}async runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:r}){let o=this.getOrCreateReflectorProgram(),i=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint};return await o.forward(i,{question:JSON.stringify(e),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:ur(this.playbook),structured:this.playbook}),expected_answer:a.severity||a.policyHint?JSON.stringify(a):void 0,feedback:n,previous_reflection:r?JSON.stringify(r):void 0})}catch(a){this.verbose&&console.warn("[AxACE] Reflector error:",a instanceof Error?a.message:a);return}}async runCurator({example:e,reflection:t,playbook:n}){if(!t)return;let r=this.getOrCreateCuratorProgram(),o=this.teacherAI??this.studentAI;try{return await r.forward(o,{playbook:JSON.stringify({markdown:ur(n),structured:n}),reflection:JSON.stringify(t),question_context:JSON.stringify(e),token_budget:1024})}catch(i){this.verbose&&console.warn("[AxACE] Curator error:",i instanceof Error?i.message:i);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=ie().input("question",ie.string("Original task input serialized as JSON")).input("generator_answer",ie.string("Generator output serialized as JSON")).input("generator_reasoning",ie.string("Generator reasoning trace").optional()).input("playbook",ie.string("Current context playbook rendered as markdown")).input("expected_answer",ie.string("Expected output when ground truth is available").optional()).input("feedback",ie.string("External feedback or reward signal").optional()).input("previous_reflection",ie.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",ie.string("Step-by-step analysis of generator performance")).output("errorIdentification",ie.string("Specific mistakes detected")).output("rootCauseAnalysis",ie.string("Underlying cause of the error")).output("correctApproach",ie.string("What the generator should do differently")).output("keyInsight",ie.string("Reusable insight to remember")).output("bulletTags",ie.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=Ie(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=ie().input("playbook",ie.string("Current playbook serialized as JSON")).input("reflection",ie.string("Latest reflection output serialized as JSON")).input("question_context",ie.string("Original task input serialized as JSON")).input("token_budget",ie.number("Approximate token budget for curator response").optional()).output("reasoning",ie.string("Justification for the proposed updates")).output("operations",ie.json("List of operations with type/section/content fields")).build();this.curatorProgram=Ie(e)}return this.curatorProgram}};var bn=class extends Fe{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,o){let i=Date.now(),a=o?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=wp([...t],this.maxExamples),u=this.traces.length;for(let d=0;d<c.length;d+=this.batchSize){d>0&&(l.modelConfig.temperature=.7+.001*d);let p=c.slice(d,d+this.batchSize);for(let m of p){if(!m||typeof m!="object")continue;let h=t.filter(f=>f!==m);e.setExamples(h);let A=this.getTeacherOrStudentAI();this.stats.totalCalls++;let g;try{let f={...l,maxRetries:1};g=await e.forward(A,m,f),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(g).length/4),await r({prediction:g,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(f){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${f instanceof Error?f.message:"Unknown error"}`),g={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let p=this.traces.length-u;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:p>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(p>0)this.stats.earlyStopping.bestScoreRound=n;else if(n-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,r){this.validateExamples(t,!1);let o=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<o&&(await this.compileRound(e,t,l,n,r),!this.stats.earlyStopped);l++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let i=Rp(this.traces),a=0;return this.traces.length>0&&(a=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),await this.logOptimizationComplete("BootstrapFewShot",a,{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a,demosGenerated:i.length,tracesCollected:this.traces.length},r),{demos:i,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function Rp(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 wp=(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)};function cc(s,e,t=0){let n=new Set([...Object.keys(s),...Object.keys(e)]),r=!0,o=!1;for(let i of n){let a=s[i]??0,l=e[i]??0;if(a+t<l){r=!1;break}a>l+t&&(o=!0)}return r&&o}function at(s,e=0){let t=[];for(let n=0;n<s.length;n++){let r=0,o=!1;for(let i=0;i<s.length;i++)if(n!==i){if(cc(s[i].scores,s[n].scores,e)){o=!0;break}cc(s[n].scores,s[i].scores,e)&&r++}o||t.push({idx:s[n].idx,scores:s[n].scores,dominated:r})}return t}function Ke(s){if(s.length===0)return;let e=Object.keys(s[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...s].sort((a,l)=>(l[t]??0)-(a[t]??0)),o=0,i=0;for(let a of r){let l=a[t]??0,c=a[n]??0,u=Math.max(c-i,0);o+=l*u,i=Math.max(i,c)}return o}function $t(s){if(s.length===0)return 0;let e=0;for(let t of s)e+=t;return e/s.length}function Bo(s){let e={},t={};for(let r of s)for(let[o,i]of Object.entries(r))e[o]=(e[o]||0)+(typeof i=="number"?i:0),t[o]=(t[o]||0)+1;let n={};for(let[r,o]of Object.entries(e))n[r]=o/Math.max(t[r]||1,1);return n}function dr(s,e){let t=new Set;for(let u of s)for(let d of u)t.add(d);let r=[...Array.from(t)].sort((u,d)=>(e[u]??0)-(e[d]??0)),o=new Set,i=(u,d)=>{for(let p of s){if(!p.has(u))continue;let m=!1;for(let h of d)if(p.has(h)){m=!0;break}if(!m)return!1}return!0},a=!0;for(;a;){a=!1;for(let u of r){if(o.has(u))continue;let d=new Set(r.filter(p=>p!==u&&!o.has(p)));if(i(u,d)){o.add(u),a=!0;break}}}let l=r.filter(u=>!o.has(u)),c=new Set(l);return s.map(u=>{let d=new Set;for(let p of u)c.has(p)&&d.add(p);return d})}function mr(s,e,t){let n=dr(s,e),r={};for(let l of n)for(let c of l)r[c]=(r[c]||0)+1;let o=[];for(let[l,c]of Object.entries(r)){let u=Number(l);for(let d=0;d<c;d++)o.push(u)}if(o.length===0)return 0;let i=typeof t=="function"?t():Math.random(),a=Math.floor(i*o.length);return o[a]}var jo=class extends Fe{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;paretoSetSize;crossoverEvery;tieEpsilon;feedbackMemorySize;feedbackMemory=[];mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;rngState=123456789;samplerState={epoch:-1,shuffled:[],freq:new Map};localScoreHistory=[];localConfigurationHistory=[];constructor(e){super(e);let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??20,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(o??Math.max(3,Math.floor(this.numTrials/4))));let i=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(i)?i:0;let a=e?.feedbackMemorySize;this.feedbackMemorySize=Math.max(0,Math.floor(a??4));let l=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(l??0)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.localScoreHistory=[],this.localConfigurationHistory=[],this.feedbackMemory=[],this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}async compile(e,t,n,r){let o=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let i=r?.validationExamples,a=r?.feedbackExamples,l=(i&&i.length>0?i:t).slice(0,this.paretoSetSize),c=a&&a.length>0?a:t,u=async(I,S)=>{try{e.setInstruction?.(I);let C=await e.forward(this.studentAI,S,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:C,example:S})||{}}catch{return{}}},d=async(I,S)=>{let C=[];for(let M of S)C.push(await u(I,M));return Bo(C)},p=await this.getBaseInstruction(e),m=[{instruction:p,parent:void 0,scores:await d(p,l)}],h=I=>{let S=r?.paretoMetricKey,C=r?.paretoScalarize;if(typeof C=="function")return C(I);if(S)return Number.isFinite(I[S])?I[S]:0;let M=Object.values(I);return M.length?M.reduce((_,D)=>_+D,0)/M.length:0},A=[],g=async(I,S)=>{let C=[];for(let M of S){let _=await u(I,M);C.push(h(_))}return C};A.push(await g(p,l));let f=()=>{let I=A[0]?.length??0,S=[];for(let M=0;M<I;M++){let _=Number.NEGATIVE_INFINITY,D=new Set;for(let z=0;z<A.length;z++){let j=A[z][M];j>_+this.tieEpsilon?(_=j,D.clear(),D.add(z)):Math.abs(j-_)<=this.tieEpsilon&&D.add(z)}S.push(D)}let C=A.map(M=>$t(M));return mr(S,C)};this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let b=0,T=at(m.map((I,S)=>({idx:S,scores:I.scores})),this.tieEpsilon).map(I=>I.idx),E,R=r?.maxMetricCalls;if(!Number.isFinite(R)||R<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let k=Math.floor(R);for(let I=0;I<this.numTrials&&!(k!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(k)));I++){let S=A[0]?.length??0,C=[];for(let N=0;N<S;N++){let U=Number.NEGATIVE_INFINITY,q=new Set;for(let H=0;H<A.length;H++){let J=A[H][N];J>U+this.tieEpsilon?(U=J,q.clear(),q.add(H)):Math.abs(J-U)<=this.tieEpsilon&&q.add(H)}C.push(q)}let M=A.map(N=>$t(N));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let N=L=>{let $=[],G=L;for(;G!==void 0;)$.push(G),G=m[G]?.parent;return $},U=L=>L.length?L[Math.floor(this.rand()*L.length)]:void 0,q=dr(C,M),H=new Set;for(let L of q)for(let $ of L)H.add($);let J=Array.from(H),oe;for(let L=0;L<10&&!oe&&!(J.length<2);L++){let $=U(J),G=U(J);if($===G)continue;G<$&&([$,G]=[G,$]);let ne=new Set(N($)),me=new Set(N(G));if(ne.has(G)||me.has($))continue;let re=[...ne].filter(pe=>me.has(pe));if(re.length===0)continue;let Y=re.map(pe=>Math.max(1e-9,M[pe])),Z=this.rand()*Y.reduce((pe,Ve)=>pe+Ve,0),X=re[re.length-1];for(let pe=0;pe<re.length;pe++){if(Z<Y[pe]){X=re[pe];break}Z-=Y[pe]}oe={i:$,j:G,a:X}}if(this.lastIterFoundNewProgram=!1,oe){let{i:L,j:$,a:G}=oe,ne=M[G],me=M[L],re=M[$],Y=m[G].instruction,Z=m[L].instruction,X=m[$].instruction,pe=Z===Y&&X!==Z||X===Y&&Z!==X,Ve=ne<=Math.min(me,re)&&pe,Ne="",$e="i",ft=!1;if(Ve){let lt=`${L}|${$}|${G}`;if(this.mergeAttemptKeys.has(lt))Ve=!1;else{Z===Y&&X!==Z?(Ne=X,$e="j"):X===Y&&Z!==X?(Ne=Z,$e="i"):Z!==Y&&X!==Y&&Z!==X?me>re||me===re&&this.rand()<.5?(Ne=Z,$e="i"):(Ne=X,$e="j"):(Ne=Z,$e="i");let ce=`${Math.min(L,$)}|${Math.max(L,$)}|${$e}`;if(this.mergeCompositionKeys.has(ce))Ve=!1;else{this.mergeAttemptKeys.add(lt),this.mergeCompositionKeys.add(ce);let Je=A[L],ct=A[$],Ge=Array.from({length:Je.length},(se,Re)=>Re),At=Ge.filter(se=>(Je[se]??0)>(ct[se]??0)),Lt=Ge.filter(se=>(ct[se]??0)>(Je[se]??0)),vt=Ge.filter(se=>!(At.includes(se)||Lt.includes(se))),ut=5,xt=Math.ceil(ut/3),W=(se,Re)=>{if(Re<=0||se.length===0)return[];if(se.length<=Re)return[...se];let On=[],xr=new Set;for(;On.length<Re;){let Ye=Math.floor(this.rand()*se.length);xr.has(Ye)||(xr.add(Ye),On.push(se[Ye]))}return On},ae=[];ae.push(...W(At,Math.min(xt,At.length))),ae.push(...W(Lt,Math.min(xt,Lt.length)));let St=ut-ae.length;ae.push(...W(vt,Math.max(0,St)));let Ot=ut-ae.length;if(Ot>0){let se=Ge.filter(Re=>!ae.includes(Re));ae.push(...W(se,Math.min(Ot,se.length)))}let Ce=ae.slice(0,Math.min(ut,Ge.length)),es=Ce.map(se=>l[se]);ft=!0;let vc=(await g(Ne,es)).reduce((se,Re)=>se+Re,0),Sc=Ce.reduce((se,Re)=>se+(Je[Re]??0),0),Oc=Ce.reduce((se,Re)=>se+(ct[Re]??0),0);if(vc>=Math.max(Sc,Oc)+this.tieEpsilon){let se=await d(Ne,l);m.push({instruction:Ne,parent:G,scores:se}),A.push(await g(Ne,l));let Re=T.length,On=Ke(T.map(Ye=>m[Ye].scores))??0;T=at(m.map((Ye,kc)=>({idx:kc,scores:Ye.scores})),this.tieEpsilon).map(Ye=>Ye.idx);let xr=Ke(T.map(Ye=>m[Ye].scores))??0;(T.length>Re||xr>On+1e-6)&&(b=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(ft)continue}}let _=mr(C,M,()=>this.rand()),D=this.minibatch?this.nextMinibatchIndices(c.length,I).map(N=>c[N]):c;if(r?.skipPerfectScore??!0){let N=Number(r?.perfectScore??1),U=await g(m[_].instruction,D);if(U.length>0&&U.every(q=>q>=N))continue}let z=!1,j=m[_].instruction,Q="reflective_mutation",le,ye;if(z){let N=(_+1)%m.length;j=await this.mergeInstructions(m[_].instruction,m[N].instruction,r),Q="merge",this.mergesUsed+=1}else{let N=r?.gepaAdapter;if(N){try{let U={instruction:m[_].instruction},q=await N.evaluate(D,U,!0);le=Array.isArray(q?.scores)?q.scores.reduce((L,$)=>L+(Number($)||0),0):void 0;let H=N.make_reflective_dataset(U,q,["instruction"]),J=await N.propose_new_texts?.(U,H,["instruction"]),oe=J?.instruction??(J?Object.values(J)[0]:void 0);typeof oe=="string"&&oe.length>0?j=oe:j=await this.reflectInstruction(m[_].instruction,e,D,async({prediction:L,example:$})=>{let G=await n({prediction:L,example:$}),ne=Object.values(G||{});return ne.length?ne.reduce((me,re)=>me+re,0)/ne.length:0},r)}catch{j=await this.reflectInstruction(m[_].instruction,e,D,async({prediction:U,example:q})=>{let H=await n({prediction:U,example:q}),J=Object.values(H||{});return J.length?J.reduce((oe,L)=>oe+L,0)/J.length:0},r)}if(le!==void 0)try{let U=await N.evaluate(D,{instruction:j},!1);ye=Array.isArray(U?.scores)?U.scores.reduce((q,H)=>q+(Number(H)||0),0):void 0}catch{}}else j=await this.reflectInstruction(m[_].instruction,e,D,async({prediction:U,example:q})=>{let H=await n({prediction:U,example:q}),J=Object.values(H||{});return J.length?J.reduce((oe,L)=>oe+L,0)/J.length:0},r)}let _e=await g(m[_].instruction,D),We=await g(j,D),Oe=_e.reduce((N,U)=>N+U,0),ue=We.reduce((N,U)=>N+U,0);if(this.currentRound=I+1,await this.updateOptimizationProgress(this.currentRound,ue,{instructionLen:j.length,parent:_,totalRounds:this.numTrials},"GEPA",{strategy:Q,paretoSetSize:l.length},ue,{instructionLen:m[_].instruction.length,idx:_},{...r??{},maxIterations:this.numTrials}),!(ue>Oe+this.tieEpsilon&&(le===void 0||ye===void 0||ye>le+this.tieEpsilon))){if(++b>=this.earlyStoppingTrials)break;continue}let De=await d(j,l);m.push({instruction:j,parent:_,scores:De}),A.push(await g(j,l));let Le=T.length,gt=Ke(T.map(N=>m[N].scores))??0;T=at(m.map((N,U)=>({idx:U,scores:N.scores})),this.tieEpsilon).map(N=>N.idx);let ht=Ke(T.map(N=>m[N].scores))??0;if(T.length>Le||ht>gt+1e-6)b=0;else if(b++,b>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let y=at(m.map((I,S)=>({idx:S,scores:I.scores})),this.tieEpsilon),O=y.length>0?Math.max(...y.map(I=>h(I.scores))):0,F;if(y.length>0){let I=Number.NEGATIVE_INFINITY;for(let S of y){let C=h(S.scores);C>I&&(I=C,F=S.idx)}}let P=Ke(y.map(I=>I.scores));this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(y.length,m.length,"GEPA",P);let w=Date.now()-o,v=typeof F=="number"?new it({bestScore:O,stats:this.stats,instruction:m[F].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:w,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0;return this.generateOptimizationReport(y,P,O),{demos:[],stats:this.stats,bestScore:O,paretoFront:y.map(I=>({demos:[],scores:I.scores,configuration:{candidate:I.idx},dominatedSolutions:I.dominated})),paretoFrontSize:y.length,hypervolume:P,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:v}}configureAuto(e){switch(e){case"light":this.numTrials=10,this.minibatch=!0,this.minibatchSize=15;break;case"medium":this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numTrials=35,this.minibatch=!0,this.minibatchSize=35;break}}async getBaseInstruction(e){try{let t=e.getSignature?.();if(t&&typeof t.instruction=="string"&&t.instruction.length>0)return t.instruction}catch{}return"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let i of n){let a=await this.evaluateOne(e,t,i,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?$t(o):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let i=await r({prediction:o,example:n});if(typeof i=="number"&&!Number.isNaN(i)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return i>=a&&(this.stats.successfulDemos+=1),i}return 0}catch(o){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(o)}),0}}async reflectInstruction(e,t,n,r,o){let i=[];for(let m of n)try{t.setInstruction?.(e);let h=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let A=await r({prediction:h,example:m});i.push({input:m,prediction:h,score:typeof A=="number"?A:0})}catch{i.push({input:m,prediction:{},score:0})}let a=o?.overrideTeacherAI??this.teacherAI??this.studentAI,l=Ie('minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback per case if available" -> feedbackSummary:string "Concise feedback: common errors, missing constraints, desired changes"'),c=[],u=o?.feedbackFn;if(typeof u=="function")for(let m=0;m<i.length;m++)try{let h=u({prediction:i[m].prediction,example:i[m].input});h&&(Array.isArray(h)?c.push(...h):c.push(h))}catch{}let d="";try{d=(await l.forward(a,{minibatch:i,evalFeedback:c}))?.feedbackSummary?.trim()||"",d&&(this.feedbackMemory.unshift(d),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop())}catch{}let p=Ie('currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", recentFeedback?:string[] "Past feedback memory", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction within 1-6 sentences."');try{let h=(await p.forward(a,{currentInstruction:e,feedbackSummary:d,recentFeedback:this.feedbackMemory,minibatch:i}))?.newInstruction?.trim();if(h&&h.length>16)return h}catch{}return`${e.trim()} Focus on step-by-step evidence-based reasoning. Avoid hallucinations.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,c)=>c);for(let l=t.length-1;l>0;l--){let c=Math.floor(this.rand()*(l+1));[t[l],t[c]]=[t[c],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,i=Array.from({length:e},(l,c)=>c).sort((l,c)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let l=0;l<o;l++){let c=i[l%i.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let i=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(i,i+n)}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}generateOptimizationReport(e,t,n){console.log(`
|
|
318
318
|
\u{1F389} GEPA Multi-Objective Optimization Complete!
|
|
319
319
|
`),console.log("\u2705 Improvements:"),e.length>1?console.log("\u2022 Successfully found multiple Pareto-optimal solutions"):console.log("\u2022 Found at least one optimal solution"),t!==void 0&&t>0&&console.log(`\u2022 Hypervolume improvement: ${(t*100).toFixed(1)}%`),n!==void 0&&console.log(`\u2022 Best score achieved: ${n.toFixed(3)}`),console.log(`\u2022 Multi-objective approach balances competing goals
|
|
320
320
|
`),console.log("\u26A0\uFE0F Limitations:"),e.length===1&&console.log("\u2022 Limited diversity in Pareto frontier"),this.stats.totalCalls<100&&console.log("\u2022 Relatively few optimization trials performed"),console.log("\u2022 Results depend on training data quality and size"),console.log(`\u2022 Optimization time scales with problem complexity
|
|
@@ -322,7 +322,7 @@ ${t}`.trim()}function Ip(s){let e=s.toLowerCase().replace(/[^a-z0-9]+/g,"-").rep
|
|
|
322
322
|
`),console.log("\u{1F4A1} What This Means:"),console.log("\u2022 GEPA framework successfully demonstrates multi-objective optimization"),console.log("\u2022 Pareto frontier reveals real trade-offs between objectives"),console.log("\u2022 Users can select solutions based on their specific priorities"),console.log("\u2022 More training data and trials would likely improve results")}async mergeInstructions(e,t,n){let r=n?.overrideTeacherAI??this.teacherAI??this.studentAI,o=Ie(`instructionA:string "Parent A instruction",
|
|
323
323
|
instructionB:string "Parent B instruction",
|
|
324
324
|
recentFeedback?:string[] "Past feedback memory"
|
|
325
|
-
-> mergedInstruction:string "Merged instruction (1-6 sentences) combining strengths, fixing weaknesses"`);try{let a=(await o.forward(r,{instructionA:e,instructionB:t,recentFeedback:this.feedbackMemory}))?.mergedInstruction?.trim();if(a&&a.length>16)return a}catch{}return(e.length>=t.length?e:t).slice(0,2e3)}};var zo=class extends Fe{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;crossoverEvery;tieEpsilon;paretoSetSize;mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;rngState;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;samplerState={epoch:-1,shuffled:[],freq:new Map};constructor(e){super(e),this.numTrials=e.numTrials??24,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??8,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1,this.crossoverEvery=Math.max(0,Math.floor(e?.crossoverEvery??Math.max(3,Math.floor(this.numTrials/3)))),this.tieEpsilon=Number.isFinite(e?.tieEpsilon)?Number(e?.tieEpsilon):0;let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(o??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}configureAuto(e){switch(e){case"light":this.numTrials=8,this.minibatch=!0,this.minibatchSize=6;break;case"medium":this.numTrials=16,this.minibatch=!0,this.minibatchSize=10;break;case"heavy":this.numTrials=28,this.minibatch=!0,this.minibatchSize=14;break}}async compile(e,t,n,r){let o=Date.now(),i=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=i.getNodePrograms?.();if(!a||a.length===0)throw new Error("AxGEPAFlow: flow has no nodes to optimize");let l=r?.validationExamples,c=r?.feedbackExamples,u=(l&&l.length>0?l:t).slice(0,this.paretoSetSize),d=c&&c.length>0?c:t;this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA-Flow",exampleCount:t.length,validationCount:u.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let m=async(w,v)=>{try{i.setAllNodeInstructions?.(w);let I=await i.forward(this.studentAI,v,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:I,example:v})||{}}catch{return{}}},h=async(w,v)=>{let I=[];for(let S of v)I.push(await m(w,S));return Bo(I)},A={};for(let w of a)A[w.name]=await this.getBaseInstruction(w.program);let g=[{cfg:{...A},parent:void 0,scores:await h(A,u)}],f=w=>{let v=r?.paretoMetricKey,I=r?.paretoScalarize;if(typeof I=="function")return I(w);if(v)return Number.isFinite(w[v])?w[v]:0;let S=Object.values(w);return S.length?S.reduce((C,M)=>C+M,0)/S.length:0},x=[],b=async(w,v)=>{let I=[];for(let S of v){let C=await m(w,S);I.push(f(C))}return I};x.push(await b(A,u));let T=at(g.map((w,v)=>({idx:v,scores:w.scores})),this.tieEpsilon).map(w=>w.idx),E=0,R=new Set,k=r?.maxMetricCalls;if(!Number.isFinite(k)||k<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let y=Math.floor(k);for(let w=0;w<this.numTrials&&!(y!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(y)));w++){let v=x[0]?.length??0,I=[];for(let N=0;N<v;N++){let U=Number.NEGATIVE_INFINITY,q=new Set;for(let H=0;H<x.length;H++){let J=x[H][N];J>U+this.tieEpsilon?(U=J,q.clear(),q.add(H)):Math.abs(J-U)<=this.tieEpsilon&&q.add(H)}I.push(q)}let S=x.map(N=>$t(N));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let N=dr(I,S),U=new Set;for(let L of N)for(let $ of L)U.add($);let q=Array.from(U),H=L=>{let $=[],G=L;for(;G!==void 0;)$.push(G),G=g[G]?.parent;return $},J=L=>L.length?L[Math.floor(this.rand()*L.length)]:void 0,oe;for(let L=0;L<10&&!oe&&!(q.length<2);L++){let $=J(q),G=J(q);if($===G)continue;G<$&&([$,G]=[G,$]);let ne=new Set(H($)),me=new Set(H(G));if(ne.has(G)||me.has($))continue;let re=[...ne].filter(ce=>me.has(ce));if(re.length===0)continue;let Y=[];for(let ce of re){let Je=g[ce].cfg,ct=g[$].cfg,Ge=g[G].cfg,At=!1,Lt=new Set([...Object.keys(Je),...Object.keys(ct),...Object.keys(Ge)]);for(let vt of Lt){let ut=Je[vt],xt=ct[vt],W=Ge[vt];if(xt===ut&&W!==xt||W===ut&&xt!==W){At=!0;break}}At&&Y.push(ce)}if(Y.length===0)continue;let Z=Y.map(ce=>Math.max(1e-9,S[ce])),X=this.rand()*Z.reduce((ce,Je)=>ce+Je,0),pe=Y[Y.length-1];for(let ce=0;ce<Y.length;ce++){if(X<Z[ce]){pe=Y[ce];break}X-=Z[ce]}let Ve=S[pe],Ne=S[$],$e=S[G];if(Ve>Math.min(Ne,$e))continue;let ft=`${$}|${G}|${pe}`;if(this.mergeAttemptKeys.has(ft))continue;this.mergeAttemptKeys.add(ft);let lt=`${$}|${G}|${pe}`;R.has(lt)||(oe={i:$,j:G,a:pe})}if(this.lastIterFoundNewProgram=!1,oe){let{i:L,j:$,a:G}=oe,{cfg:ne,descSig:me}=this.systemAwareMergeWithSig(g,L,$,(W,ae)=>S[W]>=S[ae]?W:ae),re=`${Math.min(L,$)}|${Math.max(L,$)}|${me}`;if(this.mergeCompositionKeys.has(re))continue;this.mergeCompositionKeys.add(re);let Y=x[L],Z=x[$],X=Array.from({length:Y.length},(W,ae)=>ae),pe=X.filter(W=>(Y[W]??0)>(Z[W]??0)),Ve=X.filter(W=>(Z[W]??0)>(Y[W]??0)),Ne=X.filter(W=>!(pe.includes(W)||Ve.includes(W))),$e=5,ft=Math.ceil($e/3),lt=(W,ae)=>{if(ae<=0||W.length===0)return[];if(W.length<=ae)return[...W];let St=[],Ot=new Set;for(;St.length<ae;){let Ce=Math.floor(this.rand()*W.length);Ot.has(Ce)||(Ot.add(Ce),St.push(W[Ce]))}return St},ce=[];ce.push(...lt(pe,Math.min(ft,pe.length))),ce.push(...lt(Ve,Math.min(ft,Ve.length)));let Je=$e-ce.length;ce.push(...lt(Ne,Math.max(0,Je)));let ct=$e-ce.length;if(ct>0){let W=X.filter(ae=>!ce.includes(ae));ce.push(...lt(W,Math.min(ct,W.length)))}let Ge=ce.slice(0,Math.min($e,X.length)),At=Ge.map(W=>u[W]),vt=(await b(ne,At)).reduce((W,ae)=>W+ae,0),ut=Ge.reduce((W,ae)=>W+(Y[ae]??0),0),xt=Ge.reduce((W,ae)=>W+(Z[ae]??0),0);if(vt>=Math.max(ut,xt)+this.tieEpsilon){let W=await h(ne,u);g.push({cfg:ne,parent:G,scores:W}),x.push(await b(ne,u));let ae=T.length,St=Ke(T.map(Ce=>g[Ce].scores))??0;T=at(g.map((Ce,es)=>({idx:es,scores:Ce.scores})),this.tieEpsilon).map(Ce=>Ce.idx);let Ot=Ke(T.map(Ce=>g[Ce].scores))??0;(T.length>ae||Ot>St+1e-6)&&(E=0),this.mergesDue-=1,this.totalMergesTested+=1,R.add(`${Math.min(L,$)}|${Math.max(L,$)}|${G}`)}continue}}let C=mr(I,S,()=>this.rand());this.lastIterFoundNewProgram=!1;let M=this.minibatch?this.nextMinibatchIndices(d.length,w).map(N=>d[N]):d;if(r?.skipPerfectScore??!0){let N=Number(r?.perfectScore??1),U=await b(g[C].cfg,M);if(U.length>0&&U.every(q=>q>=N))continue}let _=!1,D={...g[C].cfg},z="reflective_mutation",j=w%a.length,Q=a[j],le,xe;if(_&&this.mergesUsed<this.mergeMax){let N=(C+1)%g.length,U=L=>{let $=[],G=L;for(;G!==void 0;)$.push(G),G=g[G]?.parent;return $},q=U(C),H=U(N),J=q.find(L=>H.includes(L)),oe=!0;if(J||(oe=!1),(H.includes(C)||q.includes(N))&&(oe=!1),oe){let L=g[J].cfg,$=g[C].cfg,G=g[N].cfg,ne=!1,me=new Set([...Object.keys(L),...Object.keys($),...Object.keys(G)]);for(let re of me){let Y=L[re],Z=$[re],X=G[re];if(Z===Y&&X!==Z||X===Y&&Z!==X){ne=!0;break}}ne||(oe=!1)}if(oe){let L=Math.min(C,N),$=Math.max(C,N),G=`${L}|${$}|${J}`;if(!R.has(G)){let ne=f(g[J].scores),me=f(g[C].scores),re=f(g[N].scores);ne<=Math.min(me,re)&&(D=this.systemAwareMerge(g,C,N,(Y,Z)=>{let X=f(g[Y].scores),pe=f(g[Z].scores);return X>=pe?Y:Z}),z="system_merge",this.mergesUsed+=1,R.add(G))}}else{let L=g[C].cfg[Q.name],$=r?.gepaAdapter,G;if($)try{let ne=await $.evaluate(M,{...g[C].cfg},!0);le=Array.isArray(ne?.scores)?ne.scores.reduce((Z,X)=>Z+(Number(X)||0),0):void 0;let me=$.make_reflective_dataset({...g[C].cfg},ne,[Q.name]),Y=(await $.propose_new_texts?.({...g[C].cfg},me,[Q.name]))?.[Q.name];typeof Y=="string"&&Y.length>0&&(G=Y)}catch{}if(G||(G=await this.reflectModuleInstruction(Q.name,L,i,a,{...g[C].cfg},M,async({prediction:ne,example:me})=>{let re=await n({prediction:ne,example:me}),Y=Object.values(re||{});return Y.length?Y.reduce((Z,X)=>Z+X,0)/Y.length:0},r)),D[Q.name]=G,$&&le!==void 0)try{let ne=await $.evaluate(M,D,!1);xe=Array.isArray(ne?.scores)?ne.scores.reduce((me,re)=>me+(Number(re)||0),0):void 0}catch{}}}else{let N=g[C].cfg[Q.name],U=r?.gepaAdapter,q;if(U)try{let H=await U.evaluate(M,{...g[C].cfg},!0);le=Array.isArray(H?.scores)?H.scores.reduce(($,G)=>$+(Number(G)||0),0):void 0;let J=U.make_reflective_dataset({...g[C].cfg},H,[Q.name]),L=(await U.propose_new_texts?.({...g[C].cfg},J,[Q.name]))?.[Q.name];typeof L=="string"&&L.length>0&&(q=L)}catch{}if(q||(q=await this.reflectModuleInstruction(Q.name,N,i,a,{...g[C].cfg},M,async({prediction:H,example:J})=>{let oe=await n({prediction:H,example:J}),L=Object.values(oe||{});return L.length?L.reduce(($,G)=>$+G,0)/L.length:0},r)),D[Q.name]=q,U&&le!==void 0)try{let H=await U.evaluate(M,D,!1);xe=Array.isArray(H?.scores)?H.scores.reduce((J,oe)=>J+(Number(oe)||0),0):void 0}catch{}}let _e=await b(g[C].cfg,M),We=await b(D,M),Oe=_e.reduce((N,U)=>N+U,0),ue=We.reduce((N,U)=>N+U,0);if(this.currentRound=w+1,await this.updateOptimizationProgress(this.currentRound,ue,{modules:a.length,mutatedModule:Q.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:z,paretoSetSize:u.length},ue,{idx:C},{...r??{},maxIterations:this.numTrials}),!(ue>Oe+this.tieEpsilon&&(le===void 0||xe===void 0||xe>le+this.tieEpsilon))){if(++E>=this.earlyStoppingTrials)break;continue}let De=await h(D,u);g.push({cfg:D,parent:C,scores:De}),x.push(await b(D,u));let Le=T.length,gt=Ke(T.map(N=>g[N].scores))??0;T=at(g.map((N,U)=>({idx:U,scores:N.scores})),this.tieEpsilon).map(N=>N.idx);let ht=Ke(T.map(N=>g[N].scores))??0;if(T.length>Le||ht>gt+1e-6)E=0;else if(E++,E>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let O=at(g.map((w,v)=>({idx:v,scores:w.scores})),this.tieEpsilon),F=O.length>0?Math.max(...O.map(w=>f(w.scores))):0,P=Ke(O.map(w=>w.scores));return this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(O.length,g.length,"GEPA-Flow",P),{demos:[],stats:this.stats,bestScore:F,paretoFront:O.map(w=>({demos:[],scores:w.scores,configuration:{candidate:w.idx},dominatedSolutions:w.dominated})),paretoFrontSize:O.length,hypervolume:P,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:g.length}}}async getBaseInstruction(e){try{let t=e?.getSignature?.();if(t&&typeof t.instruction=="string"&&t.instruction.length>0)return t.instruction}catch{}return"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let i of n){let a=await this.evaluateOne(e,t,i,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?$t(o):0}async evaluateOne(e,t,n,r){try{e.setAllNodeInstructions?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let i=await r({prediction:o,example:n});return typeof i=="number"&&!Number.isNaN(i)?((typeof this.targetScore=="number"?i>=this.targetScore:i>=.5)&&(this.stats.successfulDemos+=1),i):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,o,i,a,l){let c=[],u=[];for(let f of i)try{o[e]=t,n.setAllNodeInstructions?.(o);let x=await n.forward(this.studentAI,f,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let b=await a({prediction:x,example:f});u.push({input:f,prediction:x,score:typeof b=="number"?b:0})}catch{u.push({input:f,prediction:{},score:0})}let d=l?.overrideTeacherAI??this.teacherAI??this.studentAI,p=Ie('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],h=l?.feedbackFn;if(typeof h=="function")for(let f of u){let x=h({prediction:f.prediction,example:f.input});x&&(Array.isArray(x)?m.push(...x):m.push(x))}let A="";try{A=(await p.forward(d,{moduleName:e,minibatch:u,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let g=Ie('moduleName:string "Target module", currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction (1-6 sentences) for the module"');try{let x=(await g.forward(d,{moduleName:e,currentInstruction:t,feedbackSummary:A,minibatch:u}))?.newInstruction?.trim();if(x&&x.length>16)return x}catch{}return`${t.trim()} Focus on step-by-step, module-specific reasoning and factual grounding.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,c)=>c);for(let l=t.length-1;l>0;l--){let c=Math.floor(this.rand()*(l+1));[t[l],t[c]]=[t[c],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,i=Array.from({length:e},(l,c)=>c).sort((l,c)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let l=0;l<o;l++){let c=i[l%i.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let i=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(i,i+n)}systemAwareMergeWithSig(e,t,n,r){let o=g=>{let f=[],x=g;for(;x!==void 0;)f.push(x),x=e[x]?.parent;return f},i=o(t),a=o(n),c=i.find(g=>a.includes(g))??t,u=e[c].cfg,d=e[t].cfg,p=e[n].cfg,m={},h=[],A=Array.from(new Set([...Object.keys(u),...Object.keys(d),...Object.keys(p)])).sort();for(let g of A){let f=u[g],x=d[g],b=p[g];if(x===f&&b!==x)m[g]=b,h.push("j");else if(b===f&&x!==b)m[g]=x,h.push("i");else if(x!==b&&x!==f&&b!==f){let T=r(t,n);m[g]=T===t?x:b,h.push(T===t?"i":"j")}else m[g]=x??b??f,h.push("i")}return{cfg:m,descSig:h.join("|")}}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}systemAwareMerge(e,t,n,r){let o=A=>{let g=[],f=A;for(;f!==void 0;)g.push(f),f=e[f]?.parent;return g},i=o(t),a=o(n),c=i.find(A=>a.includes(A))??t,u=e[c].cfg,d=e[t].cfg,p=e[n].cfg,m={},h=new Set([...Object.keys(u),...Object.keys(d),...Object.keys(p)]);for(let A of h){let g=u[A],f=d[A],x=p[A];if(f===g&&x!==f)m[A]=x;else if(x===g&&f!==x)m[A]=f;else if(f!==x&&f!==g&&x!==g){let b=r(t,n);m[A]=b===t?f:x}else m[A]=f??x??g}return m}};var qo=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 Ho=class extends Fe{maxBootstrappedDemos;maxLabeledDemos;numCandidates;initTemperature;numTrials;minibatch;minibatchSize;minibatchFullEvalSteps;programAwareProposer;dataAwareProposer;viewDataBatchSize;tipAwareProposer;fewshotAwareProposer;earlyStoppingTrials;minImprovementThreshold;bayesianOptimization;acquisitionFunction;explorationWeight;optimizeTopP;sampleCount;pythonClient;localScoreHistory=[];localConfigurationHistory=[];customResultPicker;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??!0,this.acquisitionFunction=e.acquisitionFunction??"expected_improvement",this.explorationWeight=e.explorationWeight??.1,this.optimizeTopP=e.optimizeTopP??!1,this.sampleCount=e.sampleCount??1,this.customResultPicker=e.resultPicker,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 qo(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let o=e.results.findIndex(i=>!i.isError);return o>=0?o:0}let t=new Map;for(let o of e.results){let i=JSON.stringify(o.sample??{}),a=t.get(i);a?a.count+=1:t.set(i,{count:1,firstIndex:o.index})}let n="",r={count:-1,firstIndex:0};for(let[o,i]of t.entries())i.count>r.count&&(r=i,n=o);return t.get(n)?.firstIndex??0};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=`
|
|
325
|
+
-> mergedInstruction:string "Merged instruction (1-6 sentences) combining strengths, fixing weaknesses"`);try{let a=(await o.forward(r,{instructionA:e,instructionB:t,recentFeedback:this.feedbackMemory}))?.mergedInstruction?.trim();if(a&&a.length>16)return a}catch{}return(e.length>=t.length?e:t).slice(0,2e3)}};var zo=class extends Fe{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;crossoverEvery;tieEpsilon;paretoSetSize;mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;rngState;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;samplerState={epoch:-1,shuffled:[],freq:new Map};constructor(e){super(e),this.numTrials=e.numTrials??24,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??8,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1,this.crossoverEvery=Math.max(0,Math.floor(e?.crossoverEvery??Math.max(3,Math.floor(this.numTrials/3)))),this.tieEpsilon=Number.isFinite(e?.tieEpsilon)?Number(e?.tieEpsilon):0;let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(o??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}configureAuto(e){switch(e){case"light":this.numTrials=8,this.minibatch=!0,this.minibatchSize=6;break;case"medium":this.numTrials=16,this.minibatch=!0,this.minibatchSize=10;break;case"heavy":this.numTrials=28,this.minibatch=!0,this.minibatchSize=14;break}}async compile(e,t,n,r){let o=Date.now(),i=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=i.getNodePrograms?.();if(!a||a.length===0)throw new Error("AxGEPAFlow: flow has no nodes to optimize");let l=r?.validationExamples,c=r?.feedbackExamples,u=(l&&l.length>0?l:t).slice(0,this.paretoSetSize),d=c&&c.length>0?c:t;this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA-Flow",exampleCount:t.length,validationCount:u.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let m=async(w,v)=>{try{i.setAllNodeInstructions?.(w);let I=await i.forward(this.studentAI,v,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:I,example:v})||{}}catch{return{}}},h=async(w,v)=>{let I=[];for(let S of v)I.push(await m(w,S));return Bo(I)},A={};for(let w of a)A[w.name]=await this.getBaseInstruction(w.program);let g=[{cfg:{...A},parent:void 0,scores:await h(A,u)}],f=w=>{let v=r?.paretoMetricKey,I=r?.paretoScalarize;if(typeof I=="function")return I(w);if(v)return Number.isFinite(w[v])?w[v]:0;let S=Object.values(w);return S.length?S.reduce((C,M)=>C+M,0)/S.length:0},x=[],b=async(w,v)=>{let I=[];for(let S of v){let C=await m(w,S);I.push(f(C))}return I};x.push(await b(A,u));let T=at(g.map((w,v)=>({idx:v,scores:w.scores})),this.tieEpsilon).map(w=>w.idx),E=0,R=new Set,k=r?.maxMetricCalls;if(!Number.isFinite(k)||k<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let y=Math.floor(k);for(let w=0;w<this.numTrials&&!(y!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(y)));w++){let v=x[0]?.length??0,I=[];for(let N=0;N<v;N++){let U=Number.NEGATIVE_INFINITY,q=new Set;for(let H=0;H<x.length;H++){let J=x[H][N];J>U+this.tieEpsilon?(U=J,q.clear(),q.add(H)):Math.abs(J-U)<=this.tieEpsilon&&q.add(H)}I.push(q)}let S=x.map(N=>$t(N));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let N=dr(I,S),U=new Set;for(let L of N)for(let $ of L)U.add($);let q=Array.from(U),H=L=>{let $=[],G=L;for(;G!==void 0;)$.push(G),G=g[G]?.parent;return $},J=L=>L.length?L[Math.floor(this.rand()*L.length)]:void 0,oe;for(let L=0;L<10&&!oe&&!(q.length<2);L++){let $=J(q),G=J(q);if($===G)continue;G<$&&([$,G]=[G,$]);let ne=new Set(H($)),me=new Set(H(G));if(ne.has(G)||me.has($))continue;let re=[...ne].filter(ce=>me.has(ce));if(re.length===0)continue;let Y=[];for(let ce of re){let Je=g[ce].cfg,ct=g[$].cfg,Ge=g[G].cfg,At=!1,Lt=new Set([...Object.keys(Je),...Object.keys(ct),...Object.keys(Ge)]);for(let vt of Lt){let ut=Je[vt],xt=ct[vt],W=Ge[vt];if(xt===ut&&W!==xt||W===ut&&xt!==W){At=!0;break}}At&&Y.push(ce)}if(Y.length===0)continue;let Z=Y.map(ce=>Math.max(1e-9,S[ce])),X=this.rand()*Z.reduce((ce,Je)=>ce+Je,0),pe=Y[Y.length-1];for(let ce=0;ce<Y.length;ce++){if(X<Z[ce]){pe=Y[ce];break}X-=Z[ce]}let Ve=S[pe],Ne=S[$],$e=S[G];if(Ve>Math.min(Ne,$e))continue;let ft=`${$}|${G}|${pe}`;if(this.mergeAttemptKeys.has(ft))continue;this.mergeAttemptKeys.add(ft);let lt=`${$}|${G}|${pe}`;R.has(lt)||(oe={i:$,j:G,a:pe})}if(this.lastIterFoundNewProgram=!1,oe){let{i:L,j:$,a:G}=oe,{cfg:ne,descSig:me}=this.systemAwareMergeWithSig(g,L,$,(W,ae)=>S[W]>=S[ae]?W:ae),re=`${Math.min(L,$)}|${Math.max(L,$)}|${me}`;if(this.mergeCompositionKeys.has(re))continue;this.mergeCompositionKeys.add(re);let Y=x[L],Z=x[$],X=Array.from({length:Y.length},(W,ae)=>ae),pe=X.filter(W=>(Y[W]??0)>(Z[W]??0)),Ve=X.filter(W=>(Z[W]??0)>(Y[W]??0)),Ne=X.filter(W=>!(pe.includes(W)||Ve.includes(W))),$e=5,ft=Math.ceil($e/3),lt=(W,ae)=>{if(ae<=0||W.length===0)return[];if(W.length<=ae)return[...W];let St=[],Ot=new Set;for(;St.length<ae;){let Ce=Math.floor(this.rand()*W.length);Ot.has(Ce)||(Ot.add(Ce),St.push(W[Ce]))}return St},ce=[];ce.push(...lt(pe,Math.min(ft,pe.length))),ce.push(...lt(Ve,Math.min(ft,Ve.length)));let Je=$e-ce.length;ce.push(...lt(Ne,Math.max(0,Je)));let ct=$e-ce.length;if(ct>0){let W=X.filter(ae=>!ce.includes(ae));ce.push(...lt(W,Math.min(ct,W.length)))}let Ge=ce.slice(0,Math.min($e,X.length)),At=Ge.map(W=>u[W]),vt=(await b(ne,At)).reduce((W,ae)=>W+ae,0),ut=Ge.reduce((W,ae)=>W+(Y[ae]??0),0),xt=Ge.reduce((W,ae)=>W+(Z[ae]??0),0);if(vt>=Math.max(ut,xt)+this.tieEpsilon){let W=await h(ne,u);g.push({cfg:ne,parent:G,scores:W}),x.push(await b(ne,u));let ae=T.length,St=Ke(T.map(Ce=>g[Ce].scores))??0;T=at(g.map((Ce,es)=>({idx:es,scores:Ce.scores})),this.tieEpsilon).map(Ce=>Ce.idx);let Ot=Ke(T.map(Ce=>g[Ce].scores))??0;(T.length>ae||Ot>St+1e-6)&&(E=0),this.mergesDue-=1,this.totalMergesTested+=1,R.add(`${Math.min(L,$)}|${Math.max(L,$)}|${G}`)}continue}}let C=mr(I,S,()=>this.rand());this.lastIterFoundNewProgram=!1;let M=this.minibatch?this.nextMinibatchIndices(d.length,w).map(N=>d[N]):d;if(r?.skipPerfectScore??!0){let N=Number(r?.perfectScore??1),U=await b(g[C].cfg,M);if(U.length>0&&U.every(q=>q>=N))continue}let _=!1,D={...g[C].cfg},z="reflective_mutation",j=w%a.length,Q=a[j],le,ye;if(_&&this.mergesUsed<this.mergeMax){let N=(C+1)%g.length,U=L=>{let $=[],G=L;for(;G!==void 0;)$.push(G),G=g[G]?.parent;return $},q=U(C),H=U(N),J=q.find(L=>H.includes(L)),oe=!0;if(J||(oe=!1),(H.includes(C)||q.includes(N))&&(oe=!1),oe){let L=g[J].cfg,$=g[C].cfg,G=g[N].cfg,ne=!1,me=new Set([...Object.keys(L),...Object.keys($),...Object.keys(G)]);for(let re of me){let Y=L[re],Z=$[re],X=G[re];if(Z===Y&&X!==Z||X===Y&&Z!==X){ne=!0;break}}ne||(oe=!1)}if(oe){let L=Math.min(C,N),$=Math.max(C,N),G=`${L}|${$}|${J}`;if(!R.has(G)){let ne=f(g[J].scores),me=f(g[C].scores),re=f(g[N].scores);ne<=Math.min(me,re)&&(D=this.systemAwareMerge(g,C,N,(Y,Z)=>{let X=f(g[Y].scores),pe=f(g[Z].scores);return X>=pe?Y:Z}),z="system_merge",this.mergesUsed+=1,R.add(G))}}else{let L=g[C].cfg[Q.name],$=r?.gepaAdapter,G;if($)try{let ne=await $.evaluate(M,{...g[C].cfg},!0);le=Array.isArray(ne?.scores)?ne.scores.reduce((Z,X)=>Z+(Number(X)||0),0):void 0;let me=$.make_reflective_dataset({...g[C].cfg},ne,[Q.name]),Y=(await $.propose_new_texts?.({...g[C].cfg},me,[Q.name]))?.[Q.name];typeof Y=="string"&&Y.length>0&&(G=Y)}catch{}if(G||(G=await this.reflectModuleInstruction(Q.name,L,i,a,{...g[C].cfg},M,async({prediction:ne,example:me})=>{let re=await n({prediction:ne,example:me}),Y=Object.values(re||{});return Y.length?Y.reduce((Z,X)=>Z+X,0)/Y.length:0},r)),D[Q.name]=G,$&&le!==void 0)try{let ne=await $.evaluate(M,D,!1);ye=Array.isArray(ne?.scores)?ne.scores.reduce((me,re)=>me+(Number(re)||0),0):void 0}catch{}}}else{let N=g[C].cfg[Q.name],U=r?.gepaAdapter,q;if(U)try{let H=await U.evaluate(M,{...g[C].cfg},!0);le=Array.isArray(H?.scores)?H.scores.reduce(($,G)=>$+(Number(G)||0),0):void 0;let J=U.make_reflective_dataset({...g[C].cfg},H,[Q.name]),L=(await U.propose_new_texts?.({...g[C].cfg},J,[Q.name]))?.[Q.name];typeof L=="string"&&L.length>0&&(q=L)}catch{}if(q||(q=await this.reflectModuleInstruction(Q.name,N,i,a,{...g[C].cfg},M,async({prediction:H,example:J})=>{let oe=await n({prediction:H,example:J}),L=Object.values(oe||{});return L.length?L.reduce(($,G)=>$+G,0)/L.length:0},r)),D[Q.name]=q,U&&le!==void 0)try{let H=await U.evaluate(M,D,!1);ye=Array.isArray(H?.scores)?H.scores.reduce((J,oe)=>J+(Number(oe)||0),0):void 0}catch{}}let _e=await b(g[C].cfg,M),We=await b(D,M),Oe=_e.reduce((N,U)=>N+U,0),ue=We.reduce((N,U)=>N+U,0);if(this.currentRound=w+1,await this.updateOptimizationProgress(this.currentRound,ue,{modules:a.length,mutatedModule:Q.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:z,paretoSetSize:u.length},ue,{idx:C},{...r??{},maxIterations:this.numTrials}),!(ue>Oe+this.tieEpsilon&&(le===void 0||ye===void 0||ye>le+this.tieEpsilon))){if(++E>=this.earlyStoppingTrials)break;continue}let De=await h(D,u);g.push({cfg:D,parent:C,scores:De}),x.push(await b(D,u));let Le=T.length,gt=Ke(T.map(N=>g[N].scores))??0;T=at(g.map((N,U)=>({idx:U,scores:N.scores})),this.tieEpsilon).map(N=>N.idx);let ht=Ke(T.map(N=>g[N].scores))??0;if(T.length>Le||ht>gt+1e-6)E=0;else if(E++,E>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let O=at(g.map((w,v)=>({idx:v,scores:w.scores})),this.tieEpsilon),F=O.length>0?Math.max(...O.map(w=>f(w.scores))):0,P=Ke(O.map(w=>w.scores));return this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(O.length,g.length,"GEPA-Flow",P),{demos:[],stats:this.stats,bestScore:F,paretoFront:O.map(w=>({demos:[],scores:w.scores,configuration:{candidate:w.idx},dominatedSolutions:w.dominated})),paretoFrontSize:O.length,hypervolume:P,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:g.length}}}async getBaseInstruction(e){try{let t=e?.getSignature?.();if(t&&typeof t.instruction=="string"&&t.instruction.length>0)return t.instruction}catch{}return"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let i of n){let a=await this.evaluateOne(e,t,i,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?$t(o):0}async evaluateOne(e,t,n,r){try{e.setAllNodeInstructions?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let i=await r({prediction:o,example:n});return typeof i=="number"&&!Number.isNaN(i)?((typeof this.targetScore=="number"?i>=this.targetScore:i>=.5)&&(this.stats.successfulDemos+=1),i):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,o,i,a,l){let c=[],u=[];for(let f of i)try{o[e]=t,n.setAllNodeInstructions?.(o);let x=await n.forward(this.studentAI,f,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let b=await a({prediction:x,example:f});u.push({input:f,prediction:x,score:typeof b=="number"?b:0})}catch{u.push({input:f,prediction:{},score:0})}let d=l?.overrideTeacherAI??this.teacherAI??this.studentAI,p=Ie('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],h=l?.feedbackFn;if(typeof h=="function")for(let f of u){let x=h({prediction:f.prediction,example:f.input});x&&(Array.isArray(x)?m.push(...x):m.push(x))}let A="";try{A=(await p.forward(d,{moduleName:e,minibatch:u,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let g=Ie('moduleName:string "Target module", currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction (1-6 sentences) for the module"');try{let x=(await g.forward(d,{moduleName:e,currentInstruction:t,feedbackSummary:A,minibatch:u}))?.newInstruction?.trim();if(x&&x.length>16)return x}catch{}return`${t.trim()} Focus on step-by-step, module-specific reasoning and factual grounding.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,c)=>c);for(let l=t.length-1;l>0;l--){let c=Math.floor(this.rand()*(l+1));[t[l],t[c]]=[t[c],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,i=Array.from({length:e},(l,c)=>c).sort((l,c)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let l=0;l<o;l++){let c=i[l%i.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let i=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(i,i+n)}systemAwareMergeWithSig(e,t,n,r){let o=g=>{let f=[],x=g;for(;x!==void 0;)f.push(x),x=e[x]?.parent;return f},i=o(t),a=o(n),c=i.find(g=>a.includes(g))??t,u=e[c].cfg,d=e[t].cfg,p=e[n].cfg,m={},h=[],A=Array.from(new Set([...Object.keys(u),...Object.keys(d),...Object.keys(p)])).sort();for(let g of A){let f=u[g],x=d[g],b=p[g];if(x===f&&b!==x)m[g]=b,h.push("j");else if(b===f&&x!==b)m[g]=x,h.push("i");else if(x!==b&&x!==f&&b!==f){let T=r(t,n);m[g]=T===t?x:b,h.push(T===t?"i":"j")}else m[g]=x??b??f,h.push("i")}return{cfg:m,descSig:h.join("|")}}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}systemAwareMerge(e,t,n,r){let o=A=>{let g=[],f=A;for(;f!==void 0;)g.push(f),f=e[f]?.parent;return g},i=o(t),a=o(n),c=i.find(A=>a.includes(A))??t,u=e[c].cfg,d=e[t].cfg,p=e[n].cfg,m={},h=new Set([...Object.keys(u),...Object.keys(d),...Object.keys(p)]);for(let A of h){let g=u[A],f=d[A],x=p[A];if(f===g&&x!==f)m[A]=x;else if(x===g&&f!==x)m[A]=f;else if(f!==x&&f!==g&&x!==g){let b=r(t,n);m[A]=b===t?f:x}else m[A]=f??x??g}return m}};var qo=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 Ho=class extends Fe{maxBootstrappedDemos;maxLabeledDemos;numCandidates;initTemperature;numTrials;minibatch;minibatchSize;minibatchFullEvalSteps;programAwareProposer;dataAwareProposer;viewDataBatchSize;tipAwareProposer;fewshotAwareProposer;earlyStoppingTrials;minImprovementThreshold;bayesianOptimization;acquisitionFunction;explorationWeight;optimizeTopP;sampleCount;pythonClient;localScoreHistory=[];localConfigurationHistory=[];customResultPicker;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??!0,this.acquisitionFunction=e.acquisitionFunction??"expected_improvement",this.explorationWeight=e.explorationWeight??.1,this.optimizeTopP=e.optimizeTopP??!1,this.sampleCount=e.sampleCount??1,this.customResultPicker=e.resultPicker,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 qo(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let o=e.results.findIndex(i=>!i.isError);return o>=0?o:0}let t=new Map;for(let o of e.results){let i=JSON.stringify(o.sample??{}),a=t.get(i);a?a.count+=1:t.set(i,{count:1,firstIndex:o.index})}let n="",r={count:-1,firstIndex:0};for(let[o,i]of t.entries())i.count>r.count&&(r=i,n=o);return t.get(n)?.firstIndex??0};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=`
|
|
326
326
|
Analyze this language model program and provide a concise summary of its purpose and structure.
|
|
327
327
|
|
|
328
328
|
Program Signature: ${e.getSignature()}
|