@ax-llm/ax 14.0.37 → 14.0.39
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 +68 -66
- package/index.cjs.map +1 -1
- package/index.d.cts +22 -14
- package/index.d.ts +22 -14
- package/index.global.js +66 -64
- package/index.global.js.map +1 -1
- package/index.js +69 -67
- package/index.js.map +1 -1
- package/package.json +2 -2
package/index.global.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use strict";var ax=(()=>{var hc=Object.create;var mr=Object.defineProperty;var fc=Object.getOwnPropertyDescriptor;var Ac=Object.getOwnPropertyNames;var xc=Object.getPrototypeOf,yc=Object.prototype.hasOwnProperty;var bc=(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 gr=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ic=(s,e)=>{for(var t in e)mr(s,t,{get:e[t],enumerable:!0})},mi=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ac(e))!yc.call(s,r)&&r!==t&&mr(s,r,{get:()=>e[r],enumerable:!(n=fc(e,r))||n.enumerable});return s};var Rn=(s,e,t)=>(t=s!=null?hc(xc(s)):{},mi(e||!s||!s.__esModule?mr(t,"default",{value:s,enumerable:!0}):t,s)),Tc=s=>mi(mr({},"__esModule",{value:!0}),s);var cl=gr((Ls,Us)=>{"use strict";(function(s,e){typeof Ls=="object"&&typeof Us<"u"?Us.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs=e()})(Ls,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",p="year",d="date",m="Invalid Date",g=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,f=/\[([^\]]+)]|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,h={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(T){var C=["th","st","nd","rd"],y=T%100;return"["+T+(C[(y-20)%10]||C[y]||C[0])+"]"}},A=function(T,C,y){var O=String(T);return!O||O.length>=C?T:""+Array(C+1-O.length).join(y)+T},x={s:A,z:function(T){var C=-T.utcOffset(),y=Math.abs(C),O=Math.floor(y/60),v=y%60;return(C<=0?"+":"-")+A(O,2,"0")+":"+A(v,2,"0")},m:function T(C,y){if(C.date()<y.date())return-T(y,C);var O=12*(y.year()-C.year())+(y.month()-C.month()),v=C.clone().add(O,c),k=y-v<0,_=C.clone().add(O+(k?-1:1),c);return+(-(O+(y-v)/(k?v-_:_-v))||0)},a:function(T){return T<0?Math.ceil(T)||0:Math.floor(T)},p:function(T){return{M:c,y:p,w:l,d:a,D:d,h:i,m:o,s:r,ms:n,Q:u}[T]||String(T||"").toLowerCase().replace(/s$/,"")},u:function(T){return T===void 0}},b="en",I={};I[b]=h;var M="$isDayjsObject",R=function(T){return T instanceof L||!(!T||!T[M])},w=function T(C,y,O){var v;if(!C)return b;if(typeof C=="string"){var k=C.toLowerCase();I[k]&&(v=k),y&&(I[k]=y,v=k);var _=C.split("-");if(!v&&_.length>1)return T(_[0])}else{var F=C.name;I[F]=C,v=F}return!O&&v&&(b=v),v||!O&&b},S=function(T,C){if(R(T))return T.clone();var y=typeof C=="object"?C:{};return y.date=T,y.args=arguments,new L(y)},E=x;E.l=w,E.i=R,E.w=function(T,C){return S(T,{locale:C.$L,utc:C.$u,x:C.$x,$offset:C.$offset})};var L=function(){function T(y){this.$L=w(y.locale,null,!0),this.parse(y),this.$x=this.$x||y.x||{},this[M]=!0}var C=T.prototype;return C.parse=function(y){this.$d=function(O){var v=O.date,k=O.utc;if(v===null)return new Date(NaN);if(E.u(v))return new Date;if(v instanceof Date)return new Date(v);if(typeof v=="string"&&!/Z$/i.test(v)){var _=v.match(g);if(_){var F=_[2]-1||0,z=(_[7]||"0").substring(0,3);return k?new Date(Date.UTC(_[1],F,_[3]||1,_[4]||0,_[5]||0,_[6]||0,z)):new Date(_[1],F,_[3]||1,_[4]||0,_[5]||0,_[6]||0,z)}}return new Date(v)}(y),this.init()},C.init=function(){var y=this.$d;this.$y=y.getFullYear(),this.$M=y.getMonth(),this.$D=y.getDate(),this.$W=y.getDay(),this.$H=y.getHours(),this.$m=y.getMinutes(),this.$s=y.getSeconds(),this.$ms=y.getMilliseconds()},C.$utils=function(){return E},C.isValid=function(){return this.$d.toString()!==m},C.isSame=function(y,O){var v=S(y);return this.startOf(O)<=v&&v<=this.endOf(O)},C.isAfter=function(y,O){return S(y)<this.startOf(O)},C.isBefore=function(y,O){return this.endOf(O)<S(y)},C.$g=function(y,O,v){return E.u(y)?this[O]:this.set(v,y)},C.unix=function(){return Math.floor(this.valueOf()/1e3)},C.valueOf=function(){return this.$d.getTime()},C.startOf=function(y,O){var v=this,k=!!E.u(O)||O,_=E.p(y),F=function(Se,ue){var Oe=E.w(v.$u?Date.UTC(v.$y,ue,Se):new Date(v.$y,ue,Se),v);return k?Oe:Oe.endOf(a)},z=function(Se,ue){return E.w(v.toDate()[Se].apply(v.toDate("s"),(k?[0,0,0,0]:[23,59,59,999]).slice(ue)),v)},q=this.$W,Q=this.$M,ae=this.$D,xe="set"+(this.$u?"UTC":"");switch(_){case p:return k?F(1,0):F(31,11);case c:return k?F(1,Q):F(0,Q+1);case l:var Fe=this.$locale().weekStart||0,je=(q<Fe?q+7:q)-Fe;return F(k?ae-je:ae+(6-je),Q);case a:case d: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()}},C.endOf=function(y){return this.startOf(y,!1)},C.$set=function(y,O){var v,k=E.p(y),_="set"+(this.$u?"UTC":""),F=(v={},v[a]=_+"Date",v[d]=_+"Date",v[c]=_+"Month",v[p]=_+"FullYear",v[i]=_+"Hours",v[o]=_+"Minutes",v[r]=_+"Seconds",v[n]=_+"Milliseconds",v)[k],z=k===a?this.$D+(O-this.$W):O;if(k===c||k===p){var q=this.clone().set(d,1);q.$d[F](z),q.init(),this.$d=q.set(d,Math.min(this.$D,q.daysInMonth())).$d}else F&&this.$d[F](z);return this.init(),this},C.set=function(y,O){return this.clone().$set(y,O)},C.get=function(y){return this[E.p(y)]()},C.add=function(y,O){var v,k=this;y=Number(y);var _=E.p(O),F=function(Q){var ae=S(k);return E.w(ae.date(ae.date()+Math.round(Q*y)),k)};if(_===c)return this.set(c,this.$M+y);if(_===p)return this.set(p,this.$y+y);if(_===a)return F(1);if(_===l)return F(7);var z=(v={},v[o]=e,v[i]=t,v[r]=s,v)[_]||1,q=this.$d.getTime()+y*z;return E.w(q,this)},C.subtract=function(y,O){return this.add(-1*y,O)},C.format=function(y){var O=this,v=this.$locale();if(!this.isValid())return v.invalidDate||m;var k=y||"YYYY-MM-DDTHH:mm:ssZ",_=E.z(this),F=this.$H,z=this.$m,q=this.$M,Q=v.weekdays,ae=v.months,xe=v.meridiem,Fe=function(ue,Oe,De,Ge){return ue&&(ue[Oe]||ue(O,k))||De[Oe].slice(0,Ge)},je=function(ue){return E.s(F%12||12,ue,"0")},Se=xe||function(ue,Oe,De){var Ge=ue<12?"AM":"PM";return De?Ge.toLowerCase():Ge};return k.replace(f,function(ue,Oe){return Oe||function(De){switch(De){case"YY":return String(O.$y).slice(-2);case"YYYY":return E.s(O.$y,4,"0");case"M":return q+1;case"MM":return E.s(q+1,2,"0");case"MMM":return Fe(v.monthsShort,q,ae,3);case"MMMM":return Fe(ae,q);case"D":return O.$D;case"DD":return E.s(O.$D,2,"0");case"d":return String(O.$W);case"dd":return Fe(v.weekdaysMin,O.$W,Q,2);case"ddd":return Fe(v.weekdaysShort,O.$W,Q,3);case"dddd":return Q[O.$W];case"H":return String(F);case"HH":return E.s(F,2,"0");case"h":return je(1);case"hh":return je(2);case"a":return Se(F,z,!0);case"A":return Se(F,z,!1);case"m":return String(z);case"mm":return E.s(z,2,"0");case"s":return String(O.$s);case"ss":return E.s(O.$s,2,"0");case"SSS":return E.s(O.$ms,3,"0");case"Z":return _}return null}(ue)||_.replace(":","")})},C.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},C.diff=function(y,O,v){var k,_=this,F=E.p(O),z=S(y),q=(z.utcOffset()-this.utcOffset())*e,Q=this-z,ae=function(){return E.m(_,z)};switch(F){case p:k=ae()/12;break;case c:k=ae();break;case u:k=ae()/3;break;case l:k=(Q-q)/6048e5;break;case a:k=(Q-q)/864e5;break;case i:k=Q/t;break;case o:k=Q/e;break;case r:k=Q/s;break;default:k=Q}return v?k:E.a(k)},C.daysInMonth=function(){return this.endOf(c).$D},C.$locale=function(){return I[this.$L]},C.locale=function(y,O){if(!y)return this.$L;var v=this.clone(),k=w(y,O,!0);return k&&(v.$L=k),v},C.clone=function(){return E.w(this.$d,this)},C.toDate=function(){return new Date(this.valueOf())},C.toJSON=function(){return this.isValid()?this.toISOString():null},C.toISOString=function(){return this.$d.toISOString()},C.toString=function(){return this.$d.toUTCString()},T}(),P=L.prototype;return S.prototype=P,[["$ms",n],["$s",r],["$m",o],["$H",i],["$W",a],["$M",c],["$y",p],["$D",d]].forEach(function(T){P[T[1]]=function(C){return this.$g(C,T[0],T[1])}}),S.extend=function(T,C){return T.$i||(T(C,L,S),T.$i=!0),S},S.locale=w,S.isDayjs=R,S.unix=function(T){return S(1e3*T)},S.en=I[b],S.Ls=I,S.p={},S})});var ul=gr((Bs,qs)=>{"use strict";(function(s,e){typeof Bs=="object"&&typeof qs<"u"?qs.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_customParseFormat=e()})(Bs,function(){"use strict";var s={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},e=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,t=/\d/,n=/\d\d/,r=/\d\d?/,o=/\d*[^-_:/,()\s\d]+/,i={},a=function(g){return(g=+g)+(g>68?1900:2e3)},l=function(g){return function(f){this[g]=+f}},c=[/[+-]\d\d:?(\d\d)?|Z/,function(g){(this.zone||(this.zone={})).offset=function(f){if(!f||f==="Z")return 0;var h=f.match(/([+-]|\d\d)/g),A=60*h[1]+(+h[2]||0);return A===0?0:h[0]==="+"?-A:A}(g)}],u=function(g){var f=i[g];return f&&(f.indexOf?f:f.s.concat(f.f))},p=function(g,f){var h,A=i.meridiem;if(A){for(var x=1;x<=24;x+=1)if(g.indexOf(A(x,0,f))>-1){h=x>12;break}}else h=g===(f?"pm":"PM");return h},d={A:[o,function(g){this.afternoon=p(g,!1)}],a:[o,function(g){this.afternoon=p(g,!0)}],Q:[t,function(g){this.month=3*(g-1)+1}],S:[t,function(g){this.milliseconds=100*+g}],SS:[n,function(g){this.milliseconds=10*+g}],SSS:[/\d{3}/,function(g){this.milliseconds=+g}],s:[r,l("seconds")],ss:[r,l("seconds")],m:[r,l("minutes")],mm:[r,l("minutes")],H:[r,l("hours")],h:[r,l("hours")],HH:[r,l("hours")],hh:[r,l("hours")],D:[r,l("day")],DD:[n,l("day")],Do:[o,function(g){var f=i.ordinal,h=g.match(/\d+/);if(this.day=h[0],f)for(var A=1;A<=31;A+=1)f(A).replace(/\[|\]/g,"")===g&&(this.day=A)}],w:[r,l("week")],ww:[n,l("week")],M:[r,l("month")],MM:[n,l("month")],MMM:[o,function(g){var f=u("months"),h=(u("monthsShort")||f.map(function(A){return A.slice(0,3)})).indexOf(g)+1;if(h<1)throw new Error;this.month=h%12||h}],MMMM:[o,function(g){var f=u("months").indexOf(g)+1;if(f<1)throw new Error;this.month=f%12||f}],Y:[/[+-]?\d+/,l("year")],YY:[n,function(g){this.year=a(g)}],YYYY:[/\d{4}/,l("year")],Z:c,ZZ:c};function m(g){var f,h;f=g,h=i&&i.formats;for(var A=(g=f.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(S,E,L){var P=L&&L.toUpperCase();return E||h[L]||s[L]||h[P].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(T,C,y){return C||y.slice(1)})})).match(e),x=A.length,b=0;b<x;b+=1){var I=A[b],M=d[I],R=M&&M[0],w=M&&M[1];A[b]=w?{regex:R,parser:w}:I.replace(/^\[|\]$/g,"")}return function(S){for(var E={},L=0,P=0;L<x;L+=1){var T=A[L];if(typeof T=="string")P+=T.length;else{var C=T.regex,y=T.parser,O=S.slice(P),v=C.exec(O)[0];y.call(E,v),S=S.replace(v,"")}}return function(k){var _=k.afternoon;if(_!==void 0){var F=k.hours;_?F<12&&(k.hours+=12):F===12&&(k.hours=0),delete k.afternoon}}(E),E}}return function(g,f,h){h.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var A=f.prototype,x=A.parse;A.parse=function(b){var I=b.date,M=b.utc,R=b.args;this.$u=M;var w=R[1];if(typeof w=="string"){var S=R[2]===!0,E=R[3]===!0,L=S||E,P=R[2];E&&(P=R[2]),i=this.$locale(),!S&&P&&(i=h.Ls[P]),this.$d=function(O,v,k,_){try{if(["x","X"].indexOf(v)>-1)return new Date((v==="X"?1e3:1)*O);var F=m(v)(O),z=F.year,q=F.month,Q=F.day,ae=F.hours,xe=F.minutes,Fe=F.seconds,je=F.milliseconds,Se=F.zone,ue=F.week,Oe=new Date,De=Q||(z||q?1:Oe.getDate()),Ge=z||Oe.getFullYear(),pt=0;z&&!q||(pt=q>0?q-1:Oe.getMonth());var dt,D=ae||0,U=xe||0,j=Fe||0,H=je||0;return Se?new Date(Date.UTC(Ge,pt,De,D,U,j,H+60*Se.offset*1e3)):k?new Date(Date.UTC(Ge,pt,De,D,U,j,H)):(dt=new Date(Ge,pt,De,D,U,j,H),ue&&(dt=_(dt).week(ue).toDate()),dt)}catch{return new Date("")}}(I,w,M,h),this.init(),P&&P!==!0&&(this.$L=this.locale(P).$L),L&&I!=this.format(w)&&(this.$d=new Date("")),i={}}else if(w instanceof Array)for(var T=w.length,C=1;C<=T;C+=1){R[1]=w[C-1];var y=h.apply(this,R);if(y.isValid()){this.$d=y.$d,this.$L=y.$L,this.init();break}C===T&&(this.$d=new Date(""))}else x.call(this,b)}}})});var pl=gr((zs,js)=>{"use strict";(function(s,e){typeof zs=="object"&&typeof js<"u"?js.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_timezone=e()})(zs,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,p,d){d===void 0&&(d={});var m=new Date(u),g=function(f,h){h===void 0&&(h={});var A=h.timeZoneName||"short",x=f+"|"+A,b=e[x];return b||(b=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:f,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:A}),e[x]=b),b}(p,d);return g.formatToParts(m)},a=function(u,p){for(var d=i(u,p),m=[],g=0;g<d.length;g+=1){var f=d[g],h=f.type,A=f.value,x=s[h];x>=0&&(m[x]=parseInt(A,10))}var b=m[3],I=b===24?0:b,M=m[0]+"-"+m[1]+"-"+m[2]+" "+I+":"+m[4]+":"+m[5]+":000",R=+u;return(r.utc(M).valueOf()-(R-=R%1e3))/6e4},l=n.prototype;l.tz=function(u,p){u===void 0&&(u=o);var d,m=this.utcOffset(),g=this.toDate(),f=g.toLocaleString("en-US",{timeZone:u}),h=Math.round((g-new Date(f))/1e3/60),A=15*-Math.round(g.getTimezoneOffset()/15)-h;if(!Number(A))d=this.utcOffset(0,p);else if(d=r(f,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(A,!0),p){var x=d.utcOffset();d=d.add(m-x,"minute")}return d.$x.$timezone=u,d},l.offsetName=function(u){var p=this.$x.$timezone||r.tz.guess(),d=i(this.valueOf(),p,{timeZoneName:u}).find(function(m){return m.type.toLowerCase()==="timezonename"});return d&&d.value};var c=l.startOf;l.startOf=function(u,p){if(!this.$x||!this.$x.$timezone)return c.call(this,u,p);var d=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"),{locale:this.$L});return c.call(d,u,p).tz(this.$x.$timezone,!0)},r.tz=function(u,p,d){var m=d&&p,g=d||p||o,f=a(+r(),g);if(typeof u!="string")return r(u).tz(g);var h=function(I,M,R){var w=I-60*M*1e3,S=a(w,R);if(M===S)return[w,M];var E=a(w-=60*(S-M)*1e3,R);return S===E?[w,S]:[I-60*Math.min(S,E)*1e3,Math.max(S,E)]}(r.utc(u,m).valueOf(),f,g),A=h[0],x=h[1],b=r(A).utcOffset(x);return b.$x.$timezone=g,b},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(u){o=u}}})});var dl=gr((Hs,Ks)=>{"use strict";(function(s,e){typeof Hs=="object"&&typeof Ks<"u"?Ks.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_utc=e()})(Hs,function(){"use strict";var s="minute",e=/[+-]\d\d(?::?\d\d)?/g,t=/([+-]|\d\d)/g;return function(n,r,o){var i=r.prototype;o.utc=function(m){var g={date:m,utc:!0,args:arguments};return new r(g)},i.utc=function(m){var g=o(this.toDate(),{locale:this.$L,utc:!0});return m?g.add(this.utcOffset(),s):g},i.local=function(){return o(this.toDate(),{locale:this.$L,utc:!1})};var a=i.parse;i.parse=function(m){m.utc&&(this.$u=!0),this.$utils().u(m.$offset)||(this.$offset=m.$offset),a.call(this,m)};var l=i.init;i.init=function(){if(this.$u){var m=this.$d;this.$y=m.getUTCFullYear(),this.$M=m.getUTCMonth(),this.$D=m.getUTCDate(),this.$W=m.getUTCDay(),this.$H=m.getUTCHours(),this.$m=m.getUTCMinutes(),this.$s=m.getUTCSeconds(),this.$ms=m.getUTCMilliseconds()}else l.call(this)};var c=i.utcOffset;i.utcOffset=function(m,g){var f=this.$utils().u;if(f(m))return this.$u?0:f(this.$offset)?c.call(this):this.$offset;if(typeof m=="string"&&(m=function(b){b===void 0&&(b="");var I=b.match(e);if(!I)return null;var M=(""+I[0]).match(t)||["-",0,0],R=M[0],w=60*+M[1]+ +M[2];return w===0?0:R==="+"?w:-w}(m),m===null))return this;var h=Math.abs(m)<=16?60*m:m,A=this;if(g)return A.$offset=h,A.$u=m===0,A;if(m!==0){var x=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(A=this.local().add(h+x,s)).$offset=h,A.$x.$localOffset=x}else A=this.utc();return A};var u=i.format;i.format=function(m){var g=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return u.call(this,g)},i.valueOf=function(){var m=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*m},i.isUTC=function(){return!!this.$u},i.toISOString=function(){return this.toDate().toISOString()},i.toString=function(){return this.toDate().toUTCString()};var p=i.toDate;i.toDate=function(m){return m==="s"&&this.$offset?o(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():p.call(this)};var d=i.diff;i.diff=function(m,g,f){if(m&&this.$u===m.$u)return d.call(this,m,g,f);var h=this.local(),A=o(m).local();return d.call(h,A,g,f)}}})});var gp={};Ic(gp,{AxACE:()=>Oo,AxACEOptimizedProgram:()=>sr,AxAI:()=>Kn,AxAIAnthropic:()=>Bt,AxAIAnthropicModel:()=>En,AxAIAnthropicVertexModel:()=>Sr,AxAIAzureOpenAI:()=>Kt,AxAICohere:()=>Wt,AxAICohereEmbedModel:()=>Dn,AxAICohereModel:()=>Fn,AxAIDeepSeek:()=>Vt,AxAIDeepSeekModel:()=>Nn,AxAIGoogleGemini:()=>Jt,AxAIGoogleGeminiEmbedModel:()=>Gr,AxAIGoogleGeminiEmbedTypes:()=>fs,AxAIGoogleGeminiModel:()=>$n,AxAIGoogleGeminiSafetyCategory:()=>Lr,AxAIGoogleGeminiSafetyThreshold:()=>Ur,AxAIGrok:()=>ln,AxAIGrokEmbedModels:()=>Ms,AxAIGrokModel:()=>Hn,AxAIGroq:()=>Qt,AxAIGroqModel:()=>Gn,AxAIHuggingFace:()=>Zt,AxAIHuggingFaceModel:()=>jr,AxAIMistral:()=>Xt,AxAIMistralEmbedModels:()=>Ts,AxAIMistralModel:()=>Ln,AxAIOllama:()=>en,AxAIOpenAI:()=>Ht,AxAIOpenAIBase:()=>he,AxAIOpenAIEmbedModel:()=>qt,AxAIOpenAIModel:()=>_n,AxAIOpenAIResponses:()=>nn,AxAIOpenAIResponsesBase:()=>Un,AxAIOpenAIResponsesImpl:()=>tn,AxAIOpenAIResponsesModel:()=>zt,AxAIOpenRouter:()=>rn,AxAIRefusalError:()=>de,AxAIReka:()=>on,AxAIRekaModel:()=>qn,AxAIServiceAbortedError:()=>Dt,AxAIServiceAuthenticationError:()=>ft,AxAIServiceError:()=>Re,AxAIServiceNetworkError:()=>et,AxAIServiceResponseError:()=>lt,AxAIServiceStatusError:()=>wt,AxAIServiceStreamTerminatedError:()=>Ve,AxAIServiceTimeoutError:()=>vt,AxAITogether:()=>sn,AxAIWebLLM:()=>an,AxAIWebLLMModel:()=>jn,AxAgent:()=>pr,AxApacheTika:()=>Io,AxAssertionError:()=>tt,AxBalancer:()=>_r,AxBaseAI:()=>fe,AxBaseOptimizer:()=>_e,AxBootstrapFewShot:()=>hn,AxContentProcessingError:()=>Je,AxDB:()=>ro,AxDBBase:()=>qe,AxDBCloudflare:()=>cn,AxDBManager:()=>oo,AxDBMemory:()=>yt,AxDBPinecone:()=>un,AxDBWeaviate:()=>pn,AxDefaultCostTracker:()=>rr,AxDefaultResultReranker:()=>bo,AxDockerSession:()=>No,AxEmbeddingAdapter:()=>$o,AxEvalUtil:()=>Bl,AxFlow:()=>cr,AxFlowDependencyAnalyzer:()=>fn,AxFlowExecutionPlanner:()=>xn,AxFlowSubContextImpl:()=>In,AxFlowTypedSubContextImpl:()=>Fo,AxFluentFieldType:()=>Ie,AxFunctionError:()=>Jn,AxFunctionProcessor:()=>Qn,AxGEPA:()=>Mo,AxGEPAFlow:()=>Eo,AxGen:()=>Pe,AxGenerateError:()=>tr,AxHFDataLoader:()=>wo,AxInstanceRegistry:()=>gn,AxLLMRequestTypeValues:()=>es,AxMCPClient:()=>Go,AxMCPHTTPSSETransport:()=>Bo,AxMCPStreambleHTTPTransport:()=>Uo,AxMediaNotSupportedError:()=>Be,AxMemory:()=>dn,AxMiPRO:()=>_o,AxMockAIService:()=>Wr,AxMultiServiceRouter:()=>Vr,AxOptimizedProgramImpl:()=>rt,AxProgram:()=>It,AxPromptTemplate:()=>Mt,AxProviderRouter:()=>Zr,AxRateLimiterTokenUsage:()=>Yt,AxSignature:()=>ge,AxSignatureBuilder:()=>Xn,AxSimpleClassifier:()=>Co,AxSimpleClassifierClass:()=>To,AxSpanKindValues:()=>ts,AxStopFunctionCallException:()=>kt,AxStringUtil:()=>yo,AxTestPrompt:()=>Ro,agent:()=>cc,ai:()=>Ua,ax:()=>ye,axAIAnthropicDefaultConfig:()=>cs,axAIAnthropicVertexDefaultConfig:()=>ha,axAIAzureOpenAIBestConfig:()=>ya,axAIAzureOpenAICreativeConfig:()=>Aa,axAIAzureOpenAIDefaultConfig:()=>ps,axAIAzureOpenAIFastConfig:()=>xa,axAICohereCreativeConfig:()=>Ra,axAICohereDefaultConfig:()=>gs,axAIDeepSeekCodeConfig:()=>wa,axAIDeepSeekDefaultConfig:()=>hs,axAIGoogleGeminiDefaultConfig:()=>ys,axAIGoogleGeminiDefaultCreativeConfig:()=>Sa,axAIGrokBestConfig:()=>La,axAIGrokDefaultConfig:()=>no,axAIHuggingFaceCreativeConfig:()=>Oa,axAIHuggingFaceDefaultConfig:()=>Is,axAIMistralBestConfig:()=>ka,axAIMistralDefaultConfig:()=>Kr,axAIOllamaDefaultConfig:()=>Cs,axAIOllamaDefaultCreativeConfig:()=>Ma,axAIOpenAIBestConfig:()=>Mr,axAIOpenAICreativeConfig:()=>Er,axAIOpenAIDefaultConfig:()=>St,axAIOpenAIFastConfig:()=>Pr,axAIOpenAIResponsesBestConfig:()=>Ea,axAIOpenAIResponsesCreativeConfig:()=>Pa,axAIOpenAIResponsesDefaultConfig:()=>Bn,axAIOpenRouterDefaultConfig:()=>ws,axAIRekaBestConfig:()=>Da,axAIRekaCreativeConfig:()=>Na,axAIRekaDefaultConfig:()=>zn,axAIRekaFastConfig:()=>$a,axAITogetherDefaultConfig:()=>Ss,axAIWebLLMCreativeConfig:()=>Ga,axAIWebLLMDefaultConfig:()=>ks,axAnalyzeChatPromptRequirements:()=>_a,axAnalyzeRequestRequirements:()=>Ot,axBaseAIDefaultConfig:()=>ee,axBaseAIDefaultCreativeConfig:()=>Ae,axCheckMetricsHealth:()=>Ba,axCreateDefaultColorLogger:()=>Xo,axCreateDefaultOptimizerColorLogger:()=>si,axCreateDefaultOptimizerTextLogger:()=>zl,axCreateDefaultTextLogger:()=>Gi,axCreateFlowColorLogger:()=>lr,axCreateFlowTextLogger:()=>Yl,axDefaultFlowLogger:()=>Ql,axDefaultMetricsConfig:()=>Fs,axDefaultOptimizerLogger:()=>nr,axDefaultOptimizerMetricsConfig:()=>ii,axGetCompatibilityReport:()=>ba,axGetFormatCompatibility:()=>Ta,axGetMetricsConfig:()=>za,axGetOptimizerMetricsConfig:()=>Hl,axGetProvidersWithMediaSupport:()=>Ia,axGlobals:()=>ce,axModelInfoAnthropic:()=>Pn,axModelInfoCohere:()=>Nr,axModelInfoDeepSeek:()=>$r,axModelInfoGoogleGemini:()=>Br,axModelInfoGrok:()=>to,axModelInfoGroq:()=>qr,axModelInfoHuggingFace:()=>zr,axModelInfoMistral:()=>Hr,axModelInfoOpenAI:()=>jt,axModelInfoOpenAIResponses:()=>kr,axModelInfoReka:()=>Qr,axModelInfoTogether:()=>Xr,axModelInfoWebLLM:()=>eo,axProcessContentForProvider:()=>Yr,axRAG:()=>uc,axScoreProvidersForRequest:()=>Fr,axSelectOptimalProvider:()=>Dr,axSpanAttributes:()=>V,axSpanEvents:()=>Ye,axUpdateMetricsConfig:()=>qa,axUpdateOptimizerMetricsConfig:()=>jl,axValidateChatRequestMessage:()=>Ut,axValidateChatResponseResult:()=>vr,axValidateProviderCapabilities:()=>ds,f:()=>se,flow:()=>Do,s:()=>Kl});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 jo=(()=>{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 be(){return jo.randomUUID()}async function Cc(s){let e=new TextEncoder,t=typeof s=="string"?e.encode(s):s,n=await jo.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var zo=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 Cc(this.data)}};function hr(s){if(s!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new zo}function gi(){return jo}var fr=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 fc=Object.create;var gr=Object.defineProperty;var hc=Object.getOwnPropertyDescriptor;var Ac=Object.getOwnPropertyNames;var xc=Object.getPrototypeOf,yc=Object.prototype.hasOwnProperty;var bc=(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 fr=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ic=(s,e)=>{for(var t in e)gr(s,t,{get:e[t],enumerable:!0})},mi=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ac(e))!yc.call(s,r)&&r!==t&&gr(s,r,{get:()=>e[r],enumerable:!(n=hc(e,r))||n.enumerable});return s};var wn=(s,e,t)=>(t=s!=null?fc(xc(s)):{},mi(e||!s||!s.__esModule?gr(t,"default",{value:s,enumerable:!0}):t,s)),Tc=s=>mi(gr({},"__esModule",{value:!0}),s);var cl=fr((Ls,Us)=>{"use strict";(function(s,e){typeof Ls=="object"&&typeof Us<"u"?Us.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs=e()})(Ls,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",g=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,f={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(R){var w=["th","st","nd","rd"],b=R%100;return"["+R+(w[(b-20)%10]||w[b]||w[0])+"]"}},A=function(R,w,b){var O=String(R);return!O||O.length>=w?R:""+Array(w+1-O.length).join(b)+R},x={s:A,z:function(R){var w=-R.utcOffset(),b=Math.abs(w),O=Math.floor(b/60),S=b%60;return(w<=0?"+":"-")+A(O,2,"0")+":"+A(S,2,"0")},m:function R(w,b){if(w.date()<b.date())return-R(b,w);var O=12*(b.year()-w.year())+(b.month()-w.month()),S=w.clone().add(O,c),M=b-S<0,_=w.clone().add(O+(M?-1:1),c);return+(-(O+(b-S)/(M?S-_:_-S))||0)},a:function(R){return R<0?Math.ceil(R)||0:Math.floor(R)},p:function(R){return{M:c,y:d,w:l,d:a,D:p,h:i,m:o,s:r,ms:n,Q:u}[R]||String(R||"").toLowerCase().replace(/s$/,"")},u:function(R){return R===void 0}},y="en",I={};I[y]=f;var E="$isDayjsObject",C=function(R){return R instanceof L||!(!R||!R[E])},T=function R(w,b,O){var S;if(!w)return y;if(typeof w=="string"){var M=w.toLowerCase();I[M]&&(S=M),b&&(I[M]=b,S=M);var _=w.split("-");if(!S&&_.length>1)return R(_[0])}else{var F=w.name;I[F]=w,S=F}return!O&&S&&(y=S),S||!O&&y},v=function(R,w){if(C(R))return R.clone();var b=typeof w=="object"?w:{};return b.date=R,b.args=arguments,new L(b)},k=x;k.l=T,k.i=C,k.w=function(R,w){return v(R,{locale:w.$L,utc:w.$u,x:w.$x,$offset:w.$offset})};var L=function(){function R(b){this.$L=T(b.locale,null,!0),this.parse(b),this.$x=this.$x||b.x||{},this[E]=!0}var w=R.prototype;return w.parse=function(b){this.$d=function(O){var S=O.date,M=O.utc;if(S===null)return new Date(NaN);if(k.u(S))return new Date;if(S instanceof Date)return new Date(S);if(typeof S=="string"&&!/Z$/i.test(S)){var _=S.match(g);if(_){var F=_[2]-1||0,z=(_[7]||"0").substring(0,3);return M?new Date(Date.UTC(_[1],F,_[3]||1,_[4]||0,_[5]||0,_[6]||0,z)):new Date(_[1],F,_[3]||1,_[4]||0,_[5]||0,_[6]||0,z)}}return new Date(S)}(b),this.init()},w.init=function(){var b=this.$d;this.$y=b.getFullYear(),this.$M=b.getMonth(),this.$D=b.getDate(),this.$W=b.getDay(),this.$H=b.getHours(),this.$m=b.getMinutes(),this.$s=b.getSeconds(),this.$ms=b.getMilliseconds()},w.$utils=function(){return k},w.isValid=function(){return this.$d.toString()!==m},w.isSame=function(b,O){var S=v(b);return this.startOf(O)<=S&&S<=this.endOf(O)},w.isAfter=function(b,O){return v(b)<this.startOf(O)},w.isBefore=function(b,O){return this.endOf(O)<v(b)},w.$g=function(b,O,S){return k.u(b)?this[O]:this.set(S,b)},w.unix=function(){return Math.floor(this.valueOf()/1e3)},w.valueOf=function(){return this.$d.getTime()},w.startOf=function(b,O){var S=this,M=!!k.u(O)||O,_=k.p(b),F=function(Se,ue){var Oe=k.w(S.$u?Date.UTC(S.$y,ue,Se):new Date(S.$y,ue,Se),S);return M?Oe:Oe.endOf(a)},z=function(Se,ue){return k.w(S.toDate()[Se].apply(S.toDate("s"),(M?[0,0,0,0]:[23,59,59,999]).slice(ue)),S)},q=this.$W,Q=this.$M,le=this.$D,xe="set"+(this.$u?"UTC":"");switch(_){case d:return M?F(1,0):F(31,11);case c:return M?F(1,Q):F(0,Q+1);case l:var Fe=this.$locale().weekStart||0,He=(q<Fe?q+7:q)-Fe;return F(M?le-He:le+(6-He),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()}},w.endOf=function(b){return this.startOf(b,!1)},w.$set=function(b,O){var S,M=k.p(b),_="set"+(this.$u?"UTC":""),F=(S={},S[a]=_+"Date",S[p]=_+"Date",S[c]=_+"Month",S[d]=_+"FullYear",S[i]=_+"Hours",S[o]=_+"Minutes",S[r]=_+"Seconds",S[n]=_+"Milliseconds",S)[M],z=M===a?this.$D+(O-this.$W):O;if(M===c||M===d){var q=this.clone().set(p,1);q.$d[F](z),q.init(),this.$d=q.set(p,Math.min(this.$D,q.daysInMonth())).$d}else F&&this.$d[F](z);return this.init(),this},w.set=function(b,O){return this.clone().$set(b,O)},w.get=function(b){return this[k.p(b)]()},w.add=function(b,O){var S,M=this;b=Number(b);var _=k.p(O),F=function(Q){var le=v(M);return k.w(le.date(le.date()+Math.round(Q*b)),M)};if(_===c)return this.set(c,this.$M+b);if(_===d)return this.set(d,this.$y+b);if(_===a)return F(1);if(_===l)return F(7);var z=(S={},S[o]=e,S[i]=t,S[r]=s,S)[_]||1,q=this.$d.getTime()+b*z;return k.w(q,this)},w.subtract=function(b,O){return this.add(-1*b,O)},w.format=function(b){var O=this,S=this.$locale();if(!this.isValid())return S.invalidDate||m;var M=b||"YYYY-MM-DDTHH:mm:ssZ",_=k.z(this),F=this.$H,z=this.$m,q=this.$M,Q=S.weekdays,le=S.months,xe=S.meridiem,Fe=function(ue,Oe,De,Ge){return ue&&(ue[Oe]||ue(O,M))||De[Oe].slice(0,Ge)},He=function(ue){return k.s(F%12||12,ue,"0")},Se=xe||function(ue,Oe,De){var Ge=ue<12?"AM":"PM";return De?Ge.toLowerCase():Ge};return M.replace(h,function(ue,Oe){return Oe||function(De){switch(De){case"YY":return String(O.$y).slice(-2);case"YYYY":return k.s(O.$y,4,"0");case"M":return q+1;case"MM":return k.s(q+1,2,"0");case"MMM":return Fe(S.monthsShort,q,le,3);case"MMMM":return Fe(le,q);case"D":return O.$D;case"DD":return k.s(O.$D,2,"0");case"d":return String(O.$W);case"dd":return Fe(S.weekdaysMin,O.$W,Q,2);case"ddd":return Fe(S.weekdaysShort,O.$W,Q,3);case"dddd":return Q[O.$W];case"H":return String(F);case"HH":return k.s(F,2,"0");case"h":return He(1);case"hh":return He(2);case"a":return Se(F,z,!0);case"A":return Se(F,z,!1);case"m":return String(z);case"mm":return k.s(z,2,"0");case"s":return String(O.$s);case"ss":return k.s(O.$s,2,"0");case"SSS":return k.s(O.$ms,3,"0");case"Z":return _}return null}(ue)||_.replace(":","")})},w.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},w.diff=function(b,O,S){var M,_=this,F=k.p(O),z=v(b),q=(z.utcOffset()-this.utcOffset())*e,Q=this-z,le=function(){return k.m(_,z)};switch(F){case d:M=le()/12;break;case c:M=le();break;case u:M=le()/3;break;case l:M=(Q-q)/6048e5;break;case a:M=(Q-q)/864e5;break;case i:M=Q/t;break;case o:M=Q/e;break;case r:M=Q/s;break;default:M=Q}return S?M:k.a(M)},w.daysInMonth=function(){return this.endOf(c).$D},w.$locale=function(){return I[this.$L]},w.locale=function(b,O){if(!b)return this.$L;var S=this.clone(),M=T(b,O,!0);return M&&(S.$L=M),S},w.clone=function(){return k.w(this.$d,this)},w.toDate=function(){return new Date(this.valueOf())},w.toJSON=function(){return this.isValid()?this.toISOString():null},w.toISOString=function(){return this.$d.toISOString()},w.toString=function(){return this.$d.toUTCString()},R}(),P=L.prototype;return v.prototype=P,[["$ms",n],["$s",r],["$m",o],["$H",i],["$W",a],["$M",c],["$y",d],["$D",p]].forEach(function(R){P[R[1]]=function(w){return this.$g(w,R[0],R[1])}}),v.extend=function(R,w){return R.$i||(R(w,L,v),R.$i=!0),v},v.locale=T,v.isDayjs=C,v.unix=function(R){return v(1e3*R)},v.en=I[y],v.Ls=I,v.p={},v})});var ul=fr((Bs,qs)=>{"use strict";(function(s,e){typeof Bs=="object"&&typeof qs<"u"?qs.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_customParseFormat=e()})(Bs,function(){"use strict";var s={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},e=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,t=/\d/,n=/\d\d/,r=/\d\d?/,o=/\d*[^-_:/,()\s\d]+/,i={},a=function(g){return(g=+g)+(g>68?1900:2e3)},l=function(g){return function(h){this[g]=+h}},c=[/[+-]\d\d:?(\d\d)?|Z/,function(g){(this.zone||(this.zone={})).offset=function(h){if(!h||h==="Z")return 0;var f=h.match(/([+-]|\d\d)/g),A=60*f[1]+(+f[2]||0);return A===0?0:f[0]==="+"?-A:A}(g)}],u=function(g){var h=i[g];return h&&(h.indexOf?h:h.s.concat(h.f))},d=function(g,h){var f,A=i.meridiem;if(A){for(var x=1;x<=24;x+=1)if(g.indexOf(A(x,0,h))>-1){f=x>12;break}}else f=g===(h?"pm":"PM");return f},p={A:[o,function(g){this.afternoon=d(g,!1)}],a:[o,function(g){this.afternoon=d(g,!0)}],Q:[t,function(g){this.month=3*(g-1)+1}],S:[t,function(g){this.milliseconds=100*+g}],SS:[n,function(g){this.milliseconds=10*+g}],SSS:[/\d{3}/,function(g){this.milliseconds=+g}],s:[r,l("seconds")],ss:[r,l("seconds")],m:[r,l("minutes")],mm:[r,l("minutes")],H:[r,l("hours")],h:[r,l("hours")],HH:[r,l("hours")],hh:[r,l("hours")],D:[r,l("day")],DD:[n,l("day")],Do:[o,function(g){var h=i.ordinal,f=g.match(/\d+/);if(this.day=f[0],h)for(var A=1;A<=31;A+=1)h(A).replace(/\[|\]/g,"")===g&&(this.day=A)}],w:[r,l("week")],ww:[n,l("week")],M:[r,l("month")],MM:[n,l("month")],MMM:[o,function(g){var h=u("months"),f=(u("monthsShort")||h.map(function(A){return A.slice(0,3)})).indexOf(g)+1;if(f<1)throw new Error;this.month=f%12||f}],MMMM:[o,function(g){var h=u("months").indexOf(g)+1;if(h<1)throw new Error;this.month=h%12||h}],Y:[/[+-]?\d+/,l("year")],YY:[n,function(g){this.year=a(g)}],YYYY:[/\d{4}/,l("year")],Z:c,ZZ:c};function m(g){var h,f;h=g,f=i&&i.formats;for(var A=(g=h.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(v,k,L){var P=L&&L.toUpperCase();return k||f[L]||s[L]||f[P].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(R,w,b){return w||b.slice(1)})})).match(e),x=A.length,y=0;y<x;y+=1){var I=A[y],E=p[I],C=E&&E[0],T=E&&E[1];A[y]=T?{regex:C,parser:T}:I.replace(/^\[|\]$/g,"")}return function(v){for(var k={},L=0,P=0;L<x;L+=1){var R=A[L];if(typeof R=="string")P+=R.length;else{var w=R.regex,b=R.parser,O=v.slice(P),S=w.exec(O)[0];b.call(k,S),v=v.replace(S,"")}}return function(M){var _=M.afternoon;if(_!==void 0){var F=M.hours;_?F<12&&(M.hours+=12):F===12&&(M.hours=0),delete M.afternoon}}(k),k}}return function(g,h,f){f.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var A=h.prototype,x=A.parse;A.parse=function(y){var I=y.date,E=y.utc,C=y.args;this.$u=E;var T=C[1];if(typeof T=="string"){var v=C[2]===!0,k=C[3]===!0,L=v||k,P=C[2];k&&(P=C[2]),i=this.$locale(),!v&&P&&(i=f.Ls[P]),this.$d=function(O,S,M,_){try{if(["x","X"].indexOf(S)>-1)return new Date((S==="X"?1e3:1)*O);var F=m(S)(O),z=F.year,q=F.month,Q=F.day,le=F.hours,xe=F.minutes,Fe=F.seconds,He=F.milliseconds,Se=F.zone,ue=F.week,Oe=new Date,De=Q||(z||q?1:Oe.getDate()),Ge=z||Oe.getFullYear(),dt=0;z&&!q||(dt=q>0?q-1:Oe.getMonth());var mt,D=le||0,U=xe||0,j=Fe||0,H=He||0;return Se?new Date(Date.UTC(Ge,dt,De,D,U,j,H+60*Se.offset*1e3)):M?new Date(Date.UTC(Ge,dt,De,D,U,j,H)):(mt=new Date(Ge,dt,De,D,U,j,H),ue&&(mt=_(mt).week(ue).toDate()),mt)}catch{return new Date("")}}(I,T,E,f),this.init(),P&&P!==!0&&(this.$L=this.locale(P).$L),L&&I!=this.format(T)&&(this.$d=new Date("")),i={}}else if(T instanceof Array)for(var R=T.length,w=1;w<=R;w+=1){C[1]=T[w-1];var b=f.apply(this,C);if(b.isValid()){this.$d=b.$d,this.$L=b.$L,this.init();break}w===R&&(this.$d=new Date(""))}else x.call(this,y)}}})});var pl=fr((zs,js)=>{"use strict";(function(s,e){typeof zs=="object"&&typeof js<"u"?js.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_timezone=e()})(zs,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),g=function(h,f){f===void 0&&(f={});var A=f.timeZoneName||"short",x=h+"|"+A,y=e[x];return y||(y=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:h,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:A}),e[x]=y),y}(d,p);return g.formatToParts(m)},a=function(u,d){for(var p=i(u,d),m=[],g=0;g<p.length;g+=1){var h=p[g],f=h.type,A=h.value,x=s[f];x>=0&&(m[x]=parseInt(A,10))}var y=m[3],I=y===24?0:y,E=m[0]+"-"+m[1]+"-"+m[2]+" "+I+":"+m[4]+":"+m[5]+":000",C=+u;return(r.utc(E).valueOf()-(C-=C%1e3))/6e4},l=n.prototype;l.tz=function(u,d){u===void 0&&(u=o);var p,m=this.utcOffset(),g=this.toDate(),h=g.toLocaleString("en-US",{timeZone:u}),f=Math.round((g-new Date(h))/1e3/60),A=15*-Math.round(g.getTimezoneOffset()/15)-f;if(!Number(A))p=this.utcOffset(0,d);else if(p=r(h,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(A,!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,g=p||d||o,h=a(+r(),g);if(typeof u!="string")return r(u).tz(g);var f=function(I,E,C){var T=I-60*E*1e3,v=a(T,C);if(E===v)return[T,E];var k=a(T-=60*(v-E)*1e3,C);return v===k?[T,v]:[I-60*Math.min(v,k)*1e3,Math.max(v,k)]}(r.utc(u,m).valueOf(),h,g),A=f[0],x=f[1],y=r(A).utcOffset(x);return y.$x.$timezone=g,y},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(u){o=u}}})});var dl=fr((Hs,Ks)=>{"use strict";(function(s,e){typeof Hs=="object"&&typeof Ks<"u"?Ks.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_utc=e()})(Hs,function(){"use strict";var s="minute",e=/[+-]\d\d(?::?\d\d)?/g,t=/([+-]|\d\d)/g;return function(n,r,o){var i=r.prototype;o.utc=function(m){var g={date:m,utc:!0,args:arguments};return new r(g)},i.utc=function(m){var g=o(this.toDate(),{locale:this.$L,utc:!0});return m?g.add(this.utcOffset(),s):g},i.local=function(){return o(this.toDate(),{locale:this.$L,utc:!1})};var a=i.parse;i.parse=function(m){m.utc&&(this.$u=!0),this.$utils().u(m.$offset)||(this.$offset=m.$offset),a.call(this,m)};var l=i.init;i.init=function(){if(this.$u){var m=this.$d;this.$y=m.getUTCFullYear(),this.$M=m.getUTCMonth(),this.$D=m.getUTCDate(),this.$W=m.getUTCDay(),this.$H=m.getUTCHours(),this.$m=m.getUTCMinutes(),this.$s=m.getUTCSeconds(),this.$ms=m.getUTCMilliseconds()}else l.call(this)};var c=i.utcOffset;i.utcOffset=function(m,g){var h=this.$utils().u;if(h(m))return this.$u?0:h(this.$offset)?c.call(this):this.$offset;if(typeof m=="string"&&(m=function(y){y===void 0&&(y="");var I=y.match(e);if(!I)return null;var E=(""+I[0]).match(t)||["-",0,0],C=E[0],T=60*+E[1]+ +E[2];return T===0?0:C==="+"?T:-T}(m),m===null))return this;var f=Math.abs(m)<=16?60*m:m,A=this;if(g)return A.$offset=f,A.$u=m===0,A;if(m!==0){var x=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(A=this.local().add(f+x,s)).$offset=f,A.$x.$localOffset=x}else A=this.utc();return A};var u=i.format;i.format=function(m){var g=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return u.call(this,g)},i.valueOf=function(){var m=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*m},i.isUTC=function(){return!!this.$u},i.toISOString=function(){return this.toDate().toISOString()},i.toString=function(){return this.toDate().toUTCString()};var d=i.toDate;i.toDate=function(m){return m==="s"&&this.$offset?o(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():d.call(this)};var p=i.diff;i.diff=function(m,g,h){if(m&&this.$u===m.$u)return p.call(this,m,g,h);var f=this.local(),A=o(m).local();return p.call(f,A,g,h)}}})});var gp={};Ic(gp,{AxACE:()=>Oo,AxACEOptimizedProgram:()=>ir,AxAI:()=>Wn,AxAIAnthropic:()=>qt,AxAIAnthropicModel:()=>Pn,AxAIAnthropicVertexModel:()=>Sr,AxAIAzureOpenAI:()=>Wt,AxAICohere:()=>Vt,AxAICohereEmbedModel:()=>Nn,AxAICohereModel:()=>Dn,AxAIDeepSeek:()=>Jt,AxAIDeepSeekModel:()=>$n,AxAIGoogleGemini:()=>Yt,AxAIGoogleGeminiEmbedModel:()=>Gr,AxAIGoogleGeminiEmbedTypes:()=>hs,AxAIGoogleGeminiModel:()=>Gn,AxAIGoogleGeminiSafetyCategory:()=>Lr,AxAIGoogleGeminiSafetyThreshold:()=>Ur,AxAIGrok:()=>cn,AxAIGrokEmbedModels:()=>Ms,AxAIGrokModel:()=>Kn,AxAIGroq:()=>Zt,AxAIGroqModel:()=>Ln,AxAIHuggingFace:()=>Xt,AxAIHuggingFaceModel:()=>jr,AxAIMistral:()=>en,AxAIMistralEmbedModels:()=>Ts,AxAIMistralModel:()=>Un,AxAIOllama:()=>tn,AxAIOpenAI:()=>Kt,AxAIOpenAIBase:()=>fe,AxAIOpenAIEmbedModel:()=>zt,AxAIOpenAIModel:()=>Fn,AxAIOpenAIResponses:()=>rn,AxAIOpenAIResponsesBase:()=>Bn,AxAIOpenAIResponsesImpl:()=>nn,AxAIOpenAIResponsesModel:()=>jt,AxAIOpenRouter:()=>on,AxAIRefusalError:()=>de,AxAIReka:()=>sn,AxAIRekaModel:()=>zn,AxAIServiceAbortedError:()=>Nt,AxAIServiceAuthenticationError:()=>At,AxAIServiceError:()=>Re,AxAIServiceNetworkError:()=>tt,AxAIServiceResponseError:()=>ct,AxAIServiceStatusError:()=>vt,AxAIServiceStreamTerminatedError:()=>Je,AxAIServiceTimeoutError:()=>St,AxAITogether:()=>an,AxAIWebLLM:()=>ln,AxAIWebLLMModel:()=>Hn,AxAgent:()=>dr,AxApacheTika:()=>Io,AxAssertionError:()=>nt,AxBalancer:()=>_r,AxBaseAI:()=>he,AxBaseOptimizer:()=>_e,AxBootstrapFewShot:()=>hn,AxContentProcessingError:()=>Ye,AxDB:()=>ro,AxDBBase:()=>ze,AxDBCloudflare:()=>un,AxDBManager:()=>oo,AxDBMemory:()=>bt,AxDBPinecone:()=>pn,AxDBWeaviate:()=>dn,AxDefaultCostTracker:()=>or,AxDefaultResultReranker:()=>bo,AxDockerSession:()=>No,AxEmbeddingAdapter:()=>$o,AxEvalUtil:()=>Bl,AxFlow:()=>ur,AxFlowDependencyAnalyzer:()=>An,AxFlowExecutionPlanner:()=>yn,AxFlowSubContextImpl:()=>Tn,AxFlowTypedSubContextImpl:()=>Fo,AxFluentFieldType:()=>Ie,AxFunctionError:()=>Yn,AxFunctionProcessor:()=>Zn,AxGEPA:()=>Mo,AxGEPAFlow:()=>Eo,AxGen:()=>Pe,AxGenerateError:()=>nr,AxHFDataLoader:()=>wo,AxInstanceRegistry:()=>fn,AxLLMRequestTypeValues:()=>es,AxMCPClient:()=>Go,AxMCPHTTPSSETransport:()=>Bo,AxMCPStreambleHTTPTransport:()=>Uo,AxMediaNotSupportedError:()=>qe,AxMemory:()=>mn,AxMiPRO:()=>_o,AxMockAIService:()=>Wr,AxMultiServiceRouter:()=>Vr,AxOptimizedProgramImpl:()=>ot,AxProgram:()=>Tt,AxPromptTemplate:()=>Et,AxProviderRouter:()=>Zr,AxRateLimiterTokenUsage:()=>Qt,AxSignature:()=>ge,AxSignatureBuilder:()=>er,AxSimpleClassifier:()=>Co,AxSimpleClassifierClass:()=>To,AxSpanKindValues:()=>ts,AxStopFunctionCallException:()=>Mt,AxStringUtil:()=>yo,AxTestPrompt:()=>Ro,agent:()=>cc,ai:()=>Ua,ax:()=>ye,axAIAnthropicDefaultConfig:()=>cs,axAIAnthropicVertexDefaultConfig:()=>fa,axAIAzureOpenAIBestConfig:()=>ya,axAIAzureOpenAICreativeConfig:()=>Aa,axAIAzureOpenAIDefaultConfig:()=>ps,axAIAzureOpenAIFastConfig:()=>xa,axAICohereCreativeConfig:()=>Ra,axAICohereDefaultConfig:()=>gs,axAIDeepSeekCodeConfig:()=>wa,axAIDeepSeekDefaultConfig:()=>fs,axAIGoogleGeminiDefaultConfig:()=>ys,axAIGoogleGeminiDefaultCreativeConfig:()=>Sa,axAIGrokBestConfig:()=>La,axAIGrokDefaultConfig:()=>no,axAIHuggingFaceCreativeConfig:()=>Oa,axAIHuggingFaceDefaultConfig:()=>Is,axAIMistralBestConfig:()=>ka,axAIMistralDefaultConfig:()=>Kr,axAIOllamaDefaultConfig:()=>Cs,axAIOllamaDefaultCreativeConfig:()=>Ma,axAIOpenAIBestConfig:()=>Mr,axAIOpenAICreativeConfig:()=>Er,axAIOpenAIDefaultConfig:()=>Ot,axAIOpenAIFastConfig:()=>Pr,axAIOpenAIResponsesBestConfig:()=>Ea,axAIOpenAIResponsesCreativeConfig:()=>Pa,axAIOpenAIResponsesDefaultConfig:()=>qn,axAIOpenRouterDefaultConfig:()=>ws,axAIRekaBestConfig:()=>Da,axAIRekaCreativeConfig:()=>Na,axAIRekaDefaultConfig:()=>jn,axAIRekaFastConfig:()=>$a,axAITogetherDefaultConfig:()=>Ss,axAIWebLLMCreativeConfig:()=>Ga,axAIWebLLMDefaultConfig:()=>ks,axAnalyzeChatPromptRequirements:()=>_a,axAnalyzeRequestRequirements:()=>kt,axBaseAIDefaultConfig:()=>te,axBaseAIDefaultCreativeConfig:()=>Ae,axCheckMetricsHealth:()=>Ba,axCreateDefaultColorLogger:()=>Xo,axCreateDefaultOptimizerColorLogger:()=>si,axCreateDefaultOptimizerTextLogger:()=>zl,axCreateDefaultTextLogger:()=>Gi,axCreateFlowColorLogger:()=>cr,axCreateFlowTextLogger:()=>Yl,axDefaultFlowLogger:()=>Ql,axDefaultMetricsConfig:()=>Fs,axDefaultOptimizerLogger:()=>rr,axDefaultOptimizerMetricsConfig:()=>ii,axGetCompatibilityReport:()=>ba,axGetFormatCompatibility:()=>Ta,axGetMetricsConfig:()=>za,axGetOptimizerMetricsConfig:()=>Hl,axGetProvidersWithMediaSupport:()=>Ia,axGlobals:()=>ee,axModelInfoAnthropic:()=>_n,axModelInfoCohere:()=>Nr,axModelInfoDeepSeek:()=>$r,axModelInfoGoogleGemini:()=>Br,axModelInfoGrok:()=>to,axModelInfoGroq:()=>qr,axModelInfoHuggingFace:()=>zr,axModelInfoMistral:()=>Hr,axModelInfoOpenAI:()=>Ht,axModelInfoOpenAIResponses:()=>kr,axModelInfoReka:()=>Qr,axModelInfoTogether:()=>Xr,axModelInfoWebLLM:()=>eo,axProcessContentForProvider:()=>Yr,axRAG:()=>uc,axScoreProvidersForRequest:()=>Fr,axSelectOptimalProvider:()=>Dr,axSpanAttributes:()=>V,axSpanEvents:()=>Qe,axUpdateMetricsConfig:()=>qa,axUpdateOptimizerMetricsConfig:()=>jl,axValidateChatRequestMessage:()=>Bt,axValidateChatResponseResult:()=>vr,axValidateProviderCapabilities:()=>ds,f:()=>ie,flow:()=>Do,s:()=>Kl});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 jo=(()=>{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 be(){return jo.randomUUID()}async function Cc(s){let e=new TextEncoder,t=typeof s=="string"?e.encode(s):s,n=await jo.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var zo=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 Cc(this.data)}};function Be(s){if(s!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new zo}function gi(){return jo}var hr=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
|
`)?`
|
|
5
5
|
`:"")+e.trim();return}let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();switch(n){case"event":this.currentEvent.event=r;break;case"data":this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
|
|
6
6
|
`)?`
|
|
7
|
-
`:"")+r;break;case"id":this.currentEvent.id=r;break;case"retry":{let o=Number.parseInt(r,10);Number.isNaN(o)||(this.currentEvent.retry=o);break}}}processEvent(e){if(this.currentEvent.rawData){if(this.currentEvent.event||(this.currentEvent.event="message"),this.currentEvent.rawData.trim()==="[DONE]"){this.currentEvent={rawData:""};return}try{let t=this.dataParser(this.currentEvent.rawData);e.enqueue(t)}catch(t){this.onError(t,this.currentEvent.rawData)}this.currentEvent={rawData:""}}}};var Ho=class{decoder;constructor(){this.decoder=new TextDecoder}transform(e,t){if(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e)))throw new TypeError("Input data must be a BufferSource");let n=this.decoder.decode(e,{stream:!0});n.length!==0&&t.enqueue(n)}flush(e){let t=this.decoder.decode();t.length!==0&&e.enqueue(t)}},Ar=class extends TransformStream{constructor(){super(new Ho)}};var Rc={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},wc=globalThis.TextDecoderStream??Ar,Re=class extends Error{constructor(t,n,r,o,i={}){super(t);this.url=n;this.requestBody=r;this.responseBody=o;this.name=
|
|
8
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},
|
|
9
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},
|
|
10
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},
|
|
11
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function
|
|
7
|
+
`:"")+r;break;case"id":this.currentEvent.id=r;break;case"retry":{let o=Number.parseInt(r,10);Number.isNaN(o)||(this.currentEvent.retry=o);break}}}processEvent(e){if(this.currentEvent.rawData){if(this.currentEvent.event||(this.currentEvent.event="message"),this.currentEvent.rawData.trim()==="[DONE]"){this.currentEvent={rawData:""};return}try{let t=this.dataParser(this.currentEvent.rawData);e.enqueue(t)}catch(t){this.onError(t,this.currentEvent.rawData)}this.currentEvent={rawData:""}}}};var Ho=class{decoder;constructor(){this.decoder=new TextDecoder}transform(e,t){if(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e)))throw new TypeError("Input data must be a BufferSource");let n=this.decoder.decode(e,{stream:!0});n.length!==0&&t.enqueue(n)}flush(e){let t=this.decoder.decode();t.length!==0&&e.enqueue(t)}},Ar=class extends TransformStream{constructor(){super(new Ho)}};var Rc={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},wc=globalThis.TextDecoderStream??Ar,Re=class extends Error{constructor(t,n,r,o,i={}){super(t);this.url=n;this.requestBody=r;this.responseBody=o;this.name="AxAIServiceError",this.timestamp=new Date().toISOString(),this.errorId=be(),this.context=i,this.stack=this.toString()}timestamp;errorId;context;toString(){return[`${this.name}: ${this.message}`,`URL: ${this.url}`,`Request Body: ${JSON.stringify(this.requestBody,null,2)}`,`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
|
|
8
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},vt=class extends Re{constructor(t,n,r,o,i,a){super(`HTTP ${t} - ${n}`,r,o,{httpStatus:t,httpStatusText:n,responseBody:i,...a});this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},tt=class extends Re{constructor(t,n,r,o,i){super(`Network Error: ${t.message}`,n,r,o,{originalErrorName:t.name,originalErrorStack:t.stack,...i});this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},ct=class extends Re{constructor(e,t,n,r){super(e,t,n,void 0,r),this.name="AxAIServiceResponseError"}},Je=class extends Re{constructor(t,n,r,o){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...o});this.lastChunk=r;this.name="AxAIServiceStreamTerminatedError"}},St=class extends Re{constructor(e,t,n,r){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r}),this.name="AxAIServiceTimeoutError"}},Nt=class extends Re{constructor(e,t,n,r){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r}),this.name="AxAIServiceAbortedError"}},At=class extends Re{constructor(e,t,n,r){super("Authentication failed",e,t,n,r),this.name="AxAIServiceAuthenticationError"}},de=class extends Error{constructor(t,n,r){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=r;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=be()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Refusal: ${this.refusalMessage}`,this.model?`Model: ${this.model}`:"",this.requestId?`Request ID: ${this.requestId}`:"",`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].filter(Boolean).join(`
|
|
9
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},qe=class extends Error{constructor(t,n,r=!1){super(`${t} not supported by ${n}${r?" (fallback available)":""}`);this.mediaType=t;this.provider=n;this.fallbackAvailable=r;this.name="AxMediaNotSupportedError",this.timestamp=new Date().toISOString(),this.errorId=be()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Media Type: ${this.mediaType}`,`Provider: ${this.provider}`,`Fallback Available: ${this.fallbackAvailable}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
|
|
10
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Ye=class extends Error{constructor(t,n,r){super(`Failed to process ${n} during ${r}: ${t.message}`);this.originalError=t;this.contentType=n;this.processingStep=r;this.name="AxContentProcessingError",this.timestamp=new Date().toISOString(),this.errorId=be()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Content Type: ${this.contentType}`,`Processing Step: ${this.processingStep}`,`Original Error: ${this.originalError.message}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
|
|
11
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function fi(s){try{return s.headers.get("content-type")?.includes("application/json")?await s.json():await s.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function hi(s,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**s)*(.75+Math.random()*.5)}function vc(){return{startTime:Date.now(),retryCount:0}}function Ai(s){s.retryCount++,s.lastRetryTime=Date.now()}function xi(s,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:s instanceof tt&&!(s instanceof At)}var ke=async(s,e)=>{if(s.localCall)return await s.localCall(e,s.stream);if(!s.url)throw new Error("API URL is required when localCall is not provided");let t={...Rc,...s.retry},n=s.timeout,r=vc(),o,i=new URL(s.url),a=`${[i.pathname,s.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${i.search}`,l=new URL(a,i);if(s.corsProxy){let d=l.href;l=new URL(`${s.corsProxy}?url=${encodeURIComponent(d)}`)}let c=be();if(s.validateRequest&&!await s.validateRequest(e))throw new ct("Invalid request data",l.href,e,{validation:"request"});s.span?.setAttributes({"http.request.method":s.put?"PUT":"POST","url.full":l.href,"request.id":c,"request.startTime":r.startTime});let u=0;for(;;){let d=new AbortController;if(s.abortSignal){if(s.abortSignal.aborted)throw new Nt(l.href,s.abortSignal.reason,e,{metrics:r});let p=()=>{d.abort(s.abortSignal.reason||"User aborted request")};s.abortSignal.addEventListener("abort",p,{once:!0});let m=d.abort.bind(d);d.abort=g=>{s.abortSignal.removeEventListener("abort",p),m(g)}}n&&(o=setTimeout(()=>{d.abort("Request timeout")},n));try{let p=await(s.fetch??fetch)(l,{method:s.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":c,"X-Retry-Count":u.toString(),...s.headers},body:JSON.stringify(e),signal:d.signal});if(o&&clearTimeout(o),p.status===401||p.status===403){let x=await fi(p);throw new At(l.href,e,x,{metrics:r})}if(p.status>=400&&xi(new Error,p.status,u,t)){let x=hi(u,t);u++,Ai(r),s.span?.addEvent("retry",{attempt:u,delay:x,status:p.status,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(y=>setTimeout(y,x));continue}if(p.status>=400){let x=await fi(p);throw new vt(p.status,p.statusText,l.href,e,x,{metrics:r})}if(!s.stream){let x=await p.json();if(s.validateResponse&&!await s.validateResponse(x))throw new ct("Invalid response data",l.href,e,{validation:"response"});return s.span?.setAttributes({"response.time":Date.now()-r.startTime,"response.retries":r.retryCount}),x}if(!p.body)throw new ct("Response body is null",l.href,e,{metrics:r});let m,g=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(x){let y=p.body.getReader(),I=new TextDecoder,E="";async function C(){try{for(;;){let{done:T,value:v}=await y.read();if(T){A=!0,x.close();break}E+=I.decode(v,{stream:!0});let k=E.split(`
|
|
12
12
|
|
|
13
|
-
`);
|
|
14
|
-
`),T="",C="message";for(let y of P)y.startsWith("data: ")?T=y.slice(6):y.startsWith("event: ")&&(C=y.slice(7));if(T){if(T==="[DONE]"){x.close();return}try{let y=JSON.parse(T);m=y,g++,r.streamChunks=g,r.lastChunkTime=Date.now(),x.enqueue(y),s.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":C})}catch(y){s.debug&&console.warn("Skipping non-JSON SSE data:",T,y)}}}}}catch(w){let S=w,E={...r,streamDuration:Date.now()-r.startTime};S.name==="AbortError"||S.message?.includes("aborted")?x.error(new Ve(l.href,e,m,{streamMetrics:E})):x.error(new et(S,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:E}))}finally{b.releaseLock()}}R()}});let h=new TransformStream({transform(x,b){m=x,g++,r.streamChunks=g,r.lastChunkTime=Date.now(),b.enqueue(x),s.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),A=!1;return new ReadableStream({start(x){let b=d.body.pipeThrough(new wc).pipeThrough(new fr).pipeThrough(h).getReader();async function I(){try{for(;;){let{done:M,value:R}=await b.read();if(M){A||(A=!0,x.close());break}if(A)break;x.enqueue(R)}}catch(M){let R=M,w={...r,streamDuration:Date.now()-r.startTime};throw R.name==="AbortError"||R.message?.includes("aborted")?x.error(new Ve(l.href,e,m,{streamMetrics:w})):R instanceof TypeError&&R.message.includes("cancelled")?x.error(new Ve(l.href,e,m,{streamMetrics:w,cancelReason:"Stream cancelled by client"})):x.error(new et(R,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:w})),R}finally{o&&clearTimeout(o),b.releaseLock()}}I()},cancel(){A=!0}})}catch(d){if(d instanceof Error&&d.name==="AbortError")throw s.abortSignal?.aborted?new Dt(l.href,s.abortSignal.reason,e,{metrics:r}):new vt(l.href,n||0,e,{metrics:r});if(s.span?.isRecording()&&(s.span.recordException(d),s.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),d instanceof et&&xi(d,void 0,u,t)){let m=fi(u,t);u++,Ai(r),s.span?.addEvent("retry",{attempt:u,delay:m,error:d.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(g=>setTimeout(g,m));continue}throw d instanceof Re&&(d.context.metrics=r),d}finally{o!==void 0&&clearTimeout(o)}}};var yi=typeof globalThis=="object"?globalThis:global;var ct="1.9.0";var bi=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Sc(s){var e=new Set([s]),t=new Set,n=s.match(bi);if(!n)return function(){return!1};var r={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(r.prerelease!=null)return function(l){return l===s};function o(a){return t.add(a),!1}function i(a){return e.add(a),!0}return function(l){if(e.has(l))return!0;if(t.has(l))return!1;var c=l.match(bi);if(!c)return o(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||r.major!==u.major?o(l):r.major===0?r.minor===u.minor&&r.patch<=u.patch?i(l):o(l):r.minor<=u.minor?i(l):o(l)}}var Ii=Sc(ct);var Oc=ct.split(".")[0],wn=Symbol.for("opentelemetry.js.api."+Oc),vn=yi;function Nt(s,e,t,n){var r;n===void 0&&(n=!1);var o=vn[wn]=(r=vn[wn])!==null&&r!==void 0?r:{version:ct};if(!n&&o[s]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+s);return t.error(i.stack||i.message),!1}if(o.version!==ct){var i=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+s+" does not match previously registered API v"+ct);return t.error(i.stack||i.message),!1}return o[s]=e,t.debug("@opentelemetry/api: Registered a global for "+s+" v"+ct+"."),!0}function ut(s){var e,t,n=(e=vn[wn])===null||e===void 0?void 0:e.version;if(!(!n||!Ii(n)))return(t=vn[wn])===null||t===void 0?void 0:t[s]}function $t(s,e){e.debug("@opentelemetry/api: Unregistering a global for "+s+" v"+ct+".");var t=vn[wn];t&&delete t[s]}var kc=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Mc=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},Ti=function(){function s(e){this._namespace=e.namespace||"DiagComponentLogger"}return s.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Sn("debug",this._namespace,e)},s.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Sn("error",this._namespace,e)},s.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Sn("info",this._namespace,e)},s.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Sn("warn",this._namespace,e)},s.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Sn("verbose",this._namespace,e)},s}();function Sn(s,e,t){var n=ut("diag");if(n)return t.unshift(e),n[s].apply(n,Mc([],kc(t),!1))}var we;(function(s){s[s.NONE=0]="NONE",s[s.ERROR=30]="ERROR",s[s.WARN=50]="WARN",s[s.INFO=60]="INFO",s[s.DEBUG=70]="DEBUG",s[s.VERBOSE=80]="VERBOSE",s[s.ALL=9999]="ALL"})(we||(we={}));function Ci(s,e){s<we.NONE?s=we.NONE:s>we.ALL&&(s=we.ALL),e=e||{};function t(n,r){var o=e[n];return typeof o=="function"&&s>=r?o.bind(e):function(){}}return{error:t("error",we.ERROR),warn:t("warn",we.WARN),info:t("info",we.INFO),debug:t("debug",we.DEBUG),verbose:t("verbose",we.VERBOSE)}}var Ec=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Pc=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},_c="diag",Gt=function(){function s(){function e(r){return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];var a=ut("diag");if(a)return a[r].apply(a,Pc([],Ec(o),!1))}}var t=this,n=function(r,o){var i,a,l;if(o===void 0&&(o={logLevel:we.INFO}),r===t){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof o=="number"&&(o={logLevel:o});var u=ut("diag"),p=Ci((a=o.logLevel)!==null&&a!==void 0?a:we.INFO,r);if(u&&!o.suppressOverrideMessage){var d=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+d),p.warn("Current logger will overwrite one already registered from "+d)}return Nt("diag",p,t,!0)};t.setLogger=n,t.disable=function(){$t(_c,t)},t.createComponentLogger=function(r){return new Ti(r)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return s.instance=function(){return this._instance||(this._instance=new s),this._instance},s}();function Ri(s){return Symbol.for(s)}var Fc=function(){function s(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,r){var o=new s(t._currentContext);return o._currentContext.set(n,r),o},t.deleteValue=function(n){var r=new s(t._currentContext);return r._currentContext.delete(n),r}}return s}(),wi=new Fc;var Dc=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Nc=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},vi=function(){function s(){}return s.prototype.active=function(){return wi},s.prototype.with=function(e,t,n){for(var r=[],o=3;o<arguments.length;o++)r[o-3]=arguments[o];return t.call.apply(t,Nc([n],Dc(r),!1))},s.prototype.bind=function(e,t){return t},s.prototype.enable=function(){return this},s.prototype.disable=function(){return this},s}();var $c=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Gc=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},Ko="context",Lc=new vi,Lt=function(){function s(){}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalContextManager=function(e){return Nt(Ko,e,Gt.instance())},s.prototype.active=function(){return this._getContextManager().active()},s.prototype.with=function(e,t,n){for(var r,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return(r=this._getContextManager()).with.apply(r,Gc([e,t,n],$c(o),!1))},s.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},s.prototype._getContextManager=function(){return ut(Ko)||Lc},s.prototype.disable=function(){this._getContextManager().disable(),$t(Ko,Gt.instance())},s}();var xr;(function(s){s[s.NONE=0]="NONE",s[s.SAMPLED=1]="SAMPLED"})(xr||(xr={}));var Wo="0000000000000000",Vo="00000000000000000000000000000000",Si={traceId:Vo,spanId:Wo,traceFlags:xr.NONE};var At=function(){function s(e){e===void 0&&(e=Si),this._spanContext=e}return s.prototype.spanContext=function(){return this._spanContext},s.prototype.setAttribute=function(e,t){return this},s.prototype.setAttributes=function(e){return this},s.prototype.addEvent=function(e,t){return this},s.prototype.addLink=function(e){return this},s.prototype.addLinks=function(e){return this},s.prototype.setStatus=function(e){return this},s.prototype.updateName=function(e){return this},s.prototype.end=function(e){},s.prototype.isRecording=function(){return!1},s.prototype.recordException=function(e,t){},s}();var Jo=Ri("OpenTelemetry Context Key SPAN");function yr(s){return s.getValue(Jo)||void 0}function Oi(){return yr(Lt.getInstance().active())}function On(s,e){return s.setValue(Jo,e)}function ki(s){return s.deleteValue(Jo)}function Mi(s,e){return On(s,new At(e))}function br(s){var e;return(e=yr(s))===null||e===void 0?void 0:e.spanContext()}var Uc=/^([0-9a-f]{32})$/i,Bc=/^[0-9a-f]{16}$/i;function qc(s){return Uc.test(s)&&s!==Vo}function zc(s){return Bc.test(s)&&s!==Wo}function Ir(s){return qc(s.traceId)&&zc(s.spanId)}function Ei(s){return new At(s)}var Yo=Lt.getInstance(),Tr=function(){function s(){}return s.prototype.startSpan=function(e,t,n){n===void 0&&(n=Yo.active());var r=!!t?.root;if(r)return new At;var o=n&&br(n);return jc(o)&&Ir(o)?new At(o):new At},s.prototype.startActiveSpan=function(e,t,n,r){var o,i,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(o=t,a=n):(o=t,i=n,a=r);var l=i??Yo.active(),c=this.startSpan(e,o,l),u=On(l,c);return Yo.with(u,a,void 0,c)}},s}();function jc(s){return typeof s=="object"&&typeof s.spanId=="string"&&typeof s.traceId=="string"&&typeof s.traceFlags=="number"}var Hc=new Tr,Pi=function(){function s(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return s.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},s.prototype.startActiveSpan=function(e,t,n,r){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},s.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):Hc},s}();var _i=function(){function s(){}return s.prototype.getTracer=function(e,t,n){return new Tr},s}();var Kc=new _i,Qo=function(){function s(){}return s.prototype.getTracer=function(e,t,n){var r;return(r=this.getDelegateTracer(e,t,n))!==null&&r!==void 0?r:new Pi(this,e,t,n)},s.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Kc},s.prototype.setDelegate=function(e){this._delegate=e},s.prototype.getDelegateTracer=function(e,t,n){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(e,t,n)},s}();var Me;(function(s){s[s.INTERNAL=0]="INTERNAL",s[s.SERVER=1]="SERVER",s[s.CLIENT=2]="CLIENT",s[s.PRODUCER=3]="PRODUCER",s[s.CONSUMER=4]="CONSUMER"})(Me||(Me={}));var xt=Lt.getInstance();var Zo="trace",Fi=function(){function s(){this._proxyTracerProvider=new Qo,this.wrapSpanContext=Ei,this.isSpanContextValid=Ir,this.deleteSpan=ki,this.getSpan=yr,this.getActiveSpan=Oi,this.getSpanContext=br,this.setSpan=On,this.setSpanContext=Mi}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalTracerProvider=function(e){var t=Nt(Zo,this._proxyTracerProvider,Gt.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},s.prototype.getTracerProvider=function(){return ut(Zo)||this._proxyTracerProvider},s.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},s.prototype.disable=function(){$t(Zo,Gt.instance()),this._proxyTracerProvider=new Qo},s}();var kn=Fi.getInstance();var ce={signatureStrict:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,functionResultFormatter:s=>typeof s=="string"?s:s==null?"":JSON.stringify(s,null,2)};var ve=class{ANSI_WHITE_BRIGHT="\x1B[97m";ANSI_GREEN_BRIGHT="\x1B[92m";ANSI_BLUE_BRIGHT="\x1B[94m";ANSI_RED_BRIGHT="\x1B[91m";ANSI_YELLOW_BRIGHT="\x1B[93m";ANSI_YELLOW="\x1B[93m";ANSI_RED="\x1B[91m";ANSI_RESET="\x1B[0m";ANSI_ORANGE="\x1B[38;5;208m";ANSI_WHITE="\x1B[37m";ANSI_CYAN_BRIGHT="\x1B[96m";ANSI_MAGENTA_BRIGHT="\x1B[95m";ANSI_GRAY="\x1B[90m";ANSI_GREEN="\x1B[32m";ANSI_CYAN="\x1B[36m";ANSI_MAGENTA="\x1B[35m";ANSI_BLUE="\x1B[34m";ANSI_YELLOW_DIM="\x1B[33m";colorize(e,t){return`${t}${e}${this.ANSI_RESET}`}whiteBright(e){return this.colorize(e,this.ANSI_WHITE_BRIGHT)}greenBright(e){return this.colorize(e,this.ANSI_GREEN_BRIGHT)}blueBright(e){return this.colorize(e,this.ANSI_BLUE_BRIGHT)}redBright(e){return this.colorize(e,this.ANSI_RED_BRIGHT)}white(e){return this.colorize(e,this.ANSI_WHITE)}yellow(e){return this.colorize(e,this.ANSI_YELLOW)}yellowBright(e){return this.colorize(e,this.ANSI_YELLOW_BRIGHT)}red(e){return this.colorize(e,this.ANSI_RED)}orange(e){return this.colorize(e,this.ANSI_ORANGE)}cyanBright(e){return this.colorize(e,this.ANSI_CYAN_BRIGHT)}magentaBright(e){return this.colorize(e,this.ANSI_MAGENTA_BRIGHT)}gray(e){return this.colorize(e,this.ANSI_GRAY)}green(e){return this.colorize(e,this.ANSI_GREEN)}cyan(e){return this.colorize(e,this.ANSI_CYAN)}magenta(e){return this.colorize(e,this.ANSI_MAGENTA)}blue(e){return this.colorize(e,this.ANSI_BLUE)}yellowDim(e){return this.colorize(e,this.ANSI_YELLOW_DIM)}};var Gd=new ve,Di=s=>{console.log(s)},Ni=(s,e,t)=>{let n=(r,o)=>t&&o&&o in t?t[o](r):r;switch(s.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
|
|
13
|
+
`);E=k.pop()||"";for(let L of k){if(!L.trim())continue;let P=L.split(`
|
|
14
|
+
`),R="",w="message";for(let b of P)b.startsWith("data: ")?R=b.slice(6):b.startsWith("event: ")&&(w=b.slice(7));if(R){if(R==="[DONE]"){x.close();return}try{let b=JSON.parse(R);m=b,g++,r.streamChunks=g,r.lastChunkTime=Date.now(),x.enqueue(b),s.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":w})}catch(b){s.debug&&console.warn("Skipping non-JSON SSE data:",R,b)}}}}}catch(T){let v=T,k={...r,streamDuration:Date.now()-r.startTime};v.name==="AbortError"||v.message?.includes("aborted")?x.error(new Je(l.href,e,m,{streamMetrics:k})):x.error(new tt(v,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:k}))}finally{y.releaseLock()}}C()}});let f=new TransformStream({transform(x,y){m=x,g++,r.streamChunks=g,r.lastChunkTime=Date.now(),y.enqueue(x),s.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),A=!1;return new ReadableStream({start(x){let y=p.body.pipeThrough(new wc).pipeThrough(new hr).pipeThrough(f).getReader();async function I(){try{for(;;){let{done:E,value:C}=await y.read();if(E){A||(A=!0,x.close());break}if(A)break;x.enqueue(C)}}catch(E){let C=E,T={...r,streamDuration:Date.now()-r.startTime};throw C.name==="AbortError"||C.message?.includes("aborted")?x.error(new Je(l.href,e,m,{streamMetrics:T})):C instanceof TypeError&&C.message.includes("cancelled")?x.error(new Je(l.href,e,m,{streamMetrics:T,cancelReason:"Stream cancelled by client"})):x.error(new tt(C,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:T})),C}finally{o&&clearTimeout(o),y.releaseLock()}}I()},cancel(){A=!0}})}catch(p){if(p instanceof Error&&p.name==="AbortError")throw s.abortSignal?.aborted?new Nt(l.href,s.abortSignal.reason,e,{metrics:r}):new St(l.href,n||0,e,{metrics:r});if(s.span?.isRecording()&&(s.span.recordException(p),s.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),p instanceof tt&&xi(p,void 0,u,t)){let m=hi(u,t);u++,Ai(r),s.span?.addEvent("retry",{attempt:u,delay:m,error:p.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(g=>setTimeout(g,m));continue}throw p instanceof Re&&(p.context.metrics=r),p}finally{o!==void 0&&clearTimeout(o)}}};var yi=typeof globalThis=="object"?globalThis:global;var ut="1.9.0";var bi=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Sc(s){var e=new Set([s]),t=new Set,n=s.match(bi);if(!n)return function(){return!1};var r={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(r.prerelease!=null)return function(l){return l===s};function o(a){return t.add(a),!1}function i(a){return e.add(a),!0}return function(l){if(e.has(l))return!0;if(t.has(l))return!1;var c=l.match(bi);if(!c)return o(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||r.major!==u.major?o(l):r.major===0?r.minor===u.minor&&r.patch<=u.patch?i(l):o(l):r.minor<=u.minor?i(l):o(l)}}var Ii=Sc(ut);var Oc=ut.split(".")[0],vn=Symbol.for("opentelemetry.js.api."+Oc),Sn=yi;function $t(s,e,t,n){var r;n===void 0&&(n=!1);var o=Sn[vn]=(r=Sn[vn])!==null&&r!==void 0?r:{version:ut};if(!n&&o[s]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+s);return t.error(i.stack||i.message),!1}if(o.version!==ut){var i=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+s+" does not match previously registered API v"+ut);return t.error(i.stack||i.message),!1}return o[s]=e,t.debug("@opentelemetry/api: Registered a global for "+s+" v"+ut+"."),!0}function pt(s){var e,t,n=(e=Sn[vn])===null||e===void 0?void 0:e.version;if(!(!n||!Ii(n)))return(t=Sn[vn])===null||t===void 0?void 0:t[s]}function Gt(s,e){e.debug("@opentelemetry/api: Unregistering a global for "+s+" v"+ut+".");var t=Sn[vn];t&&delete t[s]}var kc=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Mc=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},Ti=function(){function s(e){this._namespace=e.namespace||"DiagComponentLogger"}return s.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return On("debug",this._namespace,e)},s.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return On("error",this._namespace,e)},s.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return On("info",this._namespace,e)},s.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return On("warn",this._namespace,e)},s.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return On("verbose",this._namespace,e)},s}();function On(s,e,t){var n=pt("diag");if(n)return t.unshift(e),n[s].apply(n,Mc([],kc(t),!1))}var we;(function(s){s[s.NONE=0]="NONE",s[s.ERROR=30]="ERROR",s[s.WARN=50]="WARN",s[s.INFO=60]="INFO",s[s.DEBUG=70]="DEBUG",s[s.VERBOSE=80]="VERBOSE",s[s.ALL=9999]="ALL"})(we||(we={}));function Ci(s,e){s<we.NONE?s=we.NONE:s>we.ALL&&(s=we.ALL),e=e||{};function t(n,r){var o=e[n];return typeof o=="function"&&s>=r?o.bind(e):function(){}}return{error:t("error",we.ERROR),warn:t("warn",we.WARN),info:t("info",we.INFO),debug:t("debug",we.DEBUG),verbose:t("verbose",we.VERBOSE)}}var Ec=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Pc=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},_c="diag",Lt=function(){function s(){function e(r){return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];var a=pt("diag");if(a)return a[r].apply(a,Pc([],Ec(o),!1))}}var t=this,n=function(r,o){var i,a,l;if(o===void 0&&(o={logLevel:we.INFO}),r===t){var c=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((i=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof o=="number"&&(o={logLevel:o});var u=pt("diag"),d=Ci((a=o.logLevel)!==null&&a!==void 0?a:we.INFO,r);if(u&&!o.suppressOverrideMessage){var p=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+p),d.warn("Current logger will overwrite one already registered from "+p)}return $t("diag",d,t,!0)};t.setLogger=n,t.disable=function(){Gt(_c,t)},t.createComponentLogger=function(r){return new Ti(r)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return s.instance=function(){return this._instance||(this._instance=new s),this._instance},s}();function Ri(s){return Symbol.for(s)}var Fc=function(){function s(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,r){var o=new s(t._currentContext);return o._currentContext.set(n,r),o},t.deleteValue=function(n){var r=new s(t._currentContext);return r._currentContext.delete(n),r}}return s}(),wi=new Fc;var Dc=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Nc=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},vi=function(){function s(){}return s.prototype.active=function(){return wi},s.prototype.with=function(e,t,n){for(var r=[],o=3;o<arguments.length;o++)r[o-3]=arguments[o];return t.call.apply(t,Nc([n],Dc(r),!1))},s.prototype.bind=function(e,t){return t},s.prototype.enable=function(){return this},s.prototype.disable=function(){return this},s}();var $c=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Gc=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},Ko="context",Lc=new vi,Ut=function(){function s(){}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalContextManager=function(e){return $t(Ko,e,Lt.instance())},s.prototype.active=function(){return this._getContextManager().active()},s.prototype.with=function(e,t,n){for(var r,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return(r=this._getContextManager()).with.apply(r,Gc([e,t,n],$c(o),!1))},s.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},s.prototype._getContextManager=function(){return pt(Ko)||Lc},s.prototype.disable=function(){this._getContextManager().disable(),Gt(Ko,Lt.instance())},s}();var xr;(function(s){s[s.NONE=0]="NONE",s[s.SAMPLED=1]="SAMPLED"})(xr||(xr={}));var Wo="0000000000000000",Vo="00000000000000000000000000000000",Si={traceId:Vo,spanId:Wo,traceFlags:xr.NONE};var xt=function(){function s(e){e===void 0&&(e=Si),this._spanContext=e}return s.prototype.spanContext=function(){return this._spanContext},s.prototype.setAttribute=function(e,t){return this},s.prototype.setAttributes=function(e){return this},s.prototype.addEvent=function(e,t){return this},s.prototype.addLink=function(e){return this},s.prototype.addLinks=function(e){return this},s.prototype.setStatus=function(e){return this},s.prototype.updateName=function(e){return this},s.prototype.end=function(e){},s.prototype.isRecording=function(){return!1},s.prototype.recordException=function(e,t){},s}();var Jo=Ri("OpenTelemetry Context Key SPAN");function yr(s){return s.getValue(Jo)||void 0}function Oi(){return yr(Ut.getInstance().active())}function kn(s,e){return s.setValue(Jo,e)}function ki(s){return s.deleteValue(Jo)}function Mi(s,e){return kn(s,new xt(e))}function br(s){var e;return(e=yr(s))===null||e===void 0?void 0:e.spanContext()}var Uc=/^([0-9a-f]{32})$/i,Bc=/^[0-9a-f]{16}$/i;function qc(s){return Uc.test(s)&&s!==Vo}function zc(s){return Bc.test(s)&&s!==Wo}function Ir(s){return qc(s.traceId)&&zc(s.spanId)}function Ei(s){return new xt(s)}var Yo=Ut.getInstance(),Tr=function(){function s(){}return s.prototype.startSpan=function(e,t,n){n===void 0&&(n=Yo.active());var r=!!t?.root;if(r)return new xt;var o=n&&br(n);return jc(o)&&Ir(o)?new xt(o):new xt},s.prototype.startActiveSpan=function(e,t,n,r){var o,i,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(o=t,a=n):(o=t,i=n,a=r);var l=i??Yo.active(),c=this.startSpan(e,o,l),u=kn(l,c);return Yo.with(u,a,void 0,c)}},s}();function jc(s){return typeof s=="object"&&typeof s.spanId=="string"&&typeof s.traceId=="string"&&typeof s.traceFlags=="number"}var Hc=new Tr,Pi=function(){function s(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return s.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},s.prototype.startActiveSpan=function(e,t,n,r){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},s.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):Hc},s}();var _i=function(){function s(){}return s.prototype.getTracer=function(e,t,n){return new Tr},s}();var Kc=new _i,Qo=function(){function s(){}return s.prototype.getTracer=function(e,t,n){var r;return(r=this.getDelegateTracer(e,t,n))!==null&&r!==void 0?r:new Pi(this,e,t,n)},s.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Kc},s.prototype.setDelegate=function(e){this._delegate=e},s.prototype.getDelegateTracer=function(e,t,n){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(e,t,n)},s}();var Me;(function(s){s[s.INTERNAL=0]="INTERNAL",s[s.SERVER=1]="SERVER",s[s.CLIENT=2]="CLIENT",s[s.PRODUCER=3]="PRODUCER",s[s.CONSUMER=4]="CONSUMER"})(Me||(Me={}));var yt=Ut.getInstance();var Zo="trace",Fi=function(){function s(){this._proxyTracerProvider=new Qo,this.wrapSpanContext=Ei,this.isSpanContextValid=Ir,this.deleteSpan=ki,this.getSpan=yr,this.getActiveSpan=Oi,this.getSpanContext=br,this.setSpan=kn,this.setSpanContext=Mi}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalTracerProvider=function(e){var t=$t(Zo,this._proxyTracerProvider,Lt.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},s.prototype.getTracerProvider=function(){return pt(Zo)||this._proxyTracerProvider},s.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},s.prototype.disable=function(){Gt(Zo,Lt.instance()),this._proxyTracerProvider=new Qo},s}();var Mn=Fi.getInstance();var ee={signatureStrict:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,abortSignal:void 0,cachingFunction:void 0,functionResultFormatter:s=>typeof s=="string"?s:s==null?"":JSON.stringify(s,null,2)};var ve=class{ANSI_WHITE_BRIGHT="\x1B[97m";ANSI_GREEN_BRIGHT="\x1B[92m";ANSI_BLUE_BRIGHT="\x1B[94m";ANSI_RED_BRIGHT="\x1B[91m";ANSI_YELLOW_BRIGHT="\x1B[93m";ANSI_YELLOW="\x1B[93m";ANSI_RED="\x1B[91m";ANSI_RESET="\x1B[0m";ANSI_ORANGE="\x1B[38;5;208m";ANSI_WHITE="\x1B[37m";ANSI_CYAN_BRIGHT="\x1B[96m";ANSI_MAGENTA_BRIGHT="\x1B[95m";ANSI_GRAY="\x1B[90m";ANSI_GREEN="\x1B[32m";ANSI_CYAN="\x1B[36m";ANSI_MAGENTA="\x1B[35m";ANSI_BLUE="\x1B[34m";ANSI_YELLOW_DIM="\x1B[33m";colorize(e,t){return`${t}${e}${this.ANSI_RESET}`}whiteBright(e){return this.colorize(e,this.ANSI_WHITE_BRIGHT)}greenBright(e){return this.colorize(e,this.ANSI_GREEN_BRIGHT)}blueBright(e){return this.colorize(e,this.ANSI_BLUE_BRIGHT)}redBright(e){return this.colorize(e,this.ANSI_RED_BRIGHT)}white(e){return this.colorize(e,this.ANSI_WHITE)}yellow(e){return this.colorize(e,this.ANSI_YELLOW)}yellowBright(e){return this.colorize(e,this.ANSI_YELLOW_BRIGHT)}red(e){return this.colorize(e,this.ANSI_RED)}orange(e){return this.colorize(e,this.ANSI_ORANGE)}cyanBright(e){return this.colorize(e,this.ANSI_CYAN_BRIGHT)}magentaBright(e){return this.colorize(e,this.ANSI_MAGENTA_BRIGHT)}gray(e){return this.colorize(e,this.ANSI_GRAY)}green(e){return this.colorize(e,this.ANSI_GREEN)}cyan(e){return this.colorize(e,this.ANSI_CYAN)}magenta(e){return this.colorize(e,this.ANSI_MAGENTA)}blue(e){return this.colorize(e,this.ANSI_BLUE)}yellowDim(e){return this.colorize(e,this.ANSI_YELLOW_DIM)}};var Gd=new ve,Di=s=>{console.log(s)},Ni=(s,e,t)=>{let n=(r,o)=>t&&o&&o in t?t[o](r):r;switch(s.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
|
|
15
15
|
${n(s.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
|
|
16
16
|
${n(s.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","greenBright")}
|
|
17
17
|
`;if(typeof s.content=="string")return r+n(s.content,"green");let o=s.content.map(i=>{if(i.type==="text")return n(i.text,"green");if(i.type==="image"){let a=e?"[Image]":`[Image: ${i.image}]`;return n(a,"green")}if(i.type==="audio"){let a=e?"[Audio]":`[Audio: ${i.data}]`;return n(a,"green")}return n("[Unknown content type]","gray")});return r+o.join(`
|
|
@@ -147,19 +147,19 @@ ${e}
|
|
|
147
147
|
`,n.value.forEach(o=>{r+=`- ${o.title||o.url}
|
|
148
148
|
`,o.description&&(r+=` ${o.description}
|
|
149
149
|
`)}),r+=`${e}
|
|
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"},Ye={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"},es=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(es||{}),ts=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(ts||{});var ns=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()}},Cr=class extends TransformStream{constructor(e,t){super(new ns(e,t))}};function Rr(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 Li=(s,e,t,n)=>{let r=n?s.filter(i=>i.role!=="system"):[...s];t({name:"ChatRequestChatPrompt",step:e,value:r})};var Ui=(s,e)=>{if(!s.results)return;let t={name:"ChatResponseResults",value:s.results};e(t)},Bi=(s,e,t)=>{t({name:"ChatResponseStreamingResult",index:e,value:s})};function qi(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?Rr(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 zi=(s,e)=>{e({name:"FunctionResults",value:s})},rs=(s,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:s})},ji=(s,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:s})},Hi=(s,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:s})},Ki=(s,e,t)=>{t({name:"RefusalError",index:e,error:s})};var Wi=(s,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:s})},Vi=(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)},Ji=(s,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:s,selectedIndex:e,latency:t})};var os=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},wr,Yi=s=>{if(wr)return wr;if(s)return wr=Wc(s),wr};var Wc=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)"})}),Qi=(s,e,t,n,r)=>{try{if(s.latencyHistogram){let o=os({operation:e,ai_service:n,...r?{model:r}:{}});s.latencyHistogram.record(t,o)}}catch(o){console.warn("Failed to record latency metric:",o)}},Zi=(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)},Xi=(s,e,t,n)=>{try{if(s.errorCounter){let r=os({operation:e,ai_service:t,...n?{model:n}:{}});s.errorCounter.add(1,r)}}catch(r){console.warn("Failed to record error metric:",r)}},ea=(s,e,t,n,r)=>{s.errorRateGauge&&s.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{}})},ta=(s,e,t,n)=>{s.requestCounter&&s.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Mn=(s,e,t,n,r)=>{try{let o=os({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)}},na=(s,e,t,n,r)=>{t&&s.streamingRequestsCounter&&s.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{}})},ra=(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)},ss=(s,e,t,n,r)=>{s.requestSizeHistogram&&s.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},is=(s,e,t,n,r)=>{s.responseSizeHistogram&&s.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},oa=(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)},as=(s,e,t,n,r)=>{s.estimatedCostCounter&&s.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{}})},sa=(s,e,t,n)=>{s.promptLengthHistogram&&s.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},ia=(s,e,t,n)=>{s.contextWindowUsageGauge&&s.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},aa=(s,e,t,n)=>{s.timeoutsCounter&&s.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},la=(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}:{}})},ua=(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 pa(s){try{return JSON.stringify(s,null,2)}catch{return String(s)}}function Qe(s,e={}){let t=[s];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${pa(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${pa(e.item)}`),new Error(t.join(`
|
|
151
|
-
`))}function Ut(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&&Qe("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"&&Qe("Assistant message content must be a string",{fieldPath:"content",value:n,item:s}),r!==void 0&&!Array.isArray(r)&&Qe("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")&&Qe("functionCalls entry must be an object",{fieldPath:`functionCalls[${a}]`,value:l,item:s}),(!("id"in l)||typeof l.id!="string"||l.id.trim()==="")&&Qe("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${a}].id`,value:l.id,item:s}),(!("type"in l)||l.type!=="function")&&Qe("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${a}].type`,value:l.type,item:s}),!("function"in l)||!l.function)Qe("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()==="")&&Qe("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"&&Qe("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()==="")&&Qe("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"&&Qe("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 vr(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 ee=()=>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??ce.tracer,this.meter=a.meter??ce.meter,this.modelInfo=o,this.models=c,this.id=be();let u=this.getModel(i.model)??i.model,p=this.getEmbedModel(i.embedModel)??i.embedModel;if(this.defaults={model:u,embedModel:p},!i.model||typeof i.model!="string"||i.model==="")throw new Error("No model defined");this.setOptions(a),c&&Jc(c)}#e=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=ce.logger??$i;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 Yi(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??ce.debug??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??ce.tracer,this.meter=e.meter??ce.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??ce.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;Qi(r,e,t,this.name,o),Zi(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;ta(r,e,this.name,o),t&&Xi(r,e,this.name,o),ea(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&&Mn(t,"input",n,this.name,e.model),r&&Mn(t,"output",r,this.name,e.model),o&&Mn(t,"total",o,this.name,e.model),i&&Mn(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&&ra(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;aa(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;la(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;na(r,"chat",a,this.name,o);let{hasImages:l,hasAudio:c}=this.detectMultimodalContent(e);ua(r,l,c,this.name,o);let u=this.calculatePromptLength(e);sa(r,u,this.name,o),oa(r,i?.temperature,i?.maxTokens,this.name,o),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&ca(r,this.modelUsage.tokens.thoughtsTokens,this.name,o);let p=this.calculateRequestSize(e);if(ss(r,"chat",p,this.name,o),n&&!a){let d=n,m=this.calculateResponseSize(d);if(is(r,"chat",m,this.name,o),d.results)for(let h of d.results)h.functionCalls&&this.recordFunctionCallMetrics(h.functionCalls,this.lastUsedChatModel);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,d.modelUsage);g>0&&ia(r,g,this.name,o);let f=this.estimateCost(this.lastUsedChatModel,d.modelUsage);f>0&&as(r,"chat",f,this.name,o)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let r=this.lastUsedEmbedModel,o=this.calculateRequestSize(e);ss(n,"embed",o,this.name,r);let i=this.calculateResponseSize(t);is(n,"embed",i,this.name,r);let a=this.estimateCostByName(r,t.modelUsage);a>0&&as(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)Ut(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:Me.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??xt.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(A=>this.cleanupFunctionSchema(A)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,i&&Li(l.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let c=this.getFeatures(e).functions,u=r?.functionCallMode??"auto",d=u==="prompt"||u==="auto"&&!c?{...l,chatPrompt:l.chatPrompt.map(A=>{if(A.role==="assistant"){let{content:x,name:b,cache:I}=A;return{role:"assistant",content:x,name:b,cache:I}}return A.role==="function"?{role:"user",content:A.result}:A}),functions:[]}:l,m=async()=>{let[A,x]=await this.aiImpl.createChatReq(d,r);return o?.isRecording()&&Vc(n,o,this.excludeContentFromTrace),await ke({name:A.name,url:this.apiURL,localCall:A.localCall,headers:await this.buildHeaders(A.headers),stream:t.stream,timeout:this.timeout,debug:i,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},x)},g=r?.rateLimiter??this.rt,f=g?await g(m,{modelUsage:this.modelUsage}):await m();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let A=this.aiImpl.createChatStreamResp.bind(this),x=R=>w=>{let S=A(w,R);if(S.sessionId=r?.sessionId,!S.modelUsage){let E=this.aiImpl.getTokenUsage();E&&(S.modelUsage={ai:this.name,model:e,tokens:E})}if(this.modelUsage=S.modelUsage,this.recordTokenUsage(S.modelUsage),o?.isRecording()&&da(S,o,this.excludeContentFromTrace),i)for(let E of S.results)Bi(E,E.index,r?.logger??this.logger);return S},b=async R=>{o?.isRecording()&&o.end(),i&&qi(R,r?.logger??this.logger)};if(typeof window<"u"){let R=f,w={},S=[],E=r?.abortSignal??this.abortSignal;return new ReadableStream({start:L=>{let P=R.getReader(),T=()=>{try{P.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat")}catch{}try{o?.isRecording()&&o.end()}catch{}try{L.error(new DOMException("Aborted","AbortError"))}catch{L.error(new Error("Aborted"))}};if(E){if(E.aborted){T();return}E.addEventListener("abort",T,{once:!0})}async function C(){try{for(;;){let{done:y,value:O}=await P.read();if(y){b&&await b(S),L.close();break}let v=x(w)(O);v&&(S.push(v),L.enqueue(v))}}catch(y){if(L.error(y),o?.isRecording())try{o.end()}catch{}}finally{if(P.releaseLock(),E)try{E.removeEventListener("abort",T)}catch{}}}C()}})}return f.pipeThrough(new Cr(x({}),b))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let h=this.aiImpl.createChatResp(f);if(h.sessionId=r?.sessionId,!h.modelUsage){let A=this.aiImpl.getTokenUsage();A&&(h.modelUsage={ai:this.name,model:e,tokens:A})}return h.modelUsage&&(this.modelUsage=h.modelUsage,this.recordTokenUsage(h.modelUsage)),o?.isRecording()&&(da(h,o,this.excludeContentFromTrace),o.end()),i&&Ui(h,r?.logger??this.logger),h}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:Me.SERVER,attributes:{[V.LLM_SYSTEM]:this.name,[V.LLM_OPERATION_NAME]:"embeddings",[V.LLM_REQUEST_MODEL]:n}},t?.traceContext??xt.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&&Wi(a.texts??[],e,n?.logger??this.logger);let l=async()=>{let[d,m]=await o(a);return await ke({name:d.name,url:this.apiURL,localCall:d.localCall,headers:await this.buildHeaders(d.headers),debug:i,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},m)},c=n?.rateLimiter??this.rt,u=c?await c(l,{modelUsage:this.embedModelUsage}):await l(),p=this.aiImpl.createEmbedResp?.(u);if(p.sessionId=n?.sessionId,!p.modelUsage){let d=this.aiImpl.getTokenUsage();d&&(p.modelUsage={ai:this.name,model:e,tokens:d})}return this.embedModelUsage=p.modelUsage,this.recordTokenUsage(p.modelUsage),r?.isRecording()&&p.modelUsage?.tokens&&r.addEvent(Ye.GEN_AI_USAGE,{[V.LLM_USAGE_INPUT_TOKENS]:p.modelUsage.tokens.promptTokens,[V.LLM_USAGE_OUTPUT_TOKENS]:p.modelUsage.tokens.completionTokens??0,[V.LLM_USAGE_TOTAL_TOKENS]:p.modelUsage.tokens.totalTokens}),i&&Vi(p.embeddings,n?.logger??this.logger),r?.end(),p}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}};function Vc(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(Ye.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(Ye.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(Ye.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:o.functionId};t||(i.content=o.result),e.addEvent(Ye.GEN_AI_TOOL_MESSAGE,i);break}}let r={};t||(r.content=n.join(`
|
|
152
|
-
`)),e.addEvent(Ye.GEN_AI_USER_MESSAGE,r)}function da(s,e,t){if(s.modelUsage?.tokens){let n=s.modelUsage.tokens.thoughtsTokens?{[V.LLM_USAGE_THOUGHTS_TOKENS]:s.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(Ye.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(Ye.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function ma(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 Jc(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 En=(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))(En||{}),Sr=(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))(Sr||{});var Pn=[{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 Or=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,Or(n)]))),e.items&&(e.items=Or(e.items)),e},cs=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...ee()}),ha=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...ee()}),ls=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,r=e.modelConfig?.stream??this.config.stream,o;this.isVertex?o={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:o={name:"/messages"};let i;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":i={tool_choice:{type:"auto"}};break;case"required":i={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)i={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.filter(w=>w.role==="system").map(w=>({type:"text",text:w.content,...w.cache?{cache_control:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(w=>w.role!=="system"),c=e.functions?.map(w=>({name:w.name,description:w.description,input_schema:w.parameters?Or(w.parameters):void 0})),p=(this.config.tools??[]).map(w=>w&&typeof w=="object"&&"type"in w?w:{name:w.name,description:w.description,input_schema:w.input_schema?Or(w.input_schema):void 0,...w.cache_control?{cache_control:w.cache_control}:{}}),d=[...c??[],...p];this.isVertex&&d.length>0&&(d=d.filter(w=>!(w&&typeof w=="object"&&"type"in w))),d.length===0&&(d=void 0);let m=e.modelConfig?.maxTokens??this.config.maxTokens,g=e.modelConfig?.stopSequences??this.config.stopSequences,f=e.modelConfig?.temperature,h=e.modelConfig?.topP,A=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 w=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":b=void 0;break;case"minimal":b={type:"enabled",budget_tokens:w?.minimal??1024};break;case"low":b={type:"enabled",budget_tokens:w?.low??5e3};break;case"medium":b={type:"enabled",budget_tokens:w?.medium??1e4};break;case"high":b={type:"enabled",budget_tokens:w?.high??2e4};break;case"highest":b={type:"enabled",budget_tokens:w?.highest??32e3};break}}if(!b&&t?.thinkingTokenBudget===void 0){let w=this.config.thinkingTokenBudgetLevels}let I=Yc(l,!!b);I.some(w=>w.role==="assistant"&&Array.isArray(w.content)&&w.content.length>0&&w.content[0]?.type==="tool_use")&&(b=void 0);let R={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...m?{max_tokens:m}:{},...g&&g.length>0?{stop_sequences:g}:{},...f!==void 0&&!b?{temperature:f}:{},...h!==void 0&&(!b||h>=.95)?{top_p:h}:{},...A&&!b?{top_k:A}:{},...i,...d?{tools:d}:{},...r?{stream:!0}:{},...a?{system:a}:{},...b?{thinking:b}:{},messages:I};return[o,R]};createChatResp=e=>{if(e.type==="error")throw new de(e.error.message,void 0,void 0);let t=ga(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o="",i=!1,a,l=[],c=[];for(let d of e.content)switch(d.type){case"text":if(r+=d.text??"",Array.isArray(d.citations))for(let m of d.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+=d.thinking??d.data??""),d.type==="redacted_thinking"&&(i=!0),typeof d.signature=="string"&&(a=d.signature);break;case"tool_use":l.push({id:d.id,type:"function",function:{name:d.name,params:d.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 p=[u];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens,cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens},{results:p,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)},{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,content:""}]};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:0,completionTokens:i.output_tokens,totalTokens:i.output_tokens},{results:[{index:r,content:"",finishReason:ga(o.stop_reason)}]}}return{results:[{index:r,content:""}]}}},Bt=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":"prompt-caching-2024-07-31","x-api-key":typeof e=="function"?await e():e})}let u={...cs(),...r},p=new ls(u,a),d=g=>{let f=Ue({model:g,modelInfo:Pn,models:i});return{functions:!0,streaming:!0,hasThinkingBudget:f?.supported?.thinkingBudget??!1,hasShowThoughts:f?.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:f?.supported?.thinkingBudget??!1,multiTurn:!0}},m=i?.map(g=>{let f=g,h=f?.config;if(!h)return g;let A={};h.maxTokens!==void 0&&(A.maxTokens=h.maxTokens),h.temperature!==void 0&&(A.temperature=h.temperature),h.topP!==void 0&&(A.topP=h.topP),h.topK!==void 0&&(A.topK=h.topK),h.presencePenalty!==void 0&&(A.presencePenalty=h.presencePenalty),h.frequencyPenalty!==void 0&&(A.frequencyPenalty=h.frequencyPenalty),h.stopSequences!==void 0&&(A.stopSequences=h.stopSequences),h.endSequences!==void 0&&(A.endSequences=h.endSequences),h.stream!==void 0&&(A.stream=h.stream),h.n!==void 0&&(A.n=h.n);let x={...f};Object.keys(A).length>0&&(x.modelConfig={...f.modelConfig??{},...A});let b=h.thinking?.thinkingTokenBudget;if(typeof b=="number"){let I=u.thinkingTokenBudgetLevels,M=[["minimal",I?.minimal??200],["low",I?.low??800],["medium",I?.medium??5e3],["high",I?.high??1e4],["highest",I?.highest??24500]],R="minimal",w=Number.POSITIVE_INFINITY;for(let[S,E]of M){let L=Math.abs(b-E);L<w&&(w=L,R=S)}x.thinkingTokenBudget=R}return h.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!h.thinking.includeThoughts),x});super(p,{name:"Anthropic",apiURL:l,headers:c,modelInfo:Pn,defaults:{model:u.model},options:o,supportFor:d,models:m??i})}};function Yc(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:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:i.mimeType,data:i.image},...i.cache?{cache:{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={};return typeof l.function.params=="string"?c=JSON.parse(l.function.params):typeof l.function.params=="object"&&(c=l.function.params),{type:"tool_use",id:l.id,name:l.function.name,input:c,...r.cache?{cache:{type:"ephemeral"}}:{}}}),Array.isArray(o)&&i.length>0&&(o=[...i,...o])),{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=Qc(t);return Zc(n)}function Qc(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 Zc(s){return s.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function ga(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 _n=(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))(_n||{}),qt=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(qt||{});var zt=(S=>(S.GPT4="gpt-4",S.GPT41="gpt-4.1",S.GPT41Mini="gpt-4.1-mini",S.GPT41Nano="gpt-4.1-nano",S.GPT4O="gpt-4o",S.GPT4OMini="gpt-4o-mini",S.GPT4ChatGPT4O="chatgpt-4o-latest",S.GPT4Turbo="gpt-4-turbo",S.GPT35Turbo="gpt-3.5-turbo",S.GPT35TurboInstruct="gpt-3.5-turbo-instruct",S.GPT35TextDavinci002="text-davinci-002",S.GPT3TextBabbage002="text-babbage-002",S.GPT3TextAda001="text-ada-001",S.GPT5="gpt-5",S.GPT5Nano="gpt-5-nano",S.GPT5Mini="gpt-5-mini",S.GPT5Chat="gpt-5-chat",S.O1Pro="o1-pro",S.O1="o1",S.O1Mini="o1-mini",S.O3Pro="o3-pro",S.O3="o3",S.O3Mini="o3-mini",S.O4Mini="o4-mini",S))(zt||{});var jt=[{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}],kr=[{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 Xc=s=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(s)||e.includes(s)},St=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...ee()}),Mr=()=>structuredClone({...St(),model:"gpt-5"}),Er=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Ae()}),Pr=()=>({...St(),model:"gpt-5-nano"}),us=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=eu(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,p=Xc(n),d={model:n,messages:a,...this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...i?{tool_choice:i}:{},...p?{}:{...(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&&(d.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(d.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":d.reasoning_effort=void 0;break;case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":d.reasoning_effort="high";break;case"high":d.reasoning_effort="high";break;case"highest":d.reasoning_effort="high";break}if(!d.reasoning_effort&&t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":case"high":case"highest":d.reasoning_effort="high";break}return this.chatReqUpdater&&(d=this.chatReqUpdater(d)),[r,d]};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=fa(a.finish_reason),c=a.message.tool_calls?.map(({id:u,function:{arguments:p,name:d}})=>({id:u,type:"function",function:{name:d,params:p}}));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:p,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:f})=>{if(p)throw new de(p,void 0,n);let h=fa(f),A=d?.map(({id:x,index:b,function:{name:I,arguments:M}})=>{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:I,params:M}}:null}).filter(x=>x!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:g?.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:A,finishReason:h,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)}}},fa=s=>{switch(s){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function eu(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 us(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})}},Ht=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=[...jt,...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,p=u?.config;if(!p)return c;let d={};p.maxTokens!==void 0&&(d.maxTokens=p.maxTokens),p.temperature!==void 0&&(d.temperature=p.temperature),p.topP!==void 0&&(d.topP=p.topP),p.presencePenalty!==void 0&&(d.presencePenalty=p.presencePenalty),p.frequencyPenalty!==void 0&&(d.frequencyPenalty=p.frequencyPenalty);let m=p.stopSequences??p.stop;m!==void 0&&(d.stopSequences=m),p.n!==void 0&&(d.n=p.n),p.stream!==void 0&&(d.stream=p.stream);let g={...u};Object.keys(d).length>0&&(g.modelConfig={...u.modelConfig??{},...d});let f=p?.thinking?.thinkingTokenBudget;if(typeof f=="number"){let h=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],A="minimal",x=Number.POSITIVE_INFINITY;for(let[b,I]of h){let M=Math.abs(f-I);M<x&&(x=M,A=b)}g.thinkingTokenBudget=A}return p?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!p.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...St(),...n},options:r,modelInfo:i,models:l??o,supportFor:a}),super.setName("OpenAI")}};var ps=St,Aa=Er,xa=Pr,ya=Mr,Kt=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={...ps(),...o};l=[...jt,...l??[]];let u=d=>{let m=Ue({model:d,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 p=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${r}`,p).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.");tu(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 Re))throw n;switch(n.constructor){case ft:throw n;case wt:break;case et:break;case lt:break;case Ve:break;case vt: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 Re)||!this.handleFailure(n))throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function tu(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 Ot(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 p of u.content)switch(l.add(p.type),p.type){case"image":e=!0,p.cache&&(a=!0),c+=85;break;case"audio":t=!0,p.cache&&(a=!0),c+=p.duration||60;break;case"file":n=!0,p.cache&&(a=!0),c+=Math.ceil((p.extractedText?.length||1e3)/4);break;case"url":r=!0,p.cache&&(a=!0),c+=Math.ceil((p.cachedContent?.length||2e3)/4);break;case"text":p.cache&&(a=!0),c+=Math.ceil(p.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 ds(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 Fr(s,e){return s.map(t=>{let n=t.getFeatures(),r=ds(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 Dr(s,e,t={}){if(e.length===0)throw new Error("No providers available");let n=Ot(s),r=Fr(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 ba(s,e){let t=Ot(s),n=Fr(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 Ia(s,e){return s.filter(t=>t.getFeatures().media[e].supported)}function Ta(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 Fn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Fn||{}),Dn=(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))(Dn||{});var Nr=[{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 gs=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...ee()}),Ra=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Ae()}),ms=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=nu(r),a=e.functions?.map(p=>{let d={};if(p.parameters?.properties)for(let[m,g]of Object.entries(p.parameters.properties))d[m]={description:g.description,type:g.type,required:p.parameters.required?.includes(m)??!1};return{name:p.name,description:p.description,parameter_definitions:d}}),l=e.chatPrompt.filter(p=>p.role==="function").map(p=>{let d=a?.find(m=>m.name===p.functionId);if(!d)throw new Error("Function not found");return{call:{name:d.name,parameters:d.parameter_definitions},outputs:[{result:p.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}}},Wt=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={...gs(),...t},i=new ms(o),a=r?.map(l=>{let c=l,u=c?.config;if(!u)return l;let p={};u.maxTokens!==void 0&&(p.maxTokens=u.maxTokens),u.temperature!==void 0&&(p.temperature=u.temperature),u.topP!==void 0&&(p.topP=u.topP),u.topK!==void 0&&(p.topK=u.topK),u.presencePenalty!==void 0&&(p.presencePenalty=u.presencePenalty),u.frequencyPenalty!==void 0&&(p.frequencyPenalty=u.frequencyPenalty),u.stopSequences!==void 0&&(p.stopSequences=u.stopSequences),u.endSequences!==void 0&&(p.endSequences=u.endSequences),u.stream!==void 0&&(p.stream=u.stream),u.n!==void 0&&(p.n=u.n);let d={...c};return Object.keys(p).length>0&&(d.modelConfig={...c.modelConfig??{},...p}),d});super(i,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Nr,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 nu(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=Ca(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=Ca(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 Ca(s){return s?.map(e=>{let t=typeof e.function.params=="string"?JSON.parse(e.function.params):e.function.params;return{name:e.function.name,parameters:t}})}var Nn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Nn||{});var $r=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var hs=()=>structuredClone({model:"deepseek-chat",...ee()}),wa=()=>structuredClone({model:"deepseek-coder",...Ae()}),Vt=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={...hs(),...t};o=[...$r,...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 $n=(m=>(m.Gemini25Pro="gemini-2.5-pro",m.Gemini25Flash="gemini-2.5-flash",m.Gemini25FlashLite="gemini-2.5-flash-lite",m.Gemini20Flash="gemini-2.0-flash",m.Gemini20FlashLite="gemini-2.0-flash-lite",m.Gemini1Pro="gemini-1.0-pro",m.Gemini15Flash="gemini-1.5-flash",m.Gemini15Flash002="gemini-1.5-flash-002",m.Gemini15Flash8B="gemini-1.5-flash-8b",m.Gemini15Pro="gemini-1.5-pro",m.GeminiFlashLatest="gemini-flash-latest",m.GeminiFlashLiteLatest="gemini-flash-lite-latest",m.GeminiProLatest="gemini-pro-latest",m))($n||{}),Gr=(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))(Gr||{}),Lr=(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))(Lr||{}),Ur=(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))(Ur||{}),fs=(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))(fs||{});var Br=[{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,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 As=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,As(n)]))),e.items&&(e.items=As(e.items)),e},va=[{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"}],ys=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:va,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...ee()}),Sa=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:va,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Ae()}),xs=class{constructor(e,t,n,r,o){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=o;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o;if(this.endpointId?o={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:o={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let h=r?"&":"?",A=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${h}key=${A}`}let i=e.chatPrompt.filter(h=>h.role==="system").map(h=>h.content),a=i.length>0?{role:"user",parts:[{text:i.join(" ")}]}:void 0,l=e.chatPrompt.filter(h=>h.role!=="system").map((h,A)=>{switch(h.role){case"user":return{role:"user",parts:Array.isArray(h.content)?h.content.map((b,I)=>{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: ${I})`)}}):[{text:h.content}]};case"assistant":{let x=[];if(h.functionCalls){if(x=h.functionCalls.map(b=>{let I=typeof b.function.params=="string"?JSON.parse(b.function.params):b.function.params;return{functionCall:{name:b.function.name,args:I}}}),!x)throw new Error("Function call is empty");return{role:"model",parts:x}}if(!h.content)throw new Error("Assistant content is empty");return x=[{text:h.content}],{role:"model",parts:x}}case"function":{if(!("functionId"in h))throw new Error(`Chat prompt functionId is empty (index: ${A})`);return{role:"user",parts:[{functionResponse:{name:h.functionId,response:{result:h.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(h)} (index: ${A})`)}}),c=[];if(e.functions&&e.functions.length>0){let h=e.functions.map(A=>({...A,parameters:A.parameters?As(A.parameters):void 0}));c.push({function_declarations:h})}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 h=this.options.googleMaps,A=h?.enableWidget!==void 0?{enableWidget:h.enableWidget}:{};c.push({google_maps:A})}this.options?.urlContext&&c.push({url_context:{}}),c.length===0&&(c=void 0);let u,p=Array.isArray(c)?c.some(h=>h&&Array.isArray(h.function_declarations)&&h.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 h=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};u={function_calling_config:{mode:"ANY"},...h}}else p&&(u={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(u={...u??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let d={};if(this.config.thinking?.includeThoughts&&(d.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(d.thinkingBudget=this.config.thinking.thinkingTokenBudget),t?.thinkingTokenBudget){let h=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":d.thinkingBudget=0,d.includeThoughts=!1;break;case"minimal":d.thinkingBudget=h?.minimal??200;break;case"low":d.thinkingBudget=h?.low??800;break;case"medium":d.thinkingBudget=h?.medium??5e3;break;case"high":d.thinkingBudget=h?.high??1e4;break;case"highest":d.thinkingBudget=h?.highest??24500;break}}t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(d.includeThoughts=t.showThoughts);let 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(d).length>0?{thinkingConfig:d}:{}},g=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:u,systemInstruction:a,generationConfig:m,safetySettings:g}]};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?i.thought=c.text:i.content=c.text;continue}"functionCall"in c&&(i.functionCalls=[{id:be(),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}}},Jt=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,p;if(c){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let h;r?h="endpoints":h="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${h}`,p=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",p=async()=>({})}let d={...ys(),...o},m=new xs(d,c,r,e,i);l=[...Br,...l??[]];let g=h=>{let A=Ue({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:A?.supported?.thinkingBudget??!1,hasShowThoughts:A?.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:A?.supported?.thinkingBudget??!1,multiTurn:!0}},f=a?.map(h=>{let A=h,x=A?.config;if(!x)return h;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 I={...A};Object.keys(b).length>0&&(I.modelConfig={...A.modelConfig??{},...b});let M=x.thinking?.thinkingTokenBudget;if(typeof M=="number"){let R=d.thinkingTokenBudgetLevels,w=[["minimal",R?.minimal??200],["low",R?.low??800],["medium",R?.medium??5e3],["high",R?.high??1e4],["highest",R?.highest??24500]],S="minimal",E=Number.POSITIVE_INFINITY;for(let[L,P]of w){let T=Math.abs(M-P);T<E&&(E=T,S=L)}I.thinkingTokenBudget=S}return x.thinking?.includeThoughts!==void 0&&(I.showThoughts=!!x.thinking.includeThoughts),I});super(m,{name:"GoogleGeminiAI",apiURL:u,headers:p,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:i,supportFor:g,models:f??a})}};var ru=new ve,Yt=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(ru.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 Gn=(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))(Gn||{});var qr=[{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 ou=()=>structuredClone({model:"llama-3.3-70b-versatile",...ee()}),Qt=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={...ou(),...t},a={...n,streamingUsage:!1};o=[...qr,...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 Yt(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 zr=[];var jr=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(jr||{});var Is=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...ee()}),Oa=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Ae()}),bs=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:
|
|
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"},Qe={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"},es=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(es||{}),ts=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(ts||{});var ns=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()}},Cr=class extends TransformStream{constructor(e,t){super(new ns(e,t))}};function Rr(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 Li=(s,e,t,n)=>{let r=n?s.filter(i=>i.role!=="system"):[...s];t({name:"ChatRequestChatPrompt",step:e,value:r})};var Ui=(s,e)=>{if(!s.results)return;let t={name:"ChatResponseResults",value:s.results};e(t)},Bi=(s,e,t)=>{t({name:"ChatResponseStreamingResult",index:e,value:s})};function qi(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?Rr(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 zi=(s,e)=>{e({name:"FunctionResults",value:s})},rs=(s,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:s})},ji=(s,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:s})},Hi=(s,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:s})},Ki=(s,e,t)=>{t({name:"RefusalError",index:e,error:s})};var Wi=(s,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:s})},Vi=(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)},Ji=(s,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:s,selectedIndex:e,latency:t})};var os=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},wr,Yi=s=>{if(wr)return wr;if(s)return wr=Wc(s),wr};var Wc=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)"})}),Qi=(s,e,t,n,r)=>{try{if(s.latencyHistogram){let o=os({operation:e,ai_service:n,...r?{model:r}:{}});s.latencyHistogram.record(t,o)}}catch(o){console.warn("Failed to record latency metric:",o)}},Zi=(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)},Xi=(s,e,t,n)=>{try{if(s.errorCounter){let r=os({operation:e,ai_service:t,...n?{model:n}:{}});s.errorCounter.add(1,r)}}catch(r){console.warn("Failed to record error metric:",r)}},ea=(s,e,t,n,r)=>{s.errorRateGauge&&s.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{}})},ta=(s,e,t,n)=>{s.requestCounter&&s.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},En=(s,e,t,n,r)=>{try{let o=os({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)}},na=(s,e,t,n,r)=>{t&&s.streamingRequestsCounter&&s.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{}})},ra=(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)},ss=(s,e,t,n,r)=>{s.requestSizeHistogram&&s.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},is=(s,e,t,n,r)=>{s.responseSizeHistogram&&s.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},oa=(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)},as=(s,e,t,n,r)=>{s.estimatedCostCounter&&s.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{}})},sa=(s,e,t,n)=>{s.promptLengthHistogram&&s.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},ia=(s,e,t,n)=>{s.contextWindowUsageGauge&&s.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},aa=(s,e,t,n)=>{s.timeoutsCounter&&s.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},la=(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}:{}})},ua=(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 pa(s){try{return JSON.stringify(s,null,2)}catch{return String(s)}}function Ze(s,e={}){let t=[s];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${pa(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${pa(e.item)}`),new Error(t.join(`
|
|
151
|
+
`))}function Bt(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&&Ze("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"&&Ze("Assistant message content must be a string",{fieldPath:"content",value:n,item:s}),r!==void 0&&!Array.isArray(r)&&Ze("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")&&Ze("functionCalls entry must be an object",{fieldPath:`functionCalls[${a}]`,value:l,item:s}),(!("id"in l)||typeof l.id!="string"||l.id.trim()==="")&&Ze("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${a}].id`,value:l.id,item:s}),(!("type"in l)||l.type!=="function")&&Ze("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${a}].type`,value:l.type,item:s}),!("function"in l)||!l.function)Ze("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()==="")&&Ze("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"&&Ze("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()==="")&&Ze("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"&&Ze("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 vr(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}),he=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=be();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&&Jc(c)}#e=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=ee.logger??$i;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 Yi(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;Qi(r,e,t,this.name,o),Zi(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;ta(r,e,this.name,o),t&&Xi(r,e,this.name,o),ea(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&&En(t,"input",n,this.name,e.model),r&&En(t,"output",r,this.name,e.model),o&&En(t,"total",o,this.name,e.model),i&&En(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&&ra(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;aa(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;la(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;na(r,"chat",a,this.name,o);let{hasImages:l,hasAudio:c}=this.detectMultimodalContent(e);ua(r,l,c,this.name,o);let u=this.calculatePromptLength(e);sa(r,u,this.name,o),oa(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(ss(r,"chat",d,this.name,o),n&&!a){let p=n,m=this.calculateResponseSize(p);if(is(r,"chat",m,this.name,o),p.results)for(let f of p.results)f.functionCalls&&this.recordFunctionCallMetrics(f.functionCalls,this.lastUsedChatModel);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,p.modelUsage);g>0&&ia(r,g,this.name,o);let h=this.estimateCost(this.lastUsedChatModel,p.modelUsage);h>0&&as(r,"chat",h,this.name,o)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let r=this.lastUsedEmbedModel,o=this.calculateRequestSize(e);ss(n,"embed",o,this.name,r);let i=this.calculateResponseSize(t);is(n,"embed",i,this.name,r);let a=this.estimateCostByName(r,t.modelUsage);a>0&&as(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)Bt(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:Me.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??yt.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(A=>this.cleanupFunctionSchema(A)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,i&&Li(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(A=>{if(A.role==="assistant"){let{content:x,name:y,cache:I}=A;return{role:"assistant",content:x,name:y,cache:I}}return A.role==="function"?{role:"user",content:A.result}:A}),functions:[]}:l,m=async()=>{let[A,x]=await this.aiImpl.createChatReq(p,r);return o?.isRecording()&&Vc(n,o,this.excludeContentFromTrace),await ke({name:A.name,url:this.apiURL,localCall:A.localCall,headers:await this.buildHeaders(A.headers),stream:t.stream,timeout:this.timeout,debug:i,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},x)},g=r?.rateLimiter??this.rt,h=g?await g(m,{modelUsage:this.modelUsage}):await m();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let A=this.aiImpl.createChatStreamResp.bind(this),x=C=>T=>{let v=A(T,C);if(v.sessionId=r?.sessionId,!v.modelUsage){let k=this.aiImpl.getTokenUsage();k&&(v.modelUsage={ai:this.name,model:e,tokens:k})}if(this.modelUsage=v.modelUsage,this.recordTokenUsage(v.modelUsage),o?.isRecording()&&da(v,o,this.excludeContentFromTrace),i)for(let k of v.results)Bi(k,k.index,r?.logger??this.logger);return v},y=async C=>{o?.isRecording()&&o.end(),i&&qi(C,r?.logger??this.logger)};if(typeof window<"u"){let C=h,T={},v=[],k=r?.abortSignal??this.abortSignal;return new ReadableStream({start:L=>{let P=C.getReader(),R=()=>{try{P.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat")}catch{}try{o?.isRecording()&&o.end()}catch{}try{L.error(new DOMException("Aborted","AbortError"))}catch{L.error(new Error("Aborted"))}};if(k){if(k.aborted){R();return}k.addEventListener("abort",R,{once:!0})}async function w(){try{for(;;){let{done:b,value:O}=await P.read();if(b){y&&await y(v),L.close();break}let S=x(T)(O);S&&(v.push(S),L.enqueue(S))}}catch(b){if(L.error(b),o?.isRecording())try{o.end()}catch{}}finally{if(P.releaseLock(),k)try{k.removeEventListener("abort",R)}catch{}}}w()}})}return h.pipeThrough(new Cr(x({}),y))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let f=this.aiImpl.createChatResp(h);if(f.sessionId=r?.sessionId,!f.modelUsage){let A=this.aiImpl.getTokenUsage();A&&(f.modelUsage={ai:this.name,model:e,tokens:A})}return f.modelUsage&&(this.modelUsage=f.modelUsage,this.recordTokenUsage(f.modelUsage)),o?.isRecording()&&(da(f,o,this.excludeContentFromTrace),o.end()),i&&Ui(f,r?.logger??this.logger),f}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:Me.SERVER,attributes:{[V.LLM_SYSTEM]:this.name,[V.LLM_OPERATION_NAME]:"embeddings",[V.LLM_REQUEST_MODEL]:n}},t?.traceContext??yt.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&&Wi(a.texts??[],e,n?.logger??this.logger);let l=async()=>{let[p,m]=await o(a);return await ke({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(Qe.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&&Vi(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 Vc(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(Qe.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(Qe.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(Qe.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:o.functionId};t||(i.content=o.result),e.addEvent(Qe.GEN_AI_TOOL_MESSAGE,i);break}}let r={};t||(r.content=n.join(`
|
|
152
|
+
`)),e.addEvent(Qe.GEN_AI_USER_MESSAGE,r)}function da(s,e,t){if(s.modelUsage?.tokens){let n=s.modelUsage.tokens.thoughtsTokens?{[V.LLM_USAGE_THOUGHTS_TOKENS]:s.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(Qe.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(Qe.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function ma(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 Jc(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 Pn=(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))(Pn||{}),Sr=(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))(Sr||{});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 Or=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,Or(n)]))),e.items&&(e.items=Or(e.items)),e},cs=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...te()}),fa=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...te()}),ls=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,r=e.modelConfig?.stream??this.config.stream,o;this.isVertex?o={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:o={name:"/messages"};let i;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":i={tool_choice:{type:"auto"}};break;case"required":i={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)i={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.filter(T=>T.role==="system").map(T=>({type:"text",text:T.content,...T.cache?{cache_control:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(T=>T.role!=="system"),c=e.functions?.map(T=>{let v={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},k=T.parameters?Or(T.parameters):void 0;return k===void 0||k&&typeof k=="object"&&Object.keys(k).length===0?k={...v}:k&&typeof k=="object"&&k.type==="object"&&(!("properties"in k)||!k.properties||Object.keys(k.properties).length===0)&&(k={...k,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:T.name,description:T.description,input_schema:k}}),d=(this.config.tools??[]).map(T=>T&&typeof T=="object"&&"type"in T?T:{name:T.name,description:T.description,input_schema:T.input_schema?Or(T.input_schema):void 0,...T.cache_control?{cache_control:T.cache_control}:{}}),p=[...c??[],...d];this.isVertex&&p.length>0&&(p=p.filter(T=>!(T&&typeof T=="object"&&"type"in T))),p.length===0&&(p=void 0);let m=e.modelConfig?.maxTokens??this.config.maxTokens,g=e.modelConfig?.stopSequences??this.config.stopSequences,h=e.modelConfig?.temperature,f=e.modelConfig?.topP,A=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 y;if(this.config.thinking?.budget_tokens&&(y=this.config.thinking),t?.thinkingTokenBudget){let T=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":y=void 0;break;case"minimal":y={type:"enabled",budget_tokens:T?.minimal??1024};break;case"low":y={type:"enabled",budget_tokens:T?.low??5e3};break;case"medium":y={type:"enabled",budget_tokens:T?.medium??1e4};break;case"high":y={type:"enabled",budget_tokens:T?.high??2e4};break;case"highest":y={type:"enabled",budget_tokens:T?.highest??32e3};break}}if(!y&&t?.thinkingTokenBudget===void 0){let T=this.config.thinkingTokenBudgetLevels}let I=Yc(l,!!y);I.some(T=>T.role==="assistant"&&Array.isArray(T.content)&&T.content.length>0&&T.content[0]?.type==="tool_use")&&(y=void 0);let C={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...m?{max_tokens:m}:{},...g&&g.length>0?{stop_sequences:g}:{},...h!==void 0&&!y?{temperature:h}:{},...f!==void 0&&(!y||f>=.95)?{top_p:f}:{},...A&&!y?{top_k:A}:{},...i,...p?{tools:p}:{},...r?{stream:!0}:{},...a?{system:a}:{},...y?{thinking:y}:{},messages:I};return[o,C]};createChatResp=e=>{if(e.type==="error")throw new de(e.error.message,void 0,void 0);let t=ga(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,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)},{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,content:""}]};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:0,completionTokens:i.output_tokens,totalTokens:i.output_tokens},{results:[{index:r,content:"",finishReason:ga(o.stop_reason)}]}}return{results:[{index:r,content:""}]}}},qt=class s extends he{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":"prompt-caching-2024-07-31","x-api-key":typeof e=="function"?await e():e})}let u={...cs(),...r},d=new ls(u,a),p=g=>{let h=Ue({model:g,modelInfo:_n,models:i});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.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:h?.supported?.thinkingBudget??!1,multiTurn:!0}},m=i?.map(g=>{let h=g,f=h?.config;if(!f)return g;let A={};f.maxTokens!==void 0&&(A.maxTokens=f.maxTokens),f.temperature!==void 0&&(A.temperature=f.temperature),f.topP!==void 0&&(A.topP=f.topP),f.topK!==void 0&&(A.topK=f.topK),f.presencePenalty!==void 0&&(A.presencePenalty=f.presencePenalty),f.frequencyPenalty!==void 0&&(A.frequencyPenalty=f.frequencyPenalty),f.stopSequences!==void 0&&(A.stopSequences=f.stopSequences),f.endSequences!==void 0&&(A.endSequences=f.endSequences),f.stream!==void 0&&(A.stream=f.stream),f.n!==void 0&&(A.n=f.n);let x={...h};Object.keys(A).length>0&&(x.modelConfig={...h.modelConfig??{},...A});let y=f.thinking?.thinkingTokenBudget;if(typeof y=="number"){let I=u.thinkingTokenBudgetLevels,E=[["minimal",I?.minimal??200],["low",I?.low??800],["medium",I?.medium??5e3],["high",I?.high??1e4],["highest",I?.highest??24500]],C="minimal",T=Number.POSITIVE_INFINITY;for(let[v,k]of E){let L=Math.abs(y-k);L<T&&(T=L,C=v)}x.thinkingTokenBudget=C}return f.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!f.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 Yc(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:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:i.mimeType,data:i.image},...i.cache?{cache:{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:{type:"ephemeral"}}:{}}}),Array.isArray(o)&&i.length>0&&(o=[...i,...o])),{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=Qc(t);return Zc(n)}function Qc(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 Zc(s){return s.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function ga(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 Fn=(C=>(C.GPT4="gpt-4",C.GPT41="gpt-4.1",C.GPT41Mini="gpt-4.1-mini",C.GPT41Nano="gpt-4.1-nano",C.GPT4O="gpt-4o",C.GPT4OMini="gpt-4o-mini",C.GPT4ChatGPT4O="chatgpt-4o-latest",C.GPT4Turbo="gpt-4-turbo",C.GPT35Turbo="gpt-3.5-turbo",C.GPT35TurboInstruct="gpt-3.5-turbo-instruct",C.GPT35TextDavinci002="text-davinci-002",C.GPT3TextBabbage002="text-babbage-002",C.GPT3TextAda001="text-ada-001",C.GPT5="gpt-5",C.GPT5Nano="gpt-5-nano",C.GPT5Mini="gpt-5-mini",C.GPT5Chat="gpt-5-chat",C.O1="o1",C.O1Mini="o1-mini",C.O3="o3",C.O3Mini="o3-mini",C.O4Mini="o4-mini",C))(Fn||{}),zt=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(zt||{});var jt=(v=>(v.GPT4="gpt-4",v.GPT41="gpt-4.1",v.GPT41Mini="gpt-4.1-mini",v.GPT41Nano="gpt-4.1-nano",v.GPT4O="gpt-4o",v.GPT4OMini="gpt-4o-mini",v.GPT4ChatGPT4O="chatgpt-4o-latest",v.GPT4Turbo="gpt-4-turbo",v.GPT35Turbo="gpt-3.5-turbo",v.GPT35TurboInstruct="gpt-3.5-turbo-instruct",v.GPT35TextDavinci002="text-davinci-002",v.GPT3TextBabbage002="text-babbage-002",v.GPT3TextAda001="text-ada-001",v.GPT5="gpt-5",v.GPT5Nano="gpt-5-nano",v.GPT5Mini="gpt-5-mini",v.GPT5Chat="gpt-5-chat",v.O1Pro="o1-pro",v.O1="o1",v.O1Mini="o1-mini",v.O3Pro="o3-pro",v.O3="o3",v.O3Mini="o3-mini",v.O4Mini="o4-mini",v))(jt||{});var Ht=[{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}],kr=[{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 Xc=s=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(s)||e.includes(s)},Ot=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...te()}),Mr=()=>structuredClone({...Ot(),model:"gpt-5"}),Er=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Ae()}),Pr=()=>({...Ot(),model:"gpt-5-nano"}),us=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=eu(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,d=Xc(n),p={model:n,messages:a,...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=ha(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:g},finish_reason:h})=>{if(d)throw new de(d,void 0,n);let f=ha(h),A=p?.map(({id:x,index:y,function:{name:I,arguments:E}})=>{typeof x=="string"&&typeof y=="number"&&!i.indexIdMap[y]&&(i.indexIdMap[y]=x);let C=i.indexIdMap[y];return C?{id:C,type:"function",function:{name:I,params:E}}:null}).filter(x=>x!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:g?.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:A,finishReason:f,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(r=>r.embedding)}}},ha=s=>{switch(s){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function eu(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 fe=class extends he{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 us(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})}},Kt=class extends fe{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=[...Ht,...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 g={...u};Object.keys(p).length>0&&(g.modelConfig={...u.modelConfig??{},...p});let h=d?.thinking?.thinkingTokenBudget;if(typeof h=="number"){let f=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],A="minimal",x=Number.POSITIVE_INFINITY;for(let[y,I]of f){let E=Math.abs(h-I);E<x&&(x=E,A=y)}g.thinkingTokenBudget=A}return d?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!d.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...Ot(),...n},options:r,modelInfo:i,models:l??o,supportFor:a}),super.setName("OpenAI")}};var ps=Ot,Aa=Er,xa=Pr,ya=Mr,Wt=class extends fe{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={...ps(),...o};l=[...Ht,...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.");tu(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 Re))throw n;switch(n.constructor){case At:throw n;case vt:break;case tt:break;case ct:break;case Je:break;case St: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 Re)||!this.handleFailure(n))throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function tu(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 kt(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 ds(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 Fr(s,e){return s.map(t=>{let n=t.getFeatures(),r=ds(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 Dr(s,e,t={}){if(e.length===0)throw new Error("No providers available");let n=kt(s),r=Fr(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 ba(s,e){let t=kt(s),n=Fr(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 Ia(s,e){return s.filter(t=>t.getFeatures().media[e].supported)}function Ta(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 Dn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Dn||{}),Nn=(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))(Nn||{});var Nr=[{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 gs=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...te()}),Ra=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Ae()}),ms=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=nu(r),a=e.functions?.map(d=>{let p={};if(d.parameters?.properties)for(let[m,g]of Object.entries(d.parameters.properties))p[m]={description:g.description,type:g.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}}},Vt=class extends he{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...gs(),...t},i=new ms(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:Nr,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 nu(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=Ca(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=Ca(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 Ca(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 $n=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))($n||{});var $r=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var fs=()=>structuredClone({model:"deepseek-chat",...te()}),wa=()=>structuredClone({model:"deepseek-coder",...Ae()}),Jt=class extends fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...fs(),...t};o=[...$r,...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 Gn=(m=>(m.Gemini25Pro="gemini-2.5-pro",m.Gemini25Flash="gemini-2.5-flash",m.Gemini25FlashLite="gemini-2.5-flash-lite",m.Gemini20Flash="gemini-2.0-flash",m.Gemini20FlashLite="gemini-2.0-flash-lite",m.Gemini1Pro="gemini-1.0-pro",m.Gemini15Flash="gemini-1.5-flash",m.Gemini15Flash002="gemini-1.5-flash-002",m.Gemini15Flash8B="gemini-1.5-flash-8b",m.Gemini15Pro="gemini-1.5-pro",m.GeminiFlashLatest="gemini-flash-latest",m.GeminiFlashLiteLatest="gemini-flash-lite-latest",m.GeminiProLatest="gemini-pro-latest",m))(Gn||{}),Gr=(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))(Gr||{}),Lr=(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))(Lr||{}),Ur=(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))(Ur||{}),hs=(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))(hs||{});var Br=[{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,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 As=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,As(n)]))),e.items&&(e.items=As(e.items)),e},va=[{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"}],ys=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:va,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...te()}),Sa=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:va,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Ae()}),xs=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 f=r?"&":"?",A=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${f}key=${A}`}let i=e.chatPrompt.filter(f=>f.role==="system").map(f=>f.content),a=i.length>0?{role:"user",parts:[{text:i.join(" ")}]}:void 0,l=e.chatPrompt.filter(f=>f.role!=="system").map((f,A)=>{switch(f.role){case"user":return{role:"user",parts:Array.isArray(f.content)?f.content.map((y,I)=>{switch(y.type){case"text":return{text:y.text};case"image":return{inlineData:{mimeType:y.mimeType,data:y.image}};case"audio":return{inlineData:{mimeType:`audio/${y.format??"mp3"}`,data:y.data}};case"file":return"fileUri"in y?{fileData:{mimeType:y.mimeType,fileUri:y.fileUri}}:{inlineData:{mimeType:y.mimeType,data:y.data}};default:throw new Error(`Chat prompt content type not supported (index: ${I})`)}}):[{text:f.content}]};case"assistant":{let x=[];if(f.functionCalls){if(x=f.functionCalls.map(y=>{let I;if(typeof y.function.params=="string"){let E=y.function.params;if(E.trim().length===0)I={};else try{I=JSON.parse(E)}catch{throw new Error(`Failed to parse function params JSON: ${E}`)}}else I=y.function.params;return{functionCall:{name:y.function.name,args:I}}}),!x)throw new Error("Function call is empty");return{role:"model",parts:x}}if(!f.content)throw new Error("Assistant content is empty");return x=[{text:f.content}],{role:"model",parts:x}}case"function":{if(!("functionId"in f))throw new Error(`Chat prompt functionId is empty (index: ${A})`);return{role:"user",parts:[{functionResponse:{name:f.functionId,response:{result:f.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(f)} (index: ${A})`)}}),c=[];if(e.functions&&e.functions.length>0){let f=e.functions.map(A=>{let x={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},y=A.parameters?As(A.parameters):void 0;return y===void 0||y&&typeof y=="object"&&Object.keys(y).length===0?y={...x}:y&&typeof y=="object"&&y.type==="object"&&(!("properties"in y)||!y.properties||Object.keys(y.properties).length===0)&&(y={...y,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{...A,parameters:y}});c.push({function_declarations:f})}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 f=this.options.googleMaps,A=f?.enableWidget!==void 0?{enableWidget:f.enableWidget}:{};c.push({google_maps:A})}this.options?.urlContext&&c.push({url_context:{}}),c.length===0&&(c=void 0);let u,d=Array.isArray(c)?c.some(f=>f&&Array.isArray(f.function_declarations)&&f.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 f=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};u={function_calling_config:{mode:"ANY"},...f}}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),t?.thinkingTokenBudget){let f=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":p.thinkingBudget=0,p.includeThoughts=!1;break;case"minimal":p.thinkingBudget=f?.minimal??200;break;case"low":p.thinkingBudget=f?.low??800;break;case"medium":p.thinkingBudget=f?.medium??5e3;break;case"high":p.thinkingBudget=f?.high??1e4;break;case"highest":p.thinkingBudget=f?.highest??24500;break}}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}:{}},g=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:u,systemInstruction:a,generationConfig:m,safetySettings:g}]};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?i.thought=c.text:i.content=c.text;continue}"functionCall"in c&&(i.functionCalls=[{id:be(),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}}},Yt=class s extends he{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 f;r?f="endpoints":f="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${f}`,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={...ys(),...o},m=new xs(p,c,r,e,i);l=[...Br,...l??[]];let g=f=>{let A=Ue({model:f,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:A?.supported?.thinkingBudget??!1,hasShowThoughts:A?.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:A?.supported?.thinkingBudget??!1,multiTurn:!0}},h=a?.map(f=>{let A=f,x=A?.config;if(!x)return f;let y={};x.maxTokens!==void 0&&(y.maxTokens=x.maxTokens),x.temperature!==void 0&&(y.temperature=x.temperature),x.topP!==void 0&&(y.topP=x.topP),x.topK!==void 0&&(y.topK=x.topK),x.presencePenalty!==void 0&&(y.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(y.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(y.stopSequences=x.stopSequences),x.endSequences!==void 0&&(y.endSequences=x.endSequences),x.stream!==void 0&&(y.stream=x.stream),x.n!==void 0&&(y.n=x.n);let I={...A};Object.keys(y).length>0&&(I.modelConfig={...A.modelConfig??{},...y});let E=x.thinking?.thinkingTokenBudget;if(typeof E=="number"){let C=p.thinkingTokenBudgetLevels,T=[["minimal",C?.minimal??200],["low",C?.low??800],["medium",C?.medium??5e3],["high",C?.high??1e4],["highest",C?.highest??24500]],v="minimal",k=Number.POSITIVE_INFINITY;for(let[L,P]of T){let R=Math.abs(E-P);R<k&&(k=R,v=L)}I.thinkingTokenBudget=v}return x.thinking?.includeThoughts!==void 0&&(I.showThoughts=!!x.thinking.includeThoughts),I});super(m,{name:"GoogleGeminiAI",apiURL:u,headers:d,modelInfo:l,defaults:{model:p.model,embedModel:p.embedModel},options:i,supportFor:g,models:h??a})}};var ru=new ve,Qt=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(ru.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 Ln=(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))(Ln||{});var qr=[{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 ou=()=>structuredClone({model:"llama-3.3-70b-versatile",...te()}),Zt=class extends fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let i={...ou(),...t},a={...n,streamingUsage:!1};o=[...qr,...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 Qt(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 zr=[];var jr=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(jr||{});var Is=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...te()}),Oa=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Ae()}),bs=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
|
-
`:"",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
|
|
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}
|
|
156
156
|
Functions:
|
|
157
157
|
${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(`
|
|
158
|
-
`),o=`${n} ${r}`.trim(),i={name:"/models"},a={model:t,inputs:o,parameters:{max_new_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,repetition_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},top_k:e.modelConfig?.topK??this.config.topK,return_full_text:this.config.returnFullText,num_return_sequences:this.config.n,do_sample:this.config.doSample,max_time:this.config.maxTime},options:{use_cache:this.config.useCache,wait_for_model:this.config.waitForModel}};return[i,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},Zt=class extends fe{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let o={...Is(),...t},i=new bs(o);super(i,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:zr,defaults:{model:o.model},options:n,supportFor:{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r})}};var Ln=(l=>(l.Mistral7B="open-mistral-7b",l.Mistral8x7B="open-mixtral-8x7b",l.MistralSmall="mistral-small-latest",l.MistralNemo="mistral-nemo-latest",l.MistralLarge="mistral-large-latest",l.Codestral="codestral-latest",l.OpenCodestralMamba="open-codestral-mamba",l.OpenMistralNemo="open-mistral-nemo-latest",l))(Ln||{}),Ts=(e=>(e.MistralEmbed="mistral-embed",e))(Ts||{});var Hr=[{name:"open-mistral-7b",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mixtral-8x7b",currency:"USD",promptTokenCostPer1M:.7,completionTokenCostPer1M:.7},{name:"mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.15,completionTokenCostPer1M:.15},{name:"mistral-small-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"mistral-large-latest",currency:"USD",promptTokenCostPer1M:2,completionTokenCostPer1M:6},{name:"codestral-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"open-codestral-mamba",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.3}];var Kr=()=>structuredClone({model:"mistral-small-latest",...ee(),topP:1}),ka=()=>structuredClone({...Kr(),model:"mistral-large-latest"}),Xt=class extends he{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Mistral API key not set");let i={...Kr(),...t};o=[...Hr,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},l=c=>{let{max_completion_tokens:u,messages:p,...d}=c;return{...d,messages:this.updateMessages(p),max_tokens:u}};super({apiKey:e,config:i,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Mistral")}updateMessages(e){let t=[];if(!Array.isArray(e))return e;for(let n of e)if(n.role==="user"&&Array.isArray(n.content)){let r=n.content.map(o=>typeof o=="object"&&o!==null&&"image_url"in o?{type:"image_url",image_url:{url:o.image_url?.url}}:o);t.push({...n,content:r})}else t.push(n);return t}};var Wr=class{constructor(e={}){this.config=e;this.config.id=this.config.id??be()}metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getLastUsedChatModel(){return this.config.modelInfo?.name??"mock-model"}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??"mock-embed-model"}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??"mock-ai-service"}getId(){return this.config.id??"mock-ai-service-id"}getFeatures(e){return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getModelList(){return this.config.models}getMetrics(){return this.metrics}async chat(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock chat error");return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):this.config.chatResponse??{results:[{index:0,content:"Mock response",finishReason:"stop"}],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock embed error");return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((r,o)=>r+o,0)/n.length,n.length>0){let r=[...n].sort((a,l)=>a-l),o=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[o]??t;let i=Math.max(0,Math.floor(r.length*.99)-1);this.metrics.latency[e].p99=r[i]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let r=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=r>0?this.metrics.errors[e].count/r:0}}};var Vr=class s{options;lastUsedService;services=new Map;constructor(e){if(e.length===0)throw new Error("No AI services provided.");for(let[t,n]of e.entries())if("key"in n){if(this.services.has(n.key))throw new Error(`Duplicate model key: ${n.key}`);let{service:o,description:i,isInternal:a}=n;this.services.set(n.key,{service:o,description:i,isInternal:a})}else{let o=n.getModelList();if(!o)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let i of o){if(this.services.has(i.key)){let a=this.services.get(i.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${i.key} as service ${a?.getName()}`)}if("model"in i&&typeof i.model)this.services.set(i.key,{description:i.description,service:n,model:i.model});else if("embedModel"in i&&i.embedModel)this.services.set(i.key,{description:i.description,service:n,embedModel:i.embedModel});else throw new Error(`Key ${i.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(e){return new s(e)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{model:o,...i}=e;return await r.service.chat(i,t)}return await r.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw new Error("Embed model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{embedModel:o,...i}=e;return await r.service.embed(i,t)}return await r.service.embed({embedModel:n,...e},t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(",")}`}getName(){return"MultiServiceRouter"}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw new Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(e)}return{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e="service"in t?t.service:t)}if(!e)throw new Error("No service available to get metrics.");return e.getMetrics()}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw new Error("No service available to get logger.");return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};var Cs=()=>structuredClone({...ee(),model:"nous-hermes2",embedModel:"all-minilm"}),Ma=()=>structuredClone({...Ae(),model:"nous-hermes2",embedModel:"all-minilm"}),en=class extends he{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:o}){let i={...Cs(),...n};super({apiKey:e,options:r,config:i,apiURL:t,models:o,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}),super.setName("Ollama")}};var su=s=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(s),tn=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,stopSequences:e.stopSequences,topP:e.topP,stream:e.stream}}mapInternalContentToResponsesInput(e,t){let n=[];for(let r of e){if(r.type==="text"){t==="assistant"?n.push({type:"output_text",text:r.text}):n.push({type:"input_text",text:r.text});continue}if(t==="assistant")continue;if(r.type==="image"){let i=`data:${r.mimeType};base64,${r.image}`;n.push({type:"input_image",image_url:{url:i,details:r.details??"auto"}});continue}if(r.type==="audio"){n.push({type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}});continue}let o=r;throw new Error(`Unsupported content part: ${JSON.stringify(o)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let r of e){if(t&&r.role==="system")continue;let o;if(r.role==="system"||r.role==="user"||r.role==="assistant"&&r.content)if(typeof r.content=="string")r.role==="system"?o=r.content:r.role==="assistant"?o=[{type:"output_text",text:r.content}]:o=[{type:"input_text",text:r.content}];else if(Array.isArray(r.content))o=this.mapInternalContentToResponsesInput(r.content,r.role==="assistant"?"assistant":"user");else{if(!(r.role==="assistant"&&!r.content&&r.functionCalls))throw new Error(`Invalid content type for role ${r.role}`);o=""}else r.role,o="";switch(r.role){case"system":n.push({type:"message",role:"system",content:o});break;case"user":n.push({type:"message",role:"user",content:o,name:r.name});break;case"assistant":if(r.content||r.functionCalls){let i={type:"message",role:"assistant",content:""};if(r.content&&(i.content=o),r.name&&(i.name=r.name),r.content&&n.push(i),r.functionCalls)for(let a of r.functionCalls)n.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:typeof a.function.params=="object"?JSON.stringify(a.function.params):a.function.params||""})}break;case"function":n.push({type:"function_call_output",call_id:r.functionId,output:r.result});break;default:{let i=r.role;throw new Error(`Invalid role in chat prompt: ${i}`)}}}return n}createChatReq(e,t){let n=e.model,r={name:"/responses"},o=null,i=!1;if(e.chatPrompt){for(let A of e.chatPrompt)if(A.role==="system"&&typeof A.content=="string"){o=A.content,i=!0;break}}let a=o??this.config.systemPrompt??null,l=e.functions?.map(A=>({type:"function",name:A.name,description:A.description,parameters:A.parameters??{}})),c=[],u=su(n),p=this.config.reasoningSummary;t?.showThoughts?p||(p="auto"):p=void 0;let d=this.config.reasoningEffort;if(t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d=void 0;break;case"minimal":d="minimal";break;case"low":d="medium";break;case"medium":case"high":case"highest":d="high";break}let m={model:n,input:"",instructions:a,tools:l?.length?l:void 0,tool_choice:e.functionCall==="none"||e.functionCall==="auto"||e.functionCall==="required"?e.functionCall:typeof e.functionCall=="object"&&e.functionCall.function?{type:"function",name:e.functionCall.function.name}:void 0,...u?{max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0}:{...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty??void 0,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty??void 0,max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0},stream:e.modelConfig?.stream??this.config.stream??!1,background:void 0,include:c.length>0?c:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...d?{reasoning:{effort:d,summary:p}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let g=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,i):[];if(g.length>0)m.input=g;else if(e.chatPrompt&&e.chatPrompt.length===1&&e.chatPrompt[0]?.role==="user"&&e.chatPrompt[0]?.content&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(g.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let f=m.reasoning??{};if(this.config.reasoningEffort&&(f={...f,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":f={};break;case"minimal":f={...f,effort:"minimal"};break;case"low":f={...f,effort:"medium"};break;case"medium":case"high":case"highest":f={...f,effort:"high"};break}Object.keys(f).length>0&&f.effort?m.reasoning=f:m.reasoning=void 0;let h=m;return this.responsesReqUpdater&&(h=this.responsesReqUpdater(h)),[r,h]}createChatResp(e){let{id:t,output:n,usage:r}=e;r&&(this.tokensUsed={promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens??r.output_tokens??0,totalTokens:r.total_tokens});let o={};for(let i of n??[])switch(i.type){case"message":o.id=i.id,o.content=Rs(i.content,t),o.finishReason=i.status==="completed"?"stop":"content_filter",o.citations=Jr(i.content);break;case"reasoning":o.id=i.id,i.encrypted_content?o.thought=i.encrypted_content:o.thought=i.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
|
|
158
|
+
`),o=`${n} ${r}`.trim(),i={name:"/models"},a={model:t,inputs:o,parameters:{max_new_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,repetition_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},top_k:e.modelConfig?.topK??this.config.topK,return_full_text:this.config.returnFullText,num_return_sequences:this.config.n,do_sample:this.config.doSample,max_time:this.config.maxTime},options:{use_cache:this.config.useCache,wait_for_model:this.config.waitForModel}};return[i,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},Xt=class extends he{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let o={...Is(),...t},i=new bs(o);super(i,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:zr,defaults:{model:o.model},options:n,supportFor:{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r})}};var Un=(l=>(l.Mistral7B="open-mistral-7b",l.Mistral8x7B="open-mixtral-8x7b",l.MistralSmall="mistral-small-latest",l.MistralNemo="mistral-nemo-latest",l.MistralLarge="mistral-large-latest",l.Codestral="codestral-latest",l.OpenCodestralMamba="open-codestral-mamba",l.OpenMistralNemo="open-mistral-nemo-latest",l))(Un||{}),Ts=(e=>(e.MistralEmbed="mistral-embed",e))(Ts||{});var Hr=[{name:"open-mistral-7b",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mixtral-8x7b",currency:"USD",promptTokenCostPer1M:.7,completionTokenCostPer1M:.7},{name:"mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.15,completionTokenCostPer1M:.15},{name:"mistral-small-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"mistral-large-latest",currency:"USD",promptTokenCostPer1M:2,completionTokenCostPer1M:6},{name:"codestral-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"open-codestral-mamba",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.3}];var Kr=()=>structuredClone({model:"mistral-small-latest",...te(),topP:1}),ka=()=>structuredClone({...Kr(),model:"mistral-large-latest"}),en=class extends fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Mistral API key not set");let i={...Kr(),...t};o=[...Hr,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},l=c=>{let{max_completion_tokens:u,messages:d,...p}=c;return{...p,messages:this.updateMessages(d),max_tokens:u}};super({apiKey:e,config:i,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Mistral")}updateMessages(e){let t=[];if(!Array.isArray(e))return e;for(let n of e)if(n.role==="user"&&Array.isArray(n.content)){let r=n.content.map(o=>typeof o=="object"&&o!==null&&"image_url"in o?{type:"image_url",image_url:{url:o.image_url?.url}}:o);t.push({...n,content:r})}else t.push(n);return t}};var Wr=class{constructor(e={}){this.config=e;this.config.id=this.config.id??be()}metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getLastUsedChatModel(){return this.config.modelInfo?.name??"mock-model"}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??"mock-embed-model"}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??"mock-ai-service"}getId(){return this.config.id??"mock-ai-service-id"}getFeatures(e){return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getModelList(){return this.config.models}getMetrics(){return this.metrics}async chat(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock chat error");return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):this.config.chatResponse??{results:[{index:0,content:"Mock response",finishReason:"stop"}],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock embed error");return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((r,o)=>r+o,0)/n.length,n.length>0){let r=[...n].sort((a,l)=>a-l),o=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[o]??t;let i=Math.max(0,Math.floor(r.length*.99)-1);this.metrics.latency[e].p99=r[i]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let r=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=r>0?this.metrics.errors[e].count/r:0}}};var Vr=class s{options;lastUsedService;services=new Map;constructor(e){if(e.length===0)throw new Error("No AI services provided.");for(let[t,n]of e.entries())if("key"in n){if(this.services.has(n.key))throw new Error(`Duplicate model key: ${n.key}`);let{service:o,description:i,isInternal:a}=n;this.services.set(n.key,{service:o,description:i,isInternal:a})}else{let o=n.getModelList();if(!o)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let i of o){if(this.services.has(i.key)){let a=this.services.get(i.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${i.key} as service ${a?.getName()}`)}if("model"in i&&typeof i.model)this.services.set(i.key,{description:i.description,service:n,model:i.model});else if("embedModel"in i&&i.embedModel)this.services.set(i.key,{description:i.description,service:n,embedModel:i.embedModel});else throw new Error(`Key ${i.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(e){return new s(e)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{model:o,...i}=e;return await r.service.chat(i,t)}return await r.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw new Error("Embed model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{embedModel:o,...i}=e;return await r.service.embed(i,t)}return await r.service.embed({embedModel:n,...e},t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(",")}`}getName(){return"MultiServiceRouter"}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw new Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(e)}return{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e="service"in t?t.service:t)}if(!e)throw new Error("No service available to get metrics.");return e.getMetrics()}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw new Error("No service available to get logger.");return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};var Cs=()=>structuredClone({...te(),model:"nous-hermes2",embedModel:"all-minilm"}),Ma=()=>structuredClone({...Ae(),model:"nous-hermes2",embedModel:"all-minilm"}),tn=class extends fe{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:o}){let i={...Cs(),...n};super({apiKey:e,options:r,config:i,apiURL:t,models:o,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}),super.setName("Ollama")}};var su=s=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(s),nn=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,stopSequences:e.stopSequences,topP:e.topP,stream:e.stream}}mapInternalContentToResponsesInput(e,t){let n=[];for(let r of e){if(r.type==="text"){t==="assistant"?n.push({type:"output_text",text:r.text}):n.push({type:"input_text",text:r.text});continue}if(t==="assistant")continue;if(r.type==="image"){let i=`data:${r.mimeType};base64,${r.image}`;n.push({type:"input_image",image_url:{url:i,details:r.details??"auto"}});continue}if(r.type==="audio"){n.push({type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}});continue}let o=r;throw new Error(`Unsupported content part: ${JSON.stringify(o)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let r of e){if(t&&r.role==="system")continue;let o;if(r.role==="system"||r.role==="user"||r.role==="assistant"&&r.content)if(typeof r.content=="string")r.role==="system"?o=r.content:r.role==="assistant"?o=[{type:"output_text",text:r.content}]:o=[{type:"input_text",text:r.content}];else if(Array.isArray(r.content))o=this.mapInternalContentToResponsesInput(r.content,r.role==="assistant"?"assistant":"user");else{if(!(r.role==="assistant"&&!r.content&&r.functionCalls))throw new Error(`Invalid content type for role ${r.role}`);o=""}else r.role,o="";switch(r.role){case"system":n.push({type:"message",role:"system",content:o});break;case"user":n.push({type:"message",role:"user",content:o,name:r.name});break;case"assistant":if(r.content||r.functionCalls){let i={type:"message",role:"assistant",content:""};if(r.content&&(i.content=o),r.name&&(i.name=r.name),r.content&&n.push(i),r.functionCalls)for(let a of r.functionCalls)n.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:typeof a.function.params=="object"?JSON.stringify(a.function.params):a.function.params||""})}break;case"function":n.push({type:"function_call_output",call_id:r.functionId,output:r.result});break;default:{let i=r.role;throw new Error(`Invalid role in chat prompt: ${i}`)}}}return n}createChatReq(e,t){let n=e.model,r={name:"/responses"},o=null,i=!1;if(e.chatPrompt){for(let A of e.chatPrompt)if(A.role==="system"&&typeof A.content=="string"){o=A.content,i=!0;break}}let a=o??this.config.systemPrompt??null,l=e.functions?.map(A=>({type:"function",name:A.name,description:A.description,parameters:A.parameters??{}})),c=[],u=su(n),d=this.config.reasoningSummary;t?.showThoughts?d||(d="auto"):d=void 0;let p=this.config.reasoningEffort;if(t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":p=void 0;break;case"minimal":p="minimal";break;case"low":p="medium";break;case"medium":case"high":case"highest":p="high";break}let m={model:n,input:"",instructions:a,tools:l?.length?l:void 0,tool_choice:e.functionCall==="none"||e.functionCall==="auto"||e.functionCall==="required"?e.functionCall:typeof e.functionCall=="object"&&e.functionCall.function?{type:"function",name:e.functionCall.function.name}:void 0,...u?{max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0}:{...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty??void 0,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty??void 0,max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0},stream:e.modelConfig?.stream??this.config.stream??!1,background:void 0,include:c.length>0?c:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...p?{reasoning:{effort:p,summary:d}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let g=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,i):[];if(g.length>0)m.input=g;else if(e.chatPrompt&&e.chatPrompt.length===1&&e.chatPrompt[0]?.role==="user"&&e.chatPrompt[0]?.content&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(g.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let h=m.reasoning??{};if(this.config.reasoningEffort&&(h={...h,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":h={};break;case"minimal":h={...h,effort:"minimal"};break;case"low":h={...h,effort:"medium"};break;case"medium":case"high":case"highest":h={...h,effort:"high"};break}Object.keys(h).length>0&&h.effort?m.reasoning=h:m.reasoning=void 0;let f=m;return this.responsesReqUpdater&&(f=this.responsesReqUpdater(f)),[r,f]}createChatResp(e){let{id:t,output:n,usage:r}=e;r&&(this.tokensUsed={promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens??r.output_tokens??0,totalTokens:r.total_tokens});let o={};for(let i of n??[])switch(i.type){case"message":o.id=i.id,o.content=Rs(i.content,t),o.finishReason=i.status==="completed"?"stop":"content_filter",o.citations=Jr(i.content);break;case"reasoning":o.id=i.id,i.encrypted_content?o.thought=i.encrypted_content:o.thought=i.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
|
|
159
159
|
`);break;case"file_search_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"file_search",params:{queries:i.queries,results:i.results}}}],o.finishReason="function_call";break;case"web_search_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"web_search",params:{queries:i.queries}}}],o.finishReason="function_call";break;case"computer_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"computer_use",params:{action:i.action}}}],o.finishReason="function_call";break;case"code_interpreter_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"code_interpreter",params:{code:i.code,results:i.results}}}],o.finishReason="function_call";break;case"image_generation_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"image_generation",params:{result:i.result}}}],o.finishReason="function_call";break;case"local_shell_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"local_shell",params:{action:i.action}}}],o.finishReason="function_call";break;case"mcp_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"mcp",params:{name:i.name,args:i.args,serverLabel:i.server_label,output:i.output,error:i.error}}}],o.finishReason="function_call";break;case"function_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:i.name,params:i.arguments}}],o.finishReason="function_call";break}return{results:[{...o,index:0}],remoteId:t}}createChatStreamResp(e){let t=e,n={index:0,id:"",content:"",finishReason:"stop"},r;switch(t.type){case"response.created":case"response.in_progress":case"response.queued":r=t.response.id,n.id=`${t.response.id}_res_0`;break;case"response.output_item.added":switch(t.item.type){case"message":n.id=t.item.id,n.content=Rs(t.item.content,t.item.id),n.citations=Jr(t.item.content);break;case"function_call":n.id=t.item.id,n.functionCalls=[{id:t.item.id,type:"function",function:{name:t.item.name,params:t.item.arguments}}];break;case"file_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"file_search",params:{queries:o.queries||[],results:o.results?.map(i=>({fileId:i.file_id,filename:i.filename,score:i.score,text:i.text,attributes:i.attributes}))}}}]}break;case"web_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"web_search",params:{queries:o.queries||[]}}}]}break;case"computer_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"computer_use",params:{action:o.action||{}}}}]}break;case"code_interpreter_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"code_interpreter",params:{code:o.code||"",results:o.results}}}]}break;case"image_generation_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"image_generation",params:{result:o.result}}}]}break;case"local_shell_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"local_shell",params:{action:o.action||{}}}}]}break;case"mcp_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"mcp",params:{name:o.name||"",args:o.args||"",serverLabel:o.server_label||"",output:o.output,error:o.error}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=Rs([t.part],t.item_id),n.citations=Jr([t.part]);break;case"response.output_text.delta":n.id=t.item_id,n.content=t.delta;break;case"response.output_text.done":break;case"response.function_call_arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.reasoning_summary_text.delta":n.id=t.item_id,n.thought=t.delta;break;case"response.file_search_call.in_progress":case"response.file_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.file_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.in_progress":case"response.web_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.in_progress":case"response.image_generation_call.generating":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.partial_image":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.in_progress":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.mcp_call.arguments.done":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.arguments}}];break;case"response.mcp_call.completed":case"response.mcp_call.failed":n.id="mcp_call_event",n.finishReason="function_call";break;case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":n.id="mcp_list_tools_event",n.finishReason="function_call";break;case"response.output_item.done":switch(t.item.type){case"message":if(n.id=t.item.id,n.finishReason=t.item.status==="completed"?"stop":"error",!n.citations||n.citations.length===0){let o=Jr(t.item.content||[]);o&&(n.citations=o)}break;case"function_call":case"file_search_call":case"web_search_call":case"computer_call":case"code_interpreter_call":case"image_generation_call":case"local_shell_call":case"mcp_call":n.id=t.item.id,n.finishReason="function_call";break}break;case"response.completed":t.response.usage&&(this.tokensUsed={promptTokens:t.response.usage.prompt_tokens,completionTokens:t.response.usage.completion_tokens??t.response.usage.output_tokens??0,totalTokens:t.response.usage.total_tokens}),r=t.response.id,n.id=`${t.response.id}_completed`,n.finishReason="stop";break;case"response.failed":r=t.response.id,n.id=`${t.response.id}_failed`,n.finishReason="error";break;case"response.incomplete":r=t.response.id,n.id=`${t.response.id}_incomplete`,n.finishReason="length";break;case"error":n.id="error",n.content=`Error: ${t.message}`,n.finishReason="error";break;default:n.id="unknown";break}return{results:[n],remoteId:r}}createEmbedReq(e){let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]}},Rs=(s,e)=>{let t=s.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(r=>r.refusal).join(`
|
|
160
160
|
`);throw new de(n,void 0,e)}return s.filter(n=>n.type==="output_text").map(n=>n.text).join(`
|
|
161
|
-
`)};function Jr(s){let e=[];for(let t of s??[])if(t?.type==="output_text"&&Array.isArray(t.annotations))for(let n of t.annotations)n&&n.type==="url_citation"&&typeof n.url=="string"&&e.push({url:n.url,title:n.title,description:n.description});return e.length?e:void 0}var Bn=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),Ea=()=>({...Bn(),model:"gpt-4o",temperature:.5}),Pa=()=>({...Bn(),model:"gpt-4o",temperature:.9}),Un=class extends fe{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=[],models:i,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new tn(t,n?.streamingUsage??!0,a),u=i?.map(p=>{let d=p,m=d?.config;if(!m)return p;let g={};m.maxTokens!==void 0&&(g.maxTokens=m.maxTokens),m.temperature!==void 0&&(g.temperature=m.temperature),m.topP!==void 0&&(g.topP=m.topP),m.presencePenalty!==void 0&&(g.presencePenalty=m.presencePenalty),m.frequencyPenalty!==void 0&&(g.frequencyPenalty=m.frequencyPenalty);let f=m.stopSequences??m.stop;f!==void 0&&(g.stopSequences=f),m.n!==void 0&&(g.n=m.n),m.stream!==void 0&&(g.stream=m.stream);let h={...d};Object.keys(g).length>0&&(h.modelConfig={...d.modelConfig??{},...g});let A=m?.thinking?.thinkingTokenBudget;if(typeof A=="number"){let x=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],b="minimal",I=Number.POSITIVE_INFINITY;for(let[M,R]of x){let w=Math.abs(A-R);w<I&&(I=w,b=M)}h.thinkingTokenBudget=b}return m?.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!m.thinking.includeThoughts),h});super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model??"gpt-4o",embedModel:t.embedModel??"text-embedding-ada-002"},options:n,supportFor:l,models:u??i})}},nn=class extends Un{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...kr,...o??[]];let i=a=>{let l=Ue({model:a,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!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:{...Bn(),...t},options:n,modelInfo:o,models:r,supportFor:i})}};var ws=()=>structuredClone({model:"openrouter/auto",...ee()}),rn=class extends he{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o,referer:i,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let l={...ws(),...t},c={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},u=o??[];super({apiKey:e,config:l,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:u,models:r,supportFor:c}),super.setName("OpenRouter"),super.setHeaders(async()=>{let p={Authorization:`Bearer ${e}`};return i&&(p["HTTP-Referer"]=i),a&&(p["X-Title"]=a),p})}};async function Yr(s,e,t={}){if(typeof s=="string")return[{type:"text",text:s}];if(!Array.isArray(s))return[{type:"text",text:String(s)}];let n=e.getFeatures(),r=[];for(let o of s)try{switch(o.type){case"text":r.push({type:"text",text:o.text});break;case"image":if(n.media.images.supported)o.altText?r.push({type:"text",text:`[Image: ${o.altText}]`}):r.push({type:"text",text:"[Image content]"});else if(o.altText)r.push({type:"text",text:o.altText});else if(t.imageToText)try{let i=await t.imageToText(o.image);r.push({type:"text",text:i})}catch(i){throw new Je(i,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new Be("Images",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:"[Image content not supported by this provider]"})}break;case"audio":if(n.media.audio.supported)o.transcription?r.push({type:"text",text:o.transcription}):r.push({type:"text",text:"[Audio content]"});else if(o.transcription)r.push({type:"text",text:o.transcription});else if(t.audioToText)try{let i=await t.audioToText(o.data,o.format);r.push({type:"text",text:i})}catch(i){throw new Je(i,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new Be("Audio",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:"[Audio content not supported by this provider]"})}break;case"file":if(n.media.files.supported)o.extractedText?r.push({type:"text",text:o.extractedText}):r.push({type:"text",text:`[File: ${o.filename}]`});else if(o.extractedText)r.push({type:"text",text:o.extractedText});else if(t.fileToText)try{let i=await t.fileToText(o.data,o.mimeType);r.push({type:"text",text:i})}catch(i){throw new Je(i,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new Be("Files",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:`[File: ${o.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)o.cachedContent?r.push({type:"text",text:o.cachedContent}):r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`});else if(o.cachedContent)r.push({type:"text",text:o.cachedContent});else if(t.urlToText)try{let i=await t.urlToText(o.url);r.push({type:"text",text:i})}catch(i){throw new Je(i,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new Be("URLs",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`})}break;default:typeof o=="object"&&o.text?r.push({type:"text",text:o.text}):r.push({type:"text",text:String(o)})}}catch(i){throw i instanceof Be||i instanceof Je?i:new Je(i,o.type||"unknown","content processing")}return r}function _a(s){let e=!1,t=!1,n=!1,r=!1;for(let o of s)if(o.role==="user"&&Array.isArray(o.content))for(let i of o.content)switch(i.type){case"image":e=!0;break;case"audio":t=!0;break;case"file":n=!0;break;case"url":r=!0;break}return{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r}}var qn=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(qn||{});var Qr=[{name:"reka-core",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"reka-flash",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2},{name:"reka-edge",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1}];var zn=()=>structuredClone({model:"reka-core",...ee()}),Da=()=>structuredClone({...zn(),model:"reka-core"}),Na=()=>structuredClone({model:"reka-core",...Ae()}),$a=()=>({...zn(),model:"reka-flash"}),vs=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=e=>{let t=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let n={name:"/chat/completions"},r=iu(e),o=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,i=e.modelConfig?.stream??this.config.stream,a={model:t,messages:r,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},top_k:e.modelConfig?.n??this.config.n,...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},stop:e.modelConfig?.stopSequences??this.config.stop,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...o?{frequency_penalty:o}:{},...i?{stream:!0}:{}};return[n,a]};createChatResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((i,a)=>{let l=Fa(i.finish_reason),c;return typeof i.message.content=="string"?c=i.message.content:c=i.message.content.text,{index:a,id:`${t}`,content:c,finishReason:l}}),remoteId:t}};createChatStreamResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((i,a)=>{let l=Fa(i.finish_reason),c;return typeof i.chunk.content=="string"?c=i.chunk.content:c=i.chunk.content.text,{index:a,id:`${t}`,content:c,finishReason:l}})}}},Fa=s=>{switch(s){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function iu(s){return s.chatPrompt.map(e=>{switch(e.role){case"system":return{role:"user",content:e.content};case"user":return Array.isArray(e.content)?{role:"user",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})}:{role:"user",content:e.content};case"assistant":if(Array.isArray(e.content))return{role:"assistant",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})};if(!e.content)throw new Error("Assistant content is empty");return{role:"user",content:e.content};default:throw new Error("Invalid role")}})}var on=class extends fe{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=Qr,models:i}){if(!e||e==="")throw new Error("Reka API key not set");let a={...zn(),...t},l=new vs(a);super(l,{name:"Reka",apiURL:r||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:o,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:i})}};var Zr=class{providers;processingServices;config;constructor(e){this.providers=[e.providers.primary,...e.providers.alternatives],this.processingServices=e.processing,this.config=e.routing}async chat(e,t={}){let n=await this.selectProviderWithDegradation(e,t.routingOptions||{}),r=await this.preprocessRequest(e,n.provider,t.processingOptions);try{return{response:await n.provider.chat(r,t),routing:n}}catch(o){if(o instanceof Be&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw o}}async preprocessRequest(e,t,n){let r={...n,fallbackBehavior:n?.fallbackBehavior||"degrade",imageToText:n?.imageToText||this.processingServices.imageToText,audioToText:n?.audioToText||this.processingServices.audioToText,fileToText:n?.fileToText||this.processingServices.fileToText,urlToText:n?.urlToText||this.processingServices.urlToText},o=[];for(let i of e.chatPrompt)if(i.role==="user"&&Array.isArray(i.content)){let a=await Yr(i.content,t,r);a.every(c=>c.type==="text")&&a.length===1?o.push({...i,content:a[0].text}):o.push({...i,content:a.map(c=>({type:"text",text:c.text}))})}else o.push(i);return{...e,chatPrompt:o}}async selectProviderWithDegradation(e,t){let n=Ot(e),r=[],o=[],i=[];try{let a=Dr(e,this.providers,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation}),l=a.getFeatures();return n.hasImages&&!l.media.images.supported&&(o.push("Images will be converted to text descriptions"),r.push("Image-to-text conversion")),n.hasAudio&&!l.media.audio.supported&&(o.push("Audio will be transcribed to text"),r.push("Audio-to-text transcription")),n.hasFiles&&!l.media.files.supported&&(o.push("File content will be extracted to text"),r.push("File-to-text extraction")),n.hasUrls&&!l.media.urls.supported&&(o.push("URL content will be pre-fetched"),r.push("URL content fetching")),n.requiresStreaming&&!l.streaming&&i.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!l.caching.supported&&i.push("Content caching not supported"),{provider:a,processingApplied:r,degradations:o,warnings:i}}catch(a){throw new Error(`Provider selection failed: ${a instanceof Error?a.message:"Unknown error"}`)}}async tryFallbackProviders(e,t,n){for(let r of t)try{let o={provider:r,processingApplied:["Fallback provider selection"],degradations:["Using fallback provider due to primary provider failure"],warnings:[]},i=await this.preprocessRequest(e,r,{fallbackBehavior:"degrade"});return{response:await r.chat(i,n),routing:o}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=Ot(e),n=[],r=[];try{let o=await this.selectProviderWithDegradation(e,{});return o.degradations.length>0&&(n.push(...o.degradations),r.push("Consider using a provider that natively supports all media types")),o.warnings.length>0&&n.push(...o.warnings),t.hasImages&&this.processingServices.imageToText===void 0&&(this.providers.some(a=>a.getFeatures().media.images.supported)||(n.push("No image processing service available and no providers support images"),r.push("Add imageToText processing service or use image-capable provider"))),t.hasAudio&&this.processingServices.audioToText===void 0&&(this.providers.some(a=>a.getFeatures().media.audio.supported)||(n.push("No audio processing service available and no providers support audio"),r.push("Add audioToText processing service or use audio-capable provider"))),{canHandle:n.length===0||o.degradations.length>0,issues:n,recommendations:r}}catch(o){return{canHandle:!1,issues:[`Cannot route request: ${o instanceof Error?o.message:"Unknown error"}`],recommendations:["Add more providers or processing services to handle this request"]}}}getRoutingStats(){let e={};for(let t of this.providers){let n=t.getFeatures(),r=t.getName();n.functions&&(e.Functions=e.Functions||[],e.Functions.push(r)),n.streaming&&(e.Streaming=e.Streaming||[],e.Streaming.push(r)),n.media.images.supported&&(e.Images=e.Images||[],e.Images.push(r)),n.media.audio.supported&&(e.Audio=e.Audio||[],e.Audio.push(r)),n.media.files.supported&&(e.Files=e.Files||[],e.Files.push(r)),n.media.urls.supported&&(e.URLs=e.URLs||[],e.URLs.push(r)),n.caching.supported&&(e.Caching=e.Caching||[],e.Caching.push(r))}return{totalProviders:this.providers.length,capabilityMatrix:e,recommendedProvider:this.providers[0]?.getName()||"None"}}};var Xr=[];var Ss=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...ee()}),sn=class extends he{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Together API key not set");let i={...Ss(),...t};o=[...Xr,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:i,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:o,models:r,supportFor:a}),super.setName("Together")}};var jn=(d=>(d.Llama31_8B_Instruct="Llama-3.1-8B-Instruct-q4f32_1-MLC",d.Llama31_70B_Instruct="Llama-3.1-70B-Instruct-q4f16_1-MLC",d.Llama32_1B_Instruct="Llama-3.2-1B-Instruct-q4f32_1-MLC",d.Llama32_3B_Instruct="Llama-3.2-3B-Instruct-q4f32_1-MLC",d.Mistral7B_Instruct="Mistral-7B-Instruct-v0.3-q4f32_1-MLC",d.Phi35_Mini_Instruct="Phi-3.5-mini-instruct-q4f32_1-MLC",d.Gemma2_2B_Instruct="gemma-2-2b-it-q4f32_1-MLC",d.Gemma2_9B_Instruct="gemma-2-9b-it-q4f32_1-MLC",d.Qwen2_5_0_5B_Instruct="Qwen2.5-0.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_1_5B_Instruct="Qwen2.5-1.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_3B_Instruct="Qwen2.5-3B-Instruct-q4f32_1-MLC",d.Qwen2_5_7B_Instruct="Qwen2.5-7B-Instruct-q4f32_1-MLC",d))(jn||{});var eo=[{name:"Llama-3.1-8B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"Llama-3.1-70B-Instruct-q4f16_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096,isExpensive:!0},{name:"Llama-3.2-1B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Llama-3.2-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Mistral-7B-Instruct-v0.3-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096},{name:"Phi-3.5-mini-instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"gemma-2-2b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"gemma-2-9b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"Qwen2.5-0.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-1.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-7B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096}];var ks=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...ee()}),Ga=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Ae()}),Os=class{constructor(e,t){this.config=e;this.engine=t}tokensUsed;engine;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.map(a=>{if(a.role==="function")return{role:"function",name:a.functionId,content:typeof a.result=="string"?a.result:JSON.stringify(a.result)};let l="";typeof a.content=="string"?l=a.content:Array.isArray(a.content)&&(l=a.content.filter(u=>u.type==="text").map(u=>u.text).join(`
|
|
162
|
-
`));let c={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...c,tool_calls:a.functionCalls.map(u=>({id:u.id,type:"function",function:{name:u.function.name,arguments:typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params||{})}}))}:c}),r=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),o={name:"/chat/completions",localCall:async(a,l)=>{try{let c=await this.engine.chat.completions.create({...a,stream:l||!1});return l?new ReadableStream({async start(u){try{for await(let p of c)u.enqueue(p);u.close()}catch(p){u.error(p)}}}):c}catch(c){throw new Error(`WebLLM API error: ${c}`)}}},i={model:t,messages:n,...r?.length?{tools:r}:{},max_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}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,stop:e.modelConfig?.stopSequences??this.config.stopSequences,stream:e.modelConfig?.stream??this.config.stream,n:e.modelConfig?.n??this.config.n};return[o,i]}createEmbedReq=e=>{throw new Error("WebLLM does not support embeddings")};createChatResp=e=>(this.tokensUsed={promptTokens:e.usage?.prompt_tokens??0,completionTokens:e.usage?.completion_tokens??0,totalTokens:e.usage?.total_tokens??0},{results:e.choices.map((n,r)=>{let o="stop";switch(n.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let i=n.message.tool_calls?.map(a=>({id:a.id,type:"function",function:{name:a.function.name,params:a.function.arguments}}));return{index:r,id:e.id,content:n.message.content||"",functionCalls:i,finishReason:o}}),remoteId:e.id});createChatStreamResp=(e,t)=>{let n=t,r=e.choices[0];if(!r)throw new Error("No choice in WebLLM stream response");if(r.delta.content&&(n.content=(n.content||"")+r.delta.content),r.delta.tool_calls){n.toolCalls||(n.toolCalls=[]);for(let l of r.delta.tool_calls){let c=n.toolCalls[l.index];c?l.function?.arguments&&(c.function.arguments=(c.function?.arguments||"")+l.function.arguments):n.toolCalls[l.index]={id:l.id,type:l.type,function:{name:l.function?.name,arguments:l.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let o;if(r.finish_reason)switch(r.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let i=n.toolCalls?.map(l=>({id:l.id||"",type:"function",function:{name:l.function?.name||"",params:l.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:i,finishReason:o}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},an=class extends fe{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let o={...ks(),...t},i=new Os(o,e);super(i,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:eo,defaults:{model:o.model},supportFor:a=>({functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}),options:n,models:r})}};var Hn=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(Hn||{}),Ms=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Ms||{});var to=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,supported:{thinkingBudget:!0}},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,supported:{thinkingBudget:!0}}];var no=()=>structuredClone({model:"grok-3-mini",...ee()}),La=()=>structuredClone({...no(),model:"grok-3"}),ln=class extends he{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Grok API key not set");let i={...no(),...t};o=[...to,...o??[]];let a=c=>{let u=Ue({model:c,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}},l=c=>{if(n?.searchParameters){let u=n.searchParameters;return{...c,search_parameters:{mode:u.mode,return_citations:u.returnCitations,from_date:u.fromDate,to_date:u.toDate,max_search_results:u.maxSearchResults,sources:u.sources?.map(p=>({type:p.type,country:p.country,excluded_websites:p.excludedWebsites,allowed_websites:p.allowedWebsites,safe_search:p.safeSearch,x_handles:p.xHandles,links:p.links}))}}}return c};super({apiKey:e,config:i,options:n,apiURL:"https://api.x.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};function Ua(s){return Kn.create(s)}var Kn=class s{ai;static create(e){return new s(e)}constructor(e){switch(e.name){case"openai":this.ai=new Ht(e);break;case"openai-responses":this.ai=new nn(e);break;case"azure-openai":this.ai=new Kt(e);break;case"grok":this.ai=new ln(e);break;case"huggingface":this.ai=new Zt(e);break;case"groq":this.ai=new Qt(e);break;case"together":this.ai=new sn(e);break;case"openrouter":this.ai=new rn(e);break;case"cohere":this.ai=new Wt(e);break;case"google-gemini":this.ai=new Jt(e);break;case"anthropic":this.ai=new Bt(e);break;case"mistral":this.ai=new Xt(e);break;case"deepseek":this.ai=new Vt(e);break;case"ollama":this.ai=new en(e);break;case"reka":this.ai=new on(e);break;case"webllm":this.ai=new an(e);break;default:throw new Error("Unknown AI")}}getName(){return this.ai.getName()}getId(){return this.ai.getId()}getFeatures(e){return this.ai.getFeatures(e)}getModelList(){return this.ai.getModelList()}getLastUsedChatModel(){return this.ai.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.ai.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.ai.getLastUsedModelConfig()}getMetrics(){return this.ai.getMetrics()}async chat(e,t){return await this.ai.chat(e,t)}async embed(e,t){return await this.ai.embed(e,t)}setOptions(e){this.ai.setOptions(e)}getOptions(){return this.ai.getOptions()}getLogger(){return this.ai.getLogger()}};var qe=class{name;fetch;tracer;_upsert;_batchUpsert;_query;constructor({name:e,fetch:t,tracer:n}){this.name=e,this.fetch=t,this.tracer=n}async upsert(e,t){if(!this._upsert)throw new Error("upsert() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Upsert Request",{kind:Me.SERVER,attributes:{[V.DB_SYSTEM]:this.name,[V.DB_OPERATION_NAME]:"upsert",[V.DB_TABLE]:e.table,[V.DB_NAMESPACE]:e.namespace,[V.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._upsert(e,t,{span:n})}finally{n.end()}}):await this._upsert(e,t)}async batchUpsert(e,t){if(!this._batchUpsert)throw new Error("batchUpsert() not implemented");if(e.length===0)throw new Error("Batch request is empty");if(!e[0])throw new Error("Batch request is invalid first element is undefined");return this.tracer?await this.tracer.startActiveSpan("DB Batch Upsert Request",{kind:Me.SERVER,attributes:{[V.DB_SYSTEM]:this.name,[V.DB_OPERATION_NAME]:"upsert",[V.DB_TABLE]:e[0].table,[V.DB_NAMESPACE]:e[0].namespace,[V.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._batchUpsert(e,t,{span:n})}finally{n.end()}}):await this._batchUpsert(e,t)}async query(e){if(!this._query)throw new Error("query() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Query Request",{kind:Me.SERVER,attributes:{[V.DB_SYSTEM]:this.name,[V.DB_OPERATION_NAME]:"upsert",[V.DB_TABLE]:e.table,[V.DB_NAMESPACE]:e.namespace,[V.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var Es="https://api.cloudflare.com/client/v4/accounts/",cn=class extends qe{apiKey;accountId;constructor({apiKey:e,accountId:t,fetch:n,tracer:r}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:r}),this.apiKey=e,this.accountId=t}_upsert=async(e,t,n)=>{let r=await ke({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,Es),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(r.errors)throw new Error(`Cloudflare upsert failed: ${r.errors.map(({message:o})=>o).join(", ")}`);return{ids:r.result.ids}};batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length<1)throw new Error("Batch request is empty");if(!e[0]||!e[0].table)throw new Error("Table name is empty");let r=e[0].table,o=await ke({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,Es),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(i=>({id:i.id,values:i.values,namespace:i.namespace,metadata:i.metadata})));if(o.errors)throw new Error(`Cloudflare batch upsert failed: ${o.errors.map(({message:i})=>i).join(", ")}`);return{ids:o.result.ids}};query=async(e,t)=>{let n=await ke({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,Es),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:t?.span},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:o})=>o).join(", ")}`);return{matches:n.result.matches.map(({id:o,score:i,values:a,metadata:l})=>({id:o,score:i,values:a,metadata:l}))}}};var yt=class extends qe{state;constructor({tracer:e}={}){super({name:"Memory",tracer:e}),this.state={}}_upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let r=this.state[e.table];if(!r)throw new Error(`Table not found: ${e.table}`);r[e.id]=e}return{ids:[e.id]}};_batchUpsert=async(e,t,n)=>{let r=[];for(let o of e){let i=await this.upsert(o,t);r.push(...i.ids)}return{ids:r}};_query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let r=[];return Object.entries(n).forEach(([o,i])=>{if(e.values&&i.values){let a=au(e.values,i.values);r.push({id:o,score:a,metadata:i.metadata})}}),r.sort((o,i)=>o.score-i.score),e.limit&&(r.length=e.limit),{matches:r}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},au=(s,e)=>{if(s.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,r=0,o=!0,i=!0,a=new Float64Array(s),l=new Float64Array(e);for(let d=0;d<a.length;d++)t+=a[d]*l[d],n+=a[d]*a[d],r+=l[d]*l[d],a[d]!==0&&(o=!1),l[d]!==0&&(i=!1);if(o||i)return 1;let c=Math.sqrt(n),u=Math.sqrt(r);return 1-t/(c*u)};var lu=s=>({namespace:s.namespace,topK:s.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:s.values??[],id:s.id}),un=class extends qe{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]});_batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await ke({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:r,values:o=[],metadata:i})=>({id:r,values:o,metadata:i}))),{ids:e.map(({id:r})=>r)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await ke({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},lu(e))).matches.map(({id:o,score:i,values:a,metadata:l})=>({id:o,score:i,metadata:l,values:a}))}}};var pn=class extends qe{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>{let r=await ke({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:n?.span},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:e.metadata??{}});if(r?.result?.errors)throw new Error(`Weaviate upsert failed: ${r.result.errors.error.map(({message:o})=>o).join(", ")}`);return{ids:[r.id]}};_batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length===0)throw new Error("Batch request is empty");let r=e.map(i=>({id:i.id,class:i.table,tenant:i.namespace,vector:i.values,properties:i.metadata??{}})),o=await ke({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:r});if(o?.some(({result:i})=>i?.errors))throw new Error(`Weaviate batch upsert failed: ${o.map(({result:i})=>i?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:o.map(({id:i})=>i)}};_query=async(e,t)=>{let n="";if(e.columns&&e.columns.length===0)throw new Error("Weaviate requires at least one column");if(e.values)n=`nearVector: {
|
|
161
|
+
`)};function Jr(s){let e=[];for(let t of s??[])if(t?.type==="output_text"&&Array.isArray(t.annotations))for(let n of t.annotations)n&&n.type==="url_citation"&&typeof n.url=="string"&&e.push({url:n.url,title:n.title,description:n.description});return e.length?e:void 0}var qn=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),Ea=()=>({...qn(),model:"gpt-4o",temperature:.5}),Pa=()=>({...qn(),model:"gpt-4o",temperature:.9}),Bn=class extends he{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=[],models:i,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new nn(t,n?.streamingUsage??!0,a),u=i?.map(d=>{let p=d,m=p?.config;if(!m)return d;let g={};m.maxTokens!==void 0&&(g.maxTokens=m.maxTokens),m.temperature!==void 0&&(g.temperature=m.temperature),m.topP!==void 0&&(g.topP=m.topP),m.presencePenalty!==void 0&&(g.presencePenalty=m.presencePenalty),m.frequencyPenalty!==void 0&&(g.frequencyPenalty=m.frequencyPenalty);let h=m.stopSequences??m.stop;h!==void 0&&(g.stopSequences=h),m.n!==void 0&&(g.n=m.n),m.stream!==void 0&&(g.stream=m.stream);let f={...p};Object.keys(g).length>0&&(f.modelConfig={...p.modelConfig??{},...g});let A=m?.thinking?.thinkingTokenBudget;if(typeof A=="number"){let x=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],y="minimal",I=Number.POSITIVE_INFINITY;for(let[E,C]of x){let T=Math.abs(A-C);T<I&&(I=T,y=E)}f.thinkingTokenBudget=y}return m?.thinking?.includeThoughts!==void 0&&(f.showThoughts=!!m.thinking.includeThoughts),f});super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model??"gpt-4o",embedModel:t.embedModel??"text-embedding-ada-002"},options:n,supportFor:l,models:u??i})}},rn=class extends Bn{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...kr,...o??[]];let i=a=>{let l=Ue({model:a,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!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:{...qn(),...t},options:n,modelInfo:o,models:r,supportFor:i})}};var ws=()=>structuredClone({model:"openrouter/auto",...te()}),on=class extends fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o,referer:i,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let l={...ws(),...t},c={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},u=o??[];super({apiKey:e,config:l,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:u,models:r,supportFor:c}),super.setName("OpenRouter"),super.setHeaders(async()=>{let d={Authorization:`Bearer ${e}`};return i&&(d["HTTP-Referer"]=i),a&&(d["X-Title"]=a),d})}};async function Yr(s,e,t={}){if(typeof s=="string")return[{type:"text",text:s}];if(!Array.isArray(s))return[{type:"text",text:String(s)}];let n=e.getFeatures(),r=[];for(let o of s)try{switch(o.type){case"text":r.push({type:"text",text:o.text});break;case"image":if(n.media.images.supported)o.altText?r.push({type:"text",text:`[Image: ${o.altText}]`}):r.push({type:"text",text:"[Image content]"});else if(o.altText)r.push({type:"text",text:o.altText});else if(t.imageToText)try{let i=await t.imageToText(o.image);r.push({type:"text",text:i})}catch(i){throw new Ye(i,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new qe("Images",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:"[Image content not supported by this provider]"})}break;case"audio":if(n.media.audio.supported)o.transcription?r.push({type:"text",text:o.transcription}):r.push({type:"text",text:"[Audio content]"});else if(o.transcription)r.push({type:"text",text:o.transcription});else if(t.audioToText)try{let i=await t.audioToText(o.data,o.format);r.push({type:"text",text:i})}catch(i){throw new Ye(i,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new qe("Audio",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:"[Audio content not supported by this provider]"})}break;case"file":if(n.media.files.supported)o.extractedText?r.push({type:"text",text:o.extractedText}):r.push({type:"text",text:`[File: ${o.filename}]`});else if(o.extractedText)r.push({type:"text",text:o.extractedText});else if(t.fileToText)try{let i=await t.fileToText(o.data,o.mimeType);r.push({type:"text",text:i})}catch(i){throw new Ye(i,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new qe("Files",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:`[File: ${o.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)o.cachedContent?r.push({type:"text",text:o.cachedContent}):r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`});else if(o.cachedContent)r.push({type:"text",text:o.cachedContent});else if(t.urlToText)try{let i=await t.urlToText(o.url);r.push({type:"text",text:i})}catch(i){throw new Ye(i,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new qe("URLs",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`})}break;default:typeof o=="object"&&o.text?r.push({type:"text",text:o.text}):r.push({type:"text",text:String(o)})}}catch(i){throw i instanceof qe||i instanceof Ye?i:new Ye(i,o.type||"unknown","content processing")}return r}function _a(s){let e=!1,t=!1,n=!1,r=!1;for(let o of s)if(o.role==="user"&&Array.isArray(o.content))for(let i of o.content)switch(i.type){case"image":e=!0;break;case"audio":t=!0;break;case"file":n=!0;break;case"url":r=!0;break}return{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r}}var zn=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(zn||{});var Qr=[{name:"reka-core",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"reka-flash",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2},{name:"reka-edge",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1}];var jn=()=>structuredClone({model:"reka-core",...te()}),Da=()=>structuredClone({...jn(),model:"reka-core"}),Na=()=>structuredClone({model:"reka-core",...Ae()}),$a=()=>({...jn(),model:"reka-flash"}),vs=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=e=>{let t=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let n={name:"/chat/completions"},r=iu(e),o=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,i=e.modelConfig?.stream??this.config.stream,a={model:t,messages:r,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},top_k:e.modelConfig?.n??this.config.n,...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},stop:e.modelConfig?.stopSequences??this.config.stop,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...o?{frequency_penalty:o}:{},...i?{stream:!0}:{}};return[n,a]};createChatResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((i,a)=>{let l=Fa(i.finish_reason),c;return typeof i.message.content=="string"?c=i.message.content:c=i.message.content.text,{index:a,id:`${t}`,content:c,finishReason:l}}),remoteId:t}};createChatStreamResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((i,a)=>{let l=Fa(i.finish_reason),c;return typeof i.chunk.content=="string"?c=i.chunk.content:c=i.chunk.content.text,{index:a,id:`${t}`,content:c,finishReason:l}})}}},Fa=s=>{switch(s){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function iu(s){return s.chatPrompt.map(e=>{switch(e.role){case"system":return{role:"user",content:e.content};case"user":return Array.isArray(e.content)?{role:"user",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})}:{role:"user",content:e.content};case"assistant":if(Array.isArray(e.content))return{role:"assistant",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})};if(!e.content)throw new Error("Assistant content is empty");return{role:"user",content:e.content};default:throw new Error("Invalid role")}})}var sn=class extends he{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=Qr,models:i}){if(!e||e==="")throw new Error("Reka API key not set");let a={...jn(),...t},l=new vs(a);super(l,{name:"Reka",apiURL:r||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:o,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:i})}};var Zr=class{providers;processingServices;config;constructor(e){this.providers=[e.providers.primary,...e.providers.alternatives],this.processingServices=e.processing,this.config=e.routing}async chat(e,t={}){let n=await this.selectProviderWithDegradation(e,t.routingOptions||{}),r=await this.preprocessRequest(e,n.provider,t.processingOptions);try{return{response:await n.provider.chat(r,t),routing:n}}catch(o){if(o instanceof qe&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw o}}async preprocessRequest(e,t,n){let r={...n,fallbackBehavior:n?.fallbackBehavior||"degrade",imageToText:n?.imageToText||this.processingServices.imageToText,audioToText:n?.audioToText||this.processingServices.audioToText,fileToText:n?.fileToText||this.processingServices.fileToText,urlToText:n?.urlToText||this.processingServices.urlToText},o=[];for(let i of e.chatPrompt)if(i.role==="user"&&Array.isArray(i.content)){let a=await Yr(i.content,t,r);a.every(c=>c.type==="text")&&a.length===1?o.push({...i,content:a[0].text}):o.push({...i,content:a.map(c=>({type:"text",text:c.text}))})}else o.push(i);return{...e,chatPrompt:o}}async selectProviderWithDegradation(e,t){let n=kt(e),r=[],o=[],i=[];try{let a=Dr(e,this.providers,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation}),l=a.getFeatures();return n.hasImages&&!l.media.images.supported&&(o.push("Images will be converted to text descriptions"),r.push("Image-to-text conversion")),n.hasAudio&&!l.media.audio.supported&&(o.push("Audio will be transcribed to text"),r.push("Audio-to-text transcription")),n.hasFiles&&!l.media.files.supported&&(o.push("File content will be extracted to text"),r.push("File-to-text extraction")),n.hasUrls&&!l.media.urls.supported&&(o.push("URL content will be pre-fetched"),r.push("URL content fetching")),n.requiresStreaming&&!l.streaming&&i.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!l.caching.supported&&i.push("Content caching not supported"),{provider:a,processingApplied:r,degradations:o,warnings:i}}catch(a){throw new Error(`Provider selection failed: ${a instanceof Error?a.message:"Unknown error"}`)}}async tryFallbackProviders(e,t,n){for(let r of t)try{let o={provider:r,processingApplied:["Fallback provider selection"],degradations:["Using fallback provider due to primary provider failure"],warnings:[]},i=await this.preprocessRequest(e,r,{fallbackBehavior:"degrade"});return{response:await r.chat(i,n),routing:o}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=kt(e),n=[],r=[];try{let o=await this.selectProviderWithDegradation(e,{});return o.degradations.length>0&&(n.push(...o.degradations),r.push("Consider using a provider that natively supports all media types")),o.warnings.length>0&&n.push(...o.warnings),t.hasImages&&this.processingServices.imageToText===void 0&&(this.providers.some(a=>a.getFeatures().media.images.supported)||(n.push("No image processing service available and no providers support images"),r.push("Add imageToText processing service or use image-capable provider"))),t.hasAudio&&this.processingServices.audioToText===void 0&&(this.providers.some(a=>a.getFeatures().media.audio.supported)||(n.push("No audio processing service available and no providers support audio"),r.push("Add audioToText processing service or use audio-capable provider"))),{canHandle:n.length===0||o.degradations.length>0,issues:n,recommendations:r}}catch(o){return{canHandle:!1,issues:[`Cannot route request: ${o instanceof Error?o.message:"Unknown error"}`],recommendations:["Add more providers or processing services to handle this request"]}}}getRoutingStats(){let e={};for(let t of this.providers){let n=t.getFeatures(),r=t.getName();n.functions&&(e.Functions=e.Functions||[],e.Functions.push(r)),n.streaming&&(e.Streaming=e.Streaming||[],e.Streaming.push(r)),n.media.images.supported&&(e.Images=e.Images||[],e.Images.push(r)),n.media.audio.supported&&(e.Audio=e.Audio||[],e.Audio.push(r)),n.media.files.supported&&(e.Files=e.Files||[],e.Files.push(r)),n.media.urls.supported&&(e.URLs=e.URLs||[],e.URLs.push(r)),n.caching.supported&&(e.Caching=e.Caching||[],e.Caching.push(r))}return{totalProviders:this.providers.length,capabilityMatrix:e,recommendedProvider:this.providers[0]?.getName()||"None"}}};var Xr=[];var Ss=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...te()}),an=class extends fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Together API key not set");let i={...Ss(),...t};o=[...Xr,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:i,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:o,models:r,supportFor:a}),super.setName("Together")}};var Hn=(p=>(p.Llama31_8B_Instruct="Llama-3.1-8B-Instruct-q4f32_1-MLC",p.Llama31_70B_Instruct="Llama-3.1-70B-Instruct-q4f16_1-MLC",p.Llama32_1B_Instruct="Llama-3.2-1B-Instruct-q4f32_1-MLC",p.Llama32_3B_Instruct="Llama-3.2-3B-Instruct-q4f32_1-MLC",p.Mistral7B_Instruct="Mistral-7B-Instruct-v0.3-q4f32_1-MLC",p.Phi35_Mini_Instruct="Phi-3.5-mini-instruct-q4f32_1-MLC",p.Gemma2_2B_Instruct="gemma-2-2b-it-q4f32_1-MLC",p.Gemma2_9B_Instruct="gemma-2-9b-it-q4f32_1-MLC",p.Qwen2_5_0_5B_Instruct="Qwen2.5-0.5B-Instruct-q4f32_1-MLC",p.Qwen2_5_1_5B_Instruct="Qwen2.5-1.5B-Instruct-q4f32_1-MLC",p.Qwen2_5_3B_Instruct="Qwen2.5-3B-Instruct-q4f32_1-MLC",p.Qwen2_5_7B_Instruct="Qwen2.5-7B-Instruct-q4f32_1-MLC",p))(Hn||{});var eo=[{name:"Llama-3.1-8B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"Llama-3.1-70B-Instruct-q4f16_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096,isExpensive:!0},{name:"Llama-3.2-1B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Llama-3.2-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Mistral-7B-Instruct-v0.3-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096},{name:"Phi-3.5-mini-instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"gemma-2-2b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"gemma-2-9b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"Qwen2.5-0.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-1.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-7B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096}];var ks=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...te()}),Ga=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Ae()}),Os=class{constructor(e,t){this.config=e;this.engine=t}tokensUsed;engine;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.map(a=>{if(a.role==="function")return{role:"function",name:a.functionId,content:typeof a.result=="string"?a.result:JSON.stringify(a.result)};let l="";typeof a.content=="string"?l=a.content:Array.isArray(a.content)&&(l=a.content.filter(u=>u.type==="text").map(u=>u.text).join(`
|
|
162
|
+
`));let c={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...c,tool_calls:a.functionCalls.map(u=>({id:u.id,type:"function",function:{name:u.function.name,arguments:typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params||{})}}))}:c}),r=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),o={name:"/chat/completions",localCall:async(a,l)=>{try{let c=await this.engine.chat.completions.create({...a,stream:l||!1});return l?new ReadableStream({async start(u){try{for await(let d of c)u.enqueue(d);u.close()}catch(d){u.error(d)}}}):c}catch(c){throw new Error(`WebLLM API error: ${c}`)}}},i={model:t,messages:n,...r?.length?{tools:r}:{},max_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}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,stop:e.modelConfig?.stopSequences??this.config.stopSequences,stream:e.modelConfig?.stream??this.config.stream,n:e.modelConfig?.n??this.config.n};return[o,i]}createEmbedReq=e=>{throw new Error("WebLLM does not support embeddings")};createChatResp=e=>(this.tokensUsed={promptTokens:e.usage?.prompt_tokens??0,completionTokens:e.usage?.completion_tokens??0,totalTokens:e.usage?.total_tokens??0},{results:e.choices.map((n,r)=>{let o="stop";switch(n.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let i=n.message.tool_calls?.map(a=>({id:a.id,type:"function",function:{name:a.function.name,params:a.function.arguments}}));return{index:r,id:e.id,content:n.message.content||"",functionCalls:i,finishReason:o}}),remoteId:e.id});createChatStreamResp=(e,t)=>{let n=t,r=e.choices[0];if(!r)throw new Error("No choice in WebLLM stream response");if(r.delta.content&&(n.content=(n.content||"")+r.delta.content),r.delta.tool_calls){n.toolCalls||(n.toolCalls=[]);for(let l of r.delta.tool_calls){let c=n.toolCalls[l.index];c?l.function?.arguments&&(c.function.arguments=(c.function?.arguments||"")+l.function.arguments):n.toolCalls[l.index]={id:l.id,type:l.type,function:{name:l.function?.name,arguments:l.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let o;if(r.finish_reason)switch(r.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let i=n.toolCalls?.map(l=>({id:l.id||"",type:"function",function:{name:l.function?.name||"",params:l.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:i,finishReason:o}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},ln=class extends he{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let o={...ks(),...t},i=new Os(o,e);super(i,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:eo,defaults:{model:o.model},supportFor:a=>({functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}),options:n,models:r})}};var Kn=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(Kn||{}),Ms=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Ms||{});var to=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,supported:{thinkingBudget:!0}},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,supported:{thinkingBudget:!0}}];var no=()=>structuredClone({model:"grok-3-mini",...te()}),La=()=>structuredClone({...no(),model:"grok-3"}),cn=class extends fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Grok API key not set");let i={...no(),...t};o=[...to,...o??[]];let a=c=>{let u=Ue({model:c,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}},l=c=>{if(n?.searchParameters){let u=n.searchParameters;return{...c,search_parameters:{mode:u.mode,return_citations:u.returnCitations,from_date:u.fromDate,to_date:u.toDate,max_search_results:u.maxSearchResults,sources:u.sources?.map(d=>({type:d.type,country:d.country,excluded_websites:d.excludedWebsites,allowed_websites:d.allowedWebsites,safe_search:d.safeSearch,x_handles:d.xHandles,links:d.links}))}}}return c};super({apiKey:e,config:i,options:n,apiURL:"https://api.x.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};function Ua(s){return Wn.create(s)}var Wn=class s{ai;static create(e){return new s(e)}constructor(e){switch(e.name){case"openai":this.ai=new Kt(e);break;case"openai-responses":this.ai=new rn(e);break;case"azure-openai":this.ai=new Wt(e);break;case"grok":this.ai=new cn(e);break;case"huggingface":this.ai=new Xt(e);break;case"groq":this.ai=new Zt(e);break;case"together":this.ai=new an(e);break;case"openrouter":this.ai=new on(e);break;case"cohere":this.ai=new Vt(e);break;case"google-gemini":this.ai=new Yt(e);break;case"anthropic":this.ai=new qt(e);break;case"mistral":this.ai=new en(e);break;case"deepseek":this.ai=new Jt(e);break;case"ollama":this.ai=new tn(e);break;case"reka":this.ai=new sn(e);break;case"webllm":this.ai=new ln(e);break;default:throw new Error("Unknown AI")}}getName(){return this.ai.getName()}getId(){return this.ai.getId()}getFeatures(e){return this.ai.getFeatures(e)}getModelList(){return this.ai.getModelList()}getLastUsedChatModel(){return this.ai.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.ai.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.ai.getLastUsedModelConfig()}getMetrics(){return this.ai.getMetrics()}async chat(e,t){return await this.ai.chat(e,t)}async embed(e,t){return await this.ai.embed(e,t)}setOptions(e){this.ai.setOptions(e)}getOptions(){return this.ai.getOptions()}getLogger(){return this.ai.getLogger()}};var ze=class{name;fetch;tracer;_upsert;_batchUpsert;_query;constructor({name:e,fetch:t,tracer:n}){this.name=e,this.fetch=t,this.tracer=n}async upsert(e,t){if(!this._upsert)throw new Error("upsert() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Upsert Request",{kind:Me.SERVER,attributes:{[V.DB_SYSTEM]:this.name,[V.DB_OPERATION_NAME]:"upsert",[V.DB_TABLE]:e.table,[V.DB_NAMESPACE]:e.namespace,[V.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._upsert(e,t,{span:n})}finally{n.end()}}):await this._upsert(e,t)}async batchUpsert(e,t){if(!this._batchUpsert)throw new Error("batchUpsert() not implemented");if(e.length===0)throw new Error("Batch request is empty");if(!e[0])throw new Error("Batch request is invalid first element is undefined");return this.tracer?await this.tracer.startActiveSpan("DB Batch Upsert Request",{kind:Me.SERVER,attributes:{[V.DB_SYSTEM]:this.name,[V.DB_OPERATION_NAME]:"upsert",[V.DB_TABLE]:e[0].table,[V.DB_NAMESPACE]:e[0].namespace,[V.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._batchUpsert(e,t,{span:n})}finally{n.end()}}):await this._batchUpsert(e,t)}async query(e){if(!this._query)throw new Error("query() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Query Request",{kind:Me.SERVER,attributes:{[V.DB_SYSTEM]:this.name,[V.DB_OPERATION_NAME]:"upsert",[V.DB_TABLE]:e.table,[V.DB_NAMESPACE]:e.namespace,[V.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var Es="https://api.cloudflare.com/client/v4/accounts/",un=class extends ze{apiKey;accountId;constructor({apiKey:e,accountId:t,fetch:n,tracer:r}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:r}),this.apiKey=e,this.accountId=t}_upsert=async(e,t,n)=>{let r=await ke({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,Es),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(r.errors)throw new Error(`Cloudflare upsert failed: ${r.errors.map(({message:o})=>o).join(", ")}`);return{ids:r.result.ids}};batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length<1)throw new Error("Batch request is empty");if(!e[0]||!e[0].table)throw new Error("Table name is empty");let r=e[0].table,o=await ke({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,Es),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(i=>({id:i.id,values:i.values,namespace:i.namespace,metadata:i.metadata})));if(o.errors)throw new Error(`Cloudflare batch upsert failed: ${o.errors.map(({message:i})=>i).join(", ")}`);return{ids:o.result.ids}};query=async(e,t)=>{let n=await ke({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,Es),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:t?.span},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:o})=>o).join(", ")}`);return{matches:n.result.matches.map(({id:o,score:i,values:a,metadata:l})=>({id:o,score:i,values:a,metadata:l}))}}};var bt=class extends ze{state;constructor({tracer:e}={}){super({name:"Memory",tracer:e}),this.state={}}_upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let r=this.state[e.table];if(!r)throw new Error(`Table not found: ${e.table}`);r[e.id]=e}return{ids:[e.id]}};_batchUpsert=async(e,t,n)=>{let r=[];for(let o of e){let i=await this.upsert(o,t);r.push(...i.ids)}return{ids:r}};_query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let r=[];return Object.entries(n).forEach(([o,i])=>{if(e.values&&i.values){let a=au(e.values,i.values);r.push({id:o,score:a,metadata:i.metadata})}}),r.sort((o,i)=>o.score-i.score),e.limit&&(r.length=e.limit),{matches:r}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},au=(s,e)=>{if(s.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,r=0,o=!0,i=!0,a=new Float64Array(s),l=new Float64Array(e);for(let p=0;p<a.length;p++)t+=a[p]*l[p],n+=a[p]*a[p],r+=l[p]*l[p],a[p]!==0&&(o=!1),l[p]!==0&&(i=!1);if(o||i)return 1;let c=Math.sqrt(n),u=Math.sqrt(r);return 1-t/(c*u)};var lu=s=>({namespace:s.namespace,topK:s.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:s.values??[],id:s.id}),pn=class extends ze{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]});_batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await ke({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:r,values:o=[],metadata:i})=>({id:r,values:o,metadata:i}))),{ids:e.map(({id:r})=>r)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await ke({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},lu(e))).matches.map(({id:o,score:i,values:a,metadata:l})=>({id:o,score:i,metadata:l,values:a}))}}};var dn=class extends ze{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>{let r=await ke({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:n?.span},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:e.metadata??{}});if(r?.result?.errors)throw new Error(`Weaviate upsert failed: ${r.result.errors.error.map(({message:o})=>o).join(", ")}`);return{ids:[r.id]}};_batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length===0)throw new Error("Batch request is empty");let r=e.map(i=>({id:i.id,class:i.table,tenant:i.namespace,vector:i.values,properties:i.metadata??{}})),o=await ke({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:r});if(o?.some(({result:i})=>i?.errors))throw new Error(`Weaviate batch upsert failed: ${o.map(({result:i})=>i?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:o.map(({id:i})=>i)}};_query=async(e,t)=>{let n="";if(e.columns&&e.columns.length===0)throw new Error("Weaviate requires at least one column");if(e.values)n=`nearVector: {
|
|
163
163
|
vector: [${e.values.join(",")}],
|
|
164
164
|
}`;else if(e.text)n=`nearText: {
|
|
165
165
|
concepts: ['${e.text}'],
|
|
@@ -173,9 +173,9 @@ ${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
|
|
|
173
173
|
`)}
|
|
174
174
|
}
|
|
175
175
|
}
|
|
176
|
-
}`});if(r.errors)throw new Error(`Weaviate query failed: ${r.errors.map(({message:a})=>a).join(", ")}`);let o=r.data.Get[e.table];return o?{matches:o.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var ro=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new
|
|
176
|
+
}`});if(r.errors)throw new Error(`Weaviate query failed: ${r.errors.map(({message:a})=>a).join(", ")}`);let o=r.data.Get[e.table];return o?{matches:o.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var ro=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new dn(e);break;case"pinecone":this.db=new pn(e);break;case"cloudflare":this.db=new un(e);break;case"memory":this.db=new bt(e);break;default:throw new Error("Unknown DB")}}async upsert(e,t){return await this.db.upsert(e,t)}async batchUpsert(e,t){return await this.db.batchUpsert(e,t)}async query(e){return await this.db.query(e)}};var Ps="_internal",oo=class{ai;db;chunker;rewriter;reranker;constructor({ai:e,db:t,config:n}){this.ai=e,this.db=t,this.chunker=n?.chunker??this.defaultChunker,this.reranker=n?.reranker,this.rewriter=n?.rewriter}defaultChunker=e=>e.split(/\n\n+/);insert=async(e,t)=>{try{let n=Array.isArray(e)?e.join(`
|
|
177
177
|
|
|
178
|
-
`):e,r=this.chunker(n).filter(c=>c.length>0),o=t?.maxWordsPerChunk,i=t?.minWordsPerChunk,a=cu({initialChunks:r,minWordsPerChunk:i,maxWordsPerChunk:o}),l=t?.batchSize??10;for(let c=0;c<a.length;c+=l){let u=a.slice(c,c+l),
|
|
178
|
+
`):e,r=this.chunker(n).filter(c=>c.length>0),o=t?.maxWordsPerChunk,i=t?.minWordsPerChunk,a=cu({initialChunks:r,minWordsPerChunk:i,maxWordsPerChunk:o}),l=t?.batchSize??10;for(let c=0;c<a.length;c+=l){let u=a.slice(c,c+l),p=(await this.ai.embed({texts:u},{abortSignal:t?.abortSignal})).embeddings.map((m,g)=>({id:`chunk_${Date.now()+g}`,table:Ps,values:m,metadata:{text:u[g]??""}})).filter(m=>m.metadata?.text&&m.metadata?.text.length>0);await this.db.batchUpsert(p)}}catch(n){throw new Error(`Error processing text: ${n}`)}};query=async(e,{topPercent:t,abortSignal:n}={})=>{let r=Array.isArray(e)?e:[e];if(typeof r[0]=="string"&&this.rewriter)for(let[l,c]of r.entries()){let{rewrittenQuery:u}=await this.rewriter.forward(this.ai,{query:c});r[l]=u}let o;typeof r[0]=="string"?o=(await this.ai.embed({texts:r},{abortSignal:n})).embeddings.map(c=>this.db.query({table:Ps,values:c})):o=r.map(l=>this.db.query({table:Ps,values:l}));let i=await Promise.all(o),a=[];for(let{matches:l}of i){let c=l.filter(p=>p.metadata?.text&&p.metadata?.text.length>0).map(({score:p,metadata:m})=>({score:p,text:m?.text??""})),u=t&&t>1?t/100:t,d=u?uu(c,u):c;if(this.reranker){let{rankedItems:p}=await this.reranker.forward(this.ai,{query:r[0],items:d.map(g=>g.text)}),m=p.map(g=>d.find(h=>h.text===g)).filter(g=>g!==void 0);a.push(m)}else a.push(d)}return a}},cu=({initialChunks:s,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],r="",o=0;return s.forEach(i=>{let a=i.split(/\s+/),l=a.length;if(o+l<=e)r+=`${i}
|
|
179
179
|
|
|
180
180
|
`,o+=l;else if(o>0&&o+l<=e*1.5)r+=`${i}
|
|
181
181
|
|
|
@@ -183,24 +183,24 @@ ${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},uu=(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 Wn=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}},dn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Wn}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Wn),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Ut(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){vr(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 Wn):this.defaultMemory.reset()}};var tt=class extends Error{constructor({message:e}){super(e),this.name=this.constructor.name}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},so=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 tt({message:o});if(!o)throw r?new tt({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},_s=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 tt({message:c});if(!c&&a)throw new tt({message:a})}}};var Fs={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Vn,Ds=s=>{if(Vn)return Vn;let e=s??ce.meter;if(e)return Vn=pu(e),Vn};var Ba=()=>{let s=[];return ce.meter||s.push("Global meter not initialized"),!Vn&&ce.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},pu=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"})}),io=Fs,qa=s=>{io={...io,...s}},za=()=>({...io}),Ze=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=io.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},ja=(s,e,t,n,r,o)=>{try{let i=Ze({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)}},ao=(s,e,t,n)=>{try{let r=Ze({...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)}},Ns=(s,e,t)=>{try{let n=Ze({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)}},Ha=(s,e)=>{try{let t=Ze({error_type:"refusal",...e?{signature:e}:{}});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},$s=(s,e,t,n,r)=>{try{let o=Ze({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)}},Ka=(s,e,t,n,r=!1,o)=>{try{let i=Ze({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)}},Wa=(s,e,t,n)=>{try{let r=Ze({...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)}},Va=(s,e,t,n,r)=>{try{let o=Ze({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)}},Ja=(s,e,t,n,r)=>{try{let o=Ze({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)}},Ya=(s,e,t,n,r,o)=>{try{let i=Ze({...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)}},lo=(s,e,t,n)=>{try{let r=Ze({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 mn=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},Ee=class extends Error{constructor(e){super(e),this.name=this.constructor.name}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()}},Qa=s=>{let t=s.map(n=>`'${n.title}' (${mn(n.type)})`).join(", ");return new Ee(`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 ${mn(s[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},co=s=>new Ee(`Expected (Required) field not found: '${s.title}'. Begin a new section with "${s.title}:" and then provide a valid ${mn(s.type)} value directly after.`);var Za=s=>new Ee(`Required field is missing: '${s.title}'. After the "${s.title}:" label, provide a non-empty ${mn(s.type)}. Do not use null, undefined, or leave it blank.`),Xa=(s,e)=>new Ee(`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.`),el=(s,e)=>new Ee(`Invalid Array: ${e} for '${s.title}'. Provide a JSON array of ${mn(s.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),tl=(s,e,t)=>new Ee(`Field '${s.title}' has an invalid value '${e}': ${t}. Provide a ${mn(s.type)}. Ensure formatting exactly matches the expected type.`),nl=(s,e,t)=>new Ee(`Invalid date for '${s.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),rl=(s,e,t)=>new Ee(`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}.`);var ol=({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(", ")??"";ji(s,e,l,n)}return r&&Ns(r,"validation",o),i&&i.addEvent("validation.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},sl=({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(", ")??"";Hi(s,e,l,n)}return r&&Ns(r,"assertion",o),i&&i.addEvent("assertion.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},il=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{t&&n&&Ki(s,e,n),r&&Ha(r,o),i&&i.addEvent("refusal.error",{message:s.toString()})};var al=s=>{let e=[],t=(n,r="")=>{if(!n||typeof n!="object")return;let o=["array","integer","number","string","boolean","null","object"];if(n.anyOf&&Array.isArray(n.anyOf)){n.anyOf.length===0&&e.push({path:r||"root",issue:"anyOf array is empty",fix:"Add at least one schema to the anyOf array",example:'anyOf: [{ type: "string" }, { type: "null" }]'}),n.anyOf.forEach((i,a)=>{t(i,`${r}anyOf[${a}].`)});return}if(n.oneOf&&Array.isArray(n.oneOf)){n.oneOf.length===0&&e.push({path:r||"root",issue:"oneOf array is empty",fix:"Add at least one schema to the oneOf array",example:'oneOf: [{ type: "string" }, { type: "number" }]'}),n.oneOf.forEach((i,a)=>{t(i,`${r}oneOf[${a}].`)});return}if(n.allOf&&Array.isArray(n.allOf)){n.allOf.length===0&&e.push({path:r||"root",issue:"allOf array is empty",fix:"Add at least one schema to the allOf array",example:'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'}),n.allOf.forEach((i,a)=>{t(i,`${r}allOf[${a}].`)});return}if(n.type){if(!o.includes(n.type)){e.push({path:r||"root",issue:`Invalid type '${n.type}'`,fix:`Change type to one of: ${o.join(", ")}`,example:'{ type: "string" } or { type: "object" }'});return}if(n.type==="object"){if(n.properties)if(typeof n.properties!="object"||Array.isArray(n.properties))e.push({path:r||"root",issue:"properties must be an object, not an array or primitive",fix:"Change properties to be an object with property names as keys",example:'properties: { name: { type: "string" }, age: { type: "number" } }'});else for(let i in n.properties){let a=n.properties[i];if(a!=null){if(typeof a!="object"){e.push({path:`${r}${i}`,issue:`Property schema must be an object, got ${typeof a}`,fix:"Define the property as a proper schema object",example:`${i}: { type: "string", description: "..." }`});continue}t(a,`${r}${i}.`)}}if(n.required){if(!Array.isArray(n.required))e.push({path:r||"root",issue:`'required' must be an array, got ${typeof n.required}`,fix:"Change required to be an array of property names",example:'required: ["name", "email"] instead of required: "name,email"'});else if(n.required.length!==0){if(n.properties)for(let i of n.required)typeof i!="string"?e.push({path:`${r}required`,issue:`Required property names must be strings, got ${typeof i}`,fix:"Ensure all items in required array are strings",example:'required: ["name", "email"] not required: [123, "email"]'}):i in n.properties||e.push({path:`${r}required`,issue:`Required property '${i}' is not defined in properties`,fix:`Either add '${i}' to properties or remove it from required`,example:`properties: { ${i}: { type: "string" } }`})}}}n.type==="array"&&(n.items?typeof n.items!="object"?e.push({path:`${r}items`,issue:`Array items schema must be an object, got ${typeof n.items}`,fix:"Define items as a proper schema object",example:'items: { type: "string" } or items: { type: "object", properties: {...} }'}):t(n.items,`${r}items.`):e.push({path:r||"root",issue:'Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)',fix:'Add an "items" schema describing the array element type, e.g., items: { type: "string" } or items: { type: "object", properties: { ... } }',example:['type: "array",','description: "List of step strings"','items: { type: "string" }'].join(`
|
|
186
|
+
`,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},uu=(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 Vn=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}},mn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Vn}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Vn),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Bt(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){vr(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 Vn):this.defaultMemory.reset()}};var nt=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()}},so=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 nt({message:o});if(!o)throw r?new nt({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},_s=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 nt({message:c});if(!c&&a)throw new nt({message:a})}}};var Fs={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Jn,Ds=s=>{if(Jn)return Jn;let e=s??ee.meter;if(e)return Jn=pu(e),Jn};var Ba=()=>{let s=[];return ee.meter||s.push("Global meter not initialized"),!Jn&&ee.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},pu=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"})}),io=Fs,qa=s=>{io={...io,...s}},za=()=>({...io}),Xe=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=io.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},ja=(s,e,t,n,r,o)=>{try{let i=Xe({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)}},ao=(s,e,t,n)=>{try{let r=Xe({...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)}},Ns=(s,e,t)=>{try{let n=Xe({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)}},Ha=(s,e)=>{try{let t=Xe({error_type:"refusal",...e?{signature:e}:{}});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},$s=(s,e,t,n,r)=>{try{let o=Xe({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)}},Ka=(s,e,t,n,r=!1,o)=>{try{let i=Xe({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)}},Wa=(s,e,t,n)=>{try{let r=Xe({...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)}},Va=(s,e,t,n,r)=>{try{let o=Xe({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)}},Ja=(s,e,t,n,r)=>{try{let o=Xe({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)}},Ya=(s,e,t,n,r,o)=>{try{let i=Xe({...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)}},lo=(s,e,t,n)=>{try{let r=Xe({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 gn=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},Ee=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()}},Qa=s=>{let t=s.map(n=>`'${n.title}' (${gn(n.type)})`).join(", ");return new Ee(`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 ${gn(s[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},co=s=>new Ee(`Expected (Required) field not found: '${s.title}'. Begin a new section with "${s.title}:" and then provide a valid ${gn(s.type)} value directly after.`);var Za=s=>new Ee(`Required field is missing: '${s.title}'. After the "${s.title}:" label, provide a non-empty ${gn(s.type)}. Do not use null, undefined, or leave it blank.`),Xa=(s,e)=>new Ee(`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.`),el=(s,e)=>new Ee(`Invalid Array: ${e} for '${s.title}'. Provide a JSON array of ${gn(s.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),tl=(s,e,t)=>new Ee(`Field '${s.title}' has an invalid value '${e}': ${t}. Provide a ${gn(s.type)}. Ensure formatting exactly matches the expected type.`),nl=(s,e,t)=>new Ee(`Invalid date for '${s.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),rl=(s,e,t)=>new Ee(`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}.`);var ol=({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(", ")??"";ji(s,e,l,n)}return r&&Ns(r,"validation",o),i&&i.addEvent("validation.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},sl=({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(", ")??"";Hi(s,e,l,n)}return r&&Ns(r,"assertion",o),i&&i.addEvent("assertion.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},il=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{t&&n&&Ki(s,e,n),r&&Ha(r,o),i&&i.addEvent("refusal.error",{message:s.toString()})};var al=s=>{let e=[],t=(n,r="")=>{if(!n||typeof n!="object")return;let o=["array","integer","number","string","boolean","null","object"];if(n.anyOf&&Array.isArray(n.anyOf)){n.anyOf.length===0&&e.push({path:r||"root",issue:"anyOf array is empty",fix:"Add at least one schema to the anyOf array",example:'anyOf: [{ type: "string" }, { type: "null" }]'}),n.anyOf.forEach((i,a)=>{t(i,`${r}anyOf[${a}].`)});return}if(n.oneOf&&Array.isArray(n.oneOf)){n.oneOf.length===0&&e.push({path:r||"root",issue:"oneOf array is empty",fix:"Add at least one schema to the oneOf array",example:'oneOf: [{ type: "string" }, { type: "number" }]'}),n.oneOf.forEach((i,a)=>{t(i,`${r}oneOf[${a}].`)});return}if(n.allOf&&Array.isArray(n.allOf)){n.allOf.length===0&&e.push({path:r||"root",issue:"allOf array is empty",fix:"Add at least one schema to the allOf array",example:'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'}),n.allOf.forEach((i,a)=>{t(i,`${r}allOf[${a}].`)});return}if(n.type){if(!o.includes(n.type)){e.push({path:r||"root",issue:`Invalid type '${n.type}'`,fix:`Change type to one of: ${o.join(", ")}`,example:'{ type: "string" } or { type: "object" }'});return}if(n.type==="object"){if(n.properties)if(typeof n.properties!="object"||Array.isArray(n.properties))e.push({path:r||"root",issue:"properties must be an object, not an array or primitive",fix:"Change properties to be an object with property names as keys",example:'properties: { name: { type: "string" }, age: { type: "number" } }'});else for(let i in n.properties){let a=n.properties[i];if(a!=null){if(typeof a!="object"){e.push({path:`${r}${i}`,issue:`Property schema must be an object, got ${typeof a}`,fix:"Define the property as a proper schema object",example:`${i}: { type: "string", description: "..." }`});continue}t(a,`${r}${i}.`)}}if(n.required){if(!Array.isArray(n.required))e.push({path:r||"root",issue:`'required' must be an array, got ${typeof n.required}`,fix:"Change required to be an array of property names",example:'required: ["name", "email"] instead of required: "name,email"'});else if(n.required.length!==0){if(n.properties)for(let i of n.required)typeof i!="string"?e.push({path:`${r}required`,issue:`Required property names must be strings, got ${typeof i}`,fix:"Ensure all items in required array are strings",example:'required: ["name", "email"] not required: [123, "email"]'}):i in n.properties||e.push({path:`${r}required`,issue:`Required property '${i}' is not defined in properties`,fix:`Either add '${i}' to properties or remove it from required`,example:`properties: { ${i}: { type: "string" } }`})}}}n.type==="array"&&(n.items?typeof n.items!="object"?e.push({path:`${r}items`,issue:`Array items schema must be an object, got ${typeof n.items}`,fix:"Define items as a proper schema object",example:'items: { type: "string" } or items: { type: "object", properties: {...} }'}):t(n.items,`${r}items.`):e.push({path:r||"root",issue:'Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)',fix:'Add an "items" schema describing the array element type, e.g., items: { type: "string" } or items: { type: "object", properties: { ... } }',example:['type: "array",','description: "List of step strings"','items: { type: "string" }'].join(`
|
|
187
187
|
`)}))}};if(t(s),e.length>0){let n=["JSON Schema validation failed:","",...e.map((r,o)=>{let i=[`${o+1}. Path: ${r.path}`,` Issue: ${r.issue}`,` Fix: ${r.fix}`];return r.example&&i.push(` Example: ${r.example}`),i.join(`
|
|
188
188
|
`)}),"","Please fix these issues and try again."].join(`
|
|
189
|
-
`);throw new Error(n)}};var
|
|
190
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},
|
|
189
|
+
`);throw new Error(n)}};var Mt=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},Yn=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(`
|
|
190
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Qn=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}'
|
|
191
191
|
${t.join(`
|
|
192
192
|
`)}`};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(`
|
|
193
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},
|
|
193
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Zn=class{funcList=[];constructor(e){this.funcList=e}executeFunction=async(e,t,n)=>{let r;if(typeof t.args=="string"&&t.args.length>0)try{r=JSON.parse(t.args)}catch(c){throw new Error(`Invalid function arguments: ${t.args}`,{cause:c})}else r=t.args;let o=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai}:void 0,i;e.parameters?i=e.func.length===2?await e.func(r,o):await e.func(r):i=e.func.length===1?await e.func(o):await e.func();let l=(n?.functionResultFormatter??ee.functionResultFormatter)(i);return{formatted:String(l),rawResult:i,parsedArgs:r}};executeWithDetails=async(e,t)=>{let n=i=>i.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),r=n(e.name),o=this.funcList.find(i=>i.name===e.name);if(o||(o=this.funcList.find(i=>n(i.name)===r)),!o)throw new Error(`Function not found: ${e.name}`);if(!o.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(o,e,t)}catch(i){throw i instanceof Yn?new Qn(i.getFields(),o,e.id):i}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},uo=(s,e)=>{if(s.length===0)return[...e??[]];let t=s.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(r=>r.parameters))if(n.parameters)try{al(n.parameters)}catch(r){throw r instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
|
|
194
194
|
${r.message}
|
|
195
|
-
Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},po=async({ai:s,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:o,span:i,excludeContentFromTrace:a,index:l,functionResultFormatter:c,logger:u,debug:
|
|
196
|
-
`),r=[];for(let o of n){let i=o.trim();if(i){if(i[0]&&e.has(i[0]))r.push(i.slice(1).trim());else if(t.test(i))r.push(i.replace(t,"").trim());else if(r.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(r.length===0)throw new Error("Could not parse markdown list: no valid list items found");return r};function Vs(s,e){let{index:t,delta:n,version:r}=e,o=s.find(a=>a.index===t)?.delta;if(!o)return s.push({index:t,delta:n,version:r}),s;for(let a of Object.keys(n)){let l=o[a],c=n[a];l===void 0&&Array.isArray(c)?o[a]=[...c]:Array.isArray(l)&&Array.isArray(c)?o[a]=[...l,...c]:(l===void 0||typeof l=="string")&&typeof c=="string"?o[a]=`${l??""}${c}`:o[a]=c}let i=s.find(a=>a.index===t);return i&&(i.version=r),s}var Ws=class{cache=new Map;maxSize;constructor(e){this.maxSize=e}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(e,t)}},gu=new Ws(500);function bl(s,e,t=0,n=gu){if(/^```[a-zA-Z]*\s*$/.test(s))return-4;if(/^[\s`]*$/.test(s))return-3;let r=s.indexOf(e,t);if(r!==-1)return r;let o=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,o);let i=-1;for(let a=o.length-1;a>=0;a--){let l=o[a];if(s.endsWith(l)){i=a;break}}return i>=0?-2:-1}var Ys=(s,e,t,n)=>{let r=n?.strictMode??!1,o=n?.treatAllFieldsOptional??!1,i=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};Qs(s,e,a,t,{strictMode:r,skipEarlyFail:i,treatAllFieldsOptional:o}),Zs(s,e,a,t,{strictMode:r,treatAllFieldsOptional:o,forceFinalize:!0});for(let l of s.getOutputFields())l.isInternal&&delete e[l.name]},Js=(s,e,t)=>{let n=[];for(let r of t)r&&!r.isOptional&&e[r.name]===void 0&&n.push(r);if(n.length>0)throw Qa(n)},Qs=(s,e,t,n,{strictMode:r,skipEarlyFail:o}={})=>{let i=s.getOutputFields(),a;for(;;){let l=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&l.add(t.currFieldIndex);let c=i.map((g,
|
|
197
|
-
`)+
|
|
198
|
-
${m.title}:`,
|
|
199
|
-
${i.title}:`,
|
|
200
|
-
`);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
|
|
201
|
-
Content: ${i.content}`)}async function*xu({state:s,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:i,traceId:a,span:l,strictMode:c,excludeContentFromTrace:u,streamingAsserts:
|
|
202
|
-
Content: ${P.content}`)}let
|
|
203
|
-
`)}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(ce.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"],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 Ol(s){return new ni(s).parse()}var Xn=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},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},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)}},Ie=class s{type;isArray;options;description;isOptional;isInternal;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.isOptional=e.isOptional,this.isInternal=e.isInternal}optional(){return new s({...this,isOptional:!0})}array(){return new s({...this,isArray:!0})}internal(){return new s({...this,isInternal:!0})}},se=Object.assign(()=>new Xn,{string:s=>new Ie({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1}),number:s=>new Ie({type:"number",isArray:!1,description:s,isOptional:!1,isInternal:!1}),boolean:s=>new Ie({type:"boolean",isArray:!1,description:s,isOptional:!1,isInternal:!1}),json:s=>new Ie({type:"json",isArray:!1,description:s,isOptional:!1,isInternal:!1}),datetime:s=>new Ie({type:"datetime",isArray:!1,description:s,isOptional:!1,isInternal:!1}),date:s=>new Ie({type:"date",isArray:!1,description:s,isOptional:!1,isInternal:!1}),class:(s,e)=>new Ie({type:"class",isArray:!1,options:s,description:e,isOptional:!1,isInternal:!1}),image:s=>new Ie({type:"image",isArray:!1,description:s,isOptional:!1,isInternal:!1}),audio:s=>new Ie({type:"audio",isArray:!1,description:s,isOptional:!1,isInternal:!1}),file:s=>new Ie({type:"file",isArray:!1,description:s,isOptional:!1,isInternal:!1}),url:s=>new Ie({type:"url",isArray:!1,description:s,isOptional:!1,isInternal:!1}),code:(s,e)=>new Ie({type:"code",isArray:!1,description:e||s,isOptional:!1,isInternal:!1})});function ho(s){return{type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0},description:s.description,isOptional:s.isOptional,isInternal:s.isInternal}}var 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=Ol(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);nt(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);nt(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 nt(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 nt(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,...ho(t)}),n};prependInputField=(e,t)=>{let n=new s(this),r={name:e,...ho(t)},o=n.parseField(r);nt(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,...ho(t)}),n};prependOutputField=(e,t)=>{let n=new s(this),r={name:e,...ho(t)},o=n.parseField(r);nt(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)};toJSONSchema=()=>{let e={},t=[];for(let r of this.inputFields){let o=r.type?r.type.name:"string";r.type?.isArray?e[r.name]={description:r.description,type:"array",items:{type:o,description:r.description}}:e[r.name]={description:r.description,type:o},r.isOptional||t.push(r.name)}return{type:"object",properties:e,required:t}};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{nt(e,"input")}),this.getOutputFields().forEach(e=>{nt(e,"output")}),this.sigHash=hr("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Ml(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=>{nt(e,"input")}),this.getOutputFields().forEach(e=>{nt(e,"output")}),this.validateSignatureConsistency(),this.sigHash=hr("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Ml(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})};function kl(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 Ml(s,e,t){let n=s?`"${s}" `:"",r=e.map(kl).join(", "),o=t.map(kl).join(", ");return`${n}${r} -> ${o}`}function yu(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function nt(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(!yu(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(ce.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&&bu(s,e)}function bu(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")}var It=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 gn,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&&(mo(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 Zn(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 Iu=`
|
|
195
|
+
Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},po=async({ai:s,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:o,span:i,excludeContentFromTrace:a,index:l,functionResultFormatter:c,logger:u,debug:d,stopFunctionNames:p})=>{let m=new Zn(e),g=new Set,h=[],f=I=>{let E=v=>v.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),C=E(I),T=e.find(v=>v.name===I);return T||(T=e.find(v=>E(v.name)===C)),T},A=t.map(I=>{if(!I.id)throw new Error(`Function ${I.name} did not return an ID`);let E=s.getOptions().tracer??ee.tracer;return E?E.startActiveSpan(`Tool: ${I.name}`,async C=>{try{C?.setAttributes?.({"tool.name":I.name,"tool.mode":"native","function.id":I.id,"session.id":r??""});let{formatted:T,rawResult:v,parsedArgs:k}=await m.executeWithDetails(I,{sessionId:r,ai:s,functionResultFormatter:c,traceId:C?.spanContext?.().traceId??o,stopFunctionNames:p});if(g.add(I.name.toLowerCase()),p?.includes(I.name.toLowerCase())){let L=f(I.name);L&&h.push({func:L,args:k,result:v})}if(a?C.addEvent("gen_ai.tool.message",{name:I.name}):C.addEvent("gen_ai.tool.message",{name:I.name,args:I.args,result:T??""}),i){let L={name:I.name};a||(L.args=I.args,L.result=T??""),i.addEvent("function.call",L)}return{result:T??"",role:"function",functionId:I.id,index:l}}catch(T){if(C?.recordException?.(T),T instanceof Qn){let v=T.getFixingInstructions(),k={name:I.name,message:T.toString()};return a||(k.args=I.args,k.fixing_instructions=v),C?.addEvent?.("function.error",k),d&&rs(T,l,v,u),{functionId:I.id,isError:!0,index:l,result:v,role:"function"}}throw T}finally{C?.end?.()}}):m.executeWithDetails(I,{sessionId:r,ai:s,functionResultFormatter:c,traceId:o,stopFunctionNames:p}).then(({formatted:C,rawResult:T,parsedArgs:v})=>{if(g.add(I.name.toLowerCase()),p?.includes(I.name.toLowerCase())){let k=f(I.name);k&&h.push({func:k,args:v,result:T})}if(i){let k={name:I.name};a||(k.args=I.args,k.result=C??""),i.addEvent("function.call",k)}return{result:C??"",role:"function",functionId:I.id,index:l}}).catch(C=>{if(!(C instanceof Qn))throw C;let T=C.getFixingInstructions();if(i){let v={name:I.name,message:C.toString()};a||(v.args=I.args,v.fixing_instructions=T),i.addEvent("function.error",v)}return d&&rs(C,l,T,u),{functionId:I.id,isError:!0,index:l,result:T,role:"function"}})}),y=(await Promise.all(A)).map(I=>I.result===void 0||I.result===""?{...I,result:"done"}:I);if(n.addFunctionResults(y,r),d){let I=y.filter(E=>!E.isError);I.length>0&&zi(I,u)}if(h.length>0)throw new Mt(h);return g};function Gs(s,e,t,n){if(!e||e.length===0)return;if(!s.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(o=>({id:o.id,name:o.function.name,args:o.function.params}))}function ll(s,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:s?{functions:s.map(i=>"toFunction"in i?i.toFunction():i).flat(),functionCall:r}:{functions:[],functionCall:r}}var It=wn(cl(),1),ml=wn(ul(),1),gl=wn(pl(),1),fl=wn(dl(),1);It.default.extend(fl.default);It.default.extend(gl.default);It.default.extend(ml.default);function hl(s,e,t=!1){try{return du(e)}catch(n){if(s.isOptional&&!t)return;let r=n.message;throw nl(s,e,r)}}function du(s){if(!(0,It.default)(s,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return It.default.utc(s,"YYYY-MM-DD").startOf("day").toDate()}function Al(s,e,t=!1){try{return mu(e)}catch(n){if(s.isOptional&&!t)return;let r=n.message;throw rl(s,e,r)}}function mu(s){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=s.match(e);if(!t)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');let[,n,r]=t;if(!n||!r)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');try{let o=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",i=It.default.tz(n,o,r);if(!i.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return i.utc().toDate()}catch{throw new Error(`Unrecognized time zone ${r}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`)}}var xl=s=>(0,It.default)(s).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var Sh=new ve,mo=(s,e)=>{let t=s.type??{name:"string",isArray:!1},n=(c,u)=>{switch(c){case"class":return typeof u=="string";case"code":return typeof u=="string";case"string":return typeof u=="string";case"number":return typeof u=="number";case"boolean":return typeof u=="boolean";case"date":return u instanceof Date||typeof u=="string";case"datetime":return u instanceof Date||typeof u=="string";case"json":return typeof u=="object"||typeof u=="string";default:return!1}},r=c=>!(!c||typeof c!="object"||!("mimeType"in c)||!("data"in c));if(s.type?.name==="image"){let c;if(Array.isArray(e)){for(let u of e)if(!r(u)){c="object ({ mimeType: string; data: string })";break}}else r(e)||(c="object ({ mimeType: string; data: string })");if(c)throw new Error(`Validation failed: Expected '${s.name}' to be type '${c}' instead got '${e}'`);return}let o=c=>!(!c||typeof c!="object"||!("data"in c));if(s.type?.name==="audio"){let c;if(Array.isArray(e)){for(let u of e)if(!o(u)){c="object ({ data: string; format?: string })";break}}else o(e)||(c="object ({ data: string; format?: string })");if(c)throw new Error(`Validation failed: Expected '${s.name}' to be type '${c}' instead got '${e}'`);return}let i=c=>{if(!c||typeof c!="object"||!("mimeType"in c))return!1;let u="data"in c,d="fileUri"in c;return!(!u&&!d||u&&d)};if(s.type?.name==="file"){let c;if(Array.isArray(e)){for(let u of e)if(!i(u)){c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else i(e)||(c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })");if(c)throw new Error(`Validation failed: Expected '${s.name}' to be type '${c}' instead got '${e}'`);return}let a=c=>typeof c=="string"?!0:!(!c||typeof c!="object"||!("url"in c));if(s.type?.name==="url"){let c;if(Array.isArray(e)){for(let u of e)if(!a(u)){c="string or object ({ url: string; title?: string; description?: string })";break}}else a(e)||(c="string or object ({ url: string; title?: string; description?: string })");if(c)throw new Error(`Validation failed: Expected '${s.name}' to be type '${c}' instead got '${e}'`);return}let l=!0;if(t.isArray){if(!Array.isArray(e))l=!1;else for(let c of e)if(!n(t.name,c)){l=!1;break}}else l=n(t.name,e);if(!l){let c=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${s.name}' to be a ${s.type?.isArray?"an array of ":""}${t.name} instead got '${c}' (${JSON.stringify(e)})`)}};function Xn(s){let e={};for(let t of s){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let r=e[n];if(r){let o=r.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};o.promptTokens+=t?.tokens?.promptTokens??0,o.completionTokens+=t?.tokens?.completionTokens??0,o.totalTokens+=t?.tokens?.totalTokens??0,r.tokens=o;let i=r.citations??[],a=t.citations??[];if(a.length){let l=new Set(i.map(c=>c.url));for(let c of a)c?.url&&!l.has(c.url)&&(i.push(c),l.add(c.url));r.citations=i}}}return Object.values(e)}var yl=s=>{if(!s.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=s.split(`
|
|
196
|
+
`),r=[];for(let o of n){let i=o.trim();if(i){if(i[0]&&e.has(i[0]))r.push(i.slice(1).trim());else if(t.test(i))r.push(i.replace(t,"").trim());else if(r.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(r.length===0)throw new Error("Could not parse markdown list: no valid list items found");return r};function Vs(s,e){let{index:t,delta:n,version:r}=e,o=s.find(a=>a.index===t)?.delta;if(!o)return s.push({index:t,delta:n,version:r}),s;for(let a of Object.keys(n)){let l=o[a],c=n[a];l===void 0&&Array.isArray(c)?o[a]=[...c]:Array.isArray(l)&&Array.isArray(c)?o[a]=[...l,...c]:(l===void 0||typeof l=="string")&&typeof c=="string"?o[a]=`${l??""}${c}`:o[a]=c}let i=s.find(a=>a.index===t);return i&&(i.version=r),s}var Ws=class{cache=new Map;maxSize;constructor(e){this.maxSize=e}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(e,t)}},gu=new Ws(500);function bl(s,e,t=0,n=gu){if(/^```[a-zA-Z]*\s*$/.test(s))return-4;if(/^[\s`]*$/.test(s))return-3;let r=s.indexOf(e,t);if(r!==-1)return r;let o=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,o);let i=-1;for(let a=o.length-1;a>=0;a--){let l=o[a];if(s.endsWith(l)){i=a;break}}return i>=0?-2:-1}var Ys=(s,e,t,n)=>{let r=n?.strictMode??!1,o=n?.treatAllFieldsOptional??!1,i=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};Qs(s,e,a,t,{strictMode:r,skipEarlyFail:i,treatAllFieldsOptional:o}),Zs(s,e,a,t,{strictMode:r,treatAllFieldsOptional:o,forceFinalize:!0});for(let l of s.getOutputFields())l.isInternal&&delete e[l.name]},Js=(s,e,t)=>{let n=[];for(let r of t)r&&!r.isOptional&&e[r.name]===void 0&&n.push(r);if(n.length>0)throw Qa(n)},Qs=(s,e,t,n,{strictMode:r,skipEarlyFail:o}={})=>{let i=s.getOutputFields(),a;for(;;){let l=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&l.add(t.currFieldIndex);let c=i.map((g,h)=>({field:g,index:h})).filter(({index:g})=>!l.has(g)),u,d,p=-1,m=0;for(let{index:g,field:h}of c){let A=`${(t.extractedFields.length===0?"":`
|
|
197
|
+
`)+h.title}:`,x=bl(n,A,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=A.length,u=g,d=h)}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 g=i.find(h=>!h.isOptional);if(g)throw co(g)}break}if(a&&d&&a.name!==d.name)throw co(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let g=n.substring(t.s,p).trim(),h=go(t.currField,g);h!==void 0&&(e[t.currField.name]=h),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)}},Zs=(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 g=`
|
|
198
|
+
${m.title}:`,h=n.indexOf(g,t.s);h!==-1&&h<c&&(c=h)}let d=n.substring(t.s,c).trim(),p=go(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 co(d)}if(fu(s,e,n,t),!i){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?Js(t,e,s.getOutputFields()):c||Js(t,e,s.getOutputFields())}},fu=(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=`
|
|
199
|
+
${i.title}:`,d=t.indexOf(u,c),p=t.substring(c,d===-1?t.length:d).trim();if(p)try{let m=go(i,p);if(m!==void 0){e[i.name]=m;return}}catch{}}}}let o=t.split(`
|
|
200
|
+
`);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=go(i,u);if(d!==void 0){e[i.name]=d;break}}catch(d){if(!i.isOptional)throw d}break}}}},Il=(s,e,t=!1)=>{switch(s.type?.name){case"code":return Cl(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 hl(s,e,t);case"datetime":return Al(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*Tl(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 g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let h=d?g.trimStart():g;r.currField?.type?.name==="code"&&(h=h.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),h.length>0&&(yield{index:o,delta:{[i]:h}},r.streamedIndex[i]=u+g.length)}function*Xs(s,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:l,e:c}=i;yield*Tl(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*Tl(e,n.currField,n.s,e.length,n,r);let o=s.getOutputFields();for(let i of Object.keys(t)){let a=o.find(c=>c.name===i);if(!a||a.isInternal)continue;let l=t[i];if(Array.isArray(l)){let c=n.streamedIndex?.[i]??0,u=l.slice(c);u&&u.length>0&&(yield{index:r,delta:{[i]:u}},n.streamedIndex[i]=c+u.length);continue}n.streamedIndex[i]||(yield{index:r,delta:{[i]:l}},n.streamedIndex[i]=1)}}function go(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw Za(s)}let t;if(s.type?.name==="json")try{let n=Cl(e);return t=JSON.parse(n),t}catch(n){throw Xa(s,n.message)}if(s.type?.isArray)try{try{t=JSON.parse(e)}catch{t=yl(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(n){throw el(s,n.message)}try{if(Array.isArray(t)){for(let[n,r]of t.entries())if(r!==void 0){let o=typeof r=="string"?r.trim():r;t[n]=Il(s,o,!0)}}else t=Il(s,e)}catch(n){throw tl(s,e,n.message)}if(!(typeof t=="string"&&t===""))return t}var Cl=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 ei(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});Rl(r.field,t,i,n)}}async function ti(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});Rl(t.currField,n,u,o)}}var Rl=(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=hu(s,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function hu(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*wl({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 g of p.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!p.content||p.content==="")&&(!p.thought||p.thought==="")&&(!p.functionCalls||p.functionCalls.length===0))continue;let m=t.find(g=>g.index===p.index);if(!m)throw new Error(`No state found for result (index: ${p.index})`);yield*Au({...r,result:p,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*xu({...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*Au({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)Rr(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){if(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),Qs(a,i.values,i.xstate,i.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await _s(u,i.xstate,i.content),l.length!==0&&await ti(l,i.content,i.xstate,e,i.values,t),yield*Xs(a,i.content,i.values,i.xstate,s.index),await so(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}});if(s.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
201
|
+
Content: ${i.content}`)}async function*xu({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:g,functionResultFormatter:h,signatureToolCallingManager:f,logger:A,debug:x,stopFunctionNames:y}){let I=f?void 0:Gs(t,s.functionCalls,s.values,n);if(I){if(!r)throw new Error("Functions are not defined");let E=await po({ai:t,functionList:r,functionCalls:I,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:u,functionResultFormatter:h,logger:A,debug:x,stopFunctionNames:y});s.functionsExecuted=new Set([...s.functionsExecuted,...E]),s.functionCalls=[]}else{let E=f!==void 0;if(Zs(e,s.values,s.xstate,s.content,{strictMode:c,treatAllFieldsOptional:E,deferRequiredCheckForStreaming:!0,forceFinalize:!0}),f){let C=await f.processResults(s.values);if(C&&C.length>0){if(!r)throw new Error("Functions are not defined");let T=await po({ai:t,functionList:r,functionCalls:C,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:u,functionResultFormatter:h,logger:A,debug:x,stopFunctionNames:y});s.functionsExecuted=new Set([...s.functionsExecuted,...T]),o.updateResult({name:void 0,content:s.content,functionCalls:C.map(v=>({id:v.id,type:"function",function:{name:v.name,params:v.args}})),index:s.index},i);return}}await _s(d,s.xstate,s.content,!0),await so(p,s.values),m.length&&await ei(m,s.values,o,i),g.length!==0&&await ti(g,s.content,s.xstate,o,s.values,i,!0),yield*Xs(e,s.content,s.values,s.xstate,s.index)}}async function*vl({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:g,functionResultFormatter:h,logger:f,debug:A,signatureToolCallingManager:x,stopFunctionNames:y,disableMemoryCleanup:I}){let E=e.results??[],C=x!==void 0;t.addResponse(E,n);let T=[];for(let P of E)if(Array.isArray(P?.citations))for(let R of P.citations)R?.url&&T.push({url:R.url,title:R.title,description:R.description,license:R.license,publicationDate:R.publicationDate,snippet:R.snippet});for(let P of E){let R=l[P.index];if(!R)throw new Error(`No state found for result (index: ${P.index})`);if(e.modelUsage){let w=Array.from(new Map(T.filter(O=>O.url).map(O=>[O.url,O])).values()),b={...e.modelUsage,...w.length?{citations:w}:{}};if(c.push(b),A&&f){let O=structuredClone(b);delete O.citations,f({name:"ChatResponseUsage",value:O}),b.citations&&b.citations.length>0&&f({name:"ChatResponseCitations",value:b.citations})}}if(x&&P.content){P.thought&&P.thought.length>0&&(R.values[m]=P.thought),Ys(g,R.values,P.content,{strictMode:a,treatAllFieldsOptional:C});let b=(await x.processResults(R.values))?.map(O=>({id:O.id,type:"function",function:{name:O.name,params:O.args}}));b&&b.length>0&&t.updateResult({name:P.name,content:P.content,functionCalls:b,index:P.index},n)}if(P.functionCalls?.length){let w=Gs(s,P.functionCalls,R.values);if(w&&w.length>0){if(!o)throw new Error("Functions are not defined");let b;try{b=await po({ai:s,functionList:o,functionCalls:w,mem:t,sessionId:n,traceId:r,span:i,excludeContentFromTrace:u,index:P.index,functionResultFormatter:h,logger:f,debug:A,stopFunctionNames:y})}catch(O){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),O}R.functionsExecuted=new Set([...R.functionsExecuted,...b])}}else P.content&&(P.thought&&P.thought.length>0&&(R.values[m]=P.thought),Ys(g,R.values,P.content,{strictMode:a,treatAllFieldsOptional:C}));if(await so(d,R.values),I||(t.removeByTag("correction",n),t.removeByTag("error",n)),p.length&&await ei(p,R.values,t,n),P.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
202
|
+
Content: ${P.content}`)}let v=l.map(P=>P.values);for(let P of v)for(let R of g.getOutputFields())R.isInternal&&delete P[R.name];let k=g.getOutputFields(),L=v.map((P,R)=>{let w={};for(let b of k)b.isInternal||(w[b.name]=P[b.name]);return P[m]!==void 0&&(w[m]=P[m]),{index:R,delta:w}});for(let P of L)yield P}function Sl(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 fn=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"}},ni=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(`
|
|
203
|
+
`)}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"],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 Ol(s){return new ni(s).parse()}var er=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},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},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)}},Ie=class s{type;isArray;options;description;isOptional;isInternal;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.isOptional=e.isOptional,this.isInternal=e.isInternal}optional(){return new s({...this,isOptional:!0})}array(){return new s({...this,isArray:!0})}internal(){return new s({...this,isInternal:!0})}},ie=Object.assign(()=>new er,{string:s=>new Ie({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1}),number:s=>new Ie({type:"number",isArray:!1,description:s,isOptional:!1,isInternal:!1}),boolean:s=>new Ie({type:"boolean",isArray:!1,description:s,isOptional:!1,isInternal:!1}),json:s=>new Ie({type:"json",isArray:!1,description:s,isOptional:!1,isInternal:!1}),datetime:s=>new Ie({type:"datetime",isArray:!1,description:s,isOptional:!1,isInternal:!1}),date:s=>new Ie({type:"date",isArray:!1,description:s,isOptional:!1,isInternal:!1}),class:(s,e)=>new Ie({type:"class",isArray:!1,options:s,description:e,isOptional:!1,isInternal:!1}),image:s=>new Ie({type:"image",isArray:!1,description:s,isOptional:!1,isInternal:!1}),audio:s=>new Ie({type:"audio",isArray:!1,description:s,isOptional:!1,isInternal:!1}),file:s=>new Ie({type:"file",isArray:!1,description:s,isOptional:!1,isInternal:!1}),url:s=>new Ie({type:"url",isArray:!1,description:s,isOptional:!1,isInternal:!1}),code:(s,e)=>new Ie({type:"code",isArray:!1,description:e||s,isOptional:!1,isInternal:!1})});function fo(s){return{type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0},description:s.description,isOptional:s.isOptional,isInternal:s.isInternal}}var 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=Ol(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);rt(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);rt(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 rt(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 rt(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,...fo(t)}),n};prependInputField=(e,t)=>{let n=new s(this),r={name:e,...fo(t)},o=n.parseField(r);rt(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,...fo(t)}),n};prependOutputField=(e,t)=>{let n=new s(this),r={name:e,...fo(t)},o=n.parseField(r);rt(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)};toJSONSchema=()=>{let e={},t=[];for(let r of this.inputFields){let o=r.type?r.type.name:"string";r.type?.isArray?e[r.name]={description:r.description,type:"array",items:{type:o,description:r.description}}:e[r.name]={description:r.description,type:o},r.isOptional||t.push(r.name)}return{type:"object",properties:e,required:t}};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{rt(e,"input")}),this.getOutputFields().forEach(e=>{rt(e,"output")}),this.sigHash=Be("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Ml(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=>{rt(e,"input")}),this.getOutputFields().forEach(e=>{rt(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=Ml(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})};function kl(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 Ml(s,e,t){let n=s?`"${s}" `:"",r=e.map(kl).join(", "),o=t.map(kl).join(", ");return`${n}${r} -> ${o}`}function yu(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function rt(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(!yu(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&&bu(s,e)}function bu(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")}var Tt=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 fn,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&&(mo(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 Xn(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 Iu=`
|
|
204
204
|
## Function Call Instructions
|
|
205
205
|
- Complete the task, using the functions defined earlier in this prompt.
|
|
206
206
|
- Output fields should only be generated after all functions have been called.
|
|
@@ -211,18 +211,18 @@ Content: ${P.content}`)}let S=l.map(P=>P.values);for(let P of S)for(let T of g.g
|
|
|
211
211
|
- Output field, values must strictly adhere to the specified output field formatting rules.
|
|
212
212
|
- Do not include fields with empty, unknown, or placeholder values.
|
|
213
213
|
- Do not add any text before or after the output fields, just the field name and value.
|
|
214
|
-
- Do not use code blocks.`,
|
|
214
|
+
- Do not use code blocks.`,Et=class{sig;fieldTemplates;task;thoughtFieldName;functions;cacheSystemPrompt;constructor(e,t,n){this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=t?.thoughtFieldName??"thought",this.functions=t?.functions,this.cacheSystemPrompt=t?.cacheSystemPrompt;let r=[],o=El(this.sig.getInputFields()),i=El(this.sig.getOutputFields());r.push(`You will be provided with the following fields: ${o}. Your task is to generate new fields: ${i}.`);let l=this.functions?.map(p=>"toFunction"in p?p.toFunction():p)?.flat()?.map(p=>`- \`${p.name}\`: ${ho(p.description)}`).join(`
|
|
215
215
|
`);l&&l.length>0&&r.push(`## Available Functions
|
|
216
216
|
${l}`);let c=Cu(this.sig.getInputFields());r.push(`## Input Fields
|
|
217
217
|
${c}`);let u=Ru(this.sig.getOutputFields());r.push(`## Output Fields
|
|
218
|
-
${u}`),l&&l.length>0&&r.push(Iu.trim()),r.push(Tu.trim());let
|
|
218
|
+
${u}`),l&&l.length>0&&r.push(Iu.trim()),r.push(Tu.trim());let d=this.sig.getDescription();if(d){let p=ho(d);r.push(p)}this.task={type:"text",text:r.join(`
|
|
219
219
|
|
|
220
220
|
`)}}renderSingleValueUserContent=(e,t,n,r)=>{let o=this.renderInputFields(e),a=(r?o:[...t,...n,...o]).filter(l=>l!==void 0);return a.every(l=>l.type==="text")?a.map(l=>l.text).join(`
|
|
221
221
|
`):a.reduce(Pl(`
|
|
222
222
|
`),[])};render=(e,{examples:t,demos:n})=>{let r=t?[{type:"text",text:`
|
|
223
223
|
|
|
224
224
|
## Examples
|
|
225
|
-
`},...this.renderExamples(t)]:[],o=n?this.renderDemos(n):[],i=r.every(
|
|
225
|
+
`},...this.renderExamples(t)]:[],o=n?this.renderDemos(n):[],i=r.every(p=>p.type==="text"),a=o.every(p=>p.type==="text"),l=i&&a,c=this.task.text;if(l){let p=[{type:"text",text:c},...r,...o];p.reduce(Pl(""),[]),p?.[0]&&(c=p[0].text)}let u={role:"system",content:c,cache:this.cacheSystemPrompt};if(Array.isArray(e)){let p=[],m=e,g=!0;for(let h of m){let f;if(g?(f=this.renderSingleValueUserContent(h.values,r,o,l),g=!1):f=this.renderSingleValueUserContent(h.values,[],[],!1),h.role==="user"){p.push({role:"user",content:f});continue}if(h.role!=="assistant")throw new Error("Invalid message role");if(typeof f!="string")throw new Error("Assistant message cannot contain non-text content like images, files,etc");p.push({role:"assistant",content:f})}return[u,...p]}let d=this.renderSingleValueUserContent(e,r,o,l);return[u,{role:"user",content:d}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((o,i)=>{let a=i.title;return o[a]||(o[a]=[]),o[a].push(i),o},{});return Object.entries(n).map(([o,i])=>{if(i.length===1){let a=i[0];return{title:o,name:a.name,description:a.description}}if(i.length>1){let a=i.map(l=>`- ${l.description}`).join(`
|
|
226
226
|
`);return{title:o,name:i[0].name,description:a}}}).filter(Boolean).forEach(o=>{let i=this.fieldTemplates?.[o.name]??this.defaultRenderInField;t.push(...i(o,o.description))}),t};renderExamples=e=>{let t=[],n={isExample:!0};for(let[r,o]of e.entries()){let i=this.sig.getInputFields().map(c=>this.renderInField(c,o,{...n,isInputField:!0})).filter(c=>c!==void 0).flat(),a=this.sig.getOutputFields().map(c=>this.renderInField(c,o,{...n,isInputField:!1})).filter(c=>c!==void 0).flat(),l=[...i,...a];r>0&&l.length>0&&l[0]?.type==="text"&&t.push({type:"text",text:`---
|
|
227
227
|
|
|
228
228
|
`}),l.forEach(c=>{"text"in c&&(c.text=`${c.text}
|
|
@@ -230,19 +230,19 @@ ${u}`),l&&l.length>0&&r.push(Iu.trim()),r.push(Tu.trim());let p=this.sig.getDesc
|
|
|
230
230
|
`),t.push(u)})}return t};renderInputFields=e=>{let t=this.sig.getInputFields().map(n=>this.renderInField(n,e,void 0)).filter(n=>n!==void 0).flat();return t.filter(n=>n.type==="text").forEach(n=>{n.text=`${n.text}
|
|
231
231
|
`}),t};renderInField=(e,t,n)=>{let r=t[e.name];if(vu(e,r,n))return;e.type&&mo(e,r);let o=wu(e,r);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,o)};defaultRenderInField=(e,t)=>{if(e.type?.name==="image"){let r=i=>{if(!i)throw new Error("Image field value is required.");if(typeof i!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in i))throw new Error("Image field must have mimeType");if(!("data"in i))throw new Error("Image field must have data");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let i=r(t);o.push({type:"image",mimeType:i.mimeType,image:i.data})}return o}if(e.type?.name==="audio"){let r=i=>{if(!i)throw new Error("Audio field value is required.");if(typeof i!="object")throw new Error("Audio field value must be an object.");if(!("data"in i))throw new Error("Audio field must have data");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let i=r(t);o.push({type:"audio",format:i.format??"wav",data:i.data})}return o}if(e.type?.name==="file"){let r=i=>{if(!i)throw new Error("File field value is required.");if(typeof i!="object")throw new Error("File field value must be an object.");if(!("mimeType"in i))throw new Error("File field must have mimeType");let a="data"in i,l="fileUri"in i;if(!a&&!l)throw new Error("File field must have either data or fileUri");if(a&&l)throw new Error("File field cannot have both data and fileUri");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return"fileUri"in a?{type:"file",mimeType:a.mimeType,fileUri:a.fileUri}:{type:"file",mimeType:a.mimeType,data:a.data}}))}else{let i=r(t);o.push("fileUri"in i?{type:"file",mimeType:i.mimeType,fileUri:i.fileUri}:{type:"file",mimeType:i.mimeType,data:i.data})}return o}if(e.type?.name==="url"){let r=i=>{if(!i)throw new Error("URL field value is required.");if(typeof i=="string")return{url:i};if(typeof i!="object")throw new Error("URL field value must be a string or object.");if(!("url"in i))throw new Error("URL field must have url property");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return{type:"url",url:a.url,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{}}}))}else{let i=r(t);o.push({type:"url",url:i.url,...i.title?{title:i.title}:{},...i.description?{description:i.description}:{}})}return o}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
|
|
232
232
|
`),n.push(t.map(r=>`- ${r}`).join(`
|
|
233
|
-
`))):n.push(t),[{type:"text",text:n.join("")}]}},El=s=>s.map(e=>`\`${e.title}\``).join(", "),Cu=s=>s.map(t=>{let n=t.title,r=t.type?.name?_l(t.type):"string",o=t.isOptional?`This optional ${r} field may be omitted`:`A ${r} field`,i=t.description?` ${
|
|
234
|
-
`),Ru=s=>s.map(t=>{let n=t.title,r=t.type?.name?_l(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:
|
|
235
|
-
`),wu=(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?xl(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)},_l=s=>{let e=(()=>{switch(s?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"file":return"file (with filename, mimeType, and data)";case"url":return"URL (string or object with url, title, description)";default:return"string"}})();return s?.isArray?`json array of ${e} items`:e};function Pl(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 vu=(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 fo(s){let e=s.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Su(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 Ou(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 Ao(s,e,t,n){if(!e?.resultPicker||s.length<=1)return 0;let r=e.resultPicker;if((t?Su(t,n):!1)&&t){let l=Ou(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 Fl(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 Ao(r,t,s,e)}var xo=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}=ku(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 p=i.get(c);if(!p)continue;let d=p.get(a);if(!d)continue;let m=o.get(u.name)??{};this.setNested(m,d,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 p=(l.parameters.required||[]).filter(d=>c[d]===void 0);if(p.length>0)throw new Ee(`Missing required arguments for tool '${l.name}': ${p.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 ku(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 p=a?`${a}.${c}`:c,d=`${s.name}.${p}`;if(u.type==="object"&&u.properties)o(u.properties,p,u.required||[]);else{let m=Mu(u);e.push({name:Pu(d),title:Eu(s.name,p),type:m,description:u.description||`${c} parameter for ${s.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Mu(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 Eu(s,e){return`${s} ${e.replace(/\./g," ")}`}function Pu(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function $l(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=ri(o.name),l=Nl(o.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:Dl(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}=_u(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=ri(o.name),a=Nl(o.parameters);n.getOutputFields().some(c=>c.name===i)||n.addOutputField({name:i,title:Dl(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function _u(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 p=a?`${a}.${c}`:c,d=`${s.name}.${p}`;if(u.type==="object"&&u.properties)o(u.properties,p,u.required||[]);else{let m=Fu(u),g={name:ri(d),title:Du(s.name,p),type:m,description:u.description||`${c} parameter for ${s.name}`,isOptional:!0};e.push(g),t.set(d,g)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Fu(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 Du(s,e){return`${s} ${e.replace(/\./g," ")}`}function ri(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Dl(s){return s.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function Nl(s){return!s||!s.properties||Object.keys(s.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var er=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new xo(e)}processSignature(e){let{signature:t}=$l(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 It{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??Mt)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?uo(t.functions):[],this.usage=[]}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Ds()}updateMeter(e){Ds(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:p,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await Fl(t,l,{resultPicker:n?.resultPicker}),f=t?.history(g,l)??[];if(f.length===0)throw new Error("No chat prompt found");let h={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},A=this.isDebug(e,n),x=a===0,b=this.getLogger(e,n);return o=this.signatureToolCallingManager?[]:o,await e.chat({chatPrompt:f,functions:o,functionCall:i,modelConfig:h,model:c},{sessionId:l,rateLimiter:u,stream:p,debug:A,debugHideSystemPrompt:!x,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.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??{},p=n?.functionResultFormatter??this.options?.functionResultFormatter,d=n?.functionCall??this.options?.functionCall,m=this.signatureToolCallingManager,g=n?.strictMode??!1,f=n.model,h=this.usage,A=r===0,x=this.isDebug(e,n),b=this.getLogger(e,n),{functions:I,functionCall:M}=ll(u,d,A,n),R=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:I,functionCall:M,stepIndex:r});R instanceof ReadableStream?yield*wl({ai:e,model:f,res:R,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,strictMode:g,span:o,states:a,usage:h,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:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*vl({ai:e,model:f,res:R,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,span:o,strictMode:g,states:a,usage:h,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:b,debug:x,functionResultFormatter:p,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(L=>L.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??10,u=r.maxSteps??this.options?.maxSteps??10,p=r.mem??this.options?.mem??new dn,d=[...this.functions,...r.functions?uo(r.functions):[]],m=d&&d.length>0,g=r.functionCallMode??this.options?.functionCallMode??"auto",f=r.cacheSystemPrompt??this.options?.cacheSystemPrompt;m&&g==="prompt"&&(this.signatureToolCallingManager=new er(d)),m&&g==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new er(d));let h,A,x=this.options?.promptTemplate??Mt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let b={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,cacheSystemPrompt:f};this.promptTemplate=new x(this.signature,b);let I,M=performance.now();Array.isArray(t)?(ma(t),I=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):I=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let R=performance.now()-M,w=this.getMetricsInstruments();w&&lo(w,"prompt_render",R,this.getSignatureName());let S=performance.now();p.addRequest(I,r.sessionId);let E=performance.now()-S;w&&lo(w,"memory_update",E,this.getSignatureName());e:for(let L=0;L<u;L++){for(let T=0;T<c;T++)try{let C=this.forwardCore({options:r,ai:e,mem:p,stepIndex:L,span:o,traceContext:i,states:n,stopFunctionNames:l}),y=!1;try{for await(let k of C)k!==void 0&&(yield{version:T,index:k.index,delta:k.delta})}catch(k){if(k instanceof kt)y=!0;else throw k}if(y?!1:Sl(p,l,n,r?.sessionId)){let k=this.getMetricsInstruments();k&&ao(k,L+1,u,this.getSignatureName());continue e}r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let v=this.getMetricsInstruments();if(v){ao(v,L+1,u,this.getSignatureName());let k=new Set;n.forEach(_=>{_.functionsExecuted.forEach(F=>k.add(F))}),k.size>0&&Ka(v,!0,k.size,!0,!1,this.getSignatureName()),Wa(v,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(C){A=C;let y,O=this.isDebug(e,r),v=this.getLogger(e,r),k=this.getMetricsInstruments(),_=this.getSignatureName(),F={error:C,errCount:T,logger:v,metricsInstruments:k,signatureName:_,span:o,debug:O};if(o?.recordException(C),C instanceof Ee)y=ol(F),h=C;else if(C instanceof tt)y=sl(F),h=C;else if(C instanceof de)il(F);else if(!(C instanceof Ve))throw oi(C,e,this.signature);y&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(y)}],r.sessionId),p.addTag("correction",r.sessionId))}let P=this.getMetricsInstruments();throw P&&$s(P,c,!1,c,this.getSignatureName()),oi(new Error(`Unable to fix validation error: ${(h??A)?.message??(h??A)?.toString()??"unknown error"}`),e,this.signature)}throw w&&ao(w,u,u,this.getSignatureName()),oi(new Error(`Max steps reached: ${u}`),e,this.signature)}async*_forward1(e,t,n){let r=performance.now(),o=this.createStates(n.sampleCount??1),i=performance.now()-r,a=this.getMetricsInstruments();a&&lo(a,"state_creation",i,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,c=this.functions;if(n?.functions&&(c=uo(n.functions,this.functions)),!l){yield*this._forward2(e,t,o,{...n,functions:c});return}let u=c?.map(A=>A.name).join(","),p={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}:{}},d=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=d?`AxGen > ${d}`:"AxGen",g=l.startSpan(m,{kind:Me.SERVER,attributes:p}),f=xt.active(),h=kn.setSpan(f,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:c},g,h),!this.excludeContentFromTrace){let A=o.map(b=>b.values),x=A.length===1?A[0]:A;g.addEvent("output",{content:JSON.stringify(x,null,2)})}}finally{g.end()}}async forward(e,t,n){let r=performance.now(),o=this.getSignatureName(),i=n?.stream??!1,a=!1,l=0,c=!1;try{let u=this.getMetricsInstruments();u&&Ya(u,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,o);let p=this._forward1(e,t,n??{}),d=[],m=0,g=0;for await(let M of p)M.version!==m&&(d=[]),m=M.version,d=Vs(d,M),g++;l=m;let f=performance.now();c=!!n?.resultPicker;let h=await Ao(d,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),A=performance.now()-f,b=d[h]?.delta??{},I=Array.isArray(t)?{}:t??{};if(this.trace={...I,...b},c&&this.isDebug(e,n)){let M=this.getLogger(e,n);Ji(d.length,h,A,M)}return a=!0,u&&(Ja(u,d.length,c,c?A:void 0,o),Va(u,i,g,void 0,o)),b}catch(u){throw a=!1,u}finally{let u=performance.now()-r,p=this.getMetricsInstruments();p&&(ja(p,u,a,o,e.getName(),n?.model?String(n.model):void 0),l>0&&$s(p,l,a,n?.maxRetries??10,o))}}async*streamingForward(e,t,n){if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let r=this._forward1(e,t,{...n,stream:!0}),o=[],i=0;for await(let c of r)c.version!==i&&(o=[]),i=c.version,o=Vs(o,c);let a=await Ao(o,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),l=o[a];l&&(yield{version:i,index:a,delta:l.delta})}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??ce.logger??e.getLogger()}},tr=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function oi(s,e,t){let n=s instanceof Error?s:new Error(String(s)),r=e.getLastUsedChatModel(),o=e.getLastUsedModelConfig(),i={model:r,maxTokens:o?.maxTokens,streaming:o?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new tr("Generate failed",i,{cause:n})}var Nu=s=>s.replace(/^\W+|\W+$/g,""),$u=(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]},Gu=s=>{let e=new Set,t=[];for(let n of s)e.has(n)||(e.add(n),t.push(n));return t},Lu=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}},Uu=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():s},Bu=(s,e)=>{let t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t},yo={trimNonAlphaNum:Nu,splitIntoTwo:$u,dedup:Gu,extractIdAndText:Lu,extractIndexPrefixedText:Uu,batchArray:Bu};var bo=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."
|
|
236
|
-
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}=yo.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 Io=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 PA=new ve,To=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},Co=class{ai;db;debug;constructor(e){this.db=new yt,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 Gl=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 Ll(s,e){return s.filter(t=>!e.has(t))}function Ul(s){let e={};for(let t of s)e[t]=(e[t]||0)+1;return e}function Et(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 qu(s,e){return Et(s)===Et(e)?1:0}function zu(s,e){let t=Et(s).split(" "),n=Et(e).split(" "),r=Ul(t),o=Ul(n),i=0;for(let c in r){let u=r[c]??0,p=o[c]??0;i+=Math.min(u,p)}if(i===0)return 0;let a=i/t.length,l=i/n.length;return 2*a*l/(a+l)}function ju(s,e,t,n=!1){let r=Et(s).split(" "),o=Et(e).split(" "),i=Et(t).split(" "),a=new Set([...Gl,...r]);o=Ll(o,a),i=Ll(i,a);let l=0,c=l/o.length,u=l/i.length,p=2*c*u/(c+u);return n?u:p}var Bl={emScore:qu,f1Score:zu,novelF1ScoreOptimized:ju};var Ro=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(`
|
|
233
|
+
`))):n.push(t),[{type:"text",text:n.join("")}]}},El=s=>s.map(e=>`\`${e.title}\``).join(", "),Cu=s=>s.map(t=>{let n=t.title,r=t.type?.name?_l(t.type):"string",o=t.isOptional?`This optional ${r} field may be omitted`:`A ${r} field`,i=t.description?` ${ho(t.description)}`:"";return`${n}: (${o})${i}`.trim()}).join(`
|
|
234
|
+
`),Ru=s=>s.map(t=>{let n=t.title,r=t.type?.name?_l(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:ho(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(`
|
|
235
|
+
`),wu=(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?xl(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)},_l=s=>{let e=(()=>{switch(s?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"file":return"file (with filename, mimeType, and data)";case"url":return"URL (string or object with url, title, description)";default:return"string"}})();return s?.isArray?`json array of ${e} items`:e};function Pl(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 vu=(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 ho(s){let e=s.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Su(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 Ou(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 Ao(s,e,t,n){if(!e?.resultPicker||s.length<=1)return 0;let r=e.resultPicker;if((t?Su(t,n):!1)&&t){let l=Ou(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 Fl(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 Ao(r,t,s,e)}var xo=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}=ku(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 Ee(`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 ku(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=Mu(u);e.push({name:Pu(p),title:Eu(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 Mu(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 Eu(s,e){return`${s} ${e.replace(/\./g," ")}`}function Pu(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function $l(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=ri(o.name),l=Nl(o.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:Dl(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}=_u(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=ri(o.name),a=Nl(o.parameters);n.getOutputFields().some(c=>c.name===i)||n.addOutputField({name:i,title:Dl(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function _u(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=Fu(u),g={name:ri(p),title:Du(s.name,d),type:m,description:u.description||`${c} parameter for ${s.name}`,isOptional:!0};e.push(g),t.set(p,g)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Fu(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 Du(s,e){return`${s} ${e.replace(/\./g," ")}`}function ri(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Dl(s){return s.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function Nl(s){return!s||!s.properties||Object.keys(s.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var tr=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new xo(e)}processSignature(e){let{signature:t}=$l(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 Tt{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??Et)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?uo(t.functions):[],this.usage=[]}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Ds()}updateMeter(e){Ds(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??{},g=await Fl(t,l,{resultPicker:n?.resultPicker}),h=t?.history(g,l)??[];if(h.length===0)throw new Error("No chat prompt found");let f={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},A=this.isDebug(e,n),x=a===0,y=this.getLogger(e,n);return o=this.signatureToolCallingManager?[]:o,await e.chat({chatPrompt:h,functions:o,functionCall:i,modelConfig:f,model:c},{sessionId:l,rateLimiter:u,stream:d,debug:A,debugHideSystemPrompt:!x,thinkingTokenBudget:p,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??ee.abortSignal,stepIndex:a,logger:y,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,g=n?.strictMode??!1,h=n.model,f=this.usage,A=r===0,x=this.isDebug(e,n),y=this.getLogger(e,n),{functions:I,functionCall:E}=ll(u,p,A,n),C=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:I,functionCall:E,stepIndex:r});C instanceof ReadableStream?yield*wl({ai:e,model:h,res:C,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,strictMode:g,span:o,states:a,usage:f,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:x,functionResultFormatter:d,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*vl({ai:e,model:h,res:C,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,span:o,strictMode:g,states:a,usage:f,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,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(L=>L.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 mn,p=[...this.functions,...r.functions?uo(r.functions):[]],m=p&&p.length>0,g=r.functionCallMode??this.options?.functionCallMode??"auto",h=r.cacheSystemPrompt??this.options?.cacheSystemPrompt;m&&g==="prompt"&&(this.signatureToolCallingManager=new tr(p)),m&&g==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new tr(p));let f,A,x=this.options?.promptTemplate??Et;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let y={functions:this.signatureToolCallingManager?[]:p,thoughtFieldName:this.thoughtFieldName,cacheSystemPrompt:h};this.promptTemplate=new x(this.signature,y);let I,E=performance.now();Array.isArray(t)?(ma(t),I=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):I=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let C=performance.now()-E,T=this.getMetricsInstruments();T&&lo(T,"prompt_render",C,this.getSignatureName());let v=performance.now();d.addRequest(I,r.sessionId);let k=performance.now()-v;T&&lo(T,"memory_update",k,this.getSignatureName());e:for(let L=0;L<u;L++){for(let R=0;R<c;R++)try{let w=this.forwardCore({options:r,ai:e,mem:d,stepIndex:L,span:o,traceContext:i,states:n,stopFunctionNames:l}),b=!1;try{for await(let M of w)M!==void 0&&(yield{version:R,index:M.index,delta:M.delta})}catch(M){if(M instanceof Mt)b=!0;else throw M}if(b?!1:Sl(d,l,n,r?.sessionId)){let M=this.getMetricsInstruments();M&&ao(M,L+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 S=this.getMetricsInstruments();if(S){ao(S,L+1,u,this.getSignatureName());let M=new Set;n.forEach(_=>{_.functionsExecuted.forEach(F=>M.add(F))}),M.size>0&&Ka(S,!0,M.size,!0,!1,this.getSignatureName()),Wa(S,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(w){A=w;let b,O=this.isDebug(e,r),S=this.getLogger(e,r),M=this.getMetricsInstruments(),_=this.getSignatureName(),F={error:w,errCount:R,logger:S,metricsInstruments:M,signatureName:_,span:o,debug:O};if(o?.recordException(w),w instanceof Ee)b=ol(F),f=w;else if(w instanceof nt)b=sl(F),f=w;else if(w instanceof de)il(F);else if(!(w instanceof Je))throw oi(w,e,this.signature);b&&(d.addTag("error",r.sessionId),d.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(b)}],r.sessionId),d.addTag("correction",r.sessionId))}let P=this.getMetricsInstruments();throw P&&$s(P,c,!1,c,this.getSignatureName()),oi(new Error(`Unable to fix validation error: ${(f??A)?.message??(f??A)?.toString()??"unknown error"}`),e,this.signature)}throw T&&ao(T,u,u,this.getSignatureName()),oi(new Error(`Max steps reached: ${u}`),e,this.signature)}async*_forward1(e,t,n){let r=performance.now(),o=this.createStates(n.sampleCount??1),i=performance.now()-r,a=this.getMetricsInstruments();a&&lo(a,"state_creation",i,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,c=this.functions;if(n?.functions&&(c=uo(n.functions,this.functions)),!l){yield*this._forward2(e,t,o,{...n,functions:c});return}let u=c?.map(A=>A.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",g=l.startSpan(m,{kind:Me.SERVER,attributes:d}),h=yt.active(),f=Mn.setSpan(h,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:c},g,f),!this.excludeContentFromTrace){let A=o.map(y=>y.values),x=A.length===1?A[0]:A;g.addEvent("output",{content:JSON.stringify(x,null,2)})}}finally{g.end()}}async forward(e,t,n){let 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&&Ya(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??{}),g=[],h=0,f=0;for await(let T of m)T.version!==h&&(g=[]),h=T.version,g=Vs(g,T),f++;u=h;let A=performance.now();d=!!n?.resultPicker;let x=await Ao(g,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),y=performance.now()-A,E=g[x]?.delta??{},C=Array.isArray(t)?{}:t??{};if(this.trace={...C,...E},d&&this.isDebug(e,n)){let T=this.getLogger(e,n);Ji(g.length,x,y,T)}if(c=!0,p&&(Ja(p,g.length,d,d?y:void 0,a),Va(p,l,f,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&&(ja(m,p,c,a,e.getName(),n?.model?String(n.model):void 0),u>0&&$s(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=Vs(a,d);let c=await Ao(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")}},nr=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function oi(s,e,t){let n=s instanceof Error?s:new Error(String(s)),r=e.getLastUsedChatModel(),o=e.getLastUsedModelConfig(),i={model:r,maxTokens:o?.maxTokens,streaming:o?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new nr("Generate failed",i,{cause:n})}var Nu=s=>s.replace(/^\W+|\W+$/g,""),$u=(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]},Gu=s=>{let e=new Set,t=[];for(let n of s)e.has(n)||(e.add(n),t.push(n));return t},Lu=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}},Uu=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():s},Bu=(s,e)=>{let t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t},yo={trimNonAlphaNum:Nu,splitIntoTwo:$u,dedup:Gu,extractIdAndText:Lu,extractIndexPrefixedText:Uu,batchArray:Bu};var bo=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."
|
|
236
|
+
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}=yo.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 Io=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 _A=new ve,To=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},Co=class{ai;db;debug;constructor(e){this.db=new bt,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 Gl=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 Ll(s,e){return s.filter(t=>!e.has(t))}function Ul(s){let e={};for(let t of s)e[t]=(e[t]||0)+1;return e}function Pt(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 qu(s,e){return Pt(s)===Pt(e)?1:0}function zu(s,e){let t=Pt(s).split(" "),n=Pt(e).split(" "),r=Ul(t),o=Ul(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 ju(s,e,t,n=!1){let r=Pt(s).split(" "),o=Pt(e).split(" "),i=Pt(t).split(" "),a=new Set([...Gl,...r]);o=Ll(o,a),i=Ll(i,a);let l=0,c=l/o.length,u=l/i.length,d=2*c*u/(c+u);return n?u:d}var Bl={emScore:qu,f1Score:zu,novelF1ScoreOptimized:ju};var Ro=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(`
|
|
237
237
|
Performance: `,r,"/",n,"Average Score: ",o,`
|
|
238
|
-
`)}};var wo=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
|
|
238
|
+
`)}};var wo=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 ql=s=>{console.log(s)},si=(s=ql)=>{let e=new ve,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let o="";switch(r.name){case"OptimizationStart":o=`
|
|
239
239
|
${e.blueBright("\u25CF ")}${e.whiteBright("Optimization Started")}
|
|
240
240
|
${t}
|
|
241
241
|
${e.white("Optimizer:")} ${e.cyan(r.value.optimizerType)}
|
|
242
242
|
${e.white("Examples:")} ${e.green(r.value.exampleCount.toString())} training, ${e.green(r.value.validationCount.toString())} validation
|
|
243
243
|
${e.white("Config:")} ${e.white(JSON.stringify(r.value.config).slice(0,80))}${JSON.stringify(r.value.config).length>80?"...":""}
|
|
244
244
|
${n}
|
|
245
|
-
`;break;case"RoundProgress":{let i=r.value.configuration||{},a=[];i.temperature!==void 0&&typeof i.temperature=="number"&&a.push(`T=${i.temperature.toFixed(2)}`),i.bootstrappedDemos!==void 0&&a.push(`demos=${i.bootstrappedDemos}`),Object.entries(i).forEach(([p
|
|
245
|
+
`;break;case"RoundProgress":{let i=r.value.configuration||{},a=[];i.temperature!==void 0&&typeof i.temperature=="number"&&a.push(`T=${i.temperature.toFixed(2)}`),i.bootstrappedDemos!==void 0&&a.push(`demos=${i.bootstrappedDemos}`),Object.entries(i).forEach(([d,p])=>{d!=="temperature"&&d!=="bootstrappedDemos"&&d!=="trialNumber"&&typeof p=="number"&&a.push(`${d}=${p.toFixed(2)}`)});let l=r.value.currentScore-r.value.bestScore,c=l>0?e.greenBright(` \u2191${l.toFixed(3)}`):l<0?e.red(` \u2193${Math.abs(l).toFixed(3)}`):"",u=typeof r.value.totalRounds=="number"&&r.value.totalRounds>0?r.value.totalRounds:typeof i.totalRounds=="number"&&i.totalRounds>0?i.totalRounds:0;o=`${e.yellow("\u25CF ")}${e.whiteBright(`Round ${r.value.round}/${u}`)}`+(i.trialNumber!==void 0?e.gray(` [Trial #${i.trialNumber}]`):"")+`
|
|
246
246
|
${e.white("Score:")} ${e.green(r.value.currentScore.toFixed(3))} ${e.white("(best:")} ${e.greenBright(r.value.bestScore.toFixed(3))}${e.white(")")}${c}
|
|
247
247
|
`+(a.length>0?` ${e.white("Config:")} ${e.cyan(a.join(", "))}
|
|
248
248
|
`:"")}break;case"EarlyStopping":o=`
|
|
@@ -304,7 +304,7 @@ Score: ${t.value.score.toFixed(3)}
|
|
|
304
304
|
Config: ${JSON.stringify(t.value.config)}
|
|
305
305
|
${e}`;break;default:n=`[ UNKNOWN OPTIMIZER EVENT ]
|
|
306
306
|
${JSON.stringify(t)}
|
|
307
|
-
${e}`}s(n)}},nr=si();var ii={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},vo,Hu=s=>{if(vo)return vo;if(s)return vo=Ku(s),vo};var So=ii,jl=s=>{So={...So,...s}},Hl=()=>({...So}),Ku=s=>({optimizationLatencyHistogram:s.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:s.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:s.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:s.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:s.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:s.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:s.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:s.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:s.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:s.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:s.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:s.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:s.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:s.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:s.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:s.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:s.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:s.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:s.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:s.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:s.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:s.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:s.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:s.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:s.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:s.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:s.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:s.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:s.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:s.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:s.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),Xe=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=So.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},Wu=(s,e,t,n,r)=>{try{let o=Xe({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{}});s.optimizationLatencyHistogram&&s.optimizationLatencyHistogram.record(e,o),s.optimizationRequestsCounter&&s.optimizationRequestsCounter.add(1,o),!t&&s.optimizationErrorsCounter&&s.optimizationErrorsCounter.add(1,o)}catch(o){console.warn("Failed to record optimization metric:",o)}},Vu=(s,e,t,n,r,o)=>{try{let i=Xe({optimizer_type:o});s.convergenceRoundsHistogram&&s.convergenceRoundsHistogram.record(e,i),s.convergenceScoreGauge&&s.convergenceScoreGauge.record(t,i),s.convergenceImprovementGauge&&s.convergenceImprovementGauge.record(n,i),s.stagnationRoundsGauge&&s.stagnationRoundsGauge.record(r,i)}catch(i){console.warn("Failed to record convergence metric:",i)}},Ju=(s,e,t)=>{try{let n=Xe({reason:e,optimizer_type:t});s.earlyStoppingCounter&&s.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},Yu=(s,e,t,n,r)=>{try{let o=Xe({optimizer_type:n});s.tokenUsageCounter&&s.tokenUsageCounter.add(e,o),s.costUsageCounter&&s.costUsageCounter.add(t,o),r!==void 0&&s.memoryUsageGauge&&s.memoryUsageGauge.record(r,o)}catch(o){console.warn("Failed to record resource usage metric:",o)}},Qu=(s,e,t)=>{try{let n=Xe({optimizer_type:t});s.optimizationDurationHistogram&&s.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},Zu=(s,e,t,n)=>{try{let r=Xe({optimizer_type:n});s.teacherStudentUsageCounter&&s.teacherStudentUsageCounter.add(1,r),s.teacherStudentLatencyHistogram&&s.teacherStudentLatencyHistogram.record(e,r),s.teacherStudentScoreImprovementGauge&&s.teacherStudentScoreImprovementGauge.record(t,r)}catch(r){console.warn("Failed to record teacher-student metric:",r)}},Xu=(s,e,t,n,r)=>{try{let o=Xe({operation:e,success:n.toString(),optimizer_type:r});e==="save"?(s.checkpointSaveCounter&&s.checkpointSaveCounter.add(1,o),s.checkpointSaveLatencyHistogram&&s.checkpointSaveLatencyHistogram.record(t,o)):(s.checkpointLoadCounter&&s.checkpointLoadCounter.add(1,o),s.checkpointLoadLatencyHistogram&&s.checkpointLoadLatencyHistogram.record(t,o))}catch(o){console.warn("Failed to record checkpoint metric:",o)}},ep=(s,e,t,n,r)=>{try{let o=Xe({optimizer_type:n});s.paretoOptimizationsCounter&&s.paretoOptimizationsCounter.add(1,o),s.paretoFrontSizeHistogram&&s.paretoFrontSizeHistogram.record(e,o),r!==void 0&&s.paretoHypervolumeGauge&&s.paretoHypervolumeGauge.record(r,o),s.paretoSolutionsGeneratedHistogram&&s.paretoSolutionsGeneratedHistogram.record(t,o)}catch(o){console.warn("Failed to record Pareto metric:",o)}},tp=(s,e,t,n,r,o)=>{try{let i=Xe({optimizer_type:o});s.programInputFieldsGauge&&s.programInputFieldsGauge.record(e,i),s.programOutputFieldsGauge&&s.programOutputFieldsGauge.record(t,i),s.examplesCountGauge&&s.examplesCountGauge.record(n,i),s.validationSetSizeGauge&&s.validationSetSizeGauge.record(r,i)}catch(i){console.warn("Failed to record program complexity metric:",i)}},np=(s,e,t,n)=>{try{let r=Xe({metric_type:e,optimizer_type:n});switch(e){case"evaluation":s.evaluationLatencyHistogram&&s.evaluationLatencyHistogram.record(t,r);break;case"demo_generation":s.demoGenerationLatencyHistogram&&s.demoGenerationLatencyHistogram.record(t,r);break;case"metric_computation":s.metricComputationLatencyHistogram&&s.metricComputationLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record optimizer performance metric:",r)}},rp=(s,e,t,n)=>{try{let r=Xe({optimizer_type:e});s.optimizerTypeGauge&&s.optimizerTypeGauge.record(1,r),t!==void 0&&s.targetScoreGauge&&s.targetScoreGauge.record(t,r),n!==void 0&&s.maxRoundsGauge&&s.maxRoundsGauge.record(n,r)}catch(r){console.warn("Failed to record optimizer configuration metric:",r)}},rt=class{bestScore;stats;instruction;demos;examples;modelConfig;optimizerType;optimizationTime;totalRounds;converged;scoreHistory;configurationHistory;constructor(e){this.bestScore=e.bestScore,this.stats=e.stats,this.instruction=e.instruction,this.demos=e.demos,this.examples=e.examples,this.modelConfig=e.modelConfig,this.optimizerType=e.optimizerType,this.optimizationTime=e.optimizationTime,this.totalRounds=e.totalRounds,this.converged=e.converged,this.scoreHistory=e.scoreHistory,this.configurationHistory=e.configurationHistory}applyTo(e){this.demos&&this.demos.length>0&&e.setDemos(this.demos),this.examples&&this.examples.length>0&&e.setExamples(this.examples),this.instruction&&(e._optimizedInstruction=this.instruction),this.modelConfig&&(e._optimizedModelConfig=this.modelConfig)}},rr=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let r=this.costPerModel[t]||.001;e+=n/1e3*r}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},_e=class{studentAI;teacherAI;targetScore;minSuccessRate;onProgress;onEarlyStop;costTracker;seed;checkpointSave;checkpointLoad;checkpointInterval;resumeFromCheckpoint;logger;verbose;debugOptimizer;optimizerLogger;currentRound=0;scoreHistory=[];configurationHistory=[];stats;metricsInstruments;resultExplainer;constructor(e){this.studentAI=e.studentAI,this.teacherAI=e.teacherAI,this.targetScore=e.targetScore,this.minSuccessRate=e.minSuccessRate,this.onProgress=e.onProgress,this.onEarlyStop=e.onEarlyStop,this.seed=e.seed,this.checkpointSave=e.checkpointSave,this.checkpointLoad=e.checkpointLoad,this.checkpointInterval=e.checkpointInterval??10,this.resumeFromCheckpoint=e.resumeFromCheckpoint,this.logger=e.logger,this.verbose=e.verbose;let t=new rr({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=Hu(ce.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?nr:void 0),this.initializeResultExplainer()}initializeResultExplainer(){this.resultExplainer=void 0}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}validateExamples(e,t=!0){if(!e||e.length===0)throw new Error("At least 1 example is required for optimization");if(t&&e.length<2)throw new Error("At least 2 examples are required for optimization with auto-splitting. Provide more examples to enable proper train/validation split.");let n=t?10:5;e.length<n&&this.verbose&&console.warn(`[Ax Optimizer] Warning: Only ${e.length} examples provided. Consider providing more examples (${n}+ recommended) for better optimization results.`)}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let r=this.getAIService(t,n);return await e(r)}async*compileStream(e,t,n,r){let o=Date.now(),i=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(i,a);let l,c=(g,f,h,A,x,b,I,M={},R)=>{this.getOptimizerLogger(R)?.({name:"RoundProgress",value:{round:g,totalRounds:R?.maxIterations??0,currentScore:f,bestScore:b,configuration:h}}),this.updateOptimizationProgress(g,f,h,A,x,b,I,M,R)},u=(g,f)=>{l=g,this.triggerEarlyStopping(g,this.currentRound)},p=g=>{this.onProgress?.(g),c(g.round,g.currentScore,g.currentConfiguration||{},i,{},g.bestScore,g.bestConfiguration,g.convergenceInfo,r)},d=await this.compile(e,t,n,{...r,overrideOnProgress:p,overrideOnEarlyStop:u}),m=Date.now()-o;return this.recordOptimizationComplete(m,!0,i,a),l&&this.getLogger(r)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${l}`}),{demos:d.demos,stats:d.stats,bestScore:d.bestScore,finalConfiguration:d.finalConfiguration,scoreHistory:d.scoreHistory,configurationHistory:d.configurationHistory}}async compilePareto(e,t,n,r){let o=this.constructor.name,i=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),l=await this.generateConstraintSolutions(e,t,n,r),c=[...a,...l],u=this.findParetoFrontier(c),p=this.calculateHypervolume(u);this.updateResourceUsage(i),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(u.length,c.length,"base_optimizer",p);let d=u.length>0?Math.max(...u.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:u.length>0?[...u[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:u,hypervolume:p,paretoFrontSize:u.length,finalConfiguration:{paretoFrontSize:u.length,hypervolume:p,strategy:"weighted_combinations_and_constraints",numSolutions:c.length}}}async generateWeightedSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for Pareto optimization");let i=t[0],a=await e.forward(this.getAIService(!1,r),i),l=await n({prediction:a,example:i}),c=Object.keys(l),u=this.generateWeightCombinations(c);for(let p=0;p<u.length;p++){let d=u[p],m=async({prediction:g,example:f})=>{let h=await n({prediction:g,example:f}),A=0;for(let[x,b]of Object.entries(h))A+=b*(d[x]||0);return A};try{let g=await this.compile(e,t,m,{...r,verbose:!1}),f=await this.evaluateWithMultiObjective(e,g,n,t);o.push({scores:f,demos:g.demos,configuration:{...g.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return o}async generateConstraintSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for multi-objective optimization");let i=t[0],a=await e.forward(this.getAIService(!1,r),i),l=await n({prediction:a,example:i}),c=Object.keys(l);for(let u of c){let p=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),f=g[u]||0,h=0;for(let[A,x]of Object.entries(g))A!==u&&x<.3&&(h+=(.3-x)*2);return f-h};try{let d=await this.compile(e,t,p,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);o.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:u,strategy:"constraint_based"}})}catch{}}return o}generateWeightCombinations(e){let t=[];for(let r of e){let o={};for(let i of e)o[i]=i===r?1:0;t.push(o)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,o]=e;for(let i=.1;i<=.9;i+=.2){let a=1-i;t.push({[r]:i,[o]:a})}}if(e.length===3){let[r,o,i]=e;t.push({[r]:.5,[o]:.3,[i]:.2},{[r]:.3,[o]:.5,[i]:.2},{[r]:.2,[o]:.3,[i]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let o=new Pe(e.getSignature());t.demos&&o.setDemos(t.demos);let i=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),l=r.slice(-a),c={},u=l;for(let d of u)try{let m=await o.forward(this.studentAI,d),g=await n({prediction:m,example:d});for(let[f,h]of Object.entries(g))c[f]||(c[f]=[]),c[f].push(h)}catch{}let p={};for(let[d,m]of Object.entries(c))p[d]=m.length>0?m.reduce((g,f)=>g+f,0)/m.length:0;return p}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=!1,i=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,r.scores)){o=!0;break}this.dominates(r.scores,l.scores)&&i++}o||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:i})}return t}dominates(e,t){let n=Object.keys(e),r=!0,o=!1;for(let i of n){let a=e[i]||0,l=t[i]||0;if(a<l){r=!1;break}a>l&&(o=!0)}return r&&o}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,o]=n,i=0,a=[...e].sort((c,u)=>(u.scores[r]||0)-(c.scores[r]||0)),l=0;for(let c of a){let u=c.scores[r]||0,p=c.scores[o]||0;i+=u*(p-l),l=Math.max(l,p)}return i}}async saveCheckpoint(e,t,n,r,o={},i){let a=i?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),c=!1,u;try{let p={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:r,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:o,examples:[]};u=await a(p),c=!0}catch(p){throw c=!1,p}finally{let p=Date.now()-l;this.recordCheckpointMetrics("save",p,c,e)}return u}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),o=!1,i=null;try{i=await n(e),o=i!==null}catch(a){throw o=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,o,"unknown")}return i}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=t?.overrideCheckpointInterval||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,r,o,i,a,l={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,o,i,a,l,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:i,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,o={},i){i?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...o,final:!0},i)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:this.studentAI.getLogger()}isLoggingEnabled(e){return e?.verbose!==void 0?e.verbose:this.verbose??!0}recordOptimizationStart(e,t){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,r=(t.match(/output:/g)||[]).length;tp(this.metricsInstruments,n,r,0,0,e)}rp(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,r){if(!this.metricsInstruments)return;Wu(this.metricsInstruments,e,t,n,r),Qu(this.metricsInstruments,e,n);let o=this.costTracker?.getCurrentCost()??0,i=this.costTracker?.getTotalTokens()??0;Yu(this.metricsInstruments,i,o,n)}recordConvergenceMetrics(e,t,n,r,o){this.metricsInstruments&&Vu(this.metricsInstruments,e,t,n,r,o)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&Ju(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&Zu(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,r){this.metricsInstruments&&Xu(this.metricsInstruments,e,t,n,r)}recordParetoMetrics(e,t,n,r){this.metricsInstruments&&ep(this.metricsInstruments,e,t,n,r)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&np(this.metricsInstruments,e,t,n)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??ce.optimizerLogger??nr}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,o=this.stats.totalCalls,i=o>0?this.stats.successfulDemos/o*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${r?"yes":"no"}. Success rate: ${i.toFixed(1)}%.`,l=[];if(r||l.push("Increase numTrials or relax earlyStoppingTrials to allow further improvement."),typeof this.targetScore=="number"&&e<this.targetScore&&l.push("Tighten the metric or supply more/better-labeled examples to reach targetScore."),t&&"bootstrappedDemos"in t){let u=t.bootstrappedDemos;typeof u=="number"&&u===0&&l.push("Consider allowing a small number of bootstrapped demos to boost performance.")}l.length===0&&l.push("Re-run with more trials or different acquisition settings to explore more of the space.");let c=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:l,performanceAssessment:c}}async logOptimizationComplete(e,t,n,r,o){let i=this.getOptimizerLogger(r);i&&i(o?{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",explanation:o.humanExplanation,recommendations:o.recommendations,performanceAssessment:o.performanceAssessment,stats:this.stats}}:{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",stats:this.stats}})}reset(){this.stats=this.initializeStats(),this.costTracker?.reset(),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}};function Kl(s){return ge.create(s)}function ye(s,e){let t=typeof s=="string"?ge.create(s):s;return new Pe(t,e)}var Wl=Rn(bc("crypto"),1);function ai(s){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:s}}function Pt(s){return JSON.parse(JSON.stringify(s))}function op(s){return Math.ceil(s.length/4)}function li(s,e,t){let n=[],r=[],{maxSectionSize:o=Number.POSITIVE_INFINITY,allowDynamicSections:i=!0,enableAutoPrune:a=!1,protectedBulletIds:l}=t??{},c=new Date().toISOString(),u=l??new Set;for(let p of e){if(!p.section)continue;if(!s.sections[p.section]){if(!i)continue;s.sections[p.section]=[]}let d=s.sections[p.section];switch(p.type){case"ADD":{if(d.length>=o){if(!a)continue;let f=ip(d,u);if(!f)continue;n.push(f.id),r.push({type:"REMOVE",section:p.section,bulletId:f.id,metadata:{...f.metadata??{},autoPruned:!0,removedAt:c}})}let m=p.bulletId??sp(p.section),g={id:m,section:p.section,content:p.content??"",helpfulCount:0,harmfulCount:0,createdAt:c,updatedAt:c,metadata:p.metadata?{...p.metadata}:void 0};d.push(g),n.push(m);break}case"UPDATE":{let m=d.find(g=>g.id===p.bulletId);if(!m)continue;typeof p.content=="string"&&(m.content=p.content),m.updatedAt=c,p.metadata&&(m.metadata={...m.metadata??{},...p.metadata}),n.push(m.id);break}case"REMOVE":{let m=d.findIndex(g=>g.id===p.bulletId);if(m>=0){let[g]=d.splice(m,1);g&&n.push(g.id)}break}}}return pi(s),s.updatedAt=c,{updatedBulletIds:n,autoRemoved:r}}function ci(s,e,t){for(let n of Object.values(s.sections)){let r=n.find(o=>o.id===e);if(r){t==="helpful"?r.helpfulCount+=1:t==="harmful"&&(r.harmfulCount+=1),r.updatedAt=new Date().toISOString(),pi(s);return}}}function or(s){let e=s.description?`## Context Playbook
|
|
307
|
+
${e}`}s(n)}},rr=si();var ii={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},vo,Hu=s=>{if(vo)return vo;if(s)return vo=Ku(s),vo};var So=ii,jl=s=>{So={...So,...s}},Hl=()=>({...So}),Ku=s=>({optimizationLatencyHistogram:s.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:s.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:s.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:s.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:s.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:s.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:s.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:s.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:s.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:s.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:s.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:s.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:s.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:s.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:s.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:s.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:s.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:s.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:s.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:s.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:s.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:s.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:s.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:s.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:s.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:s.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:s.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:s.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:s.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:s.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:s.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),et=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=So.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},Wu=(s,e,t,n,r)=>{try{let o=et({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{}});s.optimizationLatencyHistogram&&s.optimizationLatencyHistogram.record(e,o),s.optimizationRequestsCounter&&s.optimizationRequestsCounter.add(1,o),!t&&s.optimizationErrorsCounter&&s.optimizationErrorsCounter.add(1,o)}catch(o){console.warn("Failed to record optimization metric:",o)}},Vu=(s,e,t,n,r,o)=>{try{let i=et({optimizer_type:o});s.convergenceRoundsHistogram&&s.convergenceRoundsHistogram.record(e,i),s.convergenceScoreGauge&&s.convergenceScoreGauge.record(t,i),s.convergenceImprovementGauge&&s.convergenceImprovementGauge.record(n,i),s.stagnationRoundsGauge&&s.stagnationRoundsGauge.record(r,i)}catch(i){console.warn("Failed to record convergence metric:",i)}},Ju=(s,e,t)=>{try{let n=et({reason:e,optimizer_type:t});s.earlyStoppingCounter&&s.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},Yu=(s,e,t,n,r)=>{try{let o=et({optimizer_type:n});s.tokenUsageCounter&&s.tokenUsageCounter.add(e,o),s.costUsageCounter&&s.costUsageCounter.add(t,o),r!==void 0&&s.memoryUsageGauge&&s.memoryUsageGauge.record(r,o)}catch(o){console.warn("Failed to record resource usage metric:",o)}},Qu=(s,e,t)=>{try{let n=et({optimizer_type:t});s.optimizationDurationHistogram&&s.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},Zu=(s,e,t,n)=>{try{let r=et({optimizer_type:n});s.teacherStudentUsageCounter&&s.teacherStudentUsageCounter.add(1,r),s.teacherStudentLatencyHistogram&&s.teacherStudentLatencyHistogram.record(e,r),s.teacherStudentScoreImprovementGauge&&s.teacherStudentScoreImprovementGauge.record(t,r)}catch(r){console.warn("Failed to record teacher-student metric:",r)}},Xu=(s,e,t,n,r)=>{try{let o=et({operation:e,success:n.toString(),optimizer_type:r});e==="save"?(s.checkpointSaveCounter&&s.checkpointSaveCounter.add(1,o),s.checkpointSaveLatencyHistogram&&s.checkpointSaveLatencyHistogram.record(t,o)):(s.checkpointLoadCounter&&s.checkpointLoadCounter.add(1,o),s.checkpointLoadLatencyHistogram&&s.checkpointLoadLatencyHistogram.record(t,o))}catch(o){console.warn("Failed to record checkpoint metric:",o)}},ep=(s,e,t,n,r)=>{try{let o=et({optimizer_type:n});s.paretoOptimizationsCounter&&s.paretoOptimizationsCounter.add(1,o),s.paretoFrontSizeHistogram&&s.paretoFrontSizeHistogram.record(e,o),r!==void 0&&s.paretoHypervolumeGauge&&s.paretoHypervolumeGauge.record(r,o),s.paretoSolutionsGeneratedHistogram&&s.paretoSolutionsGeneratedHistogram.record(t,o)}catch(o){console.warn("Failed to record Pareto metric:",o)}},tp=(s,e,t,n,r,o)=>{try{let i=et({optimizer_type:o});s.programInputFieldsGauge&&s.programInputFieldsGauge.record(e,i),s.programOutputFieldsGauge&&s.programOutputFieldsGauge.record(t,i),s.examplesCountGauge&&s.examplesCountGauge.record(n,i),s.validationSetSizeGauge&&s.validationSetSizeGauge.record(r,i)}catch(i){console.warn("Failed to record program complexity metric:",i)}},np=(s,e,t,n)=>{try{let r=et({metric_type:e,optimizer_type:n});switch(e){case"evaluation":s.evaluationLatencyHistogram&&s.evaluationLatencyHistogram.record(t,r);break;case"demo_generation":s.demoGenerationLatencyHistogram&&s.demoGenerationLatencyHistogram.record(t,r);break;case"metric_computation":s.metricComputationLatencyHistogram&&s.metricComputationLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record optimizer performance metric:",r)}},rp=(s,e,t,n)=>{try{let r=et({optimizer_type:e});s.optimizerTypeGauge&&s.optimizerTypeGauge.record(1,r),t!==void 0&&s.targetScoreGauge&&s.targetScoreGauge.record(t,r),n!==void 0&&s.maxRoundsGauge&&s.maxRoundsGauge.record(n,r)}catch(r){console.warn("Failed to record optimizer configuration metric:",r)}},ot=class{bestScore;stats;instruction;demos;examples;modelConfig;optimizerType;optimizationTime;totalRounds;converged;scoreHistory;configurationHistory;constructor(e){this.bestScore=e.bestScore,this.stats=e.stats,this.instruction=e.instruction,this.demos=e.demos,this.examples=e.examples,this.modelConfig=e.modelConfig,this.optimizerType=e.optimizerType,this.optimizationTime=e.optimizationTime,this.totalRounds=e.totalRounds,this.converged=e.converged,this.scoreHistory=e.scoreHistory,this.configurationHistory=e.configurationHistory}applyTo(e){this.demos&&this.demos.length>0&&e.setDemos(this.demos),this.examples&&this.examples.length>0&&e.setExamples(this.examples),this.instruction&&(e._optimizedInstruction=this.instruction),this.modelConfig&&(e._optimizedModelConfig=this.modelConfig)}},or=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let r=this.costPerModel[t]||.001;e+=n/1e3*r}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},_e=class{studentAI;teacherAI;targetScore;minSuccessRate;onProgress;onEarlyStop;costTracker;seed;checkpointSave;checkpointLoad;checkpointInterval;resumeFromCheckpoint;logger;verbose;debugOptimizer;optimizerLogger;currentRound=0;scoreHistory=[];configurationHistory=[];stats;metricsInstruments;resultExplainer;constructor(e){this.studentAI=e.studentAI,this.teacherAI=e.teacherAI,this.targetScore=e.targetScore,this.minSuccessRate=e.minSuccessRate,this.onProgress=e.onProgress,this.onEarlyStop=e.onEarlyStop,this.seed=e.seed,this.checkpointSave=e.checkpointSave,this.checkpointLoad=e.checkpointLoad,this.checkpointInterval=e.checkpointInterval??10,this.resumeFromCheckpoint=e.resumeFromCheckpoint,this.logger=e.logger,this.verbose=e.verbose;let t=new or({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=Hu(ee.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?rr:void 0),this.initializeResultExplainer()}initializeResultExplainer(){this.resultExplainer=void 0}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}validateExamples(e,t=!0){if(!e||e.length===0)throw new Error("At least 1 example is required for optimization");if(t&&e.length<2)throw new Error("At least 2 examples are required for optimization with auto-splitting. Provide more examples to enable proper train/validation split.");let n=t?10:5;e.length<n&&this.verbose&&console.warn(`[Ax Optimizer] Warning: Only ${e.length} examples provided. Consider providing more examples (${n}+ recommended) for better optimization results.`)}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let r=this.getAIService(t,n);return await e(r)}async*compileStream(e,t,n,r){let o=Date.now(),i=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(i,a);let l,c=(g,h,f,A,x,y,I,E={},C)=>{this.getOptimizerLogger(C)?.({name:"RoundProgress",value:{round:g,totalRounds:C?.maxIterations??0,currentScore:h,bestScore:y,configuration:f}}),this.updateOptimizationProgress(g,h,f,A,x,y,I,E,C)},u=(g,h)=>{l=g,this.triggerEarlyStopping(g,this.currentRound)},d=g=>{this.onProgress?.(g),c(g.round,g.currentScore,g.currentConfiguration||{},i,{},g.bestScore,g.bestConfiguration,g.convergenceInfo,r)},p=await this.compile(e,t,n,{...r,overrideOnProgress:d,overrideOnEarlyStop:u}),m=Date.now()-o;return this.recordOptimizationComplete(m,!0,i,a),l&&this.getLogger(r)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${l}`}),{demos:p.demos,stats:p.stats,bestScore:p.bestScore,finalConfiguration:p.finalConfiguration,scoreHistory:p.scoreHistory,configurationHistory:p.configurationHistory}}async compilePareto(e,t,n,r){let o=this.constructor.name,i=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),l=await this.generateConstraintSolutions(e,t,n,r),c=[...a,...l],u=this.findParetoFrontier(c),d=this.calculateHypervolume(u);this.updateResourceUsage(i),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(u.length,c.length,"base_optimizer",d);let p=u.length>0?Math.max(...u.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:u.length>0?[...u[0].demos]:void 0,stats:this.stats,bestScore:p,paretoFront:u,hypervolume:d,paretoFrontSize:u.length,finalConfiguration:{paretoFrontSize:u.length,hypervolume:d,strategy:"weighted_combinations_and_constraints",numSolutions:c.length}}}async generateWeightedSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for Pareto optimization");let i=t[0],a=await e.forward(this.getAIService(!1,r),i),l=await n({prediction:a,example:i}),c=Object.keys(l),u=this.generateWeightCombinations(c);for(let d=0;d<u.length;d++){let p=u[d],m=async({prediction:g,example:h})=>{let f=await n({prediction:g,example:h}),A=0;for(let[x,y]of Object.entries(f))A+=y*(p[x]||0);return A};try{let g=await this.compile(e,t,m,{...r,verbose:!1}),h=await this.evaluateWithMultiObjective(e,g,n,t);o.push({scores:h,demos:g.demos,configuration:{...g.finalConfiguration,weights:p,strategy:"weighted_combination"}})}catch{}}return o}async generateConstraintSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for multi-objective optimization");let i=t[0],a=await e.forward(this.getAIService(!1,r),i),l=await n({prediction:a,example:i}),c=Object.keys(l);for(let u of c){let d=async({prediction:p,example:m})=>{let g=await n({prediction:p,example:m}),h=g[u]||0,f=0;for(let[A,x]of Object.entries(g))A!==u&&x<.3&&(f+=(.3-x)*2);return h-f};try{let p=await this.compile(e,t,d,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,p,n,t);o.push({scores:m,demos:p.demos,configuration:{...p.finalConfiguration,primaryObjective:u,strategy:"constraint_based"}})}catch{}}return o}generateWeightCombinations(e){let t=[];for(let r of e){let o={};for(let i of e)o[i]=i===r?1:0;t.push(o)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,o]=e;for(let i=.1;i<=.9;i+=.2){let a=1-i;t.push({[r]:i,[o]:a})}}if(e.length===3){let[r,o,i]=e;t.push({[r]:.5,[o]:.3,[i]:.2},{[r]:.3,[o]:.5,[i]:.2},{[r]:.2,[o]:.3,[i]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let o=new Pe(e.getSignature());t.demos&&o.setDemos(t.demos);let i=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),l=r.slice(-a),c={},u=l;for(let p of u)try{let m=await o.forward(this.studentAI,p),g=await n({prediction:m,example:p});for(let[h,f]of Object.entries(g))c[h]||(c[h]=[]),c[h].push(f)}catch{}let d={};for(let[p,m]of Object.entries(c))d[p]=m.length>0?m.reduce((g,h)=>g+h,0)/m.length:0;return d}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=!1,i=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,r.scores)){o=!0;break}this.dominates(r.scores,l.scores)&&i++}o||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:i})}return t}dominates(e,t){let n=Object.keys(e),r=!0,o=!1;for(let i of n){let a=e[i]||0,l=t[i]||0;if(a<l){r=!1;break}a>l&&(o=!0)}return r&&o}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,o]=n,i=0,a=[...e].sort((c,u)=>(u.scores[r]||0)-(c.scores[r]||0)),l=0;for(let c of a){let u=c.scores[r]||0,d=c.scores[o]||0;i+=u*(d-l),l=Math.max(l,d)}return i}}async saveCheckpoint(e,t,n,r,o={},i){let a=i?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),c=!1,u;try{let d={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:r,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:o,examples:[]};u=await a(d),c=!0}catch(d){throw c=!1,d}finally{let d=Date.now()-l;this.recordCheckpointMetrics("save",d,c,e)}return u}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),o=!1,i=null;try{i=await n(e),o=i!==null}catch(a){throw o=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,o,"unknown")}return i}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=t?.overrideCheckpointInterval||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,r,o,i,a,l={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,o,i,a,l,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:i,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,o={},i){i?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...o,final:!0},i)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:this.studentAI.getLogger()}isLoggingEnabled(e){return e?.verbose!==void 0?e.verbose:this.verbose??!0}recordOptimizationStart(e,t){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,r=(t.match(/output:/g)||[]).length;tp(this.metricsInstruments,n,r,0,0,e)}rp(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,r){if(!this.metricsInstruments)return;Wu(this.metricsInstruments,e,t,n,r),Qu(this.metricsInstruments,e,n);let o=this.costTracker?.getCurrentCost()??0,i=this.costTracker?.getTotalTokens()??0;Yu(this.metricsInstruments,i,o,n)}recordConvergenceMetrics(e,t,n,r,o){this.metricsInstruments&&Vu(this.metricsInstruments,e,t,n,r,o)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&Ju(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&Zu(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,r){this.metricsInstruments&&Xu(this.metricsInstruments,e,t,n,r)}recordParetoMetrics(e,t,n,r){this.metricsInstruments&&ep(this.metricsInstruments,e,t,n,r)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&np(this.metricsInstruments,e,t,n)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??ee.optimizerLogger??rr}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,o=this.stats.totalCalls,i=o>0?this.stats.successfulDemos/o*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${r?"yes":"no"}. Success rate: ${i.toFixed(1)}%.`,l=[];if(r||l.push("Increase numTrials or relax earlyStoppingTrials to allow further improvement."),typeof this.targetScore=="number"&&e<this.targetScore&&l.push("Tighten the metric or supply more/better-labeled examples to reach targetScore."),t&&"bootstrappedDemos"in t){let u=t.bootstrappedDemos;typeof u=="number"&&u===0&&l.push("Consider allowing a small number of bootstrapped demos to boost performance.")}l.length===0&&l.push("Re-run with more trials or different acquisition settings to explore more of the space.");let c=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:l,performanceAssessment:c}}async logOptimizationComplete(e,t,n,r,o){let i=this.getOptimizerLogger(r);i&&i(o?{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",explanation:o.humanExplanation,recommendations:o.recommendations,performanceAssessment:o.performanceAssessment,stats:this.stats}}:{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",stats:this.stats}})}reset(){this.stats=this.initializeStats(),this.costTracker?.reset(),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}};function Kl(s){return ge.create(s)}function ye(s,e){let t=typeof s=="string"?ge.create(s):s;return new Pe(t,e)}var Wl=wn(bc("crypto"),1);function ai(s){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:s}}function _t(s){return JSON.parse(JSON.stringify(s))}function op(s){return Math.ceil(s.length/4)}function li(s,e,t){let n=[],r=[],{maxSectionSize:o=Number.POSITIVE_INFINITY,allowDynamicSections:i=!0,enableAutoPrune:a=!1,protectedBulletIds:l}=t??{},c=new Date().toISOString(),u=l??new Set;for(let d of e){if(!d.section)continue;if(!s.sections[d.section]){if(!i)continue;s.sections[d.section]=[]}let p=s.sections[d.section];switch(d.type){case"ADD":{if(p.length>=o){if(!a)continue;let h=ip(p,u);if(!h)continue;n.push(h.id),r.push({type:"REMOVE",section:d.section,bulletId:h.id,metadata:{...h.metadata??{},autoPruned:!0,removedAt:c}})}let m=d.bulletId??sp(d.section),g={id:m,section:d.section,content:d.content??"",helpfulCount:0,harmfulCount:0,createdAt:c,updatedAt:c,metadata:d.metadata?{...d.metadata}:void 0};p.push(g),n.push(m);break}case"UPDATE":{let m=p.find(g=>g.id===d.bulletId);if(!m)continue;typeof d.content=="string"&&(m.content=d.content),m.updatedAt=c,d.metadata&&(m.metadata={...m.metadata??{},...d.metadata}),n.push(m.id);break}case"REMOVE":{let m=p.findIndex(g=>g.id===d.bulletId);if(m>=0){let[g]=p.splice(m,1);g&&n.push(g.id)}break}}}return pi(s),s.updatedAt=c,{updatedBulletIds:n,autoRemoved:r}}function ci(s,e,t){for(let n of Object.values(s.sections)){let r=n.find(o=>o.id===e);if(r){t==="helpful"?r.helpfulCount+=1:t==="harmful"&&(r.harmfulCount+=1),r.updatedAt=new Date().toISOString(),pi(s);return}}}function sr(s){let e=s.description?`## Context Playbook
|
|
308
308
|
${s.description.trim()}
|
|
309
309
|
`:`## Context Playbook
|
|
310
310
|
`,t=Object.entries(s.sections).map(([n,r])=>{let o=r.map(i=>`- [${i.id}] ${i.content}`).join(`
|
|
@@ -313,11 +313,11 @@ ${o}`:`### ${n}
|
|
|
313
313
|
_(empty)_`}).join(`
|
|
314
314
|
|
|
315
315
|
`);return`${e}
|
|
316
|
-
${t}`.trim()}function sp(s){let e=s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=Wl.default.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function ip(s,e){let t=-1,n;for(let o=0;o<s.length;o+=1){let i=s[o];if(e.has(i.id))continue;let a=i.helpfulCount??0,l=i.harmfulCount??0,c=a-l*2,u=Date.parse(i.updatedAt??i.createdAt),
|
|
316
|
+
${t}`.trim()}function sp(s){let e=s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=Wl.default.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function ip(s,e){let t=-1,n;for(let o=0;o<s.length;o+=1){let i=s[o];if(e.has(i.id))continue;let a=i.helpfulCount??0,l=i.harmfulCount??0,c=a-l*2,u=Date.parse(i.updatedAt??i.createdAt),d=[c,a,Number.isFinite(u)?u:Number.POSITIVE_INFINITY];if(!n){t=o,n=d;continue}let p=s[t],m=p.helpfulCount??0,g=p.harmfulCount??0,h=m-g*2,f=Date.parse(p.updatedAt??p.createdAt),A=[h,m,Number.isFinite(f)?f:Number.POSITIVE_INFINITY];(d[0]<A[0]||d[0]===A[0]&&d[1]<A[1]||d[0]===A[0]&&d[1]===A[1]&&d[2]<A[2])&&(t=o,n=d)}if(t===-1)return;let[r]=s.splice(t,1);return r}function ui(s,e=.95){for(let[t,n]of Object.entries(s.sections)){let r=new Map,o=[];for(let i of n){let a=i.content.trim().toLowerCase(),l=r.get(a);l?(l.helpfulCount+=i.helpfulCount,l.harmfulCount+=i.harmfulCount,l.updatedAt=i.updatedAt):(r.set(a,i),o.push(i))}s.sections[t]=o}pi(s)}function pi(s){let e=0,t=0,n=0,r=0;for(let o of Object.values(s.sections))for(let i of o)e+=1,t+=i.helpfulCount,n+=i.harmfulCount,r+=op(i.content);s.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var ap={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},ir=class extends ot{playbook;artifact;baseInstruction;constructor(e){super({bestScore:e.bestScore,stats:e.stats,instruction:e.instruction,demos:e.demos,examples:e.examples,modelConfig:e.modelConfig,optimizerType:e.optimizerType,optimizationTime:e.optimizationTime,totalRounds:e.totalRounds,converged:e.converged,scoreHistory:e.scoreHistory,configurationHistory:e.configurationHistory}),this.playbook=_t(e.playbook),this.artifact=e.artifact,this.baseInstruction=e.baseInstruction}applyTo(e){super.applyTo(e);let t=e.getSignature(),r=[(this.baseInstruction??t.getDescription()??"").trim(),"",sr(this.playbook)].filter(o=>o&&o.trim().length>0).join(`
|
|
317
317
|
|
|
318
|
-
`);e.setDescription(r)}},Oo=class extends _e{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;constructor(e,t){super(e),this.aceConfig={...ap,...t},this.playbook=t?.initialPlaybook!==void 0?
|
|
318
|
+
`);e.setDescription(r)}},Oo=class extends _e{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;constructor(e,t){super(e),this.aceConfig={...ap,...t},this.playbook=t?.initialPlaybook!==void 0?_t(t.initialPlaybook):ai()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?_t(this.aceConfig.initialPlaybook):ai(),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=_t(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 A=0;A<d;A++)for(let x=0;x<t.length;x++){let y=t[x],I=this.composeInstruction(a??l,this.playbook);e.setDescription?.(I);let E=await e.forward(this.studentAI,y);this.stats.totalCalls+=1;let C=await n({prediction:E,example:y});typeof C=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,C),c=Math.max(c,C));let T=E?.severity,v=y?.severity,k=this.createGeneratorOutput(E,y),L=v&&T&&v!==T,P=await this.runReflectionRounds({example:y,generatorOutput:k,feedback:v&&T&&v!==T?`Expected severity "${v}" but model predicted "${T}".`:void 0}),R=await this.runCurator({example:y,reflection:P,playbook:this.playbook}),w=this.normalizeCuratorOperations(R?.operations);w.length===0&&L&&(w=this.inferOperationsFromReflection(P)),w=this.resolveCuratorOperationTargets(w,this.playbook,P,k);let b=R||w.length>0?{...R??{},operations:w}:void 0,O=[];if(w.length>0){let z=this.collectProtectedBulletIds(w),q=li(this.playbook,w,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:z});O=q.updatedBulletIds,q.autoRemoved.length>0&&(w.push(...q.autoRemoved),b&&(b.operations=w))}if(P?.bulletTags)for(let z of P.bulletTags)ci(this.playbook,z.id,z.tag);w.length>0&&O.length>0&&ui(this.playbook,this.aceConfig.similarityThreshold);let S={example:y,prediction:E,score:typeof C=="number"?C:0,generatorOutput:k,reflection:P,curator:b,timestamp:new Date().toISOString()};this.generatorHistory.push(S),O.length>0&&b?.operations?.length&&this.deltaHistory.push({epoch:A,exampleIndex:x,operations:b.operations}),u+=1,this.currentRound=u;let M=typeof C=="number"&&Number.isFinite(C)?C:0,_=Number.isFinite(c)?c:M,F={...r??{},maxIterations:p};await this.updateOptimizationProgress(u,M,{epoch:A,exampleIndex:x,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:d,totalRounds:p},_,{playbookBullets:this.playbook.stats.bulletCount},void 0,F),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 g={playbook:_t(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},h=new ir({baseInstruction:a??l,playbook:this.playbook,artifact:g,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:h,playbook:_t(this.playbook),artifact:g}}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=li(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)),ui(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(),"",sr(t)].filter(r=>r.trim().length>0).join(`
|
|
319
319
|
|
|
320
|
-
`)}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,p)=>{if(i.has(u))return;let d=this.locateBullet(t,u);if(!d)return;let m=a.get(d.section)??{harmful:[],primary:[],generator:[]};m[p].push(d.id),a.set(d.section,m)};for(let u of n?.bulletTags??[]){let p=u.tag==="harmful"?"harmful":"primary";l(u.id,p)}if(r?.bulletIds)for(let u of r.bulletIds)l(u,"generator");let c=u=>{let p=a.get(u);if(!p)return this.locateFallbackBullet(t,u,i);let d=g=>{for(;g.length>0;){let f=g.shift();if(!i.has(f))return f}},m=d(p.harmful)??d(p.primary)??d(p.generator);return m||this.locateFallbackBullet(t,u,i)};for(let u of e){if((u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId){let p=c(u.section);p&&(u.bulletId=p,i.add(p))}(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??"",p=typeof u=="string"?u.trim():"";if(a!=="REMOVE"&&p.length===0)continue;let d=r.bulletId??r.id,m=typeof d=="string"&&d.trim().length>0?d.trim():void 0,f=[a,c,p,m??""].join(":");if(n.has(f))continue;n.add(f);let h={type:a,section:c};a!=="REMOVE"&&(h.content=p),m&&(h.bulletId=m);let A=r.metadata;A&&typeof A=="object"&&(h.metadata={...A}),t.push(h)}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:or(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:or(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=se().input("question",se.string("Original task input serialized as JSON")).input("generator_answer",se.string("Generator output serialized as JSON")).input("generator_reasoning",se.string("Generator reasoning trace").optional()).input("playbook",se.string("Current context playbook rendered as markdown")).input("expected_answer",se.string("Expected output when ground truth is available").optional()).input("feedback",se.string("External feedback or reward signal").optional()).input("previous_reflection",se.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",se.string("Step-by-step analysis of generator performance")).output("errorIdentification",se.string("Specific mistakes detected")).output("rootCauseAnalysis",se.string("Underlying cause of the error")).output("correctApproach",se.string("What the generator should do differently")).output("keyInsight",se.string("Reusable insight to remember")).output("bulletTags",se.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=ye(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=se().input("playbook",se.string("Current playbook serialized as JSON")).input("reflection",se.string("Latest reflection output serialized as JSON")).input("question_context",se.string("Original task input serialized as JSON")).input("token_budget",se.number("Approximate token budget for curator response").optional()).output("reasoning",se.string("Justification for the proposed updates")).output("operations",se.json("List of operations with type/section/content fields")).build();this.curatorProgram=ye(e)}return this.curatorProgram}};var hn=class extends _e{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=cp([...t],this.maxExamples),u=this.traces.length;for(let p=0;p<c.length;p+=this.batchSize){p>0&&(l.modelConfig.temperature=.7+.001*p);let d=c.slice(p,p+this.batchSize);for(let m of d){if(!m||typeof m!="object")continue;let g=t.filter(A=>A!==m);e.setExamples(g);let f=this.getTeacherOrStudentAI();this.stats.totalCalls++;let h;try{let A={...l,maxRetries:1};h=await e.forward(f,m,A),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(h).length/4),await r({prediction:h,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(A){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${A instanceof Error?A.message:"Unknown error"}`),h={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-u;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:d>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(d>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=lp(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 lp(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 cp=(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 Vl(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 ot(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(Vl(s[i].scores,s[n].scores,e)){o=!0;break}Vl(s[n].scores,s[i].scores,e)&&r++}o||t.push({idx:s[n].idx,scores:s[n].scores,dominated:r})}return t}function ze(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 ko(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 ir(s,e){let t=new Set;for(let u of s)for(let p of u)t.add(p);let r=[...Array.from(t)].sort((u,p)=>(e[u]??0)-(e[p]??0)),o=new Set,i=(u,p)=>{for(let d of s){if(!d.has(u))continue;let m=!1;for(let g of p)if(d.has(g)){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 p=new Set(r.filter(d=>d!==u&&!o.has(d)));if(i(u,p)){o.add(u),a=!0;break}}}let l=r.filter(u=>!o.has(u)),c=new Set(l);return s.map(u=>{let p=new Set;for(let d of u)c.has(d)&&p.add(d);return p})}function ar(s,e,t){let n=ir(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 p=0;p<c;p++)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 Mo=class extends _e{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(y,O)=>{try{e.setInstruction?.(y);let v=await e.forward(this.studentAI,O,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:v,example:O})||{}}catch{return{}}},p=async(y,O)=>{let v=[];for(let k of O)v.push(await u(y,k));return ko(v)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await p(d,l)}],g=y=>{let O=r?.paretoMetricKey,v=r?.paretoScalarize;if(typeof v=="function")return v(y);if(O)return Number.isFinite(y[O])?y[O]:0;let k=Object.values(y);return k.length?k.reduce((_,F)=>_+F,0)/k.length:0},f=[],h=async(y,O)=>{let v=[];for(let k of O){let _=await u(y,k);v.push(g(_))}return v};f.push(await h(d,l));let A=()=>{let y=f[0]?.length??0,O=[];for(let k=0;k<y;k++){let _=Number.NEGATIVE_INFINITY,F=new Set;for(let z=0;z<f.length;z++){let q=f[z][k];q>_+this.tieEpsilon?(_=q,F.clear(),F.add(z)):Math.abs(q-_)<=this.tieEpsilon&&F.add(z)}O.push(F)}let v=f.map(k=>_t(k));return ar(O,v)};this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let b=0,I=ot(m.map((y,O)=>({idx:O,scores:y.scores})),this.tieEpsilon).map(y=>y.idx),M,R=r?.maxMetricCalls;if(!Number.isFinite(R)||R<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let w=Math.floor(R);for(let y=0;y<this.numTrials&&!(w!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(w)));y++){let O=f[0]?.length??0,v=[];for(let D=0;D<O;D++){let U=Number.NEGATIVE_INFINITY,j=new Set;for(let H=0;H<f.length;H++){let J=f[H][D];J>U+this.tieEpsilon?(U=J,j.clear(),j.add(H)):Math.abs(J-U)<=this.tieEpsilon&&j.add(H)}v.push(j)}let k=f.map(D=>_t(D));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let D=$=>{let N=[],G=$;for(;G!==void 0;)N.push(G),G=m[G]?.parent;return N},U=$=>$.length?$[Math.floor(this.rand()*$.length)]:void 0,j=ir(v,k),H=new Set;for(let $ of j)for(let N of $)H.add(N);let J=Array.from(H),re;for(let $=0;$<10&&!re&&!(J.length<2);$++){let N=U(J),G=U(J);if(N===G)continue;G<N&&([N,G]=[G,N]);let te=new Set(D(N)),me=new Set(D(G));if(te.has(G)||me.has(N))continue;let ne=[...te].filter(pe=>me.has(pe));if(ne.length===0)continue;let Y=ne.map(pe=>Math.max(1e-9,k[pe])),Z=this.rand()*Y.reduce((pe,He)=>pe+He,0),X=ne[ne.length-1];for(let pe=0;pe<ne.length;pe++){if(Z<Y[pe]){X=ne[pe];break}Z-=Y[pe]}re={i:N,j:G,a:X}}if(this.lastIterFoundNewProgram=!1,re){let{i:$,j:N,a:G}=re,te=k[G],me=k[$],ne=k[N],Y=m[G].instruction,Z=m[$].instruction,X=m[N].instruction,pe=Z===Y&&X!==Z||X===Y&&Z!==X,He=te<=Math.min(me,ne)&&pe,Ne="",$e="i",mt=!1;if(He){let st=`${$}|${N}|${G}`;if(this.mergeAttemptKeys.has(st))He=!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>ne||me===ne&&this.rand()<.5?(Ne=Z,$e="i"):(Ne=X,$e="j"):(Ne=Z,$e="i");let le=`${Math.min($,N)}|${Math.max($,N)}|${$e}`;if(this.mergeCompositionKeys.has(le))He=!1;else{this.mergeAttemptKeys.add(st),this.mergeCompositionKeys.add(le);let Ke=f[$],it=f[N],Le=Array.from({length:Ke.length},(oe,Ce)=>Ce),gt=Le.filter(oe=>(Ke[oe]??0)>(it[oe]??0)),Ft=Le.filter(oe=>(it[oe]??0)>(Ke[oe]??0)),Tt=Le.filter(oe=>!(gt.includes(oe)||Ft.includes(oe))),at=5,ht=Math.ceil(at/3),W=(oe,Ce)=>{if(Ce<=0||oe.length===0)return[];if(oe.length<=Ce)return[...oe];let Cn=[],dr=new Set;for(;Cn.length<Ce;){let We=Math.floor(this.rand()*oe.length);dr.has(We)||(dr.add(We),Cn.push(oe[We]))}return Cn},ie=[];ie.push(...W(gt,Math.min(ht,gt.length))),ie.push(...W(Ft,Math.min(ht,Ft.length)));let Ct=at-ie.length;ie.push(...W(Tt,Math.max(0,Ct)));let Rt=at-ie.length;if(Rt>0){let oe=Le.filter(Ce=>!ie.includes(Ce));ie.push(...W(oe,Math.min(Rt,oe.length)))}let Te=ie.slice(0,Math.min(at,Le.length)),qo=Te.map(oe=>l[oe]);mt=!0;let pc=(await h(Ne,qo)).reduce((oe,Ce)=>oe+Ce,0),dc=Te.reduce((oe,Ce)=>oe+(Ke[Ce]??0),0),mc=Te.reduce((oe,Ce)=>oe+(it[Ce]??0),0);if(pc>=Math.max(dc,mc)+this.tieEpsilon){let oe=await p(Ne,l);m.push({instruction:Ne,parent:G,scores:oe}),f.push(await h(Ne,l));let Ce=I.length,Cn=ze(I.map(We=>m[We].scores))??0;I=ot(m.map((We,gc)=>({idx:gc,scores:We.scores})),this.tieEpsilon).map(We=>We.idx);let dr=ze(I.map(We=>m[We].scores))??0;(I.length>Ce||dr>Cn+1e-6)&&(b=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(mt)continue}}let _=ar(v,k,()=>this.rand()),F=this.minibatch?this.nextMinibatchIndices(c.length,y).map(D=>c[D]):c;if(r?.skipPerfectScore??!0){let D=Number(r?.perfectScore??1),U=await h(m[_].instruction,F);if(U.length>0&&U.every(j=>j>=D))continue}let z=!1,q=m[_].instruction,Q="reflective_mutation",ae,xe;if(z){let D=(_+1)%m.length;q=await this.mergeInstructions(m[_].instruction,m[D].instruction,r),Q="merge",this.mergesUsed+=1}else{let D=r?.gepaAdapter;if(D){try{let U={instruction:m[_].instruction},j=await D.evaluate(F,U,!0);ae=Array.isArray(j?.scores)?j.scores.reduce(($,N)=>$+(Number(N)||0),0):void 0;let H=D.make_reflective_dataset(U,j,["instruction"]),J=await D.propose_new_texts?.(U,H,["instruction"]),re=J?.instruction??(J?Object.values(J)[0]:void 0);typeof re=="string"&&re.length>0?q=re:q=await this.reflectInstruction(m[_].instruction,e,F,async({prediction:$,example:N})=>{let G=await n({prediction:$,example:N}),te=Object.values(G||{});return te.length?te.reduce((me,ne)=>me+ne,0)/te.length:0},r)}catch{q=await this.reflectInstruction(m[_].instruction,e,F,async({prediction:U,example:j})=>{let H=await n({prediction:U,example:j}),J=Object.values(H||{});return J.length?J.reduce((re,$)=>re+$,0)/J.length:0},r)}if(ae!==void 0)try{let U=await D.evaluate(F,{instruction:q},!1);xe=Array.isArray(U?.scores)?U.scores.reduce((j,H)=>j+(Number(H)||0),0):void 0}catch{}}else q=await this.reflectInstruction(m[_].instruction,e,F,async({prediction:U,example:j})=>{let H=await n({prediction:U,example:j}),J=Object.values(H||{});return J.length?J.reduce((re,$)=>re+$,0)/J.length:0},r)}let Fe=await h(m[_].instruction,F),je=await h(q,F),Se=Fe.reduce((D,U)=>D+U,0),ue=je.reduce((D,U)=>D+U,0);if(this.currentRound=y+1,await this.updateOptimizationProgress(this.currentRound,ue,{instructionLen:q.length,parent:_,totalRounds:this.numTrials},"GEPA",{strategy:Q,paretoSetSize:l.length},ue,{instructionLen:m[_].instruction.length,idx:_},{...r??{},maxIterations:this.numTrials}),!(ue>Se+this.tieEpsilon&&(ae===void 0||xe===void 0||xe>ae+this.tieEpsilon))){if(++b>=this.earlyStoppingTrials)break;continue}let De=await p(q,l);m.push({instruction:q,parent:_,scores:De}),f.push(await h(q,l));let Ge=I.length,pt=ze(I.map(D=>m[D].scores))??0;I=ot(m.map((D,U)=>({idx:U,scores:D.scores})),this.tieEpsilon).map(D=>D.idx);let dt=ze(I.map(D=>m[D].scores))??0;if(I.length>Ge||dt>pt+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 S=ot(m.map((y,O)=>({idx:O,scores:y.scores})),this.tieEpsilon),E=S.length>0?Math.max(...S.map(y=>g(y.scores))):0,L;if(S.length>0){let y=Number.NEGATIVE_INFINITY;for(let O of S){let v=g(O.scores);v>y&&(y=v,L=O.idx)}}let P=ze(S.map(y=>y.scores));this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(S.length,m.length,"GEPA",P);let T=Date.now()-o,C=typeof L=="number"?new rt({bestScore:E,stats:this.stats,instruction:m[L].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:T,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0;return this.generateOptimizationReport(S,P,E),{demos:[],stats:this.stats,bestScore:E,paretoFront:S.map(y=>({demos:[],scores:y.scores,configuration:{candidate:y.idx},dominatedSolutions:y.dominated})),paretoFrontSize:S.length,hypervolume:P,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:C}}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 g=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let f=await r({prediction:g,example:m});i.push({input:m,prediction:g,score:typeof f=="number"?f:0})}catch{i.push({input:m,prediction:{},score:0})}let a=o?.overrideTeacherAI??this.teacherAI??this.studentAI,l=ye('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 g=u({prediction:i[m].prediction,example:i[m].input});g&&(Array.isArray(g)?c.push(...g):c.push(g))}catch{}let p="";try{p=(await l.forward(a,{minibatch:i,evalFeedback:c}))?.feedbackSummary?.trim()||"",p&&(this.feedbackMemory.unshift(p),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop())}catch{}let d=ye('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 g=(await d.forward(a,{currentInstruction:e,feedbackSummary:p,recentFeedback:this.feedbackMemory,minibatch:i}))?.newInstruction?.trim();if(g&&g.length>16)return g}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(`
|
|
320
|
+
`)}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=g=>{for(;g.length>0;){let h=g.shift();if(!i.has(h))return h}},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,h=[a,c,d,m??""].join(":");if(n.has(h))continue;n.add(h);let f={type:a,section:c};a!=="REMOVE"&&(f.content=d),m&&(f.bulletId=m);let A=r.metadata;A&&typeof A=="object"&&(f.metadata={...A}),t.push(f)}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:sr(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:sr(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=ye(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=ye(e)}return this.curatorProgram}};var hn=class extends _e{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=cp([...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 g=t.filter(A=>A!==m);e.setExamples(g);let h=this.getTeacherOrStudentAI();this.stats.totalCalls++;let f;try{let A={...l,maxRetries:1};f=await e.forward(h,m,A),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(f).length/4),await r({prediction:f,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(A){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${A instanceof Error?A.message:"Unknown error"}`),f={}}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=lp(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 lp(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 cp=(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 Vl(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 st(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(Vl(s[i].scores,s[n].scores,e)){o=!0;break}Vl(s[n].scores,s[i].scores,e)&&r++}o||t.push({idx:s[n].idx,scores:s[n].scores,dominated:r})}return t}function je(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 Ft(s){if(s.length===0)return 0;let e=0;for(let t of s)e+=t;return e/s.length}function ko(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 ar(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 g of d)if(p.has(g)){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 lr(s,e,t){let n=ar(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 Mo=class extends _e{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(b,O)=>{try{e.setInstruction?.(b);let S=await e.forward(this.studentAI,O,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:S,example:O})||{}}catch{return{}}},d=async(b,O)=>{let S=[];for(let M of O)S.push(await u(b,M));return ko(S)},p=await this.getBaseInstruction(e),m=[{instruction:p,parent:void 0,scores:await d(p,l)}],g=b=>{let O=r?.paretoMetricKey,S=r?.paretoScalarize;if(typeof S=="function")return S(b);if(O)return Number.isFinite(b[O])?b[O]:0;let M=Object.values(b);return M.length?M.reduce((_,F)=>_+F,0)/M.length:0},h=[],f=async(b,O)=>{let S=[];for(let M of O){let _=await u(b,M);S.push(g(_))}return S};h.push(await f(p,l));let A=()=>{let b=h[0]?.length??0,O=[];for(let M=0;M<b;M++){let _=Number.NEGATIVE_INFINITY,F=new Set;for(let z=0;z<h.length;z++){let q=h[z][M];q>_+this.tieEpsilon?(_=q,F.clear(),F.add(z)):Math.abs(q-_)<=this.tieEpsilon&&F.add(z)}O.push(F)}let S=h.map(M=>Ft(M));return lr(O,S)};this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let y=0,I=st(m.map((b,O)=>({idx:O,scores:b.scores})),this.tieEpsilon).map(b=>b.idx),E,C=r?.maxMetricCalls;if(!Number.isFinite(C)||C<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let T=Math.floor(C);for(let b=0;b<this.numTrials&&!(T!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(T)));b++){let O=h[0]?.length??0,S=[];for(let D=0;D<O;D++){let U=Number.NEGATIVE_INFINITY,j=new Set;for(let H=0;H<h.length;H++){let J=h[H][D];J>U+this.tieEpsilon?(U=J,j.clear(),j.add(H)):Math.abs(J-U)<=this.tieEpsilon&&j.add(H)}S.push(j)}let M=h.map(D=>Ft(D));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let D=$=>{let N=[],G=$;for(;G!==void 0;)N.push(G),G=m[G]?.parent;return N},U=$=>$.length?$[Math.floor(this.rand()*$.length)]:void 0,j=ar(S,M),H=new Set;for(let $ of j)for(let N of $)H.add(N);let J=Array.from(H),oe;for(let $=0;$<10&&!oe&&!(J.length<2);$++){let N=U(J),G=U(J);if(N===G)continue;G<N&&([N,G]=[G,N]);let ne=new Set(D(N)),me=new Set(D(G));if(ne.has(G)||me.has(N))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,Ke)=>pe+Ke,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:N,j:G,a:X}}if(this.lastIterFoundNewProgram=!1,oe){let{i:$,j:N,a:G}=oe,ne=M[G],me=M[$],re=M[N],Y=m[G].instruction,Z=m[$].instruction,X=m[N].instruction,pe=Z===Y&&X!==Z||X===Y&&Z!==X,Ke=ne<=Math.min(me,re)&&pe,Ne="",$e="i",gt=!1;if(Ke){let it=`${$}|${N}|${G}`;if(this.mergeAttemptKeys.has(it))Ke=!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($,N)}|${Math.max($,N)}|${$e}`;if(this.mergeCompositionKeys.has(ce))Ke=!1;else{this.mergeAttemptKeys.add(it),this.mergeCompositionKeys.add(ce);let We=h[$],at=h[N],Le=Array.from({length:We.length},(se,Ce)=>Ce),ft=Le.filter(se=>(We[se]??0)>(at[se]??0)),Dt=Le.filter(se=>(at[se]??0)>(We[se]??0)),Ct=Le.filter(se=>!(ft.includes(se)||Dt.includes(se))),lt=5,ht=Math.ceil(lt/3),W=(se,Ce)=>{if(Ce<=0||se.length===0)return[];if(se.length<=Ce)return[...se];let Rn=[],mr=new Set;for(;Rn.length<Ce;){let Ve=Math.floor(this.rand()*se.length);mr.has(Ve)||(mr.add(Ve),Rn.push(se[Ve]))}return Rn},ae=[];ae.push(...W(ft,Math.min(ht,ft.length))),ae.push(...W(Dt,Math.min(ht,Dt.length)));let Rt=lt-ae.length;ae.push(...W(Ct,Math.max(0,Rt)));let wt=lt-ae.length;if(wt>0){let se=Le.filter(Ce=>!ae.includes(Ce));ae.push(...W(se,Math.min(wt,se.length)))}let Te=ae.slice(0,Math.min(lt,Le.length)),qo=Te.map(se=>l[se]);gt=!0;let pc=(await f(Ne,qo)).reduce((se,Ce)=>se+Ce,0),dc=Te.reduce((se,Ce)=>se+(We[Ce]??0),0),mc=Te.reduce((se,Ce)=>se+(at[Ce]??0),0);if(pc>=Math.max(dc,mc)+this.tieEpsilon){let se=await d(Ne,l);m.push({instruction:Ne,parent:G,scores:se}),h.push(await f(Ne,l));let Ce=I.length,Rn=je(I.map(Ve=>m[Ve].scores))??0;I=st(m.map((Ve,gc)=>({idx:gc,scores:Ve.scores})),this.tieEpsilon).map(Ve=>Ve.idx);let mr=je(I.map(Ve=>m[Ve].scores))??0;(I.length>Ce||mr>Rn+1e-6)&&(y=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(gt)continue}}let _=lr(S,M,()=>this.rand()),F=this.minibatch?this.nextMinibatchIndices(c.length,b).map(D=>c[D]):c;if(r?.skipPerfectScore??!0){let D=Number(r?.perfectScore??1),U=await f(m[_].instruction,F);if(U.length>0&&U.every(j=>j>=D))continue}let z=!1,q=m[_].instruction,Q="reflective_mutation",le,xe;if(z){let D=(_+1)%m.length;q=await this.mergeInstructions(m[_].instruction,m[D].instruction,r),Q="merge",this.mergesUsed+=1}else{let D=r?.gepaAdapter;if(D){try{let U={instruction:m[_].instruction},j=await D.evaluate(F,U,!0);le=Array.isArray(j?.scores)?j.scores.reduce(($,N)=>$+(Number(N)||0),0):void 0;let H=D.make_reflective_dataset(U,j,["instruction"]),J=await D.propose_new_texts?.(U,H,["instruction"]),oe=J?.instruction??(J?Object.values(J)[0]:void 0);typeof oe=="string"&&oe.length>0?q=oe:q=await this.reflectInstruction(m[_].instruction,e,F,async({prediction:$,example:N})=>{let G=await n({prediction:$,example:N}),ne=Object.values(G||{});return ne.length?ne.reduce((me,re)=>me+re,0)/ne.length:0},r)}catch{q=await this.reflectInstruction(m[_].instruction,e,F,async({prediction:U,example:j})=>{let H=await n({prediction:U,example:j}),J=Object.values(H||{});return J.length?J.reduce((oe,$)=>oe+$,0)/J.length:0},r)}if(le!==void 0)try{let U=await D.evaluate(F,{instruction:q},!1);xe=Array.isArray(U?.scores)?U.scores.reduce((j,H)=>j+(Number(H)||0),0):void 0}catch{}}else q=await this.reflectInstruction(m[_].instruction,e,F,async({prediction:U,example:j})=>{let H=await n({prediction:U,example:j}),J=Object.values(H||{});return J.length?J.reduce((oe,$)=>oe+$,0)/J.length:0},r)}let Fe=await f(m[_].instruction,F),He=await f(q,F),Se=Fe.reduce((D,U)=>D+U,0),ue=He.reduce((D,U)=>D+U,0);if(this.currentRound=b+1,await this.updateOptimizationProgress(this.currentRound,ue,{instructionLen:q.length,parent:_,totalRounds:this.numTrials},"GEPA",{strategy:Q,paretoSetSize:l.length},ue,{instructionLen:m[_].instruction.length,idx:_},{...r??{},maxIterations:this.numTrials}),!(ue>Se+this.tieEpsilon&&(le===void 0||xe===void 0||xe>le+this.tieEpsilon))){if(++y>=this.earlyStoppingTrials)break;continue}let De=await d(q,l);m.push({instruction:q,parent:_,scores:De}),h.push(await f(q,l));let Ge=I.length,dt=je(I.map(D=>m[D].scores))??0;I=st(m.map((D,U)=>({idx:U,scores:D.scores})),this.tieEpsilon).map(D=>D.idx);let mt=je(I.map(D=>m[D].scores))??0;if(I.length>Ge||mt>dt+1e-6)y=0;else if(y++,y>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let v=st(m.map((b,O)=>({idx:O,scores:b.scores})),this.tieEpsilon),k=v.length>0?Math.max(...v.map(b=>g(b.scores))):0,L;if(v.length>0){let b=Number.NEGATIVE_INFINITY;for(let O of v){let S=g(O.scores);S>b&&(b=S,L=O.idx)}}let P=je(v.map(b=>b.scores));this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(v.length,m.length,"GEPA",P);let R=Date.now()-o,w=typeof L=="number"?new ot({bestScore:k,stats:this.stats,instruction:m[L].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:R,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0;return this.generateOptimizationReport(v,P,k),{demos:[],stats:this.stats,bestScore:k,paretoFront:v.map(b=>({demos:[],scores:b.scores,configuration:{candidate:b.idx},dominatedSolutions:b.dominated})),paretoFrontSize:v.length,hypervolume:P,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:w}}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?Ft(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 g=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let h=await r({prediction:g,example:m});i.push({input:m,prediction:g,score:typeof h=="number"?h:0})}catch{i.push({input:m,prediction:{},score:0})}let a=o?.overrideTeacherAI??this.teacherAI??this.studentAI,l=ye('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 g=u({prediction:i[m].prediction,example:i[m].input});g&&(Array.isArray(g)?c.push(...g):c.push(g))}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=ye('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 g=(await p.forward(a,{currentInstruction:e,feedbackSummary:d,recentFeedback:this.feedbackMemory,minibatch:i}))?.newInstruction?.trim();if(g&&g.length>16)return g}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(`
|
|
321
321
|
\u{1F389} GEPA Multi-Objective Optimization Complete!
|
|
322
322
|
`),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
|
|
323
323
|
`),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
|
|
@@ -325,7 +325,7 @@ ${t}`.trim()}function sp(s){let e=s.toLowerCase().replace(/[^a-z0-9]+/g,"-").rep
|
|
|
325
325
|
`),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=ye(`instructionA:string "Parent A instruction",
|
|
326
326
|
instructionB:string "Parent B instruction",
|
|
327
327
|
recentFeedback?:string[] "Past feedback memory"
|
|
328
|
-
-> 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 Eo=class extends _e{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),p=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(T,C)=>{try{i.setAllNodeInstructions?.(T);let y=await i.forward(this.studentAI,C,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:y,example:C})||{}}catch{return{}}},g=async(T,C)=>{let y=[];for(let O of C)y.push(await m(T,O));return ko(y)},f={};for(let T of a)f[T.name]=await this.getBaseInstruction(T.program);let h=[{cfg:{...f},parent:void 0,scores:await g(f,u)}],A=T=>{let C=r?.paretoMetricKey,y=r?.paretoScalarize;if(typeof y=="function")return y(T);if(C)return Number.isFinite(T[C])?T[C]:0;let O=Object.values(T);return O.length?O.reduce((v,k)=>v+k,0)/O.length:0},x=[],b=async(T,C)=>{let y=[];for(let O of C){let v=await m(T,O);y.push(A(v))}return y};x.push(await b(f,u));let I=ot(h.map((T,C)=>({idx:C,scores:T.scores})),this.tieEpsilon).map(T=>T.idx),M=0,R=new Set,w=r?.maxMetricCalls;if(!Number.isFinite(w)||w<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let S=Math.floor(w);for(let T=0;T<this.numTrials&&!(S!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(S)));T++){let C=x[0]?.length??0,y=[];for(let D=0;D<C;D++){let U=Number.NEGATIVE_INFINITY,j=new Set;for(let H=0;H<x.length;H++){let J=x[H][D];J>U+this.tieEpsilon?(U=J,j.clear(),j.add(H)):Math.abs(J-U)<=this.tieEpsilon&&j.add(H)}y.push(j)}let O=x.map(D=>_t(D));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let D=ir(y,O),U=new Set;for(let $ of D)for(let N of $)U.add(N);let j=Array.from(U),H=$=>{let N=[],G=$;for(;G!==void 0;)N.push(G),G=h[G]?.parent;return N},J=$=>$.length?$[Math.floor(this.rand()*$.length)]:void 0,re;for(let $=0;$<10&&!re&&!(j.length<2);$++){let N=J(j),G=J(j);if(N===G)continue;G<N&&([N,G]=[G,N]);let te=new Set(H(N)),me=new Set(H(G));if(te.has(G)||me.has(N))continue;let ne=[...te].filter(le=>me.has(le));if(ne.length===0)continue;let Y=[];for(let le of ne){let Ke=h[le].cfg,it=h[N].cfg,Le=h[G].cfg,gt=!1,Ft=new Set([...Object.keys(Ke),...Object.keys(it),...Object.keys(Le)]);for(let Tt of Ft){let at=Ke[Tt],ht=it[Tt],W=Le[Tt];if(ht===at&&W!==ht||W===at&&ht!==W){gt=!0;break}}gt&&Y.push(le)}if(Y.length===0)continue;let Z=Y.map(le=>Math.max(1e-9,O[le])),X=this.rand()*Z.reduce((le,Ke)=>le+Ke,0),pe=Y[Y.length-1];for(let le=0;le<Y.length;le++){if(X<Z[le]){pe=Y[le];break}X-=Z[le]}let He=O[pe],Ne=O[N],$e=O[G];if(He>Math.min(Ne,$e))continue;let mt=`${N}|${G}|${pe}`;if(this.mergeAttemptKeys.has(mt))continue;this.mergeAttemptKeys.add(mt);let st=`${N}|${G}|${pe}`;R.has(st)||(re={i:N,j:G,a:pe})}if(this.lastIterFoundNewProgram=!1,re){let{i:$,j:N,a:G}=re,{cfg:te,descSig:me}=this.systemAwareMergeWithSig(h,$,N,(W,ie)=>O[W]>=O[ie]?W:ie),ne=`${Math.min($,N)}|${Math.max($,N)}|${me}`;if(this.mergeCompositionKeys.has(ne))continue;this.mergeCompositionKeys.add(ne);let Y=x[$],Z=x[N],X=Array.from({length:Y.length},(W,ie)=>ie),pe=X.filter(W=>(Y[W]??0)>(Z[W]??0)),He=X.filter(W=>(Z[W]??0)>(Y[W]??0)),Ne=X.filter(W=>!(pe.includes(W)||He.includes(W))),$e=5,mt=Math.ceil($e/3),st=(W,ie)=>{if(ie<=0||W.length===0)return[];if(W.length<=ie)return[...W];let Ct=[],Rt=new Set;for(;Ct.length<ie;){let Te=Math.floor(this.rand()*W.length);Rt.has(Te)||(Rt.add(Te),Ct.push(W[Te]))}return Ct},le=[];le.push(...st(pe,Math.min(mt,pe.length))),le.push(...st(He,Math.min(mt,He.length)));let Ke=$e-le.length;le.push(...st(Ne,Math.max(0,Ke)));let it=$e-le.length;if(it>0){let W=X.filter(ie=>!le.includes(ie));le.push(...st(W,Math.min(it,W.length)))}let Le=le.slice(0,Math.min($e,X.length)),gt=Le.map(W=>u[W]),Tt=(await b(te,gt)).reduce((W,ie)=>W+ie,0),at=Le.reduce((W,ie)=>W+(Y[ie]??0),0),ht=Le.reduce((W,ie)=>W+(Z[ie]??0),0);if(Tt>=Math.max(at,ht)+this.tieEpsilon){let W=await g(te,u);h.push({cfg:te,parent:G,scores:W}),x.push(await b(te,u));let ie=I.length,Ct=ze(I.map(Te=>h[Te].scores))??0;I=ot(h.map((Te,qo)=>({idx:qo,scores:Te.scores})),this.tieEpsilon).map(Te=>Te.idx);let Rt=ze(I.map(Te=>h[Te].scores))??0;(I.length>ie||Rt>Ct+1e-6)&&(M=0),this.mergesDue-=1,this.totalMergesTested+=1,R.add(`${Math.min($,N)}|${Math.max($,N)}|${G}`)}continue}}let v=ar(y,O,()=>this.rand());this.lastIterFoundNewProgram=!1;let k=this.minibatch?this.nextMinibatchIndices(p.length,T).map(D=>p[D]):p;if(r?.skipPerfectScore??!0){let D=Number(r?.perfectScore??1),U=await b(h[v].cfg,k);if(U.length>0&&U.every(j=>j>=D))continue}let _=!1,F={...h[v].cfg},z="reflective_mutation",q=T%a.length,Q=a[q],ae,xe;if(_&&this.mergesUsed<this.mergeMax){let D=(v+1)%h.length,U=$=>{let N=[],G=$;for(;G!==void 0;)N.push(G),G=h[G]?.parent;return N},j=U(v),H=U(D),J=j.find($=>H.includes($)),re=!0;if(J||(re=!1),(H.includes(v)||j.includes(D))&&(re=!1),re){let $=h[J].cfg,N=h[v].cfg,G=h[D].cfg,te=!1,me=new Set([...Object.keys($),...Object.keys(N),...Object.keys(G)]);for(let ne of me){let Y=$[ne],Z=N[ne],X=G[ne];if(Z===Y&&X!==Z||X===Y&&Z!==X){te=!0;break}}te||(re=!1)}if(re){let $=Math.min(v,D),N=Math.max(v,D),G=`${$}|${N}|${J}`;if(!R.has(G)){let te=A(h[J].scores),me=A(h[v].scores),ne=A(h[D].scores);te<=Math.min(me,ne)&&(F=this.systemAwareMerge(h,v,D,(Y,Z)=>{let X=A(h[Y].scores),pe=A(h[Z].scores);return X>=pe?Y:Z}),z="system_merge",this.mergesUsed+=1,R.add(G))}}else{let $=h[v].cfg[Q.name],N=r?.gepaAdapter,G;if(N)try{let te=await N.evaluate(k,{...h[v].cfg},!0);ae=Array.isArray(te?.scores)?te.scores.reduce((Z,X)=>Z+(Number(X)||0),0):void 0;let me=N.make_reflective_dataset({...h[v].cfg},te,[Q.name]),Y=(await N.propose_new_texts?.({...h[v].cfg},me,[Q.name]))?.[Q.name];typeof Y=="string"&&Y.length>0&&(G=Y)}catch{}if(G||(G=await this.reflectModuleInstruction(Q.name,$,i,a,{...h[v].cfg},k,async({prediction:te,example:me})=>{let ne=await n({prediction:te,example:me}),Y=Object.values(ne||{});return Y.length?Y.reduce((Z,X)=>Z+X,0)/Y.length:0},r)),F[Q.name]=G,N&&ae!==void 0)try{let te=await N.evaluate(k,F,!1);xe=Array.isArray(te?.scores)?te.scores.reduce((me,ne)=>me+(Number(ne)||0),0):void 0}catch{}}}else{let D=h[v].cfg[Q.name],U=r?.gepaAdapter,j;if(U)try{let H=await U.evaluate(k,{...h[v].cfg},!0);ae=Array.isArray(H?.scores)?H.scores.reduce((N,G)=>N+(Number(G)||0),0):void 0;let J=U.make_reflective_dataset({...h[v].cfg},H,[Q.name]),$=(await U.propose_new_texts?.({...h[v].cfg},J,[Q.name]))?.[Q.name];typeof $=="string"&&$.length>0&&(j=$)}catch{}if(j||(j=await this.reflectModuleInstruction(Q.name,D,i,a,{...h[v].cfg},k,async({prediction:H,example:J})=>{let re=await n({prediction:H,example:J}),$=Object.values(re||{});return $.length?$.reduce((N,G)=>N+G,0)/$.length:0},r)),F[Q.name]=j,U&&ae!==void 0)try{let H=await U.evaluate(k,F,!1);xe=Array.isArray(H?.scores)?H.scores.reduce((J,re)=>J+(Number(re)||0),0):void 0}catch{}}let Fe=await b(h[v].cfg,k),je=await b(F,k),Se=Fe.reduce((D,U)=>D+U,0),ue=je.reduce((D,U)=>D+U,0);if(this.currentRound=T+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:v},{...r??{},maxIterations:this.numTrials}),!(ue>Se+this.tieEpsilon&&(ae===void 0||xe===void 0||xe>ae+this.tieEpsilon))){if(++M>=this.earlyStoppingTrials)break;continue}let De=await g(F,u);h.push({cfg:F,parent:v,scores:De}),x.push(await b(F,u));let Ge=I.length,pt=ze(I.map(D=>h[D].scores))??0;I=ot(h.map((D,U)=>({idx:U,scores:D.scores})),this.tieEpsilon).map(D=>D.idx);let dt=ze(I.map(D=>h[D].scores))??0;if(I.length>Ge||dt>pt+1e-6)M=0;else if(M++,M>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let E=ot(h.map((T,C)=>({idx:C,scores:T.scores})),this.tieEpsilon),L=E.length>0?Math.max(...E.map(T=>A(T.scores))):0,P=ze(E.map(T=>T.scores));return this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(E.length,h.length,"GEPA-Flow",P),{demos:[],stats:this.stats,bestScore:L,paretoFront:E.map(T=>({demos:[],scores:T.scores,configuration:{candidate:T.idx},dominatedSolutions:T.dominated})),paretoFrontSize:E.length,hypervolume:P,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:h.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 A of i)try{o[e]=t,n.setAllNodeInstructions?.(o);let x=await n.forward(this.studentAI,A,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let b=await a({prediction:x,example:A});u.push({input:A,prediction:x,score:typeof b=="number"?b:0})}catch{u.push({input:A,prediction:{},score:0})}let p=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=ye('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],g=l?.feedbackFn;if(typeof g=="function")for(let A of u){let x=g({prediction:A.prediction,example:A.input});x&&(Array.isArray(x)?m.push(...x):m.push(x))}let f="";try{f=(await d.forward(p,{moduleName:e,minibatch:u,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let h=ye('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 h.forward(p,{moduleName:e,currentInstruction:t,feedbackSummary:f,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=h=>{let A=[],x=h;for(;x!==void 0;)A.push(x),x=e[x]?.parent;return A},i=o(t),a=o(n),c=i.find(h=>a.includes(h))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=[],f=Array.from(new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)])).sort();for(let h of f){let A=u[h],x=p[h],b=d[h];if(x===A&&b!==x)m[h]=b,g.push("j");else if(b===A&&x!==b)m[h]=x,g.push("i");else if(x!==b&&x!==A&&b!==A){let I=r(t,n);m[h]=I===t?x:b,g.push(I===t?"i":"j")}else m[h]=x??b??A,g.push("i")}return{cfg:m,descSig:g.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=f=>{let h=[],A=f;for(;A!==void 0;)h.push(A),A=e[A]?.parent;return h},i=o(t),a=o(n),c=i.find(f=>a.includes(f))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)]);for(let f of g){let h=u[f],A=p[f],x=d[f];if(A===h&&x!==A)m[f]=x;else if(x===h&&A!==x)m[f]=A;else if(A!==x&&A!==h&&x!==h){let b=r(t,n);m[f]=b===t?A:x}else m[f]=A??x??h}return m}};var Po=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 _o=class extends _e{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 Po(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=`
|
|
328
|
+
-> 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 Eo=class extends _e{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(R,w)=>{try{i.setAllNodeInstructions?.(R);let b=await i.forward(this.studentAI,w,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:b,example:w})||{}}catch{return{}}},g=async(R,w)=>{let b=[];for(let O of w)b.push(await m(R,O));return ko(b)},h={};for(let R of a)h[R.name]=await this.getBaseInstruction(R.program);let f=[{cfg:{...h},parent:void 0,scores:await g(h,u)}],A=R=>{let w=r?.paretoMetricKey,b=r?.paretoScalarize;if(typeof b=="function")return b(R);if(w)return Number.isFinite(R[w])?R[w]:0;let O=Object.values(R);return O.length?O.reduce((S,M)=>S+M,0)/O.length:0},x=[],y=async(R,w)=>{let b=[];for(let O of w){let S=await m(R,O);b.push(A(S))}return b};x.push(await y(h,u));let I=st(f.map((R,w)=>({idx:w,scores:R.scores})),this.tieEpsilon).map(R=>R.idx),E=0,C=new Set,T=r?.maxMetricCalls;if(!Number.isFinite(T)||T<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let v=Math.floor(T);for(let R=0;R<this.numTrials&&!(v!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(v)));R++){let w=x[0]?.length??0,b=[];for(let D=0;D<w;D++){let U=Number.NEGATIVE_INFINITY,j=new Set;for(let H=0;H<x.length;H++){let J=x[H][D];J>U+this.tieEpsilon?(U=J,j.clear(),j.add(H)):Math.abs(J-U)<=this.tieEpsilon&&j.add(H)}b.push(j)}let O=x.map(D=>Ft(D));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let D=ar(b,O),U=new Set;for(let $ of D)for(let N of $)U.add(N);let j=Array.from(U),H=$=>{let N=[],G=$;for(;G!==void 0;)N.push(G),G=f[G]?.parent;return N},J=$=>$.length?$[Math.floor(this.rand()*$.length)]:void 0,oe;for(let $=0;$<10&&!oe&&!(j.length<2);$++){let N=J(j),G=J(j);if(N===G)continue;G<N&&([N,G]=[G,N]);let ne=new Set(H(N)),me=new Set(H(G));if(ne.has(G)||me.has(N))continue;let re=[...ne].filter(ce=>me.has(ce));if(re.length===0)continue;let Y=[];for(let ce of re){let We=f[ce].cfg,at=f[N].cfg,Le=f[G].cfg,ft=!1,Dt=new Set([...Object.keys(We),...Object.keys(at),...Object.keys(Le)]);for(let Ct of Dt){let lt=We[Ct],ht=at[Ct],W=Le[Ct];if(ht===lt&&W!==ht||W===lt&&ht!==W){ft=!0;break}}ft&&Y.push(ce)}if(Y.length===0)continue;let Z=Y.map(ce=>Math.max(1e-9,O[ce])),X=this.rand()*Z.reduce((ce,We)=>ce+We,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 Ke=O[pe],Ne=O[N],$e=O[G];if(Ke>Math.min(Ne,$e))continue;let gt=`${N}|${G}|${pe}`;if(this.mergeAttemptKeys.has(gt))continue;this.mergeAttemptKeys.add(gt);let it=`${N}|${G}|${pe}`;C.has(it)||(oe={i:N,j:G,a:pe})}if(this.lastIterFoundNewProgram=!1,oe){let{i:$,j:N,a:G}=oe,{cfg:ne,descSig:me}=this.systemAwareMergeWithSig(f,$,N,(W,ae)=>O[W]>=O[ae]?W:ae),re=`${Math.min($,N)}|${Math.max($,N)}|${me}`;if(this.mergeCompositionKeys.has(re))continue;this.mergeCompositionKeys.add(re);let Y=x[$],Z=x[N],X=Array.from({length:Y.length},(W,ae)=>ae),pe=X.filter(W=>(Y[W]??0)>(Z[W]??0)),Ke=X.filter(W=>(Z[W]??0)>(Y[W]??0)),Ne=X.filter(W=>!(pe.includes(W)||Ke.includes(W))),$e=5,gt=Math.ceil($e/3),it=(W,ae)=>{if(ae<=0||W.length===0)return[];if(W.length<=ae)return[...W];let Rt=[],wt=new Set;for(;Rt.length<ae;){let Te=Math.floor(this.rand()*W.length);wt.has(Te)||(wt.add(Te),Rt.push(W[Te]))}return Rt},ce=[];ce.push(...it(pe,Math.min(gt,pe.length))),ce.push(...it(Ke,Math.min(gt,Ke.length)));let We=$e-ce.length;ce.push(...it(Ne,Math.max(0,We)));let at=$e-ce.length;if(at>0){let W=X.filter(ae=>!ce.includes(ae));ce.push(...it(W,Math.min(at,W.length)))}let Le=ce.slice(0,Math.min($e,X.length)),ft=Le.map(W=>u[W]),Ct=(await y(ne,ft)).reduce((W,ae)=>W+ae,0),lt=Le.reduce((W,ae)=>W+(Y[ae]??0),0),ht=Le.reduce((W,ae)=>W+(Z[ae]??0),0);if(Ct>=Math.max(lt,ht)+this.tieEpsilon){let W=await g(ne,u);f.push({cfg:ne,parent:G,scores:W}),x.push(await y(ne,u));let ae=I.length,Rt=je(I.map(Te=>f[Te].scores))??0;I=st(f.map((Te,qo)=>({idx:qo,scores:Te.scores})),this.tieEpsilon).map(Te=>Te.idx);let wt=je(I.map(Te=>f[Te].scores))??0;(I.length>ae||wt>Rt+1e-6)&&(E=0),this.mergesDue-=1,this.totalMergesTested+=1,C.add(`${Math.min($,N)}|${Math.max($,N)}|${G}`)}continue}}let S=lr(b,O,()=>this.rand());this.lastIterFoundNewProgram=!1;let M=this.minibatch?this.nextMinibatchIndices(d.length,R).map(D=>d[D]):d;if(r?.skipPerfectScore??!0){let D=Number(r?.perfectScore??1),U=await y(f[S].cfg,M);if(U.length>0&&U.every(j=>j>=D))continue}let _=!1,F={...f[S].cfg},z="reflective_mutation",q=R%a.length,Q=a[q],le,xe;if(_&&this.mergesUsed<this.mergeMax){let D=(S+1)%f.length,U=$=>{let N=[],G=$;for(;G!==void 0;)N.push(G),G=f[G]?.parent;return N},j=U(S),H=U(D),J=j.find($=>H.includes($)),oe=!0;if(J||(oe=!1),(H.includes(S)||j.includes(D))&&(oe=!1),oe){let $=f[J].cfg,N=f[S].cfg,G=f[D].cfg,ne=!1,me=new Set([...Object.keys($),...Object.keys(N),...Object.keys(G)]);for(let re of me){let Y=$[re],Z=N[re],X=G[re];if(Z===Y&&X!==Z||X===Y&&Z!==X){ne=!0;break}}ne||(oe=!1)}if(oe){let $=Math.min(S,D),N=Math.max(S,D),G=`${$}|${N}|${J}`;if(!C.has(G)){let ne=A(f[J].scores),me=A(f[S].scores),re=A(f[D].scores);ne<=Math.min(me,re)&&(F=this.systemAwareMerge(f,S,D,(Y,Z)=>{let X=A(f[Y].scores),pe=A(f[Z].scores);return X>=pe?Y:Z}),z="system_merge",this.mergesUsed+=1,C.add(G))}}else{let $=f[S].cfg[Q.name],N=r?.gepaAdapter,G;if(N)try{let ne=await N.evaluate(M,{...f[S].cfg},!0);le=Array.isArray(ne?.scores)?ne.scores.reduce((Z,X)=>Z+(Number(X)||0),0):void 0;let me=N.make_reflective_dataset({...f[S].cfg},ne,[Q.name]),Y=(await N.propose_new_texts?.({...f[S].cfg},me,[Q.name]))?.[Q.name];typeof Y=="string"&&Y.length>0&&(G=Y)}catch{}if(G||(G=await this.reflectModuleInstruction(Q.name,$,i,a,{...f[S].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)),F[Q.name]=G,N&&le!==void 0)try{let ne=await N.evaluate(M,F,!1);xe=Array.isArray(ne?.scores)?ne.scores.reduce((me,re)=>me+(Number(re)||0),0):void 0}catch{}}}else{let D=f[S].cfg[Q.name],U=r?.gepaAdapter,j;if(U)try{let H=await U.evaluate(M,{...f[S].cfg},!0);le=Array.isArray(H?.scores)?H.scores.reduce((N,G)=>N+(Number(G)||0),0):void 0;let J=U.make_reflective_dataset({...f[S].cfg},H,[Q.name]),$=(await U.propose_new_texts?.({...f[S].cfg},J,[Q.name]))?.[Q.name];typeof $=="string"&&$.length>0&&(j=$)}catch{}if(j||(j=await this.reflectModuleInstruction(Q.name,D,i,a,{...f[S].cfg},M,async({prediction:H,example:J})=>{let oe=await n({prediction:H,example:J}),$=Object.values(oe||{});return $.length?$.reduce((N,G)=>N+G,0)/$.length:0},r)),F[Q.name]=j,U&&le!==void 0)try{let H=await U.evaluate(M,F,!1);xe=Array.isArray(H?.scores)?H.scores.reduce((J,oe)=>J+(Number(oe)||0),0):void 0}catch{}}let Fe=await y(f[S].cfg,M),He=await y(F,M),Se=Fe.reduce((D,U)=>D+U,0),ue=He.reduce((D,U)=>D+U,0);if(this.currentRound=R+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:S},{...r??{},maxIterations:this.numTrials}),!(ue>Se+this.tieEpsilon&&(le===void 0||xe===void 0||xe>le+this.tieEpsilon))){if(++E>=this.earlyStoppingTrials)break;continue}let De=await g(F,u);f.push({cfg:F,parent:S,scores:De}),x.push(await y(F,u));let Ge=I.length,dt=je(I.map(D=>f[D].scores))??0;I=st(f.map((D,U)=>({idx:U,scores:D.scores})),this.tieEpsilon).map(D=>D.idx);let mt=je(I.map(D=>f[D].scores))??0;if(I.length>Ge||mt>dt+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 k=st(f.map((R,w)=>({idx:w,scores:R.scores})),this.tieEpsilon),L=k.length>0?Math.max(...k.map(R=>A(R.scores))):0,P=je(k.map(R=>R.scores));return this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(k.length,f.length,"GEPA-Flow",P),{demos:[],stats:this.stats,bestScore:L,paretoFront:k.map(R=>({demos:[],scores:R.scores,configuration:{candidate:R.idx},dominatedSolutions:R.dominated})),paretoFrontSize:k.length,hypervolume:P,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:f.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?Ft(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 A of i)try{o[e]=t,n.setAllNodeInstructions?.(o);let x=await n.forward(this.studentAI,A,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let y=await a({prediction:x,example:A});u.push({input:A,prediction:x,score:typeof y=="number"?y:0})}catch{u.push({input:A,prediction:{},score:0})}let d=l?.overrideTeacherAI??this.teacherAI??this.studentAI,p=ye('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],g=l?.feedbackFn;if(typeof g=="function")for(let A of u){let x=g({prediction:A.prediction,example:A.input});x&&(Array.isArray(x)?m.push(...x):m.push(x))}let h="";try{h=(await p.forward(d,{moduleName:e,minibatch:u,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let f=ye('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 f.forward(d,{moduleName:e,currentInstruction:t,feedbackSummary:h,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=f=>{let A=[],x=f;for(;x!==void 0;)A.push(x),x=e[x]?.parent;return A},i=o(t),a=o(n),c=i.find(f=>a.includes(f))??t,u=e[c].cfg,d=e[t].cfg,p=e[n].cfg,m={},g=[],h=Array.from(new Set([...Object.keys(u),...Object.keys(d),...Object.keys(p)])).sort();for(let f of h){let A=u[f],x=d[f],y=p[f];if(x===A&&y!==x)m[f]=y,g.push("j");else if(y===A&&x!==y)m[f]=x,g.push("i");else if(x!==y&&x!==A&&y!==A){let I=r(t,n);m[f]=I===t?x:y,g.push(I===t?"i":"j")}else m[f]=x??y??A,g.push("i")}return{cfg:m,descSig:g.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=h=>{let f=[],A=h;for(;A!==void 0;)f.push(A),A=e[A]?.parent;return f},i=o(t),a=o(n),c=i.find(h=>a.includes(h))??t,u=e[c].cfg,d=e[t].cfg,p=e[n].cfg,m={},g=new Set([...Object.keys(u),...Object.keys(d),...Object.keys(p)]);for(let h of g){let f=u[h],A=d[h],x=p[h];if(A===f&&x!==A)m[h]=x;else if(x===f&&A!==x)m[h]=A;else if(A!==x&&A!==f&&x!==f){let y=r(t,n);m[h]=y===t?A:x}else m[h]=A??x??f}return m}};var Po=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 _o=class extends _e{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 Po(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=`
|
|
329
329
|
Analyze this language model program and provide a concise summary of its purpose and structure.
|
|
330
330
|
|
|
331
331
|
Program Signature: ${e.getSignature()}
|
|
@@ -365,12 +365,12 @@ Requirements:
|
|
|
365
365
|
5. Keep it concise but comprehensive
|
|
366
366
|
|
|
367
367
|
Generate a single, well-crafted instruction:
|
|
368
|
-
Instruction:`;try{let m=(await ye('programSummary?:string "Program context" , datasetSummary?:string "Dataset context" , tip?:string "Generation tip" -> instructionText:string "Well-crafted instruction for the program"').forward(n,{programSummary:r??"",datasetSummary:o??"",tip:e??""})).instructionText;if(m&&m.trim().length>10)return m.trim()}catch{}let c=["Analyze the input systematically and provide a precise, well-reasoned response.","Think through this step-by-step, considering all relevant factors before responding.","Examine the input carefully and generate an accurate, detailed answer.","Process the information methodically and deliver a clear, comprehensive response.","Consider the context thoroughly and provide a thoughtful, accurate answer."],u=c[t%c.length]||c[0];return e&&(u=`${u} ${e}`),u}async proposeInstructionCandidates(e,t,n=[]){let r=[],o=this.getTeacherOrStudentAI(t),i,a;this.programAwareProposer&&(i=await this.generateProgramSummary(e,o)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],o));let l=this.tipAwareProposer?this.generateTips():[];for(let c=0;c<this.numCandidates;c++){let u=l.length>0?c%l.length:-1,
|
|
368
|
+
Instruction:`;try{let m=(await ye('programSummary?:string "Program context" , datasetSummary?:string "Dataset context" , tip?:string "Generation tip" -> instructionText:string "Well-crafted instruction for the program"').forward(n,{programSummary:r??"",datasetSummary:o??"",tip:e??""})).instructionText;if(m&&m.trim().length>10)return m.trim()}catch{}let c=["Analyze the input systematically and provide a precise, well-reasoned response.","Think through this step-by-step, considering all relevant factors before responding.","Examine the input carefully and generate an accurate, detailed answer.","Process the information methodically and deliver a clear, comprehensive response.","Consider the context thoroughly and provide a thoughtful, accurate answer."],u=c[t%c.length]||c[0];return e&&(u=`${u} ${e}`),u}async proposeInstructionCandidates(e,t,n=[]){let r=[],o=this.getTeacherOrStudentAI(t),i,a;this.programAwareProposer&&(i=await this.generateProgramSummary(e,o)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],o));let l=this.tipAwareProposer?this.generateTips():[];for(let c=0;c<this.numCandidates;c++){let u=l.length>0?c%l.length:-1,d=u>=0?l[u]:void 0,p=await this.generateInstruction({tip:d,candidateIndex:c,ai:o,programSummary:i,datasetSummary:a,previousInstructions:r});r.push(p)}return r}async bootstrapFewShotExamples(e,t,n){return(await new hn({studentAI:this.studentAI,options:{maxDemos:this.maxBootstrappedDemos,maxRounds:3,verboseMode:this.verbose??!1}}).compile(e,n,t,{maxDemos:this.maxBootstrappedDemos})).demos||[]}selectLabeledExamples(e){let t=[],n=new Set;for(;n.size<this.maxLabeledDemos&&n.size<e.length;){let r=Math.floor(Math.random()*e.length);if(!n.has(r)){n.add(r);let o=e[r];o&&t.push(o)}}return t}applyConfigToProgram(e,t,n,r){e.setInstruction&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples&&e.setExamples(r.slice(0,t.labeledExamples))}async compile(e,t,n,r){let o=Date.now();if(this.validateExamples(t),this.setupRandomSeed(),r?.auto&&this.configureAuto(r.auto),!this.pythonClient)throw new Error("AxMiPRO v2 requires the Python optimizer service. Please configure optimizerEndpoint.");if(!await this.pythonClient.healthCheck())throw new Error("Python optimizer service is not available or unhealthy");return await this.compilePython(e,t,n,r)}applyConfigToAxGen(e,t,n,r){"setInstruction"in e&&typeof e.setInstruction=="function"&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples(r.slice(0,t.labeledExamples))}getConfiguration(){return{numCandidates:this.numCandidates,initTemperature:this.initTemperature,maxBootstrappedDemos:this.maxBootstrappedDemos,maxLabeledDemos:this.maxLabeledDemos,numTrials:this.numTrials,minibatch:this.minibatch,minibatchSize:this.minibatchSize,minibatchFullEvalSteps:this.minibatchFullEvalSteps,programAwareProposer:this.programAwareProposer,dataAwareProposer:this.dataAwareProposer,tipAwareProposer:this.tipAwareProposer,fewshotAwareProposer:this.fewshotAwareProposer,earlyStoppingTrials:this.earlyStoppingTrials,minImprovementThreshold:this.minImprovementThreshold,bayesianOptimization:this.bayesianOptimization,acquisitionFunction:this.acquisitionFunction,explorationWeight:this.explorationWeight,sampleCount:this.sampleCount}}updateConfiguration(e){e.numCandidates!==void 0&&(this.numCandidates=e.numCandidates),e.initTemperature!==void 0&&(this.initTemperature=e.initTemperature),e.maxBootstrappedDemos!==void 0&&(this.maxBootstrappedDemos=e.maxBootstrappedDemos),e.maxLabeledDemos!==void 0&&(this.maxLabeledDemos=e.maxLabeledDemos),e.numTrials!==void 0&&(this.numTrials=e.numTrials),e.minibatch!==void 0&&(this.minibatch=e.minibatch),e.minibatchSize!==void 0&&(this.minibatchSize=e.minibatchSize),e.earlyStoppingTrials!==void 0&&(this.earlyStoppingTrials=e.earlyStoppingTrials),e.minImprovementThreshold!==void 0&&(this.minImprovementThreshold=e.minImprovementThreshold),e.sampleCount!==void 0&&(this.sampleCount=e.sampleCount)}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}validateProgram(e){let t=[],n=[];return{isValid:t.length===0,issues:t,suggestions:n}}async compilePython(e,t,n,r){if(!this.pythonClient)throw new Error("Python client not initialized");let o=Date.now();this.localScoreHistory=[],this.localConfigurationHistory=[];let i=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a={study_name:i,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos},...this.optimizeTopP?[{name:"topP",type:"float",low:.7,high:1}]:[]],objective:{name:"score",direction:"maximize"},n_trials:this.numTrials,sampler:"TPESampler",pruner:this.minibatch?"MedianPruner":void 0},l=await this.pythonClient.createOptimizationJob(a);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:l.job_id,numTrials:this.numTrials}}});let u=Number.NEGATIVE_INFINITY,d,p=0,m=0;for(let I=0;I<this.numTrials;I++)try{let E=await this.pythonClient.suggestParameters(i),C=E.params.temperature,T=E.params.bootstrappedDemos,v=this.optimizeTopP?E.params.topP:void 0;if(C===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(E)}`);if(T===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(E)}`);let L=!this.minibatch||this.minibatchFullEvalSteps>0&&I%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let w=Math.min(this.minibatchSize,t.length),b=new Set;for(;b.size<w;)b.add(Math.floor(Math.random()*t.length));return Array.from(b).map(O=>t[O])})(),P=await this.evaluateConfiguration(e,n,{temperature:C,bootstrappedDemos:T,topP:v},L);p++,await this.pythonClient.evaluateTrial({study_name:i,trial_number:E.trial_number,value:P}),P>u+this.minImprovementThreshold?(u=P,d={temperature:C,bootstrappedDemos:T,...v!==void 0?{topP:v}:{},trialNumber:E.trial_number},m=0):m+=1,this.currentRound=I+1;let R={temperature:C,bootstrappedDemos:T,...v!==void 0?{topP:v}:{},trialNumber:E.trial_number};if(this.localScoreHistory.push(P),this.localConfigurationHistory.push(R),await this.updateOptimizationProgress(this.currentRound,P,R,"MiPRO (Python)",{sampler:"TPESampler"},u,d),this.onProgress?.({round:I+1,totalRounds:this.numTrials,currentScore:P,bestScore:u,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-o,successfulExamples:p,totalExamples:t.length}),this.earlyStoppingTrials>0&&m>=this.earlyStoppingTrials){this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:`No improvement \u2265 ${this.minImprovementThreshold} for ${this.earlyStoppingTrials} trials`,finalScore:u,round:this.currentRound}}),this.onEarlyStop?.(`No improvement for ${this.earlyStoppingTrials} trials`,this.stats);break}}catch{}let g=u,h={},f=[];try{let I=await this.pythonClient.getStudyResults(i);if(g=I.best_value||u,h=I.best_params||{},h&&Object.keys(h).length>0){let E=h.bootstrappedDemos||0;E>0&&(f=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),f=f.slice(0,E))}}catch{}let A;try{let E=await ye('optimizerType:string "Optimizer name" , bestScore:number "Final best score" , totalCalls:number "Total eval calls" , successfulDemos:number "Successful evals" , bestConfig:json "Best configuration" -> humanExplanation:string "Readable summary", recommendations:string[] "Next steps", performanceAssessment:string "Performance notes"').forward(this.studentAI,{optimizerType:"MiPRO (Python)",bestScore:g,totalCalls:this.stats.totalCalls,successfulDemos:this.stats.successfulDemos,bestConfig:h||{}});A={humanExplanation:E.humanExplanation??"",recommendations:E.recommendations??[],performanceAssessment:E.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",g,h,r,A);try{await this.pythonClient.deleteStudy(i)}catch{}this.stats.bestScore=g;let x=new Pe(e.getSignature());f.length>0&&x.setDemos(f),h.temperature&&(x._optimizedModelConfig={temperature:h.temperature});let y=new ot({bestScore:g,stats:this.stats,instruction:void 0,demos:f,examples:[],modelConfig:{temperature:h.temperature},optimizerType:"MiPRO (Python)",optimizationTime:Date.now()-o,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged,scoreHistory:[...this.localScoreHistory],configurationHistory:[...this.localConfigurationHistory]});return this.generateOptimizationReport(g,f.length),{bestScore:g,demos:f,stats:this.stats,optimizedGen:x,optimizedProgram:y,finalConfiguration:{temperature:h.temperature,bootstrappedDemos:h.bootstrappedDemos||0,...h}}}generateOptimizationReport(e,t){console.log(`
|
|
369
369
|
\u{1F389} MiPRO Optimization Complete!
|
|
370
370
|
`),console.log("\u2705 Improvements:"),e!==void 0&&e>0&&console.log(`\u2022 Best score achieved: ${e.toFixed(3)}`),t>0&&console.log(`\u2022 Generated ${t} optimized demonstrations`),console.log("\u2022 Systematic prompt and example optimization"),console.log(`\u2022 Automated instruction refinement process
|
|
371
371
|
`),console.log("\u26A0\uFE0F Limitations:"),this.stats.totalCalls<50&&console.log("\u2022 Relatively few optimization trials performed"),t<5&&console.log("\u2022 Limited number of demonstrations generated"),console.log("\u2022 Results depend on teacher model quality"),console.log(`\u2022 Optimization time increases with example complexity
|
|
372
372
|
`),console.log("\u{1F50D} Key Issues:"),e!==void 0&&e<.7&&console.log("\u2022 Final performance may still have room for improvement"),this.stats.convergenceInfo?.converged===!1&&console.log("\u2022 Optimization may not have fully converged"),console.log("\u2022 Evaluation metrics may need domain-specific tuning"),console.log(`\u2022 Bootstrap quality depends on initial examples
|
|
373
|
-
`),console.log("\u{1F4A1} What This Means:"),console.log("\u2022 MiPRO successfully automated prompt engineering"),console.log("\u2022 Optimized instructions and examples improve model performance"),console.log("\u2022 Framework reduces manual prompt engineering effort"),console.log("\u2022 More training data and iterations would likely improve results")}async evaluateConfiguration(e,t,n,r){let o=0,i=0,a=0,l=r,c=[];if(n.bootstrappedDemos>0)try{c=(await this.bootstrapFewShotExamples(e,t,l)).slice(0,n.bootstrappedDemos)}catch{c=[]}for(let u of l)try{c.length>0&&e.setDemos?.(c);let
|
|
373
|
+
`),console.log("\u{1F4A1} What This Means:"),console.log("\u2022 MiPRO successfully automated prompt engineering"),console.log("\u2022 Optimized instructions and examples improve model performance"),console.log("\u2022 Framework reduces manual prompt engineering effort"),console.log("\u2022 More training data and iterations would likely improve results")}async evaluateConfiguration(e,t,n,r){let o=0,i=0,a=0,l=r,c=[];if(n.bootstrappedDemos>0)try{c=(await this.bootstrapFewShotExamples(e,t,l)).slice(0,n.bootstrappedDemos)}catch{c=[]}for(let u of l)try{c.length>0&&e.setDemos?.(c);let d=await e.forward(this.studentAI,u,{modelConfig:{temperature:n.temperature,...n.topP!==void 0?{topP:n.topP}:{}},sampleCount:this.sampleCount,resultPicker:this.sampleCount>1?this.customResultPicker??this.defaultResultPicker:void 0});this.stats.totalCalls+=1;let p=await t({prediction:d,example:u});if(typeof p=="number"&&!Number.isNaN(p)){o+=p,i++;let m=typeof this.targetScore=="number"?this.targetScore:.5;p>=m&&a++}}catch(d){this.getLogger()?.({name:"Notification",id:"mipro_evaluate",value:typeof d=="string"?d:String(d)})}return this.stats.successfulDemos+=a,i>0?o/i:0}};var An=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let r=e.toString(),o=Array.from(r.matchAll(/state\.(\w+)/g));for(let i of o)i[1]&&!n.includes(i[1])&&n.push(i[1]);if(n.length===0)try{let i=this.createDependencyTracker(n);e(i)}catch{}}catch(r){console.debug("Dependency analysis failed:",r)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(r,o){typeof o=="string"&&!t.includes(o)&&t.push(o);let i=r[o];return i&&typeof i=="object"?n.createTrackingProxy(i,t):i},has(r,o){return typeof o=="string"&&!t.includes(o)&&t.push(o),o in r}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let i of n)i[1]&&!t.includes(i[1])&&t.push(i[1]);let r=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let i of r)i[1]&&!t.includes(i[1])&&t.push(i[1]);let o=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let i of o)for(let a=1;a<i.length;a++)i[a]&&!t.includes(i[a])&&t.push(i[a])}catch(n){console.debug("Static dependency parsing failed:",n)}return t}createDependencyTracker(e){return new Proxy({},{get(t,n){return typeof n=="string"&&!e.includes(n)&&e.push(n),new Proxy({},{get:()=>{}})}})}};async function xn(s,e,t){if(!t||t<=0||t>=s.length){let r=s.map((o,i)=>e(o,i));return Promise.all(r)}let n=new Array(s.length);for(let r=0;r<s.length;r+=t){let i=s.slice(r,r+t).map((l,c)=>{let u=r+c;return e(l,u).then(d=>({result:d,originalIndex:u}))}),a=await Promise.all(i);for(let{result:l,originalIndex:c}of a)n[c]=l}return n}var yn=class{steps=[];parallelGroups=[];analyzer=new An;initialFields=new Set;addExecutionStep(e,t,n,r,o,i,a){let l=[],c=[],u=r||"map";if(t&&n)u="execute",l=this.analyzer.analyzeMappingDependencies(n,t),c=[`${t}Result`];else if(u==="map"&&o)c=this.analyzeMapTransformation(o),l=this.getAllProducedFields();else if(u==="parallel-map"){if(Array.isArray(o)){let p=new Set;for(let m of o)this.analyzeMapTransformation(m).forEach(h=>p.add(h));c=Array.from(p)}else o?c=this.analyzeMapTransformation(o):c=["_parallelMapResult"];l=this.getAllProducedFields()}else if(u==="merge"){if(i?.resultKey)c=[i.resultKey];else{let m=this.analyzeBranchMergeFields();c=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?l=["_parallelResults"]:l=this.getAllProducedFields()}else if(u==="parallel")c=["_parallelResults"],l=this.getAllProducedFields();else if(u==="derive")if(a?.outputFieldName&&a?.inputFieldName){c=[a.outputFieldName];let p=o?this.analyzer.analyzeMappingDependencies(o,"derive"):[];l=[a.inputFieldName,...p].filter((m,g,h)=>h.indexOf(m)===g)}else c=["_deriveResult"],l=this.getAllProducedFields();else e.toString().includes("transform(")?(u="map",l=this.getAllProducedFields(),c=["_mapResult"]):e.toString().includes("_parallelResults")&&(c=["_parallelResults"],l=this.getAllProducedFields());for(let p of l)this.getAllProducedFields().includes(p)||this.initialFields.add(p);let d={type:u,nodeName:t,dependencies:l,produces:c,stepFunction:e,stepIndex:this.steps.length};this.steps.push(d)}analyzeStepFunctionProduction(e){try{let t=this.analyzeStepFunctionSource(e);if(t.length>0&&!t.includes("_stepResult"))return t}catch(t){console.debug("Step function source analysis failed:",t)}try{let t=this.createMockState(),n=Object.keys(t),o=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(o&&typeof o=="object"&&"then"in o)return this.analyzeStepFunctionSource(e);if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Object.keys(o).filter(l=>!n.includes(l));if(a.length>0)return a}}catch(t){console.debug("Step function dynamic analysis failed:",t)}return this.analyzeStepFunctionSource(e)}analyzeStepFunctionSource(e){try{let t=e.toString(),n=t.match(/\{\s*\.\.\.state\s*,\s*(\w+)\s*:/g);if(n){let o=n.map(i=>{let a=i.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}let r=t.match(/state\.(\w+)\s*=/g);if(r){let o=r.map(i=>{let a=i.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}}catch(t){console.debug("Step function source analysis failed:",t)}return["_stepResult"]}analyzeMapTransformation(e){try{let n=e.toString().split(/\{[\s\S]*?\}/).flatMap(()=>[])}catch{}return["_mapResult"]}createMockState(){let e={};for(let t of this.initialFields)e[t]=this.createMockValue(t);for(let t of this.steps)for(let n of t.produces)n.endsWith("Result")?e[n]={text:"mockText",value:"mockValue",result:"mockResult",data:"mockData",processedText:"mockProcessedText",sentimentValue:"mockSentiment",confidenceScore:.8,isComplex:!1,mockValue:"mockValue",responseText:"mockResponseText",inputText:"mockInputText"}:e[n]=this.createMockValue(n);return e}createMockValue(e){return e.includes("List")||e.includes("Array")||e.endsWith("s")?["mockItem1","mockItem2"]:e.includes("count")||e.includes("Count")||e.includes("index")||e.includes("Index")?0:e.includes("is")||e.includes("has")||e.includes("can")?!1:"mockValue"}analyzeBranchMergeFields(){let e=this.steps.slice(-5).filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces);return e.length>0?e:this.steps.filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces)}setInitialFields(e){this.initialFields=new Set(e),this.rebuildParallelGroups()}rebuildParallelGroups(){this.parallelGroups=[];let e=new Set,t=new Set(this.initialFields),n=0;for(;e.size<this.steps.length;){let r=[];for(let o of this.steps){if(e.has(o.stepIndex))continue;if(o.dependencies.length===0||o.dependencies.every(a=>t.has(a))){if(o.type==="merge"&&r.length>0)continue;if(r.push(o),e.add(o.stepIndex),o.type==="merge")break}}if(r.length>0){for(let o of r)o.produces.forEach(i=>t.add(i));this.parallelGroups.push({level:n,steps:r}),n++}else{let o=this.steps.filter(i=>!e.has(i.stepIndex));if(o.length>0){let i=o[0];e.add(i.stepIndex),i.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[i]}),n++}else break}}}getAllProducedFields(){let e=[];for(let t of this.steps)e.push(...t.produces);return e}createOptimizedExecution(e){let t=[];for(let n of this.parallelGroups)if(n.steps.length===1){let r=n.steps[0];r&&t.push(r.stepFunction)}else if(n.steps.length>1){let r=async(o,i)=>{let a=await xn(n.steps,async u=>await u.stepFunction(o,i),e);if(a.some(u=>u&&typeof u=="object"&&"_parallelResults"in u)){let u=a.find(d=>d&&typeof d=="object"&&"_parallelResults"in d);return u||o}let c=o;for(let u of a)c={...c,...u};return c};t.push(r)}return t}getOptimizedExecutionSteps(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),this.createOptimizedExecution()}getExecutionPlan(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),{totalSteps:this.steps.length,parallelGroups:this.parallelGroups.length,maxParallelism:this.steps.length===0?1:Math.max(...this.parallelGroups.map(e=>e.steps.length),0),steps:this.steps,groups:this.parallelGroups}}};var Jl=s=>{console.log(s)},bn=(s,e=!1)=>{if(e)return"[State hidden]";let t={};for(let[n,r]of Object.entries(s))if(typeof r=="string"&&r.length>100)t[n]=`${r.substring(0,100)}...`;else if(Array.isArray(r)&&r.length>3)t[n]=[...r.slice(0,3),`... (${r.length-3} more)`];else if(typeof r=="object"&&r!==null){let o=JSON.stringify(r);o.length>200?t[n]=`${o.substring(0,200)}...`:t[n]=r}else t[n]=r;return JSON.stringify(t,null,2)},In=s=>s<1e3?`${s.toFixed(1)}ms`:s<6e4?`${(s/1e3).toFixed(2)}s`:`${(s/6e4).toFixed(2)}min`,cr=(s=Jl)=>{let e=new ve,t=e.gray(`${"\u2501".repeat(80)}
|
|
374
374
|
`),n=e.gray(`${"\u2500".repeat(40)}
|
|
375
375
|
`);return r=>{let o="";switch(r.name){case"FlowStart":o=`
|
|
376
376
|
${e.blueBright("\u{1F504} [ AXFLOW START ]")}
|
|
@@ -382,13 +382,13 @@ ${t}`,o+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
|
|
|
382
382
|
`,o+=t;break;case"StepStart":{let i=r.stepType==="execute"?"\u26A1":r.stepType==="map"?"\u{1F504}":r.stepType==="merge"?"\u{1F500}":r.stepType==="parallel"?"\u2696\uFE0F":"\u{1F4CB}";o=`${e.greenBright(`${i} [ STEP ${r.stepIndex} START ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=`
|
|
383
383
|
`,r.dependencies.length>0&&(o+=`${e.white("Dependencies:")} ${e.gray(r.dependencies.join(", "))}
|
|
384
384
|
`),r.produces.length>0&&(o+=`${e.white("Produces:")} ${e.cyan(r.produces.join(", "))}
|
|
385
|
-
`),o+=`${e.white("State:")} ${e.gray(
|
|
386
|
-
`,o+=n;break}case"StepComplete":{let i=(r.stepType==="execute"||r.stepType==="map"||r.stepType==="merge"||r.stepType==="parallel","\u2705");o=`${e.greenBright(`${i} [ STEP ${r.stepIndex} COMPLETE ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=` ${e.magenta(`in ${
|
|
385
|
+
`),o+=`${e.white("State:")} ${e.gray(bn(r.state,!0))}
|
|
386
|
+
`,o+=n;break}case"StepComplete":{let i=(r.stepType==="execute"||r.stepType==="map"||r.stepType==="merge"||r.stepType==="parallel","\u2705");o=`${e.greenBright(`${i} [ STEP ${r.stepIndex} COMPLETE ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=` ${e.magenta(`in ${In(r.executionTime)}`)}
|
|
387
387
|
`,r.newFields&&r.newFields.length>0&&(o+=`${e.white("New Fields:")} ${e.green(r.newFields.join(", "))}
|
|
388
388
|
`),r.result&&r.nodeName&&(o+=`${e.white("Result:")} ${e.yellow(JSON.stringify(r.result,null,2))}
|
|
389
389
|
`),o+=n;break}case"ParallelGroupStart":o=`${e.blueBright("\u2696\uFE0F [ PARALLEL GROUP START ]")} ${e.white(`Level ${r.groupLevel}`)}
|
|
390
390
|
`,o+=`${e.white("Steps:")} ${e.yellow(r.stepsCount.toString())} ${e.gray(`(${r.stepTypes.join(", ")})`)}
|
|
391
|
-
`,o+=n;break;case"ParallelGroupComplete":o=`${e.blueBright("\u2705 [ PARALLEL GROUP COMPLETE ]")} ${e.white(`Level ${r.groupLevel}`)}`,o+=` ${e.magenta(`in ${
|
|
391
|
+
`,o+=n;break;case"ParallelGroupComplete":o=`${e.blueBright("\u2705 [ PARALLEL GROUP COMPLETE ]")} ${e.white(`Level ${r.groupLevel}`)}`,o+=` ${e.magenta(`in ${In(r.executionTime)}`)}
|
|
392
392
|
`,o+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsCount.toString())}
|
|
393
393
|
`,o+=n;break;case"BranchEvaluation":o=`${e.yellow("\u{1F500} [ BRANCH EVALUATION ]")}
|
|
394
394
|
`,o+=`${e.white("Branch Value:")} ${e.cyan(JSON.stringify(r.branchValue))}
|
|
@@ -396,15 +396,15 @@ ${t}`,o+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
|
|
|
396
396
|
`,r.hasMatchingBranch&&(o+=`${e.white("Branch Steps:")} ${e.yellow(r.branchStepsCount.toString())}
|
|
397
397
|
`),o+=n;break;case"FlowComplete":o=`
|
|
398
398
|
${e.greenBright("\u2705 [ AXFLOW COMPLETE ]")}
|
|
399
|
-
${t}`,o+=`${e.white("Total Time:")} ${e.magenta(
|
|
399
|
+
${t}`,o+=`${e.white("Total Time:")} ${e.magenta(In(r.totalExecutionTime))}
|
|
400
400
|
`,o+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsExecuted.toString())}
|
|
401
401
|
`,o+=`${e.white("Output Fields:")} ${e.green(r.outputFields.join(", "))}
|
|
402
|
-
`,o+=`${e.white("Final State:")} ${e.gray(
|
|
402
|
+
`,o+=`${e.white("Final State:")} ${e.gray(bn(r.finalState,!0))}
|
|
403
403
|
`,o+=t;break;case"FlowError":o=`
|
|
404
404
|
${e.redBright("\u274C [ AXFLOW ERROR ]")}
|
|
405
405
|
${t}`,r.stepIndex!==void 0&&(o+=`${e.white("Step:")} ${e.yellow(r.stepIndex.toString())}`,r.stepType&&(o+=` ${e.gray(`(${r.stepType})`)}`),r.nodeName&&(o+=` ${e.cyan(`Node: ${r.nodeName}`)}`),o+=`
|
|
406
406
|
`),o+=`${e.white("Error:")} ${e.red(r.error)}
|
|
407
|
-
`,r.state&&(o+=`${e.white("State:")} ${e.gray(
|
|
407
|
+
`,r.state&&(o+=`${e.white("State:")} ${e.gray(bn(r.state,!0))}
|
|
408
408
|
`),o+=t;break;default:o=e.gray(JSON.stringify(r,null,2))}s(o)}},Yl=(s=Jl)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
|
|
409
409
|
[ AXFLOW START ]
|
|
410
410
|
${e}
|
|
@@ -417,16 +417,16 @@ ${e}
|
|
|
417
417
|
`;break;case"StepStart":r=`[ STEP ${n.stepIndex} START ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
|
|
418
418
|
`,n.dependencies.length>0&&(r+=`Dependencies: ${n.dependencies.join(", ")}
|
|
419
419
|
`),n.produces.length>0&&(r+=`Produces: ${n.produces.join(", ")}
|
|
420
|
-
`),r+=`State: ${
|
|
420
|
+
`),r+=`State: ${bn(n.state,!0)}
|
|
421
421
|
`,r+=`${t}
|
|
422
|
-
`;break;case"StepComplete":r=`[ STEP ${n.stepIndex} COMPLETE ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=` in ${
|
|
422
|
+
`;break;case"StepComplete":r=`[ STEP ${n.stepIndex} COMPLETE ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=` in ${In(n.executionTime)}
|
|
423
423
|
`,n.newFields&&n.newFields.length>0&&(r+=`New Fields: ${n.newFields.join(", ")}
|
|
424
424
|
`),n.result&&n.nodeName&&(r+=`Result: ${JSON.stringify(n.result,null,2)}
|
|
425
425
|
`),r+=`${t}
|
|
426
426
|
`;break;case"ParallelGroupStart":r=`[ PARALLEL GROUP START ] Level ${n.groupLevel}
|
|
427
427
|
`,r+=`Steps: ${n.stepsCount} (${n.stepTypes.join(", ")})
|
|
428
428
|
`,r+=`${t}
|
|
429
|
-
`;break;case"ParallelGroupComplete":r=`[ PARALLEL GROUP COMPLETE ] Level ${n.groupLevel} in ${
|
|
429
|
+
`;break;case"ParallelGroupComplete":r=`[ PARALLEL GROUP COMPLETE ] Level ${n.groupLevel} in ${In(n.executionTime)}
|
|
430
430
|
`,r+=`Steps Executed: ${n.stepsCount}
|
|
431
431
|
`,r+=`${t}
|
|
432
432
|
`;break;case"BranchEvaluation":r=`[ BRANCH EVALUATION ]
|
|
@@ -437,22 +437,24 @@ ${e}
|
|
|
437
437
|
`;break;case"FlowComplete":r=`
|
|
438
438
|
[ AXFLOW COMPLETE ]
|
|
439
439
|
${e}
|
|
440
|
-
`,r+=`Total Time: ${
|
|
440
|
+
`,r+=`Total Time: ${In(n.totalExecutionTime)}
|
|
441
441
|
`,r+=`Steps Executed: ${n.stepsExecuted}
|
|
442
442
|
`,r+=`Output Fields: ${n.outputFields.join(", ")}
|
|
443
|
-
`,r+=`Final State: ${
|
|
443
|
+
`,r+=`Final State: ${bn(n.finalState,!0)}
|
|
444
444
|
`,r+=`${e}
|
|
445
445
|
`;break;case"FlowError":r=`
|
|
446
446
|
[ AXFLOW ERROR ]
|
|
447
447
|
${e}
|
|
448
448
|
`,n.stepIndex!==void 0&&(r+=`Step: ${n.stepIndex}`,n.stepType&&(r+=` (${n.stepType})`),n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
|
|
449
449
|
`),r+=`Error: ${n.error}
|
|
450
|
-
`,n.state&&(r+=`State: ${
|
|
450
|
+
`,n.state&&(r+=`State: ${bn(n.state,!0)}
|
|
451
451
|
`),r+=`${e}
|
|
452
|
-
`;break;default:r=JSON.stringify(n,null,2)}s(r)}},Ql=lr(),Zl=s=>{let e=new Map;return{logger:s,startTiming:t=>{e.set(t,Date.now())},endTiming:t=>{let n=e.get(t);if(!n)return 0;let r=Date.now()-n;return e.delete(t),r},getCurrentTime:()=>Date.now()}};var In=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,i)=>{let a=n?.ai??i.mainAi,l=n?.options??i.mainOptions,c=t(o),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:p}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}},Fo=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,i)=>{let a=n?.ai??i.mainAi,l=n?.options??i.mainOptions,c=t(o),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:p}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}};var cr=class s{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new xn;program;nodeUsage=new Map;nodeTraces=new Map;flowLogger;timingLogger;defaultAIOptions;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}async executeStepsWithLogging(e,t,n,r){let o={...t},i=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let c=this.getStepType(l,a),u=this.getStepMetadata(l,a),p=Object.keys(o);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:u.nodeName,dependencies:u.dependencies,produces:u.produces,state:{...o}});let d=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{o=await l(o,n),i++;let g=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-d,h=Object.keys(o).filter(x=>!p.includes(x)),A;if(c==="execute"&&u.nodeName&&h.length>0){let x=`${u.nodeName}Result`;A=o[x]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:u.nodeName,executionTime:g,state:{...o},newFields:h,result:A})}catch(m){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:m instanceof Error?m.message:String(m),stepIndex:a,stepType:c,nodeName:u.nodeName,state:{...o}}),m}}return{finalState:o,stepsExecuted:i}}getStepType(e,t){let n=e.toString();return n.includes("nodeName")||n.includes("nodeProgram")?"execute":n.includes("_parallelResults")||n.includes("processBatches")?"parallel":n.includes("branchValue")||n.includes("branches.get")||n.includes("mergeFunction")?"merge":n.includes("transform(")||n.includes("...state,")?"map":n.includes("inputValue")&&n.includes("transformFn")?"derive":n.includes("condition(")&&n.includes("iterations")?n.includes("while")?"while":"feedback":n.includes("branchSteps")||n.includes("currentState")?"branch":"other"}getStepMetadata(e,t){let r=this.executionPlanner.getExecutionPlan().steps.find(a=>a.stepIndex===t);if(r)return{nodeName:r.nodeName,dependencies:r.dependencies,produces:r.produces};let o=e.toString();return{nodeName:this.extractNodeNameFromSource(o),dependencies:[],produces:[]}}extractNodeNameFromSource(e){let t=e.match(/nodeName['"]?\s*[=:]\s*['"](\w+)['"]/);if(t)return t[1];let n=e.match(/nodeProgram\.get\(['"](\w+)['"]\)/);if(n)return n[1]}inferSignatureFromFlow(){let e=this.executionPlanner.getExecutionPlan();if(this.nodeGenerators.size===0&&e.steps.length===0)return se().input("userInput",se.string("User input to the flow")).output("flowOutput",se.string("Output from the flow")).build();let t=new Set,n=new Set;for(let u of e.steps)u.produces.forEach(p=>t.add(p)),u.dependencies.forEach(p=>n.add(p));let r=new Set;for(let u of Array.from(n))t.has(u)||r.add(u);let o=new Set,i=e.steps[e.steps.length-1];if(i&&(i.type==="map"||i.type==="merge")){if(i.produces.forEach(u=>{u.startsWith("_")||o.add(u)}),i.type==="merge"&&i.produces.includes("_mergedResult"))for(let u of e.steps)u.type==="execute"&&u.produces.length>0&&u.produces.forEach(p=>o.add(p))}else for(let u of Array.from(t)){let p=!1;for(let d of e.steps)if(d.dependencies.includes(u)){p=!0;break}if(!p)if(u.endsWith("Result")){let d=u.replace("Result",""),m=this.nodeGenerators.get(d);if(m){let f=m.getSignature().getOutputFields();for(let h of f)o.add(h.name)}else o.add(u)}else o.add(u)}if(r.size===0&&o.size===0){let u=[],p=[];for(let[m,g]of Array.from(this.nodeGenerators)){let f=g.getSignature();for(let h of f.getInputFields()){let A=this.toCamelCase(`${m}_${h.name}`);u.push({name:A,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}for(let h of f.getOutputFields()){let A=this.toCamelCase(`${m}_${h.name}`);p.push({name:A,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}}let d=new ge;return u.length>0?d.setInputFields(u):d.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),p.length>0?d.setOutputFields(p):d.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),d}let a=new ge,l=[];for(let u of Array.from(r))l.push({name:u,type:{name:"string"},description:`Input field: ${u}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let c=[];for(let u of Array.from(o))u.startsWith("_")||c.push({name:u,type:{name:"string"},description:`Output field: ${u}`});return c.length===0&&c.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(c),a}constructor(e){s._ctorWarned||(console.warn("[AxFlow] new AxFlow() is deprecated. Use flow() factory instead."),s._ctorWarned=!0),this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10},e?.logger?this.flowLogger=e.logger:e?.debug===!0?this.flowLogger=lr():this.flowLogger=void 0,this.timingLogger=this.flowLogger?Zl(this.flowLogger):void 0,(e?.tracer||e?.meter)&&(this.defaultAIOptions={tracer:e.tracer,meter:e.meter})}static create(e){return new s(e)}ensureProgram(){let e=this.inferSignatureFromFlow();if(!this.program){this.program=new It(e);for(let[t,n]of Array.from(this.nodeGenerators))this.program.register(n);return}this.program.setSignature(e)}setExamples(e,t){this.ensureProgram(),this.program.setExamples(e,t)}setId(e){this.ensureProgram(),this.program.setId(e)}setParentId(e){this.ensureProgram(),this.program.setParentId(e)}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return Zn(e)}resetUsage(){this.nodeUsage.clear();for(let[e,t]of Array.from(this.nodeGenerators))t&&"resetUsage"in t&&t.resetUsage()}resetTraces(){this.nodeTraces.clear()}getUsageReport(){let e={};for(let[t,n]of Array.from(this.nodeUsage))e[t]=Zn(n);return e}getNodePrograms(){return Array.from(this.nodeGenerators).map(([e,t])=>({name:e,program:t}))}setNodeInstruction(e,t){let n=this.nodeGenerators.get(e);if(!n)return!1;let r=n;if(typeof r.setInstruction=="function")try{return r.setInstruction(t),!0}catch{return!1}return!1}setAllNodeInstructions(e){for(let[t,n]of Object.entries(e))this.setNodeInstruction(t,n)}getTracesReport(){let e={};for(let[t,n]of Array.from(this.nodeTraces))e[t]=n;return e}async*streamingForward(e,t,n){yield{version:1,index:0,delta:await this.forward(e,t,n)}}async forward(e,t,n){let r=Date.now();this.timingLogger?.startTiming("flow-execution");let o={};try{this.resetUsage(),this.resetTraces();let i;if(Array.isArray(t)){let g=t.filter(f=>f.role==="user").pop();if(!g)throw new Error("No user message found in values array");i=g.values}else i=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),o={...i},this.flowLogger){let g=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:r,inputFields:Object.keys(i),totalSteps:g.totalSteps,parallelGroups:g.parallelGroups,maxParallelism:g.maxParallelism,autoParallelEnabled:g.autoParallelEnabled})}let a=n?.tracer??this.defaultAIOptions?.tracer,l=n?.traceContext,c,u=l;if(a){let g=this.getExecutionPlan(),f=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";c=a.startSpan(f,{kind:Me.INTERNAL,attributes:{total_steps:g.totalSteps,parallel_groups:g.parallelGroups,max_parallelism:g.maxParallelism,auto_parallel_enabled:g.autoParallelEnabled}});let h=l??xt.active();u=kn.setSpan(h,c)}let p={mainAi:e,mainOptions:(()=>{let g={...this.defaultAIOptions??{},...n};return n?.model&&(g.model=String(n.model)),a&&(g.tracer=a),u&&(g.traceContext=u),Object.keys(g).length>0?g:void 0})()},d=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,m=0;if(d){this.executionPlanner.setInitialFields(Object.keys(i));let g=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),f=await this.executeStepsWithLogging(g,o,p,!0);o=f.finalState,m=f.stepsExecuted}else{let g=await this.executeStepsWithLogging(this.flowDefinition,o,p,!1);o=g.finalState,m=g.stepsExecuted}if(this.flowLogger){let g=this.timingLogger?.endTiming("flow-execution")??Date.now()-r;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:g,finalState:o,outputFields:Object.keys(o),stepsExecuted:m})}return c&&c.end(),o}catch(i){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:i instanceof Error?i.message:String(i),state:o}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),i}}node(e,t){if(typeof t=="string"||t instanceof ge){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let r=ye(n);this.nodeGenerators.set(e,r),this.ensureProgram(),this.program.register(r)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],r=async o=>(await An(n,async(l,c)=>{let u=l(o);return Promise.resolve(u)},this.autoParallelConfig.batchSize)).reduce((l,c)=>({...l,...c}),o);if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"parallel-map",n)}else{let n=async r=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");let o=e(r);return Promise.resolve(o)};if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}returns(e){let t=async n=>{let r=e(n);return Promise.resolve(r)};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}r(e){return this.returns(e)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);let o=async(i,a)=>{let l=n?.ai??a.mainAi,c={...a.mainOptions??{},...n?.options??{}},u=t(i),p=c?.traceLabel?`Node:${e} (${c.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function"){if(d=await r.forward(l,u,{...c,traceLabel:p}),"getUsage"in r&&typeof r.getUsage=="function"){let m=r.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in r&&typeof r.getTraces=="function"){let m=r.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...i,[`${e}Result`]:d}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.applyOptimization(e);for(let[t,n]of Array.from(this.nodeGenerators))n&&"applyOptimization"in n&&typeof n.applyOptimization=="function"&&n.applyOptimization(e)}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,r)=>{let o=e.predicate(n),i=e.branches.get(o);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:o,hasMatchingBranch:!!i,branchStepsCount:i?.length??0}),!i)return n;let a=n;for(let l of i)a=await l(a,r);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,r)=>{let o=await An(e,async(i,a)=>{let l=new In(this.nodeGenerators);return await i(l).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:o}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,r)=>{let o=i=>{let a=i._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=r(...a),c={...i};return delete c._parallelResults,c[n]=l,c};return this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:r}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let r=this.stepLabels.get(t),o=this.flowDefinition.length;return this.flowDefinition.push(async(i,a)=>{let l=i,c=1,u=`_feedback_${t}_iterations`;for(typeof l[u]!="number"&&(l={...l,[u]:1});e(l)&&c<n;){c++,l={...l,[u]:c};for(let p=r;p<o;p++){let d=this.flowDefinition[p];d&&(l=await d(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let r=Object.assign(o=>o,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(r),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,r=t._maxIterations,o=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(i,a)=>{let l=i,c=0;for(;n(l)&&c<r;){c++;for(let u of o)l=await u(l,a)}if(c>=r&&n(l))throw new Error(`While loop exceeded maximum iterations (${r}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,r){let o=async i=>{let a=i[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let l;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let c=r?.batchSize||this.autoParallelConfig.batchSize;l=await An(a,async(u,p)=>n(u,p,i),c)}else l=a.map((c,u)=>n(c,u,i));else l=n(a,void 0,i);return{...i,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:r?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}nodeExtended(e,t,n){let o=typeof t=="string"?ge.create(t):t;if(n.prependInputs)for(let i of n.prependInputs)o=o.prependInputField(i.name,i.type);if(n.appendInputs)for(let i of n.appendInputs)o=o.appendInputField(i.name,i.type);if(n.prependOutputs)for(let i of n.prependOutputs)o=o.prependOutputField(i.name,i.type);if(n.appendOutputs)for(let i of n.appendOutputs)o=o.appendOutputField(i.name,i.type);return this.node(e,o)}nx(e,t,n){return this.nodeExtended(e,t,n)}mapOutput(e){let t=async n=>{let r=e(n);return{...n,...r}};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}mo(e){return this.mapOutput(e)}};function Do(s){return cr.create(s)}var No=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let o=t.map(c=>`${c.hostPath}:${c.containerPath}`);n||await this.pullImage(e);let i={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:o},Labels:{}};r&&(i.Labels["com.example.tag"]=r);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new Error(`Failed to create container: ${a.statusText}`);let l=await a.json();return this.containerId=l.Id,l}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let i=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===r);if(i&&i.length>0){let l=Math.floor(Math.random()*i.length),c=i[l];if(c)return await this.connectToContainer(c.Id),{Id:c.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:r})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let r=[],o=await this.listContainers(!0),i=e?o.filter(a=>a.Labels["com.example.tag"]===e):o;for(let a of i){if(a.State.Status==="running"){let l=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!l.ok){console.warn(`Failed to stop container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"removed"})}}return r}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let r=await n.json(),o=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!o.ok)throw new Error(`Failed to start exec instance: ${o.statusText}`);return await o.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var $o=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let r=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!r)throw new Error("Failed to embed text");return this.func.length===2?this.func(r,t):this.func(r)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var Go=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(o=>o.name===t.name),r=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:r,func:async o=>{let{result:i}=await this.sendRequest("tools/call",{name:t.name,arguments:o});return i}}})}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((i,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),r=await Promise.race([t,n]),{result:o}=r;if(typeof o!="object"||o===null||Object.keys(o).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(o)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=be(),r={jsonrpc:"2.0",id:n,method:e,params:t},o=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(r).then(c=>{if(this.activeRequests.delete(n),c!==null&&typeof c=="object"&&"error"in c){let u=c;l(new Error(`RPC Error ${u.error.code}: ${u.error.message}`))}else c!==null&&typeof c=="object"&&"result"in c?a({result:c.result}):l(new Error("Invalid response no result or error"))}).catch(c=>{this.activeRequests.delete(n),l(c)})}),{result:i}=await o;return{id:n,result:i}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:r}=this.options;if(r){let o={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(o)}await this.transport.sendNotification(n)}};function Xl(s){if(typeof Buffer<"u")return Buffer.from(s).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");let e="";for(let n=0;n<s.length;n++)e+=String.fromCharCode(s[n]);return(typeof btoa=="function"?btoa(e):"").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function ec(s){let t=new TextEncoder().encode(s),n=await gi().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function di(){return Xl(await ec(be()+Math.random().toString(36)))}async function tc(s){return Xl(await ec(s))}async function Lo(s,e){let t=await fetch(s,{headers:e});if(!t.ok)throw new Error(`HTTP ${t.status} fetching ${s}: ${t.statusText}`);return await t.json()}function nc(s){let e=new URLSearchParams;for(let[t,n]of Object.entries(s))n!==void 0&&e.set(t,n);return e.toString()}function ur(s){return s.endsWith("/")?s.slice(0,-1):s}function up(s){if(!s)return null;let e=s.match(/resource_metadata\s*=\s*"([^"]+)"/i)||s.match(/resource_metadata\s*=\s*([^,\s]+)/i);return e?e[1]:null}async function rc(s,e){let t=up(e);if(t){let a=await Lo(t),l=ur(new URL(s).toString().split("?")[0]),c=ur(a.resource??"");if(!c||c!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${c}`);let u=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(u.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:u}}let n=new URL(s),r=n.pathname.replace(/\/+$/,""),o=[];r&&r!=="/"&&o.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),o.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let i;for(let a of o)try{let l=await Lo(a.url),c=ur(l.resource??""),u=ur(a.expected);if(!c||c!==u)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${u} but got ${c}`);let p=Array.isArray(l.authorization_servers)?l.authorization_servers:[];if(p.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:u,issuers:p}}catch(l){i=l}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(i)}`)}async function oc(s){let e=new URL(s),t=e.pathname.replace(/^\/+/,""),n=[];t?(n.push(`${e.origin}/.well-known/oauth-authorization-server/${t}`),n.push(`${e.origin}/.well-known/openid-configuration/${t}`),n.push(`${e.origin}/${t.replace(/\/+$/,"")}/.well-known/openid-configuration`)):(n.push(`${e.origin}/.well-known/oauth-authorization-server`),n.push(`${e.origin}/.well-known/openid-configuration`));let r;for(let o of n)try{let i=await Lo(o);if(!i.authorization_endpoint||!i.token_endpoint)throw new Error("AS metadata missing endpoints");let a=i.code_challenge_methods_supported;if(!a||!a.includes("S256"))throw new Error("Authorization server does not advertise PKCE S256 support");return i}catch(i){r=i}throw new Error(`Failed to discover AS metadata for ${s}: ${String(r)}`)}var Tn=class{constructor(e){this.oauth=e}tokenCache=new Map;asMetaCache=new Map;key(e,t){return`${e}::${t}`}async getStoredToken(e,t){let n=this.key(e,t);if(this.tokenCache.has(n))return this.tokenCache.get(n);let r=await this.oauth?.tokenStore?.getToken?.(n);return r&&this.tokenCache.set(n,r),r??null}async setStoredToken(e,t,n){let r=this.key(e,t);this.tokenCache.set(r,n),await this.oauth?.tokenStore?.setToken?.(r,n)}async clearStoredToken(e,t){let n=this.key(e,t);this.tokenCache.delete(n),await this.oauth?.tokenStore?.clearToken?.(n)}isExpired(e){return e?Date.now()>e-6e4:!1}async getASMeta(e){if(this.asMetaCache.has(e))return this.asMetaCache.get(e);let t=await oc(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await rc(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],o=await this.getASMeta(r),i=e.currentToken??await this.getStoredToken(t,r);if(i?.accessToken&&!this.isExpired(i.expiresAt))return{token:i,issuer:r,asMeta:o,resource:t};if(i?.refreshToken)try{let x=await this.refreshToken(i.refreshToken,t,r,o);return await this.setStoredToken(t,r,x),{token:x,issuer:r,asMeta:o,resource:t}}catch{await this.clearStoredToken(t,r)}let a=this.oauth.redirectUri??"http://localhost:8787/callback",l=this.oauth.clientId?{client_id:this.oauth.clientId,client_secret:this.oauth.clientSecret}:await this.dynamicClientRegistration(o,a),c=await di(),u=await tc(c),p=await di(),d=this.oauth.scopes?.join(" "),m=`${o.authorization_endpoint}?${nc({response_type:"code",client_id:l.client_id,redirect_uri:a,scope:d,state:p,code_challenge:u,code_challenge_method:"S256",resource:t})}`;if(!this.oauth.onAuthCode)throw new Error(`Authorization required. Provide oauth.onAuthCode to complete the flow. Navigate to: ${m}`);let{code:g,redirectUri:f}=await this.oauth.onAuthCode(m),h=f??a,A=await this.exchangeCodeForToken({asMeta:o,code:g,codeVerifier:c,client:l,redirectUri:h,resource:t});return await this.setStoredToken(t,r,A),{token:A,issuer:r,asMeta:o,resource:t}}async dynamicClientRegistration(e,t){if(!e.registration_endpoint)throw new Error("Authorization server does not support dynamic client registration and no clientId was provided.");let r={application_type:t.startsWith("http://localhost")?"native":"web",client_name:"Ax MCP Client",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"},o=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Dynamic client registration failed: ${o.status} ${o.statusText}`);let i=await o.json();if(!i.client_id)throw new Error("Dynamic client registration did not return client_id");return i}async exchangeCodeForToken(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("code",e.code),t.set("redirect_uri",e.redirectUri),t.set("client_id",e.client.client_id),t.set("code_verifier",e.codeVerifier),t.set("resource",e.resource),e.client.client_secret&&t.set("client_secret",e.client.client_secret);let n=await fetch(e.asMeta.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!n.ok)throw new Error(`Token exchange failed: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.access_token)throw new Error("No access_token in token response");let o=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:o}}async refreshToken(e,t,n,r){let o=new URLSearchParams;o.set("grant_type","refresh_token"),o.set("refresh_token",e),o.set("resource",t),this.oauth?.clientId&&o.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&o.set("client_secret",this.oauth.clientSecret);let i=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()});if(!i.ok)throw new Error(`Token refresh failed: ${i.status} ${i.statusText}`);let a=await i.json();if(!a.access_token)throw new Error("No access_token in refresh response");let l=a.expires_in?Date.now()+a.expires_in*1e3:void 0;return{accessToken:a.access_token,refreshToken:a.refresh_token??e,expiresAt:l}}};var Uo=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;oauthHelper;currentToken;currentIssuer;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Tn(t?.oauth)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),r=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(r.toString()),this.eventSource.onopen=()=>e(),this.eventSource.onmessage=o=>{try{let i=JSON.parse(o.data);this.messageHandler&&this.messageHandler(i)}catch(i){console.error("Failed to parse SSE message:",i)}},this.eventSource.onerror=()=>t(new Error("Failed to establish SSE connection"))})}async openListeningStreamWithFetch(e){let t=await fetch(this.mcpEndpoint,{method:"GET",headers:e});if(t.status===401){let a=t.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,this.openListeningStreamWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),r=new TextDecoder,o="",i=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}o+=r.decode(l,{stream:!0});let c=o.split(`
|
|
453
|
-
`)
|
|
454
|
-
`);a=p.pop()||"";for(let d of p)if(d.startsWith("data: ")){let m=d.slice(6);if(m==="[DONE]")return;try{let g=JSON.parse(m);if("id"in g&&g.id===t){n(g);return}this.messageHandler&&this.messageHandler(g)}catch(g){console.error("Failed to parse SSE data:",g)}}await l()}catch(c){o.releaseLock(),r(c)}};l().catch(r)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:o,currentToken:null});if(!i)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${i.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}async terminateSession(){if(this.sessionId)try{let e=this.buildHeaders({});(await fetch(this.mcpEndpoint,{method:"DELETE",headers:e})).status===405&&console.info("Server does not support explicit session termination")}catch(e){console.error("Failed to terminate session:",e)}finally{this.sessionId=void 0}}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}};var Bo=class{endpoint=null;sseUrl;eventSource;customHeaders={};oauthHelper;currentToken;currentIssuer;sseAbort;pendingRequests=new Map;messageHandler;endpointReady;constructor(e,t){this.sseUrl=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Tn(t?.oauth)}buildHeaders(e){return{...this.customHeaders,...e}}async openSSEWithFetch(e){let t=new AbortController;this.sseAbort=t;let n=await fetch(this.sseUrl,{method:"GET",headers:e,signal:t.signal});if(n.status===401){let o=n.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!i)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${i.token.accessToken}`,this.openSSEWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!n.ok)throw new Error("Failed to establish SSE connection");let r=this.createEndpointReady();this.consumeSSEStream(n),await r}createEndpointReady(){if(!this.endpointReady){let e,t=new Promise(n=>{e=n});this.endpointReady={resolve:e,promise:t}}return this.endpointReady.promise}async consumeSSEStream(e){if(!e.body)throw new Error("No response body available for SSE stream");let t=e.body.getReader(),n=new TextDecoder,r="",o=null;for(;;){let{done:i,value:a}=await t.read();if(i)break;r+=n.decode(a,{stream:!0});let l=r.split(`
|
|
455
|
-
`);
|
|
456
|
-
`)
|
|
457
|
-
`):"").
|
|
452
|
+
`;break;default:r=JSON.stringify(n,null,2)}s(r)}},Ql=cr(),Zl=s=>{let e=new Map;return{logger:s,startTiming:t=>{e.set(t,Date.now())},endTiming:t=>{let n=e.get(t);if(!n)return 0;let r=Date.now()-n;return e.delete(t),r},getCurrentTime:()=>Date.now()}};var Tn=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,i)=>{let a=n?.ai??i.mainAi,l=n?.options??i.mainOptions,c=t(o),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function")d=await r.forward(a,c,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}},Fo=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,i)=>{let a=n?.ai??i.mainAi,l=n?.options??i.mainOptions,c=t(o),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function")d=await r.forward(a,c,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}};var ur=class s{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new yn;program;flowName;nodeUsage=new Map;nodeTraces=new Map;flowLogger;timingLogger;defaultAIOptions;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}async executeStepsWithLogging(e,t,n,r){let o={...t},i=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let c=this.getStepType(l,a),u=this.getStepMetadata(l,a),d=Object.keys(o);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:u.nodeName,dependencies:u.dependencies,produces:u.produces,state:{...o}});let p=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{o=await l(o,n),i++;let g=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-p,f=Object.keys(o).filter(x=>!d.includes(x)),A;if(c==="execute"&&u.nodeName&&f.length>0){let x=`${u.nodeName}Result`;A=o[x]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:u.nodeName,executionTime:g,state:{...o},newFields:f,result:A})}catch(m){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:m instanceof Error?m.message:String(m),stepIndex:a,stepType:c,nodeName:u.nodeName,state:{...o}}),m}}return{finalState:o,stepsExecuted:i}}getStepType(e,t){let n=e.toString();return n.includes("nodeName")||n.includes("nodeProgram")?"execute":n.includes("_parallelResults")||n.includes("processBatches")?"parallel":n.includes("branchValue")||n.includes("branches.get")||n.includes("mergeFunction")?"merge":n.includes("transform(")||n.includes("...state,")?"map":n.includes("inputValue")&&n.includes("transformFn")?"derive":n.includes("condition(")&&n.includes("iterations")?n.includes("while")?"while":"feedback":n.includes("branchSteps")||n.includes("currentState")?"branch":"other"}getStepMetadata(e,t){let r=this.executionPlanner.getExecutionPlan().steps.find(a=>a.stepIndex===t);if(r)return{nodeName:r.nodeName,dependencies:r.dependencies,produces:r.produces};let o=e.toString();return{nodeName:this.extractNodeNameFromSource(o),dependencies:[],produces:[]}}extractNodeNameFromSource(e){let t=e.match(/nodeName['"]?\s*[=:]\s*['"](\w+)['"]/);if(t)return t[1];let n=e.match(/nodeProgram\.get\(['"](\w+)['"]\)/);if(n)return n[1]}inferSignatureFromFlow(){let e=this.executionPlanner.getExecutionPlan();if(this.nodeGenerators.size===0&&e.steps.length===0)return ie().input("userInput",ie.string("User input to the flow")).output("flowOutput",ie.string("Output from the flow")).build();let t=new Set,n=new Set;for(let u of e.steps)u.produces.forEach(d=>t.add(d)),u.dependencies.forEach(d=>n.add(d));let r=new Set;for(let u of Array.from(n))t.has(u)||r.add(u);let o=new Set,i=e.steps[e.steps.length-1];if(i&&(i.type==="map"||i.type==="merge")){if(i.produces.forEach(u=>{u.startsWith("_")||o.add(u)}),i.type==="merge"&&i.produces.includes("_mergedResult"))for(let u of e.steps)u.type==="execute"&&u.produces.length>0&&u.produces.forEach(d=>o.add(d))}else for(let u of Array.from(t)){let d=!1;for(let p of e.steps)if(p.dependencies.includes(u)){d=!0;break}if(!d)if(u.endsWith("Result")){let p=u.replace("Result",""),m=this.nodeGenerators.get(p);if(m){let h=m.getSignature().getOutputFields();for(let f of h)o.add(f.name)}else o.add(u)}else o.add(u)}if(r.size===0&&o.size===0){let u=[],d=[];for(let[m,g]of Array.from(this.nodeGenerators)){let h=g.getSignature();for(let f of h.getInputFields()){let A=this.toCamelCase(`${m}_${f.name}`);u.push({name:A,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}for(let f of h.getOutputFields()){let A=this.toCamelCase(`${m}_${f.name}`);d.push({name:A,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}}let p=new ge;return u.length>0?p.setInputFields(u):p.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),d.length>0?p.setOutputFields(d):p.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),p}let a=new ge,l=[];for(let u of Array.from(r))l.push({name:u,type:{name:"string"},description:`Input field: ${u}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let c=[];for(let u of Array.from(o))u.startsWith("_")||c.push({name:u,type:{name:"string"},description:`Output field: ${u}`});return c.length===0&&c.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(c),a}constructor(e){s._ctorWarned||(console.warn("[AxFlow] new AxFlow() is deprecated. Use flow() factory instead."),s._ctorWarned=!0),this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10},e?.logger?this.flowLogger=e.logger:e?.debug===!0?this.flowLogger=cr():this.flowLogger=void 0,this.timingLogger=this.flowLogger?Zl(this.flowLogger):void 0,(e?.tracer||e?.meter)&&(this.defaultAIOptions={tracer:e.tracer,meter:e.meter})}static create(e){return new s(e)}ensureProgram(){let e=this.inferSignatureFromFlow();if(!this.program){this.program=new Tt(e);for(let[t,n]of Array.from(this.nodeGenerators))this.program.register(n);return}this.program.setSignature(e)}setExamples(e,t){this.ensureProgram(),this.program.setExamples(e,t)}setId(e){this.ensureProgram(),this.program.setId(e)}setParentId(e){this.ensureProgram(),this.program.setParentId(e)}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}description(e,t){return this.ensureProgram(),this.flowName=e,this.program.setDescription(t),this}toFunction(){this.ensureProgram();let e=this.program.getSignature(),n=(this.flowName??(e.getDescription()?.trim().split(`
|
|
453
|
+
`)[0]||"axFlow")).replace(/\s+/g,"_"),r=this.toCamelCase(n),o=async(i,a)=>{let l=a?.ai;if(!l)throw new Error("AI service is required to run the flow");let c=await this.forward(l,i??{}),u=e.getOutputFields(),d=c??{};return Object.keys(d).map(p=>{let m=u.find(g=>g.name===p);return m&&m.title?`${m.title}: ${d[p]}`:`${p}: ${d[p]}`}).join(`
|
|
454
|
+
`)};return{name:r,description:e.getDescription()??"Execute this AxFlow",parameters:e.toJSONSchema(),func:o}}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return Xn(e)}resetUsage(){this.nodeUsage.clear();for(let[e,t]of Array.from(this.nodeGenerators))t&&"resetUsage"in t&&t.resetUsage()}resetTraces(){this.nodeTraces.clear()}getUsageReport(){let e={};for(let[t,n]of Array.from(this.nodeUsage))e[t]=Xn(n);return e}getNodePrograms(){return Array.from(this.nodeGenerators).map(([e,t])=>({name:e,program:t}))}setNodeInstruction(e,t){let n=this.nodeGenerators.get(e);if(!n)return!1;let r=n;if(typeof r.setInstruction=="function")try{return r.setInstruction(t),!0}catch{return!1}return!1}setAllNodeInstructions(e){for(let[t,n]of Object.entries(e))this.setNodeInstruction(t,n)}getTracesReport(){let e={};for(let[t,n]of Array.from(this.nodeTraces))e[t]=n;return e}async*streamingForward(e,t,n){let r=n?.cachingFunction??ee.cachingFunction,o=(()=>{if(!r)return;this.ensureProgram();let a=this.program.getSignature(),l=a.getInputFields().map(p=>p.name),c=Array.isArray(t)?t.filter(p=>p.role==="user").pop().values:t,u=Be("sha256");u.update(a.hash()??"");let d=p=>{let m=typeof p;if(u.update(`|${m}|`),p==null){u.update("null");return}if(m==="string"||m==="number"||m==="boolean"){u.update(String(p));return}if(Array.isArray(p)){u.update("[");for(let g of p)d(g);u.update("]");return}if(typeof p=="object"&&p!==null&&"mimeType"in p&&"data"in p){let g=p;u.update(g.mimeType??"");let h=Be("sha256").update(g.data??"").digest("hex");u.update(h);return}if(typeof p=="object"){let g=p,h=Object.keys(g).sort();for(let f of h)u.update(`{${f}}`),d(g[f]);return}u.update(String(p))};for(let p of l)d(c?.[p]);return u.digest("hex")})();if(r&&o){let a;try{a=await r(o)}catch{}if(a!==void 0){yield{version:0,index:0,delta:a};return}}let i=await this.forward(e,t,n);if(r&&o)try{await r(o,i)}catch{}yield{version:1,index:0,delta:i}}async forward(e,t,n){let r=n?.cachingFunction??ee.cachingFunction,o=(()=>{if(!r)return;this.ensureProgram();let l=this.program.getSignature(),c=l.getInputFields().map(m=>m.name),u=Array.isArray(t)?t.filter(m=>m.role==="user").pop().values:t,d=Be("sha256");d.update(l.hash()??"");let p=m=>{let g=typeof m;if(d.update(`|${g}|`),m==null){d.update("null");return}if(g==="string"||g==="number"||g==="boolean"){d.update(String(m));return}if(Array.isArray(m)){d.update("[");for(let h of m)p(h);d.update("]");return}if(typeof m=="object"&&m!==null&&"mimeType"in m&&"data"in m){let h=m;d.update(h.mimeType??"");let f=Be("sha256").update(h.data??"").digest("hex");d.update(f);return}if(typeof m=="object"){let h=m,f=Object.keys(h).sort();for(let A of f)d.update(`{${A}}`),p(h[A]);return}d.update(String(m))};for(let m of c)p(u?.[m]);return d.digest("hex")})();if(r&&o){let l=await r(o);if(l!==void 0)return l}let i=Date.now();this.timingLogger?.startTiming("flow-execution");let a={};try{this.resetUsage(),this.resetTraces();let l;if(Array.isArray(t)){let f=t.filter(A=>A.role==="user").pop();if(!f)throw new Error("No user message found in values array");l=f.values}else l=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),a={...l},this.flowLogger){let f=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:i,inputFields:Object.keys(l),totalSteps:f.totalSteps,parallelGroups:f.parallelGroups,maxParallelism:f.maxParallelism,autoParallelEnabled:f.autoParallelEnabled})}let c=n?.tracer??this.defaultAIOptions?.tracer,u=n?.traceContext,d,p=u;if(c){let f=this.getExecutionPlan(),A=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";d=c.startSpan(A,{kind:Me.INTERNAL,attributes:{total_steps:f.totalSteps,parallel_groups:f.parallelGroups,max_parallelism:f.maxParallelism,auto_parallel_enabled:f.autoParallelEnabled}});let x=u??yt.active();p=Mn.setSpan(x,d)}let m={mainAi:e,mainOptions:(()=>{let f={...this.defaultAIOptions??{},...n};return n?.model&&(f.model=String(n.model)),c&&(f.tracer=c),p&&(f.traceContext=p),Object.keys(f).length>0?f:void 0})()},g=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,h=0;if(g){this.executionPlanner.setInitialFields(Object.keys(l));let f=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),A=await this.executeStepsWithLogging(f,a,m,!0);a=A.finalState,h=A.stepsExecuted}else{let f=await this.executeStepsWithLogging(this.flowDefinition,a,m,!1);a=f.finalState,h=f.stepsExecuted}if(this.flowLogger){let f=this.timingLogger?.endTiming("flow-execution")??Date.now()-i;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:f,finalState:a,outputFields:Object.keys(a),stepsExecuted:h})}if(d&&d.end(),r&&o)try{await r(o,a)}catch{}return a}catch(l){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:l instanceof Error?l.message:String(l),state:a}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),l}}node(e,t){if(typeof t=="string"||t instanceof ge){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let r=ye(n);this.nodeGenerators.set(e,r),this.ensureProgram(),this.program.register(r)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],r=async o=>(await xn(n,async(l,c)=>{let u=l(o);return Promise.resolve(u)},this.autoParallelConfig.batchSize)).reduce((l,c)=>({...l,...c}),o);if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"parallel-map",n)}else{let n=async r=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");let o=e(r);return Promise.resolve(o)};if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}returns(e){let t=async n=>{let r=e(n);return Promise.resolve(r)};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}r(e){return this.returns(e)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);let o=async(i,a)=>{let l=n?.ai??a.mainAi,c={...a.mainOptions??{},...n?.options??{}},u=t(i),d=c?.traceLabel?`Node:${e} (${c.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function"){if(p=await r.forward(l,u,{...c,traceLabel:d}),"getUsage"in r&&typeof r.getUsage=="function"){let m=r.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in r&&typeof r.getTraces=="function"){let m=r.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...i,[`${e}Result`]:p}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.applyOptimization(e);for(let[t,n]of Array.from(this.nodeGenerators))n&&"applyOptimization"in n&&typeof n.applyOptimization=="function"&&n.applyOptimization(e)}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,r)=>{let o=e.predicate(n),i=e.branches.get(o);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:o,hasMatchingBranch:!!i,branchStepsCount:i?.length??0}),!i)return n;let a=n;for(let l of i)a=await l(a,r);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,r)=>{let o=await xn(e,async(i,a)=>{let l=new Tn(this.nodeGenerators);return await i(l).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:o}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,r)=>{let o=i=>{let a=i._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=r(...a),c={...i};return delete c._parallelResults,c[n]=l,c};return this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:r}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let r=this.stepLabels.get(t),o=this.flowDefinition.length;return this.flowDefinition.push(async(i,a)=>{let l=i,c=1,u=`_feedback_${t}_iterations`;for(typeof l[u]!="number"&&(l={...l,[u]:1});e(l)&&c<n;){c++,l={...l,[u]:c};for(let d=r;d<o;d++){let p=this.flowDefinition[d];p&&(l=await p(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let r=Object.assign(o=>o,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(r),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,r=t._maxIterations,o=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(i,a)=>{let l=i,c=0;for(;n(l)&&c<r;){c++;for(let u of o)l=await u(l,a)}if(c>=r&&n(l))throw new Error(`While loop exceeded maximum iterations (${r}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,r){let o=async i=>{let a=i[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let l;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let c=r?.batchSize||this.autoParallelConfig.batchSize;l=await xn(a,async(u,d)=>n(u,d,i),c)}else l=a.map((c,u)=>n(c,u,i));else l=n(a,void 0,i);return{...i,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:r?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}nodeExtended(e,t,n){let o=typeof t=="string"?ge.create(t):t;if(n.prependInputs)for(let i of n.prependInputs)o=o.prependInputField(i.name,i.type);if(n.appendInputs)for(let i of n.appendInputs)o=o.appendInputField(i.name,i.type);if(n.prependOutputs)for(let i of n.prependOutputs)o=o.prependOutputField(i.name,i.type);if(n.appendOutputs)for(let i of n.appendOutputs)o=o.appendOutputField(i.name,i.type);return this.node(e,o)}nx(e,t,n){return this.nodeExtended(e,t,n)}mapOutput(e){let t=async n=>{let r=e(n);return{...n,...r}};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}mo(e){return this.mapOutput(e)}};function Do(s){return ur.create(s)}var No=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let o=t.map(c=>`${c.hostPath}:${c.containerPath}`);n||await this.pullImage(e);let i={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:o},Labels:{}};r&&(i.Labels["com.example.tag"]=r);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new Error(`Failed to create container: ${a.statusText}`);let l=await a.json();return this.containerId=l.Id,l}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let i=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===r);if(i&&i.length>0){let l=Math.floor(Math.random()*i.length),c=i[l];if(c)return await this.connectToContainer(c.Id),{Id:c.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:r})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let r=[],o=await this.listContainers(!0),i=e?o.filter(a=>a.Labels["com.example.tag"]===e):o;for(let a of i){if(a.State.Status==="running"){let l=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!l.ok){console.warn(`Failed to stop container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"removed"})}}return r}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let r=await n.json(),o=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!o.ok)throw new Error(`Failed to start exec instance: ${o.statusText}`);return await o.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var $o=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let r=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!r)throw new Error("Failed to embed text");return this.func.length===2?this.func(r,t):this.func(r)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var Go=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(o=>o.name===t.name),r=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:r,func:async o=>{let{result:i}=await this.sendRequest("tools/call",{name:t.name,arguments:o});return i}}})}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((i,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),r=await Promise.race([t,n]),{result:o}=r;if(typeof o!="object"||o===null||Object.keys(o).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(o)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=be(),r={jsonrpc:"2.0",id:n,method:e,params:t},o=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(r).then(c=>{if(this.activeRequests.delete(n),c!==null&&typeof c=="object"&&"error"in c){let u=c;l(new Error(`RPC Error ${u.error.code}: ${u.error.message}`))}else c!==null&&typeof c=="object"&&"result"in c?a({result:c.result}):l(new Error("Invalid response no result or error"))}).catch(c=>{this.activeRequests.delete(n),l(c)})}),{result:i}=await o;return{id:n,result:i}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:r}=this.options;if(r){let o={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(o)}await this.transport.sendNotification(n)}};function Xl(s){if(typeof Buffer<"u")return Buffer.from(s).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");let e="";for(let n=0;n<s.length;n++)e+=String.fromCharCode(s[n]);return(typeof btoa=="function"?btoa(e):"").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function ec(s){let t=new TextEncoder().encode(s),n=await gi().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function di(){return Xl(await ec(be()+Math.random().toString(36)))}async function tc(s){return Xl(await ec(s))}async function Lo(s,e){let t=await fetch(s,{headers:e});if(!t.ok)throw new Error(`HTTP ${t.status} fetching ${s}: ${t.statusText}`);return await t.json()}function nc(s){let e=new URLSearchParams;for(let[t,n]of Object.entries(s))n!==void 0&&e.set(t,n);return e.toString()}function pr(s){return s.endsWith("/")?s.slice(0,-1):s}function up(s){if(!s)return null;let e=s.match(/resource_metadata\s*=\s*"([^"]+)"/i)||s.match(/resource_metadata\s*=\s*([^,\s]+)/i);return e?e[1]:null}async function rc(s,e){let t=up(e);if(t){let a=await Lo(t),l=pr(new URL(s).toString().split("?")[0]),c=pr(a.resource??"");if(!c||c!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${c}`);let u=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(u.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:u}}let n=new URL(s),r=n.pathname.replace(/\/+$/,""),o=[];r&&r!=="/"&&o.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),o.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let i;for(let a of o)try{let l=await Lo(a.url),c=pr(l.resource??""),u=pr(a.expected);if(!c||c!==u)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${u} but got ${c}`);let d=Array.isArray(l.authorization_servers)?l.authorization_servers:[];if(d.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:u,issuers:d}}catch(l){i=l}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(i)}`)}async function oc(s){let e=new URL(s),t=e.pathname.replace(/^\/+/,""),n=[];t?(n.push(`${e.origin}/.well-known/oauth-authorization-server/${t}`),n.push(`${e.origin}/.well-known/openid-configuration/${t}`),n.push(`${e.origin}/${t.replace(/\/+$/,"")}/.well-known/openid-configuration`)):(n.push(`${e.origin}/.well-known/oauth-authorization-server`),n.push(`${e.origin}/.well-known/openid-configuration`));let r;for(let o of n)try{let i=await Lo(o);if(!i.authorization_endpoint||!i.token_endpoint)throw new Error("AS metadata missing endpoints");let a=i.code_challenge_methods_supported;if(!a||!a.includes("S256"))throw new Error("Authorization server does not advertise PKCE S256 support");return i}catch(i){r=i}throw new Error(`Failed to discover AS metadata for ${s}: ${String(r)}`)}var Cn=class{constructor(e){this.oauth=e}tokenCache=new Map;asMetaCache=new Map;key(e,t){return`${e}::${t}`}async getStoredToken(e,t){let n=this.key(e,t);if(this.tokenCache.has(n))return this.tokenCache.get(n);let r=await this.oauth?.tokenStore?.getToken?.(n);return r&&this.tokenCache.set(n,r),r??null}async setStoredToken(e,t,n){let r=this.key(e,t);this.tokenCache.set(r,n),await this.oauth?.tokenStore?.setToken?.(r,n)}async clearStoredToken(e,t){let n=this.key(e,t);this.tokenCache.delete(n),await this.oauth?.tokenStore?.clearToken?.(n)}isExpired(e){return e?Date.now()>e-6e4:!1}async getASMeta(e){if(this.asMetaCache.has(e))return this.asMetaCache.get(e);let t=await oc(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await rc(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],o=await this.getASMeta(r),i=e.currentToken??await this.getStoredToken(t,r);if(i?.accessToken&&!this.isExpired(i.expiresAt))return{token:i,issuer:r,asMeta:o,resource:t};if(i?.refreshToken)try{let x=await this.refreshToken(i.refreshToken,t,r,o);return await this.setStoredToken(t,r,x),{token:x,issuer:r,asMeta:o,resource:t}}catch{await this.clearStoredToken(t,r)}let a=this.oauth.redirectUri??"http://localhost:8787/callback",l=this.oauth.clientId?{client_id:this.oauth.clientId,client_secret:this.oauth.clientSecret}:await this.dynamicClientRegistration(o,a),c=await di(),u=await tc(c),d=await di(),p=this.oauth.scopes?.join(" "),m=`${o.authorization_endpoint}?${nc({response_type:"code",client_id:l.client_id,redirect_uri:a,scope:p,state:d,code_challenge:u,code_challenge_method:"S256",resource:t})}`;if(!this.oauth.onAuthCode)throw new Error(`Authorization required. Provide oauth.onAuthCode to complete the flow. Navigate to: ${m}`);let{code:g,redirectUri:h}=await this.oauth.onAuthCode(m),f=h??a,A=await this.exchangeCodeForToken({asMeta:o,code:g,codeVerifier:c,client:l,redirectUri:f,resource:t});return await this.setStoredToken(t,r,A),{token:A,issuer:r,asMeta:o,resource:t}}async dynamicClientRegistration(e,t){if(!e.registration_endpoint)throw new Error("Authorization server does not support dynamic client registration and no clientId was provided.");let r={application_type:t.startsWith("http://localhost")?"native":"web",client_name:"Ax MCP Client",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"},o=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Dynamic client registration failed: ${o.status} ${o.statusText}`);let i=await o.json();if(!i.client_id)throw new Error("Dynamic client registration did not return client_id");return i}async exchangeCodeForToken(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("code",e.code),t.set("redirect_uri",e.redirectUri),t.set("client_id",e.client.client_id),t.set("code_verifier",e.codeVerifier),t.set("resource",e.resource),e.client.client_secret&&t.set("client_secret",e.client.client_secret);let n=await fetch(e.asMeta.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!n.ok)throw new Error(`Token exchange failed: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.access_token)throw new Error("No access_token in token response");let o=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:o}}async refreshToken(e,t,n,r){let o=new URLSearchParams;o.set("grant_type","refresh_token"),o.set("refresh_token",e),o.set("resource",t),this.oauth?.clientId&&o.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&o.set("client_secret",this.oauth.clientSecret);let i=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()});if(!i.ok)throw new Error(`Token refresh failed: ${i.status} ${i.statusText}`);let a=await i.json();if(!a.access_token)throw new Error("No access_token in refresh response");let l=a.expires_in?Date.now()+a.expires_in*1e3:void 0;return{accessToken:a.access_token,refreshToken:a.refresh_token??e,expiresAt:l}}};var Uo=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;oauthHelper;currentToken;currentIssuer;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Cn(t?.oauth)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),r=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(r.toString()),this.eventSource.onopen=()=>e(),this.eventSource.onmessage=o=>{try{let i=JSON.parse(o.data);this.messageHandler&&this.messageHandler(i)}catch(i){console.error("Failed to parse SSE message:",i)}},this.eventSource.onerror=()=>t(new Error("Failed to establish SSE connection"))})}async openListeningStreamWithFetch(e){let t=await fetch(this.mcpEndpoint,{method:"GET",headers:e});if(t.status===401){let a=t.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,this.openListeningStreamWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),r=new TextDecoder,o="",i=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}o+=r.decode(l,{stream:!0});let c=o.split(`
|
|
455
|
+
`);o=c.pop()||"";for(let u of c)if(u.startsWith("data: ")){let d=u.slice(6);if(d==="[DONE]")return;try{let p=JSON.parse(d);this.messageHandler&&this.messageHandler(p)}catch(p){console.error("Failed to parse SSE data:",p)}}await i()}catch(a){throw n.releaseLock(),a}};await i()}async send(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let a=r.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);let o=r.headers.get("Mcp-Session-Id");o&&(this.sessionId=o);let i=r.headers.get("Content-Type");if(i?.includes("text/event-stream"))return this.handleSSEResponse(r,e.id);if(i?.includes("application/json"))return r.json();throw new Error(`Unexpected content type: ${i}`)}async handleSSEResponse(e,t){return new Promise((n,r)=>{let o=e.body?.getReader();if(!o){r(new Error("No response body reader available"));return}let i=new TextDecoder,a="",l=async()=>{try{let{done:c,value:u}=await o.read();if(c){o.releaseLock();return}a+=i.decode(u,{stream:!0});let d=a.split(`
|
|
456
|
+
`);a=d.pop()||"";for(let p of d)if(p.startsWith("data: ")){let m=p.slice(6);if(m==="[DONE]")return;try{let g=JSON.parse(m);if("id"in g&&g.id===t){n(g);return}this.messageHandler&&this.messageHandler(g)}catch(g){console.error("Failed to parse SSE data:",g)}}await l()}catch(c){o.releaseLock(),r(c)}};l().catch(r)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:o,currentToken:null});if(!i)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${i.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}async terminateSession(){if(this.sessionId)try{let e=this.buildHeaders({});(await fetch(this.mcpEndpoint,{method:"DELETE",headers:e})).status===405&&console.info("Server does not support explicit session termination")}catch(e){console.error("Failed to terminate session:",e)}finally{this.sessionId=void 0}}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}};var Bo=class{endpoint=null;sseUrl;eventSource;customHeaders={};oauthHelper;currentToken;currentIssuer;sseAbort;pendingRequests=new Map;messageHandler;endpointReady;constructor(e,t){this.sseUrl=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Cn(t?.oauth)}buildHeaders(e){return{...this.customHeaders,...e}}async openSSEWithFetch(e){let t=new AbortController;this.sseAbort=t;let n=await fetch(this.sseUrl,{method:"GET",headers:e,signal:t.signal});if(n.status===401){let o=n.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!i)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${i.token.accessToken}`,this.openSSEWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!n.ok)throw new Error("Failed to establish SSE connection");let r=this.createEndpointReady();this.consumeSSEStream(n),await r}createEndpointReady(){if(!this.endpointReady){let e,t=new Promise(n=>{e=n});this.endpointReady={resolve:e,promise:t}}return this.endpointReady.promise}async consumeSSEStream(e){if(!e.body)throw new Error("No response body available for SSE stream");let t=e.body.getReader(),n=new TextDecoder,r="",o=null;for(;;){let{done:i,value:a}=await t.read();if(i)break;r+=n.decode(a,{stream:!0});let l=r.split(`
|
|
457
|
+
`);r=l.pop()||"";for(let c of l)if(c.startsWith("event: "))o=c.slice(7).trim();else if(c.startsWith("data: ")){let u=c.slice(6);if(o==="endpoint"){let d=u.trim(),p;try{let m=JSON.parse(d);typeof m=="string"?p=m:m&&typeof m=="object"&&"uri"in m&&(p=m.uri)}catch{p=d}if(!p)throw new Error("Endpoint URI missing in SSE event data");/^https?:\/\//i.test(p)||(p=new URL(this.sseUrl).origin+(p.startsWith("/")?p:`/${p}`)),this.endpoint=p,this.endpointReady&&(this.endpointReady.resolve(),this.endpointReady=void 0)}else{let d=u.trim();try{let p=JSON.parse(d);if(p&&typeof p=="object"&&"id"in p){let m=p.id,g=this.pendingRequests.get(m);g?(g.resolve(p),this.pendingRequests.delete(m)):this.messageHandler&&this.messageHandler(p)}else this.messageHandler&&this.messageHandler(p)}catch{}}}else c.trim()===""&&(o=null)}}async connect(){let e=this.buildHeaders({Accept:"text/event-stream"});await this.openSSEWithFetch(e)}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=new Promise((a,l)=>{this.pendingRequests.set(e.id,{resolve:a,reject:l})}),o=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(o.status===401){let a=o.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,o=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!o.ok)throw this.pendingRequests.delete(e.id),new Error(`HTTP error ${o.status}: ${o.statusText}`);if(o.headers.get("Content-Type")?.includes("application/json")){let a=await o.json();return this.pendingRequests.delete(e.id),a}return r}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!i)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${i.token.accessToken}`,r=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!r.ok)throw new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.sseAbort&&(this.sseAbort.abort(),this.sseAbort=void 0)}};function pp(s,e,t,n,r){let o={...s};if(o.parameters){let i=o.parameters.properties?Object.keys(o.parameters.properties):[],l=t.filter(c=>i.includes(c)).filter(c=>c!=="model").filter(c=>!r.excludeFieldsFromPassthrough.includes(c));if(l.length>0){o.parameters=mp(o.parameters,l);let c=o.func;o.func=async(u,d)=>{let p={};if(Array.isArray(e)){let g=e.filter(h=>h.role==="user").pop();g&&(p=ac(g.values,l))}else p=ac(e,l);let m={...u,...p};return await c(m,d)}}return o}return n&&!r.disableSmartModelRouting&&r.canConfigureSmartModelRouting&&(o.parameters=lc(o.parameters,n)),o}var sc=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),ic=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),dr=class s{ai;program;functions;agents;disableSmartModelRouting;excludeFieldsFromPassthrough;debug;options;name;func;constructor({ai:e,name:t,description:n,definition:r,signature:o,agents:i,functions:a},l){let{disableSmartModelRouting:c,excludeFieldsFromPassthrough:u,debug:d}=l??{};if(this.ai=e,this.agents=i,this.functions=a,this.disableSmartModelRouting=c,this.excludeFieldsFromPassthrough=u??[],this.debug=d,this.options=l,!t||t.length<5)throw new Error("Agent name must be at least 10 characters (more descriptive)");if(!n||n.length<20)throw sc;if(r&&r.length<100)throw ic;this.program=new Pe(o,{...l,description:r??n});for(let m of i??[])this.program.register(m);this.name=t,this.func={name:dp(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let p=e?.getModelList();p&&!this.disableSmartModelRouting&&(this.func.parameters=lc(this.func.parameters,p))}static create(e,t){let n=ge.create(e),{ai:r,name:o,description:i,definition:a,agents:l,functions:c,...u}=t;return new s({ai:r,name:o,description:i,definition:a,signature:n,agents:l,functions:c},u)}setExamples(e,t){this.program.setExamples(e,t)}setId(e){this.program.setId(e)}setParentId(e){this.program.setParentId(e)}getTraces(){return this.program.getTraces()}setDemos(e){this.program.setDemos(e)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){let e=this.forward.bind(this),t=async(n,r)=>{let{model:o,...i}=n,a=this.ai??r?.ai;if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,i,{...r,model:o}),u=this.program.getSignature().getOutputFields();return Object.keys(l).map(p=>{let m=u.find(g=>g.name===p);return m?`${m.title}: ${l[p]}`:`${p}: ${l[p]}`}).join(`
|
|
458
|
+
`)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let r=this.ai??e,o=r?.getModelList(),a=this.program.getSignature().getInputFields().map(d=>d.name),l=this.getDebug(r,n),c=this.agents?.map(d=>{let p=d.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:p.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:p.canConfigureSmartModelRouting};return pp(d.getFunction(),t,a,o,m)}),u=[...n?.functions??this.functions??[],...c??[]];return{ai:r,functions:u,debug:l}}async forward(e,t,n){let{ai:r,functions:o,debug:i}=this.init(e,t,n),a={...this.options,...n,debug:i,functions:o};return await this.program.forward(r,t,a)}async*streamingForward(e,t,n){let{ai:r,functions:o,debug:i}=this.init(e,t,n),a={...this.options,...n,debug:i,functions:o};return yield*this.program.streamingForward(r,t,a)}setDescription(e){if(!e||e.length<20)throw sc;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw ic;this.program.setDescription(e),this.func.description=e}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}applyOptimization(e){this.program.applyOptimization?.(e)}getDebug(e,t){return t?.debug??this.debug??e?.getOptions()?.debug??!1}};function dp(s){return s.split(/[^a-zA-Z0-9]/).map((n,r)=>{let o=n.toLowerCase();return r>0&&o&&o[0]?o[0].toUpperCase()+o.slice(1):o}).join("")}function lc(s,e){let t=s?structuredClone(s):{type:"object",properties:{},required:[]};if(t.properties?.model)return t;let n={type:"string",enum:e.map(i=>i.key),description:`The AI model to use for this function call. Available options: ${e.map(i=>`\`${i.key}\` ${i.description}`).join(", ")}`},r={...t.properties??{},model:n},o=[...t.required??[],"model"];return{...t,properties:r,required:o}}function mp(s,e){let t=structuredClone(s);if(t.properties)for(let n of e)delete t.properties[n];if(Array.isArray(t.required)){let n=t.required.filter(r=>!e.includes(r));Object.defineProperty(t,"required",{value:n,writable:!0,configurable:!0})}return t}function ac(s,e){let t={};for(let n of e)n in s&&(t[n]=s[n]);return t}function cc(s,e){let t=typeof s=="string"?ge.create(s):s,{ai:n,name:r,description:o,definition:i,agents:a,functions:l,...c}=e;return new dr({ai:n,name:r,description:o,definition:i,signature:t,agents:a,functions:l},c)}var uc=(s,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,o=e?.qualityTarget??.85,i=e?.disableQualityHealing??!1;return Do({logger:e?.logger,debug:e?.debug}).node("queryGenerator","originalQuestion:string, previousContext?:string -> searchQuery:string, queryReasoning:string").node("contextualizer","retrievedDocument:string, accumulatedContext?:string -> enhancedContext:string").node("qualityAssessor","currentContext:string, originalQuestion:string -> completenessScore:number, missingAspects:string[]").node("questionDecomposer","complexQuestion:string -> subQuestions:string[], decompositionReason:string").node("evidenceSynthesizer","collectedEvidence:string[], originalQuestion:string -> synthesizedEvidence:string, evidenceGaps:string[]").node("gapAnalyzer","synthesizedEvidence:string, evidenceGaps:string[], originalQuestion:string -> needsMoreInfo:boolean, focusedQueries:string[]").node("answerGenerator","finalContext:string, originalQuestion:string -> comprehensiveAnswer:string, confidenceLevel:number").node("queryRefiner","originalQuestion:string, currentContext:string, missingAspects:string[] -> refinedQuery:string").node("qualityValidator","generatedAnswer:string, userQuery:string -> qualityScore:number, issues:string[]").node("answerHealer","originalAnswer:string, healingDocument:string, issues?:string[] -> healedAnswer:string").map(a=>({...a,maxHops:t,qualityThreshold:n,maxIterations:r,qualityTarget:o,disableQualityHealing:i,currentHop:0,accumulatedContext:"",retrievedContexts:[],completenessScore:0,searchQuery:a.originalQuestion,shouldContinue:!0,iteration:0,allEvidence:[],evidenceSources:[],needsMoreInfo:!0,healingAttempts:0,currentQuality:0,shouldContinueHealing:!0,currentAnswer:"",currentIssues:[]})).while(a=>a.currentHop<a.maxHops&&a.completenessScore<a.qualityThreshold&&a.shouldContinue).map(a=>({...a,currentHop:a.currentHop+1})).execute("queryGenerator",a=>({originalQuestion:a.originalQuestion,previousContext:a.accumulatedContext||void 0})).map(async a=>{let l=a.queryGeneratorResult?.searchQuery||a.searchQuery||a.originalQuestion,c=await s(l);return{...a,retrievalResult:{retrievedDocument:c,retrievalConfidence:.9}}}).execute("contextualizer",a=>({retrievedDocument:a.retrievalResult.retrievedDocument,accumulatedContext:a.accumulatedContext||void 0})).execute("qualityAssessor",a=>({currentContext:a.contextualizerResult.enhancedContext,originalQuestion:a.originalQuestion})).map(a=>({...a,accumulatedContext:a.contextualizerResult.enhancedContext,retrievedContexts:[...a.retrievedContexts,a.retrievalResult.retrievedDocument],completenessScore:a.qualityAssessorResult.completenessScore,searchQuery:a.queryGeneratorResult.searchQuery,shouldContinue:a.qualityAssessorResult.completenessScore<a.qualityThreshold})).branch(a=>a.shouldContinue&&a.currentHop<a.maxHops).when(!0).execute("queryRefiner",a=>({originalQuestion:a.originalQuestion,currentContext:a.accumulatedContext,missingAspects:a.qualityAssessorResult.missingAspects})).map(a=>({...a,searchQuery:a.queryRefinerResult?.refinedQuery||a.searchQuery})).when(!1).map(a=>a).merge().endWhile().map(a=>({...a,allEvidence:a.retrievedContexts.length>0?a.retrievedContexts:[]})).while(a=>a.iteration<a.maxIterations&&a.needsMoreInfo).map(a=>({...a,iteration:a.iteration+1})).branch(a=>a.iteration===1).when(!0).execute("questionDecomposer",a=>({complexQuestion:a.originalQuestion})).map(a=>({...a,currentQueries:a.questionDecomposerResult.subQuestions})).when(!1).map(a=>({...a,currentQueries:a.gapAnalyzerResult?.focusedQueries||[]})).merge().map(async a=>{let l=a.currentQueries||[],c=l.length>0?await Promise.all(l.filter(Boolean).map(u=>s(u))):[];return{...a,retrievalResults:c}}).execute("evidenceSynthesizer",a=>{let l=Array.isArray(a.allEvidence)?a.allEvidence:[],c=Array.isArray(a.retrievalResults)?a.retrievalResults:[],u=[...l,...c].filter(Boolean);return{collectedEvidence:u.length>0?u:["No evidence collected yet"],originalQuestion:a.originalQuestion}}).execute("gapAnalyzer",a=>({synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence,evidenceGaps:a.evidenceSynthesizerResult.evidenceGaps,originalQuestion:a.originalQuestion})).map(a=>({...a,allEvidence:[...Array.isArray(a.allEvidence)?a.allEvidence:[],...Array.isArray(a.retrievalResults)?a.retrievalResults:[]],evidenceSources:[...Array.isArray(a.evidenceSources)?a.evidenceSources:[],`Iteration ${a.iteration} sources`],needsMoreInfo:a.gapAnalyzerResult.needsMoreInfo,synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence})).endWhile().execute("answerGenerator",a=>({finalContext:(()=>{let l=(a.accumulatedContext||"").toString().trim();if(l.length>0)return l;let c=(a.synthesizedEvidence||"").toString().trim();if(c.length>0)return c;let d=(Array.isArray(a.allEvidence)?a.allEvidence.filter(Boolean).join(`
|
|
459
|
+
`):"").toString().trim();return d.length>0?d:"No context available."})(),originalQuestion:a.originalQuestion})).branch(a=>!a.disableQualityHealing).when(!0).execute("qualityValidator",a=>({generatedAnswer:a.answerGeneratorResult.comprehensiveAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).while(a=>a.healingAttempts<3&&a.shouldContinueHealing).map(a=>({...a,healingAttempts:a.healingAttempts+1})).map(async a=>{let l=a.currentIssues||[],c=l.length>0?`${a.originalQuestion} addressing issues: ${l.join(", ")}`:`${a.originalQuestion} quality improvement`,u=await s(c);return{...a,healingResult:{healingDocument:u}}}).execute("answerHealer",a=>({originalAnswer:a.currentAnswer,healingDocument:a.healingResult.healingDocument,issues:a.currentIssues})).execute("qualityValidator",a=>({generatedAnswer:a.answerHealerResult.healedAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerHealerResult.healedAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).endWhile().when(!1).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:1,currentIssues:[],shouldContinueHealing:!1})).merge().returns(a=>({finalAnswer:a.currentAnswer,totalHops:a.currentHop,retrievedContexts:a.retrievedContexts,iterationCount:a.iteration,healingAttempts:a.healingAttempts,qualityAchieved:a.currentQuality}))};return Tc(gp);})();
|
|
458
460
|
//# sourceMappingURL=index.global.js.map
|